mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 05:37:14 +00:00
feat(mcp): add MCP server support with proxy tool and OAuth flow (#289)
* feat(mcp): add MCP server support with proxy tool and OAuth flow
Add URL-based MCP (Model Context Protocol) server support to the backend:
- DB: McpServer / AgentMcpServer / McpServerCredential models with
typed JSON columns (auth config, cached tools, stored OAuth tokens,
pending auth state) and a migration.
- Core (@shumai/core/src/mcp): DB-backed credential store, OAuth
client provider (authorization_code + client_credentials) with a
Hono-hosted redirect callback, connection lifecycle manager
(Streamable HTTP with SSE fallback, lazy connect, 401 -> needs_auth),
JSON Schema -> AgentTool parameter conversion, in-memory tool registry
with ranked search, the single 'mcp' proxy AgentTool (search /
describe / list / call / connect / status / auth-start), per-server
opt-in direct tools ({server}_{tool}), and McpService (CRUD,
discovery, OAuth, per-agent assignment via AgentMcpServer, and
permission gating on tool execution mirroring skills).
- Agent: chat agents receive the 'mcp' proxy tool (plus direct tools
for opted-in servers) built from their assigned, enabled servers.
- API: /teams/:teamId/mcp/servers CRUD, tools refresh/list, auth
start/complete/status/remove, test, permission, and the public
OAuth callback route; Admin authz via new ResourceType.McpServer;
audit logging.
- DTOs: zod schemas + types for servers, tools, auth, and per-agent
mcpServerIds.
- Tests: DB store, schema conversion, registry/search, service
integration against a real in-process MCP server (v2
@modelcontextprotocol/server), permission gating, rename
invalidation, direct tools, per-agent assignment, API route tests,
and workflow E2E (local + temporal) for proxy and direct modes.
* fix(mcp): persist OAuth discovery snapshot and stamp SEP-2352 issuer
The callback leg of the OAuth flow failed with
AuthorizationServerMismatchError ('discoveryState was not available on
the callback leg') because McpDbStore.savePendingAuth overwrote the
entire pendingAuth JSON column, clobbering the discoverySnapshot that
the provider's saveDiscoveryState() had stored inside it.
- McpDbStore.savePendingAuth now preserves an in-flight discovery
snapshot so the callback leg can satisfy the SEP-2352 authorization-
server issuer check.
- McpOauthProvider now round-trips the issuer stamp derived from the
discovery snapshot: saveClientInformation/saveTokens persist it,
clientInformation()/tokens() return it, and tokens() backfills a
missing stamp for pre-existing credentials (removes the
'stored OAuth credential has no issuer stamp' warning).
- Regression tests: savePendingAuth keeps the snapshot; the provider
stamps/round-trips the issuer on both legs.
* fix(mcp): backfill SEP-2352 issuer stamp on stale OAuth client info
clientInformation() returned stored client info without an issuer field
when it had been dynamically registered before the stamping fix, so the
SDK logged 'stored OAuth credential has no issuer stamp' on every read.
Now the stored branch backfills the issuer from the discovery snapshot
(persisting it) exactly like the tokens() backfill.
* feat(webui): add MCP server configuration and agent assignment UI (#290)
* feat(webui): add MCP server configuration and agent assignment UI
* fix(webui): auto-detect auth for unconfigured MCP servers and show connect button
* fix(mcp): auto-generate state in mcp-oauth-provider when missing in DB
* fix(mcp): persist OAuth discovery snapshot and stamp SEP-2352 issuer
The callback leg of the OAuth flow failed with
AuthorizationServerMismatchError ('discoveryState was not available on
the callback leg') because McpDbStore.savePendingAuth overwrote the
entire pendingAuth JSON column, clobbering the discoverySnapshot that
the provider's saveDiscoveryState() had stored inside it.
- McpDbStore.savePendingAuth now preserves an in-flight discovery
snapshot so the callback leg can satisfy the SEP-2352 authorization-
server issuer check.
- McpOauthProvider now round-trips the issuer stamp derived from the
discovery snapshot: saveClientInformation/saveTokens persist it,
clientInformation()/tokens() return it, and tokens() backfills a
missing stamp for pre-existing credentials (removes the
'stored OAuth credential has no issuer stamp' warning).
- Regression tests: savePendingAuth keeps the snapshot; the provider
stamps/round-trips the issuer on both legs.
* fix(mcp): backfill SEP-2352 issuer stamp on stale OAuth client info
clientInformation() returned stored client info without an issuer field
when it had been dynamically registered before the stamping fix, so the
SDK logged 'stored OAuth credential has no issuer stamp' on every read.
Now the stored branch backfills the issuer from the discovery snapshot
(persisting it) exactly like the tokens() backfill.
* fix(mcp): attach McpOauthProvider for auto-detected OAuth servers and discover tools on auth completion
* fix(webui): fix flex min-h-0 and max-h scrolling on MCP tools dialog
* fix(webui): set explicit flex height on McpToolsDialog for active scrolling
* feat(webui): make MCP server cards clickable to edit and widen server config dialog
* feat(mcp): agent-level server enablement and auto-detected server metadata (#291)
* feat(mcp): agent-level server enablement and auto-detected server metadata
- Remove the server-level `enabled` column from mcp_servers; enable/disable
now happens per-agent via the AgentMcpServer join table (mirrors skills).
- Drop the unique (teamId, name) constraint so duplicate server names are allowed.
- Add a `description` column, auto-filled from client.getServerVersion() on
connect; the server name is auto-filled from the reported title (fallback name)
with a URL-derived placeholder until first connect.
- Remove manual name input: the create dialog is URL-only, and the edit dialog
shows the auto-detected name/description read-only.
- Replace the include/exclude raw-text inputs with the tool list in the edit
dialog, managing only excludeTools; remove includeTools support and the
separate McpToolsDialog component.
- Sanitize server-reported names into safe direct-tool prefixes (spaces/punctuation
become underscores) and use the same sanitization in the proxy resolver.
* fix(mcp): give the edit-dialog tool list a definite height
The Shadcn ScrollArea viewport is h-full, which requires a definite height
on the root. Using max-h-64 left the viewport at auto height, so the root
clipped the list at 256px without engaging its own scrollbar — tools past
the cutoff were unreachable. Use a fixed h-64 container (same pattern as
move-copy-dialog) so the inner scroll area scrolls independently of the
dialog's outer scroll.
* refactor(mcp): fixed header/footer with scrollable content in server config dialog
Mirror the skill config dialog layout: the edit dialog now keeps the header
and footer fixed and scrolls only the content area (ScrollArea flex-1
min-h-0 inside an h-[85vh] flex column). The tools list no longer has its
own nested ScrollArea — it flows inside the content-level scroll, so all
tools are reachable without a nested-scroll conflict. The create dialog
stays compact (URL-only) like the skill add dialog.
Verified headlessly that max-height-based ScrollArea roots do not engage
scrolling (viewport height resolves to auto), which is why the previous
nested list clipped; the flex-based definite-height pattern scrolls.
* feat(mcp): make the endpoint URL immutable after creation
Editing a server's URL effectively points it at a different server, and the
create flow is URL-only anyway — so the edit dialog no longer allows changing
it (delete + re-add covers endpoint changes). The URL is displayed read-only
next to the auto-detected name/description, and `url` was removed from the
update DTO and service; auth/transport changes still invalidate credentials
and cached tools.
* refactor(mcp): match MCP server cards to the skill card layout
The settings list cards now share the skill card structure: row 1 is the
server name (with direct-mode/transport badges) plus the three-dot menu,
row 2 is the description (falling back to 'No description provided') with
the endpoint URL and last error as small mono lines, and row 3 holds the
connection-status badge and updated date on the left with the permission
selector and the connect button at the right end.
* fix(mcp): stop card menu clicks from opening the edit dialog
The three-dot menu is portaled, so its item clicks bubble through React's
synthetic events to the card's onClick, which opened the edit dialog before
the delete confirmation appeared. Add e.stopPropagation() to every menu
item (matching the skill card pattern).
* fix(mcp): stop Refresh Tools from submitting/closing the config dialog
The Refresh Tools button lived inside the <form> and, like all buttons
without an explicit type, defaulted to type="submit" — clicking it ran the
form submit (save + close) instead of just refreshing. Set type="button".
Also per UX: while refreshing, the button is disabled with a spinning icon,
the per-tool enable/disable switches are disabled, and the success toast is
removed — the button reverting to its idle state is the success signal
(keep the error toast for failures).
* test(mcp): provide explicit redirectUri in McpOauthProvider test helper
* fix(mcp): scope tool registry to agent-assigned servers
The MCP tool registry was a process-global singleton keyed by server id,
so a chat agent could search, describe, and even call tools belonging to
MCP servers that were not assigned to it (e.g. disabled or unassigned
servers), as long as their metadata had been discovered at some point in
the process. This mirrors the disabled-skill bug: the read path never
checked per-agent enablement.
Replace the singleton with a fresh McpToolRegistry built per
buildAgentTools call and warmed from the persisted McpServer.tools DB
cache. Because the registry only ever contains the agent's assigned
servers, unassigned/disabled servers can neither be suggested, searched,
described, nor executed. Live discovery (lazy connect / connect action)
writes into the per-agent registry via ensureConnected(serverId,
registry?).
Adds test-first coverage: suggestions, search, describe and tool-call
leaks across an unassigned same-team server, staleness after
unassignment, and direct-tools scoping.
* feat(mcp): capture and surface server instructions + server-level refresh (#293)
* feat(mcp): capture and surface server instructions
- Add McpServer.instructions column, populated from getInstructions() at
connect time (legacy initialize + modern discover results)
- Surface instructions at three levels like pi-mcp-adapter: truncated
snippet in the mcp proxy tool description, preview in server listings,
and full text via mcp({ instructions: "name" })
- Fix misleading mcp({ server, connect }) usage line to mcp({ connect })
- Share one renderServerListing helper across list and connect modes
- Expose instructions in McpServerInfo DTO and WebUI config card
- Test server supports instructions; service + API tests updated
* refactor(mcp): server-level refresh endpoint, drop agent connect mode
- Replace POST /mcp/servers/:id/tools/refresh with POST /mcp/servers/:id/refresh
returning the refreshed McpServerInfo (server-level, not tools-level)
- Add McpService.refreshServer(): force-close the connection, re-discover and
persist tools, instructions, name/description and status; used by the refresh
endpoint, Test Connection, and post-OAuth completion (replacing discoverTools)
- Remove discoverTools entirely - refreshServer is the single discovery entry
point (testServer and completeAuth route through it)
- Remove refreshTools from UpdateMcpServerRequest/PATCH (dead param)
- Remove mcp({ connect: "name" }) from the agent proxy tool: lazy tool calls
still auto-connect, so agents are unaffected
- WebUI: remove the dialog 'Refresh Tools' button and create-mode background
auto-refresh; add a server-level Refresh button at the left end of the edit
dialog footer; i18n mcp_refresh_server (+ success message)
* feat(mcp): add in-flight request tracking and idle connection cleanup (#294)
* feat(mcp): add in-flight request tracking and idle connection cleanup
* feat(mcp): add background idle cleanup timer to McpService
* feat(mcp): update default background idle cleanup check interval to 30s
* feat(webui): improve MCP server card footer, instructions, and refresh dialog freeze (#295)
* feat(webui): improve MCP server list card, instructions dialog, and refresh freeze UI
* feat(webui): refine MCP card action menu items
* docs(webui): update direct tools mode description in i18n messages
* style(webui): refine Direct Tools Mode layout in MCP server config dialog
* feat(webui): remove tool search box from MCP server config dialog
* fix(mcp): make in-flight idle tracking test deterministic
The 'tracks in-flight requests and safely prunes idle connections' test
relied on a wall-clock sleep (10ms) to guess when the tool handler had
started executing on the server. On slow/loaded CI runners the HTTP round
trip through the real MCP client/server stack can exceed that window, so
resolveSlowTool() fired the no-op placeholder, the gated handler never
completed, and callPromise hung until the 5000ms test timeout.
The handler now signals via a deferred promise when it actually starts,
and the test awaits that signal (racing it against the call promise to
surface early failures) before asserting in-flight state and releasing
the gate. Also gives the test an explicit 10s timeout.
This commit is contained in:
+297
@@ -0,0 +1,297 @@
|
||||
# Plan: MCP Support for Shumai (Backend)
|
||||
|
||||
> Status: **Plan finalized** — all design questions resolved (see §11, incl. review-round-2 decision D10). Ready to implement.
|
||||
> This file is the single source of truth for the MCP backend plan. Update it whenever the plan changes.
|
||||
|
||||
## 1. Understanding of the current architecture
|
||||
|
||||
**Chat flow today** (`packages/core/src/chat/chat.ts` → `packages/agent/src/workflows/agent-chat.ts` → `packages/agent/src/activities/agent.ts`):
|
||||
1. User sends chat → `chatService.startOrContinueChat` creates a `WorkflowTask` (type `chat`).
|
||||
2. `agentChat` workflow → `agentChatActivity` → `executeAgentPrompt` → `createAgentSession(...)` (in `packages/agent/src/index.ts`).
|
||||
3. `createAgentSession` builds `AgentTool[]` (TypeBox `parameters` + `execute(toolCallId, params)`), registers them on `AgentHarness`, and calls `harness.prompt()`. The harness validates args via `validateToolArguments` (pi-ai) which **works with plain JSON Schema objects** (falls back to `coerceWithJsonSchema` when the TypeBox `Kind` symbol is absent), and passes `tool.parameters` straight to provider APIs (`parametersJsonSchema` for Gemini / `parameters` for OpenAI).
|
||||
|
||||
**Key reference — `pi-mcp-adapter`** (idea reference only, at `/Users/yiling/Projects/pi-mcp-adapter` — do NOT modify; port patterns from it). Relevant files: `server-manager.ts`, `mcp-auth.ts`, `mcp-auth-flow.ts`, `mcp-oauth-provider.ts`, `mcp-callback-server.ts`, `proxy-modes.ts`, `direct-tools.ts`, `search-ranking.ts`, `tool-registrar.ts`, `types.ts`, `mcp-code.ts`.
|
||||
- **Tool exposure has two modes**: (1) *default* — a single `mcp` proxy tool is registered with Pi (only one tool in the LLM context), which multiplexes **all servers** via a `server` parameter that disambiguates tool calls (`mcp({ tool, server, args, connect, search, describe, ... })`); (2) *opt-in* `directTools: true | string[]` — each MCP tool is registered directly as its own prefixed tool (e.g. `xcodebuild_list_sims`), with an advisory warning at ≥75 tools because each direct tool adds prompt context. Shumai's plan (D3) adopts **the same design** (proxy default + per-server opt-in `directTools`), with one simplification: shumai's `directTools` is **boolean-only** — tool selection is always via `includeTools`/`excludeTools` filters (Q6).
|
||||
- `server-manager.ts`: `McpServerManager` wraps `Client` from `@modelcontextprotocol/client`, connects via `StdioClientTransport` / `StreamableHTTPClientTransport` / `SSEClientTransport`, discovers tools/resources/prompts, executes `client.callTool`.
|
||||
- `mcp-oauth-provider.ts`: `McpOAuthProvider implements OAuthClientProvider` (the SDK interface) — `clientInformation`, `saveClientInformation`, `tokens`, `saveTokens`, `redirectToAuthorization`, `saveCodeVerifier`/`codeVerifier`, `saveDiscoveryState`/`discoveryState`, `saveState`/`state`, `invalidateCredentials`, `addClientAuthentication`, `prepareTokenRequest`.
|
||||
- `mcp-auth.ts`: storage layer (OS keyring / plaintext files) — **this is the part we replace with DB storage**.
|
||||
- `mcp-auth-flow.ts`: `startAuth`/`completeAuth`/`authenticate`/`getValidToken`/`getAuthStatus`/`removeAuth` using SDK `auth()` + local callback server.
|
||||
- `proxy-modes.ts` `executeCall`: tool metadata lookup → `client.callTool({ name, arguments })` → transform MCP content blocks (`text`/`image`/`resource`/etc.) into model content blocks.
|
||||
|
||||
---
|
||||
|
||||
## 2. Design decisions
|
||||
|
||||
| # | Decision | Rationale |
|
||||
|---|----------|-----------|
|
||||
| D1 | MCP runtime lives in **`@shumai/core/src/mcp/`** (`McpService`, `McpServerManager`, DB-backed OAuth provider). | Both the API (CRUD/OAuth) and the agent worker (`@shumai/agent` activities) need it. `@shumai/agent` already depends on `@shumai/core`. Add `@modelcontextprotocol/client` dep to `@shumai/core` only. |
|
||||
| D2 | **URL-based servers only** (Streamable HTTP with SSE fallback), no stdio. ✅ Confirmed (Q1). | "Add MCP server address in webui" = URL. Stdio spawns local processes — conflicts with "don't store/run anything on the local host machine" and complicates multi-worker/Temporal deployments. |
|
||||
| D3 | **Single `mcp` proxy tool by default** (pi-mcp-adapter style): one `AgentTool` multiplexes all assigned MCP servers via params `{ server, tool, args, search, describe, connect, action... }` (listing via `server` without `tool`; auth via `action: 'status' | 'auth-start'`), keeping the LLM context small. **Per-server opt-in `directTools: boolean`** registers that server's tools directly as prefixed `AgentTool`s (e.g. `xcodebuild_list_sims`); which tools become direct is always controlled by `includeTools`/`excludeTools` filters — **no `string[]` form** (Q6). | Mirrors pi-mcp-adapter's proven model (confirmed by user preference): 1 tool in context by default; direct tools only for servers an agent's team explicitly opts in. |
|
||||
| D4 | All OAuth/token state stored in **DB** (`McpServerCredential` 1:1 row), replacing pi-mcp-adapter's keyring/files. Tool metadata cached in DB too. | Explicit requirement. No host-machine state. |
|
||||
| D5 | OAuth redirect/callback served by **shumai's own Hono API** (`/api/mcp/oauth/callback`) instead of a local callback server. ✅ Confirmed (Q4): `redirectUri` defaults to `${BETTER_AUTH_URL}/api/mcp/oauth/callback`, overridable via `MCP_OAUTH_REDIRECT_BASE_URL`. | Shumai is a hosted web app; the browser must reach the callback. |
|
||||
| D6 | MCP servers are **team-scoped records**, but assignment to agents is **per-agent** via an `AgentMcpServer` join table (mirrors `AgentSkill`/skills). An agent gets tools only from its **assigned + enabled** servers. ✅ Confirmed (Q2). | Per-agent control, consistent with how skills are attached to agents today. |
|
||||
| D7 | Connection lifecycle: **lazy per-process connection** in the worker/web process, single-flight per server, auto-reconnect on failure, non-fatal to chat if a server is down (tool returns error text; other tools still work). | MCP connections are in-memory resources on a worker process; DB holds config + credentials so any process can reconnect. |
|
||||
| D8 | Secrets (tokens, bearer token, clientSecret) stored in DB **as-is** (same pattern as existing `Provider.config.apiKey`). Encryption-at-rest is a follow-up. ✅ Confirmed (Q3). | Consistent with existing codebase behavior. |
|
||||
| D9 | **Auth types (Q5)**: `none`, `bearer`, and OAuth `authorization_code` (dynamic registration + pre-registered `clientId`) **and** `client_credentials` — all supported in v1. | Covers public MCP servers, static-token servers, and full OAuth 2.1 servers. |
|
||||
| D10 | **Per-server usage permission** (review round 2): `McpServer.permission TeamMemberRole @default(reviewer)` mirrors `Skill.permission`; enforced at tool-execution time in `callMcpTool` with the same `ROLE_HIERARCHY` gate as `read-skill.ts` (no user context + permission > reviewer → denied). | User decision: "add permission similar to skill". Proxy `search`/`describe`/`status` stay available so the two-phase discovery model works; the gate protects actual tool execution (the analog of reading a skill's content). |
|
||||
|
||||
---
|
||||
|
||||
## 3. Database schema (`packages/db/prisma/schema.prisma`)
|
||||
|
||||
New models (all `id @default(ulid())`, snake_case maps, cascade on team delete):
|
||||
|
||||
```prisma
|
||||
model McpServer {
|
||||
id String @id @default(ulid())
|
||||
name String // unique per team; connection key + tool prefix
|
||||
url String // Streamable HTTP / SSE endpoint
|
||||
transport McpTransport @default(streamable_http) // streamable_http | sse (auto fallback when 'streamable_http' + server doesn't support it)
|
||||
/// [McpServerAuthConfig]
|
||||
authConfig Json? @default("{}") // { type: 'none'|'bearer'|'oauth', bearerToken?, headers?, oauth?: { clientId?, clientSecret?, scope?, grantType?, authorizationParams?, redirectUri?, clientName?, clientUri?, skipIssuerMetadataValidation? } }
|
||||
/// [McpServerConfig]
|
||||
config Json? @default("{}") // { includeTools?, excludeTools?, requestTimeoutMs?, protocolVersion?, directTools?: boolean } // directTools is boolean-only (Q6); toolPrefix removed (Q12 — naming is always {server}_{tool})
|
||||
enabled Boolean @default(true)
|
||||
permission TeamMemberRole @default(reviewer) // mirrors Skill.permission; gate for tool execution (D10)
|
||||
/// [McpToolInfo[]]
|
||||
tools Json? @default("[]") // cached discovered tool list (name/description/inputSchema)
|
||||
status String @default("not_connected") // not_connected|connected|failed|needs_auth
|
||||
lastError String?
|
||||
lastConnectedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
teamId String @map("team_id")
|
||||
team Team @relation("TeamToMcpServer", fields: [teamId], references: [id], onDelete: Cascade)
|
||||
credential McpServerCredential?
|
||||
agentMcpServers AgentMcpServer[]
|
||||
|
||||
@@unique([teamId, name])
|
||||
@@map("mcp_servers")
|
||||
}
|
||||
|
||||
// Join table: which agents get which MCP servers (mirrors AgentSkill).
|
||||
model AgentMcpServer {
|
||||
id String @id @default(ulid())
|
||||
agentId String @map("agent_id")
|
||||
agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
|
||||
mcpServerId String @map("mcp_server_id")
|
||||
mcpServer McpServer @relation(fields: [mcpServerId], references: [id], onDelete: Cascade)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@unique([agentId, mcpServerId])
|
||||
@@map("agent_mcp_servers")
|
||||
}
|
||||
|
||||
model McpServerCredential {
|
||||
id String @id @default(ulid())
|
||||
serverId String @unique @map("server_id")
|
||||
server McpServer @relation(fields: [serverId], references: [id], onDelete: Cascade)
|
||||
serverUrl String // bind creds to the URL they were issued for
|
||||
/// [McpStoredTokens]
|
||||
tokens Json?
|
||||
/// [McpStoredClientInfo]
|
||||
clientInfo Json?
|
||||
codeVerifier String?
|
||||
oauthState String?
|
||||
/// [McpPendingAuth]
|
||||
pendingAuth Json? // in-flight authorization_code flow (state, discovery snapshot, authorizationUrl, expiresAt)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@map("mcp_server_credentials")
|
||||
}
|
||||
```
|
||||
|
||||
- Add `mcpServers McpServer[] @relation("TeamToMcpServer")` on `Team` (inside the relation block), `mcpServers AgentMcpServer[]` on `Agent`, and `agentMcpServers AgentMcpServer[]` on `McpServer`. Mirror the exact `AgentSkill` block style (see `packages/db/prisma/schema.prisma` ~line 761).
|
||||
|
||||
- New JSON types in `packages/db/src/prisma-json-types.ts`: `McpServerAuthConfig`, `McpServerConfig`, `McpToolInfo`, `McpStoredTokens`, `McpStoredClientInfo`, `McpPendingAuth` (mirroring pi-mcp-adapter `mcp-auth.ts` shapes).
|
||||
- **Note**: `Agent.id` is **not** refactored — it keeps doubling as the agent's `User.id` today. `AgentMcpServer.agentId` simply references the existing `Agent.id`.
|
||||
- Migration via `bun --bun run prisma migrate dev` (never hand-write DDL).
|
||||
|
||||
---
|
||||
|
||||
## 4. DTOs (`packages/dtos/src/mcp.ts` + `agent.ts` + export in `index.ts`)
|
||||
|
||||
Zod schemas + types in `mcp.ts`:
|
||||
- `McpServerAuthType = 'none' | 'bearer' | 'oauth'`
|
||||
- `CreateMcpServerRequest` (`name`, `url`, `transport?`, `authConfig?`, `config?`, `enabled?`, `permission?`)
|
||||
- `UpdateMcpServerRequest` (partial, plus optional `refreshTools` flag)
|
||||
- `UpdateMcpServerPermissionRequest` (`permission: 'owner' | 'editor' | 'reviewer'`) for the dedicated `PATCH /mcp/servers/:id/permission` (mirrors `updateSkillPermissionRequestSchema`)
|
||||
- `McpServerInfo` (id, name, url, transport, authType, enabled, permission, status, lastError, toolCount, hasCredential, createdAt/updatedAt) — **never returns tokens/secrets**
|
||||
- `McpToolInfo` (name, description, inputSchema, title?)
|
||||
- `ListMcpServersResponse` (`{ servers: McpServerInfo[] }`)
|
||||
- `RefreshToolsRequest/Response`
|
||||
- OAuth: `McpAuthStatus` (`'authenticated' | 'expired' | 'not_authenticated' | 'in_progress'`), `McpAuthStartResponse` (`{ authorizationUrl, status }`), `McpAuthCompleteRequest` (`{ code, iss? }`), `McpAuthStatusResponse`
|
||||
|
||||
Changes in `agent.ts` (per-agent assignment, Q2): add `mcpServerIds?: string[]` to `CreateAgentParams`/`UpdateAgentParams` (mirrors `skills`); `AgentInfo`/list responses include `mcpServers`/`mcpServerIds`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Core MCP runtime (`packages/core/src/mcp/`)
|
||||
|
||||
### 5a. `mcp-db-store.ts` — DB-backed credential store
|
||||
Ports pi-mcp-adapter `mcp-auth.ts` API (`getAuthForUrl`, `saveAuthEntry`, `updateTokens`, `updateClientInfo`, `updateCodeVerifier`, `updateOAuthState`, `getOAuthState`, `clearOAuthState`, `clearAllCredentials`, `clearClientInfo`, `clearTokens`, `isTokenExpired`, `hasStoredTokens`) but reads/writes `McpServerCredential` via Prisma. Also stores `pendingAuth` (the in-flight authorization_code flow) with a TTL.
|
||||
|
||||
### 5b. `mcp-oauth-provider.ts` — `OAuthClientProvider` implementation
|
||||
Adapted from pi-mcp-adapter `mcp-oauth-provider.ts`:
|
||||
- Same interface methods; storage calls go to the DB store instead of keyring/files.
|
||||
- `redirectUrl` = configured `redirectUri` or `${MCP_OAUTH_REDIRECT_BASE_URL}/api/mcp/oauth/callback`.
|
||||
- Flow state (PKCE verifier, discovery state, authorization URL, `state`) persisted to `pendingAuth` in DB so the flow survives across HTTP requests (start → browser → callback).
|
||||
|
||||
### 5c. `mcp-server-manager.ts` — connection lifecycle
|
||||
Simplified port of pi-mcp-adapter `server-manager.ts`:
|
||||
- `connect(serverId, config, creds)` — creates `Client` + `StreamableHTTPClientTransport` (fallback to SSE on 404/405/406/415) or pinned `SSEClientTransport`; passes `authProvider` (the OAuth provider above) or static bearer header; `client.connect()`.
|
||||
- Handles `UnauthorizedError`/401 → status `needs_auth`.
|
||||
- `listTools` (paginated), `callTool(name, args)`, `close(name)`, `closeAll()`, single-flight connect dedup, per-server status tracking.
|
||||
- Uses `versionNegotiation` from `@modelcontextprotocol/client` (default auto/legacy per config).
|
||||
|
||||
### 5d. `mcp-tool-schema.ts` — JSON Schema → AgentTool `parameters`
|
||||
- Normalize MCP `inputSchema`: ensure `type: 'object'`; strip unsupported keywords (`$schema`, `additionalProperties` handling); pass through as `TSchema` (the harness accepts plain JSON Schema via pi-ai's coercion path, and providers get valid JSON Schema).
|
||||
- Validate compile-ability with `typebox/compile` `Compile`; on failure fall back to `Type.Record(Type.String(), Type.Unknown())` so the tool still works (args passed through to `callTool`).
|
||||
- Unit-tested against tricky schemas (`$defs`/`$ref`, `anyOf`, enums, `additionalProperties`, `patternProperties`).
|
||||
|
||||
### 5e. `mcp-tool-registry.ts` — in-memory tool metadata + search
|
||||
- Per-process registry of discovered tools keyed by server: `{ serverId, serverName, name (prefixed), originalName, description, inputSchema }` (mirrors pi-mcp-adapter `ToolMetadata`). Loaded lazily from the DB cache (`McpServer.tools`) and refreshed on `connect`/`tools/refresh`.
|
||||
- `listTools(serverId)` (or all), `findTool(name, serverId?)` (used by proxy call resolution + `describe`), `rankSuggestions(name, limit)` for "did you mean" errors.
|
||||
- `searchTools(query, serverId?, limit?, offset?)` — port of pi-mcp-adapter `search-ranking.ts` (`normalizeSearchText` camelCase/snake-case splitting, weighted fields name>originalName>server>description, token/prefix/stem scoring, coverage gate, pagination).
|
||||
|
||||
### 5f. `mcp-proxy-tool.ts` — the single `mcp` proxy `AgentTool`
|
||||
- Built per team/session by `buildProxyTool(teamId, userId?)`. The `parameters` schema mirrors pi-mcp-adapter's proxy tool: `{ tool?, args? (object|JSON string), server?, connect?, describe?, search?, includeSchemas?, limit?, offset?, action? (status|auth-start) }`.
|
||||
- **Dynamic description** (ported from `buildProxyDescription`): server list + tool counts (`Servers: xcodebuild (12 tools), github (28)`), truncated server `instructions`, and usage examples. Rebuilt when metadata changes (per session; diffed to preserve prompt cache where possible).
|
||||
- `execute` dispatches by mode precedence (`action > tool(call) > connect > describe > search > server(list) > status`):
|
||||
- `search` → `mcp-tool-registry.searchTools` → ranked results with name/description/parameter shape (`renderTsShape`-style TS shape or indented JSON Schema).
|
||||
- `describe` → full input schema for one tool.
|
||||
- `server` (no tool) → full tool list of that server.
|
||||
- `tool + server` (or auto-disambiguated) → `callMcpTool`; errors include suggestions + auth/server status hints.
|
||||
- `connect` → lazy connect + metadata refresh; `action` → `status` / `auth-start` only (no `auth-complete` — the API callback completes OAuth server-side, so the model never has a redirect URL to paste; it polls `status` instead).
|
||||
|
||||
### 5g. direct tools — per-server opt-in
|
||||
- `resolveDirectTools(config)`: when `config.directTools === true`, that server's allowed tools (after `includeTools`/`excludeTools`) become direct `AgentTool`s. **`directTools` is boolean-only** (Q6) — tool selection is always via the include/exclude filters, never a `string[]`.
|
||||
- Prefixed names via `formatToolName` (pi-mcp-adapter "server" prefix mode: `{serverName}_{toolName}`; dots sanitized to `_`) (Q7); `parameters` from `mcp-tool-schema.ts`; `execute` → same `callMcpTool` path as the proxy.
|
||||
- These tools are registered alongside the `mcp` proxy tool (the proxy stays for discovery/auth/status and for servers not in direct mode).
|
||||
|
||||
### 5h. `mcp-service.ts` — `McpService` (singleton, per AGENTS.md patterns)
|
||||
- **CRUD**: `createServer`, `updateServer` (on **URL/auth/name** change → clear cached tools + credentials + close connection; renaming changes the direct-tool prefix, so it must invalidate exactly like a URL change), `deleteServer` (cascade), `listServers`, `getServer`.
|
||||
- **Discovery**: `discoverTools(serverId)` — connect (or read cached), `listTools`, persist to `McpServer.tools`, update `status`/`lastError`/`lastConnectedAt`, refresh the in-process registry. Used by `refreshTools` API + lazy refresh on connect.
|
||||
- **OAuth**:
|
||||
- `startAuth(serverId)` → `SDK auth()` flow: discovery + (dynamic) client registration → capture authorization URL via `redirectToAuthorization` → persist `pendingAuth` → return URL. (For `client_credentials`, exchange directly, store tokens.)
|
||||
- `completeAuth(serverId, { code, iss })` → validate pending flow (`state` checked at callback), run SDK `auth({ authorizationCode, iss, ... })` → tokens saved to DB → clear pendingAuth.
|
||||
- `handleOAuthCallback(code, state, iss)` — used by the API callback route (validates state, delegates to `completeAuth`).
|
||||
- `getAuthStatus(serverId)`, `removeAuth(serverId)`.
|
||||
- **Agent integration**: `buildAgentTools(agentId, teamId, userId?): Promise<AgentTool[]>` — reads the agent's **assigned** MCP servers via the `AgentMcpServer` join (only `enabled` ones), returns `[mcpProxyTool, ...directToolsForAssignedOptedInServers]` (D3, D6). **If the agent has zero assigned enabled servers, return `[]` (no proxy tool registered — don't waste LLM context).** Proxy description lists the agent's assigned servers; direct tools registered only for opted-in servers. Lazy connection: first `execute` ensures connect; `needs_auth` → instructive error text; failures return error text + record `lastError` (non-fatal to chat).
|
||||
- **`callMcpTool(serverId, toolName, args, ctx?: { teamId; userId? })`** — **permission gate first (D10)**: resolve the requesting user's team role and compare against `McpServer.permission` using the `ROLE_HIERARCHY` pattern from `packages/agent/src/tools/read-skill.ts`; return permission-denied error text if the role is insufficient or if there is no user context and permission > reviewer. Then ensure connection → `client.callTool({ name, arguments })` → transform content (text/image/resource → `TextContent`/`ImageContent`), fall back to `structuredContent` JSON when `content` is empty.
|
||||
- In-memory manager cache per process (`Map<serverId, McpServerManager>`), with `serverId` as the key (server names are per-team, so id is unambiguous).
|
||||
|
||||
---
|
||||
|
||||
## 6. API layer (`packages/api/src/mcp.ts` + mount in `index.ts`)
|
||||
|
||||
```
|
||||
# Public (no auth — OAuth provider redirects here)
|
||||
GET/POST /api/mcp/oauth/callback → validate state, completeAuth, return HTML page that
|
||||
postMessage()s result to the opener (webui tab) and closes
|
||||
|
||||
# Authenticated (authMiddleware + authz: Admin on Team for list/create; Admin on McpServer for id-scoped, matching skills)
|
||||
GET /teams/:teamId/mcp/servers
|
||||
POST /teams/:teamId/mcp/servers
|
||||
PATCH /mcp/servers/:id
|
||||
PATCH /mcp/servers/:id/permission → set `permission` (mirror skill)
|
||||
DELETE /mcp/servers/:id
|
||||
GET /mcp/servers/:id
|
||||
POST /mcp/servers/:id/tools/refresh → discoverTools, returns McpToolInfo[]
|
||||
GET /mcp/servers/:id/tools
|
||||
POST /mcp/servers/:id/auth/start → { authorizationUrl } | 200 (already authenticated)
|
||||
POST /mcp/servers/:id/auth/complete → { code, iss? } → status
|
||||
GET /mcp/servers/:id/auth/status
|
||||
DELETE /mcp/servers/:id/auth
|
||||
POST /mcp/servers/:id/test → optional: try connect + listTools (for UI validation)
|
||||
```
|
||||
|
||||
- Route chaining on Hono + `zValidator` (per AGENTS.md). **Authz mirrors the skill API exactly**: list/create → `ResourceType.Team` + `Permission.Admin`; id-scoped routes (`PATCH/DELETE/GET /mcp/servers/:id`, tools, auth, test, permission) → new `ResourceType.McpServer` + `Permission.Admin`, with a `resolveContext` case added in `packages/core/src/authz/authz.ts` (look up `teamId` from the server record, like `ResourceType.Skill`).
|
||||
- Audit logging via `auditLogService.logAction` with new `AuditAction` entries (`mcp_server_create/update/delete`).
|
||||
- Responses always mask secrets.
|
||||
|
||||
---
|
||||
|
||||
## 7. Agent integration (`packages/agent`)
|
||||
|
||||
1. `getAgentChatContextActivity` (and the autofill variant) fetch the agent's **assigned** `McpServer` records (via `AgentMcpServer`, only `enabled`, + cached tools + `directTools` config) and add `mcpServers` to `AgentExecutionContext`. `agentService.createAgent/updateAgent` persist `mcpServerIds` (mirrors `skills`).
|
||||
2. In `executeAgentPrompt`, after building `customTools` from `params.tools`, call `mcpService.buildAgentTools(agentId, teamId, userId)` and append → returns the single `mcp` proxy tool plus direct tools for opted-in assigned servers (D3/D6). (Autofill agents keep `disableTools` semantics; MCP tools only go to chat agents by default.)
|
||||
3. The proxy tool description carries the agent's assigned server map + usage; the model discovers tools on demand via `search`/`describe`/`server` (pi-mcp-adapter two-phase model). Direct-tool servers appear as normal native tools.
|
||||
4. `callMcpTool` handles "tool not found / needs auth / server down" with clear text + "did you mean" suggestions so the model can recover. A `needs_auth` result surfaces a hint (e.g. "Ask the admin to connect MCP server X in Settings → MCP").
|
||||
5. **Permission enforcement (D10)**: the gate lives inside `callMcpTool` (shared by proxy + direct tools), so no per-agent config is needed. Proxy `search`/`describe`/`status` stay available to keep the two-phase discovery model working; executing a tool the requesting user's role doesn't allow returns permission-denied error text (same style as `read_skill`).
|
||||
|
||||
---
|
||||
|
||||
## 8. Environment config
|
||||
|
||||
- `MCP_OAUTH_REDIRECT_BASE_URL` (optional) — the OAuth redirect base. `redirectUri` defaults to `${MCP_OAUTH_REDIRECT_BASE_URL}/api/mcp/oauth/callback`, and `MCP_OAUTH_REDIRECT_BASE_URL` itself defaults to `BETTER_AUTH_URL`. Document in README / `.env` samples.
|
||||
|
||||
---
|
||||
|
||||
## 9. Testing strategy (AGENTS.md mandates)
|
||||
|
||||
1. **Core service tests** (`packages/core/src/mcp/*.test.ts`, `setupTestDbHooks`):
|
||||
- DB store: save/read/update/clear tokens, clientInfo, verifier, state; URL-change invalidation; pendingAuth TTL.
|
||||
- OAuth provider: mocked SDK `auth()` flow asserting tokens/clientInfo persisted and `tokens()` returns stored values (adapt pi-mcp-adapter's `mcp-oauth-provider.test.ts`).
|
||||
- Tool schema conversion unit tests.
|
||||
- Server CRUD + `discoverTools` against a **real in-process MCP test server**: implement a tiny MCP server in the test using `@modelcontextprotocol/core` `Server` + `StreamableHTTP` on an ephemeral port (add `@modelcontextprotocol/core` as a devDependency); assert tools listed, `callMcpTool` round-trip, bearer auth header received, and 401 → `needs_auth`.
|
||||
- Proxy tool tests: search ranking (`searchTools` scoring/coverage gate, camelCase/snake-case queries), `describe`/`list` output, call resolution with `server` disambiguation across two servers exposing same-named tools, error suggestions.
|
||||
- Direct tools tests: `directTools: true` (boolean) + `includeTools`/`excludeTools` selection, prefixed naming (`{server}_{tool}`), and that direct tools + proxy coexist.
|
||||
- Per-agent assignment tests (`AgentMcpServer` join): agent with no assignment → `buildAgentTools` returns `[]`; agent with assignment gets that server's tools; disabled servers excluded.
|
||||
- Permission gating tests (D10): server with `permission: 'editor'` → chat as reviewer returns permission-denied text; editor/owner succeeds; no user context + permission > reviewer denied (mirror `read-skill.ts`).
|
||||
- Rename invalidation test: renaming a server clears cached tools + credentials + closes the connection (direct-tool prefix changes).
|
||||
- `buildAgentTools(agentId, ...)`: returns `[mcpProxyTool]` by default and adds direct tools only for assigned opted-in servers.
|
||||
2. **API tests** (`packages/api/src/mcp.test.ts`): mock `mcpService` (`vi.mock`), verify routes, authz, input validation, audit logging, and that the callback route validates state.
|
||||
3. **Workflow E2E** (`packages/e2e/workflow/mcp.test.ts`, both local + temporal executors): start the in-process MCP test server, seed team + McpServer, run `agent_chat` task with `AgentHarness.prototype.prompt` mocked to return a tool call to the `mcp` proxy tool (and a second case exercising direct-tools mode), and assert the workflow output reflects the MCP result (mock only AI calls — real MCP server, real DB, real S3). This exercises the full path `createAgentSession → mcpService.buildAgentTools → proxy/direct tool execute → callMcpTool → MCP server`.
|
||||
|
||||
---
|
||||
|
||||
## 10. Out of scope (this task)
|
||||
|
||||
- WebUI frontend (noted API contract is ready; `mcp.ts` DTOs + routes are the surface).
|
||||
- Encrypting secrets at rest (plaintext-in-DB confirmed, Q3; encryption is a follow-up).
|
||||
- stdio/command-based MCP servers (confirmed out of scope, Q1), resources/prompts exposure (tools only in v1).
|
||||
|
||||
---
|
||||
|
||||
## 11. Decisions & resolved questions
|
||||
|
||||
All open questions are now **resolved**:
|
||||
|
||||
| # | Question | Decision |
|
||||
|---|----------|----------|
|
||||
| Q1 | Transport scope | ✅ **URL-only** (Streamable HTTP + SSE fallback), no stdio → D2 |
|
||||
| Q2 | Tool exposure | ✅ Single `mcp` proxy tool by default + per-server opt-in `directTools` (boolean) → D3 |
|
||||
| Q3 | Scoping | ✅ **Per-agent** assignment via `AgentMcpServer` join (mirrors skills) → D6 |
|
||||
| Q4 | Secrets storage | ✅ Plaintext in DB (consistent with `Provider.config.apiKey`); encryption-at-rest is a follow-up → D8 |
|
||||
| Q5 | Callback URL base | ✅ `redirectUri` defaults to `${BETTER_AUTH_URL}/api/mcp/oauth/callback`, `MCP_OAUTH_REDIRECT_BASE_URL` override → D5 |
|
||||
| Q6 | Auth types | ✅ All: `none`, `bearer`, OAuth `authorization_code` (dynamic registration + pre-registered clientId) + `client_credentials` → D9 |
|
||||
| Q7 | Per-tool filters | ✅ Keep `includeTools`/`excludeTools`; `directTools` is **boolean-only** (no `string[]`) → D3/D6 |
|
||||
| Q8 | Direct-tool naming | ✅ pi-mcp-adapter naming: proxy tool named `mcp`; direct tools `{server}_{tool}` ("server" prefix mode) → D3/D7 |
|
||||
| Q9 | Proxy `auth-complete` action | ✅ **Dropped** — OAuth completes server-side via the API callback; proxy `action` is only `status`/`auth-start`; the model polls `status` → §5f |
|
||||
| Q10 | Usage permission | ✅ `McpServer.permission` mirrors `Skill.permission`, enforced in `callMcpTool` → D10 |
|
||||
| Q11 | Authz on id-scoped routes | ✅ Follow skill: add `ResourceType.McpServer` + `resolveContext` case → §6 |
|
||||
| Q12 | `config.toolPrefix` | ✅ **Removed** (redundant — naming always `{server}_{tool}`) → §3 |
|
||||
| Q13 | Rename handling | ✅ Rename clears cached tools + credentials + closes connection → §5h |
|
||||
|
||||
**Remaining (implementation-level, no user decision needed):** none. Ready to implement.
|
||||
|
||||
---
|
||||
|
||||
## 12. Implementation order & definition of done
|
||||
|
||||
Suggested order (each step keeps `bun run test` green where applicable):
|
||||
|
||||
1. **DB**: add `McpServer` (incl. `permission TeamMemberRole @default(reviewer)`)/`AgentMcpServer`/`McpServerCredential` models + `Team`/`Agent` relations to `packages/db/prisma/schema.prisma`; add `McpServerAuthConfig`, `McpServerConfig`, `McpToolInfo`, `McpStoredTokens`, `McpStoredClientInfo`, `McpPendingAuth` to `packages/db/src/prisma-json-types.ts` (global `PrismaJson` namespace); generate client (`bun --bun run prisma generate`) + migration (`bun --bun run prisma migrate dev --name add_mcp_servers`; never hand-write DDL).
|
||||
2. **DTOs**: `packages/dtos/src/mcp.ts` (schemas per §4, `zod`), export from `packages/dtos/src/index.ts`; add `mcpServerIds?` to `packages/dtos/src/agent.ts` `CreateAgentParams`/`UpdateAgentParams` + responses.
|
||||
3. **Core**: `packages/core/src/mcp/` files 5a→5h in dependency order (db-store → oauth-provider → server-manager → tool-schema → tool-registry → proxy-tool → direct-tools → service). Add `@modelcontextprotocol/client` to `packages/core/package.json` via `bun add @modelcontextprotocol/client --filter @shumai/core`.
|
||||
4. **Agent service**: persist `mcpServerIds` in `packages/core/src/agent/agent.ts` `createAgent`/`updateAgent` (mirror `skills` handling, including the `deleteMany` + `createMany` pattern for the join table).
|
||||
5. **API**: `packages/api/src/mcp.ts` (routes per §6, Hono chaining + `zValidator`), mount in `packages/api/src/index.ts` (**public OAuth callback route must be mounted before `authMiddleware`**, alongside `authnRoute`/`publicInviteRoute`), add `AuditAction` entries, add `ResourceType.McpServer` to `authz.ts` `resolveContext`, mask secrets in responses.
|
||||
6. **Agent integration**: `AgentExecutionContext` gains `mcpServers` in `packages/agent/src/activities/agent.ts` (fetch via join); `executeAgentPrompt` calls `mcpService.buildAgentTools(agentId, teamId, userId)` and appends to customTools (`packages/agent/src/index.ts` `createAgentSession` call site); permission gate lands inside `callMcpTool` (D10).
|
||||
7. **Tests**: core unit tests (incl. permission gating, rename-invalidation, tool-schema conversion) + in-process MCP test server (`@modelcontextprotocol/core` devDependency), API tests (`vi.mock` mcpService), workflow E2E (`packages/e2e/workflow/mcp.test.ts`, both proxy + direct modes, incl. a permission-denied case); update `apps/web/e2e/README.md` only if web specs change (they don't — webui out of scope).
|
||||
8. **Verify**: run all checks, remove verification artifacts, commit, push branch, `gh pr create` (per AGENTS.md workflow).
|
||||
|
||||
**Key shumai files to read before/while implementing**: `packages/db/prisma/schema.prisma` (models `Team` ~236, `Skill` ~277, `Agent` ~737, `AgentSkill` ~761), `packages/db/src/prisma-json-types.ts`, `packages/core/src/agent/agent.ts` (skills handling), `packages/api/src/agent.ts` (agent routes), `packages/core/src/authz/authz.ts` (Permission/ResourceType), `packages/core/src/skill/skill.ts` (service pattern), `packages/api/src/skill.ts` (route pattern), `packages/api/src/index.ts` (route mounting + audit), `packages/agent/src/index.ts` (`createAgentSession` customTools ~337), `packages/agent/src/activities/agent.ts` (`executeAgentPrompt`, `getAgentChatContextActivity`), `packages/agent/src/tools/read-skill.ts` (permission gate pattern), `packages/agent/src/tools/create-folder.ts` (AgentTool shape), `packages/core/src/logger.ts` (pino), `packages/core/src/pagination.ts` (`paginateQuery`).
|
||||
|
||||
**Definition of done** (AGENTS.md submission rules): `bun run lint` + `bun run format` + `bun run typecheck` + `bun run test` + `bun run test:e2e:app` + `bun run test:e2e:webui` + `bun run test:e2e:workflow` all pass **simultaneously** on one final code state; backend tests comprehensive (incl. the MCP in-process server round-trips and workflow E2E for both proxy and direct modes); no explicit `any`; no verification artifacts committed; Conventional Commits; PR per the AGENTS.md template.
|
||||
@@ -245,11 +245,14 @@ BETTER_AUTH_SECRET=ySxs7DxzHDZBbeeHNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
STORAGE_BACKEND=local
|
||||
SHUMAI_SERVER_PORT=3000
|
||||
AWS_ENDPOINT_URL_S3=http://localhost:3000
|
||||
# Optional: base URL for MCP OAuth redirects (defaults to BETTER_AUTH_URL)
|
||||
MCP_OAUTH_REDIRECT_BASE_URL=http://localhost:3000
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> `SHUMAI_SERVER_PORT` sets the port the server starts on, while `AWS_ENDPOINT_URL_S3` is used by the browser to build file upload URLs.
|
||||
> If deploying on a remote server (e.g. `http://123.456.7.8`) with a mapped port (e.g. `12345:3000` in docker-compose), set `AWS_ENDPOINT_URL_S3` to `http://123.456.7.8:12345`.
|
||||
> `MCP_OAUTH_REDIRECT_BASE_URL` is only needed when MCP servers use OAuth: the authorization redirect URI defaults to `{BETTER_AUTH_URL}/api/mcp/oauth/callback`; set it to an externally reachable URL if the app is served behind a proxy.
|
||||
|
||||
#### Step 6: Run Shumai
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
},
|
||||
"apps/agent": {
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
"bin": {
|
||||
"shumai-agent": "./src/index.ts",
|
||||
},
|
||||
@@ -45,7 +45,7 @@
|
||||
},
|
||||
"apps/cli": {
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
"bin": {
|
||||
"shumai-cli": "./src/index.ts",
|
||||
},
|
||||
@@ -60,7 +60,7 @@
|
||||
},
|
||||
"apps/transcode": {
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
"bin": {
|
||||
"shumai-transcode": "./src/index.ts",
|
||||
},
|
||||
@@ -72,7 +72,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
"dependencies": {
|
||||
"@shumai/agent": "workspace:*",
|
||||
"@shumai/api": "workspace:*",
|
||||
@@ -92,7 +92,7 @@
|
||||
},
|
||||
"packages/agent": {
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sandbox-runtime": "0.0.66",
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
@@ -117,7 +117,7 @@
|
||||
},
|
||||
"packages/api": {
|
||||
"name": "@shumai/api",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
"dependencies": {
|
||||
"@hono/zod-validator": "0.7.6",
|
||||
"@shumai/core": "workspace:*",
|
||||
@@ -131,10 +131,11 @@
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@shumai/core",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@earendil-works/pi-ai": "0.82.1",
|
||||
"@modelcontextprotocol/client": "2.0.0",
|
||||
"@shumai/db": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@sinclair/typebox": "0.34.49",
|
||||
@@ -151,11 +152,13 @@
|
||||
"pino": "10.3.1",
|
||||
"sharp": "0.34.5",
|
||||
"tweetnacl": "1.0.3",
|
||||
"typebox": "1.1.38",
|
||||
"ulid": "3.0.2",
|
||||
"yaml": "2.9.0",
|
||||
"zod": "4.4.3",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/server": "2.0.0",
|
||||
"@types/adm-zip": "0.5.8",
|
||||
"@types/extract-zip": "2.0.3",
|
||||
"@types/pdfkit": "0.17.6",
|
||||
@@ -163,7 +166,7 @@
|
||||
},
|
||||
"packages/db": {
|
||||
"name": "@shumai/db",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@prisma/adapter-pg": "7.8.0",
|
||||
@@ -179,7 +182,7 @@
|
||||
},
|
||||
"packages/dtos": {
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"zod": "4.4.3",
|
||||
@@ -187,7 +190,7 @@
|
||||
},
|
||||
"packages/e2e": {
|
||||
"name": "@shumai/e2e",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@google/genai": "1.52.0",
|
||||
@@ -202,11 +205,11 @@
|
||||
},
|
||||
"packages/tableprinter": {
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
},
|
||||
"packages/transcode": {
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
@@ -220,7 +223,7 @@
|
||||
},
|
||||
"packages/webui": {
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "1.5.0",
|
||||
"@dnd-kit/abstract": "0.4.0",
|
||||
@@ -318,7 +321,7 @@
|
||||
},
|
||||
"packages/workflow-core": {
|
||||
"name": "@shumai/workflow-core",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.5",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
@@ -735,6 +738,12 @@
|
||||
|
||||
"@mistralai/mistralai": ["@mistralai/mistralai@2.2.6", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.40.0", "ws": "^8.18.0", "zod": "^3.25.0 || ^4.0.0", "zod-to-json-schema": "^3.25.0" }, "peerDependencies": { "@opentelemetry/api": "^1.9.0" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-W8pX7zHxjJvMIpw8JMxeJEleapXX0Q9NPszdNzqkM3MIEoIGPObdodujj+WHteXEvGfaP/AMwlNyRfEzSY6dQQ=="],
|
||||
|
||||
"@modelcontextprotocol/client": ["@modelcontextprotocol/client@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw=="],
|
||||
|
||||
"@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.0.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA=="],
|
||||
|
||||
"@modelcontextprotocol/server": ["@modelcontextprotocol/server@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "zod": "^4.2.0" } }, "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw=="],
|
||||
|
||||
"@napi-rs/canvas": ["@napi-rs/canvas@1.0.2", "", { "optionalDependencies": { "@napi-rs/canvas-android-arm64": "1.0.2", "@napi-rs/canvas-darwin-arm64": "1.0.2", "@napi-rs/canvas-darwin-x64": "1.0.2", "@napi-rs/canvas-linux-arm-gnueabihf": "1.0.2", "@napi-rs/canvas-linux-arm64-gnu": "1.0.2", "@napi-rs/canvas-linux-arm64-musl": "1.0.2", "@napi-rs/canvas-linux-riscv64-gnu": "1.0.2", "@napi-rs/canvas-linux-x64-gnu": "1.0.2", "@napi-rs/canvas-linux-x64-musl": "1.0.2", "@napi-rs/canvas-win32-arm64-msvc": "1.0.2", "@napi-rs/canvas-win32-x64-msvc": "1.0.2" } }, "sha512-EYEqlMYaCbpZDz+IgDH5xp9MTd3ui4dmGqbQYryhMLnSRxrhHKq5KQWHHKxFUcEP4Hp8/BWgvqXocX4j7iSbOQ=="],
|
||||
|
||||
"@napi-rs/canvas-android-arm64": ["@napi-rs/canvas-android-arm64@1.0.2", "", { "os": "android", "cpu": "arm64" }, "sha512-IMXKVQod0ol4vt3gmClUfXz4JAgHYESGPCUqmH3lQxBoL0K/2greJaQE1HVBVxWWFKfLc4OLZVdxg7kXVyXv+g=="],
|
||||
@@ -1761,6 +1770,10 @@
|
||||
|
||||
"events-universal": ["events-universal@1.0.1", "", { "dependencies": { "bare-events": "^2.7.0" } }, "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw=="],
|
||||
|
||||
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
|
||||
|
||||
"eventsource-parser": ["eventsource-parser@3.1.0", "", {}, "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg=="],
|
||||
|
||||
"expect-type": ["expect-type@1.3.0", "", {}, "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA=="],
|
||||
|
||||
"exsolve": ["exsolve@1.0.8", "", {}, "sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA=="],
|
||||
@@ -2329,6 +2342,8 @@
|
||||
|
||||
"pino-std-serializers": ["pino-std-serializers@7.1.0", "", {}, "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw=="],
|
||||
|
||||
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
||||
|
||||
"pkcs7": ["pkcs7@1.0.4", "", { "dependencies": { "@babel/runtime": "^7.5.5" }, "bin": { "pkcs7": "bin/cli.js" } }, "sha512-afRERtHn54AlwaF2/+LFszyAANTCggGilmcmILUzEjvs3XgFZT+xE6+QWQcAGmu4xajy+Xtj7acLOPdx5/eXWQ=="],
|
||||
|
||||
"pkg-types": ["pkg-types@2.3.1", "", { "dependencies": { "confbox": "^0.2.4", "exsolve": "^1.0.8", "pathe": "^2.0.3" } }, "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg=="],
|
||||
|
||||
@@ -7,6 +7,7 @@ import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { mcpService } from '@shumai/core/src/mcp/mcp-service'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { encodeCursor, paginateQuery } from '@shumai/core/src/pagination'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
@@ -59,6 +60,7 @@ export interface AgentExecutionContext {
|
||||
agent: AgentWithProviderAndModel
|
||||
dbProviders: DbProviderWithModels[]
|
||||
teamSkills: Skill[]
|
||||
mcpServers: Prisma.McpServerGetPayload<Record<string, never>>[]
|
||||
enabledSkillIds: string[]
|
||||
allowedDomains: string[]
|
||||
}
|
||||
@@ -119,6 +121,13 @@ When creating a file or version, first use 'list_autofill_fields' to inspect the
|
||||
const agentConfig = agent.config as PrismaJson.AgentConfig | null | undefined
|
||||
const thinkingLevel = agentConfig?.thinkingLevel || 'off'
|
||||
|
||||
// MCP tools are only wired to chat agents (D6); autofill/embedding/naming
|
||||
// sessions never receive MCP tools even if a server is assigned.
|
||||
const mcpTools =
|
||||
agent.type === 'chat'
|
||||
? await mcpService.buildAgentTools(params.agentId, params.teamId, params.userId)
|
||||
: []
|
||||
|
||||
const { session, harness } = await createAgentSession({
|
||||
teamId: params.teamId,
|
||||
agentId: params.agentId,
|
||||
@@ -136,7 +145,7 @@ When creating a file or version, first use 'list_autofill_fields' to inspect the
|
||||
sessionId: params.sessionId,
|
||||
userId: params.userId,
|
||||
userCommentId: params.userCommentId,
|
||||
customTools: params.tools || [],
|
||||
customTools: [...(params.tools || []), ...mcpTools],
|
||||
providers: dbProviders.map((p) => ({
|
||||
name: p.name,
|
||||
config: p.config,
|
||||
@@ -881,6 +890,13 @@ export async function getAgentChatContextActivity(params: {
|
||||
const enabledSkills = (agent.skills ?? []).map((as) => as.skill)
|
||||
const enabledSkillIds = enabledSkills.map((s) => s.id)
|
||||
|
||||
// Fetch the agent's assigned MCP servers
|
||||
const assignments = await prisma.agentMcpServer.findMany({
|
||||
where: { agentId: params.agentId },
|
||||
include: { mcpServer: true },
|
||||
})
|
||||
const mcpServers = assignments.map((a) => a.mcpServer)
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
@@ -890,6 +906,7 @@ export async function getAgentChatContextActivity(params: {
|
||||
agent,
|
||||
dbProviders,
|
||||
teamSkills: enabledSkills,
|
||||
mcpServers,
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
}
|
||||
@@ -961,6 +978,9 @@ export async function getAgentAutofillContextActivity(params: {
|
||||
const enabledSkills = (agentWithDetails.skills ?? []).map((as) => as.skill)
|
||||
const enabledSkillIds = enabledSkills.map((s) => s.id)
|
||||
|
||||
// Autofill agents currently do not use MCP tools.
|
||||
const mcpServers: Prisma.McpServerGetPayload<Record<string, never>>[] = []
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
@@ -970,6 +990,7 @@ export async function getAgentAutofillContextActivity(params: {
|
||||
agent: agentWithDetails,
|
||||
dbProviders,
|
||||
teamSkills: enabledSkills,
|
||||
mcpServers,
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
mcpServerIds: (agent.mcpServers || []).map((m) => m.mcpServerId),
|
||||
deniedTools: config.deniedTools || [],
|
||||
}
|
||||
}),
|
||||
@@ -93,6 +94,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
mcpServerIds: (agent.mcpServers || []).map((m) => m.mcpServerId),
|
||||
deniedTools: config.deniedTools || [],
|
||||
}
|
||||
|
||||
@@ -146,6 +148,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
mcpServerIds: (agent.mcpServers || []).map((m) => m.mcpServerId),
|
||||
deniedTools: config.deniedTools || [],
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import fileRoute from './file'
|
||||
import folderRoute from './folder'
|
||||
import inviteRoute from './invite'
|
||||
import metadataRoute from './metadata'
|
||||
import mcpRoute, { mcpOauthCallbackRoute } from './mcp'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { tokenAuthMiddleware } from './middleware/tokenAuth'
|
||||
import notificationRoute from './notification'
|
||||
@@ -34,6 +35,7 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
|
||||
.route('/', publicInviteRoute)
|
||||
.route('/', publicShareRoute)
|
||||
.route('/', localUploadRoute)
|
||||
.route('/', mcpOauthCallbackRoute)
|
||||
|
||||
// Selected routes supporting API token authentication
|
||||
.use('/projects', tokenAuthMiddleware)
|
||||
@@ -61,6 +63,7 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
|
||||
.route('/', uploadRoute)
|
||||
.route('/', shareRoute)
|
||||
.route('/', skillRoute)
|
||||
.route('/', mcpRoute)
|
||||
.route('/', watermarkTemplateRoute)
|
||||
|
||||
app.route('/files', s3Route)
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import mcpRoute, { mcpOauthCallbackRoute } from './mcp'
|
||||
import { mcpService } from '@shumai/core/src/mcp/mcp-service'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
|
||||
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
|
||||
auditLogService: {
|
||||
logAction: vi.fn().mockResolvedValue({}),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/mcp/mcp-service', () => ({
|
||||
mcpService: {
|
||||
listServers: vi.fn(),
|
||||
createServer: vi.fn(),
|
||||
getServer: vi.fn(),
|
||||
getServerRecord: vi.fn(),
|
||||
updateServer: vi.fn(),
|
||||
updateServerPermission: vi.fn(),
|
||||
deleteServer: vi.fn(),
|
||||
refreshServer: vi.fn(),
|
||||
startAuth: vi.fn(),
|
||||
completeAuth: vi.fn(),
|
||||
getAuthStatus: vi.fn(),
|
||||
removeAuth: vi.fn(),
|
||||
testServer: vi.fn(),
|
||||
handleOauthCallback: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
McpServer: 'mcpServer',
|
||||
},
|
||||
}))
|
||||
|
||||
import type { McpServerInfo } from '@shumai/dtos'
|
||||
|
||||
const serverInfo: McpServerInfo = {
|
||||
id: 'server1',
|
||||
name: 'github',
|
||||
description: 'GitHub MCP server',
|
||||
instructions: 'Always use the sandbox API and respect rate limits.',
|
||||
url: 'https://mcp.example.com/github',
|
||||
transport: 'streamable_http',
|
||||
authType: 'bearer',
|
||||
permission: 'reviewer',
|
||||
status: 'not_connected',
|
||||
toolCount: 0,
|
||||
hasCredential: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
|
||||
describe('MCP API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', mcpRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
// Clear call history so per-test call assertions are isolated.
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
vi.mocked(mcpService.listServers).mockResolvedValue([serverInfo])
|
||||
vi.mocked(mcpService.getServer).mockResolvedValue(serverInfo)
|
||||
vi.mocked(mcpService.getServerRecord).mockResolvedValue({
|
||||
...serverInfo,
|
||||
lastError: null,
|
||||
lastConnectedAt: null,
|
||||
teamId: 'team1',
|
||||
tools: [],
|
||||
credential: null,
|
||||
config: null,
|
||||
authConfig: { type: 'bearer', bearerToken: 'secret' },
|
||||
} as never)
|
||||
})
|
||||
|
||||
test('lists servers with Admin permission on the team', async () => {
|
||||
const res = await app.request('/teams/team1/mcp/servers')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ servers: [serverInfo] })
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 'team1',
|
||||
})
|
||||
})
|
||||
|
||||
test('includes server instructions in list and get responses', async () => {
|
||||
const list = await app.request('/teams/team1/mcp/servers')
|
||||
expect((await list.json()).servers[0].instructions).toBe(
|
||||
'Always use the sandbox API and respect rate limits.',
|
||||
)
|
||||
|
||||
const got = await app.request('/mcp/servers/server1')
|
||||
expect((await got.json()).instructions).toBe(
|
||||
'Always use the sandbox API and respect rate limits.',
|
||||
)
|
||||
})
|
||||
|
||||
test('creates a server and audits it', async () => {
|
||||
vi.mocked(mcpService.createServer).mockResolvedValue(serverInfo)
|
||||
const res = await app.request('/teams/team1/mcp/servers', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: 'https://mcp.example.com/github' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(serverInfo)
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ action: 'mcp_server_create', teamId: 'team1' }),
|
||||
)
|
||||
})
|
||||
|
||||
test('rejects a server with an invalid URL', async () => {
|
||||
const res = await app.request('/teams/team1/mcp/servers', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: 'not-a-url' }),
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
expect(mcpService.createServer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('gets a single server with Admin on the McpServer resource', async () => {
|
||||
const res = await app.request('/mcp/servers/server1')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(serverInfo)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id: 'server1',
|
||||
})
|
||||
})
|
||||
|
||||
test('returns 404 when the server is missing', async () => {
|
||||
vi.mocked(mcpService.getServer).mockResolvedValue(null)
|
||||
const res = await app.request('/mcp/servers/missing')
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
test('updates a server and audits it', async () => {
|
||||
vi.mocked(mcpService.updateServer).mockResolvedValue({
|
||||
...serverInfo,
|
||||
transport: 'sse',
|
||||
})
|
||||
const res = await app.request('/mcp/servers/server1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ transport: 'sse' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ ...serverInfo, transport: 'sse' })
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ action: 'mcp_server_update', itemId: 'server1' }),
|
||||
)
|
||||
})
|
||||
|
||||
test('updates the permission via the dedicated route', async () => {
|
||||
vi.mocked(mcpService.updateServerPermission).mockResolvedValue({
|
||||
...serverInfo,
|
||||
permission: 'editor',
|
||||
})
|
||||
const res = await app.request('/mcp/servers/server1/permission', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ permission: 'editor' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ ...serverInfo, permission: 'editor' })
|
||||
expect(mcpService.updateServerPermission).toHaveBeenCalledWith('server1', 'editor')
|
||||
})
|
||||
|
||||
test('rejects an invalid permission value', async () => {
|
||||
const res = await app.request('/mcp/servers/server1/permission', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ permission: 'superadmin' }),
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
test('deletes a server and audits it', async () => {
|
||||
const res = await app.request('/mcp/servers/server1', { method: 'DELETE' })
|
||||
expect(res.status).toBe(204)
|
||||
expect(auditLogService.logAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ action: 'mcp_server_delete', itemId: 'server1' }),
|
||||
)
|
||||
})
|
||||
|
||||
test('refreshes a server and returns the updated record', async () => {
|
||||
vi.mocked(mcpService.refreshServer).mockResolvedValue({
|
||||
...serverInfo,
|
||||
status: 'connected',
|
||||
toolCount: 3,
|
||||
instructions: 'Always use the sandbox API and respect rate limits.',
|
||||
})
|
||||
const res = await app.request('/mcp/servers/server1/refresh', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
...serverInfo,
|
||||
status: 'connected',
|
||||
toolCount: 3,
|
||||
instructions: 'Always use the sandbox API and respect rate limits.',
|
||||
})
|
||||
})
|
||||
|
||||
test('refresh failure returns 502 with the error message', async () => {
|
||||
vi.mocked(mcpService.refreshServer).mockRejectedValue(new Error('boom'))
|
||||
const res = await app.request('/mcp/servers/server1/refresh', { method: 'POST' })
|
||||
expect(res.status).toBe(502)
|
||||
expect(await res.json()).toEqual({ error: 'boom' })
|
||||
})
|
||||
|
||||
test('lists cached tools', async () => {
|
||||
vi.mocked(mcpService.getServerRecord).mockResolvedValue({
|
||||
...serverInfo,
|
||||
lastError: null,
|
||||
lastConnectedAt: null,
|
||||
teamId: 'team1',
|
||||
tools: [{ name: 'echo' }],
|
||||
credential: null,
|
||||
config: null,
|
||||
authConfig: null,
|
||||
} as never)
|
||||
const res = await app.request('/mcp/servers/server1/tools')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ tools: [{ name: 'echo' }] })
|
||||
})
|
||||
|
||||
test('starts OAuth auth', async () => {
|
||||
vi.mocked(mcpService.startAuth).mockResolvedValue({
|
||||
authorizationUrl: 'https://auth.example.com/authorize',
|
||||
})
|
||||
const res = await app.request('/mcp/servers/server1/auth/start', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
authorizationUrl: 'https://auth.example.com/authorize',
|
||||
status: 'in_progress',
|
||||
})
|
||||
})
|
||||
|
||||
test('completes OAuth auth', async () => {
|
||||
vi.mocked(mcpService.completeAuth).mockResolvedValue('authenticated')
|
||||
const res = await app.request('/mcp/servers/server1/auth/complete', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code: 'auth-code', iss: 'https://issuer.example.com' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ status: 'authenticated' })
|
||||
expect(mcpService.completeAuth).toHaveBeenCalledWith('server1', {
|
||||
code: 'auth-code',
|
||||
iss: 'https://issuer.example.com',
|
||||
})
|
||||
})
|
||||
|
||||
test('reports auth status', async () => {
|
||||
vi.mocked(mcpService.getAuthStatus).mockResolvedValue('not_authenticated')
|
||||
const res = await app.request('/mcp/servers/server1/auth/status')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ status: 'not_authenticated' })
|
||||
})
|
||||
|
||||
test('removes auth', async () => {
|
||||
const res = await app.request('/mcp/servers/server1/auth', { method: 'DELETE' })
|
||||
expect(res.status).toBe(204)
|
||||
expect(mcpService.removeAuth).toHaveBeenCalledWith('server1')
|
||||
})
|
||||
|
||||
test('tests the server connection', async () => {
|
||||
vi.mocked(mcpService.testServer).mockResolvedValue({ ok: true, toolCount: 3 })
|
||||
const res = await app.request('/mcp/servers/server1/test', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ ok: true, toolCount: 3 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('MCP OAuth callback route', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
test('completes a valid callback and renders an HTML page', async () => {
|
||||
vi.mocked(mcpService.handleOauthCallback).mockResolvedValue({ ok: true })
|
||||
const res = await mcpOauthCallbackRoute.request(
|
||||
'/mcp/oauth/callback?code=abc&state=xyz&iss=https%3A%2F%2Fissuer.example.com',
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toContain('text/html')
|
||||
expect(mcpService.handleOauthCallback).toHaveBeenCalledWith(
|
||||
'abc',
|
||||
'xyz',
|
||||
'https://issuer.example.com',
|
||||
)
|
||||
const body = await res.text()
|
||||
expect(body).toContain('postMessage')
|
||||
expect(body).toContain('"ok":true')
|
||||
})
|
||||
|
||||
test('rejects a callback missing code or state', async () => {
|
||||
const res = await mcpOauthCallbackRoute.request('/mcp/oauth/callback?code=abc')
|
||||
expect(res.status).toBe(400)
|
||||
expect(mcpService.handleOauthCallback).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('surfaces callback failures in the HTML page', async () => {
|
||||
vi.mocked(mcpService.handleOauthCallback).mockResolvedValue({
|
||||
ok: false,
|
||||
message: 'Invalid or expired OAuth state',
|
||||
})
|
||||
const res = await mcpOauthCallbackRoute.request('/mcp/oauth/callback?code=abc&state=bad')
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.text()
|
||||
expect(body).toContain('"ok":false')
|
||||
expect(body).toContain('Invalid or expired OAuth state')
|
||||
})
|
||||
|
||||
test('accepts POST callbacks (form-encoded)', async () => {
|
||||
vi.mocked(mcpService.handleOauthCallback).mockResolvedValue({ ok: true })
|
||||
const res = await mcpOauthCallbackRoute.request('/mcp/oauth/callback', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: 'code=abc&state=xyz',
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(mcpService.handleOauthCallback).toHaveBeenCalledWith('abc', 'xyz', undefined)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,356 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { mcpService } from '@shumai/core/src/mcp/mcp-service'
|
||||
import {
|
||||
createMcpServerRequestSchema,
|
||||
updateMcpServerRequestSchema,
|
||||
updateMcpServerPermissionRequestSchema,
|
||||
mcpAuthCompleteRequestSchema,
|
||||
AuditAction,
|
||||
} from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/mcp/servers', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const servers = await mcpService.listServers(teamId)
|
||||
return c.json({ servers })
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/mcp/servers',
|
||||
zValidator('json', createMcpServerRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const server = await mcpService.createServer(teamId, req)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.mcp_server_create,
|
||||
teamId,
|
||||
userId: user?.id,
|
||||
itemId: server.id,
|
||||
})
|
||||
|
||||
return c.json(server)
|
||||
},
|
||||
)
|
||||
.get('/mcp/servers/:id', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
const server = await mcpService.getServer(id)
|
||||
if (!server) return c.json({ error: 'MCP server not found' }, 404)
|
||||
return c.json(server)
|
||||
})
|
||||
.patch('/mcp/servers/:id', zValidator('json', updateMcpServerRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
const existing = await mcpService.getServerRecord(id)
|
||||
if (!existing) return c.json({ error: 'MCP server not found' }, 404)
|
||||
|
||||
const server = await mcpService.updateServer(id, req)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.mcp_server_update,
|
||||
teamId: existing.teamId,
|
||||
userId: user?.id,
|
||||
itemId: id,
|
||||
})
|
||||
|
||||
return c.json(server)
|
||||
})
|
||||
.patch(
|
||||
'/mcp/servers/:id/permission',
|
||||
zValidator('json', updateMcpServerPermissionRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
const existing = await mcpService.getServerRecord(id)
|
||||
if (!existing) return c.json({ error: 'MCP server not found' }, 404)
|
||||
|
||||
const server = await mcpService.updateServerPermission(id, req.permission)
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.mcp_server_update,
|
||||
teamId: existing.teamId,
|
||||
userId: user?.id,
|
||||
itemId: id,
|
||||
})
|
||||
|
||||
return c.json(server)
|
||||
},
|
||||
)
|
||||
.delete('/mcp/servers/:id', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
const existing = await mcpService.getServerRecord(id)
|
||||
|
||||
await mcpService.deleteServer(id)
|
||||
|
||||
if (existing) {
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.mcp_server_delete,
|
||||
teamId: existing.teamId,
|
||||
userId: user?.id,
|
||||
itemId: id,
|
||||
})
|
||||
}
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.post('/mcp/servers/:id/refresh', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
try {
|
||||
const server = await mcpService.refreshServer(id)
|
||||
return c.json(server)
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
return c.json({ error: message }, 502)
|
||||
}
|
||||
})
|
||||
.get('/mcp/servers/:id/tools', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
const server = await mcpService.getServer(id)
|
||||
if (!server) return c.json({ error: 'MCP server not found' }, 404)
|
||||
const record = await mcpService.getServerRecord(id)
|
||||
return c.json({ tools: record?.tools ?? [] })
|
||||
})
|
||||
.post('/mcp/servers/:id/auth/start', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
try {
|
||||
const result = await mcpService.startAuth(id)
|
||||
if (result.alreadyAuthenticated) {
|
||||
return c.json({ status: 'authenticated' })
|
||||
}
|
||||
return c.json({ authorizationUrl: result.authorizationUrl, status: 'in_progress' })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
return c.json({ error: message }, 502)
|
||||
}
|
||||
})
|
||||
.post(
|
||||
'/mcp/servers/:id/auth/complete',
|
||||
zValidator('json', mcpAuthCompleteRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
try {
|
||||
const status = await mcpService.completeAuth(id, { code: req.code, iss: req.iss })
|
||||
return c.json({ status })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
return c.json({ error: message }, 502)
|
||||
}
|
||||
},
|
||||
)
|
||||
.get('/mcp/servers/:id/auth/status', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
try {
|
||||
const status = await mcpService.getAuthStatus(id)
|
||||
return c.json({ status })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
return c.json({ error: message }, 404)
|
||||
}
|
||||
})
|
||||
.delete('/mcp/servers/:id/auth', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
await mcpService.removeAuth(id)
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.post('/mcp/servers/:id/test', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.McpServer,
|
||||
id,
|
||||
})
|
||||
|
||||
const result = await mcpService.testServer(id)
|
||||
return c.json(result)
|
||||
})
|
||||
|
||||
export default route
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public OAuth callback route (mounted BEFORE authMiddleware in index.ts).
|
||||
// The OAuth provider redirects the user's browser here after approval.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function renderCallbackPage(payload: { ok: boolean; message?: string }): string {
|
||||
const escaped = JSON.stringify(payload).replace(/</g, '\\u003c')
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>MCP OAuth</title>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
(function () {
|
||||
var payload = ${escaped};
|
||||
try {
|
||||
if (window.opener) {
|
||||
window.opener.postMessage({ source: 'shumai-mcp-oauth', payload: payload }, '*');
|
||||
}
|
||||
} catch (e) {
|
||||
/* ignore cross-origin postMessage failures */
|
||||
}
|
||||
setTimeout(function () {
|
||||
window.close();
|
||||
document.body.textContent = payload.ok ? 'Authentication complete. You can close this window.' : 'Authentication failed: ' + (payload.message || 'unknown error');
|
||||
}, 300);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>`
|
||||
}
|
||||
|
||||
export const mcpOauthCallbackRoute = new Hono()
|
||||
.get('/mcp/oauth/callback', async (c) => {
|
||||
const code = c.req.query('code')
|
||||
const state = c.req.query('state')
|
||||
const iss = c.req.query('iss') || undefined
|
||||
|
||||
if (!code || !state) {
|
||||
return c.html(
|
||||
renderCallbackPage({ ok: false, message: 'Missing code or state parameter' }),
|
||||
400,
|
||||
)
|
||||
}
|
||||
|
||||
const result = await mcpService.handleOauthCallback(code, state, iss)
|
||||
return c.html(
|
||||
renderCallbackPage(result.ok ? { ok: true } : { ok: false, message: result.message }),
|
||||
)
|
||||
})
|
||||
.post('/mcp/oauth/callback', async (c) => {
|
||||
const body = await c.req.parseBody()
|
||||
const code = typeof body['code'] === 'string' ? body['code'] : undefined
|
||||
const state = typeof body['state'] === 'string' ? body['state'] : undefined
|
||||
const iss = typeof body['iss'] === 'string' ? body['iss'] : undefined
|
||||
|
||||
if (!code || !state) {
|
||||
return c.html(
|
||||
renderCallbackPage({ ok: false, message: 'Missing code or state parameter' }),
|
||||
400,
|
||||
)
|
||||
}
|
||||
|
||||
const result = await mcpService.handleOauthCallback(code, state, iss)
|
||||
return c.html(
|
||||
renderCallbackPage(result.ok ? { ok: true } : { ok: false, message: result.message }),
|
||||
)
|
||||
})
|
||||
@@ -8,6 +8,7 @@
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@earendil-works/pi-ai": "0.82.1",
|
||||
"@modelcontextprotocol/client": "2.0.0",
|
||||
"@shumai/db": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@sinclair/typebox": "0.34.49",
|
||||
@@ -24,11 +25,13 @@
|
||||
"pino": "10.3.1",
|
||||
"sharp": "0.34.5",
|
||||
"tweetnacl": "1.0.3",
|
||||
"typebox": "1.1.38",
|
||||
"ulid": "3.0.2",
|
||||
"yaml": "2.9.0",
|
||||
"zod": "4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/server": "2.0.0",
|
||||
"@types/adm-zip": "0.5.8",
|
||||
"@types/extract-zip": "2.0.3",
|
||||
"@types/pdfkit": "0.17.6"
|
||||
|
||||
@@ -121,6 +121,7 @@ export class AgentService {
|
||||
systemPrompt,
|
||||
soul,
|
||||
skills,
|
||||
mcpServerIds,
|
||||
deniedTools,
|
||||
} = params
|
||||
|
||||
@@ -189,6 +190,12 @@ export class AgentService {
|
||||
skillId,
|
||||
})) || [],
|
||||
},
|
||||
mcpServers: {
|
||||
create:
|
||||
mcpServerIds?.map((mcpServerId) => ({
|
||||
mcpServerId,
|
||||
})) || [],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -202,7 +209,11 @@ export class AgentService {
|
||||
|
||||
return tx.agent.findUnique({
|
||||
where: { id: agent.id },
|
||||
include: { user: true, skills: { include: { skill: true } } },
|
||||
include: {
|
||||
user: true,
|
||||
skills: { include: { skill: true } },
|
||||
mcpServers: { include: { mcpServer: true } },
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -220,6 +231,7 @@ export class AgentService {
|
||||
systemPrompt,
|
||||
soul,
|
||||
skills,
|
||||
mcpServerIds,
|
||||
deniedTools,
|
||||
} = params
|
||||
|
||||
@@ -278,6 +290,11 @@ export class AgentService {
|
||||
where: { agentId },
|
||||
})
|
||||
|
||||
// Update MCP server assignments: easier to delete all and recreate
|
||||
await tx.agentMcpServer.deleteMany({
|
||||
where: { agentId },
|
||||
})
|
||||
|
||||
return tx.agent.update({
|
||||
where: { id: agentId },
|
||||
data: {
|
||||
@@ -294,8 +311,18 @@ export class AgentService {
|
||||
skillId,
|
||||
})) || [],
|
||||
},
|
||||
mcpServers: {
|
||||
create:
|
||||
mcpServerIds?.map((mcpServerId) => ({
|
||||
mcpServerId,
|
||||
})) || [],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
skills: { include: { skill: true } },
|
||||
mcpServers: { include: { mcpServer: true } },
|
||||
},
|
||||
include: { user: true, skills: { include: { skill: true } } },
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -338,6 +365,7 @@ export class AgentService {
|
||||
skill: true,
|
||||
},
|
||||
},
|
||||
mcpServers: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ export enum ResourceType {
|
||||
MetadataField = 'metadataField',
|
||||
Skill = 'skill',
|
||||
Provider = 'provider',
|
||||
McpServer = 'mcpServer',
|
||||
Invite = 'invite',
|
||||
Comment = 'comment',
|
||||
AgentSession = 'agentSession',
|
||||
@@ -187,6 +188,15 @@ export class AuthzService {
|
||||
return { teamId: skill.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.McpServer: {
|
||||
const server = await prisma.mcpServer.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!server) throw new HTTPException(404, { message: 'MCP server not found' })
|
||||
return { teamId: server.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.Provider: {
|
||||
const provider = await prisma.provider.findUnique({
|
||||
where: { id },
|
||||
|
||||
@@ -25,3 +25,4 @@ export * from './chat/chat'
|
||||
export * from './ai-usage/ai-usage'
|
||||
export * from './watermark/watermark'
|
||||
export * from './gotenberg/gotenberg'
|
||||
export * from './mcp/mcp-service'
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import { describe, it, expect, beforeAll } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { McpDbStore } from './mcp-db-store'
|
||||
|
||||
describe('McpDbStore', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let store: McpDbStore
|
||||
let serverId: string
|
||||
|
||||
beforeAll(async () => {
|
||||
store = new McpDbStore()
|
||||
const team = await prisma.team.create({ data: { name: 'MCP DB Store Team' } })
|
||||
const server = await prisma.mcpServer.create({
|
||||
data: {
|
||||
name: 'github',
|
||||
url: 'https://mcp.example.com/github',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
serverId = server.id
|
||||
})
|
||||
|
||||
it('returns undefined when no credentials exist', async () => {
|
||||
expect(await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')).toBeUndefined()
|
||||
expect(await store.hasStoredTokens(serverId)).toBe(false)
|
||||
expect(await store.isTokenExpired(serverId)).toBeNull()
|
||||
})
|
||||
|
||||
it('saves and reads tokens bound to the URL', async () => {
|
||||
await store.updateTokens(
|
||||
serverId,
|
||||
{ accessToken: 'tok-1', refreshToken: 'ref-1' },
|
||||
'https://mcp.example.com/github',
|
||||
)
|
||||
const entry = await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')
|
||||
expect(entry?.tokens?.accessToken).toBe('tok-1')
|
||||
expect(entry?.tokens?.refreshToken).toBe('ref-1')
|
||||
expect(await store.hasStoredTokens(serverId)).toBe(true)
|
||||
})
|
||||
|
||||
it('invalidates credentials when the URL changes', async () => {
|
||||
expect(await store.getAuthForUrl(serverId, 'https://other.example.com')).toBeUndefined()
|
||||
expect(await store.hasStoredTokens(serverId)).toBe(false)
|
||||
})
|
||||
|
||||
it('saves and clears client info', async () => {
|
||||
await store.updateClientInfo(
|
||||
serverId,
|
||||
{ clientId: 'client-1', clientSecret: 'secret-1' },
|
||||
'https://mcp.example.com/github',
|
||||
)
|
||||
let entry = await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')
|
||||
expect(entry?.clientInfo?.clientId).toBe('client-1')
|
||||
|
||||
await store.clearClientInfo(serverId)
|
||||
entry = await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')
|
||||
expect(entry?.clientInfo).toBeUndefined()
|
||||
})
|
||||
|
||||
it('saves/clears the PKCE code verifier', async () => {
|
||||
await store.updateCodeVerifier(serverId, 'verifier-abc', 'https://mcp.example.com/github')
|
||||
let entry = await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')
|
||||
expect(entry?.codeVerifier).toBe('verifier-abc')
|
||||
|
||||
await store.clearCodeVerifier(serverId)
|
||||
entry = await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')
|
||||
expect(entry?.codeVerifier).toBeUndefined()
|
||||
})
|
||||
|
||||
it('saves/clears the CSRF state', async () => {
|
||||
await store.updateOauthState(serverId, 'state-xyz', 'https://mcp.example.com/github')
|
||||
expect(await store.getOauthState(serverId)).toBe('state-xyz')
|
||||
|
||||
await store.clearOauthState(serverId)
|
||||
expect(await store.getOauthState(serverId)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('detects expired tokens', async () => {
|
||||
await store.updateTokens(
|
||||
serverId,
|
||||
{ accessToken: 'tok-expired', expiresAt: Math.floor(Date.now() / 1000) - 10 },
|
||||
'https://mcp.example.com/github',
|
||||
)
|
||||
expect(await store.isTokenExpired(serverId)).toBe(true)
|
||||
|
||||
await store.updateTokens(
|
||||
serverId,
|
||||
{ accessToken: 'tok-valid', expiresAt: Math.floor(Date.now() / 1000) + 3600 },
|
||||
'https://mcp.example.com/github',
|
||||
)
|
||||
expect(await store.isTokenExpired(serverId)).toBe(false)
|
||||
})
|
||||
|
||||
it('treats tokens without an expiry as never-expiring', async () => {
|
||||
await store.updateTokens(
|
||||
serverId,
|
||||
{ accessToken: 'tok-no-expiry' },
|
||||
'https://mcp.example.com/github',
|
||||
)
|
||||
expect(await store.isTokenExpired(serverId)).toBe(false)
|
||||
})
|
||||
|
||||
it('clears tokens only', async () => {
|
||||
await store.updateTokens(serverId, { accessToken: 'tok-x' }, 'https://mcp.example.com/github')
|
||||
await store.clearTokens(serverId)
|
||||
expect(await store.hasStoredTokens(serverId)).toBe(false)
|
||||
})
|
||||
|
||||
it('clears all credentials', async () => {
|
||||
await store.updateTokens(serverId, { accessToken: 'tok-y' }, 'https://mcp.example.com/github')
|
||||
await store.updateClientInfo(serverId, { clientId: 'c' }, 'https://mcp.example.com/github')
|
||||
await store.clearAllCredentials(serverId)
|
||||
expect(await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('persists an in-flight pendingAuth with a TTL and expires it', async () => {
|
||||
const ttl = await store.getPendingAuthTtlSeconds()
|
||||
await store.savePendingAuth(serverId, {
|
||||
state: 'pending-state',
|
||||
authorizationUrl: 'https://auth.example.com/authorize?state=pending-state',
|
||||
discovery: { scope: 'read' },
|
||||
expiresAt: Math.floor(Date.now() / 1000) + ttl,
|
||||
})
|
||||
const pending = await store.getPendingAuth(serverId)
|
||||
expect(pending?.state).toBe('pending-state')
|
||||
expect(pending?.authorizationUrl).toContain('pending-state')
|
||||
|
||||
// Expired pendingAuth is cleared on read.
|
||||
await store.savePendingAuth(serverId, {
|
||||
state: 'stale',
|
||||
authorizationUrl: 'https://auth.example.com/authorize',
|
||||
discovery: {},
|
||||
expiresAt: Math.floor(Date.now() / 1000) - 10,
|
||||
})
|
||||
expect(await store.getPendingAuth(serverId)).toBeUndefined()
|
||||
|
||||
await store.clearPendingAuth(serverId)
|
||||
expect(await store.getPendingAuth(serverId)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('savePendingAuth does not clobber an in-flight discovery snapshot', async () => {
|
||||
// Simulates the SDK flow: the provider's saveDiscoveryState() stores a
|
||||
// snapshot inside the pendingAuth column, then startAuth() calls
|
||||
// savePendingAuth(). The snapshot MUST survive so the callback leg can
|
||||
// satisfy the SEP-2352 issuer check.
|
||||
await store.saveDiscoverySnapshot(serverId, 'https://mcp.example.com/github', {
|
||||
authorizationServerUrl: 'https://kling.ai/auth',
|
||||
authorizationServerMetadata: { issuer: 'https://kling.ai/auth' },
|
||||
})
|
||||
|
||||
await store.savePendingAuth(serverId, {
|
||||
state: 'state-abc',
|
||||
authorizationUrl: 'https://kling.ai/authorize',
|
||||
discovery: {},
|
||||
expiresAt: Math.floor(Date.now() / 1000) + 300,
|
||||
})
|
||||
|
||||
const snapshot = await store.getDiscoverySnapshot(serverId)
|
||||
expect(snapshot).toBeDefined()
|
||||
expect(snapshot?.['authorizationServerUrl']).toBe('https://kling.ai/auth')
|
||||
|
||||
const pending = await store.getPendingAuth(serverId)
|
||||
expect(pending?.state).toBe('state-abc')
|
||||
})
|
||||
|
||||
it('persists and clears the discovery snapshot', async () => {
|
||||
await store.saveDiscoverySnapshot(serverId, 'https://mcp.example.com/github', {
|
||||
authorizationServerUrl: 'https://issuer.example.com',
|
||||
})
|
||||
const snapshot = await store.getDiscoverySnapshot(serverId)
|
||||
expect(snapshot?.authorizationServerUrl).toBe('https://issuer.example.com')
|
||||
|
||||
await store.clearDiscoverySnapshot(serverId)
|
||||
expect(await store.getDiscoverySnapshot(serverId)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('deletes the credential row when the server is deleted (cascade)', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Cascade Team' } })
|
||||
const server = await prisma.mcpServer.create({
|
||||
data: { name: 'cascade-srv', url: 'https://mcp.example.com/cascade', teamId: team.id },
|
||||
})
|
||||
await store.updateTokens(
|
||||
server.id,
|
||||
{ accessToken: 'tok-cascade' },
|
||||
'https://mcp.example.com/cascade',
|
||||
)
|
||||
await prisma.mcpServer.delete({ where: { id: server.id } })
|
||||
const leftover = await prisma.mcpServerCredential.findUnique({ where: { serverId: server.id } })
|
||||
expect(leftover).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,388 @@
|
||||
import { prisma, Prisma } from '@shumai/db'
|
||||
|
||||
export interface StoredTokens {
|
||||
accessToken: string
|
||||
refreshToken?: string
|
||||
expiresAt?: number // Unix timestamp in seconds
|
||||
scope?: string
|
||||
/** SEP-2352 authorization-server issuer binding */
|
||||
issuer?: string
|
||||
}
|
||||
|
||||
export interface StoredClientInfo {
|
||||
clientId: string
|
||||
clientSecret?: string
|
||||
clientIdIssuedAt?: number
|
||||
clientSecretExpiresAt?: number
|
||||
redirectUris?: string[]
|
||||
issuer?: string
|
||||
configPreRegistered?: boolean
|
||||
}
|
||||
|
||||
export interface AuthEntry {
|
||||
tokens?: StoredTokens
|
||||
clientInfo?: StoredClientInfo
|
||||
codeVerifier?: string
|
||||
oauthState?: string
|
||||
serverUrl?: string // Track the URL these credentials are for
|
||||
}
|
||||
|
||||
export interface PendingAuth {
|
||||
state: string
|
||||
authorizationUrl: string
|
||||
discovery: Record<string, unknown>
|
||||
expiresAt: number // Unix timestamp in seconds
|
||||
grantType?: 'authorization_code' | 'client_credentials'
|
||||
redirectUri?: string
|
||||
}
|
||||
|
||||
/** How long an in-flight authorization_code flow is kept in the DB (5 minutes). */
|
||||
const PENDING_AUTH_TTL_SECONDS = 5 * 60
|
||||
|
||||
function rowToAuthEntry(row: {
|
||||
serverUrl: string
|
||||
tokens: unknown
|
||||
clientInfo: unknown
|
||||
codeVerifier: string | null
|
||||
oauthState: string | null
|
||||
pendingAuth: unknown
|
||||
}): {
|
||||
entry: AuthEntry
|
||||
pendingAuth?: PendingAuth
|
||||
} {
|
||||
const entry: AuthEntry = {
|
||||
serverUrl: row.serverUrl,
|
||||
...(row.tokens ? { tokens: row.tokens as StoredTokens } : {}),
|
||||
...(row.clientInfo ? { clientInfo: row.clientInfo as StoredClientInfo } : {}),
|
||||
...(row.codeVerifier ? { codeVerifier: row.codeVerifier } : {}),
|
||||
...(row.oauthState ? { oauthState: row.oauthState } : {}),
|
||||
}
|
||||
let pendingAuth: PendingAuth | undefined
|
||||
if (row.pendingAuth && typeof row.pendingAuth === 'object') {
|
||||
const raw = row.pendingAuth as Partial<PendingAuth>
|
||||
if (typeof raw.state === 'string' && typeof raw.expiresAt === 'number') {
|
||||
pendingAuth = {
|
||||
state: raw.state,
|
||||
authorizationUrl: raw.authorizationUrl ?? '',
|
||||
discovery: raw.discovery ?? {},
|
||||
expiresAt: raw.expiresAt,
|
||||
...(raw.grantType ? { grantType: raw.grantType } : {}),
|
||||
...(raw.redirectUri ? { redirectUri: raw.redirectUri } : {}),
|
||||
}
|
||||
}
|
||||
}
|
||||
return { entry, pendingAuth }
|
||||
}
|
||||
|
||||
/**
|
||||
* DB-backed credential store for MCP OAuth state (port of pi-mcp-adapter's
|
||||
* mcp-auth.ts storage layer, replacing the OS keyring/files with an
|
||||
* `McpServerCredential` row per server).
|
||||
*/
|
||||
export class McpDbStore {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
|
||||
private async getRow(serverId: string) {
|
||||
return this.prismaClient.mcpServerCredential.findUnique({
|
||||
where: { serverId },
|
||||
})
|
||||
}
|
||||
|
||||
private async ensureRow(serverId: string, serverUrl?: string) {
|
||||
const existing = await this.getRow(serverId)
|
||||
if (existing) return existing
|
||||
if (!serverUrl) throw new Error(`No credential row for MCP server ${serverId}`)
|
||||
return this.prismaClient.mcpServerCredential.create({
|
||||
data: {
|
||||
serverId,
|
||||
serverUrl,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the auth entry for a server, validated against the current URL.
|
||||
* Returns undefined when no entry exists or the URL changed (credentials invalid).
|
||||
*/
|
||||
async getAuthForUrl(serverId: string, serverUrl: string): Promise<AuthEntry | undefined> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) return undefined
|
||||
// If no serverUrl is stored or it changed, credentials are invalid.
|
||||
if (!row.serverUrl || row.serverUrl !== serverUrl) return undefined
|
||||
return rowToAuthEntry(row).entry
|
||||
}
|
||||
|
||||
async getAuthEntry(serverId: string): Promise<AuthEntry | undefined> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) return undefined
|
||||
return rowToAuthEntry(row).entry
|
||||
}
|
||||
|
||||
async saveAuthEntry(serverId: string, entry: AuthEntry, serverUrl?: string): Promise<void> {
|
||||
const row = await this.getRow(serverId)
|
||||
const serverUrlValue = serverUrl ?? entry.serverUrl ?? row?.serverUrl
|
||||
// Do NOT merge the row's credential fields back in: callers build `entry`
|
||||
// from getAuthEntry() (all current fields) and delete fields to clear
|
||||
// them. Re-adding row fields would leak cleared values.
|
||||
const merged: AuthEntry = { ...entry }
|
||||
if (serverUrlValue) {
|
||||
merged.serverUrl = serverUrlValue
|
||||
if (row && serverUrlValue !== row.serverUrl) {
|
||||
// URL changed: stale sub-credentials are dropped.
|
||||
delete merged.tokens
|
||||
delete merged.clientInfo
|
||||
delete merged.codeVerifier
|
||||
delete merged.oauthState
|
||||
}
|
||||
}
|
||||
const data = {
|
||||
serverUrl: merged.serverUrl ?? serverUrlValue ?? '',
|
||||
tokens: merged.tokens ?? undefined,
|
||||
clientInfo: merged.clientInfo ?? undefined,
|
||||
codeVerifier: merged.codeVerifier ?? undefined,
|
||||
oauthState: merged.oauthState ?? undefined,
|
||||
}
|
||||
if (row) {
|
||||
await this.prismaClient.mcpServerCredential.update({
|
||||
where: { serverId },
|
||||
data: {
|
||||
serverUrl: data.serverUrl,
|
||||
tokens:
|
||||
data.tokens === undefined
|
||||
? Prisma.JsonNull
|
||||
: (data.tokens as PrismaJson.McpStoredTokens),
|
||||
clientInfo:
|
||||
data.clientInfo === undefined
|
||||
? Prisma.JsonNull
|
||||
: (data.clientInfo as PrismaJson.McpStoredClientInfo),
|
||||
codeVerifier: data.codeVerifier ?? null,
|
||||
oauthState: data.oauthState ?? null,
|
||||
},
|
||||
})
|
||||
} else if (serverUrlValue) {
|
||||
await this.prismaClient.mcpServerCredential.create({
|
||||
data: {
|
||||
serverId,
|
||||
serverUrl: serverUrlValue,
|
||||
tokens: data.tokens as PrismaJson.McpStoredTokens | undefined,
|
||||
clientInfo: data.clientInfo as PrismaJson.McpStoredClientInfo | undefined,
|
||||
codeVerifier: data.codeVerifier,
|
||||
oauthState: data.oauthState,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async updateTokens(serverId: string, tokens: StoredTokens, serverUrl?: string): Promise<void> {
|
||||
const entry = (await this.getAuthEntry(serverId)) ?? {}
|
||||
if (serverUrl && entry.serverUrl && entry.serverUrl !== serverUrl) {
|
||||
delete entry.clientInfo
|
||||
delete entry.codeVerifier
|
||||
delete entry.oauthState
|
||||
}
|
||||
entry.tokens = tokens
|
||||
await this.saveAuthEntry(serverId, entry, serverUrl)
|
||||
}
|
||||
|
||||
async updateClientInfo(
|
||||
serverId: string,
|
||||
clientInfo: StoredClientInfo,
|
||||
serverUrl?: string,
|
||||
): Promise<void> {
|
||||
const entry = (await this.getAuthEntry(serverId)) ?? {}
|
||||
if (serverUrl && entry.serverUrl && entry.serverUrl !== serverUrl) {
|
||||
delete entry.tokens
|
||||
delete entry.codeVerifier
|
||||
delete entry.oauthState
|
||||
}
|
||||
entry.clientInfo = clientInfo
|
||||
await this.saveAuthEntry(serverId, entry, serverUrl)
|
||||
}
|
||||
|
||||
async updateCodeVerifier(
|
||||
serverId: string,
|
||||
codeVerifier: string,
|
||||
serverUrl?: string,
|
||||
): Promise<void> {
|
||||
const entry = (await this.getAuthEntry(serverId)) ?? {}
|
||||
if (serverUrl && entry.serverUrl && entry.serverUrl !== serverUrl) {
|
||||
delete entry.tokens
|
||||
delete entry.clientInfo
|
||||
delete entry.oauthState
|
||||
}
|
||||
entry.codeVerifier = codeVerifier
|
||||
await this.saveAuthEntry(serverId, entry, serverUrl)
|
||||
}
|
||||
|
||||
async clearCodeVerifier(serverId: string): Promise<void> {
|
||||
const entry = await this.getAuthEntry(serverId)
|
||||
if (entry) {
|
||||
delete entry.codeVerifier
|
||||
await this.saveAuthEntry(serverId, entry)
|
||||
}
|
||||
}
|
||||
|
||||
async updateOauthState(serverId: string, state: string, serverUrl?: string): Promise<void> {
|
||||
const entry = (await this.getAuthEntry(serverId)) ?? {}
|
||||
if (serverUrl && entry.serverUrl && entry.serverUrl !== serverUrl) {
|
||||
delete entry.tokens
|
||||
delete entry.clientInfo
|
||||
delete entry.codeVerifier
|
||||
}
|
||||
entry.oauthState = state
|
||||
await this.saveAuthEntry(serverId, entry, serverUrl)
|
||||
}
|
||||
|
||||
async getOauthState(serverId: string): Promise<string | undefined> {
|
||||
const row = await this.getRow(serverId)
|
||||
return row?.oauthState ?? undefined
|
||||
}
|
||||
|
||||
async clearOauthState(serverId: string): Promise<void> {
|
||||
const entry = await this.getAuthEntry(serverId)
|
||||
if (entry) {
|
||||
delete entry.oauthState
|
||||
await this.saveAuthEntry(serverId, entry)
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns null when no tokens exist, false when valid, true when expired. */
|
||||
async isTokenExpired(serverId: string): Promise<boolean | null> {
|
||||
const row = await this.getRow(serverId)
|
||||
const tokens = row?.tokens as StoredTokens | null | undefined
|
||||
if (!tokens?.accessToken) return null
|
||||
if (!tokens.expiresAt) return false
|
||||
return tokens.expiresAt < Date.now() / 1000
|
||||
}
|
||||
|
||||
async hasStoredTokens(serverId: string): Promise<boolean> {
|
||||
const row = await this.getRow(serverId)
|
||||
const tokens = row?.tokens as StoredTokens | null | undefined
|
||||
return !!tokens?.accessToken
|
||||
}
|
||||
|
||||
async clearAllCredentials(serverId: string): Promise<void> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) return
|
||||
await this.prismaClient.mcpServerCredential.delete({ where: { serverId } })
|
||||
}
|
||||
|
||||
async clearClientInfo(serverId: string): Promise<void> {
|
||||
const entry = await this.getAuthEntry(serverId)
|
||||
if (entry) {
|
||||
delete entry.clientInfo
|
||||
await this.saveAuthEntry(serverId, entry)
|
||||
}
|
||||
}
|
||||
|
||||
async clearTokens(serverId: string): Promise<void> {
|
||||
const entry = await this.getAuthEntry(serverId)
|
||||
if (entry) {
|
||||
delete entry.tokens
|
||||
await this.saveAuthEntry(serverId, entry)
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// In-flight authorization_code flow (pendingAuth)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
async savePendingAuth(serverId: string, pending: PendingAuth): Promise<void> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) {
|
||||
const server = await this.prismaClient.mcpServer.findUnique({
|
||||
where: { id: serverId },
|
||||
select: { url: true },
|
||||
})
|
||||
if (!server) throw new Error(`MCP server ${serverId} not found`)
|
||||
await this.ensureRow(serverId, server.url)
|
||||
}
|
||||
// Preserve an in-flight discovery snapshot: the OAuth provider's
|
||||
// saveDiscoveryState() lives in the same JSON column, and the callback
|
||||
// leg needs it for the SEP-2352 issuer check.
|
||||
const existing = (row?.pendingAuth as Record<string, unknown> | null | undefined) ?? {}
|
||||
const discoverySnapshot = existing['discoverySnapshot']
|
||||
const data = discoverySnapshot !== undefined ? { ...pending, discoverySnapshot } : pending
|
||||
await this.prismaClient.mcpServerCredential.update({
|
||||
where: { serverId },
|
||||
data: { pendingAuth: data as unknown as PrismaJson.McpPendingAuth },
|
||||
})
|
||||
}
|
||||
|
||||
async getPendingAuth(serverId: string): Promise<PendingAuth | undefined> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) return undefined
|
||||
const { pendingAuth } = rowToAuthEntry(row)
|
||||
if (!pendingAuth) return undefined
|
||||
if (pendingAuth.expiresAt < Date.now() / 1000) {
|
||||
await this.clearPendingAuth(serverId)
|
||||
return undefined
|
||||
}
|
||||
return pendingAuth
|
||||
}
|
||||
|
||||
async clearPendingAuth(serverId: string): Promise<void> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) return
|
||||
await this.prismaClient.mcpServerCredential.update({
|
||||
where: { serverId },
|
||||
data: { pendingAuth: Prisma.JsonNull },
|
||||
})
|
||||
}
|
||||
|
||||
async getPendingAuthTtlSeconds(): Promise<number> {
|
||||
return PENDING_AUTH_TTL_SECONDS
|
||||
}
|
||||
|
||||
/** Ensure a credential row exists for a server (used when persisting any auth state). */
|
||||
async ensureCredentialRow(serverId: string, serverUrl: string): Promise<void> {
|
||||
await this.ensureRow(serverId, serverUrl)
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Discovery snapshot (survives from startAuth to the callback leg)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
async saveDiscoverySnapshot(serverId: string, serverUrl: string, state: unknown): Promise<void> {
|
||||
await this.ensureRow(serverId, serverUrl)
|
||||
const row = await this.getRow(serverId)
|
||||
const existing = (row?.pendingAuth as Record<string, unknown> | null | undefined) ?? {}
|
||||
await this.prismaClient.mcpServerCredential.update({
|
||||
where: { serverId },
|
||||
data: {
|
||||
pendingAuth: {
|
||||
...existing,
|
||||
discoverySnapshot: state,
|
||||
} as unknown as PrismaJson.McpPendingAuth,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async getDiscoverySnapshot(serverId: string): Promise<Record<string, unknown> | undefined> {
|
||||
const row = await this.getRow(serverId)
|
||||
const pending = (row?.pendingAuth as Record<string, unknown> | null | undefined) ?? {}
|
||||
const snapshot = pending['discoverySnapshot']
|
||||
return snapshot && typeof snapshot === 'object'
|
||||
? (snapshot as Record<string, unknown>)
|
||||
: undefined
|
||||
}
|
||||
|
||||
async clearDiscoverySnapshot(serverId: string): Promise<void> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) return
|
||||
const pending = (row.pendingAuth as Record<string, unknown> | null | undefined) ?? {}
|
||||
const rest: Record<string, unknown> = { ...pending }
|
||||
delete rest['discoverySnapshot']
|
||||
await this.prismaClient.mcpServerCredential.update({
|
||||
where: { serverId },
|
||||
data: {
|
||||
pendingAuth:
|
||||
Object.keys(rest).length > 0
|
||||
? (rest as unknown as PrismaJson.McpPendingAuth)
|
||||
: Prisma.JsonNull,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const mcpDbStore = new McpDbStore()
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Direct MCP tools — per-server opt-in registration.
|
||||
*
|
||||
* When a server's config sets `directTools: true`, its allowed tools (after
|
||||
* excludeTools filters) are registered as native AgentTools with prefixed
|
||||
* names `{server}_{tool}`. The `mcp` proxy tool stays registered for
|
||||
* discovery/auth/status and for servers not in direct mode.
|
||||
*/
|
||||
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import type { ToolMetadata } from './mcp-tool-registry'
|
||||
import { toToolParameters } from './mcp-tool-schema'
|
||||
|
||||
export interface DirectToolCallOptions {
|
||||
serverId: string
|
||||
serverName: string
|
||||
callTool(
|
||||
serverId: string,
|
||||
toolName: string,
|
||||
args: Record<string, unknown>,
|
||||
): Promise<{
|
||||
ok: boolean
|
||||
content: AgentToolResult<Record<string, unknown>>['content']
|
||||
}>
|
||||
}
|
||||
|
||||
function globToRegExp(pattern: string): RegExp {
|
||||
const escaped = pattern
|
||||
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
||||
.replace(/\*/g, '.*')
|
||||
.replace(/\?/g, '.')
|
||||
return new RegExp(`^${escaped}$`)
|
||||
}
|
||||
|
||||
function matchesToolPattern(name: string, patterns?: string[]): boolean {
|
||||
if (!Array.isArray(patterns) || patterns.length === 0) return false
|
||||
for (const pattern of patterns) {
|
||||
if (!pattern) continue
|
||||
if (!pattern.includes('*') && !pattern.includes('?') && name === pattern) return true
|
||||
if ((pattern.includes('*') || pattern.includes('?')) && globToRegExp(pattern).test(name)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Decide whether a tool is allowed by excludeTools (matches prefixed or original name). */
|
||||
export function isToolAllowed(
|
||||
prefixedName: string,
|
||||
originalName: string,
|
||||
config?: PrismaJson.McpServerConfig,
|
||||
): boolean {
|
||||
const exclude = config?.excludeTools
|
||||
if (matchesToolPattern(prefixedName, exclude) || matchesToolPattern(originalName, exclude)) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Build direct AgentTools for a server in direct-tools mode.
|
||||
* Returns [] when directTools is not enabled or no tools pass the filters.
|
||||
*/
|
||||
export function buildDirectTools(
|
||||
metadata: ToolMetadata[],
|
||||
config: PrismaJson.McpServerConfig | undefined,
|
||||
opts: DirectToolCallOptions,
|
||||
): AgentTool[] {
|
||||
if (config?.directTools !== true) return []
|
||||
|
||||
const tools: AgentTool[] = []
|
||||
for (const tool of metadata) {
|
||||
if (!isToolAllowed(tool.name, tool.originalName, config)) continue
|
||||
const parameters = toToolParameters(tool.inputSchema)
|
||||
tools.push({
|
||||
name: tool.name,
|
||||
label: tool.name,
|
||||
description:
|
||||
tool.description || `Call ${tool.originalName} on MCP server ${opts.serverName}.`,
|
||||
parameters: parameters as unknown as import('typebox').TSchema,
|
||||
execute: async (_toolCallId, args): Promise<AgentToolResult<Record<string, unknown>>> => {
|
||||
const result = await opts.callTool(
|
||||
opts.serverId,
|
||||
tool.originalName,
|
||||
args as Record<string, unknown>,
|
||||
)
|
||||
return {
|
||||
content: result.content,
|
||||
details: { server: opts.serverName, tool: tool.originalName },
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
return tools
|
||||
}
|
||||
|
||||
// Re-exported for tests that need a fallback parameter schema.
|
||||
export { Type }
|
||||
@@ -0,0 +1,147 @@
|
||||
import { describe, it, expect, beforeAll } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { McpDbStore } from './mcp-db-store'
|
||||
import { McpOauthProvider } from './mcp-oauth-provider'
|
||||
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
// The OAuth wire format (RFC 6749 / OAuth 2.1) uses snake_case field names
|
||||
// (client_id, access_token, grant_type, ...); the test fixtures must use the
|
||||
// protocol's exact key names because they are passed to the MCP SDK's
|
||||
// OAuthClientProvider interfaces.
|
||||
|
||||
const SERVER_URL = 'https://mcp.example.com/kling'
|
||||
const ISSUER = 'https://kling.ai/auth'
|
||||
|
||||
describe('McpOauthProvider SEP-2352 issuer stamping', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let store: McpDbStore
|
||||
let serverId: string
|
||||
|
||||
const makeProvider = () =>
|
||||
new McpOauthProvider(
|
||||
serverId,
|
||||
SERVER_URL,
|
||||
{ redirectUri: 'https://shumai.ai/api/mcp/oauth/callback' },
|
||||
{ onRedirect: async () => {} },
|
||||
store,
|
||||
)
|
||||
|
||||
beforeAll(async () => {
|
||||
store = new McpDbStore()
|
||||
const team = await prisma.team.create({ data: { name: 'OAuth Provider Team' } })
|
||||
const server = await prisma.mcpServer.create({
|
||||
data: { name: 'kling', url: SERVER_URL, teamId: team.id },
|
||||
})
|
||||
serverId = server.id
|
||||
})
|
||||
|
||||
it('discoveryState() returns the snapshot saved by the start leg on the callback leg', async () => {
|
||||
const provider = makeProvider()
|
||||
// Start leg: the SDK saves the discovery state before redirecting.
|
||||
await provider.saveDiscoveryState({
|
||||
authorizationServerUrl: ISSUER,
|
||||
authorizationServerMetadata: { issuer: ISSUER },
|
||||
resourceMetadataUrl: `${SERVER_URL}/.well-known/oauth-protected-resource`,
|
||||
} as never)
|
||||
await provider.deactivate()
|
||||
|
||||
// startAuth() persists the pending flow (must not clobber the snapshot).
|
||||
await store.savePendingAuth(serverId, {
|
||||
state: 'state-xyz',
|
||||
authorizationUrl: 'https://kling.ai/authorize',
|
||||
discovery: {},
|
||||
expiresAt: Math.floor(Date.now() / 1000) + 300,
|
||||
})
|
||||
|
||||
// Callback leg: a fresh provider instance reads the same snapshot.
|
||||
const callbackProvider = makeProvider()
|
||||
const state = await callbackProvider.discoveryState()
|
||||
expect(state?.authorizationServerMetadata?.issuer).toBe(ISSUER)
|
||||
expect(state?.authorizationServerUrl).toBe(ISSUER)
|
||||
})
|
||||
|
||||
it('saveClientInformation stamps the issuer and clientInformation round-trips it', async () => {
|
||||
const provider = makeProvider()
|
||||
await provider.saveDiscoveryState({
|
||||
authorizationServerUrl: ISSUER,
|
||||
authorizationServerMetadata: { issuer: ISSUER },
|
||||
} as never)
|
||||
|
||||
await provider.saveClientInformation({
|
||||
client_id: 'dyn-client',
|
||||
client_secret: 'dyn-secret',
|
||||
} as never)
|
||||
|
||||
const info = await makeProvider().clientInformation()
|
||||
expect(info?.client_id).toBe('dyn-client')
|
||||
expect((info as { issuer?: string }).issuer).toBe(ISSUER)
|
||||
})
|
||||
|
||||
it('clientInformation() backfills a missing issuer stamp on stale client info', async () => {
|
||||
const provider = makeProvider()
|
||||
// Pre-existing client info stored WITHOUT an issuer (registered before the
|
||||
// stamping fix). The discovery snapshot is available for this read.
|
||||
await store.updateClientInfo(
|
||||
serverId,
|
||||
{ clientId: 'legacy-client', clientSecret: 'legacy-secret' },
|
||||
SERVER_URL,
|
||||
)
|
||||
await provider.saveDiscoveryState({
|
||||
authorizationServerUrl: ISSUER,
|
||||
authorizationServerMetadata: { issuer: ISSUER },
|
||||
} as never)
|
||||
|
||||
const info = await makeProvider().clientInformation()
|
||||
expect(info?.client_id).toBe('legacy-client')
|
||||
expect((info as { issuer?: string }).issuer).toBe(ISSUER)
|
||||
// The stamp is persisted, not just returned.
|
||||
const entry = await store.getAuthForUrl(serverId, SERVER_URL)
|
||||
expect(entry?.clientInfo?.issuer).toBe(ISSUER)
|
||||
})
|
||||
|
||||
it('saveTokens stamps the issuer and tokens round-trips it', async () => {
|
||||
const provider = makeProvider()
|
||||
await provider.saveDiscoveryState({
|
||||
authorizationServerUrl: ISSUER,
|
||||
authorizationServerMetadata: { issuer: ISSUER },
|
||||
} as never)
|
||||
|
||||
await provider.saveTokens({
|
||||
access_token: 'tok-1',
|
||||
token_type: 'Bearer',
|
||||
refresh_token: 'ref-1',
|
||||
expires_in: 3600,
|
||||
} as never)
|
||||
|
||||
const tokens = await makeProvider().tokens()
|
||||
expect(tokens?.access_token).toBe('tok-1')
|
||||
expect((tokens as { issuer?: string }).issuer).toBe(ISSUER)
|
||||
})
|
||||
|
||||
it('tokens() backfills a missing issuer stamp from the discovery snapshot', async () => {
|
||||
const provider = makeProvider()
|
||||
// Pre-existing tokens stored WITHOUT an issuer (pre-upgrade / buggy flow).
|
||||
await store.updateTokens(serverId, { accessToken: 'legacy-tok' }, SERVER_URL)
|
||||
// The discovery snapshot is present for the read.
|
||||
await provider.saveDiscoveryState({
|
||||
authorizationServerUrl: ISSUER,
|
||||
authorizationServerMetadata: { issuer: ISSUER },
|
||||
} as never)
|
||||
|
||||
const tokens = await provider.tokens()
|
||||
expect(tokens?.access_token).toBe('legacy-tok')
|
||||
expect((tokens as { issuer?: string }).issuer).toBe(ISSUER)
|
||||
// The stamp is persisted, not just returned.
|
||||
const entry = await store.getAuthForUrl(serverId, SERVER_URL)
|
||||
expect(entry?.tokens?.issuer).toBe(ISSUER)
|
||||
})
|
||||
|
||||
it('does not stamp an issuer when no discovery snapshot is available', async () => {
|
||||
const provider = makeProvider()
|
||||
await provider.saveClientInformation({ client_id: 'c2' } as never)
|
||||
const info = await makeProvider().clientInformation()
|
||||
expect((info as { issuer?: string }).issuer).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,503 @@
|
||||
/**
|
||||
* MCP OAuth Provider (DB-backed)
|
||||
*
|
||||
* Implementation of the MCP SDK's OAuthClientProvider interface. Adapted from
|
||||
* pi-mcp-adapter's mcp-oauth-provider.ts, with two differences:
|
||||
* 1. All persisted state (tokens, client info, PKCE verifier, discovery
|
||||
* state, CSRF state) is stored in the DB via McpDbStore instead of the OS
|
||||
* keyring/files, so the flow survives across HTTP requests and processes.
|
||||
* 2. The redirect URI is shumai's own Hono callback endpoint
|
||||
* (`${MCP_OAUTH_REDIRECT_BASE_URL}/api/mcp/oauth/callback`) instead of a
|
||||
* localhost callback server.
|
||||
*/
|
||||
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
// The OAuth wire format (RFC 6749 / OAuth 2.1 client metadata) uses snake_case
|
||||
// field names (client_id, access_token, grant_type, ...). These are dictated by
|
||||
// the OAuth protocol and the MCP SDK's OAuthClientProvider interfaces, so they
|
||||
// cannot be renamed to camelCase.
|
||||
|
||||
import {
|
||||
type AddClientAuthentication,
|
||||
type OAuthClientProvider,
|
||||
type OAuthClientInformationMixed,
|
||||
type OAuthClientMetadata,
|
||||
type OAuthDiscoveryState,
|
||||
type OAuthTokens,
|
||||
} from '@modelcontextprotocol/client'
|
||||
import type { McpDbStore, AuthEntry, StoredClientInfo, StoredTokens } from './mcp-db-store'
|
||||
|
||||
type IssuerBoundClientInformation = OAuthClientInformationMixed & { issuer?: string }
|
||||
type IssuerBoundTokens = OAuthTokens & { issuer?: string }
|
||||
|
||||
function issuersMatch(first: string, second: string): boolean {
|
||||
return (
|
||||
first === second ||
|
||||
(first.endsWith('/') && first.slice(0, -1) === second) ||
|
||||
(second.endsWith('/') && second.slice(0, -1) === first)
|
||||
)
|
||||
}
|
||||
|
||||
export function getOauthRedirectBaseUrl(): string {
|
||||
return (
|
||||
process.env.MCP_OAUTH_REDIRECT_BASE_URL?.trim() || process.env.BETTER_AUTH_URL?.trim() || ''
|
||||
)
|
||||
}
|
||||
|
||||
/** The default redirect URI used when the server config does not set one. */
|
||||
export function getDefaultOauthRedirectUri(): string | undefined {
|
||||
const base = getOauthRedirectBaseUrl()
|
||||
if (!base) return undefined
|
||||
return `${base.replace(/\/$/, '')}/api/mcp/oauth/callback`
|
||||
}
|
||||
|
||||
/** Configuration options for OAuth. */
|
||||
export interface McpOauthConfig {
|
||||
grantType?: 'authorization_code' | 'client_credentials'
|
||||
clientId?: string
|
||||
clientSecret?: string
|
||||
scope?: string
|
||||
authorizationParams?: Record<string, string>
|
||||
redirectUri?: string
|
||||
clientName?: string
|
||||
clientUri?: string
|
||||
skipIssuerMetadataValidation?: boolean
|
||||
}
|
||||
|
||||
const reservedAuthorizationParams = new Set([
|
||||
'client_id',
|
||||
'code_challenge',
|
||||
'code_challenge_method',
|
||||
'redirect_uri',
|
||||
'resource',
|
||||
'response_type',
|
||||
'scope',
|
||||
'state',
|
||||
])
|
||||
|
||||
function addAuthorizationParams(
|
||||
authorizationUrl: URL,
|
||||
params: Record<string, string> | undefined,
|
||||
): URL {
|
||||
if (!params) return authorizationUrl
|
||||
const nextUrl = new URL(authorizationUrl.toString())
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (reservedAuthorizationParams.has(key) || nextUrl.searchParams.has(key)) {
|
||||
throw new Error(
|
||||
`OAuth authorizationParams.${key} cannot override an authorization flow parameter`,
|
||||
)
|
||||
}
|
||||
nextUrl.searchParams.set(key, value)
|
||||
}
|
||||
return nextUrl
|
||||
}
|
||||
|
||||
/** Callbacks for OAuth flow interactions. */
|
||||
export interface McpOauthCallbacks {
|
||||
onRedirect: (url: URL) => void | Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* OAuth provider implementation for MCP servers backed by the DB store.
|
||||
*/
|
||||
export class McpOauthProvider implements OAuthClientProvider {
|
||||
private readonly redirectUrlSnapshot: string | undefined
|
||||
private active = true
|
||||
private flowIssuerMismatch = false
|
||||
|
||||
constructor(
|
||||
private serverId: string,
|
||||
private serverUrl: string,
|
||||
private config: McpOauthConfig,
|
||||
private callbacks: McpOauthCallbacks,
|
||||
private store: McpDbStore,
|
||||
) {
|
||||
this.redirectUrlSnapshot =
|
||||
config.grantType === 'client_credentials'
|
||||
? undefined
|
||||
: (config.redirectUri ?? getDefaultOauthRedirectUri())
|
||||
}
|
||||
|
||||
private get usesClientCredentials(): boolean {
|
||||
return this.config.grantType === 'client_credentials'
|
||||
}
|
||||
|
||||
deactivate(): void {
|
||||
this.active = false
|
||||
}
|
||||
|
||||
private throwIfInactive(): void {
|
||||
if (!this.active) throw new Error('OAuth flow is no longer active')
|
||||
}
|
||||
|
||||
private assertStoredIssuerBindings(
|
||||
entry: AuthEntry | undefined,
|
||||
issuer: string | undefined,
|
||||
): void {
|
||||
if (this.flowIssuerMismatch) {
|
||||
throw new Error(
|
||||
`OAuth authorization server issuer changed; clear credentials before authenticating again`,
|
||||
)
|
||||
}
|
||||
if (!entry || !issuer) return
|
||||
|
||||
const storedIssuers = [entry.clientInfo?.issuer, entry.tokens?.issuer].filter(
|
||||
(storedIssuer): storedIssuer is string => storedIssuer !== undefined,
|
||||
)
|
||||
if (storedIssuers.some((storedIssuer) => !issuersMatch(storedIssuer, issuer))) {
|
||||
this.flowIssuerMismatch = true
|
||||
throw new Error(
|
||||
`OAuth authorization server issuer changed; clear credentials before authenticating again`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The redirect URL for OAuth callbacks. */
|
||||
get redirectUrl(): string | undefined {
|
||||
return this.redirectUrlSnapshot
|
||||
}
|
||||
|
||||
/**
|
||||
* SEP-2352 issuer of the authorization server from the discovery snapshot
|
||||
* persisted by saveDiscoveryState (available on both the start and callback
|
||||
* legs thanks to the DB-backed store).
|
||||
*/
|
||||
private async getDiscoveredIssuer(): Promise<string | undefined> {
|
||||
const snapshot = await this.store.getDiscoverySnapshot(this.serverId)
|
||||
if (!snapshot) return undefined
|
||||
const metadata = snapshot['authorizationServerMetadata'] as { issuer?: string } | undefined
|
||||
const issuer = metadata?.issuer
|
||||
if (typeof issuer === 'string' && issuer.length > 0) return issuer
|
||||
const serverUrl = snapshot['authorizationServerUrl']
|
||||
return typeof serverUrl === 'string' && serverUrl.length > 0 ? serverUrl : undefined
|
||||
}
|
||||
|
||||
/** Client metadata for dynamic registration. */
|
||||
get clientMetadata(): OAuthClientMetadata {
|
||||
if (this.usesClientCredentials) {
|
||||
return {
|
||||
client_name: this.config.clientName ?? 'Shumai',
|
||||
client_uri: this.config.clientUri ?? 'https://shumai.ai',
|
||||
redirect_uris: [],
|
||||
grant_types: ['client_credentials'],
|
||||
token_endpoint_auth_method: this.config.clientSecret ? 'client_secret_post' : 'none',
|
||||
}
|
||||
}
|
||||
|
||||
const redirectUrl = this.redirectUrl
|
||||
if (!redirectUrl) {
|
||||
throw new Error(
|
||||
'redirectUrl is required for authorization_code flow. Set MCP_OAUTH_REDIRECT_BASE_URL or BETTER_AUTH_URL, or configure authConfig.oauth.redirectUri.',
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
redirect_uris: [redirectUrl],
|
||||
client_name: this.config.clientName ?? 'Shumai',
|
||||
client_uri: this.config.clientUri ?? 'https://shumai.ai',
|
||||
grant_types: ['authorization_code', 'refresh_token'],
|
||||
response_types: ['code'],
|
||||
token_endpoint_auth_method: this.config.clientSecret ? 'client_secret_post' : 'none',
|
||||
...(this.config.scope !== undefined ? { scope: this.config.scope } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** Get client information (pre-registered or dynamically registered). */
|
||||
async clientInformation(): Promise<OAuthClientInformationMixed | undefined> {
|
||||
const stored = await this.store.getAuthForUrl(this.serverId, this.serverUrl)
|
||||
this.assertStoredIssuerBindings(stored, undefined)
|
||||
|
||||
// Config-first (pre-registered client). The secret stays in config.
|
||||
if (this.config.clientId) {
|
||||
const storedClient =
|
||||
stored?.clientInfo?.clientId === this.config.clientId ? stored.clientInfo : undefined
|
||||
const issuer = await this.getDiscoveredIssuer()
|
||||
if (storedClient?.issuer === undefined || storedClient.configPreRegistered !== true) {
|
||||
await this.store.updateClientInfo(
|
||||
this.serverId,
|
||||
{
|
||||
clientId: this.config.clientId,
|
||||
configPreRegistered: true,
|
||||
...(issuer !== undefined ? { issuer } : {}),
|
||||
},
|
||||
this.serverUrl,
|
||||
)
|
||||
}
|
||||
return {
|
||||
client_id: this.config.clientId,
|
||||
client_secret: this.config.clientSecret,
|
||||
...(issuer !== undefined ? { issuer } : {}),
|
||||
} as IssuerBoundClientInformation
|
||||
}
|
||||
|
||||
const clientInfo = stored?.clientInfo
|
||||
if (clientInfo) {
|
||||
const isConfigStub =
|
||||
clientInfo.configPreRegistered === true ||
|
||||
(clientInfo.clientSecret === undefined &&
|
||||
clientInfo.clientIdIssuedAt === undefined &&
|
||||
clientInfo.clientSecretExpiresAt === undefined &&
|
||||
clientInfo.redirectUris === undefined)
|
||||
if (isConfigStub) return undefined
|
||||
if (
|
||||
clientInfo.clientSecretExpiresAt &&
|
||||
clientInfo.clientSecretExpiresAt < Date.now() / 1000
|
||||
) {
|
||||
return undefined
|
||||
}
|
||||
// SEP-2352: backfill a missing issuer stamp (pre-upgrade / stale storage)
|
||||
// from the discovery snapshot, persisting it so later reads are isolated.
|
||||
const issuer = await this.getDiscoveredIssuer()
|
||||
if (issuer !== undefined && clientInfo.issuer === undefined) {
|
||||
const stamped: StoredClientInfo = { ...clientInfo, issuer }
|
||||
await this.store.updateClientInfo(this.serverId, stamped, this.serverUrl)
|
||||
clientInfo.issuer = issuer
|
||||
}
|
||||
return {
|
||||
client_id: clientInfo.clientId,
|
||||
client_secret: clientInfo.clientSecret,
|
||||
...(clientInfo.clientIdIssuedAt !== undefined
|
||||
? { client_id_issued_at: clientInfo.clientIdIssuedAt }
|
||||
: {}),
|
||||
...(clientInfo.clientSecretExpiresAt !== undefined
|
||||
? { client_secret_expires_at: clientInfo.clientSecretExpiresAt }
|
||||
: {}),
|
||||
...(clientInfo.redirectUris !== undefined
|
||||
? { redirect_uris: clientInfo.redirectUris }
|
||||
: {}),
|
||||
...(clientInfo.issuer !== undefined ? { issuer: clientInfo.issuer } : {}),
|
||||
} as IssuerBoundClientInformation
|
||||
}
|
||||
|
||||
// No client info - triggers dynamic registration.
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Save client information from dynamic registration. */
|
||||
async saveClientInformation(info: OAuthClientInformationMixed): Promise<void> {
|
||||
this.throwIfInactive()
|
||||
if (this.config.clientId && info.client_id === this.config.clientId) {
|
||||
await this.store.updateClientInfo(
|
||||
this.serverId,
|
||||
{ clientId: info.client_id, configPreRegistered: true },
|
||||
this.serverUrl,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const redirectUris =
|
||||
('redirect_uris' in info ? info.redirect_uris : undefined) ??
|
||||
(this.redirectUrl ? [this.redirectUrl] : undefined)
|
||||
const issuer = await this.getDiscoveredIssuer()
|
||||
const clientInfo: StoredClientInfo = {
|
||||
clientId: info.client_id,
|
||||
...(info.client_secret !== undefined ? { clientSecret: info.client_secret } : {}),
|
||||
...(info.client_id_issued_at !== undefined
|
||||
? { clientIdIssuedAt: info.client_id_issued_at }
|
||||
: {}),
|
||||
...(info.client_secret_expires_at !== undefined
|
||||
? { clientSecretExpiresAt: info.client_secret_expires_at }
|
||||
: {}),
|
||||
...(redirectUris !== undefined ? { redirectUris } : {}),
|
||||
...(issuer !== undefined ? { issuer } : {}),
|
||||
}
|
||||
await this.store.updateClientInfo(this.serverId, clientInfo, this.serverUrl)
|
||||
}
|
||||
|
||||
/** Get stored OAuth tokens. */
|
||||
async tokens(): Promise<OAuthTokens | undefined> {
|
||||
const entry = await this.store.getAuthForUrl(this.serverId, this.serverUrl)
|
||||
if (!entry?.tokens) return undefined
|
||||
this.assertStoredIssuerBindings(entry, undefined)
|
||||
|
||||
// SEP-2352: backfill a missing issuer stamp from the discovery snapshot so
|
||||
// isolation stays active for pre-existing credentials.
|
||||
const issuer = await this.getDiscoveredIssuer()
|
||||
if (issuer !== undefined && entry.tokens.issuer === undefined) {
|
||||
const stamped: StoredTokens = { ...entry.tokens, issuer }
|
||||
await this.store.updateTokens(this.serverId, stamped, this.serverUrl)
|
||||
entry.tokens = stamped
|
||||
}
|
||||
|
||||
return {
|
||||
access_token: entry.tokens.accessToken,
|
||||
token_type: 'Bearer',
|
||||
refresh_token: entry.tokens.refreshToken,
|
||||
expires_in: entry.tokens.expiresAt
|
||||
? Math.max(0, Math.floor(entry.tokens.expiresAt - Date.now() / 1000))
|
||||
: undefined,
|
||||
scope: entry.tokens.scope,
|
||||
...(entry.tokens.issuer !== undefined ? { issuer: entry.tokens.issuer } : {}),
|
||||
} as IssuerBoundTokens
|
||||
}
|
||||
|
||||
/** Save OAuth tokens. */
|
||||
async saveTokens(tokens: OAuthTokens): Promise<void> {
|
||||
const issuer = await this.getDiscoveredIssuer()
|
||||
const storedTokens: StoredTokens = {
|
||||
accessToken: tokens.access_token,
|
||||
...(tokens.refresh_token !== undefined ? { refreshToken: tokens.refresh_token } : {}),
|
||||
...(tokens.expires_in !== undefined
|
||||
? { expiresAt: Date.now() / 1000 + tokens.expires_in }
|
||||
: {}),
|
||||
...(tokens.scope !== undefined ? { scope: tokens.scope } : {}),
|
||||
...(issuer !== undefined ? { issuer } : {}),
|
||||
}
|
||||
this.throwIfInactive()
|
||||
await this.store.updateTokens(this.serverId, storedTokens, this.serverUrl)
|
||||
}
|
||||
|
||||
/** Redirect the user to the authorization URL. */
|
||||
async redirectToAuthorization(authorizationUrl: URL): Promise<void> {
|
||||
if (this.usesClientCredentials) {
|
||||
throw new Error('redirectToAuthorization is not used for client_credentials flow')
|
||||
}
|
||||
this.throwIfInactive()
|
||||
await this.callbacks.onRedirect(
|
||||
addAuthorizationParams(authorizationUrl, this.config.authorizationParams),
|
||||
)
|
||||
}
|
||||
|
||||
/** Save the PKCE code verifier (persisted so the callback leg can use it). */
|
||||
async saveCodeVerifier(codeVerifier: string): Promise<void> {
|
||||
this.throwIfInactive()
|
||||
await this.store.updateCodeVerifier(this.serverId, codeVerifier, this.serverUrl)
|
||||
}
|
||||
|
||||
async codeVerifier(): Promise<string> {
|
||||
if (this.usesClientCredentials) {
|
||||
throw new Error('codeVerifier is not used for client_credentials flow')
|
||||
}
|
||||
this.throwIfInactive()
|
||||
const entry = await this.store.getAuthForUrl(this.serverId, this.serverUrl)
|
||||
if (!entry?.codeVerifier) {
|
||||
throw new Error(`No code verifier saved for MCP server`)
|
||||
}
|
||||
return entry.codeVerifier
|
||||
}
|
||||
|
||||
/** Keep discovery with the in-flight PKCE verifier. */
|
||||
async saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {
|
||||
this.throwIfInactive()
|
||||
// Persisted inside the pendingAuth row by mcpService after startAuth; also
|
||||
// kept on the credential row so the callback leg can re-read it.
|
||||
await this.store.saveDiscoverySnapshot(this.serverId, this.serverUrl, state)
|
||||
}
|
||||
|
||||
async discoveryState(): Promise<OAuthDiscoveryState | undefined> {
|
||||
this.throwIfInactive()
|
||||
const snapshot = await this.store.getDiscoverySnapshot(this.serverId)
|
||||
return snapshot as unknown as OAuthDiscoveryState | undefined
|
||||
}
|
||||
|
||||
/** Save the OAuth state parameter for CSRF protection. */
|
||||
async saveState(state: string): Promise<void> {
|
||||
this.throwIfInactive()
|
||||
await this.store.updateOauthState(this.serverId, state, this.serverUrl)
|
||||
}
|
||||
|
||||
async state(): Promise<string> {
|
||||
if (this.usesClientCredentials) {
|
||||
throw new Error('state is not used for client_credentials flow')
|
||||
}
|
||||
this.throwIfInactive()
|
||||
let state = await this.store.getOauthState(this.serverId)
|
||||
if (!state) {
|
||||
state = Array.from(crypto.getRandomValues(new Uint8Array(32)))
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
await this.store.updateOauthState(this.serverId, state, this.serverUrl)
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
/** Invalidate credentials when authentication fails. */
|
||||
async invalidateCredentials(
|
||||
type: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery',
|
||||
): Promise<void> {
|
||||
this.throwIfInactive()
|
||||
switch (type) {
|
||||
case 'all':
|
||||
this.flowIssuerMismatch = false
|
||||
await this.store.clearAllCredentials(this.serverId)
|
||||
break
|
||||
case 'client':
|
||||
await this.store.clearClientInfo(this.serverId)
|
||||
break
|
||||
case 'tokens':
|
||||
await this.store.clearTokens(this.serverId)
|
||||
break
|
||||
case 'verifier':
|
||||
await this.store.clearCodeVerifier(this.serverId)
|
||||
break
|
||||
case 'discovery':
|
||||
await this.store.clearDiscoverySnapshot(this.serverId)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds configured authorization-code scope and client authentication. */
|
||||
addClientAuthentication: AddClientAuthentication = async (headers, params, _url, metadata) => {
|
||||
this.throwIfInactive()
|
||||
if (
|
||||
params.get('grant_type') === 'authorization_code' &&
|
||||
!params.has('scope') &&
|
||||
this.config.scope
|
||||
) {
|
||||
params.set('scope', this.config.scope)
|
||||
}
|
||||
|
||||
const clientInfo = await this.clientInformation()
|
||||
this.throwIfInactive()
|
||||
if (!clientInfo) return
|
||||
|
||||
const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? []
|
||||
const hasClientSecret = clientInfo.client_secret !== undefined
|
||||
let authMethod: 'client_secret_basic' | 'client_secret_post' | 'none'
|
||||
|
||||
if (supportedMethods.length === 0) {
|
||||
authMethod = hasClientSecret ? 'client_secret_post' : 'none'
|
||||
} else if (hasClientSecret && supportedMethods.includes('client_secret_basic')) {
|
||||
authMethod = 'client_secret_basic'
|
||||
} else if (hasClientSecret && supportedMethods.includes('client_secret_post')) {
|
||||
authMethod = 'client_secret_post'
|
||||
} else if (supportedMethods.includes('none')) {
|
||||
authMethod = 'none'
|
||||
} else {
|
||||
authMethod = hasClientSecret ? 'client_secret_post' : 'none'
|
||||
}
|
||||
|
||||
if (authMethod === 'client_secret_basic') {
|
||||
if (!clientInfo.client_secret) {
|
||||
throw new Error('client_secret_basic authentication requires a client_secret')
|
||||
}
|
||||
headers.set(
|
||||
'Authorization',
|
||||
`Basic ${Buffer.from(`${clientInfo.client_id}:${clientInfo.client_secret}`).toString('base64')}`,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (!params.has('client_id')) {
|
||||
params.set('client_id', clientInfo.client_id)
|
||||
}
|
||||
if (
|
||||
authMethod === 'client_secret_post' &&
|
||||
clientInfo.client_secret &&
|
||||
!params.has('client_secret')
|
||||
) {
|
||||
params.set('client_secret', clientInfo.client_secret)
|
||||
}
|
||||
}
|
||||
|
||||
prepareTokenRequest(scope?: string): URLSearchParams | undefined {
|
||||
if (!this.usesClientCredentials) return undefined
|
||||
|
||||
const params = new URLSearchParams({ grant_type: 'client_credentials' })
|
||||
const requestedScope = scope ?? this.config.scope
|
||||
if (requestedScope) {
|
||||
params.set('scope', requestedScope)
|
||||
}
|
||||
return params
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
/**
|
||||
* MCP proxy tool — the single `mcp` AgentTool registered per agent.
|
||||
*
|
||||
* One tool in the LLM context multiplexes all of the agent's assigned MCP
|
||||
* servers via `{ server, tool, args, search, describe, connect, action }`.
|
||||
* Mode precedence: action > tool(call) > connect > describe > search >
|
||||
* server(list) > status.
|
||||
*/
|
||||
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
|
||||
import type { McpToolRegistry, ToolMetadata } from './mcp-tool-registry'
|
||||
import { formatSchema } from './mcp-tool-schema'
|
||||
|
||||
type ProxyToolResult = AgentToolResult<Record<string, unknown>>
|
||||
|
||||
/** Truncated instructions head baked into the proxy tool description (L1). */
|
||||
const INSTRUCTIONS_SNIPPET_LENGTH = 150
|
||||
/** Longer instructions preview appended to server listings (L2). */
|
||||
const INSTRUCTIONS_PREVIEW_LENGTH = 300
|
||||
|
||||
/** Truncate at a word boundary (mirrors pi-mcp-adapter's truncateAtWord). */
|
||||
function truncateInstruction(text: string, target: number): string {
|
||||
if (!text || text.length <= target) return text
|
||||
const truncated = text.slice(0, target)
|
||||
const lastSpace = truncated.lastIndexOf(' ')
|
||||
if (lastSpace > target * 0.6) {
|
||||
return `${truncated.slice(0, lastSpace)}...`
|
||||
}
|
||||
return `${truncated}...`
|
||||
}
|
||||
|
||||
export interface ProxyServerInfo {
|
||||
id: string
|
||||
name: string
|
||||
toolCount: number
|
||||
status: string
|
||||
/** Self-reported server usage instructions (empty when the server provides none). */
|
||||
instructions?: string
|
||||
}
|
||||
|
||||
export type ConnectionOutcome =
|
||||
| { status: 'connected' }
|
||||
| { status: 'needs-auth' }
|
||||
| { status: 'error'; message: string }
|
||||
|
||||
export interface CallToolOutcome {
|
||||
ok: boolean
|
||||
content: AgentToolResult<Record<string, unknown>>['content']
|
||||
}
|
||||
|
||||
export interface McpProxyToolContext {
|
||||
teamId: string
|
||||
userId?: string
|
||||
servers: ProxyServerInfo[]
|
||||
serverNameById: Map<string, string>
|
||||
serverIdByName: Map<string, string>
|
||||
registry: McpToolRegistry
|
||||
/** Resolve the server id for a (possibly prefixed) tool name. */
|
||||
resolveServerForTool?(toolName: string): string | undefined
|
||||
ensureConnected(serverId: string): Promise<ConnectionOutcome>
|
||||
callTool(
|
||||
serverId: string,
|
||||
toolName: string,
|
||||
args: Record<string, unknown>,
|
||||
): Promise<CallToolOutcome>
|
||||
authStatus(serverId: string): Promise<string>
|
||||
startAuth(
|
||||
serverId: string,
|
||||
): Promise<{ authorizationUrl?: string; alreadyAuthenticated?: boolean }>
|
||||
/** Server-reported usage instructions (DB cache, works without a live connection). */
|
||||
getInstructions(serverId: string): Promise<string | null>
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a tool, lazily connecting the owning server first when the registry
|
||||
* has no cached metadata for it yet (first call in a fresh process).
|
||||
*/
|
||||
async function resolveToolWithLazyConnect(
|
||||
ctx: McpProxyToolContext,
|
||||
toolName: string,
|
||||
serverId?: string,
|
||||
): Promise<{ ok: true; serverId: string; tool: ToolMetadata } | { ok: false }> {
|
||||
const firstResolve = ctx.registry.findTool(toolName, serverId)
|
||||
if (firstResolve) return { ok: true, ...firstResolve }
|
||||
|
||||
const targetServerId = serverId ?? ctx.resolveServerForTool?.(toolName)
|
||||
if (!targetServerId) return { ok: false }
|
||||
|
||||
const outcome = await ctx.ensureConnected(targetServerId)
|
||||
if (outcome.status !== 'connected') return { ok: false }
|
||||
|
||||
const retried = ctx.registry.findTool(toolName, targetServerId)
|
||||
if (!retried) return { ok: false }
|
||||
return { ok: true, ...retried }
|
||||
}
|
||||
|
||||
const proxyToolSchema = Type.Object(
|
||||
{
|
||||
server: Type.Optional(
|
||||
Type.String({
|
||||
description:
|
||||
'The MCP server name. Required to call a tool, list a server, or start auth. Omit to search across all servers.',
|
||||
}),
|
||||
),
|
||||
tool: Type.Optional(
|
||||
Type.String({
|
||||
description:
|
||||
'The name of the tool to call on the server (prefixed "{server}_{tool}" or the original tool name).',
|
||||
}),
|
||||
),
|
||||
args: Type.Optional(
|
||||
Type.Unknown({
|
||||
description: 'Arguments for the tool call: either a JSON object or a JSON-encoded string.',
|
||||
}),
|
||||
),
|
||||
describe: Type.Optional(
|
||||
Type.String({
|
||||
description: 'Tool name to show its full parameter schema.',
|
||||
}),
|
||||
),
|
||||
instructions: Type.Optional(
|
||||
Type.String({
|
||||
description: 'Server name to show its full usage instructions.',
|
||||
}),
|
||||
),
|
||||
search: Type.Optional(
|
||||
Type.String({
|
||||
description: 'Search query to find tools across servers (camelCase/snake_case aware).',
|
||||
}),
|
||||
),
|
||||
includeSchemas: Type.Optional(
|
||||
Type.Boolean({
|
||||
description: 'Include parameter schemas in search results (default true).',
|
||||
}),
|
||||
),
|
||||
limit: Type.Optional(Type.Number({ description: 'Max results for search/list (default 12).' })),
|
||||
offset: Type.Optional(Type.Number({ description: 'Pagination offset for search/list.' })),
|
||||
action: Type.Optional(
|
||||
Type.Union([Type.Literal('status'), Type.Literal('auth-start')], {
|
||||
description:
|
||||
'"status" shows connection/auth state for all servers; "auth-start" begins OAuth for `server` (the user completes it in a browser, then you poll status).',
|
||||
}),
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
)
|
||||
|
||||
function parseArgs(raw: unknown): Record<string, unknown> {
|
||||
if (raw === undefined || raw === null) return {}
|
||||
if (typeof raw === 'string') {
|
||||
const trimmed = raw.trim()
|
||||
if (!trimmed) return {}
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed)
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed as Record<string, unknown>
|
||||
}
|
||||
return { value: parsed }
|
||||
} catch {
|
||||
return { value: raw }
|
||||
}
|
||||
}
|
||||
if (typeof raw === 'object' && !Array.isArray(raw)) {
|
||||
return raw as Record<string, unknown>
|
||||
}
|
||||
return { value: raw }
|
||||
}
|
||||
|
||||
function contentText(text: string): ProxyToolResult {
|
||||
return { content: [{ type: 'text', text }], details: {} }
|
||||
}
|
||||
|
||||
/** Transform MCP content blocks into model content blocks. */
|
||||
export function transformMcpContent(
|
||||
content: Array<{
|
||||
type: string
|
||||
text?: string
|
||||
data?: string
|
||||
mimeType?: string
|
||||
resource?: unknown
|
||||
uri?: string
|
||||
name?: string
|
||||
}>,
|
||||
): AgentToolResult<Record<string, unknown>>['content'] {
|
||||
return content.map((c) => {
|
||||
if (c.type === 'text') {
|
||||
return { type: 'text', text: c.text ?? '' }
|
||||
}
|
||||
if (c.type === 'image') {
|
||||
return { type: 'image', data: c.data ?? '', mimeType: c.mimeType ?? 'image/png' }
|
||||
}
|
||||
if (c.type === 'resource') {
|
||||
const res = (c.resource ?? {}) as { uri?: string; text?: string }
|
||||
const resourceUri = res.uri ?? '(no URI)'
|
||||
const resourceContent = res.text ?? (c.resource ? JSON.stringify(c.resource) : '(no content)')
|
||||
return { type: 'text', text: `[Resource: ${resourceUri}]\n${resourceContent}` }
|
||||
}
|
||||
if (c.type === 'resource_link') {
|
||||
const linkName = c.name ?? c.uri ?? 'unknown'
|
||||
const linkUri = c.uri ?? '(no URI)'
|
||||
return { type: 'text', text: `[Resource Link: ${linkName}]\nURI: ${linkUri}` }
|
||||
}
|
||||
if (c.type === 'audio') {
|
||||
return { type: 'text', text: `[Audio content: ${c.mimeType ?? 'audio/*'}]` }
|
||||
}
|
||||
return { type: 'text', text: JSON.stringify(c) }
|
||||
})
|
||||
}
|
||||
|
||||
function renderToolShape(tool: ToolMetadata, indent = ''): string {
|
||||
if (!tool.inputSchema) return 'No parameters defined.'
|
||||
const schemaText = formatSchema(tool.inputSchema, indent)
|
||||
return `Parameters:\n${schemaText}`
|
||||
}
|
||||
|
||||
function notFoundResult(
|
||||
toolName: string,
|
||||
suggestions: string[],
|
||||
serverName?: string,
|
||||
): ProxyToolResult {
|
||||
let msg = `Tool "${toolName}" not found.`
|
||||
if (serverName) {
|
||||
msg += ` Use mcp({ server: "${serverName}" }) to list its tools or mcp({ search: "..." }) to search.`
|
||||
} else {
|
||||
msg += ` Use mcp({ search: "..." }) to search.`
|
||||
}
|
||||
if (suggestions.length > 0) {
|
||||
msg += ` Did you mean: ${suggestions.join(', ')}`
|
||||
}
|
||||
return contentText(msg)
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the dynamic proxy tool description (server list + tool counts + usage).
|
||||
* Servers with instructions surface a truncated head so the model sees the
|
||||
* guidance without making a call; full text is available on demand.
|
||||
*/
|
||||
export function buildProxyDescription(servers: ProxyServerInfo[]): string {
|
||||
const lines: string[] = []
|
||||
lines.push('Call MCP (Model Context Protocol) tools exposed by the configured servers.')
|
||||
lines.push('')
|
||||
lines.push('Servers:')
|
||||
if (servers.length === 0) {
|
||||
lines.push(' (none assigned)')
|
||||
} else {
|
||||
for (const s of servers) {
|
||||
lines.push(` - ${s.name} (${s.toolCount} tools, status: ${s.status})`)
|
||||
}
|
||||
}
|
||||
lines.push('')
|
||||
lines.push('Usage:')
|
||||
lines.push(' - mcp({}) → connection/auth status of all servers')
|
||||
lines.push(' - mcp({ server: "name" }) → list that server\'s tools')
|
||||
lines.push(' - mcp({ search: "query" }) → search tools across servers')
|
||||
lines.push(' - mcp({ describe: "tool" }) → show one tool\'s parameter schema')
|
||||
lines.push(' - mcp({ server: "name", tool: "tool_name", args: {...} }) → call a tool')
|
||||
lines.push(' - mcp({ instructions: "name" }) → show full server usage instructions')
|
||||
lines.push(' - mcp({ action: "auth-start", server: "name" }) → start OAuth for a server')
|
||||
lines.push('')
|
||||
const instructionLines: string[] = []
|
||||
for (const s of servers) {
|
||||
if (!s.instructions || s.instructions.trim() === '') continue
|
||||
const snippet = truncateInstruction(
|
||||
s.instructions.replace(/\s+/g, ' ').trim(),
|
||||
INSTRUCTIONS_SNIPPET_LENGTH,
|
||||
)
|
||||
instructionLines.push(` - ${s.name}: ${snippet}`)
|
||||
}
|
||||
if (instructionLines.length > 0) {
|
||||
lines.push('Server instructions (truncated — full text via mcp({ instructions: "name" })):')
|
||||
lines.push(...instructionLines)
|
||||
lines.push('')
|
||||
}
|
||||
lines.push(
|
||||
'Tool names are prefixed "{server}_{tool}" (dots replaced by underscores). You may pass either the prefixed or the original name. ' +
|
||||
'If a call fails with "needs auth", tell the user to connect the server in Settings → MCP.',
|
||||
)
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a server's tool listing with the L2 instructions preview appended
|
||||
* (mirrors pi-mcp-adapter's mcp({ server }) output). Shared by the `server`
|
||||
* list mode and the `connect` mode.
|
||||
*/
|
||||
function renderServerListing(
|
||||
serverName: string,
|
||||
tools: ToolMetadata[],
|
||||
instructions: string | null,
|
||||
): string {
|
||||
const lines = [`${serverName} (${tools.length} tools):`, '']
|
||||
for (const t of tools) {
|
||||
lines.push(`- ${t.name}${t.description ? ` - ${t.description.slice(0, 60)}` : ''}`)
|
||||
}
|
||||
if (instructions && instructions.trim() !== '') {
|
||||
const preview = truncateInstruction(instructions, INSTRUCTIONS_PREVIEW_LENGTH)
|
||||
lines.push('', 'Server instructions:', preview)
|
||||
if (preview !== instructions) {
|
||||
lines.push(`Use mcp({ instructions: "${serverName}" }) for the full text.`)
|
||||
}
|
||||
}
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the single `mcp` proxy AgentTool for a team/session.
|
||||
*/
|
||||
export function buildProxyTool(ctx: McpProxyToolContext): AgentTool<typeof proxyToolSchema> {
|
||||
return {
|
||||
name: 'mcp',
|
||||
label: 'MCP Tools',
|
||||
description: buildProxyDescription(ctx.servers),
|
||||
parameters: proxyToolSchema,
|
||||
execute: async (_toolCallId, params): Promise<ProxyToolResult> => {
|
||||
const action = params.action
|
||||
const server = params.server
|
||||
const tool = params.tool
|
||||
const search = params.search
|
||||
const describe = params.describe
|
||||
const instructions = params.instructions
|
||||
const limit = params.limit ?? 12
|
||||
const offset = params.offset ?? 0
|
||||
const includeSchemas = params.includeSchemas !== false
|
||||
|
||||
// 1. action: status / auth-start
|
||||
if (action === 'status') {
|
||||
const lines: string[] = ['MCP status:']
|
||||
for (const s of ctx.servers) {
|
||||
const auth = await ctx.authStatus(s.id)
|
||||
lines.push(` - ${s.name}: ${s.status} (${s.toolCount} tools, auth: ${auth})`)
|
||||
}
|
||||
lines.push('')
|
||||
lines.push('mcp({ server: "name" }) to list tools, mcp({ search: "..." }) to search')
|
||||
return contentText(lines.join('\n'))
|
||||
}
|
||||
if (action === 'auth-start') {
|
||||
const serverId = server ? ctx.serverIdByName.get(server) : undefined
|
||||
if (!serverId) {
|
||||
return contentText(
|
||||
`Server "${server ?? ''}" not found. Use mcp({ action: "status" }) to see available servers.`,
|
||||
)
|
||||
}
|
||||
const result = await ctx.startAuth(serverId)
|
||||
if (result.alreadyAuthenticated) {
|
||||
return contentText(`OAuth authentication already complete for "${server}".`)
|
||||
}
|
||||
if (!result.authorizationUrl) {
|
||||
return contentText(
|
||||
`OAuth authentication could not be started for "${server}". Ask an admin to check Settings → MCP.`,
|
||||
)
|
||||
}
|
||||
return contentText(
|
||||
`OAuth authentication required for "${server}". An admin must open this URL in a browser and approve access:\n\n${result.authorizationUrl}\n\nAfter approving, the browser redirects back to shumai automatically. Then poll mcp({ action: "status", server: "${server}" }) until it shows connected.`,
|
||||
)
|
||||
}
|
||||
|
||||
// 2. tool call
|
||||
if (tool) {
|
||||
const serverId = server ? ctx.serverIdByName.get(server) : undefined
|
||||
if (server && !serverId) {
|
||||
return contentText(
|
||||
`Server "${server}" not found. Use mcp({ action: "status" }) to see available servers.`,
|
||||
)
|
||||
}
|
||||
const resolved = await resolveToolWithLazyConnect(ctx, tool, serverId)
|
||||
if (!resolved.ok) {
|
||||
const suggestions = ctx.registry.rankSuggestions(tool, 5, ctx.serverNameById).slice(0, 5)
|
||||
return notFoundResult(tool, suggestions, server)
|
||||
}
|
||||
const outcome = await ctx.callTool(
|
||||
resolved.serverId,
|
||||
resolved.tool.originalName,
|
||||
parseArgs(params.args),
|
||||
)
|
||||
if (outcome.ok) {
|
||||
return { content: outcome.content, details: {} }
|
||||
}
|
||||
return {
|
||||
content: outcome.content,
|
||||
details: { error: 'tool_call_failed', tool, server: resolved.serverId },
|
||||
}
|
||||
}
|
||||
|
||||
// 4. describe
|
||||
if (describe) {
|
||||
const resolved = ctx.registry.findTool(
|
||||
describe,
|
||||
server ? ctx.serverIdByName.get(server) : undefined,
|
||||
)
|
||||
if (!resolved) {
|
||||
const suggestions = ctx.registry
|
||||
.rankSuggestions(describe, 5, ctx.serverNameById)
|
||||
.slice(0, 5)
|
||||
return notFoundResult(describe, suggestions, server)
|
||||
}
|
||||
const serverName = ctx.serverNameById.get(resolved.serverId) ?? resolved.serverId
|
||||
let text = `${resolved.tool.name}\nServer: ${serverName}\n\n${resolved.tool.description || '(no description)'}\n\n`
|
||||
text += renderToolShape(resolved.tool)
|
||||
return contentText(text.trim())
|
||||
}
|
||||
|
||||
// 4.5 instructions
|
||||
if (instructions) {
|
||||
const serverId = ctx.serverIdByName.get(instructions)
|
||||
if (!serverId) {
|
||||
return contentText(
|
||||
`Server "${instructions}" not found. Use mcp({ action: "status" }) to see available servers.`,
|
||||
)
|
||||
}
|
||||
const text = await ctx.getInstructions(serverId)
|
||||
if (!text || text.trim() === '') {
|
||||
return contentText(`Server "${instructions}" does not provide instructions.`)
|
||||
}
|
||||
return contentText(`${instructions} instructions:\n\n${text}`)
|
||||
}
|
||||
|
||||
// 5. search
|
||||
if (search) {
|
||||
if (search.trim().length === 0 && !server) {
|
||||
return contentText('Search query cannot be empty')
|
||||
}
|
||||
const serverId = server ? ctx.serverIdByName.get(server) : undefined
|
||||
if (server && !serverId) {
|
||||
return contentText(
|
||||
`Server "${server}" not found. Use mcp({ action: "status" }) to see available servers.`,
|
||||
)
|
||||
}
|
||||
const { items, total, hasMore, nextOffset } = ctx.registry.searchTools(
|
||||
search,
|
||||
serverId,
|
||||
ctx.serverNameById,
|
||||
limit,
|
||||
offset,
|
||||
)
|
||||
if (total === 0) {
|
||||
return contentText(
|
||||
`No tools matching "${search}"${server ? ` in "${server}"` : ''}. Use mcp({ action: "status" }) to check connection state.`,
|
||||
)
|
||||
}
|
||||
let text = `Found ${total} tool${total === 1 ? '' : 's'} matching "${search}":\n\n`
|
||||
for (const match of items) {
|
||||
const serverName = ctx.serverNameById.get(match.server) ?? match.server
|
||||
text += `${match.tool.name} (server: ${serverName})\n`
|
||||
text += ` ${match.tool.description || '(no description)'}\n`
|
||||
if (includeSchemas && match.tool.inputSchema) {
|
||||
text += ` ${renderToolShape(match.tool, ' ')}\n`
|
||||
}
|
||||
text += '\n'
|
||||
}
|
||||
if (hasMore) {
|
||||
text += `${items.length} of ${total} — offset: ${nextOffset} for more\n`
|
||||
}
|
||||
return contentText(text.trim())
|
||||
}
|
||||
|
||||
// 6. server list
|
||||
if (server) {
|
||||
const serverId = ctx.serverIdByName.get(server)
|
||||
if (!serverId) {
|
||||
return contentText(
|
||||
`Server "${server}" not found. Use mcp({ action: "status" }) to see available servers.`,
|
||||
)
|
||||
}
|
||||
const tools = ctx.registry.getTools(serverId)
|
||||
if (tools.length === 0) {
|
||||
return contentText(
|
||||
`Server "${server}" has no cached tools yet. Call a tool on this server to connect automatically, or refresh it in Settings → MCP.`,
|
||||
)
|
||||
}
|
||||
const instructionsText = await ctx.getInstructions(serverId)
|
||||
return contentText(renderServerListing(server, tools, instructionsText))
|
||||
}
|
||||
|
||||
// 7. default: status
|
||||
const lines: string[] = ['MCP status:']
|
||||
for (const s of ctx.servers) {
|
||||
const auth = await ctx.authStatus(s.id)
|
||||
lines.push(` - ${s.name}: ${s.status} (${s.toolCount} tools, auth: ${auth})`)
|
||||
}
|
||||
lines.push('')
|
||||
lines.push('mcp({ server: "name" }) to list tools, mcp({ search: "..." }) to search')
|
||||
return contentText(lines.join('\n'))
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
/**
|
||||
* MCP Server Manager
|
||||
*
|
||||
* Manages MCP client connections to URL-based servers (Streamable HTTP with
|
||||
* SSE fallback, or pinned SSE). Simplified port of pi-mcp-adapter's
|
||||
* server-manager.ts: tools only, no stdio/sampling/elicitation/tracing.
|
||||
*/
|
||||
|
||||
import {
|
||||
Client,
|
||||
SdkHttpError,
|
||||
SSEClientTransport,
|
||||
StreamableHTTPClientTransport,
|
||||
UnauthorizedError,
|
||||
type Implementation,
|
||||
type ListToolsResult,
|
||||
type RequestOptions,
|
||||
type VersionNegotiationOptions,
|
||||
} from '@modelcontextprotocol/client'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import type { McpDbStore } from './mcp-db-store'
|
||||
import { McpOauthProvider, type McpOauthConfig } from './mcp-oauth-provider'
|
||||
|
||||
export interface McpTool {
|
||||
name: string
|
||||
title?: string
|
||||
description?: string
|
||||
inputSchema?: unknown
|
||||
_meta?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface ServerConnection {
|
||||
client: Client
|
||||
definition: McpServerDefinition
|
||||
tools: McpTool[]
|
||||
status: 'connected' | 'needs-auth'
|
||||
/** Self-reported server name/title/version/description (from getServerVersion). */
|
||||
serverVersion?: Implementation
|
||||
/** Self-reported server usage instructions (from getInstructions). */
|
||||
instructions?: string
|
||||
lastUsedAt: number
|
||||
inFlight: number
|
||||
}
|
||||
|
||||
export interface McpServerDefinition {
|
||||
name: string
|
||||
url: string
|
||||
transport: 'streamable_http' | 'sse'
|
||||
authConfig?: PrismaJson.McpServerAuthConfig
|
||||
config?: PrismaJson.McpServerConfig
|
||||
}
|
||||
|
||||
function isUnauthorizedHttpError(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof UnauthorizedError || (error instanceof SdkHttpError && error.status === 401)
|
||||
)
|
||||
}
|
||||
|
||||
function shouldFallbackToSse(error: unknown, definition: McpServerDefinition): boolean {
|
||||
if (definition.config?.protocolVersion === '2026-07-28') return false
|
||||
return error instanceof SdkHttpError && [404, 405, 406, 415].includes(error.status)
|
||||
}
|
||||
|
||||
function resolveVersionNegotiation(
|
||||
definition: McpServerDefinition,
|
||||
): VersionNegotiationOptions | undefined {
|
||||
switch (definition.config?.protocolVersion) {
|
||||
case undefined:
|
||||
case 'legacy':
|
||||
return undefined
|
||||
case 'auto':
|
||||
return { mode: 'auto' }
|
||||
case '2026-07-28':
|
||||
return { mode: { pin: '2026-07-28' } }
|
||||
default:
|
||||
throw new Error(`Invalid MCP protocolVersion: ${String(definition.config?.protocolVersion)}`)
|
||||
}
|
||||
}
|
||||
|
||||
export class McpServerManager {
|
||||
private connections = new Map<string, ServerConnection>()
|
||||
private connectPromises = new Map<string, Promise<ServerConnection>>()
|
||||
private stopped = false
|
||||
|
||||
constructor(private readonly dbStore: McpDbStore) {}
|
||||
|
||||
private getRequestTimeoutMs(definition: McpServerDefinition): number | undefined {
|
||||
const timeout = definition.config?.requestTimeoutMs
|
||||
return typeof timeout === 'number' && Number.isFinite(timeout) && timeout > 0
|
||||
? timeout
|
||||
: undefined
|
||||
}
|
||||
|
||||
private buildRequestOptions(definition: McpServerDefinition): RequestOptions | undefined {
|
||||
const timeout = this.getRequestTimeoutMs(definition)
|
||||
return timeout !== undefined ? { timeout } : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to a server. Single-flight per server id. Returns a connection
|
||||
* with status 'connected' or 'needs-auth' (when the server returns 401 and
|
||||
* OAuth is configured / auto-detectable).
|
||||
*/
|
||||
async connect(serverId: string, definition: McpServerDefinition): Promise<ServerConnection> {
|
||||
if (this.stopped) throw new Error('MCP server manager is closed')
|
||||
|
||||
// Dedupe concurrent connection attempts.
|
||||
if (this.connectPromises.has(serverId)) {
|
||||
return this.connectPromises.get(serverId)!
|
||||
}
|
||||
|
||||
const existing = this.connections.get(serverId)
|
||||
if (existing?.status === 'connected') {
|
||||
existing.lastUsedAt = Date.now()
|
||||
return existing
|
||||
}
|
||||
|
||||
const promise = this.createConnection(serverId, definition).finally(() => {
|
||||
if (this.connectPromises.get(serverId) === promise) {
|
||||
this.connectPromises.delete(serverId)
|
||||
}
|
||||
})
|
||||
this.connectPromises.set(serverId, promise)
|
||||
|
||||
try {
|
||||
const connection = await promise
|
||||
this.connections.set(serverId, connection)
|
||||
return connection
|
||||
} catch (error) {
|
||||
this.connectPromises.delete(serverId)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private async createConnection(
|
||||
serverId: string,
|
||||
definition: McpServerDefinition,
|
||||
): Promise<ServerConnection> {
|
||||
const url = new URL(definition.url)
|
||||
const requestInit = this.buildRequestInit(definition)
|
||||
const authProvider = this.buildAuthProvider(serverId, definition)
|
||||
|
||||
const attempt = async (
|
||||
kind: 'streamable-http' | 'sse',
|
||||
): Promise<{
|
||||
status: 'connected' | 'needs-auth'
|
||||
client: Client
|
||||
error?: unknown
|
||||
}> => {
|
||||
const transportOptions = {
|
||||
...(requestInit !== undefined ? { requestInit } : {}),
|
||||
...(authProvider !== undefined ? { authProvider } : {}),
|
||||
...(authProvider !== undefined &&
|
||||
definition.authConfig?.oauth?.skipIssuerMetadataValidation === true
|
||||
? { skipIssuerMetadataValidation: true }
|
||||
: {}),
|
||||
}
|
||||
const transport =
|
||||
kind === 'streamable-http'
|
||||
? new StreamableHTTPClientTransport(url, transportOptions)
|
||||
: new SSEClientTransport(url, transportOptions)
|
||||
const client = this.createClient(serverId, definition)
|
||||
|
||||
try {
|
||||
await client.connect(transport, this.buildRequestOptions(definition))
|
||||
return { status: 'connected', client }
|
||||
} catch (error) {
|
||||
try {
|
||||
await client.close()
|
||||
} catch {
|
||||
// Ignore cleanup errors on a failed connect.
|
||||
}
|
||||
return { status: 'needs-auth', client, error }
|
||||
}
|
||||
}
|
||||
|
||||
let kind: 'streamable-http' | 'sse' = definition.transport === 'sse' ? 'sse' : 'streamable-http'
|
||||
for (;;) {
|
||||
const result = await attempt(kind)
|
||||
if (result.status === 'connected') {
|
||||
const tools = await this.fetchAllTools(result.client, this.buildRequestOptions(definition))
|
||||
return {
|
||||
client: result.client,
|
||||
definition,
|
||||
tools,
|
||||
status: 'connected',
|
||||
serverVersion: result.client.getServerVersion(),
|
||||
instructions: result.client.getInstructions(),
|
||||
lastUsedAt: Date.now(),
|
||||
inFlight: 0,
|
||||
}
|
||||
}
|
||||
|
||||
if (isUnauthorizedHttpError(result.error)) {
|
||||
if (this.supportsOauth(definition)) {
|
||||
return {
|
||||
client: result.client,
|
||||
definition,
|
||||
tools: [],
|
||||
status: 'needs-auth',
|
||||
lastUsedAt: Date.now(),
|
||||
inFlight: 0,
|
||||
}
|
||||
}
|
||||
throw result.error
|
||||
}
|
||||
|
||||
if (
|
||||
kind === 'streamable-http' &&
|
||||
definition.transport !== 'sse' &&
|
||||
shouldFallbackToSse(result.error, definition)
|
||||
) {
|
||||
kind = 'sse'
|
||||
continue
|
||||
}
|
||||
throw result.error
|
||||
}
|
||||
}
|
||||
|
||||
private createClient(serverId: string, definition: McpServerDefinition): Client {
|
||||
const versionNegotiation = resolveVersionNegotiation(definition)
|
||||
return new Client(
|
||||
{ name: `shumai-mcp-${serverId}`, version: '1.0.0' },
|
||||
{
|
||||
...(versionNegotiation ? { versionNegotiation } : {}),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private buildAuthProvider(
|
||||
serverId: string,
|
||||
definition: McpServerDefinition,
|
||||
): McpOauthProvider | undefined {
|
||||
if (this.supportsOauth(definition)) {
|
||||
return new McpOauthProvider(
|
||||
serverId,
|
||||
definition.url,
|
||||
this.extractOauthConfig(definition.authConfig ?? {}),
|
||||
{ onRedirect: async () => {} },
|
||||
this.dbStore,
|
||||
)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
private supportsOauth(definition: McpServerDefinition): boolean {
|
||||
const auth = definition.authConfig
|
||||
if (auth?.type === 'none') return false
|
||||
if (auth?.type === 'bearer') return false
|
||||
// Explicit oauth, or auto-detect when no auth configured and no custom headers.
|
||||
if (auth?.type === 'oauth') return true
|
||||
if (auth?.headers && Object.keys(auth.headers).length > 0) return false
|
||||
return auth === undefined || auth.type === undefined
|
||||
}
|
||||
|
||||
private extractOauthConfig(auth: PrismaJson.McpServerAuthConfig): McpOauthConfig {
|
||||
const oauth = auth.oauth
|
||||
if (!oauth) return {}
|
||||
return {
|
||||
...(oauth.grantType !== undefined ? { grantType: oauth.grantType } : {}),
|
||||
...(oauth.clientId !== undefined ? { clientId: oauth.clientId } : {}),
|
||||
...(oauth.clientSecret !== undefined ? { clientSecret: oauth.clientSecret } : {}),
|
||||
...(oauth.scope !== undefined ? { scope: oauth.scope } : {}),
|
||||
...(oauth.authorizationParams !== undefined
|
||||
? { authorizationParams: oauth.authorizationParams }
|
||||
: {}),
|
||||
...(oauth.redirectUri !== undefined ? { redirectUri: oauth.redirectUri } : {}),
|
||||
...(oauth.clientName !== undefined ? { clientName: oauth.clientName } : {}),
|
||||
...(oauth.clientUri !== undefined ? { clientUri: oauth.clientUri } : {}),
|
||||
...(oauth.skipIssuerMetadataValidation !== undefined
|
||||
? { skipIssuerMetadataValidation: oauth.skipIssuerMetadataValidation }
|
||||
: {}),
|
||||
}
|
||||
}
|
||||
|
||||
private buildRequestInit(
|
||||
definition: McpServerDefinition,
|
||||
): { headers: Record<string, string> } | undefined {
|
||||
const auth = definition.authConfig
|
||||
const headers: Record<string, string> = { ...(auth?.headers ?? {}) }
|
||||
if (auth?.type === 'bearer' && auth.bearerToken) {
|
||||
headers['Authorization'] = `Bearer ${auth.bearerToken}`
|
||||
}
|
||||
return Object.keys(headers).length > 0 ? { headers } : undefined
|
||||
}
|
||||
|
||||
private async fetchAllTools(client: Client, requestOptions?: RequestOptions): Promise<McpTool[]> {
|
||||
const allTools: McpTool[] = []
|
||||
let cursor: string | undefined
|
||||
|
||||
do {
|
||||
const result: ListToolsResult = await client.listTools(
|
||||
cursor ? { cursor } : undefined,
|
||||
requestOptions,
|
||||
)
|
||||
allTools.push(...(result.tools ?? []))
|
||||
cursor = result.nextCursor
|
||||
} while (cursor)
|
||||
|
||||
return allTools
|
||||
}
|
||||
|
||||
/** List tools for a connected server. */
|
||||
async listTools(serverId: string): Promise<McpTool[]> {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (!connection || connection.status !== 'connected') {
|
||||
throw new Error(`Server is not connected`)
|
||||
}
|
||||
return connection.tools
|
||||
}
|
||||
|
||||
/** Call a tool on a connected server. */
|
||||
async callTool(
|
||||
serverId: string,
|
||||
toolName: string,
|
||||
args: Record<string, unknown>,
|
||||
): Promise<{
|
||||
content: McpContent[]
|
||||
structuredContent?: Record<string, unknown>
|
||||
isError?: boolean
|
||||
}> {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (!connection || connection.status !== 'connected') {
|
||||
throw new Error(`Server is not connected`)
|
||||
}
|
||||
this.incrementInFlight(serverId)
|
||||
try {
|
||||
this.touch(serverId)
|
||||
const result = await connection.client.callTool(
|
||||
{ name: toolName, arguments: args },
|
||||
this.buildRequestOptions(connection.definition),
|
||||
)
|
||||
return {
|
||||
content: (result.content ?? []) as McpContent[],
|
||||
structuredContent: result.structuredContent as Record<string, unknown> | undefined,
|
||||
isError: result.isError,
|
||||
}
|
||||
} finally {
|
||||
this.decrementInFlight(serverId)
|
||||
this.touch(serverId)
|
||||
}
|
||||
}
|
||||
|
||||
incrementInFlight(serverId: string): void {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (connection) {
|
||||
connection.inFlight = (connection.inFlight ?? 0) + 1
|
||||
}
|
||||
}
|
||||
|
||||
decrementInFlight(serverId: string): void {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (connection && connection.inFlight > 0) {
|
||||
connection.inFlight--
|
||||
}
|
||||
}
|
||||
|
||||
isIdle(serverId: string, timeoutMs: number): boolean {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (!connection || connection.status !== 'connected') return false
|
||||
if (connection.inFlight > 0) return false
|
||||
return Date.now() - connection.lastUsedAt > timeoutMs
|
||||
}
|
||||
|
||||
async closeIdleConnections(defaultTimeoutMs = 10 * 60 * 1000): Promise<string[]> {
|
||||
const closedIds: string[] = []
|
||||
for (const [serverId, connection] of this.connections) {
|
||||
if (connection.definition.config?.keepAlive) continue
|
||||
const timeoutMs = connection.definition.config?.idleTimeoutMs ?? defaultTimeoutMs
|
||||
if (this.isIdle(serverId, timeoutMs)) {
|
||||
await this.close(serverId)
|
||||
closedIds.push(serverId)
|
||||
}
|
||||
}
|
||||
return closedIds
|
||||
}
|
||||
|
||||
touch(serverId: string): void {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (connection) {
|
||||
connection.lastUsedAt = Date.now()
|
||||
}
|
||||
}
|
||||
|
||||
getConnection(serverId: string): ServerConnection | undefined {
|
||||
return this.connections.get(serverId)
|
||||
}
|
||||
|
||||
getAllConnections(): Map<string, ServerConnection> {
|
||||
return new Map(this.connections)
|
||||
}
|
||||
|
||||
async close(serverId: string): Promise<void> {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (!connection) {
|
||||
const pending = this.connectPromises.get(serverId)
|
||||
if (pending) {
|
||||
try {
|
||||
await pending
|
||||
} catch {
|
||||
// Ignore failed connect during close.
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
this.connections.delete(serverId)
|
||||
try {
|
||||
await connection.client.close()
|
||||
} catch (error) {
|
||||
logger.debug({ serverId, error }, 'MCP client close failed')
|
||||
}
|
||||
}
|
||||
|
||||
async closeAll(): Promise<void> {
|
||||
const ids = [...this.connections.keys()]
|
||||
await Promise.allSettled(ids.map((id) => this.close(id)))
|
||||
this.connections.clear()
|
||||
this.connectPromises.clear()
|
||||
// The manager stays usable afterwards (tests reset between suites);
|
||||
// `stopped` only guards against using a permanently-shut-down manager.
|
||||
this.stopped = false
|
||||
}
|
||||
|
||||
isConnecting(serverId: string): boolean {
|
||||
return this.connectPromises.has(serverId)
|
||||
}
|
||||
}
|
||||
|
||||
export interface McpContent {
|
||||
type: 'text' | 'image' | 'audio' | 'resource' | 'resource_link'
|
||||
text?: string
|
||||
data?: string
|
||||
mimeType?: string
|
||||
resource?: {
|
||||
uri: string
|
||||
text?: string
|
||||
blob?: string
|
||||
}
|
||||
uri?: string
|
||||
name?: string
|
||||
description?: string
|
||||
}
|
||||
@@ -0,0 +1,990 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { McpService } from './mcp-service'
|
||||
import {
|
||||
startTestMcpServer,
|
||||
standardTestTools,
|
||||
type RunningTestMcpServer,
|
||||
type TestMcpToolDef,
|
||||
} from './mcp-test-server'
|
||||
|
||||
async function seedAgentAndUser(teamId: string, agentName: string) {
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: agentName,
|
||||
email: `${agentName.toLowerCase().replace(/\s+/g, '-')}@shumai.ai`,
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({ data: { teamId, userId: user.id, role: 'editor' } })
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: user.id,
|
||||
teamId,
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
config: { provider: 'openai', model: 'gpt-4' },
|
||||
},
|
||||
})
|
||||
return agent
|
||||
}
|
||||
|
||||
const TAVILY_TOOLS: TestMcpToolDef[] = [
|
||||
{
|
||||
name: 'tavily_search',
|
||||
description: 'Search the web for the latest information',
|
||||
handler: async () => 'tavily-search-result',
|
||||
},
|
||||
{
|
||||
name: 'tavily_research',
|
||||
description: 'Run deep multi-step research',
|
||||
handler: async () => 'tavily-research-result',
|
||||
},
|
||||
]
|
||||
|
||||
const AIRTABLE_TOOLS: TestMcpToolDef[] = [
|
||||
{
|
||||
name: 'search_records',
|
||||
description: 'Search Airtable records',
|
||||
handler: async () => 'AIRTABLE-SECRET-DATA',
|
||||
},
|
||||
{
|
||||
name: 'search_bases',
|
||||
description: 'Search Airtable bases',
|
||||
handler: async () => 'airtable-bases',
|
||||
},
|
||||
{
|
||||
name: 'search_candidate_linked_records',
|
||||
description: 'Search candidate linked records',
|
||||
handler: async () => 'airtable-candidates',
|
||||
},
|
||||
]
|
||||
|
||||
type ProxyExecute = (
|
||||
id: string,
|
||||
params: unknown,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
|
||||
describe('McpService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let teamId: string
|
||||
let srv: RunningTestMcpServer
|
||||
const service = new McpService()
|
||||
|
||||
beforeAll(async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'MCP Service Team' } })
|
||||
teamId = team.id
|
||||
srv = await startTestMcpServer({ tools: standardTestTools() })
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await srv.stop()
|
||||
await service.closeAllConnections()
|
||||
})
|
||||
|
||||
/** Seed an agent with one assigned server (tavily) and one discovered but unassigned server (airtable). */
|
||||
async function seedAgentWithUnassignedServer() {
|
||||
const agent = await seedAgentAndUser(teamId, 'Leak Guard Agent')
|
||||
const tavilySrv = await startTestMcpServer({
|
||||
tools: TAVILY_TOOLS,
|
||||
serverInfo: { name: 'tavily-mcp' },
|
||||
})
|
||||
const airtableSrv = await startTestMcpServer({
|
||||
tools: AIRTABLE_TOOLS,
|
||||
serverInfo: { name: 'airtable-mcp-server' },
|
||||
})
|
||||
const tavily = await service.createServer(teamId, { url: tavilySrv.url })
|
||||
const airtable = await service.createServer(teamId, { url: airtableSrv.url })
|
||||
await service.refreshServer(tavily.id)
|
||||
await service.refreshServer(airtable.id)
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: tavily.id } })
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
return { agent, proxy: tools[0], tavily, airtable, tavilySrv, airtableSrv }
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// CRUD
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('creates, lists, reads and deletes servers (secrets masked)', async () => {
|
||||
const created = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'bearer', bearerToken: 'super-secret' },
|
||||
})
|
||||
// Name is derived from the URL until the server self-reports on connect.
|
||||
expect(created.name).toBe('localhost')
|
||||
expect(created.url).toBe(srv.url)
|
||||
expect(created.authType).toBe('bearer')
|
||||
expect(created.toolCount).toBe(0)
|
||||
// Secrets never leak into the DTO.
|
||||
expect(JSON.stringify(created)).not.toContain('super-secret')
|
||||
|
||||
const listed = await service.listServers(teamId)
|
||||
expect(listed.map((s) => s.name)).toContain('localhost')
|
||||
|
||||
const got = await service.getServer(created.id)
|
||||
expect(got?.id).toBe(created.id)
|
||||
|
||||
await service.deleteServer(created.id)
|
||||
const after = await service.listServers(teamId)
|
||||
expect(after.map((s) => s.name)).not.toContain('localhost')
|
||||
})
|
||||
|
||||
it('allows duplicate server names per team (name is auto-derived)', async () => {
|
||||
const a = await service.createServer(teamId, { url: srv.url })
|
||||
const b = await service.createServer(teamId, { url: srv.url })
|
||||
expect(a.name).toBe(b.name)
|
||||
expect(a.id).not.toBe(b.id)
|
||||
})
|
||||
|
||||
it('derives the name from the URL host when creating', async () => {
|
||||
const github = await service.createServer(teamId, { url: 'https://api.github.com/mcp' })
|
||||
expect(github.name).toBe('github')
|
||||
|
||||
const example = await service.createServer(teamId, { url: 'https://mcp.example.com/sse' })
|
||||
expect(example.name).toBe('example')
|
||||
|
||||
const raw = await service.createServer(teamId, { url: 'not-a-url' })
|
||||
expect(raw.name).toBe('mcp-server')
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Discovery + tool calls against a real MCP server
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('refreshes a real MCP server and persists its tools', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'none' },
|
||||
})
|
||||
|
||||
const refreshed = await service.refreshServer(server.id)
|
||||
expect(refreshed.status).toBe('connected')
|
||||
expect(refreshed.toolCount).toBe(3)
|
||||
|
||||
const record = await service.getServerRecord(server.id)
|
||||
const names = ((record?.tools ?? []) as PrismaJson.McpToolInfo[]).map((t) => t.name).sort()
|
||||
expect(names).toEqual(['add', 'echo', 'list_sims'])
|
||||
|
||||
const updated = await service.getServer(server.id)
|
||||
expect(updated?.status).toBe('connected')
|
||||
expect(updated?.toolCount).toBe(3)
|
||||
expect(updated?.lastError).toBeUndefined()
|
||||
})
|
||||
|
||||
it('captures the server-reported name (title preferred) and description on discovery', async () => {
|
||||
const metaSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: {
|
||||
name: 'meta-srv',
|
||||
title: 'Meta Server',
|
||||
description: 'A server with rich metadata',
|
||||
},
|
||||
})
|
||||
try {
|
||||
const server = await service.createServer(teamId, { url: metaSrv.url })
|
||||
expect(server.name).toBe('localhost') // derived placeholder before discovery
|
||||
|
||||
await service.refreshServer(server.id)
|
||||
|
||||
const updated = await service.getServer(server.id)
|
||||
expect(updated?.name).toBe('Meta Server') // title wins over name
|
||||
expect(updated?.description).toBe('A server with rich metadata')
|
||||
|
||||
// The display name (title) flows into tool-name prefixes used by the
|
||||
// proxy registry, which is warmed from the persisted DB cache.
|
||||
const agent = await seedAgentAndUser(teamId, 'Meta Name Agent')
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
const agentTools = await service.buildAgentTools(agent.id, teamId)
|
||||
const search = await (agentTools[0].execute as ProxyExecute)('meta-1', { search: 'echo' })
|
||||
expect(JSON.stringify(search.content)).toContain('Meta_Server_echo')
|
||||
} finally {
|
||||
await metaSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('captures and persists server-reported instructions on discovery', async () => {
|
||||
const instSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: {
|
||||
name: 'inst-srv',
|
||||
instructions: 'Do not mutate production data. Always confirm destructive operations.',
|
||||
},
|
||||
})
|
||||
try {
|
||||
const server = await service.createServer(teamId, { url: instSrv.url })
|
||||
await service.refreshServer(server.id)
|
||||
|
||||
const updated = await service.getServer(server.id)
|
||||
expect(updated?.instructions).toBe(
|
||||
'Do not mutate production data. Always confirm destructive operations.',
|
||||
)
|
||||
} finally {
|
||||
await instSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('clears persisted instructions when a reconnected server stops reporting them', async () => {
|
||||
const instSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: {
|
||||
name: 'clear-srv',
|
||||
instructions: 'Temporary guidance that will disappear.',
|
||||
},
|
||||
})
|
||||
try {
|
||||
const server = await service.createServer(teamId, { url: instSrv.url })
|
||||
await service.refreshServer(server.id)
|
||||
expect((await service.getServer(server.id))?.instructions).toBe(
|
||||
'Temporary guidance that will disappear.',
|
||||
)
|
||||
|
||||
await service.closeAllConnections()
|
||||
await instSrv.stop()
|
||||
// Same URL, but the server now reports no instructions: the cached
|
||||
// value is cleared on the next successful connect.
|
||||
const bareSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'clear-srv' },
|
||||
port: instSrv.port,
|
||||
})
|
||||
try {
|
||||
await service.refreshServer(server.id)
|
||||
expect((await service.getServer(server.id))?.instructions).toBeUndefined()
|
||||
} finally {
|
||||
await bareSrv.stop()
|
||||
}
|
||||
} finally {
|
||||
await instSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('refreshServer force-reconnects and picks up updated instructions', async () => {
|
||||
const instSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'reload-srv', instructions: 'Old instructions.' },
|
||||
})
|
||||
try {
|
||||
const server = await service.createServer(teamId, { url: instSrv.url })
|
||||
await service.refreshServer(server.id)
|
||||
expect((await service.getServer(server.id))?.instructions).toBe('Old instructions.')
|
||||
expect(service.getConnectionCount(server.id)).toBe(1)
|
||||
|
||||
// The server restarts on the same URL with different instructions: a
|
||||
// refresh must force a fresh connection and re-persist the new value.
|
||||
await instSrv.stop()
|
||||
const reloadedSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'reload-srv', instructions: 'New instructions.' },
|
||||
port: instSrv.port,
|
||||
})
|
||||
try {
|
||||
const refreshed = await service.refreshServer(server.id)
|
||||
expect(refreshed.instructions).toBe('New instructions.')
|
||||
expect((await service.getServer(server.id))?.instructions).toBe('New instructions.')
|
||||
} finally {
|
||||
await reloadedSrv.stop()
|
||||
}
|
||||
} finally {
|
||||
await instSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('refreshServer re-populates tools that were cleared from the cache', async () => {
|
||||
const server = await service.createServer(teamId, { url: srv.url })
|
||||
await service.refreshServer(server.id)
|
||||
expect((await service.getServer(server.id))?.toolCount).toBe(3)
|
||||
|
||||
// Simulate a cache wipe (e.g. an auth/transport invalidation).
|
||||
await prisma.mcpServer.update({
|
||||
where: { id: server.id },
|
||||
data: { tools: [], status: 'not_connected' },
|
||||
})
|
||||
expect((await service.getServer(server.id))?.toolCount).toBe(0)
|
||||
|
||||
const refreshed = await service.refreshServer(server.id)
|
||||
expect(refreshed.toolCount).toBe(3)
|
||||
expect((await service.getServer(server.id))?.toolCount).toBe(3)
|
||||
})
|
||||
|
||||
it('surfaces server instructions at all three levels (snippet, preview, full text)', async () => {
|
||||
const instructionsText =
|
||||
'Never run destructive queries against the production database. Always operate in the ' +
|
||||
'read-only sandbox environment by default. Confirm any irreversible operation with the ' +
|
||||
'user before executing. Use the internal staging mirror for heavy analytical workloads ' +
|
||||
'and keep result sets small to avoid timeouts. Rate limits apply per account, so batch ' +
|
||||
'requests conservatively and respect the 429 backoff guidance.'
|
||||
const instSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'inst-srv', instructions: instructionsText },
|
||||
})
|
||||
try {
|
||||
const server = await service.createServer(teamId, { url: instSrv.url })
|
||||
await service.refreshServer(server.id)
|
||||
|
||||
const agent = await seedAgentAndUser(teamId, 'Instructions Agent')
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
const proxy = tools[0]
|
||||
|
||||
// L1: truncated snippet in the proxy tool description (no call needed).
|
||||
expect(proxy.description).toContain('Server instructions (truncated')
|
||||
expect(proxy.description).toContain('inst-srv:')
|
||||
expect(proxy.description).toContain('mcp({ instructions: "name" })')
|
||||
expect(proxy.description).not.toContain(instructionsText)
|
||||
|
||||
// L2: longer preview at the end of the server listing + full-text hint.
|
||||
const list = await (proxy.execute as ProxyExecute)('list-1', { server: 'inst-srv' })
|
||||
const listText = JSON.stringify(list.content)
|
||||
expect(listText).toContain('Server instructions:')
|
||||
expect(listText).toContain('for the full text')
|
||||
expect(listText).not.toContain(instructionsText)
|
||||
|
||||
// L3: full text via the instructions mode.
|
||||
const full = await (proxy.execute as ProxyExecute)('inst-1', { instructions: 'inst-srv' })
|
||||
const fullText = JSON.stringify(full.content)
|
||||
expect(fullText).toContain(instructionsText)
|
||||
expect(fullText).toContain('inst-srv instructions:')
|
||||
} finally {
|
||||
await instSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('reports when a server provides no instructions', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'No Instructions Agent')
|
||||
const server = await service.createServer(teamId, { url: srv.url })
|
||||
await service.refreshServer(server.id)
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
const proxy = tools[0]
|
||||
|
||||
// No L1 block, no L2 preview, and L3 says so explicitly.
|
||||
expect(proxy.description).not.toContain('Server instructions (truncated')
|
||||
const list = await (proxy.execute as ProxyExecute)('list-1', { server: 'test-mcp-server' })
|
||||
expect(JSON.stringify(list.content)).not.toContain('Server instructions:')
|
||||
const full = await (proxy.execute as ProxyExecute)('inst-1', {
|
||||
instructions: 'test-mcp-server',
|
||||
})
|
||||
expect(JSON.stringify(full.content)).toContain('does not provide instructions')
|
||||
})
|
||||
|
||||
it('keeps instructions available without a live connection (DB cache)', async () => {
|
||||
const instSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'cache-srv', instructions: 'Always use the read-only API.' },
|
||||
})
|
||||
try {
|
||||
const server = await service.createServer(teamId, { url: instSrv.url })
|
||||
await service.refreshServer(server.id)
|
||||
await service.closeAllConnections()
|
||||
expect(service.getConnectionCount(server.id)).toBe(0)
|
||||
|
||||
const agent = await seedAgentAndUser(teamId, 'Cache Agent')
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
const full = await (tools[0].execute as ProxyExecute)('inst-1', {
|
||||
instructions: 'cache-srv',
|
||||
})
|
||||
expect(JSON.stringify(full.content)).toContain('Always use the read-only API.')
|
||||
} finally {
|
||||
await instSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('falls back to the reported name when no title is provided', async () => {
|
||||
const server = await service.createServer(teamId, { url: srv.url })
|
||||
await service.refreshServer(server.id)
|
||||
const updated = await service.getServer(server.id)
|
||||
expect(updated?.name).toBe('test-mcp-server')
|
||||
})
|
||||
|
||||
it('calls a tool through callMcpTool and returns content', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'none' },
|
||||
})
|
||||
const result = await service.callMcpTool(server.id, 'echo', { text: 'roundtrip' }, { teamId })
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.content[0]).toMatchObject({ type: 'text', text: 'echo:roundtrip' })
|
||||
expect((result.content[0] as { text?: string }).text).toBe('echo:roundtrip')
|
||||
|
||||
const structured = await service.callMcpTool(server.id, 'add', { a: 4, b: 6 }, { teamId })
|
||||
expect(structured.ok).toBe(true)
|
||||
expect(JSON.stringify(structured.content)).toContain('10')
|
||||
})
|
||||
|
||||
it('surfaces server failures as error text (non-fatal)', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: 'http://localhost:1/mcp', // nothing listens here
|
||||
authConfig: { type: 'none' },
|
||||
})
|
||||
const result = await service.callMcpTool(server.id, 'echo', { text: 'x' }, { teamId })
|
||||
expect(result.ok).toBe(false)
|
||||
expect((result.content[0] as { text?: string }).text).toContain('Failed to connect')
|
||||
const updated = await service.getServer(server.id)
|
||||
expect(updated?.status).toBe('failed')
|
||||
expect(updated?.lastError).toBeTruthy()
|
||||
})
|
||||
|
||||
it('requires authentication via bearer token', async () => {
|
||||
const authSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
bearerToken: 'tok-123',
|
||||
})
|
||||
try {
|
||||
const wrong = await service.createServer(teamId, {
|
||||
url: authSrv.url,
|
||||
authConfig: { type: 'bearer', bearerToken: 'wrong-token' },
|
||||
})
|
||||
const result = await service.callMcpTool(wrong.id, 'echo', { text: 'x' }, { teamId })
|
||||
expect(result.ok).toBe(false)
|
||||
|
||||
const right = await service.createServer(teamId, {
|
||||
url: authSrv.url,
|
||||
authConfig: { type: 'bearer', bearerToken: 'tok-123' },
|
||||
})
|
||||
const ok = await service.callMcpTool(right.id, 'echo', { text: 'secret' }, { teamId })
|
||||
expect(ok.ok).toBe(true)
|
||||
expect((ok.content[0] as { text?: string }).text).toBe('echo:secret')
|
||||
} finally {
|
||||
await authSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// URL invalidation
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('transport change clears cached tools, credentials and the connection', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'none' },
|
||||
})
|
||||
await service.refreshServer(server.id)
|
||||
expect((await service.getServer(server.id))?.toolCount).toBe(3)
|
||||
|
||||
// The endpoint URL is immutable; a transport change invalidates the
|
||||
// cached tools + connection (and would wipe credentials).
|
||||
await service.updateServer(server.id, { transport: 'sse' })
|
||||
|
||||
const updated = await service.getServer(server.id)
|
||||
expect(updated?.transport).toBe('sse')
|
||||
expect(updated?.toolCount).toBe(0)
|
||||
expect(updated?.status).toBe('not_connected')
|
||||
expect(service.getConnectionCount(server.id)).toBe(0)
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Permission gating (D10)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('denies tool calls below the server permission and allows above it', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
permission: 'editor', // reviewers are denied
|
||||
})
|
||||
|
||||
// Reviewer user is denied.
|
||||
const reviewer = await prisma.user.create({
|
||||
data: { name: 'Reviewer', email: 'reviewer@shumai.ai', type: 'human' },
|
||||
})
|
||||
await prisma.teamMember.create({ data: { teamId, userId: reviewer.id, role: 'reviewer' } })
|
||||
|
||||
const denied = await service.callMcpTool(
|
||||
server.id,
|
||||
'echo',
|
||||
{ text: 'x' },
|
||||
{ teamId, userId: reviewer.id },
|
||||
)
|
||||
expect(denied.ok).toBe(false)
|
||||
expect((denied.content[0] as { text?: string }).text).toContain('Permission denied')
|
||||
|
||||
// Editor user is allowed.
|
||||
const editor = await prisma.user.create({
|
||||
data: { name: 'Editor', email: 'editor@shumai.ai', type: 'human' },
|
||||
})
|
||||
await prisma.teamMember.create({ data: { teamId, userId: editor.id, role: 'editor' } })
|
||||
const allowed = await service.callMcpTool(
|
||||
server.id,
|
||||
'echo',
|
||||
{ text: 'ok' },
|
||||
{ teamId, userId: editor.id },
|
||||
)
|
||||
expect(allowed.ok).toBe(true)
|
||||
})
|
||||
|
||||
it('denies calls without user context when permission is above reviewer', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
permission: 'editor',
|
||||
})
|
||||
const denied = await service.callMcpTool(server.id, 'echo', { text: 'x' }, { teamId })
|
||||
expect(denied.ok).toBe(false)
|
||||
expect((denied.content[0] as { text?: string }).text).toContain('User context required')
|
||||
})
|
||||
|
||||
it('allows calls without user context at reviewer permission', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
permission: 'reviewer',
|
||||
})
|
||||
const allowed = await service.callMcpTool(server.id, 'echo', { text: 'x' }, { teamId })
|
||||
expect(allowed.ok).toBe(true)
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Per-agent assignment (D6)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('returns [] for agents without assigned MCP servers', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'No MCP Agent')
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
expect(tools).toEqual([])
|
||||
})
|
||||
|
||||
it('builds the proxy tool for assigned servers', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'Proxy Agent')
|
||||
const server = await service.createServer(teamId, { url: srv.url })
|
||||
await service.refreshServer(server.id)
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId, undefined)
|
||||
expect(tools.length).toBe(1)
|
||||
expect(tools[0].name).toBe('mcp')
|
||||
expect(tools[0].description).toContain('test-mcp-server')
|
||||
|
||||
// Executing the proxy's call mode hits the real server.
|
||||
const result = await (
|
||||
tools[0].execute as (
|
||||
id: string,
|
||||
params: unknown,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('call-1', { server: 'test-mcp-server', tool: 'echo', args: { text: 'via-proxy' } })
|
||||
expect(JSON.stringify(result.content)).toContain('echo:via-proxy')
|
||||
})
|
||||
|
||||
it('only includes assigned servers in the agent tools', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'Assigned Only Agent')
|
||||
const assignedSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'assigned-srv' },
|
||||
})
|
||||
const unassignedSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'unassigned-srv' },
|
||||
})
|
||||
try {
|
||||
const assigned = await service.createServer(teamId, { url: assignedSrv.url })
|
||||
const unassigned = await service.createServer(teamId, { url: unassignedSrv.url })
|
||||
await service.refreshServer(assigned.id)
|
||||
await service.refreshServer(unassigned.id)
|
||||
await prisma.agentMcpServer.create({
|
||||
data: { agentId: agent.id, mcpServerId: assigned.id },
|
||||
})
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
expect(tools.length).toBe(1)
|
||||
expect(tools[0].description).toContain('assigned-srv')
|
||||
expect(tools[0].description).not.toContain('unassigned-srv')
|
||||
} finally {
|
||||
await assignedSrv.stop()
|
||||
await unassignedSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not leak unassigned server tools in "Did you mean" suggestions', async () => {
|
||||
const { proxy, tavilySrv, airtableSrv } = await seedAgentWithUnassignedServer()
|
||||
try {
|
||||
// The agent only has tavily assigned. Asking for a tool that does not
|
||||
// exist on tavily must not surface airtable's tool names as suggestions.
|
||||
const result = await (proxy.execute as ProxyExecute)('leak-1', {
|
||||
server: 'tavily-mcp',
|
||||
tool: 'search',
|
||||
})
|
||||
const text = JSON.stringify(result.content)
|
||||
expect(text).toContain('Did you mean')
|
||||
expect(text).not.toContain('airtable')
|
||||
expect(text).not.toContain('search_records')
|
||||
} finally {
|
||||
await tavilySrv.stop()
|
||||
await airtableSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not resolve, search or describe tools of unassigned servers', async () => {
|
||||
const { proxy, tavilySrv, airtableSrv } = await seedAgentWithUnassignedServer()
|
||||
try {
|
||||
const execute = proxy.execute as ProxyExecute
|
||||
|
||||
// 1. Direct tool call with the unassigned server's prefixed tool name
|
||||
// (no server param) must not execute airtable's handler.
|
||||
const call = await execute('leak-2', { tool: 'airtable_mcp_server_search_records' })
|
||||
expect(JSON.stringify(call.content)).not.toContain('AIRTABLE-SECRET-DATA')
|
||||
|
||||
// 2. Search must not surface unassigned server tools.
|
||||
const search = await execute('leak-3', { search: 'records' })
|
||||
expect(JSON.stringify(search.content)).not.toContain('airtable')
|
||||
|
||||
// 3. Describe must not leak unassigned server tool schemas (the
|
||||
// not-found reply may echo the tool name the model passed, but never
|
||||
// its description or parameter schema).
|
||||
const describe = await execute('leak-4', { describe: 'airtable_mcp_server_search_records' })
|
||||
const describeText = JSON.stringify(describe.content)
|
||||
expect(describeText).toContain('not found')
|
||||
expect(describeText).not.toContain('Search Airtable records')
|
||||
expect(describeText).not.toContain('Parameters:')
|
||||
} finally {
|
||||
await tavilySrv.stop()
|
||||
await airtableSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('drops unassigned servers from a rebuilt agent tool set', async () => {
|
||||
const { agent, airtable, tavilySrv, airtableSrv } = await seedAgentWithUnassignedServer()
|
||||
try {
|
||||
// Assign airtable, then unassign it — a rebuilt tool set must forget it.
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: airtable.id } })
|
||||
let tools = await service.buildAgentTools(agent.id, teamId)
|
||||
expect(JSON.stringify(tools[0].description)).toContain('airtable-mcp-server')
|
||||
|
||||
await prisma.agentMcpServer.deleteMany({
|
||||
where: { agentId: agent.id, mcpServerId: airtable.id },
|
||||
})
|
||||
tools = await service.buildAgentTools(agent.id, teamId)
|
||||
const search = await (tools[0].execute as ProxyExecute)('leak-5', { search: 'records' })
|
||||
expect(JSON.stringify(search.content)).not.toContain('airtable')
|
||||
|
||||
const call = await (tools[0].execute as ProxyExecute)('leak-6', {
|
||||
tool: 'airtable_mcp_server_search_records',
|
||||
})
|
||||
expect(JSON.stringify(call.content)).not.toContain('AIRTABLE-SECRET-DATA')
|
||||
} finally {
|
||||
await tavilySrv.stop()
|
||||
await airtableSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('registers direct tools only for assigned servers', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'Direct Assigned Only Agent')
|
||||
const [assignedSrv, unassignedSrv] = await Promise.all([
|
||||
startTestMcpServer({
|
||||
tools: TAVILY_TOOLS,
|
||||
serverInfo: { name: 'tavily-mcp' },
|
||||
}),
|
||||
startTestMcpServer({
|
||||
tools: AIRTABLE_TOOLS,
|
||||
serverInfo: { name: 'airtable-mcp-server' },
|
||||
}),
|
||||
])
|
||||
try {
|
||||
const assigned = await service.createServer(teamId, {
|
||||
url: assignedSrv.url,
|
||||
config: { directTools: true },
|
||||
})
|
||||
const unassigned = await service.createServer(teamId, {
|
||||
url: unassignedSrv.url,
|
||||
config: { directTools: true },
|
||||
})
|
||||
await service.refreshServer(assigned.id)
|
||||
await service.refreshServer(unassigned.id)
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: assigned.id } })
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
const names = tools.map((t) => t.name)
|
||||
expect(names).toContain('tavily_mcp_tavily_search')
|
||||
expect(names).not.toContain('airtable_mcp_server_search_records')
|
||||
} finally {
|
||||
await assignedSrv.stop()
|
||||
await unassignedSrv.stop()
|
||||
}
|
||||
}, 15000)
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Direct tools (D3/D7)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('registers direct tools for opted-in servers alongside the proxy', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'Direct Agent')
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
config: { directTools: true },
|
||||
})
|
||||
await service.refreshServer(server.id)
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
expect(tools.length).toBe(4) // proxy + 3 direct tools
|
||||
const names = tools.map((t) => t.name)
|
||||
expect(names).toContain('mcp')
|
||||
expect(names).toContain('test_mcp_server_echo')
|
||||
expect(names).toContain('test_mcp_server_add')
|
||||
|
||||
// Direct tool executes through callMcpTool.
|
||||
const echo = tools.find((t) => t.name === 'test_mcp_server_echo')!
|
||||
const result = await (
|
||||
echo.execute as (
|
||||
id: string,
|
||||
params: unknown,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('call-2', { text: 'direct' })
|
||||
expect(JSON.stringify(result.content)).toContain('echo:direct')
|
||||
})
|
||||
|
||||
it('applies excludeTools filters to direct tools', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'Filtered Agent')
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
config: { directTools: true, excludeTools: ['add'] },
|
||||
})
|
||||
await service.refreshServer(server.id)
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
const names = tools.map((t) => t.name)
|
||||
expect(names).toContain('test_mcp_server_echo')
|
||||
expect(names).toContain('test_mcp_server_list_sims')
|
||||
expect(names).not.toContain('test_mcp_server_add')
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// OAuth status helpers
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('reports auth status for each auth type', async () => {
|
||||
const none = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'none' },
|
||||
})
|
||||
expect(await service.getAuthStatus(none.id)).toBe('authenticated')
|
||||
|
||||
const bearer = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'bearer', bearerToken: 'x' },
|
||||
})
|
||||
expect(await service.getAuthStatus(bearer.id)).toBe('authenticated')
|
||||
|
||||
const bearerEmpty = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'bearer' },
|
||||
})
|
||||
expect(await service.getAuthStatus(bearerEmpty.id)).toBe('not_authenticated')
|
||||
|
||||
const oauth = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'oauth' },
|
||||
})
|
||||
expect(await service.getAuthStatus(oauth.id)).toBe('not_authenticated')
|
||||
expect(await service.getAuthStatus(oauth.id)).toBe('not_authenticated')
|
||||
})
|
||||
|
||||
it('testServer connects and lists tools', async () => {
|
||||
const server = await service.createServer(teamId, { url: srv.url })
|
||||
const result = await service.testServer(server.id)
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.toolCount).toBe(3)
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Proxy disambiguation across two servers (same-named tools)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('disambiguates same-named tools via the server parameter', async () => {
|
||||
const toolsA: TestMcpToolDef[] = [
|
||||
{ name: 'get', description: 'Get from server A', handler: async () => 'A' },
|
||||
{ name: 'shared', description: 'Shared tool on A', handler: async () => 'from-A' },
|
||||
]
|
||||
const toolsB: TestMcpToolDef[] = [
|
||||
{ name: 'get', description: 'Get from server B', handler: async () => 'B' },
|
||||
{ name: 'shared', description: 'Shared tool on B', handler: async () => 'from-B' },
|
||||
]
|
||||
const srvA = await startTestMcpServer({ tools: toolsA, serverInfo: { name: 'srvA' } })
|
||||
const srvB = await startTestMcpServer({ tools: toolsB, serverInfo: { name: 'srvB' } })
|
||||
try {
|
||||
const agent = await prisma.user.create({
|
||||
data: { name: 'Two Srv Agent', email: 'two-srv-agent@shumai.ai', type: 'agent' },
|
||||
})
|
||||
await prisma.teamMember.create({ data: { teamId, userId: agent.id, role: 'editor' } })
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: agent.id,
|
||||
teamId,
|
||||
type: 'chat',
|
||||
config: { provider: 'openai', model: 'gpt-4' },
|
||||
},
|
||||
})
|
||||
|
||||
const serverA = await service.createServer(teamId, { url: srvA.url })
|
||||
const serverB = await service.createServer(teamId, { url: srvB.url })
|
||||
await service.refreshServer(serverA.id)
|
||||
await service.refreshServer(serverB.id)
|
||||
await prisma.agentMcpServer.createMany({
|
||||
data: [
|
||||
{ agentId: agent.id, mcpServerId: serverA.id },
|
||||
{ agentId: agent.id, mcpServerId: serverB.id },
|
||||
],
|
||||
})
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
expect(tools.length).toBe(1) // only the proxy
|
||||
const proxy = tools[0]
|
||||
|
||||
const callA = await (
|
||||
proxy.execute as (
|
||||
id: string,
|
||||
params: unknown,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('c1', { server: 'srvA', tool: 'shared' })
|
||||
expect(JSON.stringify(callA.content)).toContain('from-A')
|
||||
|
||||
const callB = await (
|
||||
proxy.execute as (
|
||||
id: string,
|
||||
params: unknown,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('c2', { server: 'srvB', tool: 'shared' })
|
||||
expect(JSON.stringify(callB.content)).toContain('from-B')
|
||||
|
||||
// Prefixed names also resolve without the server parameter.
|
||||
const prefixed = await (
|
||||
proxy.execute as (
|
||||
id: string,
|
||||
params: unknown,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('c3', { tool: 'srvA_get' })
|
||||
expect(JSON.stringify(prefixed.content)).toContain('A')
|
||||
} finally {
|
||||
await srvA.stop()
|
||||
await srvB.stop()
|
||||
}
|
||||
})
|
||||
|
||||
describe('Idle connection and in-flight tracking', () => {
|
||||
it('tracks in-flight requests and safely prunes idle connections', async () => {
|
||||
// Deterministic synchronization with the server-side handler: the handler
|
||||
// signals when it starts executing and only then blocks on the release
|
||||
// gate. This avoids wall-clock guessing about when the HTTP round trip
|
||||
// has reached the server, which is slow and variable on CI.
|
||||
let slowToolStarted!: () => void
|
||||
const slowToolStartedPromise = new Promise<void>((resolve) => {
|
||||
slowToolStarted = resolve
|
||||
})
|
||||
let releaseSlowTool: () => void = () => {}
|
||||
const slowServer = await startTestMcpServer({
|
||||
tools: [
|
||||
{
|
||||
name: 'slow_tool',
|
||||
description: 'Slow tool',
|
||||
handler: async () => {
|
||||
slowToolStarted()
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseSlowTool = resolve
|
||||
})
|
||||
return 'slow-done'
|
||||
},
|
||||
},
|
||||
],
|
||||
serverInfo: { name: 'slow-mcp' },
|
||||
})
|
||||
|
||||
try {
|
||||
const serverRecord = await service.createServer(teamId, {
|
||||
url: slowServer.url,
|
||||
config: { idleTimeoutMs: 50 },
|
||||
})
|
||||
|
||||
// Connect to the server
|
||||
await service.refreshServer(serverRecord.id)
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(1)
|
||||
|
||||
// Start callTool in background
|
||||
const callPromise = service.callMcpTool(serverRecord.id, 'slow_tool', {})
|
||||
|
||||
// Wait until the tool handler is actually executing on the server so
|
||||
// the request is guaranteed to be in-flight before we assert on it.
|
||||
await Promise.race([
|
||||
slowToolStartedPromise,
|
||||
callPromise.then(() => {
|
||||
throw new Error('slow_tool finished before its handler started')
|
||||
}),
|
||||
])
|
||||
|
||||
// Connection should NOT be idle while tool is in-flight
|
||||
const closedDuringCall = await service.closeIdleConnections(0)
|
||||
expect(closedDuringCall).not.toContain(serverRecord.id)
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(1)
|
||||
|
||||
// Complete tool execution
|
||||
releaseSlowTool()
|
||||
const toolResult = await callPromise
|
||||
expect(toolResult.ok).toBe(true)
|
||||
|
||||
// Wait past idle timeout threshold
|
||||
await new Promise((r) => setTimeout(r, 60))
|
||||
|
||||
// Now idle connection should be closed
|
||||
const closedAfterIdle = await service.closeIdleConnections(50)
|
||||
expect(closedAfterIdle).toContain(serverRecord.id)
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(0)
|
||||
} finally {
|
||||
await slowServer.stop()
|
||||
}
|
||||
}, 10000)
|
||||
|
||||
it('respects keepAlive setting when closing idle connections', async () => {
|
||||
const keepAliveServer = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'keep-alive-mcp' },
|
||||
})
|
||||
|
||||
try {
|
||||
const serverRecord = await service.createServer(teamId, {
|
||||
url: keepAliveServer.url,
|
||||
config: { keepAlive: true },
|
||||
})
|
||||
|
||||
await service.refreshServer(serverRecord.id)
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(1)
|
||||
|
||||
// Wait a bit
|
||||
await new Promise((r) => setTimeout(r, 20))
|
||||
|
||||
// Should not close server marked with keepAlive even with 0 timeout
|
||||
const closed = await service.closeIdleConnections(0)
|
||||
expect(closed).not.toContain(serverRecord.id)
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(1)
|
||||
} finally {
|
||||
await keepAliveServer.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('can run periodic idle cleanup background timer', async () => {
|
||||
const timerServer = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'timer-mcp' },
|
||||
})
|
||||
|
||||
try {
|
||||
const serverRecord = await service.createServer(teamId, {
|
||||
url: timerServer.url,
|
||||
})
|
||||
await service.refreshServer(serverRecord.id)
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(1)
|
||||
|
||||
// Start timer with very short interval (20ms) and 0ms idle timeout
|
||||
service.startIdleCleanupTimer(20, 0)
|
||||
|
||||
// Wait for timer tick
|
||||
await new Promise((r) => setTimeout(r, 60))
|
||||
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(0)
|
||||
} finally {
|
||||
service.stopIdleCleanupTimer()
|
||||
await timerServer.stop()
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,952 @@
|
||||
/**
|
||||
* McpService — CRUD, discovery, OAuth, and agent integration for MCP servers.
|
||||
*/
|
||||
|
||||
import { auth } from '@modelcontextprotocol/client'
|
||||
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
|
||||
import { prisma } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import type {
|
||||
CreateMcpServerRequest,
|
||||
McpAuthStatus,
|
||||
McpServerInfo,
|
||||
UpdateMcpServerRequest,
|
||||
} from '@shumai/dtos'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { mcpDbStore, type PendingAuth } from './mcp-db-store'
|
||||
import { buildDirectTools } from './mcp-direct-tools'
|
||||
import { McpOauthProvider, type McpOauthConfig } from './mcp-oauth-provider'
|
||||
import { buildProxyTool, transformMcpContent, type McpProxyToolContext } from './mcp-proxy-tool'
|
||||
import {
|
||||
formatToolName,
|
||||
McpToolRegistry,
|
||||
sanitizeServerPrefix,
|
||||
type ToolMetadata,
|
||||
} from './mcp-tool-registry'
|
||||
import { McpServerManager, type McpServerDefinition } from './mcp-server-manager'
|
||||
|
||||
const ROLE_HIERARCHY: Record<string, number> = {
|
||||
owner: 3,
|
||||
editor: 2,
|
||||
reviewer: 1,
|
||||
}
|
||||
|
||||
export interface McpToolCallContext {
|
||||
teamId: string
|
||||
userId?: string
|
||||
}
|
||||
|
||||
export type McpToolCallContent = AgentToolResult<Record<string, unknown>>['content']
|
||||
|
||||
export interface McpToolCallResult {
|
||||
ok: boolean
|
||||
content: McpToolCallContent
|
||||
}
|
||||
|
||||
export interface McpServerRecord {
|
||||
id: string
|
||||
name: string
|
||||
description: string | null
|
||||
instructions: string | null
|
||||
url: string
|
||||
transport: 'streamable_http' | 'sse'
|
||||
authConfig: PrismaJson.McpServerAuthConfig | null
|
||||
config: PrismaJson.McpServerConfig | null
|
||||
permission: 'owner' | 'editor' | 'reviewer'
|
||||
tools: PrismaJson.McpToolInfo[] | null
|
||||
status: string
|
||||
lastError: string | null
|
||||
lastConnectedAt: Date | null
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
teamId: string
|
||||
credential: { id: string } | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a placeholder server name from its URL until the server self-reports
|
||||
* its name/title on first successful connection. Strips www/api/mcp prefixes
|
||||
* and sanitizes the remaining host label (used as the direct-tool prefix).
|
||||
*/
|
||||
function deriveServerName(url: string): string {
|
||||
try {
|
||||
const hostname = new URL(url).hostname.toLowerCase()
|
||||
const labels = hostname.split('.').filter(Boolean)
|
||||
let label = labels[0] ?? 'mcp-server'
|
||||
if (labels.length > 1 && ['www', 'api', 'mcp'].includes(label)) {
|
||||
label = labels[1]
|
||||
}
|
||||
const sanitized = label.replace(/[^a-z0-9_-]/g, '_').replace(/^[-_]+|[-_]+$/g, '')
|
||||
return sanitized || 'mcp-server'
|
||||
} catch {
|
||||
return 'mcp-server'
|
||||
}
|
||||
}
|
||||
|
||||
function generateState(): string {
|
||||
return Array.from(crypto.getRandomValues(new Uint8Array(32)))
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
}
|
||||
|
||||
function extractOauthConfig(authConfig?: PrismaJson.McpServerAuthConfig): McpOauthConfig {
|
||||
const oauth = authConfig?.oauth
|
||||
if (!oauth) return {}
|
||||
return {
|
||||
...(oauth.grantType !== undefined ? { grantType: oauth.grantType } : {}),
|
||||
...(oauth.clientId !== undefined ? { clientId: oauth.clientId } : {}),
|
||||
...(oauth.clientSecret !== undefined ? { clientSecret: oauth.clientSecret } : {}),
|
||||
...(oauth.scope !== undefined ? { scope: oauth.scope } : {}),
|
||||
...(oauth.authorizationParams !== undefined
|
||||
? { authorizationParams: oauth.authorizationParams }
|
||||
: {}),
|
||||
...(oauth.redirectUri !== undefined ? { redirectUri: oauth.redirectUri } : {}),
|
||||
...(oauth.clientName !== undefined ? { clientName: oauth.clientName } : {}),
|
||||
...(oauth.clientUri !== undefined ? { clientUri: oauth.clientUri } : {}),
|
||||
...(oauth.skipIssuerMetadataValidation !== undefined
|
||||
? { skipIssuerMetadataValidation: oauth.skipIssuerMetadataValidation }
|
||||
: {}),
|
||||
}
|
||||
}
|
||||
|
||||
export class McpService {
|
||||
private manager = new McpServerManager(mcpDbStore)
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// CRUD
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
async createServer(teamId: string, req: CreateMcpServerRequest): Promise<McpServerInfo> {
|
||||
const server = await prisma.mcpServer.create({
|
||||
data: {
|
||||
name: deriveServerName(req.url),
|
||||
url: req.url,
|
||||
teamId,
|
||||
transport: req.transport ?? 'streamable_http',
|
||||
authConfig: (req.authConfig ?? {}) as PrismaJson.McpServerAuthConfig,
|
||||
config: (req.config ?? {}) as PrismaJson.McpServerConfig,
|
||||
permission: req.permission ?? 'reviewer',
|
||||
},
|
||||
include: { credential: true },
|
||||
})
|
||||
return this.toServerInfo(this.mapRecord(server))
|
||||
}
|
||||
|
||||
async updateServer(id: string, req: UpdateMcpServerRequest): Promise<McpServerInfo> {
|
||||
const existing = await prisma.mcpServer.findUnique({ where: { id } })
|
||||
if (!existing) throw new Error('MCP server not found')
|
||||
|
||||
const authChanged =
|
||||
req.authConfig !== undefined &&
|
||||
JSON.stringify(req.authConfig) !== JSON.stringify(existing.authConfig ?? {})
|
||||
const transportChanged = req.transport !== undefined && req.transport !== existing.transport
|
||||
|
||||
// The endpoint URL is immutable (delete + re-add to change it).
|
||||
// Auth/transport changes invalidate credentials and cached tools.
|
||||
const invalidateAll = authChanged || transportChanged
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
if (invalidateAll) {
|
||||
await tx.mcpServerCredential.deleteMany({ where: { serverId: id } })
|
||||
}
|
||||
return tx.mcpServer.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(req.transport !== undefined ? { transport: req.transport } : {}),
|
||||
...(req.authConfig !== undefined
|
||||
? { authConfig: req.authConfig as PrismaJson.McpServerAuthConfig }
|
||||
: {}),
|
||||
...(req.config !== undefined ? { config: req.config as PrismaJson.McpServerConfig } : {}),
|
||||
...(req.permission !== undefined ? { permission: req.permission } : {}),
|
||||
...(invalidateAll ? { tools: [], status: 'not_connected', lastError: null } : {}),
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
if (invalidateAll) {
|
||||
await this.manager.close(id)
|
||||
}
|
||||
|
||||
const record = await this.getServerRecord(id)
|
||||
if (!record) throw new Error('MCP server not found')
|
||||
return this.toServerInfo(record)
|
||||
}
|
||||
|
||||
async updateServerPermission(
|
||||
id: string,
|
||||
permission: 'owner' | 'editor' | 'reviewer',
|
||||
): Promise<McpServerInfo> {
|
||||
const server = await prisma.mcpServer.update({
|
||||
where: { id },
|
||||
data: { permission },
|
||||
include: { credential: true },
|
||||
})
|
||||
return this.toServerInfo(this.mapRecord(server))
|
||||
}
|
||||
|
||||
async deleteServer(id: string): Promise<void> {
|
||||
await this.manager.close(id)
|
||||
const server = await prisma.mcpServer.findUnique({ where: { id } })
|
||||
if (!server) return
|
||||
await prisma.mcpServer.delete({ where: { id } })
|
||||
}
|
||||
|
||||
async listServers(teamId: string): Promise<McpServerInfo[]> {
|
||||
const servers = await prisma.mcpServer.findMany({
|
||||
where: { teamId },
|
||||
orderBy: { id: 'desc' },
|
||||
include: { credential: true },
|
||||
})
|
||||
return servers.map((s) => this.toServerInfo(this.mapRecord(s)))
|
||||
}
|
||||
|
||||
async getServerRecord(id: string): Promise<McpServerRecord | null> {
|
||||
const server = await prisma.mcpServer.findUnique({
|
||||
where: { id },
|
||||
include: { credential: true },
|
||||
})
|
||||
if (!server) return null
|
||||
return this.mapRecord(server)
|
||||
}
|
||||
|
||||
async getServer(id: string): Promise<McpServerInfo | null> {
|
||||
const server = await this.getServerRecord(id)
|
||||
if (!server) return null
|
||||
return this.toServerInfo(server)
|
||||
}
|
||||
|
||||
private mapRecord(server: {
|
||||
id: string
|
||||
name: string
|
||||
description: string | null
|
||||
instructions: string | null
|
||||
url: string
|
||||
transport: 'streamable_http' | 'sse'
|
||||
authConfig: unknown
|
||||
config: unknown
|
||||
permission: 'owner' | 'editor' | 'reviewer'
|
||||
tools: unknown
|
||||
status: string
|
||||
lastError: string | null
|
||||
lastConnectedAt: Date | null
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
teamId: string
|
||||
credential: { id: string } | null
|
||||
}): McpServerRecord {
|
||||
return {
|
||||
id: server.id,
|
||||
name: server.name,
|
||||
description: server.description,
|
||||
instructions: server.instructions,
|
||||
url: server.url,
|
||||
transport: server.transport,
|
||||
authConfig: (server.authConfig ?? null) as PrismaJson.McpServerAuthConfig | null,
|
||||
config: (server.config ?? null) as PrismaJson.McpServerConfig | null,
|
||||
permission: server.permission,
|
||||
tools: (server.tools ?? null) as PrismaJson.McpToolInfo[] | null,
|
||||
status: server.status,
|
||||
lastError: server.lastError,
|
||||
lastConnectedAt: server.lastConnectedAt,
|
||||
createdAt: server.createdAt,
|
||||
updatedAt: server.updatedAt,
|
||||
teamId: server.teamId,
|
||||
credential: server.credential,
|
||||
}
|
||||
}
|
||||
|
||||
private toServerInfo(server: McpServerRecord): McpServerInfo {
|
||||
const tools = server.tools ?? []
|
||||
return {
|
||||
id: server.id,
|
||||
name: server.name,
|
||||
description: server.description ?? undefined,
|
||||
instructions: server.instructions ?? undefined,
|
||||
url: server.url,
|
||||
transport: server.transport,
|
||||
authType: server.authConfig?.type ?? 'auto',
|
||||
config: server.config ?? undefined,
|
||||
permission: server.permission,
|
||||
status: server.status,
|
||||
lastError: server.lastError ?? undefined,
|
||||
toolCount: Array.isArray(tools) ? tools.length : 0,
|
||||
hasCredential: server.credential !== null,
|
||||
createdAt: server.createdAt.toISOString(),
|
||||
updatedAt: server.updatedAt.toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Discovery
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
private toDefinition(server: McpServerRecord): McpServerDefinition {
|
||||
return {
|
||||
name: server.name,
|
||||
url: server.url,
|
||||
transport: server.transport,
|
||||
authConfig: server.authConfig ?? undefined,
|
||||
config: server.config ?? undefined,
|
||||
}
|
||||
}
|
||||
|
||||
private async updateStatus(
|
||||
serverId: string,
|
||||
status: string,
|
||||
lastError: string | null,
|
||||
extra?: {
|
||||
tools?: PrismaJson.McpToolInfo[]
|
||||
lastConnectedAt?: Date
|
||||
name?: string
|
||||
description?: string | null
|
||||
instructions?: string | null
|
||||
},
|
||||
): Promise<void> {
|
||||
await prisma.mcpServer.update({
|
||||
where: { id: serverId },
|
||||
data: {
|
||||
status,
|
||||
lastError,
|
||||
...(extra?.tools !== undefined ? { tools: extra.tools } : {}),
|
||||
...(extra?.lastConnectedAt !== undefined ? { lastConnectedAt: extra.lastConnectedAt } : {}),
|
||||
...(extra?.name !== undefined ? { name: extra.name } : {}),
|
||||
...(extra?.description !== undefined ? { description: extra.description } : {}),
|
||||
...(extra?.instructions !== undefined ? { instructions: extra.instructions } : {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
private toStoredTools(
|
||||
tools: Array<{ name: string; title?: string; description?: string; inputSchema?: unknown }>,
|
||||
): PrismaJson.McpToolInfo[] {
|
||||
return tools.map((t) => ({
|
||||
name: t.name,
|
||||
...(t.title !== undefined ? { title: t.title } : {}),
|
||||
...(t.description !== undefined ? { description: t.description } : {}),
|
||||
...(t.inputSchema !== undefined ? { inputSchema: t.inputSchema } : {}),
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the server's self-reported metadata (name = title ?? name, plus
|
||||
* description and instructions) captured after a successful connect.
|
||||
* Description comes from getServerVersion(); instructions come from
|
||||
* getInstructions() (a sibling field of the initialize/discover result,
|
||||
* not part of Implementation).
|
||||
*/
|
||||
private serverMetadata(
|
||||
server: McpServerRecord,
|
||||
connection: { serverVersion?: unknown; instructions?: string },
|
||||
): {
|
||||
name?: string
|
||||
description?: string | null
|
||||
instructions?: string | null
|
||||
} {
|
||||
const metadata: {
|
||||
name?: string
|
||||
description?: string | null
|
||||
instructions?: string | null
|
||||
} = {}
|
||||
const impl = connection.serverVersion as
|
||||
| { name?: string; title?: string; description?: string }
|
||||
| undefined
|
||||
if (impl && typeof impl === 'object') {
|
||||
const reportedName = impl.title ?? impl.name
|
||||
if (typeof reportedName === 'string' && reportedName.trim() !== '') {
|
||||
metadata.name = reportedName.trim()
|
||||
metadata.description = typeof impl.description === 'string' ? impl.description : null
|
||||
}
|
||||
}
|
||||
if (typeof connection.instructions === 'string') {
|
||||
metadata.instructions = connection.instructions
|
||||
} else {
|
||||
// Sync-on-connect: a server that stops reporting instructions clears
|
||||
// the cached value (mirrors pi-mcp-adapter's set/delete behavior).
|
||||
metadata.instructions = null
|
||||
}
|
||||
return metadata
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh a server: force a fresh connection (closing any existing one),
|
||||
* then re-discover and persist tools, instructions, name/description and
|
||||
* status. Returns the updated server record. Throws on connection failure
|
||||
* (after marking the server as failed). This is the single discovery
|
||||
* entry point: the refresh endpoint, Test Connection, and post-OAuth
|
||||
* completion all route through it.
|
||||
*/
|
||||
async refreshServer(serverId: string): Promise<McpServerInfo> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) throw new Error('MCP server not found')
|
||||
await this.manager.close(serverId)
|
||||
|
||||
try {
|
||||
const connection = await this.manager.connect(serverId, this.toDefinition(server))
|
||||
if (connection.status === 'needs-auth') {
|
||||
await this.updateStatus(serverId, 'needs_auth', null)
|
||||
} else {
|
||||
const tools = this.toStoredTools(connection.tools)
|
||||
const metadata = this.serverMetadata(server, connection)
|
||||
await this.updateStatus(serverId, 'connected', null, {
|
||||
tools,
|
||||
lastConnectedAt: new Date(),
|
||||
...metadata,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
logger.warn({ serverId, error }, 'MCP server refresh failed')
|
||||
await this.updateStatus(serverId, 'failed', message)
|
||||
throw error
|
||||
}
|
||||
|
||||
const record = await this.getServerRecord(serverId)
|
||||
if (!record) throw new Error('MCP server not found')
|
||||
return this.toServerInfo(record)
|
||||
}
|
||||
|
||||
/** Lazy connect used by the proxy/direct tools; never throws. */
|
||||
private async ensureConnected(
|
||||
serverId: string,
|
||||
registry?: McpToolRegistry,
|
||||
): Promise<
|
||||
{ status: 'connected' } | { status: 'needs-auth' } | { status: 'error'; message: string }
|
||||
> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) return { status: 'error', message: 'server not found' }
|
||||
|
||||
const existing = this.manager.getConnection(serverId)
|
||||
if (existing?.status === 'connected') return { status: 'connected' }
|
||||
|
||||
try {
|
||||
const connection = await this.manager.connect(serverId, this.toDefinition(server))
|
||||
if (connection.status === 'needs-auth') {
|
||||
await this.updateStatus(serverId, 'needs_auth', null)
|
||||
return { status: 'needs-auth' }
|
||||
}
|
||||
const tools = this.toStoredTools(connection.tools)
|
||||
const metadata = this.serverMetadata(server, connection)
|
||||
const displayName = metadata.name ?? server.name
|
||||
registry?.setTools(serverId, displayName, connection.tools)
|
||||
await this.updateStatus(serverId, 'connected', null, {
|
||||
tools,
|
||||
lastConnectedAt: new Date(),
|
||||
...metadata,
|
||||
})
|
||||
return { status: 'connected' }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
await this.updateStatus(serverId, 'failed', message)
|
||||
return { status: 'error', message }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-reported usage instructions. Prefers the persisted value (the
|
||||
* cache, so it works without a live connection), falling back to the live
|
||||
* connection's getInstructions() for a just-connected server.
|
||||
*/
|
||||
private async getServerInstructions(serverId: string): Promise<string | null> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) return null
|
||||
if (server.instructions && server.instructions.trim() !== '') return server.instructions
|
||||
const connection = this.manager.getConnection(serverId)
|
||||
const live = connection?.client.getInstructions?.()
|
||||
return typeof live === 'string' && live.trim() !== '' ? live : null
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Tool execution
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
private async checkPermission(
|
||||
server: McpServerRecord,
|
||||
ctx?: McpToolCallContext,
|
||||
): Promise<string | null> {
|
||||
const requiredLevel = ROLE_HIERARCHY[server.permission] || 1
|
||||
|
||||
if (ctx?.userId) {
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId: server.teamId,
|
||||
userId: ctx.userId,
|
||||
},
|
||||
},
|
||||
select: { role: true },
|
||||
})
|
||||
const userLevel = member ? ROLE_HIERARCHY[member.role] || 0 : 0
|
||||
if (userLevel < requiredLevel) {
|
||||
return `Permission denied: Insufficient role to use MCP server "${server.name}". Minimum required role is "${server.permission}".`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
if (requiredLevel > 1) {
|
||||
return `Permission denied: User context required to use MCP server "${server.name}". Minimum required role is "${server.permission}".`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private contentFromMcpResult(result: {
|
||||
content: unknown[]
|
||||
structuredContent?: Record<string, unknown>
|
||||
isError?: boolean
|
||||
}): McpToolCallContent {
|
||||
const blocks = transformMcpContent(
|
||||
(Array.isArray(result.content) ? result.content : []) as Parameters<
|
||||
typeof transformMcpContent
|
||||
>[0],
|
||||
)
|
||||
if (blocks.length > 0) return blocks
|
||||
if (result.structuredContent !== undefined && result.structuredContent !== null) {
|
||||
return [
|
||||
{
|
||||
type: 'text',
|
||||
text:
|
||||
JSON.stringify(result.structuredContent, null, 2) ?? String(result.structuredContent),
|
||||
},
|
||||
]
|
||||
}
|
||||
return [{ type: 'text', text: '(empty result)' }]
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute an MCP tool (shared by the proxy and direct tools).
|
||||
* Permission gate (D10) first; never throws — failures become error text.
|
||||
*/
|
||||
async callMcpTool(
|
||||
serverId: string,
|
||||
toolName: string,
|
||||
args: Record<string, unknown>,
|
||||
ctx?: McpToolCallContext,
|
||||
): Promise<McpToolCallResult> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) {
|
||||
return { ok: false, content: [{ type: 'text', text: 'MCP server not found' }] }
|
||||
}
|
||||
|
||||
const denied = await this.checkPermission(server, ctx)
|
||||
if (denied) {
|
||||
return { ok: false, content: [{ type: 'text', text: denied }] }
|
||||
}
|
||||
|
||||
const outcome = await this.ensureConnected(serverId)
|
||||
if (outcome.status === 'needs-auth') {
|
||||
return {
|
||||
ok: false,
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `MCP server "${server.name}" requires authentication. Ask an admin to connect it in Settings → MCP.`,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
if (outcome.status === 'error') {
|
||||
return {
|
||||
ok: false,
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Failed to connect to MCP server "${server.name}": ${outcome.message}`,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.manager.callTool(serverId, toolName, args)
|
||||
if (result.isError) {
|
||||
const text = result.content.map((c) => ('text' in c ? c.text : '[image]')).join('\n')
|
||||
return {
|
||||
ok: true,
|
||||
content: [{ type: 'text', text: text ? `Error: ${text}` : 'Tool execution failed' }],
|
||||
}
|
||||
}
|
||||
return { ok: true, content: this.contentFromMcpResult(result) }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
await this.updateStatus(serverId, 'failed', message)
|
||||
return {
|
||||
ok: false,
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Failed to call tool "${toolName}" on MCP server "${server.name}": ${message}`,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// OAuth
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
async startAuth(serverId: string): Promise<{
|
||||
authorizationUrl?: string
|
||||
alreadyAuthenticated?: boolean
|
||||
}> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) throw new Error('MCP server not found')
|
||||
|
||||
const config = extractOauthConfig(server.authConfig ?? undefined)
|
||||
if (config.grantType === 'client_credentials') {
|
||||
const provider = new McpOauthProvider(
|
||||
serverId,
|
||||
server.url,
|
||||
config,
|
||||
{
|
||||
onRedirect: async () => {
|
||||
throw new Error('Browser redirect is not used for client_credentials flow')
|
||||
},
|
||||
},
|
||||
mcpDbStore,
|
||||
)
|
||||
try {
|
||||
const result = await auth(provider, {
|
||||
serverUrl: server.url,
|
||||
...(config.scope !== undefined ? { scope: config.scope } : {}),
|
||||
...(config.skipIssuerMetadataValidation === true
|
||||
? { skipIssuerMetadataValidation: true }
|
||||
: {}),
|
||||
})
|
||||
if (result !== 'AUTHORIZED') {
|
||||
throw new Error('Failed to authorize')
|
||||
}
|
||||
await mcpDbStore.clearPendingAuth(serverId)
|
||||
return { alreadyAuthenticated: true }
|
||||
} finally {
|
||||
provider.deactivate()
|
||||
}
|
||||
}
|
||||
|
||||
let capturedUrl: URL | undefined
|
||||
const provider = new McpOauthProvider(
|
||||
serverId,
|
||||
server.url,
|
||||
config,
|
||||
{
|
||||
onRedirect: async (url) => {
|
||||
capturedUrl = url
|
||||
},
|
||||
},
|
||||
mcpDbStore,
|
||||
)
|
||||
|
||||
try {
|
||||
const result = await auth(provider, {
|
||||
serverUrl: server.url,
|
||||
...(config.scope !== undefined ? { scope: config.scope } : {}),
|
||||
...(config.skipIssuerMetadataValidation === true
|
||||
? { skipIssuerMetadataValidation: true }
|
||||
: {}),
|
||||
})
|
||||
if (result === 'AUTHORIZED') {
|
||||
await mcpDbStore.clearPendingAuth(serverId)
|
||||
return { alreadyAuthenticated: true }
|
||||
}
|
||||
if (!capturedUrl) {
|
||||
throw new Error('OAuth authorization URL was not provided')
|
||||
}
|
||||
|
||||
const state = (await mcpDbStore.getOauthState(serverId)) ?? generateState()
|
||||
const discoveryState = await provider.discoveryState()
|
||||
const pending: PendingAuth = {
|
||||
state,
|
||||
authorizationUrl: capturedUrl.toString(),
|
||||
discovery: (discoveryState ?? {}) as Record<string, unknown>,
|
||||
expiresAt: Math.floor(Date.now() / 1000) + (await mcpDbStore.getPendingAuthTtlSeconds()),
|
||||
grantType: 'authorization_code',
|
||||
...(provider.redirectUrl ? { redirectUri: provider.redirectUrl } : {}),
|
||||
}
|
||||
await mcpDbStore.savePendingAuth(serverId, pending)
|
||||
return { authorizationUrl: capturedUrl.toString() }
|
||||
} finally {
|
||||
provider.deactivate()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete an authorization_code flow. `state` is validated by the caller
|
||||
* (the API callback route) before delegating here.
|
||||
*/
|
||||
async completeAuth(
|
||||
serverId: string,
|
||||
input: { code: string; iss?: string },
|
||||
): Promise<McpAuthStatus> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) throw new Error('MCP server not found')
|
||||
const pending = await mcpDbStore.getPendingAuth(serverId)
|
||||
if (!pending) throw new Error(`No pending OAuth flow for server: ${server.name}`)
|
||||
|
||||
const config = extractOauthConfig(server.authConfig ?? undefined)
|
||||
const provider = new McpOauthProvider(
|
||||
serverId,
|
||||
server.url,
|
||||
config,
|
||||
{ onRedirect: async () => {} },
|
||||
mcpDbStore,
|
||||
)
|
||||
|
||||
try {
|
||||
const result = await auth(provider, {
|
||||
serverUrl: server.url,
|
||||
authorizationCode: input.code,
|
||||
...(input.iss !== undefined ? { iss: input.iss } : {}),
|
||||
...(pending.discovery as Record<string, unknown>),
|
||||
...(config.skipIssuerMetadataValidation === true
|
||||
? { skipIssuerMetadataValidation: true }
|
||||
: {}),
|
||||
})
|
||||
if (result !== 'AUTHORIZED') {
|
||||
throw new Error('Failed to authorize')
|
||||
}
|
||||
await mcpDbStore.clearPendingAuth(serverId)
|
||||
await mcpDbStore.clearDiscoverySnapshot(serverId)
|
||||
try {
|
||||
await this.refreshServer(serverId)
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ serverId, err },
|
||||
'Post-auth server refresh failed, setting status to connected',
|
||||
)
|
||||
await this.updateStatus(serverId, 'connected', null)
|
||||
}
|
||||
return 'authenticated'
|
||||
} finally {
|
||||
provider.deactivate()
|
||||
}
|
||||
}
|
||||
|
||||
/** Find a pending flow by its CSRF state and complete it. */
|
||||
async handleOauthCallback(
|
||||
code: string,
|
||||
state: string,
|
||||
iss?: string,
|
||||
): Promise<{ ok: true } | { ok: false; message: string }> {
|
||||
const rows = await prisma.mcpServerCredential.findMany({
|
||||
select: { serverId: true, pendingAuth: true },
|
||||
})
|
||||
|
||||
let serverId: string | undefined
|
||||
for (const row of rows) {
|
||||
const raw = row.pendingAuth as Partial<PendingAuth> | null
|
||||
if (raw && typeof raw.state === 'string' && raw.state === state) {
|
||||
serverId = row.serverId
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!serverId) {
|
||||
return { ok: false, message: 'Invalid or expired OAuth state. Start authentication again.' }
|
||||
}
|
||||
|
||||
try {
|
||||
const status = await this.completeAuth(serverId, { code, iss })
|
||||
return status === 'authenticated'
|
||||
? { ok: true }
|
||||
: { ok: false, message: 'Authentication did not complete' }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
logger.error({ serverId, error }, 'MCP OAuth callback completion failed')
|
||||
await mcpDbStore.clearPendingAuth(serverId)
|
||||
return { ok: false, message }
|
||||
}
|
||||
}
|
||||
|
||||
async getAuthStatus(serverId: string): Promise<McpAuthStatus> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) throw new Error('MCP server not found')
|
||||
|
||||
const authType = server.authConfig?.type
|
||||
if (authType === 'none') return 'authenticated'
|
||||
if (authType === 'bearer') {
|
||||
return server.authConfig?.bearerToken ? 'authenticated' : 'not_authenticated'
|
||||
}
|
||||
|
||||
const pending = await mcpDbStore.getPendingAuth(serverId)
|
||||
if (pending) return 'in_progress'
|
||||
const hasTokens = await mcpDbStore.hasStoredTokens(serverId)
|
||||
if (!hasTokens) return 'not_authenticated'
|
||||
const expired = await mcpDbStore.isTokenExpired(serverId)
|
||||
return expired ? 'expired' : 'authenticated'
|
||||
}
|
||||
|
||||
async removeAuth(serverId: string): Promise<void> {
|
||||
await mcpDbStore.clearAllCredentials(serverId)
|
||||
await mcpDbStore.clearPendingAuth(serverId)
|
||||
await mcpDbStore.clearDiscoverySnapshot(serverId)
|
||||
await this.manager.close(serverId)
|
||||
await this.updateStatus(serverId, 'needs_auth', null)
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Agent integration
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Build the agent's MCP AgentTools: the single `mcp` proxy tool plus direct
|
||||
* tools for assigned servers in direct-tools mode. Returns [] when the agent
|
||||
* has no assigned servers (no proxy tool — don't waste LLM context).
|
||||
*/
|
||||
async buildAgentTools(agentId: string, teamId: string, userId?: string): Promise<AgentTool[]> {
|
||||
const assignments = await prisma.agentMcpServer.findMany({
|
||||
where: { agentId },
|
||||
include: { mcpServer: true },
|
||||
})
|
||||
if (assignments.length === 0) return []
|
||||
|
||||
// Per-agent tool registry: built fresh for this agent from the persisted
|
||||
// discovery cache (McpServer.tools). It only ever contains the agent's
|
||||
// assigned servers, so unassigned/disabled servers can neither be searched
|
||||
// nor called — no global mutable state to leak through.
|
||||
const registry = new McpToolRegistry()
|
||||
|
||||
const servers = assignments
|
||||
.map((a) => a.mcpServer)
|
||||
.map((s) => {
|
||||
const storedTools = (s.tools ?? []) as PrismaJson.McpToolInfo[]
|
||||
if (storedTools.length > 0) {
|
||||
registry.setTools(
|
||||
s.id,
|
||||
s.name,
|
||||
storedTools.map((t) => ({
|
||||
name: t.name,
|
||||
description: t.description ?? '',
|
||||
...(t.inputSchema !== undefined ? { inputSchema: t.inputSchema } : {}),
|
||||
})),
|
||||
)
|
||||
}
|
||||
return {
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
instructions: s.instructions ?? null,
|
||||
url: s.url,
|
||||
transport: s.transport,
|
||||
authConfig: (s.authConfig ?? {}) as PrismaJson.McpServerAuthConfig,
|
||||
config: (s.config ?? {}) as PrismaJson.McpServerConfig,
|
||||
tools: storedTools,
|
||||
status: s.status,
|
||||
}
|
||||
})
|
||||
|
||||
const serverNameById = new Map<string, string>()
|
||||
const serverIdByName = new Map<string, string>()
|
||||
const proxyServers = servers.map((s) => {
|
||||
serverNameById.set(s.id, s.name)
|
||||
serverIdByName.set(s.name, s.id)
|
||||
return {
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
toolCount: s.tools.length,
|
||||
status: s.status,
|
||||
...(s.instructions !== null && s.instructions !== undefined
|
||||
? { instructions: s.instructions }
|
||||
: {}),
|
||||
}
|
||||
})
|
||||
|
||||
const ctx: McpProxyToolContext = {
|
||||
teamId,
|
||||
userId,
|
||||
servers: proxyServers,
|
||||
serverNameById,
|
||||
serverIdByName,
|
||||
registry,
|
||||
resolveServerForTool: (toolName) => {
|
||||
// Longest {server}_ prefix match (dots/hyphens sanitized like the registry).
|
||||
let best: string | undefined
|
||||
let bestLen = 0
|
||||
for (const [sid, name] of serverNameById.entries()) {
|
||||
const prefix = sanitizeServerPrefix(name)
|
||||
if (toolName.startsWith(`${prefix}_`) && prefix.length > bestLen) {
|
||||
best = sid
|
||||
bestLen = prefix.length
|
||||
}
|
||||
}
|
||||
return best
|
||||
},
|
||||
ensureConnected: (serverId) => this.ensureConnected(serverId, registry),
|
||||
callTool: (serverId, toolName, args) =>
|
||||
this.callMcpTool(serverId, toolName, args, { teamId, userId }),
|
||||
authStatus: (serverId) => this.getAuthStatus(serverId),
|
||||
startAuth: (serverId) => this.startAuth(serverId),
|
||||
getInstructions: (serverId) => this.getServerInstructions(serverId),
|
||||
}
|
||||
|
||||
const tools: AgentTool[] = [buildProxyTool(ctx)]
|
||||
|
||||
for (const server of servers) {
|
||||
if (server.config?.directTools !== true) continue
|
||||
const metadata: ToolMetadata[] = registry.getTools(server.id)
|
||||
tools.push(
|
||||
...buildDirectTools(metadata, server.config, {
|
||||
serverId: server.id,
|
||||
serverName: server.name,
|
||||
callTool: (serverId, toolName, args) =>
|
||||
this.callMcpTool(serverId, toolName, args, { teamId, userId }),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
return tools
|
||||
}
|
||||
|
||||
/** Test a server by refreshing it and reporting the tool count (UI validation). */
|
||||
async testServer(
|
||||
serverId: string,
|
||||
): Promise<{ ok: boolean; toolCount: number; message?: string }> {
|
||||
try {
|
||||
const server = await this.refreshServer(serverId)
|
||||
return { ok: true, toolCount: server.toolCount }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return { ok: false, toolCount: 0, message }
|
||||
}
|
||||
}
|
||||
|
||||
/** Tool-name formatter ({server}_{tool}); exposed for tests. */
|
||||
getToolName(serverName: string, toolName: string): string {
|
||||
return formatToolName(serverName, toolName)
|
||||
}
|
||||
|
||||
private idleCleanupInterval?: ReturnType<typeof setInterval>
|
||||
|
||||
/** Start a periodic background timer to prune idle connections. Default check interval is 30 seconds. */
|
||||
startIdleCleanupTimer(intervalMs = 30 * 1000, defaultTimeoutMs?: number): void {
|
||||
if (this.idleCleanupInterval) return
|
||||
this.idleCleanupInterval = setInterval(() => {
|
||||
this.closeIdleConnections(defaultTimeoutMs).catch((error) => {
|
||||
logger.debug({ error }, 'Failed to close idle connections in background timer')
|
||||
})
|
||||
}, intervalMs)
|
||||
this.idleCleanupInterval.unref?.()
|
||||
}
|
||||
|
||||
/** Stop the background idle cleanup timer. */
|
||||
stopIdleCleanupTimer(): void {
|
||||
if (this.idleCleanupInterval) {
|
||||
clearInterval(this.idleCleanupInterval)
|
||||
this.idleCleanupInterval = undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Close all in-process MCP connections (used by tests/shutdown). */
|
||||
async closeAllConnections(): Promise<void> {
|
||||
this.stopIdleCleanupTimer()
|
||||
await this.manager.closeAll()
|
||||
}
|
||||
|
||||
/** Close idle connections across all active server connections. */
|
||||
async closeIdleConnections(defaultTimeoutMs?: number): Promise<string[]> {
|
||||
return this.manager.closeIdleConnections(defaultTimeoutMs)
|
||||
}
|
||||
|
||||
/** Number of live in-process connections (used by tests). */
|
||||
getConnectionCount(serverId: string): number {
|
||||
return this.manager.getConnection(serverId) ? 1 : 0
|
||||
}
|
||||
}
|
||||
|
||||
export const mcpService = new McpService()
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* In-process MCP test server for integration tests.
|
||||
*
|
||||
* Spins up a real Streamable HTTP MCP server on an ephemeral port using
|
||||
* `@modelcontextprotocol/server` (v2, stateless mode) and serves it over
|
||||
* Bun's web-standard fetch. Tests connect to it through the real MCP client
|
||||
* stack (`@modelcontextprotocol/client` v2), so connection lifecycle, tool
|
||||
* discovery, argument validation, and call round-trips are all exercised for
|
||||
* real — no mocks.
|
||||
*/
|
||||
|
||||
import { McpServer, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server'
|
||||
import { z, type ZodRawShape } from 'zod'
|
||||
|
||||
export interface TestMcpToolDef {
|
||||
name: string
|
||||
description?: string
|
||||
inputSchema?: ZodRawShape
|
||||
handler: (args: Record<string, unknown>) => Promise<unknown>
|
||||
/** When set, the tool returns an isError result with this text. */
|
||||
errorText?: string
|
||||
}
|
||||
|
||||
export interface TestMcpServerOptions {
|
||||
tools: TestMcpToolDef[]
|
||||
/** If set, respond with 401 to any request that lacks this bearer token. */
|
||||
bearerToken?: string
|
||||
/** Port to bind; defaults to an ephemeral port. */
|
||||
port?: number
|
||||
/** Override the server's self-reported identity (getServerVersion result). */
|
||||
serverInfo?: { name: string; title?: string; description?: string; instructions?: string }
|
||||
}
|
||||
|
||||
export interface RunningTestMcpServer {
|
||||
url: string
|
||||
port: number
|
||||
stop(): Promise<void>
|
||||
/** Requests received, in order, with their headers. */
|
||||
requests: Array<{ url: string; headers: Record<string, string> }>
|
||||
}
|
||||
|
||||
export async function startTestMcpServer(
|
||||
options: TestMcpServerOptions,
|
||||
): Promise<RunningTestMcpServer> {
|
||||
const { serverInfo } = options
|
||||
const server = new McpServer(
|
||||
{
|
||||
name: serverInfo?.name ?? 'test-mcp-server',
|
||||
version: '1.0.0',
|
||||
...(serverInfo?.title !== undefined ? { title: serverInfo.title } : {}),
|
||||
...(serverInfo?.description !== undefined ? { description: serverInfo.description } : {}),
|
||||
},
|
||||
serverInfo?.instructions !== undefined ? { instructions: serverInfo.instructions } : undefined,
|
||||
)
|
||||
// registerTool has overloads with incompatible zod type resolutions; bind a
|
||||
// narrow local signature so tool registration stays type-safe and simple.
|
||||
const registerTool = server.registerTool.bind(server) as unknown as (
|
||||
name: string,
|
||||
config: { description?: string; inputSchema?: ZodRawShape },
|
||||
cb: (args: Record<string, unknown>) => Promise<unknown> | unknown,
|
||||
) => unknown
|
||||
for (const tool of options.tools) {
|
||||
registerTool(
|
||||
tool.name,
|
||||
{
|
||||
description: tool.description ?? `Test tool ${tool.name}`,
|
||||
inputSchema: tool.inputSchema ?? {},
|
||||
},
|
||||
async (args) => {
|
||||
if (tool.errorText) {
|
||||
return {
|
||||
content: [{ type: 'text', text: tool.errorText }],
|
||||
isError: true,
|
||||
}
|
||||
}
|
||||
const result = await tool.handler(args as Record<string, unknown>)
|
||||
if (typeof result === 'string') {
|
||||
return { content: [{ type: 'text', text: result }] }
|
||||
}
|
||||
if (
|
||||
result &&
|
||||
typeof result === 'object' &&
|
||||
'structuredContent' in (result as Record<string, unknown>)
|
||||
) {
|
||||
const structuredContent = (result as Record<string, unknown>).structuredContent
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(structuredContent) }],
|
||||
structuredContent,
|
||||
}
|
||||
}
|
||||
return { content: [{ type: 'text', text: JSON.stringify(result) }] }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Stateless mode: one transport instance, no session IDs.
|
||||
const transport = new WebStandardStreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined,
|
||||
})
|
||||
await server.connect(transport)
|
||||
|
||||
const requests: RunningTestMcpServer['requests'] = []
|
||||
|
||||
const httpServer = Bun.serve({
|
||||
port: options.port ?? 0,
|
||||
idleTimeout: 30,
|
||||
async fetch(req) {
|
||||
requests.push({
|
||||
url: req.url,
|
||||
headers: Object.fromEntries(req.headers.entries()),
|
||||
})
|
||||
|
||||
if (options.bearerToken) {
|
||||
const auth = req.headers.get('authorization')
|
||||
if (auth !== `Bearer ${options.bearerToken}`) {
|
||||
return new Response('Unauthorized', { status: 401 })
|
||||
}
|
||||
}
|
||||
|
||||
const url = new URL(req.url)
|
||||
if (url.pathname === '/mcp') {
|
||||
return transport.handleRequest(req)
|
||||
}
|
||||
return new Response('not found', { status: 404 })
|
||||
},
|
||||
})
|
||||
|
||||
const port = httpServer.port as number
|
||||
return {
|
||||
url: `http://localhost:${port}/mcp`,
|
||||
port,
|
||||
requests,
|
||||
async stop() {
|
||||
await server.close().catch(() => {})
|
||||
httpServer.stop(true)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Common test tools: echo (returns string), add (structured math), list_sims. */
|
||||
export function standardTestTools(): TestMcpToolDef[] {
|
||||
return [
|
||||
{
|
||||
name: 'echo',
|
||||
description: 'Echoes the provided text back',
|
||||
inputSchema: { text: z.string() },
|
||||
handler: async (args) => `echo:${String(args.text)}`,
|
||||
},
|
||||
{
|
||||
name: 'add',
|
||||
description: 'Adds two numbers',
|
||||
inputSchema: { a: z.number(), b: z.number() },
|
||||
handler: async (args) => ({
|
||||
structuredContent: { sum: Number(args.a) + Number(args.b) },
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: 'list_sims',
|
||||
description: 'Lists simulator devices',
|
||||
handler: async () => ['iPhone 15 Pro', 'iPad Pro'],
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
McpToolRegistry,
|
||||
formatToolName,
|
||||
normalizeSearchText,
|
||||
sanitizeServerPrefix,
|
||||
tokenize,
|
||||
scoreToolMatch,
|
||||
paginate,
|
||||
} from './mcp-tool-registry'
|
||||
|
||||
function makeRegistry() {
|
||||
const registry = new McpToolRegistry()
|
||||
registry.setTools('server-1', 'xcodebuild', [
|
||||
{ name: 'list_sims', description: 'Lists available simulator devices' },
|
||||
{ name: 'build', description: 'Builds an Xcode project' },
|
||||
{ name: 'showBuildSettings', description: 'Shows build settings for a target' },
|
||||
])
|
||||
registry.setTools('server-2', 'github', [
|
||||
{ name: 'create_issue', description: 'Creates a GitHub issue' },
|
||||
{ name: 'list_issues', description: 'Lists issues in a repository' },
|
||||
{ name: 'search_code', description: 'Searches code across repositories' },
|
||||
])
|
||||
return registry
|
||||
}
|
||||
|
||||
describe('formatToolName', () => {
|
||||
it('prefixes server name and sanitizes dots', () => {
|
||||
expect(formatToolName('xcodebuild', 'list_sims')).toBe('xcodebuild_list_sims')
|
||||
expect(formatToolName('my-server', 'tool.name')).toBe('my_server_tool_name')
|
||||
})
|
||||
|
||||
it('sanitizes spaces and punctuation in the server prefix', () => {
|
||||
expect(formatToolName('Meta Server', 'echo')).toBe('Meta_Server_echo')
|
||||
expect(formatToolName('my.server/v1', 'list')).toBe('my_server_v1_list')
|
||||
expect(formatToolName('!!!', 'list')).toBe('list')
|
||||
})
|
||||
})
|
||||
|
||||
describe('sanitizeServerPrefix', () => {
|
||||
it('collapses non-alphanumeric runs into a single underscore', () => {
|
||||
expect(sanitizeServerPrefix('Meta Server')).toBe('Meta_Server')
|
||||
expect(sanitizeServerPrefix('github.com')).toBe('github_com')
|
||||
expect(sanitizeServerPrefix(' a b ')).toBe('a_b')
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeSearchText / tokenize', () => {
|
||||
it('splits camelCase, snake_case, dots and hyphens', () => {
|
||||
expect(tokenize('showBuildSettings')).toEqual(['show', 'build', 'settings'])
|
||||
expect(tokenize('list_sims')).toEqual(['list', 'sims'])
|
||||
expect(tokenize('search.code-v2')).toEqual(['search', 'code', 'v2'])
|
||||
})
|
||||
|
||||
it('lowercases input', () => {
|
||||
expect(normalizeSearchText('ListSims')).toBe('list sims')
|
||||
})
|
||||
})
|
||||
|
||||
describe('scoreToolMatch', () => {
|
||||
const tool = {
|
||||
name: 'xcodebuild_list_sims',
|
||||
originalName: 'list_sims',
|
||||
description: 'Lists available simulator devices',
|
||||
}
|
||||
|
||||
it('returns null for empty queries', () => {
|
||||
expect(scoreToolMatch(tool, 'xcodebuild', '')).toBeNull()
|
||||
expect(scoreToolMatch(tool, 'xcodebuild', ' ')).toBeNull()
|
||||
})
|
||||
|
||||
it('scores exact name matches highest', () => {
|
||||
const exact = scoreToolMatch(tool, 'xcodebuild', 'list_sims')
|
||||
const partial = scoreToolMatch(tool, 'xcodebuild', 'sims')
|
||||
const unrelated = scoreToolMatch(tool, 'xcodebuild', 'zzz')
|
||||
expect(exact).not.toBeNull()
|
||||
expect(partial).not.toBeNull()
|
||||
expect(unrelated).toBeNull()
|
||||
expect(exact!).toBeGreaterThan(partial!)
|
||||
})
|
||||
|
||||
it('matches camelCase queries against camelCase original names', () => {
|
||||
const camel = scoreToolMatch(
|
||||
{
|
||||
name: 'xcodebuild_showBuildSettings',
|
||||
originalName: 'showBuildSettings',
|
||||
description: 'Shows build settings',
|
||||
},
|
||||
'xcodebuild',
|
||||
'showBuildSettings',
|
||||
)
|
||||
expect(camel).not.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('registry searchTools', () => {
|
||||
it('finds tools across servers with ranking', () => {
|
||||
const registry = makeRegistry()
|
||||
const names = new Map([
|
||||
['server-1', 'xcodebuild'],
|
||||
['server-2', 'github'],
|
||||
])
|
||||
const { items, total } = registry.searchTools('list', undefined, names)
|
||||
expect(total).toBeGreaterThanOrEqual(2)
|
||||
// Both list_sims and list_issues should be found.
|
||||
const found = items.map((m) => m.tool.originalName)
|
||||
expect(found).toContain('list_sims')
|
||||
expect(found).toContain('list_issues')
|
||||
// Sorting is by score descending.
|
||||
for (let i = 1; i < items.length; i++) {
|
||||
expect(items[i - 1].score).toBeGreaterThanOrEqual(items[i].score)
|
||||
}
|
||||
})
|
||||
|
||||
it('scopes search to one server', () => {
|
||||
const registry = makeRegistry()
|
||||
const names = new Map([
|
||||
['server-1', 'xcodebuild'],
|
||||
['server-2', 'github'],
|
||||
])
|
||||
const { items, total } = registry.searchTools('list', 'server-1', names)
|
||||
expect(total).toBe(1)
|
||||
expect(items[0].tool.originalName).toBe('list_sims')
|
||||
})
|
||||
|
||||
it('honors limit/offset pagination', () => {
|
||||
const registry = makeRegistry()
|
||||
const names = new Map([
|
||||
['server-1', 'xcodebuild'],
|
||||
['server-2', 'github'],
|
||||
])
|
||||
const first = registry.searchTools('list', undefined, names, 1, 0)
|
||||
expect(first.items.length).toBe(1)
|
||||
expect(first.hasMore).toBe(true)
|
||||
const second = registry.searchTools('list', undefined, names, 1, 1)
|
||||
expect(second.items.length).toBe(1)
|
||||
expect(second.nextOffset).toBeNull()
|
||||
})
|
||||
|
||||
it('coverage gate rejects weak matches', () => {
|
||||
const registry = makeRegistry()
|
||||
const names = new Map([['server-1', 'xcodebuild']])
|
||||
const { total } = registry.searchTools('building skyscrapers', 'server-1', names)
|
||||
expect(total).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('registry findTool', () => {
|
||||
it('finds by prefixed or original name', () => {
|
||||
const registry = makeRegistry()
|
||||
expect(registry.findTool('xcodebuild_list_sims')?.tool.originalName).toBe('list_sims')
|
||||
expect(registry.findTool('list_sims')?.tool.originalName).toBe('list_sims')
|
||||
expect(registry.findTool('list_sims', 'server-1')?.tool.originalName).toBe('list_sims')
|
||||
expect(registry.findTool('list_sims', 'server-2')).toBeUndefined()
|
||||
expect(registry.findTool('nope')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns did-you-mean suggestions', () => {
|
||||
const registry = makeRegistry()
|
||||
const suggestions = registry.rankSuggestions(
|
||||
'xcodebuild_list_sim',
|
||||
5,
|
||||
new Map([
|
||||
['server-1', 'xcodebuild'],
|
||||
['server-2', 'github'],
|
||||
]),
|
||||
)
|
||||
expect(suggestions).toContain('xcodebuild_list_sims')
|
||||
})
|
||||
})
|
||||
|
||||
describe('paginate', () => {
|
||||
it('handles empty input and offsets beyond length', () => {
|
||||
expect(paginate([], 0, 10)).toEqual({ items: [], total: 0, hasMore: false, nextOffset: null })
|
||||
expect(paginate([1, 2, 3], 100, 10)).toEqual({
|
||||
items: [],
|
||||
total: 3,
|
||||
hasMore: false,
|
||||
nextOffset: null,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* MCP tool registry — in-memory tool metadata + search
|
||||
*
|
||||
* Per-agent registry of discovered tool metadata keyed by server id, created
|
||||
* fresh by `McpService.buildAgentTools` and warmed from the persisted DB
|
||||
* cache (`McpServer.tools`). Scoping discovery to the agent's assigned
|
||||
* servers means unassigned/disabled servers can never be searched, suggested,
|
||||
* or called. (Adapted from pi-mcp-adapter's ToolMetadata + search-ranking.ts.)
|
||||
*/
|
||||
|
||||
import type { McpTool } from './mcp-server-manager'
|
||||
|
||||
export interface ToolMetadata {
|
||||
/** Prefixed tool name (e.g. "xcodebuild_list_sims"). */
|
||||
name: string
|
||||
/** Original MCP tool name (e.g. "list_sims"). */
|
||||
originalName: string
|
||||
description: string
|
||||
inputSchema?: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a server name into a safe tool-name prefix: any run of
|
||||
* non-alphanumeric characters becomes a single underscore. Server-reported
|
||||
* names/titles may contain spaces, dots or other punctuation.
|
||||
*/
|
||||
export function sanitizeServerPrefix(serverName: string): string {
|
||||
return serverName.replace(/[^a-zA-Z0-9_]+/g, '_').replace(/^_+|_+$/g, '')
|
||||
}
|
||||
|
||||
/** Format a tool name with the "{server}_{tool}" prefix (dots sanitized). */
|
||||
export function formatToolName(serverName: string, toolName: string): string {
|
||||
const serverPart = sanitizeServerPrefix(serverName)
|
||||
const sanitized = toolName.replace(/\./g, '_')
|
||||
return serverPart ? `${serverPart}_${sanitized}` : sanitized
|
||||
}
|
||||
|
||||
const MIN_STEM_LENGTH = 4
|
||||
|
||||
const FIELD_WEIGHTS = {
|
||||
name: 12,
|
||||
originalName: 10,
|
||||
server: 8,
|
||||
description: 5,
|
||||
} as const
|
||||
|
||||
export interface RankedToolMatch {
|
||||
server: string
|
||||
tool: ToolMetadata
|
||||
score: number
|
||||
}
|
||||
|
||||
export function normalizeSearchText(value: string): string {
|
||||
return value
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.replace(/[_./:-]+/g, ' ')
|
||||
.toLowerCase()
|
||||
}
|
||||
|
||||
export function tokenize(value: string): string[] {
|
||||
return normalizeSearchText(value)
|
||||
.split(/[^a-z0-9]+/)
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
export function scoreToolMatch(tool: ToolMetadata, server: string, query: string): number | null {
|
||||
const normalizedQuery = normalizeSearchText(query).trim()
|
||||
const queryTokens = tokenize(query)
|
||||
if (queryTokens.length === 0) return null
|
||||
|
||||
const fields = {
|
||||
name: normalizeSearchText(tool.name),
|
||||
originalName: normalizeSearchText(tool.originalName),
|
||||
server: normalizeSearchText(server),
|
||||
description: normalizeSearchText(tool.description),
|
||||
}
|
||||
let score = 0
|
||||
let phraseMatched = false
|
||||
let wholeFieldExact = false
|
||||
const matchedTokens = new Set<string>()
|
||||
|
||||
for (const [field, value] of Object.entries(fields) as Array<
|
||||
[keyof typeof FIELD_WEIGHTS, string]
|
||||
>) {
|
||||
const weight = FIELD_WEIGHTS[field]
|
||||
const fieldTokens = tokenize(value)
|
||||
if (value === normalizedQuery) {
|
||||
score += weight * 14
|
||||
phraseMatched = true
|
||||
wholeFieldExact = true
|
||||
} else if (value.startsWith(normalizedQuery)) {
|
||||
score += weight * 9
|
||||
phraseMatched = true
|
||||
} else if (value.includes(normalizedQuery)) {
|
||||
score += weight * 6
|
||||
phraseMatched = true
|
||||
}
|
||||
|
||||
for (const token of queryTokens) {
|
||||
if (fieldTokens.includes(token)) {
|
||||
score += weight * 4
|
||||
matchedTokens.add(token)
|
||||
} else if (
|
||||
fieldTokens.some(
|
||||
(fieldToken) =>
|
||||
fieldToken.startsWith(token) ||
|
||||
(fieldToken.length >= MIN_STEM_LENGTH && token.startsWith(fieldToken)),
|
||||
)
|
||||
) {
|
||||
score += weight * 2
|
||||
matchedTokens.add(token)
|
||||
} else if (value.includes(token)) {
|
||||
score += weight
|
||||
matchedTokens.add(token)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const coverage = matchedTokens.size / queryTokens.length
|
||||
if (!phraseMatched && (queryTokens.length <= 2 ? coverage !== 1 : coverage < 0.6)) return null
|
||||
|
||||
score += coverage === 1 ? 25 : Math.round(coverage * 10)
|
||||
const firstQueryToken = queryTokens[0]
|
||||
if (firstQueryToken !== undefined && tokenize(fields.name).includes(firstQueryToken)) score += 8
|
||||
if (wholeFieldExact) score += 20
|
||||
return score
|
||||
}
|
||||
|
||||
export function paginate<T>(
|
||||
items: T[],
|
||||
offset: number,
|
||||
limit: number,
|
||||
): { items: T[]; total: number; hasMore: boolean; nextOffset: number | null } {
|
||||
const safeOffset = Number.isFinite(offset) ? Math.max(0, Math.trunc(offset)) : 0
|
||||
const safeLimit = Number.isFinite(limit) ? Math.max(1, Math.trunc(limit)) : 1
|
||||
const total = items.length
|
||||
const page = items.slice(safeOffset, safeOffset + safeLimit)
|
||||
const nextOffset = safeOffset + page.length
|
||||
return {
|
||||
items: page,
|
||||
total,
|
||||
hasMore: nextOffset < total,
|
||||
nextOffset: nextOffset < total ? nextOffset : null,
|
||||
}
|
||||
}
|
||||
|
||||
export class McpToolRegistry {
|
||||
private readonly metadataByServer = new Map<string, ToolMetadata[]>()
|
||||
|
||||
/** Rebuild the metadata for one server from its discovered tools. */
|
||||
setTools(serverId: string, serverName: string, tools: McpTool[]): void {
|
||||
const metadata: ToolMetadata[] = tools.map((tool) => ({
|
||||
name: formatToolName(serverName, tool.name),
|
||||
originalName: tool.name,
|
||||
description: tool.description ?? '',
|
||||
...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
|
||||
}))
|
||||
metadata.sort((a, b) => a.name.localeCompare(b.name))
|
||||
this.metadataByServer.set(serverId, metadata)
|
||||
}
|
||||
|
||||
getTools(serverId: string): ToolMetadata[] {
|
||||
return this.metadataByServer.get(serverId) ?? []
|
||||
}
|
||||
|
||||
getAllTools(): Array<{ serverId: string; serverName: string; tool: ToolMetadata }> {
|
||||
const result: Array<{ serverId: string; serverName: string; tool: ToolMetadata }> = []
|
||||
for (const [serverId, metadata] of this.metadataByServer.entries()) {
|
||||
for (const tool of metadata) {
|
||||
result.push({ serverId, serverName: serverId, tool })
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
clear(serverId: string): void {
|
||||
this.metadataByServer.delete(serverId)
|
||||
}
|
||||
|
||||
clearAll(): void {
|
||||
this.metadataByServer.clear()
|
||||
}
|
||||
|
||||
/** Find a tool by prefixed or original name, optionally within one server. */
|
||||
findTool(name: string, serverId?: string): { serverId: string; tool: ToolMetadata } | undefined {
|
||||
for (const [sid, metadata] of this.metadataByServer.entries()) {
|
||||
if (serverId && sid !== serverId) continue
|
||||
const found = metadata.find((tool) => tool.name === name || tool.originalName === name)
|
||||
if (found) return { serverId: sid, tool: found }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Ranked search across all (or one) server's tools. */
|
||||
searchTools(
|
||||
query: string,
|
||||
serverId?: string,
|
||||
serverNames: Map<string, string> = new Map(),
|
||||
limit = 12,
|
||||
offset = 0,
|
||||
): { items: RankedToolMatch[]; total: number; hasMore: boolean; nextOffset: number | null } {
|
||||
const matches: RankedToolMatch[] = []
|
||||
for (const [sid, metadata] of this.metadataByServer.entries()) {
|
||||
if (serverId && sid !== serverId) continue
|
||||
const serverName = serverNames.get(sid) ?? sid
|
||||
for (const tool of metadata) {
|
||||
const score = scoreToolMatch(tool, serverName, query)
|
||||
if (score !== null) matches.push({ server: sid, tool, score })
|
||||
}
|
||||
}
|
||||
matches.sort((a, b) => b.score - a.score || a.tool.name.localeCompare(b.tool.name))
|
||||
return paginate(matches, offset, limit)
|
||||
}
|
||||
|
||||
/** "Did you mean" suggestions for a tool name. */
|
||||
rankSuggestions(
|
||||
name: string,
|
||||
limit: number,
|
||||
serverNames: Map<string, string> = new Map(),
|
||||
): string[] {
|
||||
return this.searchTools(name, undefined, serverNames, limit, 0).items.map((m) => m.tool.name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { toToolParameters, formatSchema } from './mcp-tool-schema'
|
||||
import { Compile } from 'typebox/compile'
|
||||
|
||||
describe('toToolParameters', () => {
|
||||
it('passes through a plain object schema', () => {
|
||||
const schema = {
|
||||
type: 'object',
|
||||
properties: { query: { type: 'string' } },
|
||||
required: ['query'],
|
||||
}
|
||||
const params = toToolParameters(schema)
|
||||
expect(params).toMatchObject({ type: 'object', properties: { query: { type: 'string' } } })
|
||||
// The resulting schema must compile with the same validator pi-ai uses.
|
||||
expect(() => Compile(params)).not.toThrow()
|
||||
})
|
||||
|
||||
it('strips $schema / $id / $comment keywords', () => {
|
||||
const params = toToolParameters({
|
||||
$schema: 'http://json-schema.org/draft-07/schema#',
|
||||
$id: 'https://example.com/tool.json',
|
||||
$comment: 'strip me',
|
||||
type: 'object',
|
||||
properties: { a: { type: 'string' } },
|
||||
})
|
||||
expect(JSON.stringify(params)).not.toContain('$schema')
|
||||
expect(JSON.stringify(params)).not.toContain('$id')
|
||||
expect(JSON.stringify(params)).not.toContain('$comment')
|
||||
})
|
||||
|
||||
it('supports $defs / $ref schemas', () => {
|
||||
const params = toToolParameters({
|
||||
type: 'object',
|
||||
properties: { q: { $ref: '#/$defs/query' } },
|
||||
$defs: { query: { type: 'string' } },
|
||||
required: ['q'],
|
||||
})
|
||||
const compiled = Compile(params)
|
||||
expect(compiled.Check({ q: 'hello' })).toBe(true)
|
||||
})
|
||||
|
||||
it('supports anyOf and enums', () => {
|
||||
const params = toToolParameters({
|
||||
type: 'object',
|
||||
properties: {
|
||||
value: { anyOf: [{ type: 'string' }, { type: 'number' }] },
|
||||
color: { type: 'string', enum: ['red', 'blue'] },
|
||||
},
|
||||
})
|
||||
const compiled = Compile(params)
|
||||
expect(compiled.Check({ value: 42, color: 'red' })).toBe(true)
|
||||
expect(compiled.Check({ value: 'x', color: 'green' })).toBe(false)
|
||||
})
|
||||
|
||||
it('supports additionalProperties and patternProperties', () => {
|
||||
const params = toToolParameters({
|
||||
type: 'object',
|
||||
properties: { a: { type: 'string' } },
|
||||
additionalProperties: false,
|
||||
})
|
||||
const compiled = Compile(params)
|
||||
expect(compiled.Check({ a: 'x' })).toBe(true)
|
||||
|
||||
const patterned = toToolParameters({
|
||||
type: 'object',
|
||||
patternProperties: { '^x-': { type: 'string' } },
|
||||
})
|
||||
expect(() => Compile(patterned)).not.toThrow()
|
||||
})
|
||||
|
||||
it('normalizes non-object roots to an object', () => {
|
||||
expect(toToolParameters({ type: 'string' })).toMatchObject({ type: 'object' })
|
||||
})
|
||||
|
||||
it('falls back to a permissive record for invalid schemas', () => {
|
||||
const params = toToolParameters({ type: 'object', properties: { bad: { type: 'not-a-type' } } })
|
||||
const compiled = Compile(params)
|
||||
// Fallback must accept arbitrary arguments.
|
||||
expect(compiled.Check({ anything: 123, nested: { x: 1 } })).toBe(true)
|
||||
})
|
||||
|
||||
it('handles undefined / empty input', () => {
|
||||
expect(toToolParameters(undefined)).toMatchObject({ type: 'object' })
|
||||
expect(toToolParameters(null)).toMatchObject({ type: 'object' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatSchema', () => {
|
||||
it('formats JSON Schema as indented text', () => {
|
||||
const text = formatSchema({ type: 'object', properties: { a: { type: 'string' } } })
|
||||
expect(text).toContain('"type": "object"')
|
||||
expect(text).toContain('"properties"')
|
||||
})
|
||||
|
||||
it('returns empty string for non-objects', () => {
|
||||
expect(formatSchema(undefined)).toBe('')
|
||||
expect(formatSchema(42)).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* MCP tool schema conversion
|
||||
*
|
||||
* Normalizes an MCP tool's JSON Schema `inputSchema` into a TypeBox-compatible
|
||||
* `TSchema` that the pi-ai harness can validate and providers can serialize.
|
||||
*
|
||||
* - Ensures `type: 'object'` (MCP tool arguments are always objects).
|
||||
* - Strips keywords the harness does not understand (`$schema`, `$id`, `$comment`).
|
||||
* - Verifies the schema compiles with `typebox/compile`; if it does not, falls
|
||||
* back to a permissive `Record<string, unknown>` so the tool still works
|
||||
* (arguments pass through to `callTool`).
|
||||
*/
|
||||
|
||||
import { Compile } from 'typebox/compile'
|
||||
import { Type, type TSchema } from '@sinclair/typebox'
|
||||
|
||||
const STRIPPED_KEYS = new Set(['$schema', '$id', '$comment'])
|
||||
|
||||
function normalizeInputSchema(schema: unknown): Record<string, unknown> {
|
||||
if (!schema || typeof schema !== 'object' || Array.isArray(schema)) {
|
||||
return { type: 'object' }
|
||||
}
|
||||
const source = schema as Record<string, unknown>
|
||||
const result: Record<string, unknown> = {}
|
||||
for (const [key, value] of Object.entries(source)) {
|
||||
if (STRIPPED_KEYS.has(key)) continue
|
||||
if (value === undefined) continue
|
||||
result[key] = value
|
||||
}
|
||||
// MCP tool parameters are always a JSON object.
|
||||
if (result.type !== 'object' && result.type !== undefined) {
|
||||
result.type = 'object'
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an MCP `inputSchema` into an AgentTool `parameters` schema.
|
||||
*/
|
||||
export function toToolParameters(inputSchema: unknown): TSchema {
|
||||
const normalized = normalizeInputSchema(inputSchema)
|
||||
try {
|
||||
Compile(normalized)
|
||||
return normalized as TSchema
|
||||
} catch {
|
||||
// Fall back to a permissive object schema so the tool remains usable.
|
||||
return Type.Record(Type.String(), Type.Unknown())
|
||||
}
|
||||
}
|
||||
|
||||
/** Format a JSON Schema as indented text (used by proxy describe/search). */
|
||||
export function formatSchema(schema: unknown, indent = ''): string {
|
||||
if (!schema || typeof schema !== 'object') return ''
|
||||
try {
|
||||
return JSON.stringify(schema, null, 2)
|
||||
.split('\n')
|
||||
.map((line) => `${indent}${line}`)
|
||||
.join('\n')
|
||||
} catch {
|
||||
return String(schema)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "McpTransport" AS ENUM ('streamable_http', 'sse');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "mcp_servers" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"url" TEXT NOT NULL,
|
||||
"transport" "McpTransport" NOT NULL DEFAULT 'streamable_http',
|
||||
"authConfig" JSONB DEFAULT '{}',
|
||||
"config" JSONB DEFAULT '{}',
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"permission" "TeamMemberRole" NOT NULL DEFAULT 'reviewer',
|
||||
"tools" JSONB DEFAULT '[]',
|
||||
"status" TEXT NOT NULL DEFAULT 'not_connected',
|
||||
"last_error" TEXT,
|
||||
"last_connected_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
"team_id" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "mcp_servers_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "agent_mcp_servers" (
|
||||
"id" TEXT NOT NULL,
|
||||
"agent_id" TEXT NOT NULL,
|
||||
"mcp_server_id" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "agent_mcp_servers_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "mcp_server_credentials" (
|
||||
"id" TEXT NOT NULL,
|
||||
"server_id" TEXT NOT NULL,
|
||||
"server_url" TEXT NOT NULL,
|
||||
"tokens" JSONB,
|
||||
"clientInfo" JSONB,
|
||||
"code_verifier" TEXT,
|
||||
"oauth_state" TEXT,
|
||||
"pending_auth" JSONB,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "mcp_server_credentials_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "mcp_servers_team_id_name_key" ON "mcp_servers"("team_id", "name");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "agent_mcp_servers_agent_id_mcp_server_id_key" ON "agent_mcp_servers"("agent_id", "mcp_server_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "mcp_server_credentials_server_id_key" ON "mcp_server_credentials"("server_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "mcp_servers" ADD CONSTRAINT "mcp_servers_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "agent_mcp_servers" ADD CONSTRAINT "agent_mcp_servers_agent_id_fkey" FOREIGN KEY ("agent_id") REFERENCES "agents"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "agent_mcp_servers" ADD CONSTRAINT "agent_mcp_servers_mcp_server_id_fkey" FOREIGN KEY ("mcp_server_id") REFERENCES "mcp_servers"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "mcp_server_credentials" ADD CONSTRAINT "mcp_server_credentials_server_id_fkey" FOREIGN KEY ("server_id") REFERENCES "mcp_servers"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- You are about to drop the column `enabled` on the `mcp_servers` table. All the data in the column will be lost.
|
||||
|
||||
*/
|
||||
-- DropIndex
|
||||
DROP INDEX "mcp_servers_team_id_name_key";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "mcp_servers" DROP COLUMN "enabled",
|
||||
ADD COLUMN "description" TEXT;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "mcp_servers" ADD COLUMN "instructions" TEXT;
|
||||
@@ -252,6 +252,7 @@ model Team {
|
||||
userMetadata UserMetadata[] @relation("TeamToUserMetadata")
|
||||
providers Provider[] @relation("TeamToProvider")
|
||||
skills Skill[] @relation("TeamToSkill")
|
||||
mcpServers McpServer[] @relation("TeamToMcpServer")
|
||||
sandbox Sandbox? @relation("TeamToSandbox")
|
||||
agents Agent[] @relation("TeamToAgent")
|
||||
aiUsages AiUsage[] @relation("TeamToAiUsage")
|
||||
@@ -754,6 +755,7 @@ model Agent {
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
agentSessions AgentSession[]
|
||||
skills AgentSkill[]
|
||||
mcpServers AgentMcpServer[]
|
||||
|
||||
@@map("agents")
|
||||
}
|
||||
@@ -771,6 +773,73 @@ model AgentSkill {
|
||||
@@map("agent_skills")
|
||||
}
|
||||
|
||||
model McpServer {
|
||||
id String @id @default(ulid())
|
||||
name String
|
||||
description String?
|
||||
instructions String?
|
||||
url String
|
||||
transport McpTransport @default(streamable_http)
|
||||
/// [McpServerAuthConfig]
|
||||
authConfig Json? @default("{}")
|
||||
/// [McpServerConfig]
|
||||
config Json? @default("{}")
|
||||
permission TeamMemberRole @default(reviewer)
|
||||
/// [McpToolInfo[]]
|
||||
tools Json? @default("[]")
|
||||
status String @default("not_connected")
|
||||
lastError String? @map("last_error")
|
||||
lastConnectedAt DateTime? @map("last_connected_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
teamId String @map("team_id")
|
||||
team Team @relation("TeamToMcpServer", fields: [teamId], references: [id], onDelete: Cascade)
|
||||
|
||||
credential McpServerCredential?
|
||||
agentMcpServers AgentMcpServer[]
|
||||
|
||||
@@map("mcp_servers")
|
||||
}
|
||||
|
||||
// Join table: which agents get which MCP servers (mirrors AgentSkill).
|
||||
model AgentMcpServer {
|
||||
id String @id @default(ulid())
|
||||
agentId String @map("agent_id")
|
||||
agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
|
||||
mcpServerId String @map("mcp_server_id")
|
||||
mcpServer McpServer @relation(fields: [mcpServerId], references: [id], onDelete: Cascade)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@unique([agentId, mcpServerId])
|
||||
@@map("agent_mcp_servers")
|
||||
}
|
||||
|
||||
model McpServerCredential {
|
||||
id String @id @default(ulid())
|
||||
serverId String @unique @map("server_id")
|
||||
server McpServer @relation(fields: [serverId], references: [id], onDelete: Cascade)
|
||||
serverUrl String @map("server_url")
|
||||
/// [McpStoredTokens]
|
||||
tokens Json?
|
||||
/// [McpStoredClientInfo]
|
||||
clientInfo Json?
|
||||
codeVerifier String? @map("code_verifier")
|
||||
oauthState String? @map("oauth_state")
|
||||
/// [McpPendingAuth]
|
||||
pendingAuth Json? @map("pending_auth")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@map("mcp_server_credentials")
|
||||
}
|
||||
|
||||
enum McpTransport {
|
||||
streamable_http
|
||||
sse
|
||||
}
|
||||
|
||||
model AgentSession {
|
||||
id String @id @default(ulid())
|
||||
agentId String @map("agent_id")
|
||||
|
||||
+15
@@ -162,6 +162,21 @@ export type Agent = Prisma.AgentModel
|
||||
*
|
||||
*/
|
||||
export type AgentSkill = Prisma.AgentSkillModel
|
||||
/**
|
||||
* Model McpServer
|
||||
*
|
||||
*/
|
||||
export type McpServer = Prisma.McpServerModel
|
||||
/**
|
||||
* Model AgentMcpServer
|
||||
*
|
||||
*/
|
||||
export type AgentMcpServer = Prisma.AgentMcpServerModel
|
||||
/**
|
||||
* Model McpServerCredential
|
||||
*
|
||||
*/
|
||||
export type McpServerCredential = Prisma.McpServerCredentialModel
|
||||
/**
|
||||
* Model AgentSession
|
||||
*
|
||||
|
||||
+15
@@ -186,6 +186,21 @@ export type Agent = Prisma.AgentModel
|
||||
*
|
||||
*/
|
||||
export type AgentSkill = Prisma.AgentSkillModel
|
||||
/**
|
||||
* Model McpServer
|
||||
*
|
||||
*/
|
||||
export type McpServer = Prisma.McpServerModel
|
||||
/**
|
||||
* Model AgentMcpServer
|
||||
*
|
||||
*/
|
||||
export type AgentMcpServer = Prisma.AgentMcpServerModel
|
||||
/**
|
||||
* Model McpServerCredential
|
||||
*
|
||||
*/
|
||||
export type McpServerCredential = Prisma.McpServerCredentialModel
|
||||
/**
|
||||
* Model AgentSession
|
||||
*
|
||||
|
||||
@@ -687,6 +687,23 @@ export type EnumAgentTypeWithAggregatesFilter<$PrismaModel = never> = {
|
||||
_max?: Prisma.NestedEnumAgentTypeFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type EnumMcpTransportFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.McpTransport | Prisma.EnumMcpTransportFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.McpTransport[] | Prisma.ListEnumMcpTransportFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.McpTransport[] | Prisma.ListEnumMcpTransportFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumMcpTransportFilter<$PrismaModel> | $Enums.McpTransport
|
||||
}
|
||||
|
||||
export type EnumMcpTransportWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.McpTransport | Prisma.EnumMcpTransportFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.McpTransport[] | Prisma.ListEnumMcpTransportFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.McpTransport[] | Prisma.ListEnumMcpTransportFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumMcpTransportWithAggregatesFilter<$PrismaModel> | $Enums.McpTransport
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedEnumMcpTransportFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedEnumMcpTransportFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type EnumAgentSessionTypeFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.AgentSessionType | Prisma.EnumAgentSessionTypeFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.AgentSessionType[] | Prisma.ListEnumAgentSessionTypeFieldRefInput<$PrismaModel>
|
||||
@@ -1350,6 +1367,23 @@ export type NestedEnumAgentTypeWithAggregatesFilter<$PrismaModel = never> = {
|
||||
_max?: Prisma.NestedEnumAgentTypeFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedEnumMcpTransportFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.McpTransport | Prisma.EnumMcpTransportFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.McpTransport[] | Prisma.ListEnumMcpTransportFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.McpTransport[] | Prisma.ListEnumMcpTransportFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumMcpTransportFilter<$PrismaModel> | $Enums.McpTransport
|
||||
}
|
||||
|
||||
export type NestedEnumMcpTransportWithAggregatesFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.McpTransport | Prisma.EnumMcpTransportFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.McpTransport[] | Prisma.ListEnumMcpTransportFieldRefInput<$PrismaModel>
|
||||
notIn?: $Enums.McpTransport[] | Prisma.ListEnumMcpTransportFieldRefInput<$PrismaModel>
|
||||
not?: Prisma.NestedEnumMcpTransportWithAggregatesFilter<$PrismaModel> | $Enums.McpTransport
|
||||
_count?: Prisma.NestedIntFilter<$PrismaModel>
|
||||
_min?: Prisma.NestedEnumMcpTransportFilter<$PrismaModel>
|
||||
_max?: Prisma.NestedEnumMcpTransportFilter<$PrismaModel>
|
||||
}
|
||||
|
||||
export type NestedEnumAgentSessionTypeFilter<$PrismaModel = never> = {
|
||||
equals?: $Enums.AgentSessionType | Prisma.EnumAgentSessionTypeFieldRefInput<$PrismaModel>
|
||||
in?: $Enums.AgentSessionType[] | Prisma.ListEnumAgentSessionTypeFieldRefInput<$PrismaModel>
|
||||
|
||||
+8
@@ -189,3 +189,11 @@ export const AgentSessionType = {
|
||||
} as const
|
||||
|
||||
export type AgentSessionType = (typeof AgentSessionType)[keyof typeof AgentSessionType]
|
||||
|
||||
|
||||
export const McpTransport = {
|
||||
streamable_http: 'streamable_http',
|
||||
sse: 'sse'
|
||||
} as const
|
||||
|
||||
export type McpTransport = (typeof McpTransport)[keyof typeof McpTransport]
|
||||
|
||||
+34
-4
File diff suppressed because one or more lines are too long
+292
-1
@@ -413,6 +413,9 @@ export const ModelName = {
|
||||
WorkflowTask: 'WorkflowTask',
|
||||
Agent: 'Agent',
|
||||
AgentSkill: 'AgentSkill',
|
||||
McpServer: 'McpServer',
|
||||
AgentMcpServer: 'AgentMcpServer',
|
||||
McpServerCredential: 'McpServerCredential',
|
||||
AgentSession: 'AgentSession',
|
||||
AgentSessionEntry: 'AgentSessionEntry',
|
||||
UserMetadata: 'UserMetadata',
|
||||
@@ -437,7 +440,7 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
||||
omit: GlobalOmitOptions
|
||||
}
|
||||
meta: {
|
||||
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "sandbox" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "watermarkConfig" | "watermarkTemplate" | "watermarkFile" | "asset" | "storageKey" | "assetMetadataValue" | "assetComment" | "assetCommentAttachment" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "agentSession" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" | "aiUsage" | "auditLog"
|
||||
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "sandbox" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "watermarkConfig" | "watermarkTemplate" | "watermarkFile" | "asset" | "storageKey" | "assetMetadataValue" | "assetComment" | "assetCommentAttachment" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "mcpServer" | "agentMcpServer" | "mcpServerCredential" | "agentSession" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" | "aiUsage" | "auditLog"
|
||||
txIsolationLevel: TransactionIsolationLevel
|
||||
}
|
||||
model: {
|
||||
@@ -2587,6 +2590,228 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
||||
}
|
||||
}
|
||||
}
|
||||
McpServer: {
|
||||
payload: Prisma.$McpServerPayload<ExtArgs>
|
||||
fields: Prisma.McpServerFieldRefs
|
||||
operations: {
|
||||
findUnique: {
|
||||
args: Prisma.McpServerFindUniqueArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerPayload> | null
|
||||
}
|
||||
findUniqueOrThrow: {
|
||||
args: Prisma.McpServerFindUniqueOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerPayload>
|
||||
}
|
||||
findFirst: {
|
||||
args: Prisma.McpServerFindFirstArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerPayload> | null
|
||||
}
|
||||
findFirstOrThrow: {
|
||||
args: Prisma.McpServerFindFirstOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerPayload>
|
||||
}
|
||||
findMany: {
|
||||
args: Prisma.McpServerFindManyArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerPayload>[]
|
||||
}
|
||||
create: {
|
||||
args: Prisma.McpServerCreateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerPayload>
|
||||
}
|
||||
createMany: {
|
||||
args: Prisma.McpServerCreateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
createManyAndReturn: {
|
||||
args: Prisma.McpServerCreateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerPayload>[]
|
||||
}
|
||||
delete: {
|
||||
args: Prisma.McpServerDeleteArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerPayload>
|
||||
}
|
||||
update: {
|
||||
args: Prisma.McpServerUpdateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerPayload>
|
||||
}
|
||||
deleteMany: {
|
||||
args: Prisma.McpServerDeleteManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateMany: {
|
||||
args: Prisma.McpServerUpdateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateManyAndReturn: {
|
||||
args: Prisma.McpServerUpdateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerPayload>[]
|
||||
}
|
||||
upsert: {
|
||||
args: Prisma.McpServerUpsertArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerPayload>
|
||||
}
|
||||
aggregate: {
|
||||
args: Prisma.McpServerAggregateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.AggregateMcpServer>
|
||||
}
|
||||
groupBy: {
|
||||
args: Prisma.McpServerGroupByArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.McpServerGroupByOutputType>[]
|
||||
}
|
||||
count: {
|
||||
args: Prisma.McpServerCountArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.McpServerCountAggregateOutputType> | number
|
||||
}
|
||||
}
|
||||
}
|
||||
AgentMcpServer: {
|
||||
payload: Prisma.$AgentMcpServerPayload<ExtArgs>
|
||||
fields: Prisma.AgentMcpServerFieldRefs
|
||||
operations: {
|
||||
findUnique: {
|
||||
args: Prisma.AgentMcpServerFindUniqueArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$AgentMcpServerPayload> | null
|
||||
}
|
||||
findUniqueOrThrow: {
|
||||
args: Prisma.AgentMcpServerFindUniqueOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$AgentMcpServerPayload>
|
||||
}
|
||||
findFirst: {
|
||||
args: Prisma.AgentMcpServerFindFirstArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$AgentMcpServerPayload> | null
|
||||
}
|
||||
findFirstOrThrow: {
|
||||
args: Prisma.AgentMcpServerFindFirstOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$AgentMcpServerPayload>
|
||||
}
|
||||
findMany: {
|
||||
args: Prisma.AgentMcpServerFindManyArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$AgentMcpServerPayload>[]
|
||||
}
|
||||
create: {
|
||||
args: Prisma.AgentMcpServerCreateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$AgentMcpServerPayload>
|
||||
}
|
||||
createMany: {
|
||||
args: Prisma.AgentMcpServerCreateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
createManyAndReturn: {
|
||||
args: Prisma.AgentMcpServerCreateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$AgentMcpServerPayload>[]
|
||||
}
|
||||
delete: {
|
||||
args: Prisma.AgentMcpServerDeleteArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$AgentMcpServerPayload>
|
||||
}
|
||||
update: {
|
||||
args: Prisma.AgentMcpServerUpdateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$AgentMcpServerPayload>
|
||||
}
|
||||
deleteMany: {
|
||||
args: Prisma.AgentMcpServerDeleteManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateMany: {
|
||||
args: Prisma.AgentMcpServerUpdateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateManyAndReturn: {
|
||||
args: Prisma.AgentMcpServerUpdateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$AgentMcpServerPayload>[]
|
||||
}
|
||||
upsert: {
|
||||
args: Prisma.AgentMcpServerUpsertArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$AgentMcpServerPayload>
|
||||
}
|
||||
aggregate: {
|
||||
args: Prisma.AgentMcpServerAggregateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.AggregateAgentMcpServer>
|
||||
}
|
||||
groupBy: {
|
||||
args: Prisma.AgentMcpServerGroupByArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.AgentMcpServerGroupByOutputType>[]
|
||||
}
|
||||
count: {
|
||||
args: Prisma.AgentMcpServerCountArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.AgentMcpServerCountAggregateOutputType> | number
|
||||
}
|
||||
}
|
||||
}
|
||||
McpServerCredential: {
|
||||
payload: Prisma.$McpServerCredentialPayload<ExtArgs>
|
||||
fields: Prisma.McpServerCredentialFieldRefs
|
||||
operations: {
|
||||
findUnique: {
|
||||
args: Prisma.McpServerCredentialFindUniqueArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerCredentialPayload> | null
|
||||
}
|
||||
findUniqueOrThrow: {
|
||||
args: Prisma.McpServerCredentialFindUniqueOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerCredentialPayload>
|
||||
}
|
||||
findFirst: {
|
||||
args: Prisma.McpServerCredentialFindFirstArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerCredentialPayload> | null
|
||||
}
|
||||
findFirstOrThrow: {
|
||||
args: Prisma.McpServerCredentialFindFirstOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerCredentialPayload>
|
||||
}
|
||||
findMany: {
|
||||
args: Prisma.McpServerCredentialFindManyArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerCredentialPayload>[]
|
||||
}
|
||||
create: {
|
||||
args: Prisma.McpServerCredentialCreateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerCredentialPayload>
|
||||
}
|
||||
createMany: {
|
||||
args: Prisma.McpServerCredentialCreateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
createManyAndReturn: {
|
||||
args: Prisma.McpServerCredentialCreateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerCredentialPayload>[]
|
||||
}
|
||||
delete: {
|
||||
args: Prisma.McpServerCredentialDeleteArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerCredentialPayload>
|
||||
}
|
||||
update: {
|
||||
args: Prisma.McpServerCredentialUpdateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerCredentialPayload>
|
||||
}
|
||||
deleteMany: {
|
||||
args: Prisma.McpServerCredentialDeleteManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateMany: {
|
||||
args: Prisma.McpServerCredentialUpdateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateManyAndReturn: {
|
||||
args: Prisma.McpServerCredentialUpdateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerCredentialPayload>[]
|
||||
}
|
||||
upsert: {
|
||||
args: Prisma.McpServerCredentialUpsertArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$McpServerCredentialPayload>
|
||||
}
|
||||
aggregate: {
|
||||
args: Prisma.McpServerCredentialAggregateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.AggregateMcpServerCredential>
|
||||
}
|
||||
groupBy: {
|
||||
args: Prisma.McpServerCredentialGroupByArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.McpServerCredentialGroupByOutputType>[]
|
||||
}
|
||||
count: {
|
||||
args: Prisma.McpServerCredentialCountArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.McpServerCredentialCountAggregateOutputType> | number
|
||||
}
|
||||
}
|
||||
}
|
||||
AgentSession: {
|
||||
payload: Prisma.$AgentSessionPayload<ExtArgs>
|
||||
fields: Prisma.AgentSessionFieldRefs
|
||||
@@ -3717,6 +3942,55 @@ export const AgentSkillScalarFieldEnum = {
|
||||
export type AgentSkillScalarFieldEnum = (typeof AgentSkillScalarFieldEnum)[keyof typeof AgentSkillScalarFieldEnum]
|
||||
|
||||
|
||||
export const McpServerScalarFieldEnum = {
|
||||
id: 'id',
|
||||
name: 'name',
|
||||
description: 'description',
|
||||
instructions: 'instructions',
|
||||
url: 'url',
|
||||
transport: 'transport',
|
||||
authConfig: 'authConfig',
|
||||
config: 'config',
|
||||
permission: 'permission',
|
||||
tools: 'tools',
|
||||
status: 'status',
|
||||
lastError: 'lastError',
|
||||
lastConnectedAt: 'lastConnectedAt',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
teamId: 'teamId'
|
||||
} as const
|
||||
|
||||
export type McpServerScalarFieldEnum = (typeof McpServerScalarFieldEnum)[keyof typeof McpServerScalarFieldEnum]
|
||||
|
||||
|
||||
export const AgentMcpServerScalarFieldEnum = {
|
||||
id: 'id',
|
||||
agentId: 'agentId',
|
||||
mcpServerId: 'mcpServerId',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
} as const
|
||||
|
||||
export type AgentMcpServerScalarFieldEnum = (typeof AgentMcpServerScalarFieldEnum)[keyof typeof AgentMcpServerScalarFieldEnum]
|
||||
|
||||
|
||||
export const McpServerCredentialScalarFieldEnum = {
|
||||
id: 'id',
|
||||
serverId: 'serverId',
|
||||
serverUrl: 'serverUrl',
|
||||
tokens: 'tokens',
|
||||
clientInfo: 'clientInfo',
|
||||
codeVerifier: 'codeVerifier',
|
||||
oauthState: 'oauthState',
|
||||
pendingAuth: 'pendingAuth',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
} as const
|
||||
|
||||
export type McpServerCredentialScalarFieldEnum = (typeof McpServerCredentialScalarFieldEnum)[keyof typeof McpServerCredentialScalarFieldEnum]
|
||||
|
||||
|
||||
export const AgentSessionScalarFieldEnum = {
|
||||
id: 'id',
|
||||
agentId: 'agentId',
|
||||
@@ -4224,6 +4498,20 @@ export type ListEnumAgentTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$Pr
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'McpTransport'
|
||||
*/
|
||||
export type EnumMcpTransportFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'McpTransport'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'McpTransport[]'
|
||||
*/
|
||||
export type ListEnumMcpTransportFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'McpTransport[]'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'AgentSessionType'
|
||||
*/
|
||||
@@ -4376,6 +4664,9 @@ export type GlobalOmitConfig = {
|
||||
workflowTask?: Prisma.WorkflowTaskOmit
|
||||
agent?: Prisma.AgentOmit
|
||||
agentSkill?: Prisma.AgentSkillOmit
|
||||
mcpServer?: Prisma.McpServerOmit
|
||||
agentMcpServer?: Prisma.AgentMcpServerOmit
|
||||
mcpServerCredential?: Prisma.McpServerCredentialOmit
|
||||
agentSession?: Prisma.AgentSessionOmit
|
||||
agentSessionEntry?: Prisma.AgentSessionEntryOmit
|
||||
userMetadata?: Prisma.UserMetadataOmit
|
||||
|
||||
@@ -80,6 +80,9 @@ export const ModelName = {
|
||||
WorkflowTask: 'WorkflowTask',
|
||||
Agent: 'Agent',
|
||||
AgentSkill: 'AgentSkill',
|
||||
McpServer: 'McpServer',
|
||||
AgentMcpServer: 'AgentMcpServer',
|
||||
McpServerCredential: 'McpServerCredential',
|
||||
AgentSession: 'AgentSession',
|
||||
AgentSessionEntry: 'AgentSessionEntry',
|
||||
UserMetadata: 'UserMetadata',
|
||||
@@ -532,6 +535,55 @@ export const AgentSkillScalarFieldEnum = {
|
||||
export type AgentSkillScalarFieldEnum = (typeof AgentSkillScalarFieldEnum)[keyof typeof AgentSkillScalarFieldEnum]
|
||||
|
||||
|
||||
export const McpServerScalarFieldEnum = {
|
||||
id: 'id',
|
||||
name: 'name',
|
||||
description: 'description',
|
||||
instructions: 'instructions',
|
||||
url: 'url',
|
||||
transport: 'transport',
|
||||
authConfig: 'authConfig',
|
||||
config: 'config',
|
||||
permission: 'permission',
|
||||
tools: 'tools',
|
||||
status: 'status',
|
||||
lastError: 'lastError',
|
||||
lastConnectedAt: 'lastConnectedAt',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
teamId: 'teamId'
|
||||
} as const
|
||||
|
||||
export type McpServerScalarFieldEnum = (typeof McpServerScalarFieldEnum)[keyof typeof McpServerScalarFieldEnum]
|
||||
|
||||
|
||||
export const AgentMcpServerScalarFieldEnum = {
|
||||
id: 'id',
|
||||
agentId: 'agentId',
|
||||
mcpServerId: 'mcpServerId',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
} as const
|
||||
|
||||
export type AgentMcpServerScalarFieldEnum = (typeof AgentMcpServerScalarFieldEnum)[keyof typeof AgentMcpServerScalarFieldEnum]
|
||||
|
||||
|
||||
export const McpServerCredentialScalarFieldEnum = {
|
||||
id: 'id',
|
||||
serverId: 'serverId',
|
||||
serverUrl: 'serverUrl',
|
||||
tokens: 'tokens',
|
||||
clientInfo: 'clientInfo',
|
||||
codeVerifier: 'codeVerifier',
|
||||
oauthState: 'oauthState',
|
||||
pendingAuth: 'pendingAuth',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt'
|
||||
} as const
|
||||
|
||||
export type McpServerCredentialScalarFieldEnum = (typeof McpServerCredentialScalarFieldEnum)[keyof typeof McpServerCredentialScalarFieldEnum]
|
||||
|
||||
|
||||
export const AgentSessionScalarFieldEnum = {
|
||||
id: 'id',
|
||||
agentId: 'agentId',
|
||||
|
||||
+3
@@ -37,6 +37,9 @@ export type * from './models/Task.ts'
|
||||
export type * from './models/WorkflowTask.ts'
|
||||
export type * from './models/Agent.ts'
|
||||
export type * from './models/AgentSkill.ts'
|
||||
export type * from './models/McpServer.ts'
|
||||
export type * from './models/AgentMcpServer.ts'
|
||||
export type * from './models/McpServerCredential.ts'
|
||||
export type * from './models/AgentSession.ts'
|
||||
export type * from './models/AgentSessionEntry.ts'
|
||||
export type * from './models/UserMetadata.ts'
|
||||
|
||||
+158
@@ -226,6 +226,7 @@ export type AgentWhereInput = {
|
||||
team?: Prisma.XOR<Prisma.TeamScalarRelationFilter, Prisma.TeamWhereInput>
|
||||
agentSessions?: Prisma.AgentSessionListRelationFilter
|
||||
skills?: Prisma.AgentSkillListRelationFilter
|
||||
mcpServers?: Prisma.AgentMcpServerListRelationFilter
|
||||
}
|
||||
|
||||
export type AgentOrderByWithRelationInput = {
|
||||
@@ -245,6 +246,7 @@ export type AgentOrderByWithRelationInput = {
|
||||
team?: Prisma.TeamOrderByWithRelationInput
|
||||
agentSessions?: Prisma.AgentSessionOrderByRelationAggregateInput
|
||||
skills?: Prisma.AgentSkillOrderByRelationAggregateInput
|
||||
mcpServers?: Prisma.AgentMcpServerOrderByRelationAggregateInput
|
||||
}
|
||||
|
||||
export type AgentWhereUniqueInput = Prisma.AtLeast<{
|
||||
@@ -267,6 +269,7 @@ export type AgentWhereUniqueInput = Prisma.AtLeast<{
|
||||
team?: Prisma.XOR<Prisma.TeamScalarRelationFilter, Prisma.TeamWhereInput>
|
||||
agentSessions?: Prisma.AgentSessionListRelationFilter
|
||||
skills?: Prisma.AgentSkillListRelationFilter
|
||||
mcpServers?: Prisma.AgentMcpServerListRelationFilter
|
||||
}, "id">
|
||||
|
||||
export type AgentOrderByWithAggregationInput = {
|
||||
@@ -314,6 +317,7 @@ export type AgentCreateInput = {
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedCreateInput = {
|
||||
@@ -329,6 +333,7 @@ export type AgentUncheckedCreateInput = {
|
||||
updatedAt?: Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillUncheckedCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentUpdateInput = {
|
||||
@@ -344,6 +349,7 @@ export type AgentUpdateInput = {
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateInput = {
|
||||
@@ -359,6 +365,7 @@ export type AgentUncheckedUpdateInput = {
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUncheckedUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentCreateManyInput = {
|
||||
@@ -545,6 +552,20 @@ export type AgentUpdateOneRequiredWithoutSkillsNestedInput = {
|
||||
update?: Prisma.XOR<Prisma.XOR<Prisma.AgentUpdateToOneWithWhereWithoutSkillsInput, Prisma.AgentUpdateWithoutSkillsInput>, Prisma.AgentUncheckedUpdateWithoutSkillsInput>
|
||||
}
|
||||
|
||||
export type AgentCreateNestedOneWithoutMcpServersInput = {
|
||||
create?: Prisma.XOR<Prisma.AgentCreateWithoutMcpServersInput, Prisma.AgentUncheckedCreateWithoutMcpServersInput>
|
||||
connectOrCreate?: Prisma.AgentCreateOrConnectWithoutMcpServersInput
|
||||
connect?: Prisma.AgentWhereUniqueInput
|
||||
}
|
||||
|
||||
export type AgentUpdateOneRequiredWithoutMcpServersNestedInput = {
|
||||
create?: Prisma.XOR<Prisma.AgentCreateWithoutMcpServersInput, Prisma.AgentUncheckedCreateWithoutMcpServersInput>
|
||||
connectOrCreate?: Prisma.AgentCreateOrConnectWithoutMcpServersInput
|
||||
upsert?: Prisma.AgentUpsertWithoutMcpServersInput
|
||||
connect?: Prisma.AgentWhereUniqueInput
|
||||
update?: Prisma.XOR<Prisma.XOR<Prisma.AgentUpdateToOneWithWhereWithoutMcpServersInput, Prisma.AgentUpdateWithoutMcpServersInput>, Prisma.AgentUncheckedUpdateWithoutMcpServersInput>
|
||||
}
|
||||
|
||||
export type AgentCreateNestedOneWithoutAgentSessionsInput = {
|
||||
create?: Prisma.XOR<Prisma.AgentCreateWithoutAgentSessionsInput, Prisma.AgentUncheckedCreateWithoutAgentSessionsInput>
|
||||
connectOrCreate?: Prisma.AgentCreateOrConnectWithoutAgentSessionsInput
|
||||
@@ -655,6 +676,7 @@ export type AgentCreateWithoutUserInput = {
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedCreateWithoutUserInput = {
|
||||
@@ -669,6 +691,7 @@ export type AgentUncheckedCreateWithoutUserInput = {
|
||||
updatedAt?: Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillUncheckedCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentCreateOrConnectWithoutUserInput = {
|
||||
@@ -699,6 +722,7 @@ export type AgentUpdateWithoutUserInput = {
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateWithoutUserInput = {
|
||||
@@ -713,6 +737,7 @@ export type AgentUncheckedUpdateWithoutUserInput = {
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUncheckedUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentCreateWithoutTeamInput = {
|
||||
@@ -727,6 +752,7 @@ export type AgentCreateWithoutTeamInput = {
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedCreateWithoutTeamInput = {
|
||||
@@ -741,6 +767,7 @@ export type AgentUncheckedCreateWithoutTeamInput = {
|
||||
updatedAt?: Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillUncheckedCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentCreateOrConnectWithoutTeamInput = {
|
||||
@@ -797,6 +824,7 @@ export type AgentCreateWithoutSkillsInput = {
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedCreateWithoutSkillsInput = {
|
||||
@@ -811,6 +839,7 @@ export type AgentUncheckedCreateWithoutSkillsInput = {
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentCreateOrConnectWithoutSkillsInput = {
|
||||
@@ -841,6 +870,7 @@ export type AgentUpdateWithoutSkillsInput = {
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateWithoutSkillsInput = {
|
||||
@@ -855,6 +885,83 @@ export type AgentUncheckedUpdateWithoutSkillsInput = {
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentCreateWithoutMcpServersInput = {
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
soul?: string | null
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
user: Prisma.UserCreateNestedOneWithoutAgentInput
|
||||
provider?: Prisma.ProviderCreateNestedOneWithoutAgentsInput
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedCreateWithoutMcpServersInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillUncheckedCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentCreateOrConnectWithoutMcpServersInput = {
|
||||
where: Prisma.AgentWhereUniqueInput
|
||||
create: Prisma.XOR<Prisma.AgentCreateWithoutMcpServersInput, Prisma.AgentUncheckedCreateWithoutMcpServersInput>
|
||||
}
|
||||
|
||||
export type AgentUpsertWithoutMcpServersInput = {
|
||||
update: Prisma.XOR<Prisma.AgentUpdateWithoutMcpServersInput, Prisma.AgentUncheckedUpdateWithoutMcpServersInput>
|
||||
create: Prisma.XOR<Prisma.AgentCreateWithoutMcpServersInput, Prisma.AgentUncheckedCreateWithoutMcpServersInput>
|
||||
where?: Prisma.AgentWhereInput
|
||||
}
|
||||
|
||||
export type AgentUpdateToOneWithWhereWithoutMcpServersInput = {
|
||||
where?: Prisma.AgentWhereInput
|
||||
data: Prisma.XOR<Prisma.AgentUpdateWithoutMcpServersInput, Prisma.AgentUncheckedUpdateWithoutMcpServersInput>
|
||||
}
|
||||
|
||||
export type AgentUpdateWithoutMcpServersInput = {
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
user?: Prisma.UserUpdateOneRequiredWithoutAgentNestedInput
|
||||
provider?: Prisma.ProviderUpdateOneWithoutAgentsNestedInput
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateWithoutMcpServersInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUncheckedUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentCreateWithoutAgentSessionsInput = {
|
||||
@@ -869,6 +976,7 @@ export type AgentCreateWithoutAgentSessionsInput = {
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedCreateWithoutAgentSessionsInput = {
|
||||
@@ -883,6 +991,7 @@ export type AgentUncheckedCreateWithoutAgentSessionsInput = {
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
skills?: Prisma.AgentSkillUncheckedCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentCreateOrConnectWithoutAgentSessionsInput = {
|
||||
@@ -913,6 +1022,7 @@ export type AgentUpdateWithoutAgentSessionsInput = {
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateWithoutAgentSessionsInput = {
|
||||
@@ -927,6 +1037,7 @@ export type AgentUncheckedUpdateWithoutAgentSessionsInput = {
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
skills?: Prisma.AgentSkillUncheckedUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentCreateWithoutModelRefInput = {
|
||||
@@ -941,6 +1052,7 @@ export type AgentCreateWithoutModelRefInput = {
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedCreateWithoutModelRefInput = {
|
||||
@@ -955,6 +1067,7 @@ export type AgentUncheckedCreateWithoutModelRefInput = {
|
||||
updatedAt?: Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillUncheckedCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentCreateOrConnectWithoutModelRefInput = {
|
||||
@@ -995,6 +1108,7 @@ export type AgentCreateWithoutProviderInput = {
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedCreateWithoutProviderInput = {
|
||||
@@ -1009,6 +1123,7 @@ export type AgentUncheckedCreateWithoutProviderInput = {
|
||||
updatedAt?: Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillUncheckedCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentCreateOrConnectWithoutProviderInput = {
|
||||
@@ -1061,6 +1176,7 @@ export type AgentUpdateWithoutTeamInput = {
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateWithoutTeamInput = {
|
||||
@@ -1075,6 +1191,7 @@ export type AgentUncheckedUpdateWithoutTeamInput = {
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUncheckedUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateManyWithoutTeamInput = {
|
||||
@@ -1113,6 +1230,7 @@ export type AgentUpdateWithoutModelRefInput = {
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateWithoutModelRefInput = {
|
||||
@@ -1127,6 +1245,7 @@ export type AgentUncheckedUpdateWithoutModelRefInput = {
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUncheckedUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateManyWithoutModelRefInput = {
|
||||
@@ -1165,6 +1284,7 @@ export type AgentUpdateWithoutProviderInput = {
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateWithoutProviderInput = {
|
||||
@@ -1179,6 +1299,7 @@ export type AgentUncheckedUpdateWithoutProviderInput = {
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUncheckedUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateManyWithoutProviderInput = {
|
||||
@@ -1201,11 +1322,13 @@ export type AgentUncheckedUpdateManyWithoutProviderInput = {
|
||||
export type AgentCountOutputType = {
|
||||
agentSessions: number
|
||||
skills: number
|
||||
mcpServers: number
|
||||
}
|
||||
|
||||
export type AgentCountOutputTypeSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
agentSessions?: boolean | AgentCountOutputTypeCountAgentSessionsArgs
|
||||
skills?: boolean | AgentCountOutputTypeCountSkillsArgs
|
||||
mcpServers?: boolean | AgentCountOutputTypeCountMcpServersArgs
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1232,6 +1355,13 @@ export type AgentCountOutputTypeCountSkillsArgs<ExtArgs extends runtime.Types.Ex
|
||||
where?: Prisma.AgentSkillWhereInput
|
||||
}
|
||||
|
||||
/**
|
||||
* AgentCountOutputType without action
|
||||
*/
|
||||
export type AgentCountOutputTypeCountMcpServersArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
where?: Prisma.AgentMcpServerWhereInput
|
||||
}
|
||||
|
||||
|
||||
export type AgentSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetSelect<{
|
||||
id?: boolean
|
||||
@@ -1250,6 +1380,7 @@ export type AgentSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs =
|
||||
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
|
||||
agentSessions?: boolean | Prisma.Agent$agentSessionsArgs<ExtArgs>
|
||||
skills?: boolean | Prisma.Agent$skillsArgs<ExtArgs>
|
||||
mcpServers?: boolean | Prisma.Agent$mcpServersArgs<ExtArgs>
|
||||
_count?: boolean | Prisma.AgentCountOutputTypeDefaultArgs<ExtArgs>
|
||||
}, ExtArgs["result"]["agent"]>
|
||||
|
||||
@@ -1308,6 +1439,7 @@ export type AgentInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs =
|
||||
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
|
||||
agentSessions?: boolean | Prisma.Agent$agentSessionsArgs<ExtArgs>
|
||||
skills?: boolean | Prisma.Agent$skillsArgs<ExtArgs>
|
||||
mcpServers?: boolean | Prisma.Agent$mcpServersArgs<ExtArgs>
|
||||
_count?: boolean | Prisma.AgentCountOutputTypeDefaultArgs<ExtArgs>
|
||||
}
|
||||
export type AgentIncludeCreateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
@@ -1332,6 +1464,7 @@ export type $AgentPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs
|
||||
team: Prisma.$TeamPayload<ExtArgs>
|
||||
agentSessions: Prisma.$AgentSessionPayload<ExtArgs>[]
|
||||
skills: Prisma.$AgentSkillPayload<ExtArgs>[]
|
||||
mcpServers: Prisma.$AgentMcpServerPayload<ExtArgs>[]
|
||||
}
|
||||
scalars: runtime.Types.Extensions.GetPayloadResult<{
|
||||
id: string
|
||||
@@ -1747,6 +1880,7 @@ export interface Prisma__AgentClient<T, Null = never, ExtArgs extends runtime.Ty
|
||||
team<T extends Prisma.TeamDefaultArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.TeamDefaultArgs<ExtArgs>>): Prisma.Prisma__TeamClient<runtime.Types.Result.GetResult<Prisma.$TeamPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | Null, Null, ExtArgs, GlobalOmitOptions>
|
||||
agentSessions<T extends Prisma.Agent$agentSessionsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Agent$agentSessionsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentSessionPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
skills<T extends Prisma.Agent$skillsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Agent$skillsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentSkillPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
mcpServers<T extends Prisma.Agent$mcpServersArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Agent$mcpServersArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentMcpServerPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
/**
|
||||
* Attaches callbacks for the resolution and/or rejection of the Promise.
|
||||
* @param onfulfilled The callback to execute when the Promise is resolved.
|
||||
@@ -2272,6 +2406,30 @@ export type Agent$skillsArgs<ExtArgs extends runtime.Types.Extensions.InternalAr
|
||||
distinct?: Prisma.AgentSkillScalarFieldEnum | Prisma.AgentSkillScalarFieldEnum[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent.mcpServers
|
||||
*/
|
||||
export type Agent$mcpServersArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
/**
|
||||
* Select specific fields to fetch from the AgentMcpServer
|
||||
*/
|
||||
select?: Prisma.AgentMcpServerSelect<ExtArgs> | null
|
||||
/**
|
||||
* Omit specific fields from the AgentMcpServer
|
||||
*/
|
||||
omit?: Prisma.AgentMcpServerOmit<ExtArgs> | null
|
||||
/**
|
||||
* Choose, which related nodes to fetch as well
|
||||
*/
|
||||
include?: Prisma.AgentMcpServerInclude<ExtArgs> | null
|
||||
where?: Prisma.AgentMcpServerWhereInput
|
||||
orderBy?: Prisma.AgentMcpServerOrderByWithRelationInput | Prisma.AgentMcpServerOrderByWithRelationInput[]
|
||||
cursor?: Prisma.AgentMcpServerWhereUniqueInput
|
||||
take?: number
|
||||
skip?: number
|
||||
distinct?: Prisma.AgentMcpServerScalarFieldEnum | Prisma.AgentMcpServerScalarFieldEnum[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent without action
|
||||
*/
|
||||
|
||||
+1473
File diff suppressed because it is too large
Load Diff
+2056
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+218
@@ -197,6 +197,7 @@ export type TeamWhereInput = {
|
||||
userMetadata?: Prisma.UserMetadataListRelationFilter
|
||||
providers?: Prisma.ProviderListRelationFilter
|
||||
skills?: Prisma.SkillListRelationFilter
|
||||
mcpServers?: Prisma.McpServerListRelationFilter
|
||||
sandbox?: Prisma.XOR<Prisma.SandboxNullableScalarRelationFilter, Prisma.SandboxWhereInput> | null
|
||||
agents?: Prisma.AgentListRelationFilter
|
||||
aiUsages?: Prisma.AiUsageListRelationFilter
|
||||
@@ -220,6 +221,7 @@ export type TeamOrderByWithRelationInput = {
|
||||
userMetadata?: Prisma.UserMetadataOrderByRelationAggregateInput
|
||||
providers?: Prisma.ProviderOrderByRelationAggregateInput
|
||||
skills?: Prisma.SkillOrderByRelationAggregateInput
|
||||
mcpServers?: Prisma.McpServerOrderByRelationAggregateInput
|
||||
sandbox?: Prisma.SandboxOrderByWithRelationInput
|
||||
agents?: Prisma.AgentOrderByRelationAggregateInput
|
||||
aiUsages?: Prisma.AiUsageOrderByRelationAggregateInput
|
||||
@@ -246,6 +248,7 @@ export type TeamWhereUniqueInput = Prisma.AtLeast<{
|
||||
userMetadata?: Prisma.UserMetadataListRelationFilter
|
||||
providers?: Prisma.ProviderListRelationFilter
|
||||
skills?: Prisma.SkillListRelationFilter
|
||||
mcpServers?: Prisma.McpServerListRelationFilter
|
||||
sandbox?: Prisma.XOR<Prisma.SandboxNullableScalarRelationFilter, Prisma.SandboxWhereInput> | null
|
||||
agents?: Prisma.AgentListRelationFilter
|
||||
aiUsages?: Prisma.AiUsageListRelationFilter
|
||||
@@ -292,6 +295,7 @@ export type TeamCreateInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
@@ -314,6 +318,7 @@ export type TeamUncheckedCreateInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -336,6 +341,7 @@ export type TeamUpdateInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
@@ -358,6 +364,7 @@ export type TeamUncheckedUpdateInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -588,6 +595,20 @@ export type TeamUpdateOneRequiredWithoutAgentsNestedInput = {
|
||||
update?: Prisma.XOR<Prisma.XOR<Prisma.TeamUpdateToOneWithWhereWithoutAgentsInput, Prisma.TeamUpdateWithoutAgentsInput>, Prisma.TeamUncheckedUpdateWithoutAgentsInput>
|
||||
}
|
||||
|
||||
export type TeamCreateNestedOneWithoutMcpServersInput = {
|
||||
create?: Prisma.XOR<Prisma.TeamCreateWithoutMcpServersInput, Prisma.TeamUncheckedCreateWithoutMcpServersInput>
|
||||
connectOrCreate?: Prisma.TeamCreateOrConnectWithoutMcpServersInput
|
||||
connect?: Prisma.TeamWhereUniqueInput
|
||||
}
|
||||
|
||||
export type TeamUpdateOneRequiredWithoutMcpServersNestedInput = {
|
||||
create?: Prisma.XOR<Prisma.TeamCreateWithoutMcpServersInput, Prisma.TeamUncheckedCreateWithoutMcpServersInput>
|
||||
connectOrCreate?: Prisma.TeamCreateOrConnectWithoutMcpServersInput
|
||||
upsert?: Prisma.TeamUpsertWithoutMcpServersInput
|
||||
connect?: Prisma.TeamWhereUniqueInput
|
||||
update?: Prisma.XOR<Prisma.XOR<Prisma.TeamUpdateToOneWithWhereWithoutMcpServersInput, Prisma.TeamUpdateWithoutMcpServersInput>, Prisma.TeamUncheckedUpdateWithoutMcpServersInput>
|
||||
}
|
||||
|
||||
export type TeamCreateNestedOneWithoutUserMetadataInput = {
|
||||
create?: Prisma.XOR<Prisma.TeamCreateWithoutUserMetadataInput, Prisma.TeamUncheckedCreateWithoutUserMetadataInput>
|
||||
connectOrCreate?: Prisma.TeamCreateOrConnectWithoutUserMetadataInput
|
||||
@@ -659,6 +680,7 @@ export type TeamCreateWithoutSandboxInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -680,6 +702,7 @@ export type TeamUncheckedCreateWithoutSandboxInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -717,6 +740,7 @@ export type TeamUpdateWithoutSandboxInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -738,6 +762,7 @@ export type TeamUncheckedUpdateWithoutSandboxInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -758,6 +783,7 @@ export type TeamCreateWithoutSkillsInput = {
|
||||
notifications?: Prisma.NotificationCreateNestedManyWithoutTeamInput
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
@@ -779,6 +805,7 @@ export type TeamUncheckedCreateWithoutSkillsInput = {
|
||||
notifications?: Prisma.NotificationUncheckedCreateNestedManyWithoutTeamInput
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -816,6 +843,7 @@ export type TeamUpdateWithoutSkillsInput = {
|
||||
notifications?: Prisma.NotificationUpdateManyWithoutTeamNestedInput
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
@@ -837,6 +865,7 @@ export type TeamUncheckedUpdateWithoutSkillsInput = {
|
||||
notifications?: Prisma.NotificationUncheckedUpdateManyWithoutTeamNestedInput
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -858,6 +887,7 @@ export type TeamCreateWithoutMembersInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
@@ -879,6 +909,7 @@ export type TeamUncheckedCreateWithoutMembersInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -916,6 +947,7 @@ export type TeamUpdateWithoutMembersInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
@@ -937,6 +969,7 @@ export type TeamUncheckedUpdateWithoutMembersInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -958,6 +991,7 @@ export type TeamCreateWithoutProjectsInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
@@ -979,6 +1013,7 @@ export type TeamUncheckedCreateWithoutProjectsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1016,6 +1051,7 @@ export type TeamUpdateWithoutProjectsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
@@ -1037,6 +1073,7 @@ export type TeamUncheckedUpdateWithoutProjectsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1059,6 +1096,7 @@ export type TeamCreateWithoutWatermarkTemplatesInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
@@ -1080,6 +1118,7 @@ export type TeamUncheckedCreateWithoutWatermarkTemplatesInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1117,6 +1156,7 @@ export type TeamUpdateWithoutWatermarkTemplatesInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
@@ -1138,6 +1178,7 @@ export type TeamUncheckedUpdateWithoutWatermarkTemplatesInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1158,6 +1199,7 @@ export type TeamCreateWithoutRootFolderInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
@@ -1179,6 +1221,7 @@ export type TeamUncheckedCreateWithoutRootFolderInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1216,6 +1259,7 @@ export type TeamUpdateWithoutRootFolderInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
@@ -1237,6 +1281,7 @@ export type TeamUncheckedUpdateWithoutRootFolderInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1258,6 +1303,7 @@ export type TeamCreateWithoutInvitesInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
@@ -1279,6 +1325,7 @@ export type TeamUncheckedCreateWithoutInvitesInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1316,6 +1363,7 @@ export type TeamUpdateWithoutInvitesInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
@@ -1337,6 +1385,7 @@ export type TeamUncheckedUpdateWithoutInvitesInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1358,6 +1407,7 @@ export type TeamCreateWithoutMetadataFieldsInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
@@ -1379,6 +1429,7 @@ export type TeamUncheckedCreateWithoutMetadataFieldsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1416,6 +1467,7 @@ export type TeamUpdateWithoutMetadataFieldsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
@@ -1437,6 +1489,7 @@ export type TeamUncheckedUpdateWithoutMetadataFieldsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1458,6 +1511,7 @@ export type TeamCreateWithoutNotificationsInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
@@ -1479,6 +1533,7 @@ export type TeamUncheckedCreateWithoutNotificationsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1516,6 +1571,7 @@ export type TeamUpdateWithoutNotificationsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
@@ -1537,6 +1593,7 @@ export type TeamUncheckedUpdateWithoutNotificationsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1559,6 +1616,7 @@ export type TeamCreateWithoutAgentsInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -1580,6 +1638,7 @@ export type TeamUncheckedCreateWithoutAgentsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1617,6 +1676,7 @@ export type TeamUpdateWithoutAgentsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -1638,12 +1698,117 @@ export type TeamUncheckedUpdateWithoutAgentsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateUncheckedUpdateManyWithoutTeamNestedInput
|
||||
}
|
||||
|
||||
export type TeamCreateWithoutMcpServersInput = {
|
||||
id?: string
|
||||
name: string
|
||||
settings?:PrismaJson.Settings | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
rootFolder?: Prisma.AssetCreateNestedOneWithoutTeamRootFolderInput
|
||||
members?: Prisma.TeamMemberCreateNestedManyWithoutTeamInput
|
||||
projects?: Prisma.ProjectCreateNestedManyWithoutTeamInput
|
||||
metadataFields?: Prisma.MetadataFieldCreateNestedManyWithoutTeamInput
|
||||
invites?: Prisma.InviteCreateNestedManyWithoutTeamInput
|
||||
notifications?: Prisma.NotificationCreateNestedManyWithoutTeamInput
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateCreateNestedManyWithoutTeamInput
|
||||
}
|
||||
|
||||
export type TeamUncheckedCreateWithoutMcpServersInput = {
|
||||
id?: string
|
||||
name: string
|
||||
settings?:PrismaJson.Settings | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
rootFolderId?: string | null
|
||||
members?: Prisma.TeamMemberUncheckedCreateNestedManyWithoutTeamInput
|
||||
projects?: Prisma.ProjectUncheckedCreateNestedManyWithoutTeamInput
|
||||
metadataFields?: Prisma.MetadataFieldUncheckedCreateNestedManyWithoutTeamInput
|
||||
invites?: Prisma.InviteUncheckedCreateNestedManyWithoutTeamInput
|
||||
notifications?: Prisma.NotificationUncheckedCreateNestedManyWithoutTeamInput
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateUncheckedCreateNestedManyWithoutTeamInput
|
||||
}
|
||||
|
||||
export type TeamCreateOrConnectWithoutMcpServersInput = {
|
||||
where: Prisma.TeamWhereUniqueInput
|
||||
create: Prisma.XOR<Prisma.TeamCreateWithoutMcpServersInput, Prisma.TeamUncheckedCreateWithoutMcpServersInput>
|
||||
}
|
||||
|
||||
export type TeamUpsertWithoutMcpServersInput = {
|
||||
update: Prisma.XOR<Prisma.TeamUpdateWithoutMcpServersInput, Prisma.TeamUncheckedUpdateWithoutMcpServersInput>
|
||||
create: Prisma.XOR<Prisma.TeamCreateWithoutMcpServersInput, Prisma.TeamUncheckedCreateWithoutMcpServersInput>
|
||||
where?: Prisma.TeamWhereInput
|
||||
}
|
||||
|
||||
export type TeamUpdateToOneWithWhereWithoutMcpServersInput = {
|
||||
where?: Prisma.TeamWhereInput
|
||||
data: Prisma.XOR<Prisma.TeamUpdateWithoutMcpServersInput, Prisma.TeamUncheckedUpdateWithoutMcpServersInput>
|
||||
}
|
||||
|
||||
export type TeamUpdateWithoutMcpServersInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
name?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
settings?:PrismaJson.Settings | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
rootFolder?: Prisma.AssetUpdateOneWithoutTeamRootFolderNestedInput
|
||||
members?: Prisma.TeamMemberUpdateManyWithoutTeamNestedInput
|
||||
projects?: Prisma.ProjectUpdateManyWithoutTeamNestedInput
|
||||
metadataFields?: Prisma.MetadataFieldUpdateManyWithoutTeamNestedInput
|
||||
invites?: Prisma.InviteUpdateManyWithoutTeamNestedInput
|
||||
notifications?: Prisma.NotificationUpdateManyWithoutTeamNestedInput
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateUpdateManyWithoutTeamNestedInput
|
||||
}
|
||||
|
||||
export type TeamUncheckedUpdateWithoutMcpServersInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
name?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
settings?:PrismaJson.Settings | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
rootFolderId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
members?: Prisma.TeamMemberUncheckedUpdateManyWithoutTeamNestedInput
|
||||
projects?: Prisma.ProjectUncheckedUpdateManyWithoutTeamNestedInput
|
||||
metadataFields?: Prisma.MetadataFieldUncheckedUpdateManyWithoutTeamNestedInput
|
||||
invites?: Prisma.InviteUncheckedUpdateManyWithoutTeamNestedInput
|
||||
notifications?: Prisma.NotificationUncheckedUpdateManyWithoutTeamNestedInput
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateUncheckedUpdateManyWithoutTeamNestedInput
|
||||
}
|
||||
|
||||
export type TeamCreateWithoutUserMetadataInput = {
|
||||
id?: string
|
||||
name: string
|
||||
@@ -1658,6 +1823,7 @@ export type TeamCreateWithoutUserMetadataInput = {
|
||||
notifications?: Prisma.NotificationCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
@@ -1679,6 +1845,7 @@ export type TeamUncheckedCreateWithoutUserMetadataInput = {
|
||||
notifications?: Prisma.NotificationUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1716,6 +1883,7 @@ export type TeamUpdateWithoutUserMetadataInput = {
|
||||
notifications?: Prisma.NotificationUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
@@ -1737,6 +1905,7 @@ export type TeamUncheckedUpdateWithoutUserMetadataInput = {
|
||||
notifications?: Prisma.NotificationUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1758,6 +1927,7 @@ export type TeamCreateWithoutProvidersInput = {
|
||||
notifications?: Prisma.NotificationCreateNestedManyWithoutTeamInput
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
@@ -1779,6 +1949,7 @@ export type TeamUncheckedCreateWithoutProvidersInput = {
|
||||
notifications?: Prisma.NotificationUncheckedCreateNestedManyWithoutTeamInput
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1816,6 +1987,7 @@ export type TeamUpdateWithoutProvidersInput = {
|
||||
notifications?: Prisma.NotificationUpdateManyWithoutTeamNestedInput
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
@@ -1837,6 +2009,7 @@ export type TeamUncheckedUpdateWithoutProvidersInput = {
|
||||
notifications?: Prisma.NotificationUncheckedUpdateManyWithoutTeamNestedInput
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1859,6 +2032,7 @@ export type TeamCreateWithoutAiUsagesInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -1880,6 +2054,7 @@ export type TeamUncheckedCreateWithoutAiUsagesInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1917,6 +2092,7 @@ export type TeamUpdateWithoutAiUsagesInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -1938,6 +2114,7 @@ export type TeamUncheckedUpdateWithoutAiUsagesInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1959,6 +2136,7 @@ export type TeamCreateWithoutAuditLogsInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
@@ -1980,6 +2158,7 @@ export type TeamUncheckedCreateWithoutAuditLogsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -2017,6 +2196,7 @@ export type TeamUpdateWithoutAuditLogsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
@@ -2038,6 +2218,7 @@ export type TeamUncheckedUpdateWithoutAuditLogsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -2058,6 +2239,7 @@ export type TeamCountOutputType = {
|
||||
userMetadata: number
|
||||
providers: number
|
||||
skills: number
|
||||
mcpServers: number
|
||||
agents: number
|
||||
aiUsages: number
|
||||
auditLogs: number
|
||||
@@ -2073,6 +2255,7 @@ export type TeamCountOutputTypeSelect<ExtArgs extends runtime.Types.Extensions.I
|
||||
userMetadata?: boolean | TeamCountOutputTypeCountUserMetadataArgs
|
||||
providers?: boolean | TeamCountOutputTypeCountProvidersArgs
|
||||
skills?: boolean | TeamCountOutputTypeCountSkillsArgs
|
||||
mcpServers?: boolean | TeamCountOutputTypeCountMcpServersArgs
|
||||
agents?: boolean | TeamCountOutputTypeCountAgentsArgs
|
||||
aiUsages?: boolean | TeamCountOutputTypeCountAiUsagesArgs
|
||||
auditLogs?: boolean | TeamCountOutputTypeCountAuditLogsArgs
|
||||
@@ -2145,6 +2328,13 @@ export type TeamCountOutputTypeCountSkillsArgs<ExtArgs extends runtime.Types.Ext
|
||||
where?: Prisma.SkillWhereInput
|
||||
}
|
||||
|
||||
/**
|
||||
* TeamCountOutputType without action
|
||||
*/
|
||||
export type TeamCountOutputTypeCountMcpServersArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
where?: Prisma.McpServerWhereInput
|
||||
}
|
||||
|
||||
/**
|
||||
* TeamCountOutputType without action
|
||||
*/
|
||||
@@ -2190,6 +2380,7 @@ export type TeamSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = r
|
||||
userMetadata?: boolean | Prisma.Team$userMetadataArgs<ExtArgs>
|
||||
providers?: boolean | Prisma.Team$providersArgs<ExtArgs>
|
||||
skills?: boolean | Prisma.Team$skillsArgs<ExtArgs>
|
||||
mcpServers?: boolean | Prisma.Team$mcpServersArgs<ExtArgs>
|
||||
sandbox?: boolean | Prisma.Team$sandboxArgs<ExtArgs>
|
||||
agents?: boolean | Prisma.Team$agentsArgs<ExtArgs>
|
||||
aiUsages?: boolean | Prisma.Team$aiUsagesArgs<ExtArgs>
|
||||
@@ -2238,6 +2429,7 @@ export type TeamInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs =
|
||||
userMetadata?: boolean | Prisma.Team$userMetadataArgs<ExtArgs>
|
||||
providers?: boolean | Prisma.Team$providersArgs<ExtArgs>
|
||||
skills?: boolean | Prisma.Team$skillsArgs<ExtArgs>
|
||||
mcpServers?: boolean | Prisma.Team$mcpServersArgs<ExtArgs>
|
||||
sandbox?: boolean | Prisma.Team$sandboxArgs<ExtArgs>
|
||||
agents?: boolean | Prisma.Team$agentsArgs<ExtArgs>
|
||||
aiUsages?: boolean | Prisma.Team$aiUsagesArgs<ExtArgs>
|
||||
@@ -2264,6 +2456,7 @@ export type $TeamPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs =
|
||||
userMetadata: Prisma.$UserMetadataPayload<ExtArgs>[]
|
||||
providers: Prisma.$ProviderPayload<ExtArgs>[]
|
||||
skills: Prisma.$SkillPayload<ExtArgs>[]
|
||||
mcpServers: Prisma.$McpServerPayload<ExtArgs>[]
|
||||
sandbox: Prisma.$SandboxPayload<ExtArgs> | null
|
||||
agents: Prisma.$AgentPayload<ExtArgs>[]
|
||||
aiUsages: Prisma.$AiUsagePayload<ExtArgs>[]
|
||||
@@ -2683,6 +2876,7 @@ export interface Prisma__TeamClient<T, Null = never, ExtArgs extends runtime.Typ
|
||||
userMetadata<T extends Prisma.Team$userMetadataArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$userMetadataArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$UserMetadataPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
providers<T extends Prisma.Team$providersArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$providersArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$ProviderPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
skills<T extends Prisma.Team$skillsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$skillsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$SkillPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
mcpServers<T extends Prisma.Team$mcpServersArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$mcpServersArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$McpServerPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
sandbox<T extends Prisma.Team$sandboxArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$sandboxArgs<ExtArgs>>): Prisma.Prisma__SandboxClient<runtime.Types.Result.GetResult<Prisma.$SandboxPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
|
||||
agents<T extends Prisma.Team$agentsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$agentsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
aiUsages<T extends Prisma.Team$aiUsagesArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$aiUsagesArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AiUsagePayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
@@ -3334,6 +3528,30 @@ export type Team$skillsArgs<ExtArgs extends runtime.Types.Extensions.InternalArg
|
||||
distinct?: Prisma.SkillScalarFieldEnum | Prisma.SkillScalarFieldEnum[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Team.mcpServers
|
||||
*/
|
||||
export type Team$mcpServersArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
/**
|
||||
* Select specific fields to fetch from the McpServer
|
||||
*/
|
||||
select?: Prisma.McpServerSelect<ExtArgs> | null
|
||||
/**
|
||||
* Omit specific fields from the McpServer
|
||||
*/
|
||||
omit?: Prisma.McpServerOmit<ExtArgs> | null
|
||||
/**
|
||||
* Choose, which related nodes to fetch as well
|
||||
*/
|
||||
include?: Prisma.McpServerInclude<ExtArgs> | null
|
||||
where?: Prisma.McpServerWhereInput
|
||||
orderBy?: Prisma.McpServerOrderByWithRelationInput | Prisma.McpServerOrderByWithRelationInput[]
|
||||
cursor?: Prisma.McpServerWhereUniqueInput
|
||||
take?: number
|
||||
skip?: number
|
||||
distinct?: Prisma.McpServerScalarFieldEnum | Prisma.McpServerScalarFieldEnum[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Team.sandbox
|
||||
*/
|
||||
|
||||
@@ -359,5 +359,70 @@ declare global {
|
||||
watermarkConfigId: string
|
||||
shareLinkId?: string
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// MCP Server
|
||||
// ----------------------------------------------------------------------
|
||||
export type McpTransport = 'streamable_http' | 'sse'
|
||||
|
||||
export interface McpServerAuthConfig {
|
||||
type?: 'none' | 'bearer' | 'oauth'
|
||||
bearerToken?: string
|
||||
headers?: Record<string, string>
|
||||
oauth?: {
|
||||
grantType?: 'authorization_code' | 'client_credentials'
|
||||
clientId?: string
|
||||
clientSecret?: string
|
||||
scope?: string
|
||||
authorizationParams?: Record<string, string>
|
||||
redirectUri?: string
|
||||
clientName?: string
|
||||
clientUri?: string
|
||||
skipIssuerMetadataValidation?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
export interface McpServerConfig {
|
||||
excludeTools?: string[]
|
||||
requestTimeoutMs?: number
|
||||
idleTimeoutMs?: number
|
||||
keepAlive?: boolean
|
||||
protocolVersion?: 'legacy' | 'auto' | '2026-07-28'
|
||||
directTools?: boolean
|
||||
}
|
||||
|
||||
export interface McpToolInfo {
|
||||
name: string
|
||||
title?: string
|
||||
description?: string
|
||||
inputSchema?: unknown
|
||||
}
|
||||
|
||||
export interface McpStoredTokens {
|
||||
accessToken: string
|
||||
refreshToken?: string
|
||||
expiresAt?: number // Unix timestamp in seconds
|
||||
scope?: string
|
||||
issuer?: string
|
||||
}
|
||||
|
||||
export interface McpStoredClientInfo {
|
||||
clientId: string
|
||||
clientSecret?: string
|
||||
clientIdIssuedAt?: number
|
||||
clientSecretExpiresAt?: number
|
||||
redirectUris?: string[]
|
||||
issuer?: string
|
||||
configPreRegistered?: boolean
|
||||
}
|
||||
|
||||
export interface McpPendingAuth {
|
||||
state: string
|
||||
authorizationUrl: string
|
||||
discovery: Record<string, unknown>
|
||||
expiresAt: number // Unix timestamp in seconds
|
||||
grantType?: 'authorization_code' | 'client_credentials'
|
||||
redirectUri?: string
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ export const agentInfoSchema = z.object({
|
||||
systemPrompt: z.string().optional(),
|
||||
soul: z.string().optional(),
|
||||
skills: z.array(agentSkillSchema).optional(),
|
||||
mcpServerIds: z.array(z.string()).optional(),
|
||||
deniedTools: z.array(z.string()).optional(),
|
||||
})
|
||||
export type AgentInfo = z.infer<typeof agentInfoSchema>
|
||||
@@ -46,6 +47,7 @@ const baseAgentRequest = z.object({
|
||||
systemPrompt: z.string().optional(),
|
||||
soul: z.string().optional(),
|
||||
skills: z.array(z.string()).optional(),
|
||||
mcpServerIds: z.array(z.string()).optional(),
|
||||
deniedTools: z.array(z.string()).optional(),
|
||||
})
|
||||
|
||||
|
||||
@@ -31,6 +31,9 @@ export enum AuditAction {
|
||||
skill_create = 'skill_create',
|
||||
skill_update = 'skill_update',
|
||||
skill_delete = 'skill_delete',
|
||||
mcp_server_create = 'mcp_server_create',
|
||||
mcp_server_update = 'mcp_server_update',
|
||||
mcp_server_delete = 'mcp_server_delete',
|
||||
provider_create = 'provider_create',
|
||||
provider_update = 'provider_update',
|
||||
provider_delete = 'provider_delete',
|
||||
|
||||
@@ -6,6 +6,7 @@ export * from './collection'
|
||||
export * from './folder'
|
||||
export * from './invite'
|
||||
export * from './metadata'
|
||||
export * from './mcp'
|
||||
export * from './notification'
|
||||
export * from './pagination'
|
||||
export * from './project'
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const mcpServerAuthTypeSchema = z.enum(['auto', 'none', 'bearer', 'oauth'])
|
||||
export type McpServerAuthType = z.infer<typeof mcpServerAuthTypeSchema>
|
||||
|
||||
export const mcpTransportSchema = z.enum(['streamable_http', 'sse'])
|
||||
export type McpTransport = z.infer<typeof mcpTransportSchema>
|
||||
|
||||
export const mcpServerPermissionSchema = z.enum(['owner', 'editor', 'reviewer'])
|
||||
export type McpServerPermission = z.infer<typeof mcpServerPermissionSchema>
|
||||
|
||||
export const mcpOauthConfigSchema = z.object({
|
||||
grantType: z.enum(['authorization_code', 'client_credentials']).optional(),
|
||||
clientId: z.string().optional(),
|
||||
clientSecret: z.string().optional(),
|
||||
scope: z.string().optional(),
|
||||
authorizationParams: z.record(z.string(), z.string()).optional(),
|
||||
redirectUri: z.string().optional(),
|
||||
clientName: z.string().optional(),
|
||||
clientUri: z.string().optional(),
|
||||
skipIssuerMetadataValidation: z.boolean().optional(),
|
||||
})
|
||||
export type McpOauthConfig = z.infer<typeof mcpOauthConfigSchema>
|
||||
|
||||
export const mcpServerAuthConfigSchema = z.object({
|
||||
type: mcpServerAuthTypeSchema.optional(),
|
||||
bearerToken: z.string().optional(),
|
||||
headers: z.record(z.string(), z.string()).optional(),
|
||||
oauth: mcpOauthConfigSchema.optional(),
|
||||
})
|
||||
export type McpServerAuthConfig = z.infer<typeof mcpServerAuthConfigSchema>
|
||||
|
||||
export const mcpServerConfigSchema = z.object({
|
||||
excludeTools: z.array(z.string()).optional(),
|
||||
requestTimeoutMs: z.number().int().positive().optional(),
|
||||
idleTimeoutMs: z.number().int().positive().optional(),
|
||||
keepAlive: z.boolean().optional(),
|
||||
protocolVersion: z.enum(['legacy', 'auto', '2026-07-28']).optional(),
|
||||
directTools: z.boolean().optional(),
|
||||
})
|
||||
export type McpServerConfig = z.infer<typeof mcpServerConfigSchema>
|
||||
|
||||
export const mcpToolInfoSchema = z.object({
|
||||
name: z.string(),
|
||||
title: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
inputSchema: z.unknown().optional(),
|
||||
})
|
||||
export type McpToolInfo = z.infer<typeof mcpToolInfoSchema>
|
||||
|
||||
export const createMcpServerRequestSchema = z.object({
|
||||
url: z.string().url(),
|
||||
transport: mcpTransportSchema.optional(),
|
||||
authConfig: mcpServerAuthConfigSchema.optional(),
|
||||
config: mcpServerConfigSchema.optional(),
|
||||
permission: mcpServerPermissionSchema.optional(),
|
||||
})
|
||||
export type CreateMcpServerRequest = z.infer<typeof createMcpServerRequestSchema>
|
||||
|
||||
export const updateMcpServerRequestSchema = z.object({
|
||||
transport: mcpTransportSchema.optional(),
|
||||
authConfig: mcpServerAuthConfigSchema.optional(),
|
||||
config: mcpServerConfigSchema.optional(),
|
||||
permission: mcpServerPermissionSchema.optional(),
|
||||
})
|
||||
export type UpdateMcpServerRequest = z.infer<typeof updateMcpServerRequestSchema>
|
||||
|
||||
export const updateMcpServerPermissionRequestSchema = z.object({
|
||||
permission: mcpServerPermissionSchema,
|
||||
})
|
||||
export type UpdateMcpServerPermissionRequest = z.infer<
|
||||
typeof updateMcpServerPermissionRequestSchema
|
||||
>
|
||||
|
||||
export const mcpServerInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string().optional(),
|
||||
instructions: z.string().optional(),
|
||||
url: z.string(),
|
||||
transport: mcpTransportSchema,
|
||||
authType: mcpServerAuthTypeSchema,
|
||||
config: mcpServerConfigSchema.optional(),
|
||||
permission: mcpServerPermissionSchema,
|
||||
status: z.string(),
|
||||
lastError: z.string().nullable().optional(),
|
||||
toolCount: z.number(),
|
||||
hasCredential: z.boolean(),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
})
|
||||
export type McpServerInfo = z.infer<typeof mcpServerInfoSchema>
|
||||
|
||||
export const listMcpServersResponseSchema = z.object({
|
||||
servers: z.array(mcpServerInfoSchema),
|
||||
})
|
||||
export type ListMcpServersResponse = z.infer<typeof listMcpServersResponseSchema>
|
||||
|
||||
export const refreshToolsRequestSchema = z.object({})
|
||||
export type RefreshToolsRequest = z.infer<typeof refreshToolsRequestSchema>
|
||||
|
||||
export const refreshToolsResponseSchema = z.object({
|
||||
tools: z.array(mcpToolInfoSchema),
|
||||
})
|
||||
export type RefreshToolsResponse = z.infer<typeof refreshToolsResponseSchema>
|
||||
|
||||
export const mcpAuthStatusSchema = z.enum([
|
||||
'authenticated',
|
||||
'expired',
|
||||
'not_authenticated',
|
||||
'in_progress',
|
||||
])
|
||||
export type McpAuthStatus = z.infer<typeof mcpAuthStatusSchema>
|
||||
|
||||
export const mcpAuthStatusResponseSchema = z.object({
|
||||
status: mcpAuthStatusSchema,
|
||||
})
|
||||
export type McpAuthStatusResponse = z.infer<typeof mcpAuthStatusResponseSchema>
|
||||
|
||||
export const mcpAuthStartResponseSchema = z.object({
|
||||
authorizationUrl: z.string().optional(),
|
||||
status: mcpAuthStatusSchema,
|
||||
})
|
||||
export type McpAuthStartResponse = z.infer<typeof mcpAuthStartResponseSchema>
|
||||
|
||||
export const mcpAuthCompleteRequestSchema = z.object({
|
||||
code: z.string(),
|
||||
iss: z.string().optional(),
|
||||
})
|
||||
export type McpAuthCompleteRequest = z.infer<typeof mcpAuthCompleteRequestSchema>
|
||||
|
||||
export const mcpTestServerResponseSchema = z.object({
|
||||
ok: z.boolean(),
|
||||
toolCount: z.number(),
|
||||
message: z.string().optional(),
|
||||
})
|
||||
export type McpTestServerResponse = z.infer<typeof mcpTestServerResponseSchema>
|
||||
@@ -0,0 +1,334 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { workflowService, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { mcpService } from '@shumai/core/src/mcp/mcp-service'
|
||||
import {
|
||||
startTestMcpServer,
|
||||
standardTestTools,
|
||||
type RunningTestMcpServer,
|
||||
} from '@shumai/core/src/mcp/mcp-test-server'
|
||||
import { AgentHarness } from '@earendil-works/pi-agent-core'
|
||||
import { fileURLToPath } from 'url'
|
||||
import * as path from 'path'
|
||||
|
||||
const currentDir = path.dirname(fileURLToPath(import.meta.url))
|
||||
const agentWorkflowsPath = path.resolve(currentDir, '../../../apps/agent/src/workflows.ts')
|
||||
|
||||
describe.each(['local', 'temporal'] as const)('Workflow E2E - MCP tools (executor: %s)', (mode) => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let agentWorkerPromise: Promise<void> | null = null
|
||||
let mcpTestServer: RunningTestMcpServer
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-mcp'
|
||||
process.env.GEMINI_API_KEY = 'dummy-key'
|
||||
|
||||
// Real in-process MCP server — only AI calls are mocked. It self-reports
|
||||
// the name 'e2e-mcp' so discovery auto-fills the DB name/tool prefixes
|
||||
// exactly as the tests expect.
|
||||
mcpTestServer = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'e2e-mcp' },
|
||||
})
|
||||
|
||||
workflowService.setExecutorType(mode)
|
||||
initAgentWorkflows()
|
||||
|
||||
// Mock ONLY the AI model call. The mocked prompt locates the real `mcp`
|
||||
// proxy tool on the harness and executes it against the real MCP server,
|
||||
// so the full createAgentSession → buildAgentTools → proxy execute →
|
||||
// callMcpTool → MCP server path is exercised.
|
||||
vi.spyOn(AgentHarness.prototype, 'prompt').mockImplementation(async function (
|
||||
this: AgentHarness,
|
||||
) {
|
||||
const tools = this.getTools()
|
||||
const mcpTool = tools.find((t) => t.name === 'mcp')
|
||||
if (!mcpTool) {
|
||||
return {
|
||||
content: [{ type: 'text', text: 'NO_MCP_TOOL' }],
|
||||
usage: { input: 10, output: 20 },
|
||||
stopReason: 'stop',
|
||||
} as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>
|
||||
}
|
||||
const result = await (
|
||||
mcpTool.execute as unknown as (
|
||||
id: string,
|
||||
params: { server: string; tool: string; args: Record<string, unknown> },
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('e2e-call', {
|
||||
server: 'e2e-mcp',
|
||||
tool: 'echo',
|
||||
args: { text: 'hello from mcp e2e' },
|
||||
})
|
||||
const text = result.content
|
||||
.map((c) => ('text' in c && typeof c.text === 'string' ? c.text : ''))
|
||||
.join('\n')
|
||||
return {
|
||||
content: [{ type: 'text', text }],
|
||||
usage: { input: 10, output: 20 },
|
||||
stopReason: 'stop',
|
||||
} as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>
|
||||
})
|
||||
|
||||
if (mode === 'temporal') {
|
||||
console.log('Starting background worker for MCP Temporal E2E tests...')
|
||||
agentWorkerPromise = workflowService.startWorkers(TaskQueueAgent, {
|
||||
workflowsPath: agentWorkflowsPath,
|
||||
})
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000))
|
||||
} else {
|
||||
console.log('Starting local workflow service polling...')
|
||||
workflowService.start()
|
||||
}
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
if (mode === 'temporal') {
|
||||
console.log('Shutting down Temporal workers...')
|
||||
await workflowService.shutdownWorkers()
|
||||
await Promise.all([agentWorkerPromise].filter(Boolean))
|
||||
}
|
||||
workflowService.close()
|
||||
vi.restoreAllMocks()
|
||||
await mcpService.closeAllConnections()
|
||||
await mcpTestServer.stop()
|
||||
try {
|
||||
console.log('Cleaning up local E2E storage files...')
|
||||
await s3Service.deletePrefix('shumai-e2e-test-bucket-mcp', '')
|
||||
} catch (err) {
|
||||
console.error('Failed to clean up E2E storage folder:', err)
|
||||
}
|
||||
})
|
||||
|
||||
async function seedChatSetup() {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: `MCP E2E Team (${mode})` },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'MCP E2E Project', teamId: team.id },
|
||||
})
|
||||
|
||||
const agentUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'MCP E2E Agent',
|
||||
email: `mcp-e2e-${mode}@shumai.ai`,
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: agentUser.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
config: { api: 'google-generative-ai', apiKey: 'dummy-google-api-key' },
|
||||
},
|
||||
})
|
||||
|
||||
const model = await prisma.model.create({
|
||||
data: {
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
providerId: provider.id,
|
||||
config: {
|
||||
input: ['text'],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 8192,
|
||||
maxTokens: 2048,
|
||||
reasoning: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: agentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'mcp-chat-asset.png',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
mediaType: 'image/png',
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
const regularUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'MCP Regular User',
|
||||
email: `mcp-user-${mode}@example.com`,
|
||||
type: 'human',
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: regularUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
await prisma.agentSession.create({
|
||||
data: {
|
||||
id: `mcp-session-${mode}`,
|
||||
agentId: agentUser.id,
|
||||
userId: regularUser.id,
|
||||
cwd: process.cwd(),
|
||||
assetId: asset.id,
|
||||
},
|
||||
})
|
||||
|
||||
return { team, project, agentUser, asset, regularUser }
|
||||
}
|
||||
|
||||
async function createMcpServerAndAssign(teamId: string, agentId: string, config?: object) {
|
||||
const server = await prisma.mcpServer.create({
|
||||
data: {
|
||||
name: 'e2e-mcp',
|
||||
url: mcpTestServer.url,
|
||||
teamId,
|
||||
config: (config ?? {}) as PrismaJson.McpServerConfig,
|
||||
},
|
||||
})
|
||||
await prisma.agentMcpServer.create({ data: { agentId, mcpServerId: server.id } })
|
||||
// Mirrors the admin flow: refresh the server so its tools are cached in
|
||||
// DB and warmed in the in-process registry (buildAgentTools needs the
|
||||
// cache to register direct tools before any chat turn runs).
|
||||
await mcpService.refreshServer(server.id)
|
||||
return server
|
||||
}
|
||||
|
||||
it('runs a chat that calls the mcp proxy tool against a real MCP server', async () => {
|
||||
const { team, project, agentUser, asset, regularUser } = await seedChatSetup()
|
||||
await createMcpServerAndAssign(team.id, agentUser.id)
|
||||
|
||||
const userComment = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
message: 'Please use the MCP server',
|
||||
creatorId: regularUser.id,
|
||||
sessionId: `mcp-session-${mode}`,
|
||||
},
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: asset.id,
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
agent: {
|
||||
agentId: agentUser.id,
|
||||
sessionId: `mcp-session-${mode}`,
|
||||
userCommentId: userComment.id,
|
||||
userId: regularUser.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
console.log(`Submitted MCP E2E Chat Task. ID: ${task.id}. Awaiting completion...`)
|
||||
const completedTask = await workflowService.executeWait(task, 45000)
|
||||
|
||||
expect(completedTask.status).toBe('completed')
|
||||
|
||||
const comments = await prisma.assetComment.findMany({
|
||||
where: { assetId: asset.id, replyToId: userComment.id },
|
||||
})
|
||||
expect(comments.length).toBeGreaterThan(0)
|
||||
// The reply is the mocked model's text, which is the REAL MCP echo result.
|
||||
expect(comments[0].message).toContain('echo:hello from mcp e2e')
|
||||
}, 50000)
|
||||
|
||||
it('runs a chat with direct-tools mode (server-prefixed native tools)', async () => {
|
||||
const { team, project, agentUser, asset, regularUser } = await seedChatSetup()
|
||||
await createMcpServerAndAssign(team.id, agentUser.id, { directTools: true })
|
||||
|
||||
// For direct mode the model would call `e2e_mcp_echo` directly; simulate
|
||||
// that by executing the direct tool on the harness.
|
||||
const directSpy = vi
|
||||
.spyOn(AgentHarness.prototype, 'prompt')
|
||||
.mockImplementationOnce(async function (this: AgentHarness) {
|
||||
const tools = this.getTools()
|
||||
const echoTool = tools.find((t) => t.name === 'e2e_mcp_echo')
|
||||
if (!echoTool) {
|
||||
return {
|
||||
content: [{ type: 'text', text: 'NO_DIRECT_TOOL' }],
|
||||
usage: { input: 1, output: 1 },
|
||||
stopReason: 'stop',
|
||||
} as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>
|
||||
}
|
||||
const result = await (
|
||||
echoTool.execute as unknown as (
|
||||
id: string,
|
||||
params: Record<string, unknown>,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('e2e-direct', {
|
||||
text: 'direct call',
|
||||
})
|
||||
const text = result.content
|
||||
.map((c) => ('text' in c && typeof c.text === 'string' ? c.text : ''))
|
||||
.join('\n')
|
||||
return {
|
||||
content: [{ type: 'text', text }],
|
||||
usage: { input: 1, output: 1 },
|
||||
stopReason: 'stop',
|
||||
} as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>
|
||||
})
|
||||
|
||||
const userComment = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
message: 'Use the direct tool',
|
||||
creatorId: regularUser.id,
|
||||
sessionId: `mcp-session-${mode}`,
|
||||
},
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: asset.id,
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
agent: {
|
||||
agentId: agentUser.id,
|
||||
sessionId: `mcp-session-${mode}`,
|
||||
userCommentId: userComment.id,
|
||||
userId: regularUser.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const completedTask = await workflowService.executeWait(task, 45000)
|
||||
expect(completedTask.status).toBe('completed')
|
||||
|
||||
const comments = await prisma.assetComment.findMany({
|
||||
where: { assetId: asset.id, replyToId: userComment.id },
|
||||
})
|
||||
expect(comments.length).toBeGreaterThan(0)
|
||||
expect(comments[0].message).toContain('echo:direct call')
|
||||
directSpy.mockRestore()
|
||||
}, 50000)
|
||||
})
|
||||
@@ -2,6 +2,7 @@ import { client } from '@/ui/api/client'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -21,7 +22,7 @@ import {
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useForm, useStore } from '@tanstack/react-form'
|
||||
import { Loader2, Puzzle, Terminal } from 'lucide-react'
|
||||
import { Loader2, Puzzle, Server, Terminal } from 'lucide-react'
|
||||
import { useEffect, useMemo } from 'react'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { toast } from 'sonner'
|
||||
@@ -52,6 +53,7 @@ const agentFormSchema = z.object({
|
||||
thinkingLevel: thinkingLevelSchema.optional(),
|
||||
systemPrompt: z.string().optional(),
|
||||
skills: z.array(z.string()).optional(),
|
||||
mcpServerIds: z.array(z.string()).optional(),
|
||||
deniedTools: z.array(z.string()).optional(),
|
||||
})
|
||||
|
||||
@@ -144,6 +146,21 @@ export function AgentFormDialog({
|
||||
|
||||
const allSkills = skillsData?.skills || []
|
||||
|
||||
// Fetch MCP Servers
|
||||
const { data: mcpData } = useQuery({
|
||||
queryKey: ['teams', teamId, 'mcp', 'servers'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].mcp.servers.$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch MCP servers')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: isOpen,
|
||||
})
|
||||
|
||||
const allMcpServers = mcpData?.servers || []
|
||||
|
||||
const schema = useMemo(() => {
|
||||
return agentFormSchema.superRefine((data, ctx) => {
|
||||
if (data.type === 'chat' || data.type === 'autofill') {
|
||||
@@ -176,6 +193,7 @@ export function AgentFormDialog({
|
||||
thinkingLevel: initialValues?.thinkingLevel || 'off',
|
||||
systemPrompt: initialValues?.systemPrompt || '',
|
||||
skills: initialValues?.skills?.map((s) => s.skillId) || ([] as string[]),
|
||||
mcpServerIds: initialValues?.mcpServerIds || ([] as string[]),
|
||||
deniedTools: initialValues?.deniedTools || ([] as string[]),
|
||||
} as AgentFormValues,
|
||||
validators: {
|
||||
@@ -563,6 +581,91 @@ export function AgentFormDialog({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 border-t border-border pt-6">
|
||||
<Label className="text-base font-bold flex items-center gap-2">
|
||||
<Server className="w-5 h-5 text-primary" />
|
||||
{m.mcp_servers()}
|
||||
</Label>
|
||||
|
||||
<div className="space-y-2">
|
||||
<form.Field
|
||||
name="mcpServerIds"
|
||||
children={(mcpField) => (
|
||||
<>
|
||||
{allMcpServers.map((mcpServer) => {
|
||||
const isEnabled =
|
||||
mcpField.state.value?.includes(mcpServer.id) || false
|
||||
const needsAuth =
|
||||
mcpServer.status === 'needs_auth' ||
|
||||
(!mcpServer.hasCredential && mcpServer.authType === 'oauth')
|
||||
|
||||
return (
|
||||
<div
|
||||
key={mcpServer.id}
|
||||
className="flex items-center justify-between p-3 bg-muted/30 border border-border rounded-lg"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<Server className="w-4 h-4 text-muted-foreground" />
|
||||
<div className="flex flex-col">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">
|
||||
{mcpServer.name}
|
||||
</span>
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
{mcpServer.toolCount ?? 0} tools
|
||||
</Badge>
|
||||
{needsAuth && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="text-[10px] bg-amber-500/10 text-amber-600 border-amber-500/20"
|
||||
>
|
||||
{m.mcp_status_needs_auth()}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-[10px] font-mono text-muted-foreground line-clamp-1">
|
||||
{mcpServer.url}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{isEnabled ? m.enabled() : m.disabled()}
|
||||
</span>
|
||||
<Switch
|
||||
checked={isEnabled}
|
||||
onCheckedChange={(checked) => {
|
||||
if (checked) {
|
||||
mcpField.handleChange([
|
||||
...(mcpField.state.value || []),
|
||||
mcpServer.id,
|
||||
])
|
||||
} else {
|
||||
mcpField.handleChange(
|
||||
(mcpField.state.value || []).filter(
|
||||
(id) => id !== mcpServer.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{allMcpServers.length === 0 && (
|
||||
<div className="text-center py-6 border-2 border-dashed border-border rounded-xl">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{m.no_mcp_servers_installed()}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 border-t border-border pt-6">
|
||||
<Label className="text-base font-bold flex items-center gap-2">
|
||||
<Terminal className="w-5 h-5 text-primary" />
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
import React, { useState } from 'react'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
Server,
|
||||
Loader2,
|
||||
MoreVertical,
|
||||
Plus,
|
||||
Trash2,
|
||||
Zap,
|
||||
ShieldCheck,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
Clock,
|
||||
Key,
|
||||
Wrench,
|
||||
} from 'lucide-react'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { McpServerInfo, McpServerPermission } from '@shumai/dtos'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { toast } from 'sonner'
|
||||
import { McpServerFormDialog } from './McpServerFormDialog'
|
||||
|
||||
interface McpConfigCardProps {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
export const McpConfigCard: React.FC<McpConfigCardProps> = ({ teamId }) => {
|
||||
const queryClient = useQueryClient()
|
||||
const { canAdmin } = usePermissions()
|
||||
|
||||
const [isAddFormOpen, setIsAddFormOpen] = useState(false)
|
||||
const [editingServer, setEditingServer] = useState<McpServerInfo | null>(null)
|
||||
const [deletingServer, setDeletingServer] = useState<McpServerInfo | null>(null)
|
||||
const [authenticatingServerId, setAuthenticatingServerId] = useState<string | null>(null)
|
||||
|
||||
// Fetch MCP Servers
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'mcp', 'servers'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].mcp.servers.$get({ param: { teamId } })
|
||||
if (!res.ok) throw new Error(m.failed_load_settings())
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
// Delete Server Mutation
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const res = await client.api.mcp.servers[':id'].$delete({ param: { id } })
|
||||
if (!res.ok) throw new Error(m.failed_to_delete())
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(m.delete())
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] })
|
||||
setDeletingServer(null)
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
// Update Permission Mutation
|
||||
const updatePermissionMutation = useMutation({
|
||||
mutationFn: async ({ id, permission }: { id: string; permission: McpServerPermission }) => {
|
||||
const res = await client.api.mcp.servers[':id'].permission.$patch({
|
||||
param: { id },
|
||||
json: { permission },
|
||||
})
|
||||
if (!res.ok) throw new Error(m.failed_to_update_permission())
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] })
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
// Enable/Disable Mutation
|
||||
// (Removed: enable/disable now happens per-agent via AgentMcpServer assignment.)
|
||||
|
||||
// Disconnect Auth Mutation
|
||||
const disconnectAuthMutation = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const res = await client.api.mcp.servers[':id'].auth.$delete({ param: { id } })
|
||||
if (!res.ok) throw new Error('Failed to disconnect auth')
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(m.mcp_disconnect_auth())
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] })
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
// Start Auth Flow (OAuth Popup / Bearer)
|
||||
const handleStartAuth = async (serverId: string) => {
|
||||
setAuthenticatingServerId(serverId)
|
||||
try {
|
||||
const res = await client.api.mcp.servers[':id'].auth.start.$post({
|
||||
param: { id: serverId },
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => ({}))) as { error?: string }
|
||||
throw new Error(err.error || m.mcp_auth_failed())
|
||||
}
|
||||
const data = (await res.json()) as { authorizationUrl?: string; status?: string }
|
||||
if (data.status === 'authenticated') {
|
||||
toast.success(m.mcp_auth_success())
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] })
|
||||
setAuthenticatingServerId(null)
|
||||
return
|
||||
}
|
||||
|
||||
if (data.authorizationUrl) {
|
||||
// Open OAuth popup window
|
||||
const width = 600
|
||||
const height = 700
|
||||
const left = window.screenX + (window.outerWidth - width) / 2
|
||||
const top = window.screenY + (window.outerHeight - height) / 2
|
||||
const popup = window.open(
|
||||
data.authorizationUrl,
|
||||
'mcp_oauth_popup',
|
||||
`width=${width},height=${height},left=${left},top=${top},scrollbars=yes`,
|
||||
)
|
||||
|
||||
const handleMessage = (event: MessageEvent) => {
|
||||
if (event.data?.type === 'mcp-oauth-callback') {
|
||||
window.removeEventListener('message', handleMessage)
|
||||
setAuthenticatingServerId(null)
|
||||
if (event.data.ok) {
|
||||
toast.success(m.mcp_auth_success())
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] })
|
||||
} else {
|
||||
toast.error(event.data.message || m.mcp_auth_failed())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('message', handleMessage)
|
||||
|
||||
// Monitor popup closure
|
||||
const checkClosed = setInterval(() => {
|
||||
if (!popup || popup.closed) {
|
||||
clearInterval(checkClosed)
|
||||
window.removeEventListener('message', handleMessage)
|
||||
setAuthenticatingServerId(null)
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] })
|
||||
}
|
||||
}, 1000)
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : m.mcp_auth_failed())
|
||||
setAuthenticatingServerId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const servers = data?.servers || []
|
||||
|
||||
const renderStatusBadge = (server: McpServerInfo) => {
|
||||
switch (server.status) {
|
||||
case 'connected':
|
||||
return (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="gap-1 bg-emerald-500/10 text-emerald-600 border-emerald-500/20 text-[10px]"
|
||||
>
|
||||
<CheckCircle2 className="w-3 h-3" />
|
||||
{m.mcp_status_connected()}
|
||||
</Badge>
|
||||
)
|
||||
case 'needs_auth':
|
||||
return (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="gap-1 bg-amber-500/10 text-amber-600 border-amber-500/20 text-[10px]"
|
||||
>
|
||||
<Key className="w-3 h-3" />
|
||||
{m.mcp_status_needs_auth()}
|
||||
</Badge>
|
||||
)
|
||||
case 'failed':
|
||||
return (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="gap-1 bg-red-500/10 text-red-600 border-red-500/20 text-[10px]"
|
||||
>
|
||||
<AlertCircle className="w-3 h-3" />
|
||||
{m.mcp_status_failed()}
|
||||
</Badge>
|
||||
)
|
||||
default:
|
||||
return (
|
||||
<Badge variant="outline" className="gap-1 text-[10px]">
|
||||
<Clock className="w-3 h-3 text-muted-foreground" />
|
||||
{m.mcp_status_not_connected()}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-7">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-primary/10 text-primary rounded-lg">
|
||||
<Server className="w-6 h-6" />
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-xl font-bold">{m.mcp_servers()}</CardTitle>
|
||||
<CardDescription>{m.mcp_servers_description()}</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
{canAdmin && (
|
||||
<Button onClick={() => setIsAddFormOpen(true)} className="gap-2">
|
||||
<Plus className="w-4 h-4" /> {m.add_mcp_server()}
|
||||
</Button>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<div className="flex justify-center py-10">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||
</div>
|
||||
) : servers.length === 0 ? (
|
||||
<div className="text-center py-12 border-2 border-dashed border-border rounded-xl">
|
||||
<div className="mx-auto w-12 h-12 bg-muted rounded-full flex items-center justify-center mb-4 text-muted-foreground">
|
||||
<Server className="w-6 h-6" />
|
||||
</div>
|
||||
<h3 className="text-base font-semibold">{m.no_mcp_servers_installed()}</h3>
|
||||
<p className="text-xs text-muted-foreground mt-1 max-w-sm mx-auto">
|
||||
{m.add_mcp_server_to_get_started()}
|
||||
</p>
|
||||
{canAdmin && (
|
||||
<Button
|
||||
onClick={() => setIsAddFormOpen(true)}
|
||||
className="mt-4 gap-2"
|
||||
variant="outline"
|
||||
>
|
||||
<Plus className="w-4 h-4" /> {m.add_mcp_server()}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{servers.map((server) => {
|
||||
const isDirectMode = server.config?.directTools
|
||||
const isAuthenticating = authenticatingServerId === server.id
|
||||
const needsAuth =
|
||||
server.status === 'needs_auth' ||
|
||||
(!server.hasCredential && server.authType !== 'none')
|
||||
|
||||
return (
|
||||
<div
|
||||
key={server.id}
|
||||
onClick={() => canAdmin && setEditingServer(server)}
|
||||
className={`p-4 bg-card rounded-xl border border-border flex flex-col justify-between hover:shadow-md transition-all group ${
|
||||
canAdmin ? 'cursor-pointer' : ''
|
||||
}`}
|
||||
>
|
||||
{/* Row 1: name + three-dot */}
|
||||
<div className="flex items-start justify-between gap-2 mb-2">
|
||||
<h4 className="font-bold text-foreground flex items-center gap-2 min-w-0">
|
||||
<Server className="w-4 h-4 text-muted-foreground shrink-0" />
|
||||
<span className="truncate">{server.name}</span>
|
||||
{isDirectMode && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] bg-primary/5 text-primary border-primary/20 shrink-0"
|
||||
>
|
||||
<Zap className="w-3 h-3 mr-0.5" />
|
||||
{m.mcp_direct_tools_mode()}
|
||||
</Badge>
|
||||
)}
|
||||
<Badge variant="outline" className="text-[10px] uppercase shrink-0">
|
||||
{server.transport}
|
||||
</Badge>
|
||||
</h4>
|
||||
{canAdmin && (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8 shrink-0">
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{server.status !== 'connected' &&
|
||||
(server.authType !== 'none' || server.hasCredential) ? (
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleStartAuth(server.id)
|
||||
}}
|
||||
>
|
||||
<Key className="w-4 h-4 mr-2" />
|
||||
{m.mcp_connect_auth()}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
|
||||
{server.hasCredential && (
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
disconnectAuthMutation.mutate(server.id)
|
||||
}}
|
||||
className="text-amber-600"
|
||||
>
|
||||
<ShieldCheck className="w-4 h-4 mr-2" />
|
||||
{m.mcp_disconnect_auth()}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
|
||||
{((server.status !== 'connected' &&
|
||||
(server.authType !== 'none' || server.hasCredential)) ||
|
||||
server.hasCredential) && <DropdownMenuSeparator />}
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setDeletingServer(server)
|
||||
}}
|
||||
className="text-red-600"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
{m.delete()}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Row 2: description + url + lastError */}
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm text-muted-foreground line-clamp-2">
|
||||
{server.description || m.no_description_provided()}
|
||||
</p>
|
||||
<p className="font-mono text-[10px] text-muted-foreground/70 truncate">
|
||||
{server.url}
|
||||
</p>
|
||||
{server.lastError && (
|
||||
<p className="text-[10px] text-red-500/90 truncate font-mono">
|
||||
{server.lastError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Row 3: status + updated (left), permission + connect (right) */}
|
||||
<div className="mt-4 flex items-center justify-between gap-2 pt-2 border-t border-border/50 text-xs">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{renderStatusBadge(server)}
|
||||
<Badge variant="outline" className="text-[10px] gap-1 shrink-0">
|
||||
<Wrench className="w-3 h-3 text-muted-foreground" />
|
||||
{m.mcp_tools_count({ count: server.toolCount })}
|
||||
</Badge>
|
||||
<span className="text-[10px] text-muted-foreground uppercase tracking-wider font-semibold whitespace-nowrap">
|
||||
{m.updated_date()} {new Date(server.updatedAt).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
className="flex items-center gap-2 shrink-0"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{canAdmin ? (
|
||||
<Select
|
||||
value={server.permission}
|
||||
onValueChange={(permission) =>
|
||||
updatePermissionMutation.mutate({
|
||||
id: server.id,
|
||||
permission: permission as McpServerPermission,
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-7 text-xs px-2 bg-background border-border w-[130px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent align="end">
|
||||
<SelectItem value="reviewer">{m.permission_all_users()}</SelectItem>
|
||||
<SelectItem value="editor">
|
||||
{m.permission_owner_and_editor()}
|
||||
</SelectItem>
|
||||
<SelectItem value="owner">{m.permission_owner_only()}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
{server.permission === 'reviewer'
|
||||
? m.permission_all_users()
|
||||
: server.permission === 'editor'
|
||||
? m.permission_owner_and_editor()
|
||||
: m.permission_owner_only()}
|
||||
</Badge>
|
||||
)}
|
||||
{/* Connect button — right end of the row */}
|
||||
{needsAuth && canAdmin && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleStartAuth(server.id)
|
||||
}}
|
||||
disabled={isAuthenticating}
|
||||
className="gap-1.5 bg-amber-600 hover:bg-amber-700 text-white text-xs"
|
||||
>
|
||||
{isAuthenticating ? (
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
<Key className="w-3.5 h-3.5" />
|
||||
)}
|
||||
{m.mcp_connect_auth()}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
{/* Form Dialog for Add / Edit */}
|
||||
<McpServerFormDialog
|
||||
isOpen={isAddFormOpen || !!editingServer}
|
||||
onClose={() => {
|
||||
setIsAddFormOpen(false)
|
||||
setEditingServer(null)
|
||||
}}
|
||||
teamId={teamId}
|
||||
server={editingServer}
|
||||
/>
|
||||
|
||||
{/* Delete Confirmation Alert */}
|
||||
<AlertDialog
|
||||
open={!!deletingServer}
|
||||
onOpenChange={(open) => !open && setDeletingServer(null)}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{m.delete_mcp_server()}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{m.delete_mcp_server_confirmation({ name: deletingServer?.name || '' })}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{m.cancel()}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => deletingServer && deleteMutation.mutate(deletingServer.id)}
|
||||
className="bg-red-600 hover:bg-red-700 text-white"
|
||||
>
|
||||
{deleteMutation.isPending && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
{m.delete()}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { Loader2, Server, Info, RefreshCw, Wrench, ChevronDown, ChevronRight } from 'lucide-react'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { toast } from 'sonner'
|
||||
import {
|
||||
McpServerInfo,
|
||||
McpTransport,
|
||||
McpServerPermission,
|
||||
McpServerAuthType,
|
||||
McpToolInfo,
|
||||
CreateMcpServerRequest,
|
||||
UpdateMcpServerRequest,
|
||||
} from '@shumai/dtos'
|
||||
|
||||
interface McpServerFormDialogProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
teamId: string
|
||||
server?: McpServerInfo | null
|
||||
}
|
||||
|
||||
export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
teamId,
|
||||
server,
|
||||
}) => {
|
||||
const queryClient = useQueryClient()
|
||||
const isEditing = !!server
|
||||
|
||||
const [url, setUrl] = useState('')
|
||||
const [transport, setTransport] = useState<McpTransport>('streamable_http')
|
||||
const [permission, setPermission] = useState<McpServerPermission>('reviewer')
|
||||
|
||||
// Auth config state
|
||||
const [authType, setAuthType] = useState<McpServerAuthType | 'auto'>('auto')
|
||||
const [bearerToken, setBearerToken] = useState('')
|
||||
const [clientId, setClientId] = useState('')
|
||||
const [clientSecret, setClientSecret] = useState('')
|
||||
const [scope, setScope] = useState('')
|
||||
const [grantType, setGrantType] = useState<'authorization_code' | 'client_credentials'>(
|
||||
'authorization_code',
|
||||
)
|
||||
|
||||
// Config state
|
||||
const [directTools, setDirectTools] = useState(false)
|
||||
const [excludedTools, setExcludedTools] = useState<string[]>([])
|
||||
|
||||
// Tools inspector state
|
||||
const [expandedTools, setExpandedTools] = useState<Record<string, boolean>>({})
|
||||
const [isInstructionsExpanded, setIsInstructionsExpanded] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (server) {
|
||||
setUrl(server.url)
|
||||
setTransport(server.transport || 'streamable_http')
|
||||
setPermission(server.permission || 'reviewer')
|
||||
setAuthType(server.authType || 'auto')
|
||||
setDirectTools(server.config?.directTools ?? false)
|
||||
setExcludedTools(server.config?.excludeTools ?? [])
|
||||
setExpandedTools({})
|
||||
setIsInstructionsExpanded(false)
|
||||
} else {
|
||||
setUrl('')
|
||||
setTransport('streamable_http')
|
||||
setPermission('reviewer')
|
||||
setAuthType('auto')
|
||||
setBearerToken('')
|
||||
setClientId('')
|
||||
setClientSecret('')
|
||||
setScope('')
|
||||
setGrantType('authorization_code')
|
||||
setDirectTools(false)
|
||||
setExcludedTools([])
|
||||
setExpandedTools({})
|
||||
setIsInstructionsExpanded(false)
|
||||
}
|
||||
}, [server, isOpen])
|
||||
|
||||
const buildAuthConfig = () => {
|
||||
if (authType === 'none') {
|
||||
return { type: 'none' as const }
|
||||
}
|
||||
if (authType === 'bearer') {
|
||||
return { type: 'bearer' as const, bearerToken: bearerToken || undefined }
|
||||
}
|
||||
if (authType === 'oauth') {
|
||||
return {
|
||||
type: 'oauth' as const,
|
||||
oauth: {
|
||||
grantType,
|
||||
clientId: clientId || undefined,
|
||||
clientSecret: clientSecret || undefined,
|
||||
scope: scope || undefined,
|
||||
},
|
||||
}
|
||||
}
|
||||
return undefined // 'auto'
|
||||
}
|
||||
|
||||
// Fetch tools (edit mode only)
|
||||
const {
|
||||
data: toolsData,
|
||||
isLoading: isToolsLoading,
|
||||
refetch: refetchTools,
|
||||
} = useQuery({
|
||||
queryKey: ['mcp', 'servers', server?.id, 'tools'],
|
||||
queryFn: async () => {
|
||||
if (!server?.id) return { tools: [] as McpToolInfo[] }
|
||||
const res = await client.api.mcp.servers[':id'].tools.$get({
|
||||
param: { id: server.id },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch tools')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: isOpen && isEditing && !!server?.id,
|
||||
})
|
||||
|
||||
const refreshMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!server?.id) return
|
||||
const res = await client.api.mcp.servers[':id'].refresh.$post({
|
||||
param: { id: server.id },
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => ({}))) as { error?: string }
|
||||
throw new Error(err.error || 'Failed to refresh server')
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(m.mcp_refresh_server_success())
|
||||
// The tool list is refetched and the toggles re-enable; the server cards
|
||||
// re-fetch the updated record (name, description, instructions, status).
|
||||
refetchTools()
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] })
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const config = {
|
||||
directTools,
|
||||
excludeTools: excludedTools.length > 0 ? excludedTools : undefined,
|
||||
}
|
||||
|
||||
if (isEditing && server) {
|
||||
const updatePayload: UpdateMcpServerRequest = {
|
||||
transport,
|
||||
permission,
|
||||
authConfig: buildAuthConfig(),
|
||||
config,
|
||||
}
|
||||
|
||||
const res = await client.api.mcp.servers[':id'].$patch({
|
||||
param: { id: server.id },
|
||||
json: updatePayload,
|
||||
})
|
||||
if (!res.ok) {
|
||||
const errData = (await res.json().catch(() => ({}))) as { error?: string }
|
||||
throw new Error(errData.error || m.failed_to_update_permission())
|
||||
}
|
||||
return await res.json()
|
||||
} else {
|
||||
const createPayload: CreateMcpServerRequest = {
|
||||
url: url.trim(),
|
||||
}
|
||||
|
||||
const res = await client.api.teams[':teamId'].mcp.servers.$post({
|
||||
param: { teamId },
|
||||
json: createPayload,
|
||||
})
|
||||
if (!res.ok) {
|
||||
const errData = (await res.json().catch(() => ({}))) as { error?: string }
|
||||
throw new Error(errData.error || m.an_unknown_error_occurred())
|
||||
}
|
||||
const created = await res.json()
|
||||
return created
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(isEditing ? m.profile_updated() : m.mcp_servers())
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'mcp', 'servers'] })
|
||||
onClose()
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error(err.message)
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!url.trim()) return
|
||||
saveMutation.mutate()
|
||||
}
|
||||
|
||||
const tools = toolsData?.tools ?? []
|
||||
|
||||
const isToolExcluded = (toolName: string) => excludedTools.includes(toolName)
|
||||
|
||||
const toggleToolEnabled = (toolName: string, enabled: boolean) => {
|
||||
setExcludedTools((prev) => (enabled ? prev.filter((n) => n !== toolName) : [...prev, toolName]))
|
||||
}
|
||||
|
||||
const toggleExpand = (toolName: string) => {
|
||||
setExpandedTools((prev) => ({ ...prev, [toolName]: !prev[toolName] }))
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
{isEditing && server ? (
|
||||
/* ------------------------------------------------------------------
|
||||
* Edit / config mode: fixed header + footer, scrollable content.
|
||||
* Mirrors the skill config dialog layout.
|
||||
* ------------------------------------------------------------------ */
|
||||
<DialogContent className="sm:max-w-2xl h-[85vh] flex flex-col p-0 overflow-hidden">
|
||||
{refreshMutation.isPending && (
|
||||
<div className="absolute inset-0 bg-background/60 backdrop-blur-[1px] flex flex-col items-center justify-center z-50 rounded-lg">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-primary mb-2" />
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{m.mcp_refresh_server()}...
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogHeader className="p-6 pb-4 border-b border-border flex-shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2 text-xl font-bold">
|
||||
<Server className="w-5 h-5 text-primary" />
|
||||
{m.edit_mcp_server()}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{m.mcp_servers_description()}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit} className="flex-1 flex flex-col min-h-0 overflow-hidden">
|
||||
<ScrollArea className="flex-1 min-h-0">
|
||||
<div className="p-6 space-y-5">
|
||||
{/* Auto-detected identity (read-only) — the endpoint URL is
|
||||
set at creation and immutable here (delete + re-add to
|
||||
change it). */}
|
||||
<div className="grid grid-cols-1 gap-3 p-3 bg-muted/30 border border-border rounded-lg">
|
||||
<div className="flex flex-col">
|
||||
<span className="text-[10px] uppercase tracking-wider text-muted-foreground font-semibold">
|
||||
{m.mcp_server_name()}
|
||||
</span>
|
||||
<span className="text-sm font-medium">{server.name}</span>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<span className="text-[10px] uppercase tracking-wider text-muted-foreground font-semibold">
|
||||
{m.mcp_server_url()}
|
||||
</span>
|
||||
<span className="text-sm font-mono text-foreground break-all">
|
||||
{server.url}
|
||||
</span>
|
||||
</div>
|
||||
{server.description && (
|
||||
<div className="flex flex-col">
|
||||
<span className="text-[10px] uppercase tracking-wider text-muted-foreground font-semibold">
|
||||
{m.description()}
|
||||
</span>
|
||||
<span className="text-sm text-foreground">{server.description}</span>
|
||||
</div>
|
||||
)}
|
||||
{server.instructions && (
|
||||
<div className="flex flex-col">
|
||||
<span className="text-[10px] uppercase tracking-wider text-muted-foreground font-semibold">
|
||||
{m.mcp_server_instructions()}
|
||||
</span>
|
||||
<p
|
||||
onClick={() => setIsInstructionsExpanded((prev) => !prev)}
|
||||
className={`text-xs text-muted-foreground cursor-pointer transition-all ${
|
||||
isInstructionsExpanded ? '' : 'line-clamp-2'
|
||||
}`}
|
||||
title={isInstructionsExpanded ? undefined : server.instructions}
|
||||
>
|
||||
{server.instructions}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<span className="text-[10px] text-muted-foreground flex items-center gap-1.5">
|
||||
<Info className="w-3 h-3" />
|
||||
{m.mcp_server_auto_detected()}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Transport & Permission */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs font-semibold">{m.mcp_transport()}</Label>
|
||||
<Select
|
||||
value={transport}
|
||||
onValueChange={(val) => setTransport(val as McpTransport)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="streamable_http">Streamable HTTP (Default)</SelectItem>
|
||||
<SelectItem value="sse">Server-Sent Events (SSE)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs font-semibold">{m.skill_permission()}</Label>
|
||||
<Select
|
||||
value={permission}
|
||||
onValueChange={(val) => setPermission(val as McpServerPermission)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="reviewer">{m.permission_all_users()}</SelectItem>
|
||||
<SelectItem value="editor">{m.permission_owner_and_editor()}</SelectItem>
|
||||
<SelectItem value="owner">{m.permission_owner_only()}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Authentication Section */}
|
||||
<div className="space-y-3 pt-3 border-t border-border">
|
||||
<Label className="text-xs font-semibold flex items-center justify-between">
|
||||
<span>{m.mcp_auth_type()}</span>
|
||||
<span className="text-[10px] text-muted-foreground font-normal">
|
||||
Configures server connection auth
|
||||
</span>
|
||||
</Label>
|
||||
|
||||
<Select
|
||||
value={authType}
|
||||
onValueChange={(val) => setAuthType(val as McpServerAuthType | 'auto')}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="auto">{m.mcp_auth_auto()}</SelectItem>
|
||||
<SelectItem value="none">{m.mcp_auth_none()}</SelectItem>
|
||||
<SelectItem value="bearer">{m.mcp_auth_bearer()}</SelectItem>
|
||||
<SelectItem value="oauth">{m.mcp_auth_oauth()}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{authType === 'bearer' && (
|
||||
<div className="space-y-2 pl-1 pt-1">
|
||||
<Label className="text-xs">{m.mcp_bearer_token()}</Label>
|
||||
<Input
|
||||
type="password"
|
||||
value={bearerToken}
|
||||
onChange={(e) => setBearerToken(e.target.value)}
|
||||
placeholder="Bearer token value"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{authType === 'oauth' && (
|
||||
<div className="space-y-3 pl-1 pt-1 border-l-2 border-primary/20 pl-3">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">{m.mcp_oauth_grant_type()}</Label>
|
||||
<Select
|
||||
value={grantType}
|
||||
onValueChange={(val) =>
|
||||
setGrantType(val as 'authorization_code' | 'client_credentials')
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-9 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="authorization_code">Authorization Code</SelectItem>
|
||||
<SelectItem value="client_credentials">Client Credentials</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">{m.mcp_oauth_client_id()}</Label>
|
||||
<Input
|
||||
className="h-9 text-xs"
|
||||
value={clientId}
|
||||
onChange={(e) => setClientId(e.target.value)}
|
||||
placeholder="Optional pre-registered Client ID"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">{m.mcp_oauth_client_secret()}</Label>
|
||||
<Input
|
||||
className="h-9 text-xs"
|
||||
type="password"
|
||||
value={clientSecret}
|
||||
onChange={(e) => setClientSecret(e.target.value)}
|
||||
placeholder="Optional Client Secret"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">{m.mcp_oauth_scope()}</Label>
|
||||
<Input
|
||||
className="h-9 text-xs"
|
||||
value={scope}
|
||||
onChange={(e) => setScope(e.target.value)}
|
||||
placeholder="Optional scope (e.g. read,write)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Mode */}
|
||||
<div className="space-y-3 pt-3 border-t border-border">
|
||||
<div className="p-3 bg-muted/20 border border-border rounded-lg space-y-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-semibold text-foreground">
|
||||
{m.mcp_direct_tools_mode()}
|
||||
</span>
|
||||
<Switch checked={directTools} onCheckedChange={setDirectTools} />
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground leading-relaxed">
|
||||
{m.mcp_direct_tools_desc()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tools list (excludeTools management) */}
|
||||
<div className="space-y-3 pt-3 border-t border-border">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-xs font-semibold flex items-center gap-1.5">
|
||||
<Wrench className="w-3.5 h-3.5" />
|
||||
{m.mcp_tools()}
|
||||
</Label>
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
{m.mcp_tools_count({ count: tools.length })} — {m.mcp_excluded_tools_hint()}
|
||||
</p>
|
||||
|
||||
<div className="space-y-2">
|
||||
{isToolsLoading ? (
|
||||
<div className="flex justify-center py-8">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-primary" />
|
||||
</div>
|
||||
) : tools.length === 0 ? (
|
||||
<div className="text-center py-6 text-muted-foreground text-xs">
|
||||
{m.no_tools_found()}
|
||||
</div>
|
||||
) : (
|
||||
tools.map((tool) => {
|
||||
const enabled = !isToolExcluded(tool.name)
|
||||
const isExpanded = !!expandedTools[tool.name]
|
||||
const schemaObj = tool.inputSchema as {
|
||||
properties?: Record<string, { type?: string; description?: string }>
|
||||
required?: string[]
|
||||
}
|
||||
const hasProperties =
|
||||
schemaObj?.properties && Object.keys(schemaObj.properties).length > 0
|
||||
|
||||
return (
|
||||
<div
|
||||
key={tool.name}
|
||||
className={`border border-border rounded-lg p-3 transition-colors ${
|
||||
enabled ? 'bg-card' : 'bg-muted/30 opacity-70'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div
|
||||
className="flex items-start gap-2 flex-1 min-w-0 cursor-pointer"
|
||||
onClick={() => hasProperties && toggleExpand(tool.name)}
|
||||
>
|
||||
{hasProperties ? (
|
||||
isExpanded ? (
|
||||
<ChevronDown className="w-4 h-4 text-muted-foreground mt-0.5 shrink-0" />
|
||||
) : (
|
||||
<ChevronRight className="w-4 h-4 text-muted-foreground mt-0.5 shrink-0" />
|
||||
)
|
||||
) : (
|
||||
<div className="w-4 h-4 shrink-0" />
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-mono text-xs font-bold text-foreground break-all">
|
||||
{tool.name}
|
||||
</span>
|
||||
{tool.title && (
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
{tool.title}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{tool.description && (
|
||||
<p className="text-xs text-muted-foreground mt-1 break-words line-clamp-3">
|
||||
{tool.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Switch
|
||||
checked={enabled}
|
||||
disabled={refreshMutation.isPending || isToolsLoading}
|
||||
onCheckedChange={(checked) =>
|
||||
toggleToolEnabled(tool.name, checked)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Parameters schema expansion */}
|
||||
{isExpanded && hasProperties && (
|
||||
<div className="mt-3 pt-3 border-t border-border/60 pl-6 space-y-2">
|
||||
<span className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">
|
||||
{m.tool_parameters()}
|
||||
</span>
|
||||
<div className="grid grid-cols-1 gap-1.5">
|
||||
{Object.entries(schemaObj.properties!).map(
|
||||
([propName, propDef]) => {
|
||||
const isRequired = schemaObj.required?.includes(propName)
|
||||
return (
|
||||
<div
|
||||
key={propName}
|
||||
className="flex flex-col sm:flex-row sm:items-baseline justify-between gap-1 sm:gap-2 p-2 bg-muted/20 rounded text-xs min-w-0"
|
||||
>
|
||||
<div className="flex items-center gap-1.5 flex-wrap min-w-0">
|
||||
<span className="font-mono font-semibold break-all">
|
||||
{propName}
|
||||
</span>
|
||||
{isRequired && (
|
||||
<span className="text-[10px] text-red-500 font-bold">
|
||||
*
|
||||
</span>
|
||||
)}
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="text-[9px] px-1 py-0"
|
||||
>
|
||||
{propDef.type || 'any'}
|
||||
</Badge>
|
||||
</div>
|
||||
{propDef.description && (
|
||||
<span className="text-[11px] text-muted-foreground break-words sm:max-w-[320px]">
|
||||
{propDef.description}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<DialogFooter className="p-6 pt-4 border-t border-border flex-shrink-0">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => refreshMutation.mutate()}
|
||||
disabled={refreshMutation.isPending || isToolsLoading || saveMutation.isPending}
|
||||
className="gap-1.5 mr-auto"
|
||||
>
|
||||
<RefreshCw
|
||||
className={`w-4 h-4 ${refreshMutation.isPending ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
{m.mcp_refresh_server()}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saveMutation.isPending || !url}>
|
||||
{saveMutation.isPending && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
{m.save_changes()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
) : (
|
||||
/* ------------------------------------------------------------------
|
||||
* Create mode: compact URL-only dialog. Name/description are
|
||||
* auto-detected from the server after connecting.
|
||||
* ------------------------------------------------------------------ */
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2 text-xl font-bold">
|
||||
<Server className="w-5 h-5 text-primary" />
|
||||
{m.add_mcp_server()}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{m.mcp_servers_description()}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs font-semibold">{m.mcp_server_url()}</Label>
|
||||
<Input
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
placeholder="https://mcp.example.com/mcp"
|
||||
type="url"
|
||||
required
|
||||
/>
|
||||
<p className="text-[11px] text-muted-foreground flex items-center gap-1.5">
|
||||
<Info className="w-3.5 h-3.5" />
|
||||
{m.mcp_server_auto_detected()}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saveMutation.isPending || !url}>
|
||||
{saveMutation.isPending && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
{m.create()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
)}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -353,6 +353,53 @@
|
||||
"github_url_example": "Example: https://github.com/google/gemini-cli",
|
||||
"configure_skill": "Configure Skill: {name}",
|
||||
"manage_env_vars_description": "Manage environment variables for this skill instance.",
|
||||
|
||||
"mcp_servers": "MCP Servers",
|
||||
"mcp_servers_description": "Configure Model Context Protocol (MCP) servers and tools for your team.",
|
||||
"add_mcp_server": "Add MCP Server",
|
||||
"edit_mcp_server": "Edit MCP Server",
|
||||
"delete_mcp_server": "Delete MCP Server",
|
||||
"delete_mcp_server_confirmation": "This action cannot be undone. This will permanently delete the MCP server \"{name}\".",
|
||||
"mcp_server_name": "Server Name",
|
||||
"mcp_server_instructions": "Server Instructions",
|
||||
"mcp_server_url": "Endpoint URL",
|
||||
"mcp_transport": "Transport Protocol",
|
||||
"mcp_auth_type": "Authentication Type",
|
||||
"mcp_auth_auto": "Auto-Detect (Default)",
|
||||
"mcp_auth_none": "None",
|
||||
"mcp_auth_bearer": "Bearer Token",
|
||||
"mcp_auth_oauth": "OAuth 2.0",
|
||||
"mcp_bearer_token": "Bearer Token",
|
||||
"mcp_oauth_client_id": "Client ID",
|
||||
"mcp_oauth_client_secret": "Client Secret",
|
||||
"mcp_oauth_scope": "Scope",
|
||||
"mcp_oauth_grant_type": "Grant Type",
|
||||
"mcp_direct_tools_mode": "Direct Tools Mode",
|
||||
"mcp_direct_tools_desc": "Exposes MCP tools as native agent tools instead of hiding them behind the MCP proxy. This lets the agent see and call selected MCP tools directly, improving tool discovery and reducing unnecessary searches. Use it for frequently used or important tools; keep large MCP servers behind the proxy to avoid increasing context usage.",
|
||||
"mcp_tools": "MCP Tools",
|
||||
"mcp_tools_count": "{count} Tools",
|
||||
"mcp_status_connected": "Connected",
|
||||
"mcp_status_not_connected": "Not Connected",
|
||||
"mcp_status_failed": "Failed",
|
||||
"mcp_status_needs_auth": "Needs Authentication",
|
||||
"mcp_connect_auth": "Connect Account",
|
||||
"mcp_disconnect_auth": "Disconnect Auth",
|
||||
"mcp_auth_success": "MCP server authenticated successfully",
|
||||
"mcp_auth_failed": "Failed to authenticate MCP server",
|
||||
"mcp_test_connection": "Test Connection",
|
||||
"mcp_test_success": "MCP server test successful",
|
||||
"mcp_test_failed": "MCP server test failed",
|
||||
"mcp_refresh_server": "Refresh Server",
|
||||
"mcp_refresh_server_success": "Server refreshed",
|
||||
"no_mcp_servers_installed": "No MCP servers configured",
|
||||
"add_mcp_server_to_get_started": "Add an MCP server to extend your AI agent tools.",
|
||||
"search_tools_placeholder": "Search tools by name or description...",
|
||||
"mcp_server_auto_detected": "Name and description are auto-detected from the server after connecting.",
|
||||
"mcp_excluded_tools_hint": "Disable a tool to exclude it from this server's toolset.",
|
||||
"view_tools": "View Tools",
|
||||
"tool_parameters": "Parameters",
|
||||
"no_tools_found": "No tools found matching your search.",
|
||||
"mcp_server_requires_auth": "This MCP server requires authentication. Connect in Settings → MCP Servers.",
|
||||
"no_env_vars_found": "No environment variables found. Click \"Add Variable\" to create one.",
|
||||
"variable_name": "Variable Name",
|
||||
"default_value": "Default Value",
|
||||
|
||||
@@ -353,6 +353,53 @@
|
||||
"github_url_example": "示例:https://github.com/google/gemini-cli",
|
||||
"configure_skill": "配置技能:{name}",
|
||||
"manage_env_vars_description": "管理此技能实例的环境变量。",
|
||||
|
||||
"mcp_servers": "MCP 服务",
|
||||
"mcp_servers_description": "为团队配置 Model Context Protocol (MCP) 服务与工具。",
|
||||
"add_mcp_server": "添加 MCP 服务",
|
||||
"edit_mcp_server": "编辑 MCP 服务",
|
||||
"delete_mcp_server": "删除 MCP 服务",
|
||||
"delete_mcp_server_confirmation": "此操作无法撤销。这将永久删除 MCP 服务 \"{name}\"。",
|
||||
"mcp_server_name": "服务名称",
|
||||
"mcp_server_instructions": "服务器说明",
|
||||
"mcp_server_url": "Endpoint URL",
|
||||
"mcp_transport": "传输协议",
|
||||
"mcp_auth_type": "身份验证类型",
|
||||
"mcp_auth_auto": "自动检测 (默认)",
|
||||
"mcp_auth_none": "无",
|
||||
"mcp_auth_bearer": "Bearer 令牌",
|
||||
"mcp_auth_oauth": "OAuth 2.0",
|
||||
"mcp_bearer_token": "Bearer 令牌",
|
||||
"mcp_oauth_client_id": "Client ID",
|
||||
"mcp_oauth_client_secret": "Client Secret",
|
||||
"mcp_oauth_scope": "作用域 (Scope)",
|
||||
"mcp_oauth_grant_type": "授权模式 (Grant Type)",
|
||||
"mcp_direct_tools_mode": "直连工具模式",
|
||||
"mcp_direct_tools_desc": "将 MCP 工具直接作为智能体原生工具暴露,而非隐匿在 MCP 代理之后。这使得智能体能直接感知并调用选定的 MCP 工具,提高工具发现率并减少不必要的搜索。建议对于高频或关键工具开启此模式;大型 MCP 服务建议保持代理模式以避免增加上下文消耗。",
|
||||
"mcp_tools": "MCP 工具",
|
||||
"mcp_tools_count": "{count} 个工具",
|
||||
"mcp_status_connected": "已连接",
|
||||
"mcp_status_not_connected": "未连接",
|
||||
"mcp_status_failed": "连接失败",
|
||||
"mcp_status_needs_auth": "需要身份验证",
|
||||
"mcp_connect_auth": "连接账号",
|
||||
"mcp_disconnect_auth": "断开身份验证",
|
||||
"mcp_auth_success": "MCP 服务身份验证成功",
|
||||
"mcp_auth_failed": "MCP 服务身份验证失败",
|
||||
"mcp_test_connection": "测试连接",
|
||||
"mcp_test_success": "MCP 服务测试成功",
|
||||
"mcp_test_failed": "MCP 服务测试失败",
|
||||
"mcp_refresh_server": "刷新服务器",
|
||||
"mcp_refresh_server_success": "服务器已刷新",
|
||||
"no_mcp_servers_installed": "暂未配置 MCP 服务",
|
||||
"add_mcp_server_to_get_started": "添加 MCP 服务以扩展 AI Agent 的工具能力。",
|
||||
"search_tools_placeholder": "按名称或描述搜索工具...",
|
||||
"mcp_server_auto_detected": "连接后将自动从服务端获取名称和描述。",
|
||||
"mcp_excluded_tools_hint": "关闭某个工具会将其从该服务的工具集中排除。",
|
||||
"view_tools": "查看工具",
|
||||
"tool_parameters": "参数列表",
|
||||
"no_tools_found": "未找到符合搜索条件的工具。",
|
||||
"mcp_server_requires_auth": "该 MCP 服务需要身份验证,请前往 设置 → MCP 服务 进行连接。",
|
||||
"no_env_vars_found": "未找到环境变量。点击\"添加变量\"创建一个。",
|
||||
"variable_name": "变量名称",
|
||||
"default_value": "默认值",
|
||||
|
||||
+46
@@ -336,6 +336,52 @@ export * from "./github_repository_url.js";
|
||||
export * from "./github_url_example.js";
|
||||
export * from "./configure_skill.js";
|
||||
export * from "./manage_env_vars_description.js";
|
||||
export * from "./mcp_servers.js";
|
||||
export * from "./mcp_servers_description.js";
|
||||
export * from "./add_mcp_server.js";
|
||||
export * from "./edit_mcp_server.js";
|
||||
export * from "./delete_mcp_server.js";
|
||||
export * from "./delete_mcp_server_confirmation.js";
|
||||
export * from "./mcp_server_name.js";
|
||||
export * from "./mcp_server_instructions.js";
|
||||
export * from "./mcp_server_url.js";
|
||||
export * from "./mcp_transport.js";
|
||||
export * from "./mcp_auth_type.js";
|
||||
export * from "./mcp_auth_auto.js";
|
||||
export * from "./mcp_auth_none.js";
|
||||
export * from "./mcp_auth_bearer.js";
|
||||
export * from "./mcp_auth_oauth.js";
|
||||
export * from "./mcp_bearer_token.js";
|
||||
export * from "./mcp_oauth_client_id.js";
|
||||
export * from "./mcp_oauth_client_secret.js";
|
||||
export * from "./mcp_oauth_scope.js";
|
||||
export * from "./mcp_oauth_grant_type.js";
|
||||
export * from "./mcp_direct_tools_mode.js";
|
||||
export * from "./mcp_direct_tools_desc.js";
|
||||
export * from "./mcp_tools.js";
|
||||
export * from "./mcp_tools_count.js";
|
||||
export * from "./mcp_status_connected.js";
|
||||
export * from "./mcp_status_not_connected.js";
|
||||
export * from "./mcp_status_failed.js";
|
||||
export * from "./mcp_status_needs_auth.js";
|
||||
export * from "./mcp_connect_auth.js";
|
||||
export * from "./mcp_disconnect_auth.js";
|
||||
export * from "./mcp_auth_success.js";
|
||||
export * from "./mcp_auth_failed.js";
|
||||
export * from "./mcp_test_connection.js";
|
||||
export * from "./mcp_test_success.js";
|
||||
export * from "./mcp_test_failed.js";
|
||||
export * from "./mcp_refresh_server.js";
|
||||
export * from "./mcp_refresh_server_success.js";
|
||||
export * from "./no_mcp_servers_installed.js";
|
||||
export * from "./add_mcp_server_to_get_started.js";
|
||||
export * from "./search_tools_placeholder.js";
|
||||
export * from "./mcp_server_auto_detected.js";
|
||||
export * from "./mcp_excluded_tools_hint.js";
|
||||
export * from "./view_tools.js";
|
||||
export * from "./tool_parameters.js";
|
||||
export * from "./no_tools_found.js";
|
||||
export * from "./mcp_server_requires_auth.js";
|
||||
export * from "./no_env_vars_found.js";
|
||||
export * from "./variable_name.js";
|
||||
export * from "./default_value.js";
|
||||
|
||||
+46
@@ -338,6 +338,52 @@ export * from './github_repository_url.js'
|
||||
export * from './github_url_example.js'
|
||||
export * from './configure_skill.js'
|
||||
export * from './manage_env_vars_description.js'
|
||||
export * from './mcp_servers.js'
|
||||
export * from './mcp_servers_description.js'
|
||||
export * from './add_mcp_server.js'
|
||||
export * from './edit_mcp_server.js'
|
||||
export * from './delete_mcp_server.js'
|
||||
export * from './delete_mcp_server_confirmation.js'
|
||||
export * from './mcp_server_name.js'
|
||||
export * from './mcp_server_instructions.js'
|
||||
export * from './mcp_server_url.js'
|
||||
export * from './mcp_transport.js'
|
||||
export * from './mcp_auth_type.js'
|
||||
export * from './mcp_auth_auto.js'
|
||||
export * from './mcp_auth_none.js'
|
||||
export * from './mcp_auth_bearer.js'
|
||||
export * from './mcp_auth_oauth.js'
|
||||
export * from './mcp_bearer_token.js'
|
||||
export * from './mcp_oauth_client_id.js'
|
||||
export * from './mcp_oauth_client_secret.js'
|
||||
export * from './mcp_oauth_scope.js'
|
||||
export * from './mcp_oauth_grant_type.js'
|
||||
export * from './mcp_direct_tools_mode.js'
|
||||
export * from './mcp_direct_tools_desc.js'
|
||||
export * from './mcp_tools.js'
|
||||
export * from './mcp_tools_count.js'
|
||||
export * from './mcp_status_connected.js'
|
||||
export * from './mcp_status_not_connected.js'
|
||||
export * from './mcp_status_failed.js'
|
||||
export * from './mcp_status_needs_auth.js'
|
||||
export * from './mcp_connect_auth.js'
|
||||
export * from './mcp_disconnect_auth.js'
|
||||
export * from './mcp_auth_success.js'
|
||||
export * from './mcp_auth_failed.js'
|
||||
export * from './mcp_test_connection.js'
|
||||
export * from './mcp_test_success.js'
|
||||
export * from './mcp_test_failed.js'
|
||||
export * from './mcp_refresh_server.js'
|
||||
export * from './mcp_refresh_server_success.js'
|
||||
export * from './no_mcp_servers_installed.js'
|
||||
export * from './add_mcp_server_to_get_started.js'
|
||||
export * from './search_tools_placeholder.js'
|
||||
export * from './mcp_server_auto_detected.js'
|
||||
export * from './mcp_excluded_tools_hint.js'
|
||||
export * from './view_tools.js'
|
||||
export * from './tool_parameters.js'
|
||||
export * from './no_tools_found.js'
|
||||
export * from './mcp_server_requires_auth.js'
|
||||
export * from './no_env_vars_found.js'
|
||||
export * from './variable_name.js'
|
||||
export * from './default_value.js'
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Add MCP Server" |
|
||||
*
|
||||
* @param {Add_Mcp_ServerInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const add_mcp_server: ((inputs?: Add_Mcp_ServerInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Add_Mcp_ServerInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Add_Mcp_ServerInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Add_Mcp_ServerInputs */
|
||||
|
||||
const en_add_mcp_server = /** @type {(inputs: Add_Mcp_ServerInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Add MCP Server`)
|
||||
};
|
||||
|
||||
const zh_add_mcp_server = /** @type {(inputs: Add_Mcp_ServerInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`添加 MCP 服务`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Add MCP Server" |
|
||||
*
|
||||
* @param {Add_Mcp_ServerInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const add_mcp_server = /** @type {((inputs?: Add_Mcp_ServerInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Add_Mcp_ServerInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_add_mcp_server(inputs)
|
||||
return zh_add_mcp_server(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Add an MCP server to extend your AI agent tools." |
|
||||
*
|
||||
* @param {Add_Mcp_Server_To_Get_StartedInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const add_mcp_server_to_get_started: ((inputs?: Add_Mcp_Server_To_Get_StartedInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Add_Mcp_Server_To_Get_StartedInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Add_Mcp_Server_To_Get_StartedInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Add_Mcp_Server_To_Get_StartedInputs */
|
||||
|
||||
const en_add_mcp_server_to_get_started = /** @type {(inputs: Add_Mcp_Server_To_Get_StartedInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Add an MCP server to extend your AI agent tools.`)
|
||||
};
|
||||
|
||||
const zh_add_mcp_server_to_get_started = /** @type {(inputs: Add_Mcp_Server_To_Get_StartedInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`添加 MCP 服务以扩展 AI Agent 的工具能力。`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Add an MCP server to extend your AI agent tools." |
|
||||
*
|
||||
* @param {Add_Mcp_Server_To_Get_StartedInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const add_mcp_server_to_get_started = /** @type {((inputs?: Add_Mcp_Server_To_Get_StartedInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Add_Mcp_Server_To_Get_StartedInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_add_mcp_server_to_get_started(inputs)
|
||||
return zh_add_mcp_server_to_get_started(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Delete MCP Server" |
|
||||
*
|
||||
* @param {Delete_Mcp_ServerInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const delete_mcp_server: ((inputs?: Delete_Mcp_ServerInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Delete_Mcp_ServerInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Delete_Mcp_ServerInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Delete_Mcp_ServerInputs */
|
||||
|
||||
const en_delete_mcp_server = /** @type {(inputs: Delete_Mcp_ServerInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Delete MCP Server`)
|
||||
};
|
||||
|
||||
const zh_delete_mcp_server = /** @type {(inputs: Delete_Mcp_ServerInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`删除 MCP 服务`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Delete MCP Server" |
|
||||
*
|
||||
* @param {Delete_Mcp_ServerInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const delete_mcp_server = /** @type {((inputs?: Delete_Mcp_ServerInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Delete_Mcp_ServerInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_delete_mcp_server(inputs)
|
||||
return zh_delete_mcp_server(inputs)
|
||||
});
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "This action cannot be undone. This will permanently delete the MCP server \"{name}\"." |
|
||||
*
|
||||
* @param {Delete_Mcp_Server_ConfirmationInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const delete_mcp_server_confirmation: ((inputs: Delete_Mcp_Server_ConfirmationInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Delete_Mcp_Server_ConfirmationInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Delete_Mcp_Server_ConfirmationInputs = {
|
||||
name: NonNullable<unknown>;
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{ name: NonNullable<unknown> }} Delete_Mcp_Server_ConfirmationInputs */
|
||||
|
||||
const en_delete_mcp_server_confirmation = /** @type {(inputs: Delete_Mcp_Server_ConfirmationInputs) => LocalizedString} */ (i) => {
|
||||
return /** @type {LocalizedString} */ (`This action cannot be undone. This will permanently delete the MCP server "${i?.name}".`)
|
||||
};
|
||||
|
||||
const zh_delete_mcp_server_confirmation = /** @type {(inputs: Delete_Mcp_Server_ConfirmationInputs) => LocalizedString} */ (i) => {
|
||||
return /** @type {LocalizedString} */ (`此操作无法撤销。这将永久删除 MCP 服务 "${i?.name}"。`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "This action cannot be undone. This will permanently delete the MCP server \"{name}\"." |
|
||||
*
|
||||
* @param {Delete_Mcp_Server_ConfirmationInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const delete_mcp_server_confirmation = /** @type {((inputs: Delete_Mcp_Server_ConfirmationInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Delete_Mcp_Server_ConfirmationInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_delete_mcp_server_confirmation(inputs)
|
||||
return zh_delete_mcp_server_confirmation(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Edit MCP Server" |
|
||||
*
|
||||
* @param {Edit_Mcp_ServerInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const edit_mcp_server: ((inputs?: Edit_Mcp_ServerInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Edit_Mcp_ServerInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Edit_Mcp_ServerInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Edit_Mcp_ServerInputs */
|
||||
|
||||
const en_edit_mcp_server = /** @type {(inputs: Edit_Mcp_ServerInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Edit MCP Server`)
|
||||
};
|
||||
|
||||
const zh_edit_mcp_server = /** @type {(inputs: Edit_Mcp_ServerInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`编辑 MCP 服务`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Edit MCP Server" |
|
||||
*
|
||||
* @param {Edit_Mcp_ServerInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const edit_mcp_server = /** @type {((inputs?: Edit_Mcp_ServerInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Edit_Mcp_ServerInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_edit_mcp_server(inputs)
|
||||
return zh_edit_mcp_server(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Auto-Detect (Default)" |
|
||||
*
|
||||
* @param {Mcp_Auth_AutoInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_auto: ((inputs?: Mcp_Auth_AutoInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Auth_AutoInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Auth_AutoInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Auth_AutoInputs */
|
||||
|
||||
const en_mcp_auth_auto = /** @type {(inputs: Mcp_Auth_AutoInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Auto-Detect (Default)`)
|
||||
};
|
||||
|
||||
const zh_mcp_auth_auto = /** @type {(inputs: Mcp_Auth_AutoInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`自动检测 (默认)`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Auto-Detect (Default)" |
|
||||
*
|
||||
* @param {Mcp_Auth_AutoInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_auto = /** @type {((inputs?: Mcp_Auth_AutoInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Auth_AutoInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_auth_auto(inputs)
|
||||
return zh_mcp_auth_auto(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Bearer Token" |
|
||||
*
|
||||
* @param {Mcp_Auth_BearerInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_bearer: ((inputs?: Mcp_Auth_BearerInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Auth_BearerInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Auth_BearerInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Auth_BearerInputs */
|
||||
|
||||
const en_mcp_auth_bearer = /** @type {(inputs: Mcp_Auth_BearerInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Bearer Token`)
|
||||
};
|
||||
|
||||
const zh_mcp_auth_bearer = /** @type {(inputs: Mcp_Auth_BearerInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Bearer 令牌`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Bearer Token" |
|
||||
*
|
||||
* @param {Mcp_Auth_BearerInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_bearer = /** @type {((inputs?: Mcp_Auth_BearerInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Auth_BearerInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_auth_bearer(inputs)
|
||||
return zh_mcp_auth_bearer(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Failed to authenticate MCP server" |
|
||||
*
|
||||
* @param {Mcp_Auth_FailedInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_failed: ((inputs?: Mcp_Auth_FailedInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Auth_FailedInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Auth_FailedInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Auth_FailedInputs */
|
||||
|
||||
const en_mcp_auth_failed = /** @type {(inputs: Mcp_Auth_FailedInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Failed to authenticate MCP server`)
|
||||
};
|
||||
|
||||
const zh_mcp_auth_failed = /** @type {(inputs: Mcp_Auth_FailedInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`MCP 服务身份验证失败`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Failed to authenticate MCP server" |
|
||||
*
|
||||
* @param {Mcp_Auth_FailedInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_failed = /** @type {((inputs?: Mcp_Auth_FailedInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Auth_FailedInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_auth_failed(inputs)
|
||||
return zh_mcp_auth_failed(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "None" |
|
||||
*
|
||||
* @param {Mcp_Auth_NoneInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_none: ((inputs?: Mcp_Auth_NoneInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Auth_NoneInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Auth_NoneInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Auth_NoneInputs */
|
||||
|
||||
const en_mcp_auth_none = /** @type {(inputs: Mcp_Auth_NoneInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`None`)
|
||||
};
|
||||
|
||||
const zh_mcp_auth_none = /** @type {(inputs: Mcp_Auth_NoneInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`无`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "None" |
|
||||
*
|
||||
* @param {Mcp_Auth_NoneInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_none = /** @type {((inputs?: Mcp_Auth_NoneInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Auth_NoneInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_auth_none(inputs)
|
||||
return zh_mcp_auth_none(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "OAuth 2.0" |
|
||||
*
|
||||
* @param {Mcp_Auth_OauthInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_oauth: ((inputs?: Mcp_Auth_OauthInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Auth_OauthInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Auth_OauthInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Auth_OauthInputs */
|
||||
|
||||
const en_mcp_auth_oauth = /** @type {(inputs: Mcp_Auth_OauthInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`OAuth 2.0`)
|
||||
};
|
||||
|
||||
const zh_mcp_auth_oauth = /** @type {(inputs: Mcp_Auth_OauthInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`OAuth 2.0`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "OAuth 2.0" |
|
||||
*
|
||||
* @param {Mcp_Auth_OauthInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_oauth = /** @type {((inputs?: Mcp_Auth_OauthInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Auth_OauthInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_auth_oauth(inputs)
|
||||
return zh_mcp_auth_oauth(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "MCP server authenticated successfully" |
|
||||
*
|
||||
* @param {Mcp_Auth_SuccessInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_success: ((inputs?: Mcp_Auth_SuccessInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Auth_SuccessInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Auth_SuccessInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Auth_SuccessInputs */
|
||||
|
||||
const en_mcp_auth_success = /** @type {(inputs: Mcp_Auth_SuccessInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`MCP server authenticated successfully`)
|
||||
};
|
||||
|
||||
const zh_mcp_auth_success = /** @type {(inputs: Mcp_Auth_SuccessInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`MCP 服务身份验证成功`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "MCP server authenticated successfully" |
|
||||
*
|
||||
* @param {Mcp_Auth_SuccessInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_success = /** @type {((inputs?: Mcp_Auth_SuccessInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Auth_SuccessInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_auth_success(inputs)
|
||||
return zh_mcp_auth_success(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Authentication Type" |
|
||||
*
|
||||
* @param {Mcp_Auth_TypeInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_type: ((inputs?: Mcp_Auth_TypeInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Auth_TypeInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Auth_TypeInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Auth_TypeInputs */
|
||||
|
||||
const en_mcp_auth_type = /** @type {(inputs: Mcp_Auth_TypeInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Authentication Type`)
|
||||
};
|
||||
|
||||
const zh_mcp_auth_type = /** @type {(inputs: Mcp_Auth_TypeInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`身份验证类型`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Authentication Type" |
|
||||
*
|
||||
* @param {Mcp_Auth_TypeInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_auth_type = /** @type {((inputs?: Mcp_Auth_TypeInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Auth_TypeInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_auth_type(inputs)
|
||||
return zh_mcp_auth_type(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Bearer Token" |
|
||||
*
|
||||
* @param {Mcp_Bearer_TokenInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_bearer_token: ((inputs?: Mcp_Bearer_TokenInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Bearer_TokenInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Bearer_TokenInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Bearer_TokenInputs */
|
||||
|
||||
const en_mcp_bearer_token = /** @type {(inputs: Mcp_Bearer_TokenInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Bearer Token`)
|
||||
};
|
||||
|
||||
const zh_mcp_bearer_token = /** @type {(inputs: Mcp_Bearer_TokenInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Bearer 令牌`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Bearer Token" |
|
||||
*
|
||||
* @param {Mcp_Bearer_TokenInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_bearer_token = /** @type {((inputs?: Mcp_Bearer_TokenInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Bearer_TokenInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_bearer_token(inputs)
|
||||
return zh_mcp_bearer_token(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Connect Account" |
|
||||
*
|
||||
* @param {Mcp_Connect_AuthInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_connect_auth: ((inputs?: Mcp_Connect_AuthInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Connect_AuthInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Connect_AuthInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Connect_AuthInputs */
|
||||
|
||||
const en_mcp_connect_auth = /** @type {(inputs: Mcp_Connect_AuthInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Connect Account`)
|
||||
};
|
||||
|
||||
const zh_mcp_connect_auth = /** @type {(inputs: Mcp_Connect_AuthInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`连接账号`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Connect Account" |
|
||||
*
|
||||
* @param {Mcp_Connect_AuthInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_connect_auth = /** @type {((inputs?: Mcp_Connect_AuthInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Connect_AuthInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_connect_auth(inputs)
|
||||
return zh_mcp_connect_auth(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Exposes MCP tools as native agent tools instead of hiding them behind the MCP proxy. This lets the agent see and call selected MCP tools directly, improving ..." |
|
||||
*
|
||||
* @param {Mcp_Direct_Tools_DescInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_direct_tools_desc: ((inputs?: Mcp_Direct_Tools_DescInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Direct_Tools_DescInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Direct_Tools_DescInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Direct_Tools_DescInputs */
|
||||
|
||||
const en_mcp_direct_tools_desc = /** @type {(inputs: Mcp_Direct_Tools_DescInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Exposes MCP tools as native agent tools instead of hiding them behind the MCP proxy. This lets the agent see and call selected MCP tools directly, improving tool discovery and reducing unnecessary searches. Use it for frequently used or important tools; keep large MCP servers behind the proxy to avoid increasing context usage.`)
|
||||
};
|
||||
|
||||
const zh_mcp_direct_tools_desc = /** @type {(inputs: Mcp_Direct_Tools_DescInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`将 MCP 工具直接作为智能体原生工具暴露,而非隐匿在 MCP 代理之后。这使得智能体能直接感知并调用选定的 MCP 工具,提高工具发现率并减少不必要的搜索。建议对于高频或关键工具开启此模式;大型 MCP 服务建议保持代理模式以避免增加上下文消耗。`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Exposes MCP tools as native agent tools instead of hiding them behind the MCP proxy. This lets the agent see and call selected MCP tools directly, improving ..." |
|
||||
*
|
||||
* @param {Mcp_Direct_Tools_DescInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_direct_tools_desc = /** @type {((inputs?: Mcp_Direct_Tools_DescInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Direct_Tools_DescInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_direct_tools_desc(inputs)
|
||||
return zh_mcp_direct_tools_desc(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Direct Tools Mode" |
|
||||
*
|
||||
* @param {Mcp_Direct_Tools_ModeInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_direct_tools_mode: ((inputs?: Mcp_Direct_Tools_ModeInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Direct_Tools_ModeInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Direct_Tools_ModeInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Direct_Tools_ModeInputs */
|
||||
|
||||
const en_mcp_direct_tools_mode = /** @type {(inputs: Mcp_Direct_Tools_ModeInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Direct Tools Mode`)
|
||||
};
|
||||
|
||||
const zh_mcp_direct_tools_mode = /** @type {(inputs: Mcp_Direct_Tools_ModeInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`直连工具模式`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Direct Tools Mode" |
|
||||
*
|
||||
* @param {Mcp_Direct_Tools_ModeInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_direct_tools_mode = /** @type {((inputs?: Mcp_Direct_Tools_ModeInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Direct_Tools_ModeInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_direct_tools_mode(inputs)
|
||||
return zh_mcp_direct_tools_mode(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Disconnect Auth" |
|
||||
*
|
||||
* @param {Mcp_Disconnect_AuthInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_disconnect_auth: ((inputs?: Mcp_Disconnect_AuthInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Disconnect_AuthInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Disconnect_AuthInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Disconnect_AuthInputs */
|
||||
|
||||
const en_mcp_disconnect_auth = /** @type {(inputs: Mcp_Disconnect_AuthInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Disconnect Auth`)
|
||||
};
|
||||
|
||||
const zh_mcp_disconnect_auth = /** @type {(inputs: Mcp_Disconnect_AuthInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`断开身份验证`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Disconnect Auth" |
|
||||
*
|
||||
* @param {Mcp_Disconnect_AuthInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_disconnect_auth = /** @type {((inputs?: Mcp_Disconnect_AuthInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Disconnect_AuthInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_disconnect_auth(inputs)
|
||||
return zh_mcp_disconnect_auth(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Disable a tool to exclude it from this server's toolset." |
|
||||
*
|
||||
* @param {Mcp_Excluded_Tools_HintInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_excluded_tools_hint: ((inputs?: Mcp_Excluded_Tools_HintInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Excluded_Tools_HintInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Excluded_Tools_HintInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Excluded_Tools_HintInputs */
|
||||
|
||||
const en_mcp_excluded_tools_hint = /** @type {(inputs: Mcp_Excluded_Tools_HintInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Disable a tool to exclude it from this server's toolset.`)
|
||||
};
|
||||
|
||||
const zh_mcp_excluded_tools_hint = /** @type {(inputs: Mcp_Excluded_Tools_HintInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`关闭某个工具会将其从该服务的工具集中排除。`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Disable a tool to exclude it from this server's toolset." |
|
||||
*
|
||||
* @param {Mcp_Excluded_Tools_HintInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_excluded_tools_hint = /** @type {((inputs?: Mcp_Excluded_Tools_HintInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Excluded_Tools_HintInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_excluded_tools_hint(inputs)
|
||||
return zh_mcp_excluded_tools_hint(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Client ID" |
|
||||
*
|
||||
* @param {Mcp_Oauth_Client_IdInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_oauth_client_id: ((inputs?: Mcp_Oauth_Client_IdInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Oauth_Client_IdInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Oauth_Client_IdInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Oauth_Client_IdInputs */
|
||||
|
||||
const en_mcp_oauth_client_id = /** @type {(inputs: Mcp_Oauth_Client_IdInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Client ID`)
|
||||
};
|
||||
|
||||
const zh_mcp_oauth_client_id = /** @type {(inputs: Mcp_Oauth_Client_IdInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Client ID`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Client ID" |
|
||||
*
|
||||
* @param {Mcp_Oauth_Client_IdInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_oauth_client_id = /** @type {((inputs?: Mcp_Oauth_Client_IdInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Oauth_Client_IdInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_oauth_client_id(inputs)
|
||||
return zh_mcp_oauth_client_id(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Client Secret" |
|
||||
*
|
||||
* @param {Mcp_Oauth_Client_SecretInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_oauth_client_secret: ((inputs?: Mcp_Oauth_Client_SecretInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Oauth_Client_SecretInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Oauth_Client_SecretInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Oauth_Client_SecretInputs */
|
||||
|
||||
const en_mcp_oauth_client_secret = /** @type {(inputs: Mcp_Oauth_Client_SecretInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Client Secret`)
|
||||
};
|
||||
|
||||
const zh_mcp_oauth_client_secret = /** @type {(inputs: Mcp_Oauth_Client_SecretInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Client Secret`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Client Secret" |
|
||||
*
|
||||
* @param {Mcp_Oauth_Client_SecretInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_oauth_client_secret = /** @type {((inputs?: Mcp_Oauth_Client_SecretInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Oauth_Client_SecretInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_oauth_client_secret(inputs)
|
||||
return zh_mcp_oauth_client_secret(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Grant Type" |
|
||||
*
|
||||
* @param {Mcp_Oauth_Grant_TypeInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_oauth_grant_type: ((inputs?: Mcp_Oauth_Grant_TypeInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Oauth_Grant_TypeInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Oauth_Grant_TypeInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Oauth_Grant_TypeInputs */
|
||||
|
||||
const en_mcp_oauth_grant_type = /** @type {(inputs: Mcp_Oauth_Grant_TypeInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Grant Type`)
|
||||
};
|
||||
|
||||
const zh_mcp_oauth_grant_type = /** @type {(inputs: Mcp_Oauth_Grant_TypeInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`授权模式 (Grant Type)`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Grant Type" |
|
||||
*
|
||||
* @param {Mcp_Oauth_Grant_TypeInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_oauth_grant_type = /** @type {((inputs?: Mcp_Oauth_Grant_TypeInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Oauth_Grant_TypeInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_oauth_grant_type(inputs)
|
||||
return zh_mcp_oauth_grant_type(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Scope" |
|
||||
*
|
||||
* @param {Mcp_Oauth_ScopeInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_oauth_scope: ((inputs?: Mcp_Oauth_ScopeInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Oauth_ScopeInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Mcp_Oauth_ScopeInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Mcp_Oauth_ScopeInputs */
|
||||
|
||||
const en_mcp_oauth_scope = /** @type {(inputs: Mcp_Oauth_ScopeInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Scope`)
|
||||
};
|
||||
|
||||
const zh_mcp_oauth_scope = /** @type {(inputs: Mcp_Oauth_ScopeInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`作用域 (Scope)`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Scope" |
|
||||
*
|
||||
* @param {Mcp_Oauth_ScopeInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const mcp_oauth_scope = /** @type {((inputs?: Mcp_Oauth_ScopeInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Oauth_ScopeInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_mcp_oauth_scope(inputs)
|
||||
return zh_mcp_oauth_scope(inputs)
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user