feat(mcp): support tool-level directTools array and 3-state UI configuration (#297)

* feat(mcp): support tool-level directTools array and 3-state UI configuration

* refactor(mcp): refine tool hint explanation and separate server instructions block

* style(mcp): display tool count in header title and split option hints into 3 lines

* style(mcp): update tools description paragraph and place bulk buttons on a separate row

* fix(mcp): enforce excludeTools in proxy path and align direct-tool counts

- Filter the per-agent tool registry by excludeTools at build time (DB cache
  and lazy-connect paths), so excluded tools are unreachable through the mcp
  proxy (call, search, list, describe) — matching pi-mcp-adapter where
  isToolAllowed gates both direct and gateway exposure.
- Add shared isDirectTool predicate (matches original or prefixed name) used
  by both buildDirectTools and the proxy description counts, so the
  advertised direct/proxy counts can no longer drift from actual
  registration; toolCount now reflects allowed tools only.
- Remove the legacy boolean directTools branch (no legacy data exists).
- Drop the now-unused mcp_excluded_tools_hint i18n key and regenerate
  Paraglide messages.
- Extend unit tests: excluded tools are not counted, listed, searched, or
  callable via the proxy; prefixed-name directTools configs count correctly.
This commit is contained in:
Yiling-J
2026-08-11 15:43:27 +08:00
committed by GitHub
parent 82aee9a291
commit 851ae49c84
33 changed files with 661 additions and 587 deletions
-297
View File
@@ -1,297 +0,0 @@
# 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.
+22 -35
View File
@@ -1,16 +1,18 @@
/**
* 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.
* When a server's config sets `directTools` to an array of tool names, its
* allowed tools (matching the original or `{server}_{tool}` prefixed name,
* 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 tools 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 { isToolAllowed } from './mcp-tool-registry'
import { toToolParameters } from './mcp-tool-schema'
export interface DirectToolCallOptions {
@@ -26,37 +28,19 @@ export interface DirectToolCallOptions {
}>
}
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,
/**
* Decide whether a tool is exposed as a native direct tool. Matches the
* original MCP name or the `{server}_{tool}` prefixed name against the
* configured directTools array. Shared by direct registration and the proxy
* description counts so the two can never drift apart.
*/
export function isDirectTool(
originalName: string,
config?: PrismaJson.McpServerConfig,
prefixedName: string,
directTools?: string[],
): boolean {
const exclude = config?.excludeTools
if (matchesToolPattern(prefixedName, exclude) || matchesToolPattern(originalName, exclude)) {
return false
}
return true
if (!Array.isArray(directTools)) return false
return directTools.includes(originalName) || directTools.includes(prefixedName)
}
/**
@@ -68,11 +52,14 @@ export function buildDirectTools(
config: PrismaJson.McpServerConfig | undefined,
opts: DirectToolCallOptions,
): AgentTool[] {
if (config?.directTools !== true) return []
const directTools = config?.directTools
if (!Array.isArray(directTools) || directTools.length === 0) return []
const tools: AgentTool[] = []
for (const tool of metadata) {
if (!isToolAllowed(tool.name, tool.originalName, config)) continue
if (!isToolAllowed(tool.name, tool.originalName, config?.excludeTools)) continue
if (!isDirectTool(tool.originalName, tool.name, directTools)) continue
const parameters = toToolParameters(tool.inputSchema)
tools.push({
name: tool.name,
+25 -1
View File
@@ -34,6 +34,7 @@ export interface ProxyServerInfo {
id: string
name: string
toolCount: number
directToolCount?: number
status: string
/** Self-reported server usage instructions (empty when the server provides none). */
instructions?: string
@@ -239,13 +240,36 @@ function notFoundResult(
export function buildProxyDescription(servers: ProxyServerInfo[]): string {
const lines: string[] = []
lines.push('Call MCP (Model Context Protocol) tools exposed by the configured servers.')
const directSummaries: string[] = []
for (const s of servers) {
const directCount = s.directToolCount ?? 0
if (directCount > 0) {
directSummaries.push(`${s.name} (${directCount})`)
}
}
if (directSummaries.length > 0) {
lines.push('')
lines.push(`Direct tools available (call as normal tools): ${directSummaries.join(', ')}`)
}
lines.push('')
lines.push('Servers:')
if (servers.length === 0) {
lines.push(' (none assigned)')
} else {
let listedServerCount = 0
for (const s of servers) {
lines.push(` - ${s.name} (${s.toolCount} tools, status: ${s.status})`)
const directCount = s.directToolCount ?? 0
const proxyCount = Math.max(0, s.toolCount - directCount)
if (proxyCount > 0 || directCount === 0) {
lines.push(` - ${s.name} (${proxyCount} tools, status: ${s.status})`)
listedServerCount++
}
}
if (listedServerCount === 0) {
lines.push(' (all assigned tools are configured as direct tools)')
}
}
lines.push('')
+59 -7
View File
@@ -683,11 +683,11 @@ describe('McpService', () => {
try {
const assigned = await service.createServer(teamId, {
url: assignedSrv.url,
config: { directTools: true },
config: { directTools: ['tavily_search'] },
})
const unassigned = await service.createServer(teamId, {
url: unassignedSrv.url,
config: { directTools: true },
config: { directTools: ['search_records'] },
})
await service.refreshServer(assigned.id)
await service.refreshServer(unassigned.id)
@@ -711,17 +711,25 @@ describe('McpService', () => {
const agent = await seedAgentAndUser(teamId, 'Direct Agent')
const server = await service.createServer(teamId, {
url: srv.url,
config: { directTools: true },
config: { directTools: ['echo', '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)
expect(tools.length).toBe(4) // proxy + 3 direct tools
expect(tools.length).toBe(3) // proxy + 2 direct tools ('echo', 'add')
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')
expect(names).not.toContain('test_mcp_server_list_sims') // kept as proxy tool only
// Dynamic proxy description shows direct summary and remaining proxy count.
const proxy = tools.find((t) => t.name === 'mcp')!
expect(proxy.description).toContain(
'Direct tools available (call as normal tools): test-mcp-server (2)',
)
expect(proxy.description).toContain('test-mcp-server (1 tools, status:')
// Direct tool executes through callMcpTool.
const echo = tools.find((t) => t.name === 'test_mcp_server_echo')!
@@ -734,11 +742,11 @@ describe('McpService', () => {
expect(JSON.stringify(result.content)).toContain('echo:direct')
})
it('applies excludeTools filters to direct tools', async () => {
it('applies excludeTools filters to direct tools and the proxy', async () => {
const agent = await seedAgentAndUser(teamId, 'Filtered Agent')
const server = await service.createServer(teamId, {
url: srv.url,
config: { directTools: true, excludeTools: ['add'] },
config: { directTools: ['echo', 'add'], excludeTools: ['add'] },
})
await service.refreshServer(server.id)
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
@@ -746,8 +754,52 @@ describe('McpService', () => {
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')
// The excluded tool is also unreachable through the proxy: it is not
// counted, listed, searched, or callable.
const proxy = tools.find((t) => t.name === 'mcp')!
expect(proxy.description).toContain(
'Direct tools available (call as normal tools): test-mcp-server (1)',
)
expect(proxy.description).toContain('test-mcp-server (1 tools, status:')
const list = await (proxy.execute as ProxyExecute)('excl-list-1', {
server: 'test-mcp-server',
})
expect(JSON.stringify(list.content)).not.toContain('test_mcp_server_add')
const search = await (proxy.execute as ProxyExecute)('excl-search-1', { search: 'add' })
expect(JSON.stringify(search.content)).not.toContain('test_mcp_server_add')
const call = await (proxy.execute as ProxyExecute)('excl-call-1', {
server: 'test-mcp-server',
tool: 'add',
args: { a: 1, b: 2 },
})
expect(JSON.stringify(call.content)).toContain('not found')
})
it('matches directTools by prefixed name in the proxy description counts', async () => {
const agent = await seedAgentAndUser(teamId, 'Prefixed Direct Agent')
const server = await service.createServer(teamId, {
url: srv.url,
config: { directTools: ['test_mcp_server_echo'] },
})
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).not.toContain('test_mcp_server_add')
expect(names).not.toContain('test_mcp_server_list_sims')
const proxy = tools.find((t) => t.name === 'mcp')!
expect(proxy.description).toContain(
'Direct tools available (call as normal tools): test-mcp-server (1)',
)
expect(proxy.description).toContain('test-mcp-server (2 tools, status:')
})
// --------------------------------------------------------------------------
+18 -5
View File
@@ -14,7 +14,7 @@ import type {
} 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 { buildDirectTools, isDirectTool } from './mcp-direct-tools'
import { McpOauthProvider, type McpOauthConfig } from './mcp-oauth-provider'
import { buildProxyTool, transformMcpContent, type McpProxyToolContext } from './mcp-proxy-tool'
import {
@@ -427,7 +427,9 @@ export class McpService {
const tools = this.toStoredTools(connection.tools)
const metadata = this.serverMetadata(server, connection)
const displayName = metadata.name ?? server.name
registry?.setTools(serverId, displayName, connection.tools)
registry?.setTools(serverId, displayName, connection.tools, {
excludeTools: server.config?.excludeTools,
})
await this.updateStatus(serverId, 'connected', null, {
tools,
lastConnectedAt: new Date(),
@@ -816,6 +818,7 @@ export class McpService {
description: t.description ?? '',
...(t.inputSchema !== undefined ? { inputSchema: t.inputSchema } : {}),
})),
{ excludeTools: s.config?.excludeTools },
)
}
return {
@@ -826,7 +829,6 @@ export class McpService {
transport: s.transport,
authConfig: (s.authConfig ?? {}) as PrismaJson.McpServerAuthConfig,
config: (s.config ?? {}) as PrismaJson.McpServerConfig,
tools: storedTools,
status: s.status,
}
})
@@ -836,10 +838,19 @@ export class McpService {
const proxyServers = servers.map((s) => {
serverNameById.set(s.id, s.name)
serverIdByName.set(s.name, s.id)
// Count direct tools from the same filtered registry metadata that
// buildDirectTools consumes, so the proxy description can never drift
// from what is actually registered as native tools.
const metadata = registry.getTools(s.id)
const directToolCount = metadata.filter((t) =>
isDirectTool(t.originalName, t.name, s.config?.directTools),
).length
return {
id: s.id,
name: s.name,
toolCount: s.tools.length,
toolCount: metadata.length,
directToolCount,
status: s.status,
...(s.instructions !== null && s.instructions !== undefined
? { instructions: s.instructions }
@@ -878,7 +889,9 @@ export class McpService {
const tools: AgentTool[] = [buildProxyTool(ctx)]
for (const server of servers) {
if (server.config?.directTools !== true) continue
if (!Array.isArray(server.config?.directTools) || server.config.directTools.length === 0) {
continue
}
const metadata: ToolMetadata[] = registry.getTools(server.id)
tools.push(
...buildDirectTools(metadata, server.config, {
+60 -8
View File
@@ -35,6 +35,45 @@ export function formatToolName(serverName: string, toolName: string): string {
return serverPart ? `${serverPart}_${sanitized}` : sanitized
}
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). Applied when building the per-agent registry so excluded
* tools are invisible to both the proxy tool and direct registration.
*/
export function isToolAllowed(
prefixedName: string,
originalName: string,
excludeTools?: string[],
): boolean {
if (
matchesToolPattern(prefixedName, excludeTools) ||
matchesToolPattern(originalName, excludeTools)
) {
return false
}
return true
}
const MIN_STEM_LENGTH = 4
const FIELD_WEIGHTS = {
@@ -147,14 +186,27 @@ export function paginate<T>(
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 } : {}),
}))
/**
* Rebuild the metadata for one server from its discovered tools, skipping
* tools excluded via excludeTools so they are unreachable through the proxy.
*/
setTools(
serverId: string,
serverName: string,
tools: McpTool[],
opts?: { excludeTools?: string[] },
): void {
const metadata: ToolMetadata[] = []
for (const tool of tools) {
const name = formatToolName(serverName, tool.name)
if (!isToolAllowed(name, tool.name, opts?.excludeTools)) continue
metadata.push({
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)
}
+1 -1
View File
@@ -388,7 +388,7 @@ declare global {
idleTimeoutMs?: number
keepAlive?: boolean
protocolVersion?: 'legacy' | 'auto' | '2026-07-28'
directTools?: boolean
directTools?: string[]
}
export interface McpToolInfo {
+1 -1
View File
@@ -36,7 +36,7 @@ export const mcpServerConfigSchema = z.object({
idleTimeoutMs: z.number().int().positive().optional(),
keepAlive: z.boolean().optional(),
protocolVersion: z.enum(['legacy', 'auto', '2026-07-28']).optional(),
directTools: z.boolean().optional(),
directTools: z.array(z.string()).optional(),
})
export type McpServerConfig = z.infer<typeof mcpServerConfigSchema>
+1 -1
View File
@@ -259,7 +259,7 @@ describe.each(['local', 'temporal'] as const)('Workflow E2E - MCP tools (executo
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 })
await createMcpServerAndAssign(team.id, agentUser.id, { directTools: ['echo'] })
// For direct mode the model would call `e2e_mcp_echo` directly; simulate
// that by executing the direct tool on the harness.
@@ -7,7 +7,6 @@ import {
MoreVertical,
Plus,
Trash2,
Zap,
ShieldCheck,
CheckCircle2,
AlertCircle,
@@ -273,7 +272,6 @@ export const McpConfigCard: React.FC<McpConfigCardProps> = ({ teamId }) => {
) : (
<div className="space-y-4">
{servers.map((server) => {
const isDirectMode = server.config?.directTools
const isAuthenticating = authenticatingServerId === server.id
const needsAuth =
server.status === 'needs_auth' ||
@@ -292,15 +290,6 @@ export const McpConfigCard: React.FC<McpConfigCardProps> = ({ teamId }) => {
<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>
@@ -12,7 +12,7 @@ import {
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 { ToggleGroup, ToggleGroupItem } from '@/ui/components/ui/toggle-group'
import { Badge } from '@/ui/components/ui/badge'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import {
@@ -66,7 +66,7 @@ export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
)
// Config state
const [directTools, setDirectTools] = useState(false)
const [directTools, setDirectTools] = useState<string[]>([])
const [excludedTools, setExcludedTools] = useState<string[]>([])
// Tools inspector state
@@ -79,7 +79,7 @@ export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
setTransport(server.transport || 'streamable_http')
setPermission(server.permission || 'reviewer')
setAuthType(server.authType || 'auto')
setDirectTools(server.config?.directTools ?? false)
setDirectTools(Array.isArray(server.config?.directTools) ? server.config.directTools : [])
setExcludedTools(server.config?.excludeTools ?? [])
setExpandedTools({})
setIsInstructionsExpanded(false)
@@ -93,7 +93,7 @@ export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
setClientSecret('')
setScope('')
setGrantType('authorization_code')
setDirectTools(false)
setDirectTools([])
setExcludedTools([])
setExpandedTools({})
setIsInstructionsExpanded(false)
@@ -166,7 +166,7 @@ export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
const saveMutation = useMutation({
mutationFn: async () => {
const config = {
directTools,
directTools: directTools.length > 0 ? directTools : undefined,
excludeTools: excludedTools.length > 0 ? excludedTools : undefined,
}
@@ -222,10 +222,37 @@ export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
const tools = toolsData?.tools ?? []
const isToolExcluded = (toolName: string) => excludedTools.includes(toolName)
const getToolState = (toolName: string): 'off' | 'on' | 'direct' => {
if (excludedTools.includes(toolName)) return 'off'
if (directTools.includes(toolName)) return 'direct'
return 'on'
}
const toggleToolEnabled = (toolName: string, enabled: boolean) => {
setExcludedTools((prev) => (enabled ? prev.filter((n) => n !== toolName) : [...prev, toolName]))
const setToolState = (toolName: string, state: 'off' | 'on' | 'direct') => {
if (state === 'off') {
setExcludedTools((prev) => (prev.includes(toolName) ? prev : [...prev, toolName]))
setDirectTools((prev) => prev.filter((n) => n !== toolName))
} else if (state === 'on') {
setExcludedTools((prev) => prev.filter((n) => n !== toolName))
setDirectTools((prev) => prev.filter((n) => n !== toolName))
} else if (state === 'direct') {
setExcludedTools((prev) => prev.filter((n) => n !== toolName))
setDirectTools((prev) => (prev.includes(toolName) ? prev : [...prev, toolName]))
}
}
const handleBulkSetState = (state: 'off' | 'on' | 'direct') => {
const allToolNames = tools.map((t) => t.name)
if (state === 'off') {
setExcludedTools(allToolNames)
setDirectTools([])
} else if (state === 'on') {
setExcludedTools([])
setDirectTools([])
} else if (state === 'direct') {
setExcludedTools([])
setDirectTools(allToolNames)
}
}
const toggleExpand = (toolName: string) => {
@@ -286,52 +313,54 @@ export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
<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>
{server.instructions && (
<div className="p-3 bg-muted/20 border border-border rounded-lg space-y-1">
<span className="text-[10px] uppercase tracking-wider text-muted-foreground font-semibold block">
{m.mcp_server_instructions()}
</span>
<p
onClick={() => setIsInstructionsExpanded((prev) => !prev)}
className={`text-xs text-muted-foreground whitespace-pre-wrap leading-relaxed cursor-pointer transition-all ${
isInstructionsExpanded ? '' : 'line-clamp-2'
}`}
title={isInstructionsExpanded ? undefined : 'Click to expand instructions'}
>
{server.instructions}
</p>
</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>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-3 border-t border-border">
<div className="space-y-1.5">
<Label className="text-xs">{m.mcp_transport()}</Label>
<Select
value={transport}
onValueChange={(val) => setTransport(val as McpTransport)}
onValueChange={(val: McpTransport) => setTransport(val)}
>
<SelectTrigger>
<SelectTrigger className="h-9 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="streamable_http">Streamable HTTP (Default)</SelectItem>
<SelectItem value="streamable_http">Streamable HTTP</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>
<div className="space-y-1.5">
<Label className="text-xs">{m.skill_permission()}</Label>
<Select
value={permission}
onValueChange={(val) => setPermission(val as McpServerPermission)}
onValueChange={(val: McpServerPermission) => setPermission(val)}
>
<SelectTrigger>
<SelectTrigger className="h-9 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -343,51 +372,48 @@ export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
</div>
</div>
{/* Authentication Section */}
{/* Authentication Configuration */}
<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>
<div className="space-y-1.5">
<Label className="text-xs">{m.mcp_auth_type()}</Label>
<Select
value={authType}
onValueChange={(val: McpServerAuthType | 'auto') => setAuthType(val)}
>
<SelectTrigger className="h-9 text-xs">
<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>
</div>
{authType === 'bearer' && (
<div className="space-y-2 pl-1 pt-1">
<div className="space-y-1.5">
<Label className="text-xs">{m.mcp_bearer_token()}</Label>
<Input
className="h-9 text-xs font-mono"
type="password"
value={bearerToken}
onChange={(e) => setBearerToken(e.target.value)}
placeholder="Bearer token value"
placeholder="Enter token string"
/>
</div>
)}
{authType === 'oauth' && (
<div className="space-y-3 pl-1 pt-1 border-l-2 border-primary/20 pl-3">
<div className="p-3 bg-muted/20 border border-border rounded-lg space-y-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')
onValueChange={(val: 'authorization_code' | 'client_credentials') =>
setGrantType(val)
}
>
<SelectTrigger className="h-9 text-xs">
@@ -399,14 +425,13 @@ export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
</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"
placeholder="Optional Client ID"
/>
</div>
</div>
@@ -419,17 +444,16 @@ export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
type="password"
value={clientSecret}
onChange={(e) => setClientSecret(e.target.value)}
placeholder="Optional Client Secret"
placeholder="Optional 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)"
placeholder="Optional scope"
/>
</div>
</div>
@@ -437,32 +461,53 @@ export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
)}
</div>
{/* Mode */}
{/* Tools list */}
<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">
<div className="space-y-2.5">
<Label className="text-xs font-semibold flex items-center gap-1.5">
<Wrench className="w-3.5 h-3.5" />
{m.mcp_tools()}
{m.mcp_tools()} ({tools.length})
</Label>
<p className="text-[11px] text-muted-foreground leading-relaxed">
{m.mcp_tools_desc()}
</p>
{tools.length > 0 && (
<div className="flex items-center gap-1.5 pt-0.5">
<Button
type="button"
variant="outline"
size="sm"
className="h-7 text-[11px] px-2.5"
onClick={() => handleBulkSetState('off')}
disabled={refreshMutation.isPending || isToolsLoading}
>
{m.mcp_bulk_all_off()}
</Button>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 text-[11px] px-2.5"
onClick={() => handleBulkSetState('on')}
disabled={refreshMutation.isPending || isToolsLoading}
>
{m.mcp_bulk_all_proxy()}
</Button>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 text-[11px] px-2.5"
onClick={() => handleBulkSetState('direct')}
disabled={refreshMutation.isPending || isToolsLoading}
>
{m.mcp_bulk_all_direct()}
</Button>
</div>
)}
</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 ? (
@@ -475,7 +520,7 @@ export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
</div>
) : (
tools.map((tool) => {
const enabled = !isToolExcluded(tool.name)
const currentState = getToolState(tool.name)
const isExpanded = !!expandedTools[tool.name]
const schemaObj = tool.inputSchema as {
properties?: Record<string, { type?: string; description?: string }>
@@ -488,7 +533,7 @@ export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
<div
key={tool.name}
className={`border border-border rounded-lg p-3 transition-colors ${
enabled ? 'bg-card' : 'bg-muted/30 opacity-70'
currentState !== 'off' ? 'bg-card' : 'bg-muted/30 opacity-70'
}`}
>
<div className="flex items-start justify-between gap-3">
@@ -525,13 +570,26 @@ export const McpServerFormDialog: React.FC<McpServerFormDialogProps> = ({
</div>
<div className="flex items-center gap-2 shrink-0">
<Switch
checked={enabled}
<ToggleGroup
type="single"
value={currentState}
onValueChange={(val) => {
if (val) setToolState(tool.name, val as 'off' | 'on' | 'direct')
}}
size="sm"
variant="outline"
disabled={refreshMutation.isPending || isToolsLoading}
onCheckedChange={(checked) =>
toggleToolEnabled(tool.name, checked)
}
/>
>
<ToggleGroupItem value="off" className="text-[11px] px-2 h-7">
{m.mcp_tool_state_disabled()}
</ToggleGroupItem>
<ToggleGroupItem value="on" className="text-[11px] px-2 h-7">
{m.mcp_tool_state_proxy()}
</ToggleGroupItem>
<ToggleGroupItem value="direct" className="text-[11px] px-2 h-7">
{m.mcp_tool_state_direct()}
</ToggleGroupItem>
</ToggleGroup>
</div>
</div>
+7 -3
View File
@@ -374,8 +374,6 @@
"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",
@@ -395,7 +393,13 @@
"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.",
"mcp_tool_state_disabled": "Off",
"mcp_tool_state_proxy": "Proxy",
"mcp_tool_state_direct": "Direct",
"mcp_tools_desc": "Configure how MCP tools are exposed to the agent. Proxy mode keeps context usage low by hiding tools behind an MCP proxy, while Direct mode exposes selected tools as native agent tools for better discovery and faster access. Use Direct mode for frequently used or critical tools, and keep large MCP servers behind the proxy to avoid unnecessary context overhead.",
"mcp_bulk_all_off": "All Off",
"mcp_bulk_all_proxy": "All Proxy",
"mcp_bulk_all_direct": "All Direct",
"view_tools": "View Tools",
"tool_parameters": "Parameters",
"no_tools_found": "No tools found matching your search.",
+7 -3
View File
@@ -374,8 +374,6 @@
"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": "已连接",
@@ -395,7 +393,13 @@
"add_mcp_server_to_get_started": "添加 MCP 服务以扩展 AI Agent 的工具能力。",
"search_tools_placeholder": "按名称或描述搜索工具...",
"mcp_server_auto_detected": "连接后将自动从服务端获取名称和描述。",
"mcp_excluded_tools_hint": "关闭某个工具会将其从该服务的工具集中排除。",
"mcp_tool_state_disabled": "关闭",
"mcp_tool_state_proxy": "代理",
"mcp_tool_state_direct": "直连",
"mcp_tools_desc": "配置 MCP 工具向 Agent 的暴露方式。代理模式通过 MCP 代理隐匿工具,以保持较低的上下文占用;直连模式将选定工具直接作为 Agent 原生工具暴露,便于更好地发现与更快地调用。建议对高频或关键工具使用直连模式,对于大型 MCP 服务保持代理模式以避免不必要的上下文开销。",
"mcp_bulk_all_off": "全部关闭",
"mcp_bulk_all_proxy": "全部代理",
"mcp_bulk_all_direct": "全部直连",
"view_tools": "查看工具",
"tool_parameters": "参数列表",
"no_tools_found": "未找到符合搜索条件的工具。",
+7 -3
View File
@@ -356,8 +356,6 @@ 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";
@@ -377,7 +375,13 @@ 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 "./mcp_tool_state_disabled.js";
export * from "./mcp_tool_state_proxy.js";
export * from "./mcp_tool_state_direct.js";
export * from "./mcp_tools_desc.js";
export * from "./mcp_bulk_all_off.js";
export * from "./mcp_bulk_all_proxy.js";
export * from "./mcp_bulk_all_direct.js";
export * from "./view_tools.js";
export * from "./tool_parameters.js";
export * from "./no_tools_found.js";
+7 -3
View File
@@ -358,8 +358,6 @@ 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'
@@ -379,7 +377,13 @@ 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 './mcp_tool_state_disabled.js'
export * from './mcp_tool_state_proxy.js'
export * from './mcp_tool_state_direct.js'
export * from './mcp_tools_desc.js'
export * from './mcp_bulk_all_off.js'
export * from './mcp_bulk_all_proxy.js'
export * from './mcp_bulk_all_direct.js'
export * from './view_tools.js'
export * from './tool_parameters.js'
export * from './no_tools_found.js'
@@ -1,16 +1,16 @@
/**
* | output |
* | --- |
* | "Direct Tools Mode" |
* | "All Direct" |
*
* @param {Mcp_Direct_Tools_ModeInputs} inputs
* @param {Mcp_Bulk_All_DirectInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_direct_tools_mode: ((inputs?: Mcp_Direct_Tools_ModeInputs, options?: {
export const mcp_bulk_all_direct: ((inputs?: Mcp_Bulk_All_DirectInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Direct_Tools_ModeInputs, {
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Bulk_All_DirectInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Mcp_Direct_Tools_ModeInputs = {};
export type Mcp_Bulk_All_DirectInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Mcp_Bulk_All_DirectInputs */
const en_mcp_bulk_all_direct = /** @type {(inputs: Mcp_Bulk_All_DirectInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`All Direct`)
};
const zh_mcp_bulk_all_direct = /** @type {(inputs: Mcp_Bulk_All_DirectInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`全部直连`)
};
/**
* | output |
* | --- |
* | "All Direct" |
*
* @param {Mcp_Bulk_All_DirectInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_bulk_all_direct = /** @type {((inputs?: Mcp_Bulk_All_DirectInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Bulk_All_DirectInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_mcp_bulk_all_direct(inputs)
return zh_mcp_bulk_all_direct(inputs)
});
@@ -1,16 +1,16 @@
/**
* | output |
* | --- |
* | "Disable a tool to exclude it from this server's toolset." |
* | "All Off" |
*
* @param {Mcp_Excluded_Tools_HintInputs} inputs
* @param {Mcp_Bulk_All_OffInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_excluded_tools_hint: ((inputs?: Mcp_Excluded_Tools_HintInputs, options?: {
export const mcp_bulk_all_off: ((inputs?: Mcp_Bulk_All_OffInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Excluded_Tools_HintInputs, {
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Bulk_All_OffInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Mcp_Excluded_Tools_HintInputs = {};
export type Mcp_Bulk_All_OffInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Mcp_Bulk_All_OffInputs */
const en_mcp_bulk_all_off = /** @type {(inputs: Mcp_Bulk_All_OffInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`All Off`)
};
const zh_mcp_bulk_all_off = /** @type {(inputs: Mcp_Bulk_All_OffInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`全部关闭`)
};
/**
* | output |
* | --- |
* | "All Off" |
*
* @param {Mcp_Bulk_All_OffInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_bulk_all_off = /** @type {((inputs?: Mcp_Bulk_All_OffInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Bulk_All_OffInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_mcp_bulk_all_off(inputs)
return zh_mcp_bulk_all_off(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "All Proxy" |
*
* @param {Mcp_Bulk_All_ProxyInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_bulk_all_proxy: ((inputs?: Mcp_Bulk_All_ProxyInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Bulk_All_ProxyInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Mcp_Bulk_All_ProxyInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Mcp_Bulk_All_ProxyInputs */
const en_mcp_bulk_all_proxy = /** @type {(inputs: Mcp_Bulk_All_ProxyInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`All Proxy`)
};
const zh_mcp_bulk_all_proxy = /** @type {(inputs: Mcp_Bulk_All_ProxyInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`全部代理`)
};
/**
* | output |
* | --- |
* | "All Proxy" |
*
* @param {Mcp_Bulk_All_ProxyInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_bulk_all_proxy = /** @type {((inputs?: Mcp_Bulk_All_ProxyInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Bulk_All_ProxyInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_mcp_bulk_all_proxy(inputs)
return zh_mcp_bulk_all_proxy(inputs)
});
-16
View File
@@ -1,16 +0,0 @@
/**
* | 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 = {};
@@ -1,29 +0,0 @@
/* 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)
});
@@ -1,29 +0,0 @@
/* 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)
});
@@ -1,29 +0,0 @@
/* 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
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Direct" |
*
* @param {Mcp_Tool_State_DirectInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_tool_state_direct: ((inputs?: Mcp_Tool_State_DirectInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Tool_State_DirectInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Mcp_Tool_State_DirectInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Mcp_Tool_State_DirectInputs */
const en_mcp_tool_state_direct = /** @type {(inputs: Mcp_Tool_State_DirectInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Direct`)
};
const zh_mcp_tool_state_direct = /** @type {(inputs: Mcp_Tool_State_DirectInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`直连`)
};
/**
* | output |
* | --- |
* | "Direct" |
*
* @param {Mcp_Tool_State_DirectInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_tool_state_direct = /** @type {((inputs?: Mcp_Tool_State_DirectInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Tool_State_DirectInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_mcp_tool_state_direct(inputs)
return zh_mcp_tool_state_direct(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Off" |
*
* @param {Mcp_Tool_State_DisabledInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_tool_state_disabled: ((inputs?: Mcp_Tool_State_DisabledInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Tool_State_DisabledInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Mcp_Tool_State_DisabledInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Mcp_Tool_State_DisabledInputs */
const en_mcp_tool_state_disabled = /** @type {(inputs: Mcp_Tool_State_DisabledInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Off`)
};
const zh_mcp_tool_state_disabled = /** @type {(inputs: Mcp_Tool_State_DisabledInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`关闭`)
};
/**
* | output |
* | --- |
* | "Off" |
*
* @param {Mcp_Tool_State_DisabledInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_tool_state_disabled = /** @type {((inputs?: Mcp_Tool_State_DisabledInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Tool_State_DisabledInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_mcp_tool_state_disabled(inputs)
return zh_mcp_tool_state_disabled(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Proxy" |
*
* @param {Mcp_Tool_State_ProxyInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_tool_state_proxy: ((inputs?: Mcp_Tool_State_ProxyInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Tool_State_ProxyInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Mcp_Tool_State_ProxyInputs = {};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Mcp_Tool_State_ProxyInputs */
const en_mcp_tool_state_proxy = /** @type {(inputs: Mcp_Tool_State_ProxyInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Proxy`)
};
const zh_mcp_tool_state_proxy = /** @type {(inputs: Mcp_Tool_State_ProxyInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`代理`)
};
/**
* | output |
* | --- |
* | "Proxy" |
*
* @param {Mcp_Tool_State_ProxyInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_tool_state_proxy = /** @type {((inputs?: Mcp_Tool_State_ProxyInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Tool_State_ProxyInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_mcp_tool_state_proxy(inputs)
return zh_mcp_tool_state_proxy(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Configure how MCP tools are exposed to the agent. Proxy mode keeps context usage low by hiding tools behind an MCP proxy, while Direct mode exposes selected ..." |
*
* @param {Mcp_Tools_DescInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_tools_desc: ((inputs?: Mcp_Tools_DescInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Mcp_Tools_DescInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Mcp_Tools_DescInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Mcp_Tools_DescInputs */
const en_mcp_tools_desc = /** @type {(inputs: Mcp_Tools_DescInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Configure how MCP tools are exposed to the agent. Proxy mode keeps context usage low by hiding tools behind an MCP proxy, while Direct mode exposes selected tools as native agent tools for better discovery and faster access. Use Direct mode for frequently used or critical tools, and keep large MCP servers behind the proxy to avoid unnecessary context overhead.`)
};
const zh_mcp_tools_desc = /** @type {(inputs: Mcp_Tools_DescInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`配置 MCP 工具向 Agent 的暴露方式。代理模式通过 MCP 代理隐匿工具,以保持较低的上下文占用;直连模式将选定工具直接作为 Agent 原生工具暴露,便于更好地发现与更快地调用。建议对高频或关键工具使用直连模式,对于大型 MCP 服务保持代理模式以避免不必要的上下文开销。`)
};
/**
* | output |
* | --- |
* | "Configure how MCP tools are exposed to the agent. Proxy mode keeps context usage low by hiding tools behind an MCP proxy, while Direct mode exposes selected ..." |
*
* @param {Mcp_Tools_DescInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const mcp_tools_desc = /** @type {((inputs?: Mcp_Tools_DescInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Mcp_Tools_DescInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_mcp_tools_desc(inputs)
return zh_mcp_tools_desc(inputs)
});