* 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.
32 KiB
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):
- User sends chat →
chatService.startOrContinueChatcreates aWorkflowTask(typechat). agentChatworkflow →agentChatActivity→executeAgentPrompt→createAgentSession(...)(inpackages/agent/src/index.ts).createAgentSessionbuildsAgentTool[](TypeBoxparameters+execute(toolCallId, params)), registers them onAgentHarness, and callsharness.prompt(). The harness validates args viavalidateToolArguments(pi-ai) which works with plain JSON Schema objects (falls back tocoerceWithJsonSchemawhen the TypeBoxKindsymbol is absent), and passestool.parametersstraight to provider APIs (parametersJsonSchemafor Gemini /parametersfor 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
mcpproxy tool is registered with Pi (only one tool in the LLM context), which multiplexes all servers via aserverparameter that disambiguates tool calls (mcp({ tool, server, args, connect, search, describe, ... })); (2) opt-indirectTools: 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-indirectTools), with one simplification: shumai'sdirectToolsis boolean-only — tool selection is always viaincludeTools/excludeToolsfilters (Q6). server-manager.ts:McpServerManagerwrapsClientfrom@modelcontextprotocol/client, connects viaStdioClientTransport/StreamableHTTPClientTransport/SSEClientTransport, discovers tools/resources/prompts, executesclient.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/removeAuthusing SDKauth()+ local callback server.proxy-modes.tsexecuteCall: 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 AgentTools (e.g. xcodebuild_list_sims); which tools become direct is always controlled by includeTools/excludeToolsfilters — **nostring[]` form** (Q6). |
| 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):
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")onTeam(inside the relation block),mcpServers AgentMcpServer[]onAgent, andagentMcpServers AgentMcpServer[]onMcpServer. Mirror the exactAgentSkillblock style (seepackages/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-adaptermcp-auth.tsshapes). -
Note:
Agent.idis not refactored — it keeps doubling as the agent'sUser.idtoday.AgentMcpServer.agentIdsimply references the existingAgent.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 optionalrefreshToolsflag)UpdateMcpServerPermissionRequest(permission: 'owner' | 'editor' | 'reviewer') for the dedicatedPATCH /mcp/servers/:id/permission(mirrorsupdateSkillPermissionRequestSchema)McpServerInfo(id, name, url, transport, authType, enabled, permission, status, lastError, toolCount, hasCredential, createdAt/updatedAt) — never returns tokens/secretsMcpToolInfo(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= configuredredirectUrior${MCP_OAUTH_REDIRECT_BASE_URL}/api/mcp/oauth/callback.- Flow state (PKCE verifier, discovery state, authorization URL,
state) persisted topendingAuthin 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)— createsClient+StreamableHTTPClientTransport(fallback to SSE on 404/405/406/415) or pinnedSSEClientTransport; passesauthProvider(the OAuth provider above) or static bearer header;client.connect().- Handles
UnauthorizedError/401 → statusneeds_auth. listTools(paginated),callTool(name, args),close(name),closeAll(), single-flight connect dedup, per-server status tracking.- Uses
versionNegotiationfrom@modelcontextprotocol/client(default auto/legacy per config).
5d. mcp-tool-schema.ts — JSON Schema → AgentTool parameters
- Normalize MCP
inputSchema: ensuretype: 'object'; strip unsupported keywords ($schema,additionalPropertieshandling); pass through asTSchema(the harness accepts plain JSON Schema via pi-ai's coercion path, and providers get valid JSON Schema). - Validate compile-ability with
typebox/compileCompile; on failure fall back toType.Record(Type.String(), Type.Unknown())so the tool still works (args passed through tocallTool). - 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-adapterToolMetadata). Loaded lazily from the DB cache (McpServer.tools) and refreshed onconnect/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-adaptersearch-ranking.ts(normalizeSearchTextcamelCase/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?). Theparametersschema 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 serverinstructions, and usage examples. Rebuilt when metadata changes (per session; diffed to preserve prompt cache where possible). executedispatches 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-startonly (noauth-complete— the API callback completes OAuth server-side, so the model never has a redirect URL to paste; it pollsstatusinstead).
5g. direct tools — per-server opt-in
resolveDirectTools(config): whenconfig.directTools === true, that server's allowed tools (afterincludeTools/excludeTools) become directAgentTools.directToolsis boolean-only (Q6) — tool selection is always via the include/exclude filters, never astring[].- Prefixed names via
formatToolName(pi-mcp-adapter "server" prefix mode:{serverName}_{toolName}; dots sanitized to_) (Q7);parametersfrommcp-tool-schema.ts;execute→ samecallMcpToolpath as the proxy. - These tools are registered alongside the
mcpproxy 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 toMcpServer.tools, updatestatus/lastError/lastConnectedAt, refresh the in-process registry. Used byrefreshToolsAPI + lazy refresh on connect. - OAuth:
startAuth(serverId)→SDK auth()flow: discovery + (dynamic) client registration → capture authorization URL viaredirectToAuthorization→ persistpendingAuth→ return URL. (Forclient_credentials, exchange directly, store tokens.)completeAuth(serverId, { code, iss })→ validate pending flow (statechecked at callback), run SDKauth({ authorizationCode, iss, ... })→ tokens saved to DB → clear pendingAuth.handleOAuthCallback(code, state, iss)— used by the API callback route (validates state, delegates tocompleteAuth).getAuthStatus(serverId),removeAuth(serverId).
- Agent integration:
buildAgentTools(agentId, teamId, userId?): Promise<AgentTool[]>— reads the agent's assigned MCP servers via theAgentMcpServerjoin (onlyenabledones), 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: firstexecuteensures connect;needs_auth→ instructive error text; failures return error text + recordlastError(non-fatal to chat). callMcpTool(serverId, toolName, args, ctx?: { teamId; userId? })— permission gate first (D10): resolve the requesting user's team role and compare againstMcpServer.permissionusing theROLE_HIERARCHYpattern frompackages/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 tostructuredContentJSON whencontentis empty.- In-memory manager cache per process (
Map<serverId, McpServerManager>), withserverIdas 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) → newResourceType.McpServer+Permission.Admin, with aresolveContextcase added inpackages/core/src/authz/authz.ts(look upteamIdfrom the server record, likeResourceType.Skill). - Audit logging via
auditLogService.logActionwith newAuditActionentries (mcp_server_create/update/delete). - Responses always mask secrets.
7. Agent integration (packages/agent)
getAgentChatContextActivity(and the autofill variant) fetch the agent's assignedMcpServerrecords (viaAgentMcpServer, onlyenabled, + cached tools +directToolsconfig) and addmcpServerstoAgentExecutionContext.agentService.createAgent/updateAgentpersistmcpServerIds(mirrorsskills).- In
executeAgentPrompt, after buildingcustomToolsfromparams.tools, callmcpService.buildAgentTools(agentId, teamId, userId)and append → returns the singlemcpproxy tool plus direct tools for opted-in assigned servers (D3/D6). (Autofill agents keepdisableToolssemantics; MCP tools only go to chat agents by default.) - 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. callMcpToolhandles "tool not found / needs auth / server down" with clear text + "did you mean" suggestions so the model can recover. Aneeds_authresult surfaces a hint (e.g. "Ask the admin to connect MCP server X in Settings → MCP").- Permission enforcement (D10): the gate lives inside
callMcpTool(shared by proxy + direct tools), so no per-agent config is needed. Proxysearch/describe/statusstay 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 asread_skill).
8. Environment config
MCP_OAUTH_REDIRECT_BASE_URL(optional) — the OAuth redirect base.redirectUridefaults to${MCP_OAUTH_REDIRECT_BASE_URL}/api/mcp/oauth/callback, andMCP_OAUTH_REDIRECT_BASE_URLitself defaults toBETTER_AUTH_URL. Document in README /.envsamples.
9. Testing strategy (AGENTS.md mandates)
- 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 andtokens()returns stored values (adapt pi-mcp-adapter'smcp-oauth-provider.test.ts). - Tool schema conversion unit tests.
- Server CRUD +
discoverToolsagainst a real in-process MCP test server: implement a tiny MCP server in the test using@modelcontextprotocol/coreServer+StreamableHTTPon an ephemeral port (add@modelcontextprotocol/coreas a devDependency); assert tools listed,callMcpToolround-trip, bearer auth header received, and 401 →needs_auth. - Proxy tool tests: search ranking (
searchToolsscoring/coverage gate, camelCase/snake-case queries),describe/listoutput, call resolution withserverdisambiguation across two servers exposing same-named tools, error suggestions. - Direct tools tests:
directTools: true(boolean) +includeTools/excludeToolsselection, prefixed naming ({server}_{tool}), and that direct tools + proxy coexist. - Per-agent assignment tests (
AgentMcpServerjoin): agent with no assignment →buildAgentToolsreturns[]; 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 (mirrorread-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.
- API tests (
packages/api/src/mcp.test.ts): mockmcpService(vi.mock), verify routes, authz, input validation, audit logging, and that the callback route validates state. - Workflow E2E (
packages/e2e/workflow/mcp.test.ts, both local + temporal executors): start the in-process MCP test server, seed team + McpServer, runagent_chattask withAgentHarness.prototype.promptmocked to return a tool call to themcpproxy 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 pathcreateAgentSession → mcpService.buildAgentTools → proxy/direct tool execute → callMcpTool → MCP server.
10. Out of scope (this task)
- WebUI frontend (noted API contract is ready;
mcp.tsDTOs + 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):
- DB: add
McpServer(incl.permission TeamMemberRole @default(reviewer))/AgentMcpServer/McpServerCredentialmodels +Team/Agentrelations topackages/db/prisma/schema.prisma; addMcpServerAuthConfig,McpServerConfig,McpToolInfo,McpStoredTokens,McpStoredClientInfo,McpPendingAuthtopackages/db/src/prisma-json-types.ts(globalPrismaJsonnamespace); generate client (bun --bun run prisma generate) + migration (bun --bun run prisma migrate dev --name add_mcp_servers; never hand-write DDL). - DTOs:
packages/dtos/src/mcp.ts(schemas per §4,zod), export frompackages/dtos/src/index.ts; addmcpServerIds?topackages/dtos/src/agent.tsCreateAgentParams/UpdateAgentParams+ responses. - 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/clienttopackages/core/package.jsonviabun add @modelcontextprotocol/client --filter @shumai/core. - Agent service: persist
mcpServerIdsinpackages/core/src/agent/agent.tscreateAgent/updateAgent(mirrorskillshandling, including thedeleteMany+createManypattern for the join table). - API:
packages/api/src/mcp.ts(routes per §6, Hono chaining +zValidator), mount inpackages/api/src/index.ts(public OAuth callback route must be mounted beforeauthMiddleware, alongsideauthnRoute/publicInviteRoute), addAuditActionentries, addResourceType.McpServertoauthz.tsresolveContext, mask secrets in responses. - Agent integration:
AgentExecutionContextgainsmcpServersinpackages/agent/src/activities/agent.ts(fetch via join);executeAgentPromptcallsmcpService.buildAgentTools(agentId, teamId, userId)and appends to customTools (packages/agent/src/index.tscreateAgentSessioncall site); permission gate lands insidecallMcpTool(D10). - Tests: core unit tests (incl. permission gating, rename-invalidation, tool-schema conversion) + in-process MCP test server (
@modelcontextprotocol/coredevDependency), API tests (vi.mockmcpService), workflow E2E (packages/e2e/workflow/mcp.test.ts, both proxy + direct modes, incl. a permission-denied case); updateapps/web/e2e/README.mdonly if web specs change (they don't — webui out of scope). - 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.