mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-28 20:04:26 +00:00
feat(mcp): add MCP server support with proxy tool and OAuth flow (#289)
* feat(mcp): add MCP server support with proxy tool and OAuth flow
Add URL-based MCP (Model Context Protocol) server support to the backend:
- DB: McpServer / AgentMcpServer / McpServerCredential models with
typed JSON columns (auth config, cached tools, stored OAuth tokens,
pending auth state) and a migration.
- Core (@shumai/core/src/mcp): DB-backed credential store, OAuth
client provider (authorization_code + client_credentials) with a
Hono-hosted redirect callback, connection lifecycle manager
(Streamable HTTP with SSE fallback, lazy connect, 401 -> needs_auth),
JSON Schema -> AgentTool parameter conversion, in-memory tool registry
with ranked search, the single 'mcp' proxy AgentTool (search /
describe / list / call / connect / status / auth-start), per-server
opt-in direct tools ({server}_{tool}), and McpService (CRUD,
discovery, OAuth, per-agent assignment via AgentMcpServer, and
permission gating on tool execution mirroring skills).
- Agent: chat agents receive the 'mcp' proxy tool (plus direct tools
for opted-in servers) built from their assigned, enabled servers.
- API: /teams/:teamId/mcp/servers CRUD, tools refresh/list, auth
start/complete/status/remove, test, permission, and the public
OAuth callback route; Admin authz via new ResourceType.McpServer;
audit logging.
- DTOs: zod schemas + types for servers, tools, auth, and per-agent
mcpServerIds.
- Tests: DB store, schema conversion, registry/search, service
integration against a real in-process MCP server (v2
@modelcontextprotocol/server), permission gating, rename
invalidation, direct tools, per-agent assignment, API route tests,
and workflow E2E (local + temporal) for proxy and direct modes.
* fix(mcp): persist OAuth discovery snapshot and stamp SEP-2352 issuer
The callback leg of the OAuth flow failed with
AuthorizationServerMismatchError ('discoveryState was not available on
the callback leg') because McpDbStore.savePendingAuth overwrote the
entire pendingAuth JSON column, clobbering the discoverySnapshot that
the provider's saveDiscoveryState() had stored inside it.
- McpDbStore.savePendingAuth now preserves an in-flight discovery
snapshot so the callback leg can satisfy the SEP-2352 authorization-
server issuer check.
- McpOauthProvider now round-trips the issuer stamp derived from the
discovery snapshot: saveClientInformation/saveTokens persist it,
clientInformation()/tokens() return it, and tokens() backfills a
missing stamp for pre-existing credentials (removes the
'stored OAuth credential has no issuer stamp' warning).
- Regression tests: savePendingAuth keeps the snapshot; the provider
stamps/round-trips the issuer on both legs.
* fix(mcp): backfill SEP-2352 issuer stamp on stale OAuth client info
clientInformation() returned stored client info without an issuer field
when it had been dynamically registered before the stamping fix, so the
SDK logged 'stored OAuth credential has no issuer stamp' on every read.
Now the stored branch backfills the issuer from the discovery snapshot
(persisting it) exactly like the tokens() backfill.
* feat(webui): add MCP server configuration and agent assignment UI (#290)
* feat(webui): add MCP server configuration and agent assignment UI
* fix(webui): auto-detect auth for unconfigured MCP servers and show connect button
* fix(mcp): auto-generate state in mcp-oauth-provider when missing in DB
* fix(mcp): persist OAuth discovery snapshot and stamp SEP-2352 issuer
The callback leg of the OAuth flow failed with
AuthorizationServerMismatchError ('discoveryState was not available on
the callback leg') because McpDbStore.savePendingAuth overwrote the
entire pendingAuth JSON column, clobbering the discoverySnapshot that
the provider's saveDiscoveryState() had stored inside it.
- McpDbStore.savePendingAuth now preserves an in-flight discovery
snapshot so the callback leg can satisfy the SEP-2352 authorization-
server issuer check.
- McpOauthProvider now round-trips the issuer stamp derived from the
discovery snapshot: saveClientInformation/saveTokens persist it,
clientInformation()/tokens() return it, and tokens() backfills a
missing stamp for pre-existing credentials (removes the
'stored OAuth credential has no issuer stamp' warning).
- Regression tests: savePendingAuth keeps the snapshot; the provider
stamps/round-trips the issuer on both legs.
* fix(mcp): backfill SEP-2352 issuer stamp on stale OAuth client info
clientInformation() returned stored client info without an issuer field
when it had been dynamically registered before the stamping fix, so the
SDK logged 'stored OAuth credential has no issuer stamp' on every read.
Now the stored branch backfills the issuer from the discovery snapshot
(persisting it) exactly like the tokens() backfill.
* fix(mcp): attach McpOauthProvider for auto-detected OAuth servers and discover tools on auth completion
* fix(webui): fix flex min-h-0 and max-h scrolling on MCP tools dialog
* fix(webui): set explicit flex height on McpToolsDialog for active scrolling
* feat(webui): make MCP server cards clickable to edit and widen server config dialog
* feat(mcp): agent-level server enablement and auto-detected server metadata (#291)
* feat(mcp): agent-level server enablement and auto-detected server metadata
- Remove the server-level `enabled` column from mcp_servers; enable/disable
now happens per-agent via the AgentMcpServer join table (mirrors skills).
- Drop the unique (teamId, name) constraint so duplicate server names are allowed.
- Add a `description` column, auto-filled from client.getServerVersion() on
connect; the server name is auto-filled from the reported title (fallback name)
with a URL-derived placeholder until first connect.
- Remove manual name input: the create dialog is URL-only, and the edit dialog
shows the auto-detected name/description read-only.
- Replace the include/exclude raw-text inputs with the tool list in the edit
dialog, managing only excludeTools; remove includeTools support and the
separate McpToolsDialog component.
- Sanitize server-reported names into safe direct-tool prefixes (spaces/punctuation
become underscores) and use the same sanitization in the proxy resolver.
* fix(mcp): give the edit-dialog tool list a definite height
The Shadcn ScrollArea viewport is h-full, which requires a definite height
on the root. Using max-h-64 left the viewport at auto height, so the root
clipped the list at 256px without engaging its own scrollbar — tools past
the cutoff were unreachable. Use a fixed h-64 container (same pattern as
move-copy-dialog) so the inner scroll area scrolls independently of the
dialog's outer scroll.
* refactor(mcp): fixed header/footer with scrollable content in server config dialog
Mirror the skill config dialog layout: the edit dialog now keeps the header
and footer fixed and scrolls only the content area (ScrollArea flex-1
min-h-0 inside an h-[85vh] flex column). The tools list no longer has its
own nested ScrollArea — it flows inside the content-level scroll, so all
tools are reachable without a nested-scroll conflict. The create dialog
stays compact (URL-only) like the skill add dialog.
Verified headlessly that max-height-based ScrollArea roots do not engage
scrolling (viewport height resolves to auto), which is why the previous
nested list clipped; the flex-based definite-height pattern scrolls.
* feat(mcp): make the endpoint URL immutable after creation
Editing a server's URL effectively points it at a different server, and the
create flow is URL-only anyway — so the edit dialog no longer allows changing
it (delete + re-add covers endpoint changes). The URL is displayed read-only
next to the auto-detected name/description, and `url` was removed from the
update DTO and service; auth/transport changes still invalidate credentials
and cached tools.
* refactor(mcp): match MCP server cards to the skill card layout
The settings list cards now share the skill card structure: row 1 is the
server name (with direct-mode/transport badges) plus the three-dot menu,
row 2 is the description (falling back to 'No description provided') with
the endpoint URL and last error as small mono lines, and row 3 holds the
connection-status badge and updated date on the left with the permission
selector and the connect button at the right end.
* fix(mcp): stop card menu clicks from opening the edit dialog
The three-dot menu is portaled, so its item clicks bubble through React's
synthetic events to the card's onClick, which opened the edit dialog before
the delete confirmation appeared. Add e.stopPropagation() to every menu
item (matching the skill card pattern).
* fix(mcp): stop Refresh Tools from submitting/closing the config dialog
The Refresh Tools button lived inside the <form> and, like all buttons
without an explicit type, defaulted to type="submit" — clicking it ran the
form submit (save + close) instead of just refreshing. Set type="button".
Also per UX: while refreshing, the button is disabled with a spinning icon,
the per-tool enable/disable switches are disabled, and the success toast is
removed — the button reverting to its idle state is the success signal
(keep the error toast for failures).
* test(mcp): provide explicit redirectUri in McpOauthProvider test helper
* fix(mcp): scope tool registry to agent-assigned servers
The MCP tool registry was a process-global singleton keyed by server id,
so a chat agent could search, describe, and even call tools belonging to
MCP servers that were not assigned to it (e.g. disabled or unassigned
servers), as long as their metadata had been discovered at some point in
the process. This mirrors the disabled-skill bug: the read path never
checked per-agent enablement.
Replace the singleton with a fresh McpToolRegistry built per
buildAgentTools call and warmed from the persisted McpServer.tools DB
cache. Because the registry only ever contains the agent's assigned
servers, unassigned/disabled servers can neither be suggested, searched,
described, nor executed. Live discovery (lazy connect / connect action)
writes into the per-agent registry via ensureConnected(serverId,
registry?).
Adds test-first coverage: suggestions, search, describe and tool-call
leaks across an unassigned same-team server, staleness after
unassignment, and direct-tools scoping.
* feat(mcp): capture and surface server instructions + server-level refresh (#293)
* feat(mcp): capture and surface server instructions
- Add McpServer.instructions column, populated from getInstructions() at
connect time (legacy initialize + modern discover results)
- Surface instructions at three levels like pi-mcp-adapter: truncated
snippet in the mcp proxy tool description, preview in server listings,
and full text via mcp({ instructions: "name" })
- Fix misleading mcp({ server, connect }) usage line to mcp({ connect })
- Share one renderServerListing helper across list and connect modes
- Expose instructions in McpServerInfo DTO and WebUI config card
- Test server supports instructions; service + API tests updated
* refactor(mcp): server-level refresh endpoint, drop agent connect mode
- Replace POST /mcp/servers/:id/tools/refresh with POST /mcp/servers/:id/refresh
returning the refreshed McpServerInfo (server-level, not tools-level)
- Add McpService.refreshServer(): force-close the connection, re-discover and
persist tools, instructions, name/description and status; used by the refresh
endpoint, Test Connection, and post-OAuth completion (replacing discoverTools)
- Remove discoverTools entirely - refreshServer is the single discovery entry
point (testServer and completeAuth route through it)
- Remove refreshTools from UpdateMcpServerRequest/PATCH (dead param)
- Remove mcp({ connect: "name" }) from the agent proxy tool: lazy tool calls
still auto-connect, so agents are unaffected
- WebUI: remove the dialog 'Refresh Tools' button and create-mode background
auto-refresh; add a server-level Refresh button at the left end of the edit
dialog footer; i18n mcp_refresh_server (+ success message)
* feat(mcp): add in-flight request tracking and idle connection cleanup (#294)
* feat(mcp): add in-flight request tracking and idle connection cleanup
* feat(mcp): add background idle cleanup timer to McpService
* feat(mcp): update default background idle cleanup check interval to 30s
* feat(webui): improve MCP server card footer, instructions, and refresh dialog freeze (#295)
* feat(webui): improve MCP server list card, instructions dialog, and refresh freeze UI
* feat(webui): refine MCP card action menu items
* docs(webui): update direct tools mode description in i18n messages
* style(webui): refine Direct Tools Mode layout in MCP server config dialog
* feat(webui): remove tool search box from MCP server config dialog
* fix(mcp): make in-flight idle tracking test deterministic
The 'tracks in-flight requests and safely prunes idle connections' test
relied on a wall-clock sleep (10ms) to guess when the tool handler had
started executing on the server. On slow/loaded CI runners the HTTP round
trip through the real MCP client/server stack can exceed that window, so
resolveSlowTool() fired the no-op placeholder, the gated handler never
completed, and callPromise hung until the 5000ms test timeout.
The handler now signals via a deferred promise when it actually starts,
and the test awaits that signal (racing it against the call promise to
surface early failures) before asserting in-flight state and releasing
the gate. Also gives the test an explicit 10s timeout.
This commit is contained in:
@@ -121,6 +121,7 @@ export class AgentService {
|
||||
systemPrompt,
|
||||
soul,
|
||||
skills,
|
||||
mcpServerIds,
|
||||
deniedTools,
|
||||
} = params
|
||||
|
||||
@@ -189,6 +190,12 @@ export class AgentService {
|
||||
skillId,
|
||||
})) || [],
|
||||
},
|
||||
mcpServers: {
|
||||
create:
|
||||
mcpServerIds?.map((mcpServerId) => ({
|
||||
mcpServerId,
|
||||
})) || [],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -202,7 +209,11 @@ export class AgentService {
|
||||
|
||||
return tx.agent.findUnique({
|
||||
where: { id: agent.id },
|
||||
include: { user: true, skills: { include: { skill: true } } },
|
||||
include: {
|
||||
user: true,
|
||||
skills: { include: { skill: true } },
|
||||
mcpServers: { include: { mcpServer: true } },
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -220,6 +231,7 @@ export class AgentService {
|
||||
systemPrompt,
|
||||
soul,
|
||||
skills,
|
||||
mcpServerIds,
|
||||
deniedTools,
|
||||
} = params
|
||||
|
||||
@@ -278,6 +290,11 @@ export class AgentService {
|
||||
where: { agentId },
|
||||
})
|
||||
|
||||
// Update MCP server assignments: easier to delete all and recreate
|
||||
await tx.agentMcpServer.deleteMany({
|
||||
where: { agentId },
|
||||
})
|
||||
|
||||
return tx.agent.update({
|
||||
where: { id: agentId },
|
||||
data: {
|
||||
@@ -294,8 +311,18 @@ export class AgentService {
|
||||
skillId,
|
||||
})) || [],
|
||||
},
|
||||
mcpServers: {
|
||||
create:
|
||||
mcpServerIds?.map((mcpServerId) => ({
|
||||
mcpServerId,
|
||||
})) || [],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
skills: { include: { skill: true } },
|
||||
mcpServers: { include: { mcpServer: true } },
|
||||
},
|
||||
include: { user: true, skills: { include: { skill: true } } },
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -338,6 +365,7 @@ export class AgentService {
|
||||
skill: true,
|
||||
},
|
||||
},
|
||||
mcpServers: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ export enum ResourceType {
|
||||
MetadataField = 'metadataField',
|
||||
Skill = 'skill',
|
||||
Provider = 'provider',
|
||||
McpServer = 'mcpServer',
|
||||
Invite = 'invite',
|
||||
Comment = 'comment',
|
||||
AgentSession = 'agentSession',
|
||||
@@ -187,6 +188,15 @@ export class AuthzService {
|
||||
return { teamId: skill.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.McpServer: {
|
||||
const server = await prisma.mcpServer.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!server) throw new HTTPException(404, { message: 'MCP server not found' })
|
||||
return { teamId: server.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.Provider: {
|
||||
const provider = await prisma.provider.findUnique({
|
||||
where: { id },
|
||||
|
||||
@@ -25,3 +25,4 @@ export * from './chat/chat'
|
||||
export * from './ai-usage/ai-usage'
|
||||
export * from './watermark/watermark'
|
||||
export * from './gotenberg/gotenberg'
|
||||
export * from './mcp/mcp-service'
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import { describe, it, expect, beforeAll } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { McpDbStore } from './mcp-db-store'
|
||||
|
||||
describe('McpDbStore', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let store: McpDbStore
|
||||
let serverId: string
|
||||
|
||||
beforeAll(async () => {
|
||||
store = new McpDbStore()
|
||||
const team = await prisma.team.create({ data: { name: 'MCP DB Store Team' } })
|
||||
const server = await prisma.mcpServer.create({
|
||||
data: {
|
||||
name: 'github',
|
||||
url: 'https://mcp.example.com/github',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
serverId = server.id
|
||||
})
|
||||
|
||||
it('returns undefined when no credentials exist', async () => {
|
||||
expect(await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')).toBeUndefined()
|
||||
expect(await store.hasStoredTokens(serverId)).toBe(false)
|
||||
expect(await store.isTokenExpired(serverId)).toBeNull()
|
||||
})
|
||||
|
||||
it('saves and reads tokens bound to the URL', async () => {
|
||||
await store.updateTokens(
|
||||
serverId,
|
||||
{ accessToken: 'tok-1', refreshToken: 'ref-1' },
|
||||
'https://mcp.example.com/github',
|
||||
)
|
||||
const entry = await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')
|
||||
expect(entry?.tokens?.accessToken).toBe('tok-1')
|
||||
expect(entry?.tokens?.refreshToken).toBe('ref-1')
|
||||
expect(await store.hasStoredTokens(serverId)).toBe(true)
|
||||
})
|
||||
|
||||
it('invalidates credentials when the URL changes', async () => {
|
||||
expect(await store.getAuthForUrl(serverId, 'https://other.example.com')).toBeUndefined()
|
||||
expect(await store.hasStoredTokens(serverId)).toBe(false)
|
||||
})
|
||||
|
||||
it('saves and clears client info', async () => {
|
||||
await store.updateClientInfo(
|
||||
serverId,
|
||||
{ clientId: 'client-1', clientSecret: 'secret-1' },
|
||||
'https://mcp.example.com/github',
|
||||
)
|
||||
let entry = await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')
|
||||
expect(entry?.clientInfo?.clientId).toBe('client-1')
|
||||
|
||||
await store.clearClientInfo(serverId)
|
||||
entry = await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')
|
||||
expect(entry?.clientInfo).toBeUndefined()
|
||||
})
|
||||
|
||||
it('saves/clears the PKCE code verifier', async () => {
|
||||
await store.updateCodeVerifier(serverId, 'verifier-abc', 'https://mcp.example.com/github')
|
||||
let entry = await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')
|
||||
expect(entry?.codeVerifier).toBe('verifier-abc')
|
||||
|
||||
await store.clearCodeVerifier(serverId)
|
||||
entry = await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')
|
||||
expect(entry?.codeVerifier).toBeUndefined()
|
||||
})
|
||||
|
||||
it('saves/clears the CSRF state', async () => {
|
||||
await store.updateOauthState(serverId, 'state-xyz', 'https://mcp.example.com/github')
|
||||
expect(await store.getOauthState(serverId)).toBe('state-xyz')
|
||||
|
||||
await store.clearOauthState(serverId)
|
||||
expect(await store.getOauthState(serverId)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('detects expired tokens', async () => {
|
||||
await store.updateTokens(
|
||||
serverId,
|
||||
{ accessToken: 'tok-expired', expiresAt: Math.floor(Date.now() / 1000) - 10 },
|
||||
'https://mcp.example.com/github',
|
||||
)
|
||||
expect(await store.isTokenExpired(serverId)).toBe(true)
|
||||
|
||||
await store.updateTokens(
|
||||
serverId,
|
||||
{ accessToken: 'tok-valid', expiresAt: Math.floor(Date.now() / 1000) + 3600 },
|
||||
'https://mcp.example.com/github',
|
||||
)
|
||||
expect(await store.isTokenExpired(serverId)).toBe(false)
|
||||
})
|
||||
|
||||
it('treats tokens without an expiry as never-expiring', async () => {
|
||||
await store.updateTokens(
|
||||
serverId,
|
||||
{ accessToken: 'tok-no-expiry' },
|
||||
'https://mcp.example.com/github',
|
||||
)
|
||||
expect(await store.isTokenExpired(serverId)).toBe(false)
|
||||
})
|
||||
|
||||
it('clears tokens only', async () => {
|
||||
await store.updateTokens(serverId, { accessToken: 'tok-x' }, 'https://mcp.example.com/github')
|
||||
await store.clearTokens(serverId)
|
||||
expect(await store.hasStoredTokens(serverId)).toBe(false)
|
||||
})
|
||||
|
||||
it('clears all credentials', async () => {
|
||||
await store.updateTokens(serverId, { accessToken: 'tok-y' }, 'https://mcp.example.com/github')
|
||||
await store.updateClientInfo(serverId, { clientId: 'c' }, 'https://mcp.example.com/github')
|
||||
await store.clearAllCredentials(serverId)
|
||||
expect(await store.getAuthForUrl(serverId, 'https://mcp.example.com/github')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('persists an in-flight pendingAuth with a TTL and expires it', async () => {
|
||||
const ttl = await store.getPendingAuthTtlSeconds()
|
||||
await store.savePendingAuth(serverId, {
|
||||
state: 'pending-state',
|
||||
authorizationUrl: 'https://auth.example.com/authorize?state=pending-state',
|
||||
discovery: { scope: 'read' },
|
||||
expiresAt: Math.floor(Date.now() / 1000) + ttl,
|
||||
})
|
||||
const pending = await store.getPendingAuth(serverId)
|
||||
expect(pending?.state).toBe('pending-state')
|
||||
expect(pending?.authorizationUrl).toContain('pending-state')
|
||||
|
||||
// Expired pendingAuth is cleared on read.
|
||||
await store.savePendingAuth(serverId, {
|
||||
state: 'stale',
|
||||
authorizationUrl: 'https://auth.example.com/authorize',
|
||||
discovery: {},
|
||||
expiresAt: Math.floor(Date.now() / 1000) - 10,
|
||||
})
|
||||
expect(await store.getPendingAuth(serverId)).toBeUndefined()
|
||||
|
||||
await store.clearPendingAuth(serverId)
|
||||
expect(await store.getPendingAuth(serverId)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('savePendingAuth does not clobber an in-flight discovery snapshot', async () => {
|
||||
// Simulates the SDK flow: the provider's saveDiscoveryState() stores a
|
||||
// snapshot inside the pendingAuth column, then startAuth() calls
|
||||
// savePendingAuth(). The snapshot MUST survive so the callback leg can
|
||||
// satisfy the SEP-2352 issuer check.
|
||||
await store.saveDiscoverySnapshot(serverId, 'https://mcp.example.com/github', {
|
||||
authorizationServerUrl: 'https://kling.ai/auth',
|
||||
authorizationServerMetadata: { issuer: 'https://kling.ai/auth' },
|
||||
})
|
||||
|
||||
await store.savePendingAuth(serverId, {
|
||||
state: 'state-abc',
|
||||
authorizationUrl: 'https://kling.ai/authorize',
|
||||
discovery: {},
|
||||
expiresAt: Math.floor(Date.now() / 1000) + 300,
|
||||
})
|
||||
|
||||
const snapshot = await store.getDiscoverySnapshot(serverId)
|
||||
expect(snapshot).toBeDefined()
|
||||
expect(snapshot?.['authorizationServerUrl']).toBe('https://kling.ai/auth')
|
||||
|
||||
const pending = await store.getPendingAuth(serverId)
|
||||
expect(pending?.state).toBe('state-abc')
|
||||
})
|
||||
|
||||
it('persists and clears the discovery snapshot', async () => {
|
||||
await store.saveDiscoverySnapshot(serverId, 'https://mcp.example.com/github', {
|
||||
authorizationServerUrl: 'https://issuer.example.com',
|
||||
})
|
||||
const snapshot = await store.getDiscoverySnapshot(serverId)
|
||||
expect(snapshot?.authorizationServerUrl).toBe('https://issuer.example.com')
|
||||
|
||||
await store.clearDiscoverySnapshot(serverId)
|
||||
expect(await store.getDiscoverySnapshot(serverId)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('deletes the credential row when the server is deleted (cascade)', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Cascade Team' } })
|
||||
const server = await prisma.mcpServer.create({
|
||||
data: { name: 'cascade-srv', url: 'https://mcp.example.com/cascade', teamId: team.id },
|
||||
})
|
||||
await store.updateTokens(
|
||||
server.id,
|
||||
{ accessToken: 'tok-cascade' },
|
||||
'https://mcp.example.com/cascade',
|
||||
)
|
||||
await prisma.mcpServer.delete({ where: { id: server.id } })
|
||||
const leftover = await prisma.mcpServerCredential.findUnique({ where: { serverId: server.id } })
|
||||
expect(leftover).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,388 @@
|
||||
import { prisma, Prisma } from '@shumai/db'
|
||||
|
||||
export interface StoredTokens {
|
||||
accessToken: string
|
||||
refreshToken?: string
|
||||
expiresAt?: number // Unix timestamp in seconds
|
||||
scope?: string
|
||||
/** SEP-2352 authorization-server issuer binding */
|
||||
issuer?: string
|
||||
}
|
||||
|
||||
export interface StoredClientInfo {
|
||||
clientId: string
|
||||
clientSecret?: string
|
||||
clientIdIssuedAt?: number
|
||||
clientSecretExpiresAt?: number
|
||||
redirectUris?: string[]
|
||||
issuer?: string
|
||||
configPreRegistered?: boolean
|
||||
}
|
||||
|
||||
export interface AuthEntry {
|
||||
tokens?: StoredTokens
|
||||
clientInfo?: StoredClientInfo
|
||||
codeVerifier?: string
|
||||
oauthState?: string
|
||||
serverUrl?: string // Track the URL these credentials are for
|
||||
}
|
||||
|
||||
export interface PendingAuth {
|
||||
state: string
|
||||
authorizationUrl: string
|
||||
discovery: Record<string, unknown>
|
||||
expiresAt: number // Unix timestamp in seconds
|
||||
grantType?: 'authorization_code' | 'client_credentials'
|
||||
redirectUri?: string
|
||||
}
|
||||
|
||||
/** How long an in-flight authorization_code flow is kept in the DB (5 minutes). */
|
||||
const PENDING_AUTH_TTL_SECONDS = 5 * 60
|
||||
|
||||
function rowToAuthEntry(row: {
|
||||
serverUrl: string
|
||||
tokens: unknown
|
||||
clientInfo: unknown
|
||||
codeVerifier: string | null
|
||||
oauthState: string | null
|
||||
pendingAuth: unknown
|
||||
}): {
|
||||
entry: AuthEntry
|
||||
pendingAuth?: PendingAuth
|
||||
} {
|
||||
const entry: AuthEntry = {
|
||||
serverUrl: row.serverUrl,
|
||||
...(row.tokens ? { tokens: row.tokens as StoredTokens } : {}),
|
||||
...(row.clientInfo ? { clientInfo: row.clientInfo as StoredClientInfo } : {}),
|
||||
...(row.codeVerifier ? { codeVerifier: row.codeVerifier } : {}),
|
||||
...(row.oauthState ? { oauthState: row.oauthState } : {}),
|
||||
}
|
||||
let pendingAuth: PendingAuth | undefined
|
||||
if (row.pendingAuth && typeof row.pendingAuth === 'object') {
|
||||
const raw = row.pendingAuth as Partial<PendingAuth>
|
||||
if (typeof raw.state === 'string' && typeof raw.expiresAt === 'number') {
|
||||
pendingAuth = {
|
||||
state: raw.state,
|
||||
authorizationUrl: raw.authorizationUrl ?? '',
|
||||
discovery: raw.discovery ?? {},
|
||||
expiresAt: raw.expiresAt,
|
||||
...(raw.grantType ? { grantType: raw.grantType } : {}),
|
||||
...(raw.redirectUri ? { redirectUri: raw.redirectUri } : {}),
|
||||
}
|
||||
}
|
||||
}
|
||||
return { entry, pendingAuth }
|
||||
}
|
||||
|
||||
/**
|
||||
* DB-backed credential store for MCP OAuth state (port of pi-mcp-adapter's
|
||||
* mcp-auth.ts storage layer, replacing the OS keyring/files with an
|
||||
* `McpServerCredential` row per server).
|
||||
*/
|
||||
export class McpDbStore {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
|
||||
private async getRow(serverId: string) {
|
||||
return this.prismaClient.mcpServerCredential.findUnique({
|
||||
where: { serverId },
|
||||
})
|
||||
}
|
||||
|
||||
private async ensureRow(serverId: string, serverUrl?: string) {
|
||||
const existing = await this.getRow(serverId)
|
||||
if (existing) return existing
|
||||
if (!serverUrl) throw new Error(`No credential row for MCP server ${serverId}`)
|
||||
return this.prismaClient.mcpServerCredential.create({
|
||||
data: {
|
||||
serverId,
|
||||
serverUrl,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the auth entry for a server, validated against the current URL.
|
||||
* Returns undefined when no entry exists or the URL changed (credentials invalid).
|
||||
*/
|
||||
async getAuthForUrl(serverId: string, serverUrl: string): Promise<AuthEntry | undefined> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) return undefined
|
||||
// If no serverUrl is stored or it changed, credentials are invalid.
|
||||
if (!row.serverUrl || row.serverUrl !== serverUrl) return undefined
|
||||
return rowToAuthEntry(row).entry
|
||||
}
|
||||
|
||||
async getAuthEntry(serverId: string): Promise<AuthEntry | undefined> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) return undefined
|
||||
return rowToAuthEntry(row).entry
|
||||
}
|
||||
|
||||
async saveAuthEntry(serverId: string, entry: AuthEntry, serverUrl?: string): Promise<void> {
|
||||
const row = await this.getRow(serverId)
|
||||
const serverUrlValue = serverUrl ?? entry.serverUrl ?? row?.serverUrl
|
||||
// Do NOT merge the row's credential fields back in: callers build `entry`
|
||||
// from getAuthEntry() (all current fields) and delete fields to clear
|
||||
// them. Re-adding row fields would leak cleared values.
|
||||
const merged: AuthEntry = { ...entry }
|
||||
if (serverUrlValue) {
|
||||
merged.serverUrl = serverUrlValue
|
||||
if (row && serverUrlValue !== row.serverUrl) {
|
||||
// URL changed: stale sub-credentials are dropped.
|
||||
delete merged.tokens
|
||||
delete merged.clientInfo
|
||||
delete merged.codeVerifier
|
||||
delete merged.oauthState
|
||||
}
|
||||
}
|
||||
const data = {
|
||||
serverUrl: merged.serverUrl ?? serverUrlValue ?? '',
|
||||
tokens: merged.tokens ?? undefined,
|
||||
clientInfo: merged.clientInfo ?? undefined,
|
||||
codeVerifier: merged.codeVerifier ?? undefined,
|
||||
oauthState: merged.oauthState ?? undefined,
|
||||
}
|
||||
if (row) {
|
||||
await this.prismaClient.mcpServerCredential.update({
|
||||
where: { serverId },
|
||||
data: {
|
||||
serverUrl: data.serverUrl,
|
||||
tokens:
|
||||
data.tokens === undefined
|
||||
? Prisma.JsonNull
|
||||
: (data.tokens as PrismaJson.McpStoredTokens),
|
||||
clientInfo:
|
||||
data.clientInfo === undefined
|
||||
? Prisma.JsonNull
|
||||
: (data.clientInfo as PrismaJson.McpStoredClientInfo),
|
||||
codeVerifier: data.codeVerifier ?? null,
|
||||
oauthState: data.oauthState ?? null,
|
||||
},
|
||||
})
|
||||
} else if (serverUrlValue) {
|
||||
await this.prismaClient.mcpServerCredential.create({
|
||||
data: {
|
||||
serverId,
|
||||
serverUrl: serverUrlValue,
|
||||
tokens: data.tokens as PrismaJson.McpStoredTokens | undefined,
|
||||
clientInfo: data.clientInfo as PrismaJson.McpStoredClientInfo | undefined,
|
||||
codeVerifier: data.codeVerifier,
|
||||
oauthState: data.oauthState,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async updateTokens(serverId: string, tokens: StoredTokens, serverUrl?: string): Promise<void> {
|
||||
const entry = (await this.getAuthEntry(serverId)) ?? {}
|
||||
if (serverUrl && entry.serverUrl && entry.serverUrl !== serverUrl) {
|
||||
delete entry.clientInfo
|
||||
delete entry.codeVerifier
|
||||
delete entry.oauthState
|
||||
}
|
||||
entry.tokens = tokens
|
||||
await this.saveAuthEntry(serverId, entry, serverUrl)
|
||||
}
|
||||
|
||||
async updateClientInfo(
|
||||
serverId: string,
|
||||
clientInfo: StoredClientInfo,
|
||||
serverUrl?: string,
|
||||
): Promise<void> {
|
||||
const entry = (await this.getAuthEntry(serverId)) ?? {}
|
||||
if (serverUrl && entry.serverUrl && entry.serverUrl !== serverUrl) {
|
||||
delete entry.tokens
|
||||
delete entry.codeVerifier
|
||||
delete entry.oauthState
|
||||
}
|
||||
entry.clientInfo = clientInfo
|
||||
await this.saveAuthEntry(serverId, entry, serverUrl)
|
||||
}
|
||||
|
||||
async updateCodeVerifier(
|
||||
serverId: string,
|
||||
codeVerifier: string,
|
||||
serverUrl?: string,
|
||||
): Promise<void> {
|
||||
const entry = (await this.getAuthEntry(serverId)) ?? {}
|
||||
if (serverUrl && entry.serverUrl && entry.serverUrl !== serverUrl) {
|
||||
delete entry.tokens
|
||||
delete entry.clientInfo
|
||||
delete entry.oauthState
|
||||
}
|
||||
entry.codeVerifier = codeVerifier
|
||||
await this.saveAuthEntry(serverId, entry, serverUrl)
|
||||
}
|
||||
|
||||
async clearCodeVerifier(serverId: string): Promise<void> {
|
||||
const entry = await this.getAuthEntry(serverId)
|
||||
if (entry) {
|
||||
delete entry.codeVerifier
|
||||
await this.saveAuthEntry(serverId, entry)
|
||||
}
|
||||
}
|
||||
|
||||
async updateOauthState(serverId: string, state: string, serverUrl?: string): Promise<void> {
|
||||
const entry = (await this.getAuthEntry(serverId)) ?? {}
|
||||
if (serverUrl && entry.serverUrl && entry.serverUrl !== serverUrl) {
|
||||
delete entry.tokens
|
||||
delete entry.clientInfo
|
||||
delete entry.codeVerifier
|
||||
}
|
||||
entry.oauthState = state
|
||||
await this.saveAuthEntry(serverId, entry, serverUrl)
|
||||
}
|
||||
|
||||
async getOauthState(serverId: string): Promise<string | undefined> {
|
||||
const row = await this.getRow(serverId)
|
||||
return row?.oauthState ?? undefined
|
||||
}
|
||||
|
||||
async clearOauthState(serverId: string): Promise<void> {
|
||||
const entry = await this.getAuthEntry(serverId)
|
||||
if (entry) {
|
||||
delete entry.oauthState
|
||||
await this.saveAuthEntry(serverId, entry)
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns null when no tokens exist, false when valid, true when expired. */
|
||||
async isTokenExpired(serverId: string): Promise<boolean | null> {
|
||||
const row = await this.getRow(serverId)
|
||||
const tokens = row?.tokens as StoredTokens | null | undefined
|
||||
if (!tokens?.accessToken) return null
|
||||
if (!tokens.expiresAt) return false
|
||||
return tokens.expiresAt < Date.now() / 1000
|
||||
}
|
||||
|
||||
async hasStoredTokens(serverId: string): Promise<boolean> {
|
||||
const row = await this.getRow(serverId)
|
||||
const tokens = row?.tokens as StoredTokens | null | undefined
|
||||
return !!tokens?.accessToken
|
||||
}
|
||||
|
||||
async clearAllCredentials(serverId: string): Promise<void> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) return
|
||||
await this.prismaClient.mcpServerCredential.delete({ where: { serverId } })
|
||||
}
|
||||
|
||||
async clearClientInfo(serverId: string): Promise<void> {
|
||||
const entry = await this.getAuthEntry(serverId)
|
||||
if (entry) {
|
||||
delete entry.clientInfo
|
||||
await this.saveAuthEntry(serverId, entry)
|
||||
}
|
||||
}
|
||||
|
||||
async clearTokens(serverId: string): Promise<void> {
|
||||
const entry = await this.getAuthEntry(serverId)
|
||||
if (entry) {
|
||||
delete entry.tokens
|
||||
await this.saveAuthEntry(serverId, entry)
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// In-flight authorization_code flow (pendingAuth)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
async savePendingAuth(serverId: string, pending: PendingAuth): Promise<void> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) {
|
||||
const server = await this.prismaClient.mcpServer.findUnique({
|
||||
where: { id: serverId },
|
||||
select: { url: true },
|
||||
})
|
||||
if (!server) throw new Error(`MCP server ${serverId} not found`)
|
||||
await this.ensureRow(serverId, server.url)
|
||||
}
|
||||
// Preserve an in-flight discovery snapshot: the OAuth provider's
|
||||
// saveDiscoveryState() lives in the same JSON column, and the callback
|
||||
// leg needs it for the SEP-2352 issuer check.
|
||||
const existing = (row?.pendingAuth as Record<string, unknown> | null | undefined) ?? {}
|
||||
const discoverySnapshot = existing['discoverySnapshot']
|
||||
const data = discoverySnapshot !== undefined ? { ...pending, discoverySnapshot } : pending
|
||||
await this.prismaClient.mcpServerCredential.update({
|
||||
where: { serverId },
|
||||
data: { pendingAuth: data as unknown as PrismaJson.McpPendingAuth },
|
||||
})
|
||||
}
|
||||
|
||||
async getPendingAuth(serverId: string): Promise<PendingAuth | undefined> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) return undefined
|
||||
const { pendingAuth } = rowToAuthEntry(row)
|
||||
if (!pendingAuth) return undefined
|
||||
if (pendingAuth.expiresAt < Date.now() / 1000) {
|
||||
await this.clearPendingAuth(serverId)
|
||||
return undefined
|
||||
}
|
||||
return pendingAuth
|
||||
}
|
||||
|
||||
async clearPendingAuth(serverId: string): Promise<void> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) return
|
||||
await this.prismaClient.mcpServerCredential.update({
|
||||
where: { serverId },
|
||||
data: { pendingAuth: Prisma.JsonNull },
|
||||
})
|
||||
}
|
||||
|
||||
async getPendingAuthTtlSeconds(): Promise<number> {
|
||||
return PENDING_AUTH_TTL_SECONDS
|
||||
}
|
||||
|
||||
/** Ensure a credential row exists for a server (used when persisting any auth state). */
|
||||
async ensureCredentialRow(serverId: string, serverUrl: string): Promise<void> {
|
||||
await this.ensureRow(serverId, serverUrl)
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Discovery snapshot (survives from startAuth to the callback leg)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
async saveDiscoverySnapshot(serverId: string, serverUrl: string, state: unknown): Promise<void> {
|
||||
await this.ensureRow(serverId, serverUrl)
|
||||
const row = await this.getRow(serverId)
|
||||
const existing = (row?.pendingAuth as Record<string, unknown> | null | undefined) ?? {}
|
||||
await this.prismaClient.mcpServerCredential.update({
|
||||
where: { serverId },
|
||||
data: {
|
||||
pendingAuth: {
|
||||
...existing,
|
||||
discoverySnapshot: state,
|
||||
} as unknown as PrismaJson.McpPendingAuth,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async getDiscoverySnapshot(serverId: string): Promise<Record<string, unknown> | undefined> {
|
||||
const row = await this.getRow(serverId)
|
||||
const pending = (row?.pendingAuth as Record<string, unknown> | null | undefined) ?? {}
|
||||
const snapshot = pending['discoverySnapshot']
|
||||
return snapshot && typeof snapshot === 'object'
|
||||
? (snapshot as Record<string, unknown>)
|
||||
: undefined
|
||||
}
|
||||
|
||||
async clearDiscoverySnapshot(serverId: string): Promise<void> {
|
||||
const row = await this.getRow(serverId)
|
||||
if (!row) return
|
||||
const pending = (row.pendingAuth as Record<string, unknown> | null | undefined) ?? {}
|
||||
const rest: Record<string, unknown> = { ...pending }
|
||||
delete rest['discoverySnapshot']
|
||||
await this.prismaClient.mcpServerCredential.update({
|
||||
where: { serverId },
|
||||
data: {
|
||||
pendingAuth:
|
||||
Object.keys(rest).length > 0
|
||||
? (rest as unknown as PrismaJson.McpPendingAuth)
|
||||
: Prisma.JsonNull,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const mcpDbStore = new McpDbStore()
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Direct MCP tools — per-server opt-in registration.
|
||||
*
|
||||
* When a server's config sets `directTools: true`, its allowed tools (after
|
||||
* excludeTools filters) are registered as native AgentTools with prefixed
|
||||
* names `{server}_{tool}`. The `mcp` proxy tool stays registered for
|
||||
* discovery/auth/status and for servers not in direct mode.
|
||||
*/
|
||||
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import type { ToolMetadata } from './mcp-tool-registry'
|
||||
import { toToolParameters } from './mcp-tool-schema'
|
||||
|
||||
export interface DirectToolCallOptions {
|
||||
serverId: string
|
||||
serverName: string
|
||||
callTool(
|
||||
serverId: string,
|
||||
toolName: string,
|
||||
args: Record<string, unknown>,
|
||||
): Promise<{
|
||||
ok: boolean
|
||||
content: AgentToolResult<Record<string, unknown>>['content']
|
||||
}>
|
||||
}
|
||||
|
||||
function globToRegExp(pattern: string): RegExp {
|
||||
const escaped = pattern
|
||||
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
||||
.replace(/\*/g, '.*')
|
||||
.replace(/\?/g, '.')
|
||||
return new RegExp(`^${escaped}$`)
|
||||
}
|
||||
|
||||
function matchesToolPattern(name: string, patterns?: string[]): boolean {
|
||||
if (!Array.isArray(patterns) || patterns.length === 0) return false
|
||||
for (const pattern of patterns) {
|
||||
if (!pattern) continue
|
||||
if (!pattern.includes('*') && !pattern.includes('?') && name === pattern) return true
|
||||
if ((pattern.includes('*') || pattern.includes('?')) && globToRegExp(pattern).test(name)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Decide whether a tool is allowed by excludeTools (matches prefixed or original name). */
|
||||
export function isToolAllowed(
|
||||
prefixedName: string,
|
||||
originalName: string,
|
||||
config?: PrismaJson.McpServerConfig,
|
||||
): boolean {
|
||||
const exclude = config?.excludeTools
|
||||
if (matchesToolPattern(prefixedName, exclude) || matchesToolPattern(originalName, exclude)) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Build direct AgentTools for a server in direct-tools mode.
|
||||
* Returns [] when directTools is not enabled or no tools pass the filters.
|
||||
*/
|
||||
export function buildDirectTools(
|
||||
metadata: ToolMetadata[],
|
||||
config: PrismaJson.McpServerConfig | undefined,
|
||||
opts: DirectToolCallOptions,
|
||||
): AgentTool[] {
|
||||
if (config?.directTools !== true) return []
|
||||
|
||||
const tools: AgentTool[] = []
|
||||
for (const tool of metadata) {
|
||||
if (!isToolAllowed(tool.name, tool.originalName, config)) continue
|
||||
const parameters = toToolParameters(tool.inputSchema)
|
||||
tools.push({
|
||||
name: tool.name,
|
||||
label: tool.name,
|
||||
description:
|
||||
tool.description || `Call ${tool.originalName} on MCP server ${opts.serverName}.`,
|
||||
parameters: parameters as unknown as import('typebox').TSchema,
|
||||
execute: async (_toolCallId, args): Promise<AgentToolResult<Record<string, unknown>>> => {
|
||||
const result = await opts.callTool(
|
||||
opts.serverId,
|
||||
tool.originalName,
|
||||
args as Record<string, unknown>,
|
||||
)
|
||||
return {
|
||||
content: result.content,
|
||||
details: { server: opts.serverName, tool: tool.originalName },
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
return tools
|
||||
}
|
||||
|
||||
// Re-exported for tests that need a fallback parameter schema.
|
||||
export { Type }
|
||||
@@ -0,0 +1,147 @@
|
||||
import { describe, it, expect, beforeAll } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { McpDbStore } from './mcp-db-store'
|
||||
import { McpOauthProvider } from './mcp-oauth-provider'
|
||||
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
// The OAuth wire format (RFC 6749 / OAuth 2.1) uses snake_case field names
|
||||
// (client_id, access_token, grant_type, ...); the test fixtures must use the
|
||||
// protocol's exact key names because they are passed to the MCP SDK's
|
||||
// OAuthClientProvider interfaces.
|
||||
|
||||
const SERVER_URL = 'https://mcp.example.com/kling'
|
||||
const ISSUER = 'https://kling.ai/auth'
|
||||
|
||||
describe('McpOauthProvider SEP-2352 issuer stamping', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let store: McpDbStore
|
||||
let serverId: string
|
||||
|
||||
const makeProvider = () =>
|
||||
new McpOauthProvider(
|
||||
serverId,
|
||||
SERVER_URL,
|
||||
{ redirectUri: 'https://shumai.ai/api/mcp/oauth/callback' },
|
||||
{ onRedirect: async () => {} },
|
||||
store,
|
||||
)
|
||||
|
||||
beforeAll(async () => {
|
||||
store = new McpDbStore()
|
||||
const team = await prisma.team.create({ data: { name: 'OAuth Provider Team' } })
|
||||
const server = await prisma.mcpServer.create({
|
||||
data: { name: 'kling', url: SERVER_URL, teamId: team.id },
|
||||
})
|
||||
serverId = server.id
|
||||
})
|
||||
|
||||
it('discoveryState() returns the snapshot saved by the start leg on the callback leg', async () => {
|
||||
const provider = makeProvider()
|
||||
// Start leg: the SDK saves the discovery state before redirecting.
|
||||
await provider.saveDiscoveryState({
|
||||
authorizationServerUrl: ISSUER,
|
||||
authorizationServerMetadata: { issuer: ISSUER },
|
||||
resourceMetadataUrl: `${SERVER_URL}/.well-known/oauth-protected-resource`,
|
||||
} as never)
|
||||
await provider.deactivate()
|
||||
|
||||
// startAuth() persists the pending flow (must not clobber the snapshot).
|
||||
await store.savePendingAuth(serverId, {
|
||||
state: 'state-xyz',
|
||||
authorizationUrl: 'https://kling.ai/authorize',
|
||||
discovery: {},
|
||||
expiresAt: Math.floor(Date.now() / 1000) + 300,
|
||||
})
|
||||
|
||||
// Callback leg: a fresh provider instance reads the same snapshot.
|
||||
const callbackProvider = makeProvider()
|
||||
const state = await callbackProvider.discoveryState()
|
||||
expect(state?.authorizationServerMetadata?.issuer).toBe(ISSUER)
|
||||
expect(state?.authorizationServerUrl).toBe(ISSUER)
|
||||
})
|
||||
|
||||
it('saveClientInformation stamps the issuer and clientInformation round-trips it', async () => {
|
||||
const provider = makeProvider()
|
||||
await provider.saveDiscoveryState({
|
||||
authorizationServerUrl: ISSUER,
|
||||
authorizationServerMetadata: { issuer: ISSUER },
|
||||
} as never)
|
||||
|
||||
await provider.saveClientInformation({
|
||||
client_id: 'dyn-client',
|
||||
client_secret: 'dyn-secret',
|
||||
} as never)
|
||||
|
||||
const info = await makeProvider().clientInformation()
|
||||
expect(info?.client_id).toBe('dyn-client')
|
||||
expect((info as { issuer?: string }).issuer).toBe(ISSUER)
|
||||
})
|
||||
|
||||
it('clientInformation() backfills a missing issuer stamp on stale client info', async () => {
|
||||
const provider = makeProvider()
|
||||
// Pre-existing client info stored WITHOUT an issuer (registered before the
|
||||
// stamping fix). The discovery snapshot is available for this read.
|
||||
await store.updateClientInfo(
|
||||
serverId,
|
||||
{ clientId: 'legacy-client', clientSecret: 'legacy-secret' },
|
||||
SERVER_URL,
|
||||
)
|
||||
await provider.saveDiscoveryState({
|
||||
authorizationServerUrl: ISSUER,
|
||||
authorizationServerMetadata: { issuer: ISSUER },
|
||||
} as never)
|
||||
|
||||
const info = await makeProvider().clientInformation()
|
||||
expect(info?.client_id).toBe('legacy-client')
|
||||
expect((info as { issuer?: string }).issuer).toBe(ISSUER)
|
||||
// The stamp is persisted, not just returned.
|
||||
const entry = await store.getAuthForUrl(serverId, SERVER_URL)
|
||||
expect(entry?.clientInfo?.issuer).toBe(ISSUER)
|
||||
})
|
||||
|
||||
it('saveTokens stamps the issuer and tokens round-trips it', async () => {
|
||||
const provider = makeProvider()
|
||||
await provider.saveDiscoveryState({
|
||||
authorizationServerUrl: ISSUER,
|
||||
authorizationServerMetadata: { issuer: ISSUER },
|
||||
} as never)
|
||||
|
||||
await provider.saveTokens({
|
||||
access_token: 'tok-1',
|
||||
token_type: 'Bearer',
|
||||
refresh_token: 'ref-1',
|
||||
expires_in: 3600,
|
||||
} as never)
|
||||
|
||||
const tokens = await makeProvider().tokens()
|
||||
expect(tokens?.access_token).toBe('tok-1')
|
||||
expect((tokens as { issuer?: string }).issuer).toBe(ISSUER)
|
||||
})
|
||||
|
||||
it('tokens() backfills a missing issuer stamp from the discovery snapshot', async () => {
|
||||
const provider = makeProvider()
|
||||
// Pre-existing tokens stored WITHOUT an issuer (pre-upgrade / buggy flow).
|
||||
await store.updateTokens(serverId, { accessToken: 'legacy-tok' }, SERVER_URL)
|
||||
// The discovery snapshot is present for the read.
|
||||
await provider.saveDiscoveryState({
|
||||
authorizationServerUrl: ISSUER,
|
||||
authorizationServerMetadata: { issuer: ISSUER },
|
||||
} as never)
|
||||
|
||||
const tokens = await provider.tokens()
|
||||
expect(tokens?.access_token).toBe('legacy-tok')
|
||||
expect((tokens as { issuer?: string }).issuer).toBe(ISSUER)
|
||||
// The stamp is persisted, not just returned.
|
||||
const entry = await store.getAuthForUrl(serverId, SERVER_URL)
|
||||
expect(entry?.tokens?.issuer).toBe(ISSUER)
|
||||
})
|
||||
|
||||
it('does not stamp an issuer when no discovery snapshot is available', async () => {
|
||||
const provider = makeProvider()
|
||||
await provider.saveClientInformation({ client_id: 'c2' } as never)
|
||||
const info = await makeProvider().clientInformation()
|
||||
expect((info as { issuer?: string }).issuer).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,503 @@
|
||||
/**
|
||||
* MCP OAuth Provider (DB-backed)
|
||||
*
|
||||
* Implementation of the MCP SDK's OAuthClientProvider interface. Adapted from
|
||||
* pi-mcp-adapter's mcp-oauth-provider.ts, with two differences:
|
||||
* 1. All persisted state (tokens, client info, PKCE verifier, discovery
|
||||
* state, CSRF state) is stored in the DB via McpDbStore instead of the OS
|
||||
* keyring/files, so the flow survives across HTTP requests and processes.
|
||||
* 2. The redirect URI is shumai's own Hono callback endpoint
|
||||
* (`${MCP_OAUTH_REDIRECT_BASE_URL}/api/mcp/oauth/callback`) instead of a
|
||||
* localhost callback server.
|
||||
*/
|
||||
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
// The OAuth wire format (RFC 6749 / OAuth 2.1 client metadata) uses snake_case
|
||||
// field names (client_id, access_token, grant_type, ...). These are dictated by
|
||||
// the OAuth protocol and the MCP SDK's OAuthClientProvider interfaces, so they
|
||||
// cannot be renamed to camelCase.
|
||||
|
||||
import {
|
||||
type AddClientAuthentication,
|
||||
type OAuthClientProvider,
|
||||
type OAuthClientInformationMixed,
|
||||
type OAuthClientMetadata,
|
||||
type OAuthDiscoveryState,
|
||||
type OAuthTokens,
|
||||
} from '@modelcontextprotocol/client'
|
||||
import type { McpDbStore, AuthEntry, StoredClientInfo, StoredTokens } from './mcp-db-store'
|
||||
|
||||
type IssuerBoundClientInformation = OAuthClientInformationMixed & { issuer?: string }
|
||||
type IssuerBoundTokens = OAuthTokens & { issuer?: string }
|
||||
|
||||
function issuersMatch(first: string, second: string): boolean {
|
||||
return (
|
||||
first === second ||
|
||||
(first.endsWith('/') && first.slice(0, -1) === second) ||
|
||||
(second.endsWith('/') && second.slice(0, -1) === first)
|
||||
)
|
||||
}
|
||||
|
||||
export function getOauthRedirectBaseUrl(): string {
|
||||
return (
|
||||
process.env.MCP_OAUTH_REDIRECT_BASE_URL?.trim() || process.env.BETTER_AUTH_URL?.trim() || ''
|
||||
)
|
||||
}
|
||||
|
||||
/** The default redirect URI used when the server config does not set one. */
|
||||
export function getDefaultOauthRedirectUri(): string | undefined {
|
||||
const base = getOauthRedirectBaseUrl()
|
||||
if (!base) return undefined
|
||||
return `${base.replace(/\/$/, '')}/api/mcp/oauth/callback`
|
||||
}
|
||||
|
||||
/** Configuration options for OAuth. */
|
||||
export interface McpOauthConfig {
|
||||
grantType?: 'authorization_code' | 'client_credentials'
|
||||
clientId?: string
|
||||
clientSecret?: string
|
||||
scope?: string
|
||||
authorizationParams?: Record<string, string>
|
||||
redirectUri?: string
|
||||
clientName?: string
|
||||
clientUri?: string
|
||||
skipIssuerMetadataValidation?: boolean
|
||||
}
|
||||
|
||||
const reservedAuthorizationParams = new Set([
|
||||
'client_id',
|
||||
'code_challenge',
|
||||
'code_challenge_method',
|
||||
'redirect_uri',
|
||||
'resource',
|
||||
'response_type',
|
||||
'scope',
|
||||
'state',
|
||||
])
|
||||
|
||||
function addAuthorizationParams(
|
||||
authorizationUrl: URL,
|
||||
params: Record<string, string> | undefined,
|
||||
): URL {
|
||||
if (!params) return authorizationUrl
|
||||
const nextUrl = new URL(authorizationUrl.toString())
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (reservedAuthorizationParams.has(key) || nextUrl.searchParams.has(key)) {
|
||||
throw new Error(
|
||||
`OAuth authorizationParams.${key} cannot override an authorization flow parameter`,
|
||||
)
|
||||
}
|
||||
nextUrl.searchParams.set(key, value)
|
||||
}
|
||||
return nextUrl
|
||||
}
|
||||
|
||||
/** Callbacks for OAuth flow interactions. */
|
||||
export interface McpOauthCallbacks {
|
||||
onRedirect: (url: URL) => void | Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* OAuth provider implementation for MCP servers backed by the DB store.
|
||||
*/
|
||||
export class McpOauthProvider implements OAuthClientProvider {
|
||||
private readonly redirectUrlSnapshot: string | undefined
|
||||
private active = true
|
||||
private flowIssuerMismatch = false
|
||||
|
||||
constructor(
|
||||
private serverId: string,
|
||||
private serverUrl: string,
|
||||
private config: McpOauthConfig,
|
||||
private callbacks: McpOauthCallbacks,
|
||||
private store: McpDbStore,
|
||||
) {
|
||||
this.redirectUrlSnapshot =
|
||||
config.grantType === 'client_credentials'
|
||||
? undefined
|
||||
: (config.redirectUri ?? getDefaultOauthRedirectUri())
|
||||
}
|
||||
|
||||
private get usesClientCredentials(): boolean {
|
||||
return this.config.grantType === 'client_credentials'
|
||||
}
|
||||
|
||||
deactivate(): void {
|
||||
this.active = false
|
||||
}
|
||||
|
||||
private throwIfInactive(): void {
|
||||
if (!this.active) throw new Error('OAuth flow is no longer active')
|
||||
}
|
||||
|
||||
private assertStoredIssuerBindings(
|
||||
entry: AuthEntry | undefined,
|
||||
issuer: string | undefined,
|
||||
): void {
|
||||
if (this.flowIssuerMismatch) {
|
||||
throw new Error(
|
||||
`OAuth authorization server issuer changed; clear credentials before authenticating again`,
|
||||
)
|
||||
}
|
||||
if (!entry || !issuer) return
|
||||
|
||||
const storedIssuers = [entry.clientInfo?.issuer, entry.tokens?.issuer].filter(
|
||||
(storedIssuer): storedIssuer is string => storedIssuer !== undefined,
|
||||
)
|
||||
if (storedIssuers.some((storedIssuer) => !issuersMatch(storedIssuer, issuer))) {
|
||||
this.flowIssuerMismatch = true
|
||||
throw new Error(
|
||||
`OAuth authorization server issuer changed; clear credentials before authenticating again`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The redirect URL for OAuth callbacks. */
|
||||
get redirectUrl(): string | undefined {
|
||||
return this.redirectUrlSnapshot
|
||||
}
|
||||
|
||||
/**
|
||||
* SEP-2352 issuer of the authorization server from the discovery snapshot
|
||||
* persisted by saveDiscoveryState (available on both the start and callback
|
||||
* legs thanks to the DB-backed store).
|
||||
*/
|
||||
private async getDiscoveredIssuer(): Promise<string | undefined> {
|
||||
const snapshot = await this.store.getDiscoverySnapshot(this.serverId)
|
||||
if (!snapshot) return undefined
|
||||
const metadata = snapshot['authorizationServerMetadata'] as { issuer?: string } | undefined
|
||||
const issuer = metadata?.issuer
|
||||
if (typeof issuer === 'string' && issuer.length > 0) return issuer
|
||||
const serverUrl = snapshot['authorizationServerUrl']
|
||||
return typeof serverUrl === 'string' && serverUrl.length > 0 ? serverUrl : undefined
|
||||
}
|
||||
|
||||
/** Client metadata for dynamic registration. */
|
||||
get clientMetadata(): OAuthClientMetadata {
|
||||
if (this.usesClientCredentials) {
|
||||
return {
|
||||
client_name: this.config.clientName ?? 'Shumai',
|
||||
client_uri: this.config.clientUri ?? 'https://shumai.ai',
|
||||
redirect_uris: [],
|
||||
grant_types: ['client_credentials'],
|
||||
token_endpoint_auth_method: this.config.clientSecret ? 'client_secret_post' : 'none',
|
||||
}
|
||||
}
|
||||
|
||||
const redirectUrl = this.redirectUrl
|
||||
if (!redirectUrl) {
|
||||
throw new Error(
|
||||
'redirectUrl is required for authorization_code flow. Set MCP_OAUTH_REDIRECT_BASE_URL or BETTER_AUTH_URL, or configure authConfig.oauth.redirectUri.',
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
redirect_uris: [redirectUrl],
|
||||
client_name: this.config.clientName ?? 'Shumai',
|
||||
client_uri: this.config.clientUri ?? 'https://shumai.ai',
|
||||
grant_types: ['authorization_code', 'refresh_token'],
|
||||
response_types: ['code'],
|
||||
token_endpoint_auth_method: this.config.clientSecret ? 'client_secret_post' : 'none',
|
||||
...(this.config.scope !== undefined ? { scope: this.config.scope } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** Get client information (pre-registered or dynamically registered). */
|
||||
async clientInformation(): Promise<OAuthClientInformationMixed | undefined> {
|
||||
const stored = await this.store.getAuthForUrl(this.serverId, this.serverUrl)
|
||||
this.assertStoredIssuerBindings(stored, undefined)
|
||||
|
||||
// Config-first (pre-registered client). The secret stays in config.
|
||||
if (this.config.clientId) {
|
||||
const storedClient =
|
||||
stored?.clientInfo?.clientId === this.config.clientId ? stored.clientInfo : undefined
|
||||
const issuer = await this.getDiscoveredIssuer()
|
||||
if (storedClient?.issuer === undefined || storedClient.configPreRegistered !== true) {
|
||||
await this.store.updateClientInfo(
|
||||
this.serverId,
|
||||
{
|
||||
clientId: this.config.clientId,
|
||||
configPreRegistered: true,
|
||||
...(issuer !== undefined ? { issuer } : {}),
|
||||
},
|
||||
this.serverUrl,
|
||||
)
|
||||
}
|
||||
return {
|
||||
client_id: this.config.clientId,
|
||||
client_secret: this.config.clientSecret,
|
||||
...(issuer !== undefined ? { issuer } : {}),
|
||||
} as IssuerBoundClientInformation
|
||||
}
|
||||
|
||||
const clientInfo = stored?.clientInfo
|
||||
if (clientInfo) {
|
||||
const isConfigStub =
|
||||
clientInfo.configPreRegistered === true ||
|
||||
(clientInfo.clientSecret === undefined &&
|
||||
clientInfo.clientIdIssuedAt === undefined &&
|
||||
clientInfo.clientSecretExpiresAt === undefined &&
|
||||
clientInfo.redirectUris === undefined)
|
||||
if (isConfigStub) return undefined
|
||||
if (
|
||||
clientInfo.clientSecretExpiresAt &&
|
||||
clientInfo.clientSecretExpiresAt < Date.now() / 1000
|
||||
) {
|
||||
return undefined
|
||||
}
|
||||
// SEP-2352: backfill a missing issuer stamp (pre-upgrade / stale storage)
|
||||
// from the discovery snapshot, persisting it so later reads are isolated.
|
||||
const issuer = await this.getDiscoveredIssuer()
|
||||
if (issuer !== undefined && clientInfo.issuer === undefined) {
|
||||
const stamped: StoredClientInfo = { ...clientInfo, issuer }
|
||||
await this.store.updateClientInfo(this.serverId, stamped, this.serverUrl)
|
||||
clientInfo.issuer = issuer
|
||||
}
|
||||
return {
|
||||
client_id: clientInfo.clientId,
|
||||
client_secret: clientInfo.clientSecret,
|
||||
...(clientInfo.clientIdIssuedAt !== undefined
|
||||
? { client_id_issued_at: clientInfo.clientIdIssuedAt }
|
||||
: {}),
|
||||
...(clientInfo.clientSecretExpiresAt !== undefined
|
||||
? { client_secret_expires_at: clientInfo.clientSecretExpiresAt }
|
||||
: {}),
|
||||
...(clientInfo.redirectUris !== undefined
|
||||
? { redirect_uris: clientInfo.redirectUris }
|
||||
: {}),
|
||||
...(clientInfo.issuer !== undefined ? { issuer: clientInfo.issuer } : {}),
|
||||
} as IssuerBoundClientInformation
|
||||
}
|
||||
|
||||
// No client info - triggers dynamic registration.
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Save client information from dynamic registration. */
|
||||
async saveClientInformation(info: OAuthClientInformationMixed): Promise<void> {
|
||||
this.throwIfInactive()
|
||||
if (this.config.clientId && info.client_id === this.config.clientId) {
|
||||
await this.store.updateClientInfo(
|
||||
this.serverId,
|
||||
{ clientId: info.client_id, configPreRegistered: true },
|
||||
this.serverUrl,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const redirectUris =
|
||||
('redirect_uris' in info ? info.redirect_uris : undefined) ??
|
||||
(this.redirectUrl ? [this.redirectUrl] : undefined)
|
||||
const issuer = await this.getDiscoveredIssuer()
|
||||
const clientInfo: StoredClientInfo = {
|
||||
clientId: info.client_id,
|
||||
...(info.client_secret !== undefined ? { clientSecret: info.client_secret } : {}),
|
||||
...(info.client_id_issued_at !== undefined
|
||||
? { clientIdIssuedAt: info.client_id_issued_at }
|
||||
: {}),
|
||||
...(info.client_secret_expires_at !== undefined
|
||||
? { clientSecretExpiresAt: info.client_secret_expires_at }
|
||||
: {}),
|
||||
...(redirectUris !== undefined ? { redirectUris } : {}),
|
||||
...(issuer !== undefined ? { issuer } : {}),
|
||||
}
|
||||
await this.store.updateClientInfo(this.serverId, clientInfo, this.serverUrl)
|
||||
}
|
||||
|
||||
/** Get stored OAuth tokens. */
|
||||
async tokens(): Promise<OAuthTokens | undefined> {
|
||||
const entry = await this.store.getAuthForUrl(this.serverId, this.serverUrl)
|
||||
if (!entry?.tokens) return undefined
|
||||
this.assertStoredIssuerBindings(entry, undefined)
|
||||
|
||||
// SEP-2352: backfill a missing issuer stamp from the discovery snapshot so
|
||||
// isolation stays active for pre-existing credentials.
|
||||
const issuer = await this.getDiscoveredIssuer()
|
||||
if (issuer !== undefined && entry.tokens.issuer === undefined) {
|
||||
const stamped: StoredTokens = { ...entry.tokens, issuer }
|
||||
await this.store.updateTokens(this.serverId, stamped, this.serverUrl)
|
||||
entry.tokens = stamped
|
||||
}
|
||||
|
||||
return {
|
||||
access_token: entry.tokens.accessToken,
|
||||
token_type: 'Bearer',
|
||||
refresh_token: entry.tokens.refreshToken,
|
||||
expires_in: entry.tokens.expiresAt
|
||||
? Math.max(0, Math.floor(entry.tokens.expiresAt - Date.now() / 1000))
|
||||
: undefined,
|
||||
scope: entry.tokens.scope,
|
||||
...(entry.tokens.issuer !== undefined ? { issuer: entry.tokens.issuer } : {}),
|
||||
} as IssuerBoundTokens
|
||||
}
|
||||
|
||||
/** Save OAuth tokens. */
|
||||
async saveTokens(tokens: OAuthTokens): Promise<void> {
|
||||
const issuer = await this.getDiscoveredIssuer()
|
||||
const storedTokens: StoredTokens = {
|
||||
accessToken: tokens.access_token,
|
||||
...(tokens.refresh_token !== undefined ? { refreshToken: tokens.refresh_token } : {}),
|
||||
...(tokens.expires_in !== undefined
|
||||
? { expiresAt: Date.now() / 1000 + tokens.expires_in }
|
||||
: {}),
|
||||
...(tokens.scope !== undefined ? { scope: tokens.scope } : {}),
|
||||
...(issuer !== undefined ? { issuer } : {}),
|
||||
}
|
||||
this.throwIfInactive()
|
||||
await this.store.updateTokens(this.serverId, storedTokens, this.serverUrl)
|
||||
}
|
||||
|
||||
/** Redirect the user to the authorization URL. */
|
||||
async redirectToAuthorization(authorizationUrl: URL): Promise<void> {
|
||||
if (this.usesClientCredentials) {
|
||||
throw new Error('redirectToAuthorization is not used for client_credentials flow')
|
||||
}
|
||||
this.throwIfInactive()
|
||||
await this.callbacks.onRedirect(
|
||||
addAuthorizationParams(authorizationUrl, this.config.authorizationParams),
|
||||
)
|
||||
}
|
||||
|
||||
/** Save the PKCE code verifier (persisted so the callback leg can use it). */
|
||||
async saveCodeVerifier(codeVerifier: string): Promise<void> {
|
||||
this.throwIfInactive()
|
||||
await this.store.updateCodeVerifier(this.serverId, codeVerifier, this.serverUrl)
|
||||
}
|
||||
|
||||
async codeVerifier(): Promise<string> {
|
||||
if (this.usesClientCredentials) {
|
||||
throw new Error('codeVerifier is not used for client_credentials flow')
|
||||
}
|
||||
this.throwIfInactive()
|
||||
const entry = await this.store.getAuthForUrl(this.serverId, this.serverUrl)
|
||||
if (!entry?.codeVerifier) {
|
||||
throw new Error(`No code verifier saved for MCP server`)
|
||||
}
|
||||
return entry.codeVerifier
|
||||
}
|
||||
|
||||
/** Keep discovery with the in-flight PKCE verifier. */
|
||||
async saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {
|
||||
this.throwIfInactive()
|
||||
// Persisted inside the pendingAuth row by mcpService after startAuth; also
|
||||
// kept on the credential row so the callback leg can re-read it.
|
||||
await this.store.saveDiscoverySnapshot(this.serverId, this.serverUrl, state)
|
||||
}
|
||||
|
||||
async discoveryState(): Promise<OAuthDiscoveryState | undefined> {
|
||||
this.throwIfInactive()
|
||||
const snapshot = await this.store.getDiscoverySnapshot(this.serverId)
|
||||
return snapshot as unknown as OAuthDiscoveryState | undefined
|
||||
}
|
||||
|
||||
/** Save the OAuth state parameter for CSRF protection. */
|
||||
async saveState(state: string): Promise<void> {
|
||||
this.throwIfInactive()
|
||||
await this.store.updateOauthState(this.serverId, state, this.serverUrl)
|
||||
}
|
||||
|
||||
async state(): Promise<string> {
|
||||
if (this.usesClientCredentials) {
|
||||
throw new Error('state is not used for client_credentials flow')
|
||||
}
|
||||
this.throwIfInactive()
|
||||
let state = await this.store.getOauthState(this.serverId)
|
||||
if (!state) {
|
||||
state = Array.from(crypto.getRandomValues(new Uint8Array(32)))
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
await this.store.updateOauthState(this.serverId, state, this.serverUrl)
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
/** Invalidate credentials when authentication fails. */
|
||||
async invalidateCredentials(
|
||||
type: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery',
|
||||
): Promise<void> {
|
||||
this.throwIfInactive()
|
||||
switch (type) {
|
||||
case 'all':
|
||||
this.flowIssuerMismatch = false
|
||||
await this.store.clearAllCredentials(this.serverId)
|
||||
break
|
||||
case 'client':
|
||||
await this.store.clearClientInfo(this.serverId)
|
||||
break
|
||||
case 'tokens':
|
||||
await this.store.clearTokens(this.serverId)
|
||||
break
|
||||
case 'verifier':
|
||||
await this.store.clearCodeVerifier(this.serverId)
|
||||
break
|
||||
case 'discovery':
|
||||
await this.store.clearDiscoverySnapshot(this.serverId)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds configured authorization-code scope and client authentication. */
|
||||
addClientAuthentication: AddClientAuthentication = async (headers, params, _url, metadata) => {
|
||||
this.throwIfInactive()
|
||||
if (
|
||||
params.get('grant_type') === 'authorization_code' &&
|
||||
!params.has('scope') &&
|
||||
this.config.scope
|
||||
) {
|
||||
params.set('scope', this.config.scope)
|
||||
}
|
||||
|
||||
const clientInfo = await this.clientInformation()
|
||||
this.throwIfInactive()
|
||||
if (!clientInfo) return
|
||||
|
||||
const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? []
|
||||
const hasClientSecret = clientInfo.client_secret !== undefined
|
||||
let authMethod: 'client_secret_basic' | 'client_secret_post' | 'none'
|
||||
|
||||
if (supportedMethods.length === 0) {
|
||||
authMethod = hasClientSecret ? 'client_secret_post' : 'none'
|
||||
} else if (hasClientSecret && supportedMethods.includes('client_secret_basic')) {
|
||||
authMethod = 'client_secret_basic'
|
||||
} else if (hasClientSecret && supportedMethods.includes('client_secret_post')) {
|
||||
authMethod = 'client_secret_post'
|
||||
} else if (supportedMethods.includes('none')) {
|
||||
authMethod = 'none'
|
||||
} else {
|
||||
authMethod = hasClientSecret ? 'client_secret_post' : 'none'
|
||||
}
|
||||
|
||||
if (authMethod === 'client_secret_basic') {
|
||||
if (!clientInfo.client_secret) {
|
||||
throw new Error('client_secret_basic authentication requires a client_secret')
|
||||
}
|
||||
headers.set(
|
||||
'Authorization',
|
||||
`Basic ${Buffer.from(`${clientInfo.client_id}:${clientInfo.client_secret}`).toString('base64')}`,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (!params.has('client_id')) {
|
||||
params.set('client_id', clientInfo.client_id)
|
||||
}
|
||||
if (
|
||||
authMethod === 'client_secret_post' &&
|
||||
clientInfo.client_secret &&
|
||||
!params.has('client_secret')
|
||||
) {
|
||||
params.set('client_secret', clientInfo.client_secret)
|
||||
}
|
||||
}
|
||||
|
||||
prepareTokenRequest(scope?: string): URLSearchParams | undefined {
|
||||
if (!this.usesClientCredentials) return undefined
|
||||
|
||||
const params = new URLSearchParams({ grant_type: 'client_credentials' })
|
||||
const requestedScope = scope ?? this.config.scope
|
||||
if (requestedScope) {
|
||||
params.set('scope', requestedScope)
|
||||
}
|
||||
return params
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
/**
|
||||
* MCP proxy tool — the single `mcp` AgentTool registered per agent.
|
||||
*
|
||||
* One tool in the LLM context multiplexes all of the agent's assigned MCP
|
||||
* servers via `{ server, tool, args, search, describe, connect, action }`.
|
||||
* Mode precedence: action > tool(call) > connect > describe > search >
|
||||
* server(list) > status.
|
||||
*/
|
||||
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
|
||||
import type { McpToolRegistry, ToolMetadata } from './mcp-tool-registry'
|
||||
import { formatSchema } from './mcp-tool-schema'
|
||||
|
||||
type ProxyToolResult = AgentToolResult<Record<string, unknown>>
|
||||
|
||||
/** Truncated instructions head baked into the proxy tool description (L1). */
|
||||
const INSTRUCTIONS_SNIPPET_LENGTH = 150
|
||||
/** Longer instructions preview appended to server listings (L2). */
|
||||
const INSTRUCTIONS_PREVIEW_LENGTH = 300
|
||||
|
||||
/** Truncate at a word boundary (mirrors pi-mcp-adapter's truncateAtWord). */
|
||||
function truncateInstruction(text: string, target: number): string {
|
||||
if (!text || text.length <= target) return text
|
||||
const truncated = text.slice(0, target)
|
||||
const lastSpace = truncated.lastIndexOf(' ')
|
||||
if (lastSpace > target * 0.6) {
|
||||
return `${truncated.slice(0, lastSpace)}...`
|
||||
}
|
||||
return `${truncated}...`
|
||||
}
|
||||
|
||||
export interface ProxyServerInfo {
|
||||
id: string
|
||||
name: string
|
||||
toolCount: number
|
||||
status: string
|
||||
/** Self-reported server usage instructions (empty when the server provides none). */
|
||||
instructions?: string
|
||||
}
|
||||
|
||||
export type ConnectionOutcome =
|
||||
| { status: 'connected' }
|
||||
| { status: 'needs-auth' }
|
||||
| { status: 'error'; message: string }
|
||||
|
||||
export interface CallToolOutcome {
|
||||
ok: boolean
|
||||
content: AgentToolResult<Record<string, unknown>>['content']
|
||||
}
|
||||
|
||||
export interface McpProxyToolContext {
|
||||
teamId: string
|
||||
userId?: string
|
||||
servers: ProxyServerInfo[]
|
||||
serverNameById: Map<string, string>
|
||||
serverIdByName: Map<string, string>
|
||||
registry: McpToolRegistry
|
||||
/** Resolve the server id for a (possibly prefixed) tool name. */
|
||||
resolveServerForTool?(toolName: string): string | undefined
|
||||
ensureConnected(serverId: string): Promise<ConnectionOutcome>
|
||||
callTool(
|
||||
serverId: string,
|
||||
toolName: string,
|
||||
args: Record<string, unknown>,
|
||||
): Promise<CallToolOutcome>
|
||||
authStatus(serverId: string): Promise<string>
|
||||
startAuth(
|
||||
serverId: string,
|
||||
): Promise<{ authorizationUrl?: string; alreadyAuthenticated?: boolean }>
|
||||
/** Server-reported usage instructions (DB cache, works without a live connection). */
|
||||
getInstructions(serverId: string): Promise<string | null>
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a tool, lazily connecting the owning server first when the registry
|
||||
* has no cached metadata for it yet (first call in a fresh process).
|
||||
*/
|
||||
async function resolveToolWithLazyConnect(
|
||||
ctx: McpProxyToolContext,
|
||||
toolName: string,
|
||||
serverId?: string,
|
||||
): Promise<{ ok: true; serverId: string; tool: ToolMetadata } | { ok: false }> {
|
||||
const firstResolve = ctx.registry.findTool(toolName, serverId)
|
||||
if (firstResolve) return { ok: true, ...firstResolve }
|
||||
|
||||
const targetServerId = serverId ?? ctx.resolveServerForTool?.(toolName)
|
||||
if (!targetServerId) return { ok: false }
|
||||
|
||||
const outcome = await ctx.ensureConnected(targetServerId)
|
||||
if (outcome.status !== 'connected') return { ok: false }
|
||||
|
||||
const retried = ctx.registry.findTool(toolName, targetServerId)
|
||||
if (!retried) return { ok: false }
|
||||
return { ok: true, ...retried }
|
||||
}
|
||||
|
||||
const proxyToolSchema = Type.Object(
|
||||
{
|
||||
server: Type.Optional(
|
||||
Type.String({
|
||||
description:
|
||||
'The MCP server name. Required to call a tool, list a server, or start auth. Omit to search across all servers.',
|
||||
}),
|
||||
),
|
||||
tool: Type.Optional(
|
||||
Type.String({
|
||||
description:
|
||||
'The name of the tool to call on the server (prefixed "{server}_{tool}" or the original tool name).',
|
||||
}),
|
||||
),
|
||||
args: Type.Optional(
|
||||
Type.Unknown({
|
||||
description: 'Arguments for the tool call: either a JSON object or a JSON-encoded string.',
|
||||
}),
|
||||
),
|
||||
describe: Type.Optional(
|
||||
Type.String({
|
||||
description: 'Tool name to show its full parameter schema.',
|
||||
}),
|
||||
),
|
||||
instructions: Type.Optional(
|
||||
Type.String({
|
||||
description: 'Server name to show its full usage instructions.',
|
||||
}),
|
||||
),
|
||||
search: Type.Optional(
|
||||
Type.String({
|
||||
description: 'Search query to find tools across servers (camelCase/snake_case aware).',
|
||||
}),
|
||||
),
|
||||
includeSchemas: Type.Optional(
|
||||
Type.Boolean({
|
||||
description: 'Include parameter schemas in search results (default true).',
|
||||
}),
|
||||
),
|
||||
limit: Type.Optional(Type.Number({ description: 'Max results for search/list (default 12).' })),
|
||||
offset: Type.Optional(Type.Number({ description: 'Pagination offset for search/list.' })),
|
||||
action: Type.Optional(
|
||||
Type.Union([Type.Literal('status'), Type.Literal('auth-start')], {
|
||||
description:
|
||||
'"status" shows connection/auth state for all servers; "auth-start" begins OAuth for `server` (the user completes it in a browser, then you poll status).',
|
||||
}),
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
)
|
||||
|
||||
function parseArgs(raw: unknown): Record<string, unknown> {
|
||||
if (raw === undefined || raw === null) return {}
|
||||
if (typeof raw === 'string') {
|
||||
const trimmed = raw.trim()
|
||||
if (!trimmed) return {}
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed)
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed as Record<string, unknown>
|
||||
}
|
||||
return { value: parsed }
|
||||
} catch {
|
||||
return { value: raw }
|
||||
}
|
||||
}
|
||||
if (typeof raw === 'object' && !Array.isArray(raw)) {
|
||||
return raw as Record<string, unknown>
|
||||
}
|
||||
return { value: raw }
|
||||
}
|
||||
|
||||
function contentText(text: string): ProxyToolResult {
|
||||
return { content: [{ type: 'text', text }], details: {} }
|
||||
}
|
||||
|
||||
/** Transform MCP content blocks into model content blocks. */
|
||||
export function transformMcpContent(
|
||||
content: Array<{
|
||||
type: string
|
||||
text?: string
|
||||
data?: string
|
||||
mimeType?: string
|
||||
resource?: unknown
|
||||
uri?: string
|
||||
name?: string
|
||||
}>,
|
||||
): AgentToolResult<Record<string, unknown>>['content'] {
|
||||
return content.map((c) => {
|
||||
if (c.type === 'text') {
|
||||
return { type: 'text', text: c.text ?? '' }
|
||||
}
|
||||
if (c.type === 'image') {
|
||||
return { type: 'image', data: c.data ?? '', mimeType: c.mimeType ?? 'image/png' }
|
||||
}
|
||||
if (c.type === 'resource') {
|
||||
const res = (c.resource ?? {}) as { uri?: string; text?: string }
|
||||
const resourceUri = res.uri ?? '(no URI)'
|
||||
const resourceContent = res.text ?? (c.resource ? JSON.stringify(c.resource) : '(no content)')
|
||||
return { type: 'text', text: `[Resource: ${resourceUri}]\n${resourceContent}` }
|
||||
}
|
||||
if (c.type === 'resource_link') {
|
||||
const linkName = c.name ?? c.uri ?? 'unknown'
|
||||
const linkUri = c.uri ?? '(no URI)'
|
||||
return { type: 'text', text: `[Resource Link: ${linkName}]\nURI: ${linkUri}` }
|
||||
}
|
||||
if (c.type === 'audio') {
|
||||
return { type: 'text', text: `[Audio content: ${c.mimeType ?? 'audio/*'}]` }
|
||||
}
|
||||
return { type: 'text', text: JSON.stringify(c) }
|
||||
})
|
||||
}
|
||||
|
||||
function renderToolShape(tool: ToolMetadata, indent = ''): string {
|
||||
if (!tool.inputSchema) return 'No parameters defined.'
|
||||
const schemaText = formatSchema(tool.inputSchema, indent)
|
||||
return `Parameters:\n${schemaText}`
|
||||
}
|
||||
|
||||
function notFoundResult(
|
||||
toolName: string,
|
||||
suggestions: string[],
|
||||
serverName?: string,
|
||||
): ProxyToolResult {
|
||||
let msg = `Tool "${toolName}" not found.`
|
||||
if (serverName) {
|
||||
msg += ` Use mcp({ server: "${serverName}" }) to list its tools or mcp({ search: "..." }) to search.`
|
||||
} else {
|
||||
msg += ` Use mcp({ search: "..." }) to search.`
|
||||
}
|
||||
if (suggestions.length > 0) {
|
||||
msg += ` Did you mean: ${suggestions.join(', ')}`
|
||||
}
|
||||
return contentText(msg)
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the dynamic proxy tool description (server list + tool counts + usage).
|
||||
* Servers with instructions surface a truncated head so the model sees the
|
||||
* guidance without making a call; full text is available on demand.
|
||||
*/
|
||||
export function buildProxyDescription(servers: ProxyServerInfo[]): string {
|
||||
const lines: string[] = []
|
||||
lines.push('Call MCP (Model Context Protocol) tools exposed by the configured servers.')
|
||||
lines.push('')
|
||||
lines.push('Servers:')
|
||||
if (servers.length === 0) {
|
||||
lines.push(' (none assigned)')
|
||||
} else {
|
||||
for (const s of servers) {
|
||||
lines.push(` - ${s.name} (${s.toolCount} tools, status: ${s.status})`)
|
||||
}
|
||||
}
|
||||
lines.push('')
|
||||
lines.push('Usage:')
|
||||
lines.push(' - mcp({}) → connection/auth status of all servers')
|
||||
lines.push(' - mcp({ server: "name" }) → list that server\'s tools')
|
||||
lines.push(' - mcp({ search: "query" }) → search tools across servers')
|
||||
lines.push(' - mcp({ describe: "tool" }) → show one tool\'s parameter schema')
|
||||
lines.push(' - mcp({ server: "name", tool: "tool_name", args: {...} }) → call a tool')
|
||||
lines.push(' - mcp({ instructions: "name" }) → show full server usage instructions')
|
||||
lines.push(' - mcp({ action: "auth-start", server: "name" }) → start OAuth for a server')
|
||||
lines.push('')
|
||||
const instructionLines: string[] = []
|
||||
for (const s of servers) {
|
||||
if (!s.instructions || s.instructions.trim() === '') continue
|
||||
const snippet = truncateInstruction(
|
||||
s.instructions.replace(/\s+/g, ' ').trim(),
|
||||
INSTRUCTIONS_SNIPPET_LENGTH,
|
||||
)
|
||||
instructionLines.push(` - ${s.name}: ${snippet}`)
|
||||
}
|
||||
if (instructionLines.length > 0) {
|
||||
lines.push('Server instructions (truncated — full text via mcp({ instructions: "name" })):')
|
||||
lines.push(...instructionLines)
|
||||
lines.push('')
|
||||
}
|
||||
lines.push(
|
||||
'Tool names are prefixed "{server}_{tool}" (dots replaced by underscores). You may pass either the prefixed or the original name. ' +
|
||||
'If a call fails with "needs auth", tell the user to connect the server in Settings → MCP.',
|
||||
)
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a server's tool listing with the L2 instructions preview appended
|
||||
* (mirrors pi-mcp-adapter's mcp({ server }) output). Shared by the `server`
|
||||
* list mode and the `connect` mode.
|
||||
*/
|
||||
function renderServerListing(
|
||||
serverName: string,
|
||||
tools: ToolMetadata[],
|
||||
instructions: string | null,
|
||||
): string {
|
||||
const lines = [`${serverName} (${tools.length} tools):`, '']
|
||||
for (const t of tools) {
|
||||
lines.push(`- ${t.name}${t.description ? ` - ${t.description.slice(0, 60)}` : ''}`)
|
||||
}
|
||||
if (instructions && instructions.trim() !== '') {
|
||||
const preview = truncateInstruction(instructions, INSTRUCTIONS_PREVIEW_LENGTH)
|
||||
lines.push('', 'Server instructions:', preview)
|
||||
if (preview !== instructions) {
|
||||
lines.push(`Use mcp({ instructions: "${serverName}" }) for the full text.`)
|
||||
}
|
||||
}
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the single `mcp` proxy AgentTool for a team/session.
|
||||
*/
|
||||
export function buildProxyTool(ctx: McpProxyToolContext): AgentTool<typeof proxyToolSchema> {
|
||||
return {
|
||||
name: 'mcp',
|
||||
label: 'MCP Tools',
|
||||
description: buildProxyDescription(ctx.servers),
|
||||
parameters: proxyToolSchema,
|
||||
execute: async (_toolCallId, params): Promise<ProxyToolResult> => {
|
||||
const action = params.action
|
||||
const server = params.server
|
||||
const tool = params.tool
|
||||
const search = params.search
|
||||
const describe = params.describe
|
||||
const instructions = params.instructions
|
||||
const limit = params.limit ?? 12
|
||||
const offset = params.offset ?? 0
|
||||
const includeSchemas = params.includeSchemas !== false
|
||||
|
||||
// 1. action: status / auth-start
|
||||
if (action === 'status') {
|
||||
const lines: string[] = ['MCP status:']
|
||||
for (const s of ctx.servers) {
|
||||
const auth = await ctx.authStatus(s.id)
|
||||
lines.push(` - ${s.name}: ${s.status} (${s.toolCount} tools, auth: ${auth})`)
|
||||
}
|
||||
lines.push('')
|
||||
lines.push('mcp({ server: "name" }) to list tools, mcp({ search: "..." }) to search')
|
||||
return contentText(lines.join('\n'))
|
||||
}
|
||||
if (action === 'auth-start') {
|
||||
const serverId = server ? ctx.serverIdByName.get(server) : undefined
|
||||
if (!serverId) {
|
||||
return contentText(
|
||||
`Server "${server ?? ''}" not found. Use mcp({ action: "status" }) to see available servers.`,
|
||||
)
|
||||
}
|
||||
const result = await ctx.startAuth(serverId)
|
||||
if (result.alreadyAuthenticated) {
|
||||
return contentText(`OAuth authentication already complete for "${server}".`)
|
||||
}
|
||||
if (!result.authorizationUrl) {
|
||||
return contentText(
|
||||
`OAuth authentication could not be started for "${server}". Ask an admin to check Settings → MCP.`,
|
||||
)
|
||||
}
|
||||
return contentText(
|
||||
`OAuth authentication required for "${server}". An admin must open this URL in a browser and approve access:\n\n${result.authorizationUrl}\n\nAfter approving, the browser redirects back to shumai automatically. Then poll mcp({ action: "status", server: "${server}" }) until it shows connected.`,
|
||||
)
|
||||
}
|
||||
|
||||
// 2. tool call
|
||||
if (tool) {
|
||||
const serverId = server ? ctx.serverIdByName.get(server) : undefined
|
||||
if (server && !serverId) {
|
||||
return contentText(
|
||||
`Server "${server}" not found. Use mcp({ action: "status" }) to see available servers.`,
|
||||
)
|
||||
}
|
||||
const resolved = await resolveToolWithLazyConnect(ctx, tool, serverId)
|
||||
if (!resolved.ok) {
|
||||
const suggestions = ctx.registry.rankSuggestions(tool, 5, ctx.serverNameById).slice(0, 5)
|
||||
return notFoundResult(tool, suggestions, server)
|
||||
}
|
||||
const outcome = await ctx.callTool(
|
||||
resolved.serverId,
|
||||
resolved.tool.originalName,
|
||||
parseArgs(params.args),
|
||||
)
|
||||
if (outcome.ok) {
|
||||
return { content: outcome.content, details: {} }
|
||||
}
|
||||
return {
|
||||
content: outcome.content,
|
||||
details: { error: 'tool_call_failed', tool, server: resolved.serverId },
|
||||
}
|
||||
}
|
||||
|
||||
// 4. describe
|
||||
if (describe) {
|
||||
const resolved = ctx.registry.findTool(
|
||||
describe,
|
||||
server ? ctx.serverIdByName.get(server) : undefined,
|
||||
)
|
||||
if (!resolved) {
|
||||
const suggestions = ctx.registry
|
||||
.rankSuggestions(describe, 5, ctx.serverNameById)
|
||||
.slice(0, 5)
|
||||
return notFoundResult(describe, suggestions, server)
|
||||
}
|
||||
const serverName = ctx.serverNameById.get(resolved.serverId) ?? resolved.serverId
|
||||
let text = `${resolved.tool.name}\nServer: ${serverName}\n\n${resolved.tool.description || '(no description)'}\n\n`
|
||||
text += renderToolShape(resolved.tool)
|
||||
return contentText(text.trim())
|
||||
}
|
||||
|
||||
// 4.5 instructions
|
||||
if (instructions) {
|
||||
const serverId = ctx.serverIdByName.get(instructions)
|
||||
if (!serverId) {
|
||||
return contentText(
|
||||
`Server "${instructions}" not found. Use mcp({ action: "status" }) to see available servers.`,
|
||||
)
|
||||
}
|
||||
const text = await ctx.getInstructions(serverId)
|
||||
if (!text || text.trim() === '') {
|
||||
return contentText(`Server "${instructions}" does not provide instructions.`)
|
||||
}
|
||||
return contentText(`${instructions} instructions:\n\n${text}`)
|
||||
}
|
||||
|
||||
// 5. search
|
||||
if (search) {
|
||||
if (search.trim().length === 0 && !server) {
|
||||
return contentText('Search query cannot be empty')
|
||||
}
|
||||
const serverId = server ? ctx.serverIdByName.get(server) : undefined
|
||||
if (server && !serverId) {
|
||||
return contentText(
|
||||
`Server "${server}" not found. Use mcp({ action: "status" }) to see available servers.`,
|
||||
)
|
||||
}
|
||||
const { items, total, hasMore, nextOffset } = ctx.registry.searchTools(
|
||||
search,
|
||||
serverId,
|
||||
ctx.serverNameById,
|
||||
limit,
|
||||
offset,
|
||||
)
|
||||
if (total === 0) {
|
||||
return contentText(
|
||||
`No tools matching "${search}"${server ? ` in "${server}"` : ''}. Use mcp({ action: "status" }) to check connection state.`,
|
||||
)
|
||||
}
|
||||
let text = `Found ${total} tool${total === 1 ? '' : 's'} matching "${search}":\n\n`
|
||||
for (const match of items) {
|
||||
const serverName = ctx.serverNameById.get(match.server) ?? match.server
|
||||
text += `${match.tool.name} (server: ${serverName})\n`
|
||||
text += ` ${match.tool.description || '(no description)'}\n`
|
||||
if (includeSchemas && match.tool.inputSchema) {
|
||||
text += ` ${renderToolShape(match.tool, ' ')}\n`
|
||||
}
|
||||
text += '\n'
|
||||
}
|
||||
if (hasMore) {
|
||||
text += `${items.length} of ${total} — offset: ${nextOffset} for more\n`
|
||||
}
|
||||
return contentText(text.trim())
|
||||
}
|
||||
|
||||
// 6. server list
|
||||
if (server) {
|
||||
const serverId = ctx.serverIdByName.get(server)
|
||||
if (!serverId) {
|
||||
return contentText(
|
||||
`Server "${server}" not found. Use mcp({ action: "status" }) to see available servers.`,
|
||||
)
|
||||
}
|
||||
const tools = ctx.registry.getTools(serverId)
|
||||
if (tools.length === 0) {
|
||||
return contentText(
|
||||
`Server "${server}" has no cached tools yet. Call a tool on this server to connect automatically, or refresh it in Settings → MCP.`,
|
||||
)
|
||||
}
|
||||
const instructionsText = await ctx.getInstructions(serverId)
|
||||
return contentText(renderServerListing(server, tools, instructionsText))
|
||||
}
|
||||
|
||||
// 7. default: status
|
||||
const lines: string[] = ['MCP status:']
|
||||
for (const s of ctx.servers) {
|
||||
const auth = await ctx.authStatus(s.id)
|
||||
lines.push(` - ${s.name}: ${s.status} (${s.toolCount} tools, auth: ${auth})`)
|
||||
}
|
||||
lines.push('')
|
||||
lines.push('mcp({ server: "name" }) to list tools, mcp({ search: "..." }) to search')
|
||||
return contentText(lines.join('\n'))
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
/**
|
||||
* MCP Server Manager
|
||||
*
|
||||
* Manages MCP client connections to URL-based servers (Streamable HTTP with
|
||||
* SSE fallback, or pinned SSE). Simplified port of pi-mcp-adapter's
|
||||
* server-manager.ts: tools only, no stdio/sampling/elicitation/tracing.
|
||||
*/
|
||||
|
||||
import {
|
||||
Client,
|
||||
SdkHttpError,
|
||||
SSEClientTransport,
|
||||
StreamableHTTPClientTransport,
|
||||
UnauthorizedError,
|
||||
type Implementation,
|
||||
type ListToolsResult,
|
||||
type RequestOptions,
|
||||
type VersionNegotiationOptions,
|
||||
} from '@modelcontextprotocol/client'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import type { McpDbStore } from './mcp-db-store'
|
||||
import { McpOauthProvider, type McpOauthConfig } from './mcp-oauth-provider'
|
||||
|
||||
export interface McpTool {
|
||||
name: string
|
||||
title?: string
|
||||
description?: string
|
||||
inputSchema?: unknown
|
||||
_meta?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface ServerConnection {
|
||||
client: Client
|
||||
definition: McpServerDefinition
|
||||
tools: McpTool[]
|
||||
status: 'connected' | 'needs-auth'
|
||||
/** Self-reported server name/title/version/description (from getServerVersion). */
|
||||
serverVersion?: Implementation
|
||||
/** Self-reported server usage instructions (from getInstructions). */
|
||||
instructions?: string
|
||||
lastUsedAt: number
|
||||
inFlight: number
|
||||
}
|
||||
|
||||
export interface McpServerDefinition {
|
||||
name: string
|
||||
url: string
|
||||
transport: 'streamable_http' | 'sse'
|
||||
authConfig?: PrismaJson.McpServerAuthConfig
|
||||
config?: PrismaJson.McpServerConfig
|
||||
}
|
||||
|
||||
function isUnauthorizedHttpError(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof UnauthorizedError || (error instanceof SdkHttpError && error.status === 401)
|
||||
)
|
||||
}
|
||||
|
||||
function shouldFallbackToSse(error: unknown, definition: McpServerDefinition): boolean {
|
||||
if (definition.config?.protocolVersion === '2026-07-28') return false
|
||||
return error instanceof SdkHttpError && [404, 405, 406, 415].includes(error.status)
|
||||
}
|
||||
|
||||
function resolveVersionNegotiation(
|
||||
definition: McpServerDefinition,
|
||||
): VersionNegotiationOptions | undefined {
|
||||
switch (definition.config?.protocolVersion) {
|
||||
case undefined:
|
||||
case 'legacy':
|
||||
return undefined
|
||||
case 'auto':
|
||||
return { mode: 'auto' }
|
||||
case '2026-07-28':
|
||||
return { mode: { pin: '2026-07-28' } }
|
||||
default:
|
||||
throw new Error(`Invalid MCP protocolVersion: ${String(definition.config?.protocolVersion)}`)
|
||||
}
|
||||
}
|
||||
|
||||
export class McpServerManager {
|
||||
private connections = new Map<string, ServerConnection>()
|
||||
private connectPromises = new Map<string, Promise<ServerConnection>>()
|
||||
private stopped = false
|
||||
|
||||
constructor(private readonly dbStore: McpDbStore) {}
|
||||
|
||||
private getRequestTimeoutMs(definition: McpServerDefinition): number | undefined {
|
||||
const timeout = definition.config?.requestTimeoutMs
|
||||
return typeof timeout === 'number' && Number.isFinite(timeout) && timeout > 0
|
||||
? timeout
|
||||
: undefined
|
||||
}
|
||||
|
||||
private buildRequestOptions(definition: McpServerDefinition): RequestOptions | undefined {
|
||||
const timeout = this.getRequestTimeoutMs(definition)
|
||||
return timeout !== undefined ? { timeout } : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to a server. Single-flight per server id. Returns a connection
|
||||
* with status 'connected' or 'needs-auth' (when the server returns 401 and
|
||||
* OAuth is configured / auto-detectable).
|
||||
*/
|
||||
async connect(serverId: string, definition: McpServerDefinition): Promise<ServerConnection> {
|
||||
if (this.stopped) throw new Error('MCP server manager is closed')
|
||||
|
||||
// Dedupe concurrent connection attempts.
|
||||
if (this.connectPromises.has(serverId)) {
|
||||
return this.connectPromises.get(serverId)!
|
||||
}
|
||||
|
||||
const existing = this.connections.get(serverId)
|
||||
if (existing?.status === 'connected') {
|
||||
existing.lastUsedAt = Date.now()
|
||||
return existing
|
||||
}
|
||||
|
||||
const promise = this.createConnection(serverId, definition).finally(() => {
|
||||
if (this.connectPromises.get(serverId) === promise) {
|
||||
this.connectPromises.delete(serverId)
|
||||
}
|
||||
})
|
||||
this.connectPromises.set(serverId, promise)
|
||||
|
||||
try {
|
||||
const connection = await promise
|
||||
this.connections.set(serverId, connection)
|
||||
return connection
|
||||
} catch (error) {
|
||||
this.connectPromises.delete(serverId)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private async createConnection(
|
||||
serverId: string,
|
||||
definition: McpServerDefinition,
|
||||
): Promise<ServerConnection> {
|
||||
const url = new URL(definition.url)
|
||||
const requestInit = this.buildRequestInit(definition)
|
||||
const authProvider = this.buildAuthProvider(serverId, definition)
|
||||
|
||||
const attempt = async (
|
||||
kind: 'streamable-http' | 'sse',
|
||||
): Promise<{
|
||||
status: 'connected' | 'needs-auth'
|
||||
client: Client
|
||||
error?: unknown
|
||||
}> => {
|
||||
const transportOptions = {
|
||||
...(requestInit !== undefined ? { requestInit } : {}),
|
||||
...(authProvider !== undefined ? { authProvider } : {}),
|
||||
...(authProvider !== undefined &&
|
||||
definition.authConfig?.oauth?.skipIssuerMetadataValidation === true
|
||||
? { skipIssuerMetadataValidation: true }
|
||||
: {}),
|
||||
}
|
||||
const transport =
|
||||
kind === 'streamable-http'
|
||||
? new StreamableHTTPClientTransport(url, transportOptions)
|
||||
: new SSEClientTransport(url, transportOptions)
|
||||
const client = this.createClient(serverId, definition)
|
||||
|
||||
try {
|
||||
await client.connect(transport, this.buildRequestOptions(definition))
|
||||
return { status: 'connected', client }
|
||||
} catch (error) {
|
||||
try {
|
||||
await client.close()
|
||||
} catch {
|
||||
// Ignore cleanup errors on a failed connect.
|
||||
}
|
||||
return { status: 'needs-auth', client, error }
|
||||
}
|
||||
}
|
||||
|
||||
let kind: 'streamable-http' | 'sse' = definition.transport === 'sse' ? 'sse' : 'streamable-http'
|
||||
for (;;) {
|
||||
const result = await attempt(kind)
|
||||
if (result.status === 'connected') {
|
||||
const tools = await this.fetchAllTools(result.client, this.buildRequestOptions(definition))
|
||||
return {
|
||||
client: result.client,
|
||||
definition,
|
||||
tools,
|
||||
status: 'connected',
|
||||
serverVersion: result.client.getServerVersion(),
|
||||
instructions: result.client.getInstructions(),
|
||||
lastUsedAt: Date.now(),
|
||||
inFlight: 0,
|
||||
}
|
||||
}
|
||||
|
||||
if (isUnauthorizedHttpError(result.error)) {
|
||||
if (this.supportsOauth(definition)) {
|
||||
return {
|
||||
client: result.client,
|
||||
definition,
|
||||
tools: [],
|
||||
status: 'needs-auth',
|
||||
lastUsedAt: Date.now(),
|
||||
inFlight: 0,
|
||||
}
|
||||
}
|
||||
throw result.error
|
||||
}
|
||||
|
||||
if (
|
||||
kind === 'streamable-http' &&
|
||||
definition.transport !== 'sse' &&
|
||||
shouldFallbackToSse(result.error, definition)
|
||||
) {
|
||||
kind = 'sse'
|
||||
continue
|
||||
}
|
||||
throw result.error
|
||||
}
|
||||
}
|
||||
|
||||
private createClient(serverId: string, definition: McpServerDefinition): Client {
|
||||
const versionNegotiation = resolveVersionNegotiation(definition)
|
||||
return new Client(
|
||||
{ name: `shumai-mcp-${serverId}`, version: '1.0.0' },
|
||||
{
|
||||
...(versionNegotiation ? { versionNegotiation } : {}),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private buildAuthProvider(
|
||||
serverId: string,
|
||||
definition: McpServerDefinition,
|
||||
): McpOauthProvider | undefined {
|
||||
if (this.supportsOauth(definition)) {
|
||||
return new McpOauthProvider(
|
||||
serverId,
|
||||
definition.url,
|
||||
this.extractOauthConfig(definition.authConfig ?? {}),
|
||||
{ onRedirect: async () => {} },
|
||||
this.dbStore,
|
||||
)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
private supportsOauth(definition: McpServerDefinition): boolean {
|
||||
const auth = definition.authConfig
|
||||
if (auth?.type === 'none') return false
|
||||
if (auth?.type === 'bearer') return false
|
||||
// Explicit oauth, or auto-detect when no auth configured and no custom headers.
|
||||
if (auth?.type === 'oauth') return true
|
||||
if (auth?.headers && Object.keys(auth.headers).length > 0) return false
|
||||
return auth === undefined || auth.type === undefined
|
||||
}
|
||||
|
||||
private extractOauthConfig(auth: PrismaJson.McpServerAuthConfig): McpOauthConfig {
|
||||
const oauth = auth.oauth
|
||||
if (!oauth) return {}
|
||||
return {
|
||||
...(oauth.grantType !== undefined ? { grantType: oauth.grantType } : {}),
|
||||
...(oauth.clientId !== undefined ? { clientId: oauth.clientId } : {}),
|
||||
...(oauth.clientSecret !== undefined ? { clientSecret: oauth.clientSecret } : {}),
|
||||
...(oauth.scope !== undefined ? { scope: oauth.scope } : {}),
|
||||
...(oauth.authorizationParams !== undefined
|
||||
? { authorizationParams: oauth.authorizationParams }
|
||||
: {}),
|
||||
...(oauth.redirectUri !== undefined ? { redirectUri: oauth.redirectUri } : {}),
|
||||
...(oauth.clientName !== undefined ? { clientName: oauth.clientName } : {}),
|
||||
...(oauth.clientUri !== undefined ? { clientUri: oauth.clientUri } : {}),
|
||||
...(oauth.skipIssuerMetadataValidation !== undefined
|
||||
? { skipIssuerMetadataValidation: oauth.skipIssuerMetadataValidation }
|
||||
: {}),
|
||||
}
|
||||
}
|
||||
|
||||
private buildRequestInit(
|
||||
definition: McpServerDefinition,
|
||||
): { headers: Record<string, string> } | undefined {
|
||||
const auth = definition.authConfig
|
||||
const headers: Record<string, string> = { ...(auth?.headers ?? {}) }
|
||||
if (auth?.type === 'bearer' && auth.bearerToken) {
|
||||
headers['Authorization'] = `Bearer ${auth.bearerToken}`
|
||||
}
|
||||
return Object.keys(headers).length > 0 ? { headers } : undefined
|
||||
}
|
||||
|
||||
private async fetchAllTools(client: Client, requestOptions?: RequestOptions): Promise<McpTool[]> {
|
||||
const allTools: McpTool[] = []
|
||||
let cursor: string | undefined
|
||||
|
||||
do {
|
||||
const result: ListToolsResult = await client.listTools(
|
||||
cursor ? { cursor } : undefined,
|
||||
requestOptions,
|
||||
)
|
||||
allTools.push(...(result.tools ?? []))
|
||||
cursor = result.nextCursor
|
||||
} while (cursor)
|
||||
|
||||
return allTools
|
||||
}
|
||||
|
||||
/** List tools for a connected server. */
|
||||
async listTools(serverId: string): Promise<McpTool[]> {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (!connection || connection.status !== 'connected') {
|
||||
throw new Error(`Server is not connected`)
|
||||
}
|
||||
return connection.tools
|
||||
}
|
||||
|
||||
/** Call a tool on a connected server. */
|
||||
async callTool(
|
||||
serverId: string,
|
||||
toolName: string,
|
||||
args: Record<string, unknown>,
|
||||
): Promise<{
|
||||
content: McpContent[]
|
||||
structuredContent?: Record<string, unknown>
|
||||
isError?: boolean
|
||||
}> {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (!connection || connection.status !== 'connected') {
|
||||
throw new Error(`Server is not connected`)
|
||||
}
|
||||
this.incrementInFlight(serverId)
|
||||
try {
|
||||
this.touch(serverId)
|
||||
const result = await connection.client.callTool(
|
||||
{ name: toolName, arguments: args },
|
||||
this.buildRequestOptions(connection.definition),
|
||||
)
|
||||
return {
|
||||
content: (result.content ?? []) as McpContent[],
|
||||
structuredContent: result.structuredContent as Record<string, unknown> | undefined,
|
||||
isError: result.isError,
|
||||
}
|
||||
} finally {
|
||||
this.decrementInFlight(serverId)
|
||||
this.touch(serverId)
|
||||
}
|
||||
}
|
||||
|
||||
incrementInFlight(serverId: string): void {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (connection) {
|
||||
connection.inFlight = (connection.inFlight ?? 0) + 1
|
||||
}
|
||||
}
|
||||
|
||||
decrementInFlight(serverId: string): void {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (connection && connection.inFlight > 0) {
|
||||
connection.inFlight--
|
||||
}
|
||||
}
|
||||
|
||||
isIdle(serverId: string, timeoutMs: number): boolean {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (!connection || connection.status !== 'connected') return false
|
||||
if (connection.inFlight > 0) return false
|
||||
return Date.now() - connection.lastUsedAt > timeoutMs
|
||||
}
|
||||
|
||||
async closeIdleConnections(defaultTimeoutMs = 10 * 60 * 1000): Promise<string[]> {
|
||||
const closedIds: string[] = []
|
||||
for (const [serverId, connection] of this.connections) {
|
||||
if (connection.definition.config?.keepAlive) continue
|
||||
const timeoutMs = connection.definition.config?.idleTimeoutMs ?? defaultTimeoutMs
|
||||
if (this.isIdle(serverId, timeoutMs)) {
|
||||
await this.close(serverId)
|
||||
closedIds.push(serverId)
|
||||
}
|
||||
}
|
||||
return closedIds
|
||||
}
|
||||
|
||||
touch(serverId: string): void {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (connection) {
|
||||
connection.lastUsedAt = Date.now()
|
||||
}
|
||||
}
|
||||
|
||||
getConnection(serverId: string): ServerConnection | undefined {
|
||||
return this.connections.get(serverId)
|
||||
}
|
||||
|
||||
getAllConnections(): Map<string, ServerConnection> {
|
||||
return new Map(this.connections)
|
||||
}
|
||||
|
||||
async close(serverId: string): Promise<void> {
|
||||
const connection = this.connections.get(serverId)
|
||||
if (!connection) {
|
||||
const pending = this.connectPromises.get(serverId)
|
||||
if (pending) {
|
||||
try {
|
||||
await pending
|
||||
} catch {
|
||||
// Ignore failed connect during close.
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
this.connections.delete(serverId)
|
||||
try {
|
||||
await connection.client.close()
|
||||
} catch (error) {
|
||||
logger.debug({ serverId, error }, 'MCP client close failed')
|
||||
}
|
||||
}
|
||||
|
||||
async closeAll(): Promise<void> {
|
||||
const ids = [...this.connections.keys()]
|
||||
await Promise.allSettled(ids.map((id) => this.close(id)))
|
||||
this.connections.clear()
|
||||
this.connectPromises.clear()
|
||||
// The manager stays usable afterwards (tests reset between suites);
|
||||
// `stopped` only guards against using a permanently-shut-down manager.
|
||||
this.stopped = false
|
||||
}
|
||||
|
||||
isConnecting(serverId: string): boolean {
|
||||
return this.connectPromises.has(serverId)
|
||||
}
|
||||
}
|
||||
|
||||
export interface McpContent {
|
||||
type: 'text' | 'image' | 'audio' | 'resource' | 'resource_link'
|
||||
text?: string
|
||||
data?: string
|
||||
mimeType?: string
|
||||
resource?: {
|
||||
uri: string
|
||||
text?: string
|
||||
blob?: string
|
||||
}
|
||||
uri?: string
|
||||
name?: string
|
||||
description?: string
|
||||
}
|
||||
@@ -0,0 +1,990 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { McpService } from './mcp-service'
|
||||
import {
|
||||
startTestMcpServer,
|
||||
standardTestTools,
|
||||
type RunningTestMcpServer,
|
||||
type TestMcpToolDef,
|
||||
} from './mcp-test-server'
|
||||
|
||||
async function seedAgentAndUser(teamId: string, agentName: string) {
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: agentName,
|
||||
email: `${agentName.toLowerCase().replace(/\s+/g, '-')}@shumai.ai`,
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({ data: { teamId, userId: user.id, role: 'editor' } })
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: user.id,
|
||||
teamId,
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
config: { provider: 'openai', model: 'gpt-4' },
|
||||
},
|
||||
})
|
||||
return agent
|
||||
}
|
||||
|
||||
const TAVILY_TOOLS: TestMcpToolDef[] = [
|
||||
{
|
||||
name: 'tavily_search',
|
||||
description: 'Search the web for the latest information',
|
||||
handler: async () => 'tavily-search-result',
|
||||
},
|
||||
{
|
||||
name: 'tavily_research',
|
||||
description: 'Run deep multi-step research',
|
||||
handler: async () => 'tavily-research-result',
|
||||
},
|
||||
]
|
||||
|
||||
const AIRTABLE_TOOLS: TestMcpToolDef[] = [
|
||||
{
|
||||
name: 'search_records',
|
||||
description: 'Search Airtable records',
|
||||
handler: async () => 'AIRTABLE-SECRET-DATA',
|
||||
},
|
||||
{
|
||||
name: 'search_bases',
|
||||
description: 'Search Airtable bases',
|
||||
handler: async () => 'airtable-bases',
|
||||
},
|
||||
{
|
||||
name: 'search_candidate_linked_records',
|
||||
description: 'Search candidate linked records',
|
||||
handler: async () => 'airtable-candidates',
|
||||
},
|
||||
]
|
||||
|
||||
type ProxyExecute = (
|
||||
id: string,
|
||||
params: unknown,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
|
||||
describe('McpService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let teamId: string
|
||||
let srv: RunningTestMcpServer
|
||||
const service = new McpService()
|
||||
|
||||
beforeAll(async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'MCP Service Team' } })
|
||||
teamId = team.id
|
||||
srv = await startTestMcpServer({ tools: standardTestTools() })
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await srv.stop()
|
||||
await service.closeAllConnections()
|
||||
})
|
||||
|
||||
/** Seed an agent with one assigned server (tavily) and one discovered but unassigned server (airtable). */
|
||||
async function seedAgentWithUnassignedServer() {
|
||||
const agent = await seedAgentAndUser(teamId, 'Leak Guard Agent')
|
||||
const tavilySrv = await startTestMcpServer({
|
||||
tools: TAVILY_TOOLS,
|
||||
serverInfo: { name: 'tavily-mcp' },
|
||||
})
|
||||
const airtableSrv = await startTestMcpServer({
|
||||
tools: AIRTABLE_TOOLS,
|
||||
serverInfo: { name: 'airtable-mcp-server' },
|
||||
})
|
||||
const tavily = await service.createServer(teamId, { url: tavilySrv.url })
|
||||
const airtable = await service.createServer(teamId, { url: airtableSrv.url })
|
||||
await service.refreshServer(tavily.id)
|
||||
await service.refreshServer(airtable.id)
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: tavily.id } })
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
return { agent, proxy: tools[0], tavily, airtable, tavilySrv, airtableSrv }
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// CRUD
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('creates, lists, reads and deletes servers (secrets masked)', async () => {
|
||||
const created = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'bearer', bearerToken: 'super-secret' },
|
||||
})
|
||||
// Name is derived from the URL until the server self-reports on connect.
|
||||
expect(created.name).toBe('localhost')
|
||||
expect(created.url).toBe(srv.url)
|
||||
expect(created.authType).toBe('bearer')
|
||||
expect(created.toolCount).toBe(0)
|
||||
// Secrets never leak into the DTO.
|
||||
expect(JSON.stringify(created)).not.toContain('super-secret')
|
||||
|
||||
const listed = await service.listServers(teamId)
|
||||
expect(listed.map((s) => s.name)).toContain('localhost')
|
||||
|
||||
const got = await service.getServer(created.id)
|
||||
expect(got?.id).toBe(created.id)
|
||||
|
||||
await service.deleteServer(created.id)
|
||||
const after = await service.listServers(teamId)
|
||||
expect(after.map((s) => s.name)).not.toContain('localhost')
|
||||
})
|
||||
|
||||
it('allows duplicate server names per team (name is auto-derived)', async () => {
|
||||
const a = await service.createServer(teamId, { url: srv.url })
|
||||
const b = await service.createServer(teamId, { url: srv.url })
|
||||
expect(a.name).toBe(b.name)
|
||||
expect(a.id).not.toBe(b.id)
|
||||
})
|
||||
|
||||
it('derives the name from the URL host when creating', async () => {
|
||||
const github = await service.createServer(teamId, { url: 'https://api.github.com/mcp' })
|
||||
expect(github.name).toBe('github')
|
||||
|
||||
const example = await service.createServer(teamId, { url: 'https://mcp.example.com/sse' })
|
||||
expect(example.name).toBe('example')
|
||||
|
||||
const raw = await service.createServer(teamId, { url: 'not-a-url' })
|
||||
expect(raw.name).toBe('mcp-server')
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Discovery + tool calls against a real MCP server
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('refreshes a real MCP server and persists its tools', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'none' },
|
||||
})
|
||||
|
||||
const refreshed = await service.refreshServer(server.id)
|
||||
expect(refreshed.status).toBe('connected')
|
||||
expect(refreshed.toolCount).toBe(3)
|
||||
|
||||
const record = await service.getServerRecord(server.id)
|
||||
const names = ((record?.tools ?? []) as PrismaJson.McpToolInfo[]).map((t) => t.name).sort()
|
||||
expect(names).toEqual(['add', 'echo', 'list_sims'])
|
||||
|
||||
const updated = await service.getServer(server.id)
|
||||
expect(updated?.status).toBe('connected')
|
||||
expect(updated?.toolCount).toBe(3)
|
||||
expect(updated?.lastError).toBeUndefined()
|
||||
})
|
||||
|
||||
it('captures the server-reported name (title preferred) and description on discovery', async () => {
|
||||
const metaSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: {
|
||||
name: 'meta-srv',
|
||||
title: 'Meta Server',
|
||||
description: 'A server with rich metadata',
|
||||
},
|
||||
})
|
||||
try {
|
||||
const server = await service.createServer(teamId, { url: metaSrv.url })
|
||||
expect(server.name).toBe('localhost') // derived placeholder before discovery
|
||||
|
||||
await service.refreshServer(server.id)
|
||||
|
||||
const updated = await service.getServer(server.id)
|
||||
expect(updated?.name).toBe('Meta Server') // title wins over name
|
||||
expect(updated?.description).toBe('A server with rich metadata')
|
||||
|
||||
// The display name (title) flows into tool-name prefixes used by the
|
||||
// proxy registry, which is warmed from the persisted DB cache.
|
||||
const agent = await seedAgentAndUser(teamId, 'Meta Name Agent')
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
const agentTools = await service.buildAgentTools(agent.id, teamId)
|
||||
const search = await (agentTools[0].execute as ProxyExecute)('meta-1', { search: 'echo' })
|
||||
expect(JSON.stringify(search.content)).toContain('Meta_Server_echo')
|
||||
} finally {
|
||||
await metaSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('captures and persists server-reported instructions on discovery', async () => {
|
||||
const instSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: {
|
||||
name: 'inst-srv',
|
||||
instructions: 'Do not mutate production data. Always confirm destructive operations.',
|
||||
},
|
||||
})
|
||||
try {
|
||||
const server = await service.createServer(teamId, { url: instSrv.url })
|
||||
await service.refreshServer(server.id)
|
||||
|
||||
const updated = await service.getServer(server.id)
|
||||
expect(updated?.instructions).toBe(
|
||||
'Do not mutate production data. Always confirm destructive operations.',
|
||||
)
|
||||
} finally {
|
||||
await instSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('clears persisted instructions when a reconnected server stops reporting them', async () => {
|
||||
const instSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: {
|
||||
name: 'clear-srv',
|
||||
instructions: 'Temporary guidance that will disappear.',
|
||||
},
|
||||
})
|
||||
try {
|
||||
const server = await service.createServer(teamId, { url: instSrv.url })
|
||||
await service.refreshServer(server.id)
|
||||
expect((await service.getServer(server.id))?.instructions).toBe(
|
||||
'Temporary guidance that will disappear.',
|
||||
)
|
||||
|
||||
await service.closeAllConnections()
|
||||
await instSrv.stop()
|
||||
// Same URL, but the server now reports no instructions: the cached
|
||||
// value is cleared on the next successful connect.
|
||||
const bareSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'clear-srv' },
|
||||
port: instSrv.port,
|
||||
})
|
||||
try {
|
||||
await service.refreshServer(server.id)
|
||||
expect((await service.getServer(server.id))?.instructions).toBeUndefined()
|
||||
} finally {
|
||||
await bareSrv.stop()
|
||||
}
|
||||
} finally {
|
||||
await instSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('refreshServer force-reconnects and picks up updated instructions', async () => {
|
||||
const instSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'reload-srv', instructions: 'Old instructions.' },
|
||||
})
|
||||
try {
|
||||
const server = await service.createServer(teamId, { url: instSrv.url })
|
||||
await service.refreshServer(server.id)
|
||||
expect((await service.getServer(server.id))?.instructions).toBe('Old instructions.')
|
||||
expect(service.getConnectionCount(server.id)).toBe(1)
|
||||
|
||||
// The server restarts on the same URL with different instructions: a
|
||||
// refresh must force a fresh connection and re-persist the new value.
|
||||
await instSrv.stop()
|
||||
const reloadedSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'reload-srv', instructions: 'New instructions.' },
|
||||
port: instSrv.port,
|
||||
})
|
||||
try {
|
||||
const refreshed = await service.refreshServer(server.id)
|
||||
expect(refreshed.instructions).toBe('New instructions.')
|
||||
expect((await service.getServer(server.id))?.instructions).toBe('New instructions.')
|
||||
} finally {
|
||||
await reloadedSrv.stop()
|
||||
}
|
||||
} finally {
|
||||
await instSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('refreshServer re-populates tools that were cleared from the cache', async () => {
|
||||
const server = await service.createServer(teamId, { url: srv.url })
|
||||
await service.refreshServer(server.id)
|
||||
expect((await service.getServer(server.id))?.toolCount).toBe(3)
|
||||
|
||||
// Simulate a cache wipe (e.g. an auth/transport invalidation).
|
||||
await prisma.mcpServer.update({
|
||||
where: { id: server.id },
|
||||
data: { tools: [], status: 'not_connected' },
|
||||
})
|
||||
expect((await service.getServer(server.id))?.toolCount).toBe(0)
|
||||
|
||||
const refreshed = await service.refreshServer(server.id)
|
||||
expect(refreshed.toolCount).toBe(3)
|
||||
expect((await service.getServer(server.id))?.toolCount).toBe(3)
|
||||
})
|
||||
|
||||
it('surfaces server instructions at all three levels (snippet, preview, full text)', async () => {
|
||||
const instructionsText =
|
||||
'Never run destructive queries against the production database. Always operate in the ' +
|
||||
'read-only sandbox environment by default. Confirm any irreversible operation with the ' +
|
||||
'user before executing. Use the internal staging mirror for heavy analytical workloads ' +
|
||||
'and keep result sets small to avoid timeouts. Rate limits apply per account, so batch ' +
|
||||
'requests conservatively and respect the 429 backoff guidance.'
|
||||
const instSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'inst-srv', instructions: instructionsText },
|
||||
})
|
||||
try {
|
||||
const server = await service.createServer(teamId, { url: instSrv.url })
|
||||
await service.refreshServer(server.id)
|
||||
|
||||
const agent = await seedAgentAndUser(teamId, 'Instructions Agent')
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
const proxy = tools[0]
|
||||
|
||||
// L1: truncated snippet in the proxy tool description (no call needed).
|
||||
expect(proxy.description).toContain('Server instructions (truncated')
|
||||
expect(proxy.description).toContain('inst-srv:')
|
||||
expect(proxy.description).toContain('mcp({ instructions: "name" })')
|
||||
expect(proxy.description).not.toContain(instructionsText)
|
||||
|
||||
// L2: longer preview at the end of the server listing + full-text hint.
|
||||
const list = await (proxy.execute as ProxyExecute)('list-1', { server: 'inst-srv' })
|
||||
const listText = JSON.stringify(list.content)
|
||||
expect(listText).toContain('Server instructions:')
|
||||
expect(listText).toContain('for the full text')
|
||||
expect(listText).not.toContain(instructionsText)
|
||||
|
||||
// L3: full text via the instructions mode.
|
||||
const full = await (proxy.execute as ProxyExecute)('inst-1', { instructions: 'inst-srv' })
|
||||
const fullText = JSON.stringify(full.content)
|
||||
expect(fullText).toContain(instructionsText)
|
||||
expect(fullText).toContain('inst-srv instructions:')
|
||||
} finally {
|
||||
await instSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('reports when a server provides no instructions', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'No Instructions Agent')
|
||||
const server = await service.createServer(teamId, { url: srv.url })
|
||||
await service.refreshServer(server.id)
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
const proxy = tools[0]
|
||||
|
||||
// No L1 block, no L2 preview, and L3 says so explicitly.
|
||||
expect(proxy.description).not.toContain('Server instructions (truncated')
|
||||
const list = await (proxy.execute as ProxyExecute)('list-1', { server: 'test-mcp-server' })
|
||||
expect(JSON.stringify(list.content)).not.toContain('Server instructions:')
|
||||
const full = await (proxy.execute as ProxyExecute)('inst-1', {
|
||||
instructions: 'test-mcp-server',
|
||||
})
|
||||
expect(JSON.stringify(full.content)).toContain('does not provide instructions')
|
||||
})
|
||||
|
||||
it('keeps instructions available without a live connection (DB cache)', async () => {
|
||||
const instSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'cache-srv', instructions: 'Always use the read-only API.' },
|
||||
})
|
||||
try {
|
||||
const server = await service.createServer(teamId, { url: instSrv.url })
|
||||
await service.refreshServer(server.id)
|
||||
await service.closeAllConnections()
|
||||
expect(service.getConnectionCount(server.id)).toBe(0)
|
||||
|
||||
const agent = await seedAgentAndUser(teamId, 'Cache Agent')
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
const full = await (tools[0].execute as ProxyExecute)('inst-1', {
|
||||
instructions: 'cache-srv',
|
||||
})
|
||||
expect(JSON.stringify(full.content)).toContain('Always use the read-only API.')
|
||||
} finally {
|
||||
await instSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('falls back to the reported name when no title is provided', async () => {
|
||||
const server = await service.createServer(teamId, { url: srv.url })
|
||||
await service.refreshServer(server.id)
|
||||
const updated = await service.getServer(server.id)
|
||||
expect(updated?.name).toBe('test-mcp-server')
|
||||
})
|
||||
|
||||
it('calls a tool through callMcpTool and returns content', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'none' },
|
||||
})
|
||||
const result = await service.callMcpTool(server.id, 'echo', { text: 'roundtrip' }, { teamId })
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.content[0]).toMatchObject({ type: 'text', text: 'echo:roundtrip' })
|
||||
expect((result.content[0] as { text?: string }).text).toBe('echo:roundtrip')
|
||||
|
||||
const structured = await service.callMcpTool(server.id, 'add', { a: 4, b: 6 }, { teamId })
|
||||
expect(structured.ok).toBe(true)
|
||||
expect(JSON.stringify(structured.content)).toContain('10')
|
||||
})
|
||||
|
||||
it('surfaces server failures as error text (non-fatal)', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: 'http://localhost:1/mcp', // nothing listens here
|
||||
authConfig: { type: 'none' },
|
||||
})
|
||||
const result = await service.callMcpTool(server.id, 'echo', { text: 'x' }, { teamId })
|
||||
expect(result.ok).toBe(false)
|
||||
expect((result.content[0] as { text?: string }).text).toContain('Failed to connect')
|
||||
const updated = await service.getServer(server.id)
|
||||
expect(updated?.status).toBe('failed')
|
||||
expect(updated?.lastError).toBeTruthy()
|
||||
})
|
||||
|
||||
it('requires authentication via bearer token', async () => {
|
||||
const authSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
bearerToken: 'tok-123',
|
||||
})
|
||||
try {
|
||||
const wrong = await service.createServer(teamId, {
|
||||
url: authSrv.url,
|
||||
authConfig: { type: 'bearer', bearerToken: 'wrong-token' },
|
||||
})
|
||||
const result = await service.callMcpTool(wrong.id, 'echo', { text: 'x' }, { teamId })
|
||||
expect(result.ok).toBe(false)
|
||||
|
||||
const right = await service.createServer(teamId, {
|
||||
url: authSrv.url,
|
||||
authConfig: { type: 'bearer', bearerToken: 'tok-123' },
|
||||
})
|
||||
const ok = await service.callMcpTool(right.id, 'echo', { text: 'secret' }, { teamId })
|
||||
expect(ok.ok).toBe(true)
|
||||
expect((ok.content[0] as { text?: string }).text).toBe('echo:secret')
|
||||
} finally {
|
||||
await authSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// URL invalidation
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('transport change clears cached tools, credentials and the connection', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'none' },
|
||||
})
|
||||
await service.refreshServer(server.id)
|
||||
expect((await service.getServer(server.id))?.toolCount).toBe(3)
|
||||
|
||||
// The endpoint URL is immutable; a transport change invalidates the
|
||||
// cached tools + connection (and would wipe credentials).
|
||||
await service.updateServer(server.id, { transport: 'sse' })
|
||||
|
||||
const updated = await service.getServer(server.id)
|
||||
expect(updated?.transport).toBe('sse')
|
||||
expect(updated?.toolCount).toBe(0)
|
||||
expect(updated?.status).toBe('not_connected')
|
||||
expect(service.getConnectionCount(server.id)).toBe(0)
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Permission gating (D10)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('denies tool calls below the server permission and allows above it', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
permission: 'editor', // reviewers are denied
|
||||
})
|
||||
|
||||
// Reviewer user is denied.
|
||||
const reviewer = await prisma.user.create({
|
||||
data: { name: 'Reviewer', email: 'reviewer@shumai.ai', type: 'human' },
|
||||
})
|
||||
await prisma.teamMember.create({ data: { teamId, userId: reviewer.id, role: 'reviewer' } })
|
||||
|
||||
const denied = await service.callMcpTool(
|
||||
server.id,
|
||||
'echo',
|
||||
{ text: 'x' },
|
||||
{ teamId, userId: reviewer.id },
|
||||
)
|
||||
expect(denied.ok).toBe(false)
|
||||
expect((denied.content[0] as { text?: string }).text).toContain('Permission denied')
|
||||
|
||||
// Editor user is allowed.
|
||||
const editor = await prisma.user.create({
|
||||
data: { name: 'Editor', email: 'editor@shumai.ai', type: 'human' },
|
||||
})
|
||||
await prisma.teamMember.create({ data: { teamId, userId: editor.id, role: 'editor' } })
|
||||
const allowed = await service.callMcpTool(
|
||||
server.id,
|
||||
'echo',
|
||||
{ text: 'ok' },
|
||||
{ teamId, userId: editor.id },
|
||||
)
|
||||
expect(allowed.ok).toBe(true)
|
||||
})
|
||||
|
||||
it('denies calls without user context when permission is above reviewer', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
permission: 'editor',
|
||||
})
|
||||
const denied = await service.callMcpTool(server.id, 'echo', { text: 'x' }, { teamId })
|
||||
expect(denied.ok).toBe(false)
|
||||
expect((denied.content[0] as { text?: string }).text).toContain('User context required')
|
||||
})
|
||||
|
||||
it('allows calls without user context at reviewer permission', async () => {
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
permission: 'reviewer',
|
||||
})
|
||||
const allowed = await service.callMcpTool(server.id, 'echo', { text: 'x' }, { teamId })
|
||||
expect(allowed.ok).toBe(true)
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Per-agent assignment (D6)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('returns [] for agents without assigned MCP servers', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'No MCP Agent')
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
expect(tools).toEqual([])
|
||||
})
|
||||
|
||||
it('builds the proxy tool for assigned servers', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'Proxy Agent')
|
||||
const server = await service.createServer(teamId, { url: srv.url })
|
||||
await service.refreshServer(server.id)
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId, undefined)
|
||||
expect(tools.length).toBe(1)
|
||||
expect(tools[0].name).toBe('mcp')
|
||||
expect(tools[0].description).toContain('test-mcp-server')
|
||||
|
||||
// Executing the proxy's call mode hits the real server.
|
||||
const result = await (
|
||||
tools[0].execute as (
|
||||
id: string,
|
||||
params: unknown,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('call-1', { server: 'test-mcp-server', tool: 'echo', args: { text: 'via-proxy' } })
|
||||
expect(JSON.stringify(result.content)).toContain('echo:via-proxy')
|
||||
})
|
||||
|
||||
it('only includes assigned servers in the agent tools', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'Assigned Only Agent')
|
||||
const assignedSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'assigned-srv' },
|
||||
})
|
||||
const unassignedSrv = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'unassigned-srv' },
|
||||
})
|
||||
try {
|
||||
const assigned = await service.createServer(teamId, { url: assignedSrv.url })
|
||||
const unassigned = await service.createServer(teamId, { url: unassignedSrv.url })
|
||||
await service.refreshServer(assigned.id)
|
||||
await service.refreshServer(unassigned.id)
|
||||
await prisma.agentMcpServer.create({
|
||||
data: { agentId: agent.id, mcpServerId: assigned.id },
|
||||
})
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
expect(tools.length).toBe(1)
|
||||
expect(tools[0].description).toContain('assigned-srv')
|
||||
expect(tools[0].description).not.toContain('unassigned-srv')
|
||||
} finally {
|
||||
await assignedSrv.stop()
|
||||
await unassignedSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not leak unassigned server tools in "Did you mean" suggestions', async () => {
|
||||
const { proxy, tavilySrv, airtableSrv } = await seedAgentWithUnassignedServer()
|
||||
try {
|
||||
// The agent only has tavily assigned. Asking for a tool that does not
|
||||
// exist on tavily must not surface airtable's tool names as suggestions.
|
||||
const result = await (proxy.execute as ProxyExecute)('leak-1', {
|
||||
server: 'tavily-mcp',
|
||||
tool: 'search',
|
||||
})
|
||||
const text = JSON.stringify(result.content)
|
||||
expect(text).toContain('Did you mean')
|
||||
expect(text).not.toContain('airtable')
|
||||
expect(text).not.toContain('search_records')
|
||||
} finally {
|
||||
await tavilySrv.stop()
|
||||
await airtableSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not resolve, search or describe tools of unassigned servers', async () => {
|
||||
const { proxy, tavilySrv, airtableSrv } = await seedAgentWithUnassignedServer()
|
||||
try {
|
||||
const execute = proxy.execute as ProxyExecute
|
||||
|
||||
// 1. Direct tool call with the unassigned server's prefixed tool name
|
||||
// (no server param) must not execute airtable's handler.
|
||||
const call = await execute('leak-2', { tool: 'airtable_mcp_server_search_records' })
|
||||
expect(JSON.stringify(call.content)).not.toContain('AIRTABLE-SECRET-DATA')
|
||||
|
||||
// 2. Search must not surface unassigned server tools.
|
||||
const search = await execute('leak-3', { search: 'records' })
|
||||
expect(JSON.stringify(search.content)).not.toContain('airtable')
|
||||
|
||||
// 3. Describe must not leak unassigned server tool schemas (the
|
||||
// not-found reply may echo the tool name the model passed, but never
|
||||
// its description or parameter schema).
|
||||
const describe = await execute('leak-4', { describe: 'airtable_mcp_server_search_records' })
|
||||
const describeText = JSON.stringify(describe.content)
|
||||
expect(describeText).toContain('not found')
|
||||
expect(describeText).not.toContain('Search Airtable records')
|
||||
expect(describeText).not.toContain('Parameters:')
|
||||
} finally {
|
||||
await tavilySrv.stop()
|
||||
await airtableSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('drops unassigned servers from a rebuilt agent tool set', async () => {
|
||||
const { agent, airtable, tavilySrv, airtableSrv } = await seedAgentWithUnassignedServer()
|
||||
try {
|
||||
// Assign airtable, then unassign it — a rebuilt tool set must forget it.
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: airtable.id } })
|
||||
let tools = await service.buildAgentTools(agent.id, teamId)
|
||||
expect(JSON.stringify(tools[0].description)).toContain('airtable-mcp-server')
|
||||
|
||||
await prisma.agentMcpServer.deleteMany({
|
||||
where: { agentId: agent.id, mcpServerId: airtable.id },
|
||||
})
|
||||
tools = await service.buildAgentTools(agent.id, teamId)
|
||||
const search = await (tools[0].execute as ProxyExecute)('leak-5', { search: 'records' })
|
||||
expect(JSON.stringify(search.content)).not.toContain('airtable')
|
||||
|
||||
const call = await (tools[0].execute as ProxyExecute)('leak-6', {
|
||||
tool: 'airtable_mcp_server_search_records',
|
||||
})
|
||||
expect(JSON.stringify(call.content)).not.toContain('AIRTABLE-SECRET-DATA')
|
||||
} finally {
|
||||
await tavilySrv.stop()
|
||||
await airtableSrv.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('registers direct tools only for assigned servers', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'Direct Assigned Only Agent')
|
||||
const [assignedSrv, unassignedSrv] = await Promise.all([
|
||||
startTestMcpServer({
|
||||
tools: TAVILY_TOOLS,
|
||||
serverInfo: { name: 'tavily-mcp' },
|
||||
}),
|
||||
startTestMcpServer({
|
||||
tools: AIRTABLE_TOOLS,
|
||||
serverInfo: { name: 'airtable-mcp-server' },
|
||||
}),
|
||||
])
|
||||
try {
|
||||
const assigned = await service.createServer(teamId, {
|
||||
url: assignedSrv.url,
|
||||
config: { directTools: true },
|
||||
})
|
||||
const unassigned = await service.createServer(teamId, {
|
||||
url: unassignedSrv.url,
|
||||
config: { directTools: true },
|
||||
})
|
||||
await service.refreshServer(assigned.id)
|
||||
await service.refreshServer(unassigned.id)
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: assigned.id } })
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
const names = tools.map((t) => t.name)
|
||||
expect(names).toContain('tavily_mcp_tavily_search')
|
||||
expect(names).not.toContain('airtable_mcp_server_search_records')
|
||||
} finally {
|
||||
await assignedSrv.stop()
|
||||
await unassignedSrv.stop()
|
||||
}
|
||||
}, 15000)
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Direct tools (D3/D7)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('registers direct tools for opted-in servers alongside the proxy', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'Direct Agent')
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
config: { directTools: true },
|
||||
})
|
||||
await service.refreshServer(server.id)
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
expect(tools.length).toBe(4) // proxy + 3 direct tools
|
||||
const names = tools.map((t) => t.name)
|
||||
expect(names).toContain('mcp')
|
||||
expect(names).toContain('test_mcp_server_echo')
|
||||
expect(names).toContain('test_mcp_server_add')
|
||||
|
||||
// Direct tool executes through callMcpTool.
|
||||
const echo = tools.find((t) => t.name === 'test_mcp_server_echo')!
|
||||
const result = await (
|
||||
echo.execute as (
|
||||
id: string,
|
||||
params: unknown,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('call-2', { text: 'direct' })
|
||||
expect(JSON.stringify(result.content)).toContain('echo:direct')
|
||||
})
|
||||
|
||||
it('applies excludeTools filters to direct tools', async () => {
|
||||
const agent = await seedAgentAndUser(teamId, 'Filtered Agent')
|
||||
const server = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
config: { directTools: true, excludeTools: ['add'] },
|
||||
})
|
||||
await service.refreshServer(server.id)
|
||||
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
const names = tools.map((t) => t.name)
|
||||
expect(names).toContain('test_mcp_server_echo')
|
||||
expect(names).toContain('test_mcp_server_list_sims')
|
||||
expect(names).not.toContain('test_mcp_server_add')
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// OAuth status helpers
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('reports auth status for each auth type', async () => {
|
||||
const none = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'none' },
|
||||
})
|
||||
expect(await service.getAuthStatus(none.id)).toBe('authenticated')
|
||||
|
||||
const bearer = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'bearer', bearerToken: 'x' },
|
||||
})
|
||||
expect(await service.getAuthStatus(bearer.id)).toBe('authenticated')
|
||||
|
||||
const bearerEmpty = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'bearer' },
|
||||
})
|
||||
expect(await service.getAuthStatus(bearerEmpty.id)).toBe('not_authenticated')
|
||||
|
||||
const oauth = await service.createServer(teamId, {
|
||||
url: srv.url,
|
||||
authConfig: { type: 'oauth' },
|
||||
})
|
||||
expect(await service.getAuthStatus(oauth.id)).toBe('not_authenticated')
|
||||
expect(await service.getAuthStatus(oauth.id)).toBe('not_authenticated')
|
||||
})
|
||||
|
||||
it('testServer connects and lists tools', async () => {
|
||||
const server = await service.createServer(teamId, { url: srv.url })
|
||||
const result = await service.testServer(server.id)
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.toolCount).toBe(3)
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Proxy disambiguation across two servers (same-named tools)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
it('disambiguates same-named tools via the server parameter', async () => {
|
||||
const toolsA: TestMcpToolDef[] = [
|
||||
{ name: 'get', description: 'Get from server A', handler: async () => 'A' },
|
||||
{ name: 'shared', description: 'Shared tool on A', handler: async () => 'from-A' },
|
||||
]
|
||||
const toolsB: TestMcpToolDef[] = [
|
||||
{ name: 'get', description: 'Get from server B', handler: async () => 'B' },
|
||||
{ name: 'shared', description: 'Shared tool on B', handler: async () => 'from-B' },
|
||||
]
|
||||
const srvA = await startTestMcpServer({ tools: toolsA, serverInfo: { name: 'srvA' } })
|
||||
const srvB = await startTestMcpServer({ tools: toolsB, serverInfo: { name: 'srvB' } })
|
||||
try {
|
||||
const agent = await prisma.user.create({
|
||||
data: { name: 'Two Srv Agent', email: 'two-srv-agent@shumai.ai', type: 'agent' },
|
||||
})
|
||||
await prisma.teamMember.create({ data: { teamId, userId: agent.id, role: 'editor' } })
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: agent.id,
|
||||
teamId,
|
||||
type: 'chat',
|
||||
config: { provider: 'openai', model: 'gpt-4' },
|
||||
},
|
||||
})
|
||||
|
||||
const serverA = await service.createServer(teamId, { url: srvA.url })
|
||||
const serverB = await service.createServer(teamId, { url: srvB.url })
|
||||
await service.refreshServer(serverA.id)
|
||||
await service.refreshServer(serverB.id)
|
||||
await prisma.agentMcpServer.createMany({
|
||||
data: [
|
||||
{ agentId: agent.id, mcpServerId: serverA.id },
|
||||
{ agentId: agent.id, mcpServerId: serverB.id },
|
||||
],
|
||||
})
|
||||
|
||||
const tools = await service.buildAgentTools(agent.id, teamId)
|
||||
expect(tools.length).toBe(1) // only the proxy
|
||||
const proxy = tools[0]
|
||||
|
||||
const callA = await (
|
||||
proxy.execute as (
|
||||
id: string,
|
||||
params: unknown,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('c1', { server: 'srvA', tool: 'shared' })
|
||||
expect(JSON.stringify(callA.content)).toContain('from-A')
|
||||
|
||||
const callB = await (
|
||||
proxy.execute as (
|
||||
id: string,
|
||||
params: unknown,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('c2', { server: 'srvB', tool: 'shared' })
|
||||
expect(JSON.stringify(callB.content)).toContain('from-B')
|
||||
|
||||
// Prefixed names also resolve without the server parameter.
|
||||
const prefixed = await (
|
||||
proxy.execute as (
|
||||
id: string,
|
||||
params: unknown,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('c3', { tool: 'srvA_get' })
|
||||
expect(JSON.stringify(prefixed.content)).toContain('A')
|
||||
} finally {
|
||||
await srvA.stop()
|
||||
await srvB.stop()
|
||||
}
|
||||
})
|
||||
|
||||
describe('Idle connection and in-flight tracking', () => {
|
||||
it('tracks in-flight requests and safely prunes idle connections', async () => {
|
||||
// Deterministic synchronization with the server-side handler: the handler
|
||||
// signals when it starts executing and only then blocks on the release
|
||||
// gate. This avoids wall-clock guessing about when the HTTP round trip
|
||||
// has reached the server, which is slow and variable on CI.
|
||||
let slowToolStarted!: () => void
|
||||
const slowToolStartedPromise = new Promise<void>((resolve) => {
|
||||
slowToolStarted = resolve
|
||||
})
|
||||
let releaseSlowTool: () => void = () => {}
|
||||
const slowServer = await startTestMcpServer({
|
||||
tools: [
|
||||
{
|
||||
name: 'slow_tool',
|
||||
description: 'Slow tool',
|
||||
handler: async () => {
|
||||
slowToolStarted()
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseSlowTool = resolve
|
||||
})
|
||||
return 'slow-done'
|
||||
},
|
||||
},
|
||||
],
|
||||
serverInfo: { name: 'slow-mcp' },
|
||||
})
|
||||
|
||||
try {
|
||||
const serverRecord = await service.createServer(teamId, {
|
||||
url: slowServer.url,
|
||||
config: { idleTimeoutMs: 50 },
|
||||
})
|
||||
|
||||
// Connect to the server
|
||||
await service.refreshServer(serverRecord.id)
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(1)
|
||||
|
||||
// Start callTool in background
|
||||
const callPromise = service.callMcpTool(serverRecord.id, 'slow_tool', {})
|
||||
|
||||
// Wait until the tool handler is actually executing on the server so
|
||||
// the request is guaranteed to be in-flight before we assert on it.
|
||||
await Promise.race([
|
||||
slowToolStartedPromise,
|
||||
callPromise.then(() => {
|
||||
throw new Error('slow_tool finished before its handler started')
|
||||
}),
|
||||
])
|
||||
|
||||
// Connection should NOT be idle while tool is in-flight
|
||||
const closedDuringCall = await service.closeIdleConnections(0)
|
||||
expect(closedDuringCall).not.toContain(serverRecord.id)
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(1)
|
||||
|
||||
// Complete tool execution
|
||||
releaseSlowTool()
|
||||
const toolResult = await callPromise
|
||||
expect(toolResult.ok).toBe(true)
|
||||
|
||||
// Wait past idle timeout threshold
|
||||
await new Promise((r) => setTimeout(r, 60))
|
||||
|
||||
// Now idle connection should be closed
|
||||
const closedAfterIdle = await service.closeIdleConnections(50)
|
||||
expect(closedAfterIdle).toContain(serverRecord.id)
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(0)
|
||||
} finally {
|
||||
await slowServer.stop()
|
||||
}
|
||||
}, 10000)
|
||||
|
||||
it('respects keepAlive setting when closing idle connections', async () => {
|
||||
const keepAliveServer = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'keep-alive-mcp' },
|
||||
})
|
||||
|
||||
try {
|
||||
const serverRecord = await service.createServer(teamId, {
|
||||
url: keepAliveServer.url,
|
||||
config: { keepAlive: true },
|
||||
})
|
||||
|
||||
await service.refreshServer(serverRecord.id)
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(1)
|
||||
|
||||
// Wait a bit
|
||||
await new Promise((r) => setTimeout(r, 20))
|
||||
|
||||
// Should not close server marked with keepAlive even with 0 timeout
|
||||
const closed = await service.closeIdleConnections(0)
|
||||
expect(closed).not.toContain(serverRecord.id)
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(1)
|
||||
} finally {
|
||||
await keepAliveServer.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('can run periodic idle cleanup background timer', async () => {
|
||||
const timerServer = await startTestMcpServer({
|
||||
tools: standardTestTools(),
|
||||
serverInfo: { name: 'timer-mcp' },
|
||||
})
|
||||
|
||||
try {
|
||||
const serverRecord = await service.createServer(teamId, {
|
||||
url: timerServer.url,
|
||||
})
|
||||
await service.refreshServer(serverRecord.id)
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(1)
|
||||
|
||||
// Start timer with very short interval (20ms) and 0ms idle timeout
|
||||
service.startIdleCleanupTimer(20, 0)
|
||||
|
||||
// Wait for timer tick
|
||||
await new Promise((r) => setTimeout(r, 60))
|
||||
|
||||
expect(service.getConnectionCount(serverRecord.id)).toBe(0)
|
||||
} finally {
|
||||
service.stopIdleCleanupTimer()
|
||||
await timerServer.stop()
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,952 @@
|
||||
/**
|
||||
* McpService — CRUD, discovery, OAuth, and agent integration for MCP servers.
|
||||
*/
|
||||
|
||||
import { auth } from '@modelcontextprotocol/client'
|
||||
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
|
||||
import { prisma } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import type {
|
||||
CreateMcpServerRequest,
|
||||
McpAuthStatus,
|
||||
McpServerInfo,
|
||||
UpdateMcpServerRequest,
|
||||
} from '@shumai/dtos'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { mcpDbStore, type PendingAuth } from './mcp-db-store'
|
||||
import { buildDirectTools } from './mcp-direct-tools'
|
||||
import { McpOauthProvider, type McpOauthConfig } from './mcp-oauth-provider'
|
||||
import { buildProxyTool, transformMcpContent, type McpProxyToolContext } from './mcp-proxy-tool'
|
||||
import {
|
||||
formatToolName,
|
||||
McpToolRegistry,
|
||||
sanitizeServerPrefix,
|
||||
type ToolMetadata,
|
||||
} from './mcp-tool-registry'
|
||||
import { McpServerManager, type McpServerDefinition } from './mcp-server-manager'
|
||||
|
||||
const ROLE_HIERARCHY: Record<string, number> = {
|
||||
owner: 3,
|
||||
editor: 2,
|
||||
reviewer: 1,
|
||||
}
|
||||
|
||||
export interface McpToolCallContext {
|
||||
teamId: string
|
||||
userId?: string
|
||||
}
|
||||
|
||||
export type McpToolCallContent = AgentToolResult<Record<string, unknown>>['content']
|
||||
|
||||
export interface McpToolCallResult {
|
||||
ok: boolean
|
||||
content: McpToolCallContent
|
||||
}
|
||||
|
||||
export interface McpServerRecord {
|
||||
id: string
|
||||
name: string
|
||||
description: string | null
|
||||
instructions: string | null
|
||||
url: string
|
||||
transport: 'streamable_http' | 'sse'
|
||||
authConfig: PrismaJson.McpServerAuthConfig | null
|
||||
config: PrismaJson.McpServerConfig | null
|
||||
permission: 'owner' | 'editor' | 'reviewer'
|
||||
tools: PrismaJson.McpToolInfo[] | null
|
||||
status: string
|
||||
lastError: string | null
|
||||
lastConnectedAt: Date | null
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
teamId: string
|
||||
credential: { id: string } | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a placeholder server name from its URL until the server self-reports
|
||||
* its name/title on first successful connection. Strips www/api/mcp prefixes
|
||||
* and sanitizes the remaining host label (used as the direct-tool prefix).
|
||||
*/
|
||||
function deriveServerName(url: string): string {
|
||||
try {
|
||||
const hostname = new URL(url).hostname.toLowerCase()
|
||||
const labels = hostname.split('.').filter(Boolean)
|
||||
let label = labels[0] ?? 'mcp-server'
|
||||
if (labels.length > 1 && ['www', 'api', 'mcp'].includes(label)) {
|
||||
label = labels[1]
|
||||
}
|
||||
const sanitized = label.replace(/[^a-z0-9_-]/g, '_').replace(/^[-_]+|[-_]+$/g, '')
|
||||
return sanitized || 'mcp-server'
|
||||
} catch {
|
||||
return 'mcp-server'
|
||||
}
|
||||
}
|
||||
|
||||
function generateState(): string {
|
||||
return Array.from(crypto.getRandomValues(new Uint8Array(32)))
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
}
|
||||
|
||||
function extractOauthConfig(authConfig?: PrismaJson.McpServerAuthConfig): McpOauthConfig {
|
||||
const oauth = authConfig?.oauth
|
||||
if (!oauth) return {}
|
||||
return {
|
||||
...(oauth.grantType !== undefined ? { grantType: oauth.grantType } : {}),
|
||||
...(oauth.clientId !== undefined ? { clientId: oauth.clientId } : {}),
|
||||
...(oauth.clientSecret !== undefined ? { clientSecret: oauth.clientSecret } : {}),
|
||||
...(oauth.scope !== undefined ? { scope: oauth.scope } : {}),
|
||||
...(oauth.authorizationParams !== undefined
|
||||
? { authorizationParams: oauth.authorizationParams }
|
||||
: {}),
|
||||
...(oauth.redirectUri !== undefined ? { redirectUri: oauth.redirectUri } : {}),
|
||||
...(oauth.clientName !== undefined ? { clientName: oauth.clientName } : {}),
|
||||
...(oauth.clientUri !== undefined ? { clientUri: oauth.clientUri } : {}),
|
||||
...(oauth.skipIssuerMetadataValidation !== undefined
|
||||
? { skipIssuerMetadataValidation: oauth.skipIssuerMetadataValidation }
|
||||
: {}),
|
||||
}
|
||||
}
|
||||
|
||||
export class McpService {
|
||||
private manager = new McpServerManager(mcpDbStore)
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// CRUD
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
async createServer(teamId: string, req: CreateMcpServerRequest): Promise<McpServerInfo> {
|
||||
const server = await prisma.mcpServer.create({
|
||||
data: {
|
||||
name: deriveServerName(req.url),
|
||||
url: req.url,
|
||||
teamId,
|
||||
transport: req.transport ?? 'streamable_http',
|
||||
authConfig: (req.authConfig ?? {}) as PrismaJson.McpServerAuthConfig,
|
||||
config: (req.config ?? {}) as PrismaJson.McpServerConfig,
|
||||
permission: req.permission ?? 'reviewer',
|
||||
},
|
||||
include: { credential: true },
|
||||
})
|
||||
return this.toServerInfo(this.mapRecord(server))
|
||||
}
|
||||
|
||||
async updateServer(id: string, req: UpdateMcpServerRequest): Promise<McpServerInfo> {
|
||||
const existing = await prisma.mcpServer.findUnique({ where: { id } })
|
||||
if (!existing) throw new Error('MCP server not found')
|
||||
|
||||
const authChanged =
|
||||
req.authConfig !== undefined &&
|
||||
JSON.stringify(req.authConfig) !== JSON.stringify(existing.authConfig ?? {})
|
||||
const transportChanged = req.transport !== undefined && req.transport !== existing.transport
|
||||
|
||||
// The endpoint URL is immutable (delete + re-add to change it).
|
||||
// Auth/transport changes invalidate credentials and cached tools.
|
||||
const invalidateAll = authChanged || transportChanged
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
if (invalidateAll) {
|
||||
await tx.mcpServerCredential.deleteMany({ where: { serverId: id } })
|
||||
}
|
||||
return tx.mcpServer.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(req.transport !== undefined ? { transport: req.transport } : {}),
|
||||
...(req.authConfig !== undefined
|
||||
? { authConfig: req.authConfig as PrismaJson.McpServerAuthConfig }
|
||||
: {}),
|
||||
...(req.config !== undefined ? { config: req.config as PrismaJson.McpServerConfig } : {}),
|
||||
...(req.permission !== undefined ? { permission: req.permission } : {}),
|
||||
...(invalidateAll ? { tools: [], status: 'not_connected', lastError: null } : {}),
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
if (invalidateAll) {
|
||||
await this.manager.close(id)
|
||||
}
|
||||
|
||||
const record = await this.getServerRecord(id)
|
||||
if (!record) throw new Error('MCP server not found')
|
||||
return this.toServerInfo(record)
|
||||
}
|
||||
|
||||
async updateServerPermission(
|
||||
id: string,
|
||||
permission: 'owner' | 'editor' | 'reviewer',
|
||||
): Promise<McpServerInfo> {
|
||||
const server = await prisma.mcpServer.update({
|
||||
where: { id },
|
||||
data: { permission },
|
||||
include: { credential: true },
|
||||
})
|
||||
return this.toServerInfo(this.mapRecord(server))
|
||||
}
|
||||
|
||||
async deleteServer(id: string): Promise<void> {
|
||||
await this.manager.close(id)
|
||||
const server = await prisma.mcpServer.findUnique({ where: { id } })
|
||||
if (!server) return
|
||||
await prisma.mcpServer.delete({ where: { id } })
|
||||
}
|
||||
|
||||
async listServers(teamId: string): Promise<McpServerInfo[]> {
|
||||
const servers = await prisma.mcpServer.findMany({
|
||||
where: { teamId },
|
||||
orderBy: { id: 'desc' },
|
||||
include: { credential: true },
|
||||
})
|
||||
return servers.map((s) => this.toServerInfo(this.mapRecord(s)))
|
||||
}
|
||||
|
||||
async getServerRecord(id: string): Promise<McpServerRecord | null> {
|
||||
const server = await prisma.mcpServer.findUnique({
|
||||
where: { id },
|
||||
include: { credential: true },
|
||||
})
|
||||
if (!server) return null
|
||||
return this.mapRecord(server)
|
||||
}
|
||||
|
||||
async getServer(id: string): Promise<McpServerInfo | null> {
|
||||
const server = await this.getServerRecord(id)
|
||||
if (!server) return null
|
||||
return this.toServerInfo(server)
|
||||
}
|
||||
|
||||
private mapRecord(server: {
|
||||
id: string
|
||||
name: string
|
||||
description: string | null
|
||||
instructions: string | null
|
||||
url: string
|
||||
transport: 'streamable_http' | 'sse'
|
||||
authConfig: unknown
|
||||
config: unknown
|
||||
permission: 'owner' | 'editor' | 'reviewer'
|
||||
tools: unknown
|
||||
status: string
|
||||
lastError: string | null
|
||||
lastConnectedAt: Date | null
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
teamId: string
|
||||
credential: { id: string } | null
|
||||
}): McpServerRecord {
|
||||
return {
|
||||
id: server.id,
|
||||
name: server.name,
|
||||
description: server.description,
|
||||
instructions: server.instructions,
|
||||
url: server.url,
|
||||
transport: server.transport,
|
||||
authConfig: (server.authConfig ?? null) as PrismaJson.McpServerAuthConfig | null,
|
||||
config: (server.config ?? null) as PrismaJson.McpServerConfig | null,
|
||||
permission: server.permission,
|
||||
tools: (server.tools ?? null) as PrismaJson.McpToolInfo[] | null,
|
||||
status: server.status,
|
||||
lastError: server.lastError,
|
||||
lastConnectedAt: server.lastConnectedAt,
|
||||
createdAt: server.createdAt,
|
||||
updatedAt: server.updatedAt,
|
||||
teamId: server.teamId,
|
||||
credential: server.credential,
|
||||
}
|
||||
}
|
||||
|
||||
private toServerInfo(server: McpServerRecord): McpServerInfo {
|
||||
const tools = server.tools ?? []
|
||||
return {
|
||||
id: server.id,
|
||||
name: server.name,
|
||||
description: server.description ?? undefined,
|
||||
instructions: server.instructions ?? undefined,
|
||||
url: server.url,
|
||||
transport: server.transport,
|
||||
authType: server.authConfig?.type ?? 'auto',
|
||||
config: server.config ?? undefined,
|
||||
permission: server.permission,
|
||||
status: server.status,
|
||||
lastError: server.lastError ?? undefined,
|
||||
toolCount: Array.isArray(tools) ? tools.length : 0,
|
||||
hasCredential: server.credential !== null,
|
||||
createdAt: server.createdAt.toISOString(),
|
||||
updatedAt: server.updatedAt.toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Discovery
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
private toDefinition(server: McpServerRecord): McpServerDefinition {
|
||||
return {
|
||||
name: server.name,
|
||||
url: server.url,
|
||||
transport: server.transport,
|
||||
authConfig: server.authConfig ?? undefined,
|
||||
config: server.config ?? undefined,
|
||||
}
|
||||
}
|
||||
|
||||
private async updateStatus(
|
||||
serverId: string,
|
||||
status: string,
|
||||
lastError: string | null,
|
||||
extra?: {
|
||||
tools?: PrismaJson.McpToolInfo[]
|
||||
lastConnectedAt?: Date
|
||||
name?: string
|
||||
description?: string | null
|
||||
instructions?: string | null
|
||||
},
|
||||
): Promise<void> {
|
||||
await prisma.mcpServer.update({
|
||||
where: { id: serverId },
|
||||
data: {
|
||||
status,
|
||||
lastError,
|
||||
...(extra?.tools !== undefined ? { tools: extra.tools } : {}),
|
||||
...(extra?.lastConnectedAt !== undefined ? { lastConnectedAt: extra.lastConnectedAt } : {}),
|
||||
...(extra?.name !== undefined ? { name: extra.name } : {}),
|
||||
...(extra?.description !== undefined ? { description: extra.description } : {}),
|
||||
...(extra?.instructions !== undefined ? { instructions: extra.instructions } : {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
private toStoredTools(
|
||||
tools: Array<{ name: string; title?: string; description?: string; inputSchema?: unknown }>,
|
||||
): PrismaJson.McpToolInfo[] {
|
||||
return tools.map((t) => ({
|
||||
name: t.name,
|
||||
...(t.title !== undefined ? { title: t.title } : {}),
|
||||
...(t.description !== undefined ? { description: t.description } : {}),
|
||||
...(t.inputSchema !== undefined ? { inputSchema: t.inputSchema } : {}),
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the server's self-reported metadata (name = title ?? name, plus
|
||||
* description and instructions) captured after a successful connect.
|
||||
* Description comes from getServerVersion(); instructions come from
|
||||
* getInstructions() (a sibling field of the initialize/discover result,
|
||||
* not part of Implementation).
|
||||
*/
|
||||
private serverMetadata(
|
||||
server: McpServerRecord,
|
||||
connection: { serverVersion?: unknown; instructions?: string },
|
||||
): {
|
||||
name?: string
|
||||
description?: string | null
|
||||
instructions?: string | null
|
||||
} {
|
||||
const metadata: {
|
||||
name?: string
|
||||
description?: string | null
|
||||
instructions?: string | null
|
||||
} = {}
|
||||
const impl = connection.serverVersion as
|
||||
| { name?: string; title?: string; description?: string }
|
||||
| undefined
|
||||
if (impl && typeof impl === 'object') {
|
||||
const reportedName = impl.title ?? impl.name
|
||||
if (typeof reportedName === 'string' && reportedName.trim() !== '') {
|
||||
metadata.name = reportedName.trim()
|
||||
metadata.description = typeof impl.description === 'string' ? impl.description : null
|
||||
}
|
||||
}
|
||||
if (typeof connection.instructions === 'string') {
|
||||
metadata.instructions = connection.instructions
|
||||
} else {
|
||||
// Sync-on-connect: a server that stops reporting instructions clears
|
||||
// the cached value (mirrors pi-mcp-adapter's set/delete behavior).
|
||||
metadata.instructions = null
|
||||
}
|
||||
return metadata
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh a server: force a fresh connection (closing any existing one),
|
||||
* then re-discover and persist tools, instructions, name/description and
|
||||
* status. Returns the updated server record. Throws on connection failure
|
||||
* (after marking the server as failed). This is the single discovery
|
||||
* entry point: the refresh endpoint, Test Connection, and post-OAuth
|
||||
* completion all route through it.
|
||||
*/
|
||||
async refreshServer(serverId: string): Promise<McpServerInfo> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) throw new Error('MCP server not found')
|
||||
await this.manager.close(serverId)
|
||||
|
||||
try {
|
||||
const connection = await this.manager.connect(serverId, this.toDefinition(server))
|
||||
if (connection.status === 'needs-auth') {
|
||||
await this.updateStatus(serverId, 'needs_auth', null)
|
||||
} else {
|
||||
const tools = this.toStoredTools(connection.tools)
|
||||
const metadata = this.serverMetadata(server, connection)
|
||||
await this.updateStatus(serverId, 'connected', null, {
|
||||
tools,
|
||||
lastConnectedAt: new Date(),
|
||||
...metadata,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
logger.warn({ serverId, error }, 'MCP server refresh failed')
|
||||
await this.updateStatus(serverId, 'failed', message)
|
||||
throw error
|
||||
}
|
||||
|
||||
const record = await this.getServerRecord(serverId)
|
||||
if (!record) throw new Error('MCP server not found')
|
||||
return this.toServerInfo(record)
|
||||
}
|
||||
|
||||
/** Lazy connect used by the proxy/direct tools; never throws. */
|
||||
private async ensureConnected(
|
||||
serverId: string,
|
||||
registry?: McpToolRegistry,
|
||||
): Promise<
|
||||
{ status: 'connected' } | { status: 'needs-auth' } | { status: 'error'; message: string }
|
||||
> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) return { status: 'error', message: 'server not found' }
|
||||
|
||||
const existing = this.manager.getConnection(serverId)
|
||||
if (existing?.status === 'connected') return { status: 'connected' }
|
||||
|
||||
try {
|
||||
const connection = await this.manager.connect(serverId, this.toDefinition(server))
|
||||
if (connection.status === 'needs-auth') {
|
||||
await this.updateStatus(serverId, 'needs_auth', null)
|
||||
return { status: 'needs-auth' }
|
||||
}
|
||||
const tools = this.toStoredTools(connection.tools)
|
||||
const metadata = this.serverMetadata(server, connection)
|
||||
const displayName = metadata.name ?? server.name
|
||||
registry?.setTools(serverId, displayName, connection.tools)
|
||||
await this.updateStatus(serverId, 'connected', null, {
|
||||
tools,
|
||||
lastConnectedAt: new Date(),
|
||||
...metadata,
|
||||
})
|
||||
return { status: 'connected' }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
await this.updateStatus(serverId, 'failed', message)
|
||||
return { status: 'error', message }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-reported usage instructions. Prefers the persisted value (the
|
||||
* cache, so it works without a live connection), falling back to the live
|
||||
* connection's getInstructions() for a just-connected server.
|
||||
*/
|
||||
private async getServerInstructions(serverId: string): Promise<string | null> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) return null
|
||||
if (server.instructions && server.instructions.trim() !== '') return server.instructions
|
||||
const connection = this.manager.getConnection(serverId)
|
||||
const live = connection?.client.getInstructions?.()
|
||||
return typeof live === 'string' && live.trim() !== '' ? live : null
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Tool execution
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
private async checkPermission(
|
||||
server: McpServerRecord,
|
||||
ctx?: McpToolCallContext,
|
||||
): Promise<string | null> {
|
||||
const requiredLevel = ROLE_HIERARCHY[server.permission] || 1
|
||||
|
||||
if (ctx?.userId) {
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId: server.teamId,
|
||||
userId: ctx.userId,
|
||||
},
|
||||
},
|
||||
select: { role: true },
|
||||
})
|
||||
const userLevel = member ? ROLE_HIERARCHY[member.role] || 0 : 0
|
||||
if (userLevel < requiredLevel) {
|
||||
return `Permission denied: Insufficient role to use MCP server "${server.name}". Minimum required role is "${server.permission}".`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
if (requiredLevel > 1) {
|
||||
return `Permission denied: User context required to use MCP server "${server.name}". Minimum required role is "${server.permission}".`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private contentFromMcpResult(result: {
|
||||
content: unknown[]
|
||||
structuredContent?: Record<string, unknown>
|
||||
isError?: boolean
|
||||
}): McpToolCallContent {
|
||||
const blocks = transformMcpContent(
|
||||
(Array.isArray(result.content) ? result.content : []) as Parameters<
|
||||
typeof transformMcpContent
|
||||
>[0],
|
||||
)
|
||||
if (blocks.length > 0) return blocks
|
||||
if (result.structuredContent !== undefined && result.structuredContent !== null) {
|
||||
return [
|
||||
{
|
||||
type: 'text',
|
||||
text:
|
||||
JSON.stringify(result.structuredContent, null, 2) ?? String(result.structuredContent),
|
||||
},
|
||||
]
|
||||
}
|
||||
return [{ type: 'text', text: '(empty result)' }]
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute an MCP tool (shared by the proxy and direct tools).
|
||||
* Permission gate (D10) first; never throws — failures become error text.
|
||||
*/
|
||||
async callMcpTool(
|
||||
serverId: string,
|
||||
toolName: string,
|
||||
args: Record<string, unknown>,
|
||||
ctx?: McpToolCallContext,
|
||||
): Promise<McpToolCallResult> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) {
|
||||
return { ok: false, content: [{ type: 'text', text: 'MCP server not found' }] }
|
||||
}
|
||||
|
||||
const denied = await this.checkPermission(server, ctx)
|
||||
if (denied) {
|
||||
return { ok: false, content: [{ type: 'text', text: denied }] }
|
||||
}
|
||||
|
||||
const outcome = await this.ensureConnected(serverId)
|
||||
if (outcome.status === 'needs-auth') {
|
||||
return {
|
||||
ok: false,
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `MCP server "${server.name}" requires authentication. Ask an admin to connect it in Settings → MCP.`,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
if (outcome.status === 'error') {
|
||||
return {
|
||||
ok: false,
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Failed to connect to MCP server "${server.name}": ${outcome.message}`,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.manager.callTool(serverId, toolName, args)
|
||||
if (result.isError) {
|
||||
const text = result.content.map((c) => ('text' in c ? c.text : '[image]')).join('\n')
|
||||
return {
|
||||
ok: true,
|
||||
content: [{ type: 'text', text: text ? `Error: ${text}` : 'Tool execution failed' }],
|
||||
}
|
||||
}
|
||||
return { ok: true, content: this.contentFromMcpResult(result) }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
await this.updateStatus(serverId, 'failed', message)
|
||||
return {
|
||||
ok: false,
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Failed to call tool "${toolName}" on MCP server "${server.name}": ${message}`,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// OAuth
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
async startAuth(serverId: string): Promise<{
|
||||
authorizationUrl?: string
|
||||
alreadyAuthenticated?: boolean
|
||||
}> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) throw new Error('MCP server not found')
|
||||
|
||||
const config = extractOauthConfig(server.authConfig ?? undefined)
|
||||
if (config.grantType === 'client_credentials') {
|
||||
const provider = new McpOauthProvider(
|
||||
serverId,
|
||||
server.url,
|
||||
config,
|
||||
{
|
||||
onRedirect: async () => {
|
||||
throw new Error('Browser redirect is not used for client_credentials flow')
|
||||
},
|
||||
},
|
||||
mcpDbStore,
|
||||
)
|
||||
try {
|
||||
const result = await auth(provider, {
|
||||
serverUrl: server.url,
|
||||
...(config.scope !== undefined ? { scope: config.scope } : {}),
|
||||
...(config.skipIssuerMetadataValidation === true
|
||||
? { skipIssuerMetadataValidation: true }
|
||||
: {}),
|
||||
})
|
||||
if (result !== 'AUTHORIZED') {
|
||||
throw new Error('Failed to authorize')
|
||||
}
|
||||
await mcpDbStore.clearPendingAuth(serverId)
|
||||
return { alreadyAuthenticated: true }
|
||||
} finally {
|
||||
provider.deactivate()
|
||||
}
|
||||
}
|
||||
|
||||
let capturedUrl: URL | undefined
|
||||
const provider = new McpOauthProvider(
|
||||
serverId,
|
||||
server.url,
|
||||
config,
|
||||
{
|
||||
onRedirect: async (url) => {
|
||||
capturedUrl = url
|
||||
},
|
||||
},
|
||||
mcpDbStore,
|
||||
)
|
||||
|
||||
try {
|
||||
const result = await auth(provider, {
|
||||
serverUrl: server.url,
|
||||
...(config.scope !== undefined ? { scope: config.scope } : {}),
|
||||
...(config.skipIssuerMetadataValidation === true
|
||||
? { skipIssuerMetadataValidation: true }
|
||||
: {}),
|
||||
})
|
||||
if (result === 'AUTHORIZED') {
|
||||
await mcpDbStore.clearPendingAuth(serverId)
|
||||
return { alreadyAuthenticated: true }
|
||||
}
|
||||
if (!capturedUrl) {
|
||||
throw new Error('OAuth authorization URL was not provided')
|
||||
}
|
||||
|
||||
const state = (await mcpDbStore.getOauthState(serverId)) ?? generateState()
|
||||
const discoveryState = await provider.discoveryState()
|
||||
const pending: PendingAuth = {
|
||||
state,
|
||||
authorizationUrl: capturedUrl.toString(),
|
||||
discovery: (discoveryState ?? {}) as Record<string, unknown>,
|
||||
expiresAt: Math.floor(Date.now() / 1000) + (await mcpDbStore.getPendingAuthTtlSeconds()),
|
||||
grantType: 'authorization_code',
|
||||
...(provider.redirectUrl ? { redirectUri: provider.redirectUrl } : {}),
|
||||
}
|
||||
await mcpDbStore.savePendingAuth(serverId, pending)
|
||||
return { authorizationUrl: capturedUrl.toString() }
|
||||
} finally {
|
||||
provider.deactivate()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete an authorization_code flow. `state` is validated by the caller
|
||||
* (the API callback route) before delegating here.
|
||||
*/
|
||||
async completeAuth(
|
||||
serverId: string,
|
||||
input: { code: string; iss?: string },
|
||||
): Promise<McpAuthStatus> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) throw new Error('MCP server not found')
|
||||
const pending = await mcpDbStore.getPendingAuth(serverId)
|
||||
if (!pending) throw new Error(`No pending OAuth flow for server: ${server.name}`)
|
||||
|
||||
const config = extractOauthConfig(server.authConfig ?? undefined)
|
||||
const provider = new McpOauthProvider(
|
||||
serverId,
|
||||
server.url,
|
||||
config,
|
||||
{ onRedirect: async () => {} },
|
||||
mcpDbStore,
|
||||
)
|
||||
|
||||
try {
|
||||
const result = await auth(provider, {
|
||||
serverUrl: server.url,
|
||||
authorizationCode: input.code,
|
||||
...(input.iss !== undefined ? { iss: input.iss } : {}),
|
||||
...(pending.discovery as Record<string, unknown>),
|
||||
...(config.skipIssuerMetadataValidation === true
|
||||
? { skipIssuerMetadataValidation: true }
|
||||
: {}),
|
||||
})
|
||||
if (result !== 'AUTHORIZED') {
|
||||
throw new Error('Failed to authorize')
|
||||
}
|
||||
await mcpDbStore.clearPendingAuth(serverId)
|
||||
await mcpDbStore.clearDiscoverySnapshot(serverId)
|
||||
try {
|
||||
await this.refreshServer(serverId)
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ serverId, err },
|
||||
'Post-auth server refresh failed, setting status to connected',
|
||||
)
|
||||
await this.updateStatus(serverId, 'connected', null)
|
||||
}
|
||||
return 'authenticated'
|
||||
} finally {
|
||||
provider.deactivate()
|
||||
}
|
||||
}
|
||||
|
||||
/** Find a pending flow by its CSRF state and complete it. */
|
||||
async handleOauthCallback(
|
||||
code: string,
|
||||
state: string,
|
||||
iss?: string,
|
||||
): Promise<{ ok: true } | { ok: false; message: string }> {
|
||||
const rows = await prisma.mcpServerCredential.findMany({
|
||||
select: { serverId: true, pendingAuth: true },
|
||||
})
|
||||
|
||||
let serverId: string | undefined
|
||||
for (const row of rows) {
|
||||
const raw = row.pendingAuth as Partial<PendingAuth> | null
|
||||
if (raw && typeof raw.state === 'string' && raw.state === state) {
|
||||
serverId = row.serverId
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!serverId) {
|
||||
return { ok: false, message: 'Invalid or expired OAuth state. Start authentication again.' }
|
||||
}
|
||||
|
||||
try {
|
||||
const status = await this.completeAuth(serverId, { code, iss })
|
||||
return status === 'authenticated'
|
||||
? { ok: true }
|
||||
: { ok: false, message: 'Authentication did not complete' }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
logger.error({ serverId, error }, 'MCP OAuth callback completion failed')
|
||||
await mcpDbStore.clearPendingAuth(serverId)
|
||||
return { ok: false, message }
|
||||
}
|
||||
}
|
||||
|
||||
async getAuthStatus(serverId: string): Promise<McpAuthStatus> {
|
||||
const server = await this.getServerRecord(serverId)
|
||||
if (!server) throw new Error('MCP server not found')
|
||||
|
||||
const authType = server.authConfig?.type
|
||||
if (authType === 'none') return 'authenticated'
|
||||
if (authType === 'bearer') {
|
||||
return server.authConfig?.bearerToken ? 'authenticated' : 'not_authenticated'
|
||||
}
|
||||
|
||||
const pending = await mcpDbStore.getPendingAuth(serverId)
|
||||
if (pending) return 'in_progress'
|
||||
const hasTokens = await mcpDbStore.hasStoredTokens(serverId)
|
||||
if (!hasTokens) return 'not_authenticated'
|
||||
const expired = await mcpDbStore.isTokenExpired(serverId)
|
||||
return expired ? 'expired' : 'authenticated'
|
||||
}
|
||||
|
||||
async removeAuth(serverId: string): Promise<void> {
|
||||
await mcpDbStore.clearAllCredentials(serverId)
|
||||
await mcpDbStore.clearPendingAuth(serverId)
|
||||
await mcpDbStore.clearDiscoverySnapshot(serverId)
|
||||
await this.manager.close(serverId)
|
||||
await this.updateStatus(serverId, 'needs_auth', null)
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Agent integration
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Build the agent's MCP AgentTools: the single `mcp` proxy tool plus direct
|
||||
* tools for assigned servers in direct-tools mode. Returns [] when the agent
|
||||
* has no assigned servers (no proxy tool — don't waste LLM context).
|
||||
*/
|
||||
async buildAgentTools(agentId: string, teamId: string, userId?: string): Promise<AgentTool[]> {
|
||||
const assignments = await prisma.agentMcpServer.findMany({
|
||||
where: { agentId },
|
||||
include: { mcpServer: true },
|
||||
})
|
||||
if (assignments.length === 0) return []
|
||||
|
||||
// Per-agent tool registry: built fresh for this agent from the persisted
|
||||
// discovery cache (McpServer.tools). It only ever contains the agent's
|
||||
// assigned servers, so unassigned/disabled servers can neither be searched
|
||||
// nor called — no global mutable state to leak through.
|
||||
const registry = new McpToolRegistry()
|
||||
|
||||
const servers = assignments
|
||||
.map((a) => a.mcpServer)
|
||||
.map((s) => {
|
||||
const storedTools = (s.tools ?? []) as PrismaJson.McpToolInfo[]
|
||||
if (storedTools.length > 0) {
|
||||
registry.setTools(
|
||||
s.id,
|
||||
s.name,
|
||||
storedTools.map((t) => ({
|
||||
name: t.name,
|
||||
description: t.description ?? '',
|
||||
...(t.inputSchema !== undefined ? { inputSchema: t.inputSchema } : {}),
|
||||
})),
|
||||
)
|
||||
}
|
||||
return {
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
instructions: s.instructions ?? null,
|
||||
url: s.url,
|
||||
transport: s.transport,
|
||||
authConfig: (s.authConfig ?? {}) as PrismaJson.McpServerAuthConfig,
|
||||
config: (s.config ?? {}) as PrismaJson.McpServerConfig,
|
||||
tools: storedTools,
|
||||
status: s.status,
|
||||
}
|
||||
})
|
||||
|
||||
const serverNameById = new Map<string, string>()
|
||||
const serverIdByName = new Map<string, string>()
|
||||
const proxyServers = servers.map((s) => {
|
||||
serverNameById.set(s.id, s.name)
|
||||
serverIdByName.set(s.name, s.id)
|
||||
return {
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
toolCount: s.tools.length,
|
||||
status: s.status,
|
||||
...(s.instructions !== null && s.instructions !== undefined
|
||||
? { instructions: s.instructions }
|
||||
: {}),
|
||||
}
|
||||
})
|
||||
|
||||
const ctx: McpProxyToolContext = {
|
||||
teamId,
|
||||
userId,
|
||||
servers: proxyServers,
|
||||
serverNameById,
|
||||
serverIdByName,
|
||||
registry,
|
||||
resolveServerForTool: (toolName) => {
|
||||
// Longest {server}_ prefix match (dots/hyphens sanitized like the registry).
|
||||
let best: string | undefined
|
||||
let bestLen = 0
|
||||
for (const [sid, name] of serverNameById.entries()) {
|
||||
const prefix = sanitizeServerPrefix(name)
|
||||
if (toolName.startsWith(`${prefix}_`) && prefix.length > bestLen) {
|
||||
best = sid
|
||||
bestLen = prefix.length
|
||||
}
|
||||
}
|
||||
return best
|
||||
},
|
||||
ensureConnected: (serverId) => this.ensureConnected(serverId, registry),
|
||||
callTool: (serverId, toolName, args) =>
|
||||
this.callMcpTool(serverId, toolName, args, { teamId, userId }),
|
||||
authStatus: (serverId) => this.getAuthStatus(serverId),
|
||||
startAuth: (serverId) => this.startAuth(serverId),
|
||||
getInstructions: (serverId) => this.getServerInstructions(serverId),
|
||||
}
|
||||
|
||||
const tools: AgentTool[] = [buildProxyTool(ctx)]
|
||||
|
||||
for (const server of servers) {
|
||||
if (server.config?.directTools !== true) continue
|
||||
const metadata: ToolMetadata[] = registry.getTools(server.id)
|
||||
tools.push(
|
||||
...buildDirectTools(metadata, server.config, {
|
||||
serverId: server.id,
|
||||
serverName: server.name,
|
||||
callTool: (serverId, toolName, args) =>
|
||||
this.callMcpTool(serverId, toolName, args, { teamId, userId }),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
return tools
|
||||
}
|
||||
|
||||
/** Test a server by refreshing it and reporting the tool count (UI validation). */
|
||||
async testServer(
|
||||
serverId: string,
|
||||
): Promise<{ ok: boolean; toolCount: number; message?: string }> {
|
||||
try {
|
||||
const server = await this.refreshServer(serverId)
|
||||
return { ok: true, toolCount: server.toolCount }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return { ok: false, toolCount: 0, message }
|
||||
}
|
||||
}
|
||||
|
||||
/** Tool-name formatter ({server}_{tool}); exposed for tests. */
|
||||
getToolName(serverName: string, toolName: string): string {
|
||||
return formatToolName(serverName, toolName)
|
||||
}
|
||||
|
||||
private idleCleanupInterval?: ReturnType<typeof setInterval>
|
||||
|
||||
/** Start a periodic background timer to prune idle connections. Default check interval is 30 seconds. */
|
||||
startIdleCleanupTimer(intervalMs = 30 * 1000, defaultTimeoutMs?: number): void {
|
||||
if (this.idleCleanupInterval) return
|
||||
this.idleCleanupInterval = setInterval(() => {
|
||||
this.closeIdleConnections(defaultTimeoutMs).catch((error) => {
|
||||
logger.debug({ error }, 'Failed to close idle connections in background timer')
|
||||
})
|
||||
}, intervalMs)
|
||||
this.idleCleanupInterval.unref?.()
|
||||
}
|
||||
|
||||
/** Stop the background idle cleanup timer. */
|
||||
stopIdleCleanupTimer(): void {
|
||||
if (this.idleCleanupInterval) {
|
||||
clearInterval(this.idleCleanupInterval)
|
||||
this.idleCleanupInterval = undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Close all in-process MCP connections (used by tests/shutdown). */
|
||||
async closeAllConnections(): Promise<void> {
|
||||
this.stopIdleCleanupTimer()
|
||||
await this.manager.closeAll()
|
||||
}
|
||||
|
||||
/** Close idle connections across all active server connections. */
|
||||
async closeIdleConnections(defaultTimeoutMs?: number): Promise<string[]> {
|
||||
return this.manager.closeIdleConnections(defaultTimeoutMs)
|
||||
}
|
||||
|
||||
/** Number of live in-process connections (used by tests). */
|
||||
getConnectionCount(serverId: string): number {
|
||||
return this.manager.getConnection(serverId) ? 1 : 0
|
||||
}
|
||||
}
|
||||
|
||||
export const mcpService = new McpService()
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* In-process MCP test server for integration tests.
|
||||
*
|
||||
* Spins up a real Streamable HTTP MCP server on an ephemeral port using
|
||||
* `@modelcontextprotocol/server` (v2, stateless mode) and serves it over
|
||||
* Bun's web-standard fetch. Tests connect to it through the real MCP client
|
||||
* stack (`@modelcontextprotocol/client` v2), so connection lifecycle, tool
|
||||
* discovery, argument validation, and call round-trips are all exercised for
|
||||
* real — no mocks.
|
||||
*/
|
||||
|
||||
import { McpServer, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server'
|
||||
import { z, type ZodRawShape } from 'zod'
|
||||
|
||||
export interface TestMcpToolDef {
|
||||
name: string
|
||||
description?: string
|
||||
inputSchema?: ZodRawShape
|
||||
handler: (args: Record<string, unknown>) => Promise<unknown>
|
||||
/** When set, the tool returns an isError result with this text. */
|
||||
errorText?: string
|
||||
}
|
||||
|
||||
export interface TestMcpServerOptions {
|
||||
tools: TestMcpToolDef[]
|
||||
/** If set, respond with 401 to any request that lacks this bearer token. */
|
||||
bearerToken?: string
|
||||
/** Port to bind; defaults to an ephemeral port. */
|
||||
port?: number
|
||||
/** Override the server's self-reported identity (getServerVersion result). */
|
||||
serverInfo?: { name: string; title?: string; description?: string; instructions?: string }
|
||||
}
|
||||
|
||||
export interface RunningTestMcpServer {
|
||||
url: string
|
||||
port: number
|
||||
stop(): Promise<void>
|
||||
/** Requests received, in order, with their headers. */
|
||||
requests: Array<{ url: string; headers: Record<string, string> }>
|
||||
}
|
||||
|
||||
export async function startTestMcpServer(
|
||||
options: TestMcpServerOptions,
|
||||
): Promise<RunningTestMcpServer> {
|
||||
const { serverInfo } = options
|
||||
const server = new McpServer(
|
||||
{
|
||||
name: serverInfo?.name ?? 'test-mcp-server',
|
||||
version: '1.0.0',
|
||||
...(serverInfo?.title !== undefined ? { title: serverInfo.title } : {}),
|
||||
...(serverInfo?.description !== undefined ? { description: serverInfo.description } : {}),
|
||||
},
|
||||
serverInfo?.instructions !== undefined ? { instructions: serverInfo.instructions } : undefined,
|
||||
)
|
||||
// registerTool has overloads with incompatible zod type resolutions; bind a
|
||||
// narrow local signature so tool registration stays type-safe and simple.
|
||||
const registerTool = server.registerTool.bind(server) as unknown as (
|
||||
name: string,
|
||||
config: { description?: string; inputSchema?: ZodRawShape },
|
||||
cb: (args: Record<string, unknown>) => Promise<unknown> | unknown,
|
||||
) => unknown
|
||||
for (const tool of options.tools) {
|
||||
registerTool(
|
||||
tool.name,
|
||||
{
|
||||
description: tool.description ?? `Test tool ${tool.name}`,
|
||||
inputSchema: tool.inputSchema ?? {},
|
||||
},
|
||||
async (args) => {
|
||||
if (tool.errorText) {
|
||||
return {
|
||||
content: [{ type: 'text', text: tool.errorText }],
|
||||
isError: true,
|
||||
}
|
||||
}
|
||||
const result = await tool.handler(args as Record<string, unknown>)
|
||||
if (typeof result === 'string') {
|
||||
return { content: [{ type: 'text', text: result }] }
|
||||
}
|
||||
if (
|
||||
result &&
|
||||
typeof result === 'object' &&
|
||||
'structuredContent' in (result as Record<string, unknown>)
|
||||
) {
|
||||
const structuredContent = (result as Record<string, unknown>).structuredContent
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(structuredContent) }],
|
||||
structuredContent,
|
||||
}
|
||||
}
|
||||
return { content: [{ type: 'text', text: JSON.stringify(result) }] }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Stateless mode: one transport instance, no session IDs.
|
||||
const transport = new WebStandardStreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined,
|
||||
})
|
||||
await server.connect(transport)
|
||||
|
||||
const requests: RunningTestMcpServer['requests'] = []
|
||||
|
||||
const httpServer = Bun.serve({
|
||||
port: options.port ?? 0,
|
||||
idleTimeout: 30,
|
||||
async fetch(req) {
|
||||
requests.push({
|
||||
url: req.url,
|
||||
headers: Object.fromEntries(req.headers.entries()),
|
||||
})
|
||||
|
||||
if (options.bearerToken) {
|
||||
const auth = req.headers.get('authorization')
|
||||
if (auth !== `Bearer ${options.bearerToken}`) {
|
||||
return new Response('Unauthorized', { status: 401 })
|
||||
}
|
||||
}
|
||||
|
||||
const url = new URL(req.url)
|
||||
if (url.pathname === '/mcp') {
|
||||
return transport.handleRequest(req)
|
||||
}
|
||||
return new Response('not found', { status: 404 })
|
||||
},
|
||||
})
|
||||
|
||||
const port = httpServer.port as number
|
||||
return {
|
||||
url: `http://localhost:${port}/mcp`,
|
||||
port,
|
||||
requests,
|
||||
async stop() {
|
||||
await server.close().catch(() => {})
|
||||
httpServer.stop(true)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Common test tools: echo (returns string), add (structured math), list_sims. */
|
||||
export function standardTestTools(): TestMcpToolDef[] {
|
||||
return [
|
||||
{
|
||||
name: 'echo',
|
||||
description: 'Echoes the provided text back',
|
||||
inputSchema: { text: z.string() },
|
||||
handler: async (args) => `echo:${String(args.text)}`,
|
||||
},
|
||||
{
|
||||
name: 'add',
|
||||
description: 'Adds two numbers',
|
||||
inputSchema: { a: z.number(), b: z.number() },
|
||||
handler: async (args) => ({
|
||||
structuredContent: { sum: Number(args.a) + Number(args.b) },
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: 'list_sims',
|
||||
description: 'Lists simulator devices',
|
||||
handler: async () => ['iPhone 15 Pro', 'iPad Pro'],
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
McpToolRegistry,
|
||||
formatToolName,
|
||||
normalizeSearchText,
|
||||
sanitizeServerPrefix,
|
||||
tokenize,
|
||||
scoreToolMatch,
|
||||
paginate,
|
||||
} from './mcp-tool-registry'
|
||||
|
||||
function makeRegistry() {
|
||||
const registry = new McpToolRegistry()
|
||||
registry.setTools('server-1', 'xcodebuild', [
|
||||
{ name: 'list_sims', description: 'Lists available simulator devices' },
|
||||
{ name: 'build', description: 'Builds an Xcode project' },
|
||||
{ name: 'showBuildSettings', description: 'Shows build settings for a target' },
|
||||
])
|
||||
registry.setTools('server-2', 'github', [
|
||||
{ name: 'create_issue', description: 'Creates a GitHub issue' },
|
||||
{ name: 'list_issues', description: 'Lists issues in a repository' },
|
||||
{ name: 'search_code', description: 'Searches code across repositories' },
|
||||
])
|
||||
return registry
|
||||
}
|
||||
|
||||
describe('formatToolName', () => {
|
||||
it('prefixes server name and sanitizes dots', () => {
|
||||
expect(formatToolName('xcodebuild', 'list_sims')).toBe('xcodebuild_list_sims')
|
||||
expect(formatToolName('my-server', 'tool.name')).toBe('my_server_tool_name')
|
||||
})
|
||||
|
||||
it('sanitizes spaces and punctuation in the server prefix', () => {
|
||||
expect(formatToolName('Meta Server', 'echo')).toBe('Meta_Server_echo')
|
||||
expect(formatToolName('my.server/v1', 'list')).toBe('my_server_v1_list')
|
||||
expect(formatToolName('!!!', 'list')).toBe('list')
|
||||
})
|
||||
})
|
||||
|
||||
describe('sanitizeServerPrefix', () => {
|
||||
it('collapses non-alphanumeric runs into a single underscore', () => {
|
||||
expect(sanitizeServerPrefix('Meta Server')).toBe('Meta_Server')
|
||||
expect(sanitizeServerPrefix('github.com')).toBe('github_com')
|
||||
expect(sanitizeServerPrefix(' a b ')).toBe('a_b')
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeSearchText / tokenize', () => {
|
||||
it('splits camelCase, snake_case, dots and hyphens', () => {
|
||||
expect(tokenize('showBuildSettings')).toEqual(['show', 'build', 'settings'])
|
||||
expect(tokenize('list_sims')).toEqual(['list', 'sims'])
|
||||
expect(tokenize('search.code-v2')).toEqual(['search', 'code', 'v2'])
|
||||
})
|
||||
|
||||
it('lowercases input', () => {
|
||||
expect(normalizeSearchText('ListSims')).toBe('list sims')
|
||||
})
|
||||
})
|
||||
|
||||
describe('scoreToolMatch', () => {
|
||||
const tool = {
|
||||
name: 'xcodebuild_list_sims',
|
||||
originalName: 'list_sims',
|
||||
description: 'Lists available simulator devices',
|
||||
}
|
||||
|
||||
it('returns null for empty queries', () => {
|
||||
expect(scoreToolMatch(tool, 'xcodebuild', '')).toBeNull()
|
||||
expect(scoreToolMatch(tool, 'xcodebuild', ' ')).toBeNull()
|
||||
})
|
||||
|
||||
it('scores exact name matches highest', () => {
|
||||
const exact = scoreToolMatch(tool, 'xcodebuild', 'list_sims')
|
||||
const partial = scoreToolMatch(tool, 'xcodebuild', 'sims')
|
||||
const unrelated = scoreToolMatch(tool, 'xcodebuild', 'zzz')
|
||||
expect(exact).not.toBeNull()
|
||||
expect(partial).not.toBeNull()
|
||||
expect(unrelated).toBeNull()
|
||||
expect(exact!).toBeGreaterThan(partial!)
|
||||
})
|
||||
|
||||
it('matches camelCase queries against camelCase original names', () => {
|
||||
const camel = scoreToolMatch(
|
||||
{
|
||||
name: 'xcodebuild_showBuildSettings',
|
||||
originalName: 'showBuildSettings',
|
||||
description: 'Shows build settings',
|
||||
},
|
||||
'xcodebuild',
|
||||
'showBuildSettings',
|
||||
)
|
||||
expect(camel).not.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('registry searchTools', () => {
|
||||
it('finds tools across servers with ranking', () => {
|
||||
const registry = makeRegistry()
|
||||
const names = new Map([
|
||||
['server-1', 'xcodebuild'],
|
||||
['server-2', 'github'],
|
||||
])
|
||||
const { items, total } = registry.searchTools('list', undefined, names)
|
||||
expect(total).toBeGreaterThanOrEqual(2)
|
||||
// Both list_sims and list_issues should be found.
|
||||
const found = items.map((m) => m.tool.originalName)
|
||||
expect(found).toContain('list_sims')
|
||||
expect(found).toContain('list_issues')
|
||||
// Sorting is by score descending.
|
||||
for (let i = 1; i < items.length; i++) {
|
||||
expect(items[i - 1].score).toBeGreaterThanOrEqual(items[i].score)
|
||||
}
|
||||
})
|
||||
|
||||
it('scopes search to one server', () => {
|
||||
const registry = makeRegistry()
|
||||
const names = new Map([
|
||||
['server-1', 'xcodebuild'],
|
||||
['server-2', 'github'],
|
||||
])
|
||||
const { items, total } = registry.searchTools('list', 'server-1', names)
|
||||
expect(total).toBe(1)
|
||||
expect(items[0].tool.originalName).toBe('list_sims')
|
||||
})
|
||||
|
||||
it('honors limit/offset pagination', () => {
|
||||
const registry = makeRegistry()
|
||||
const names = new Map([
|
||||
['server-1', 'xcodebuild'],
|
||||
['server-2', 'github'],
|
||||
])
|
||||
const first = registry.searchTools('list', undefined, names, 1, 0)
|
||||
expect(first.items.length).toBe(1)
|
||||
expect(first.hasMore).toBe(true)
|
||||
const second = registry.searchTools('list', undefined, names, 1, 1)
|
||||
expect(second.items.length).toBe(1)
|
||||
expect(second.nextOffset).toBeNull()
|
||||
})
|
||||
|
||||
it('coverage gate rejects weak matches', () => {
|
||||
const registry = makeRegistry()
|
||||
const names = new Map([['server-1', 'xcodebuild']])
|
||||
const { total } = registry.searchTools('building skyscrapers', 'server-1', names)
|
||||
expect(total).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('registry findTool', () => {
|
||||
it('finds by prefixed or original name', () => {
|
||||
const registry = makeRegistry()
|
||||
expect(registry.findTool('xcodebuild_list_sims')?.tool.originalName).toBe('list_sims')
|
||||
expect(registry.findTool('list_sims')?.tool.originalName).toBe('list_sims')
|
||||
expect(registry.findTool('list_sims', 'server-1')?.tool.originalName).toBe('list_sims')
|
||||
expect(registry.findTool('list_sims', 'server-2')).toBeUndefined()
|
||||
expect(registry.findTool('nope')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns did-you-mean suggestions', () => {
|
||||
const registry = makeRegistry()
|
||||
const suggestions = registry.rankSuggestions(
|
||||
'xcodebuild_list_sim',
|
||||
5,
|
||||
new Map([
|
||||
['server-1', 'xcodebuild'],
|
||||
['server-2', 'github'],
|
||||
]),
|
||||
)
|
||||
expect(suggestions).toContain('xcodebuild_list_sims')
|
||||
})
|
||||
})
|
||||
|
||||
describe('paginate', () => {
|
||||
it('handles empty input and offsets beyond length', () => {
|
||||
expect(paginate([], 0, 10)).toEqual({ items: [], total: 0, hasMore: false, nextOffset: null })
|
||||
expect(paginate([1, 2, 3], 100, 10)).toEqual({
|
||||
items: [],
|
||||
total: 3,
|
||||
hasMore: false,
|
||||
nextOffset: null,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* MCP tool registry — in-memory tool metadata + search
|
||||
*
|
||||
* Per-agent registry of discovered tool metadata keyed by server id, created
|
||||
* fresh by `McpService.buildAgentTools` and warmed from the persisted DB
|
||||
* cache (`McpServer.tools`). Scoping discovery to the agent's assigned
|
||||
* servers means unassigned/disabled servers can never be searched, suggested,
|
||||
* or called. (Adapted from pi-mcp-adapter's ToolMetadata + search-ranking.ts.)
|
||||
*/
|
||||
|
||||
import type { McpTool } from './mcp-server-manager'
|
||||
|
||||
export interface ToolMetadata {
|
||||
/** Prefixed tool name (e.g. "xcodebuild_list_sims"). */
|
||||
name: string
|
||||
/** Original MCP tool name (e.g. "list_sims"). */
|
||||
originalName: string
|
||||
description: string
|
||||
inputSchema?: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a server name into a safe tool-name prefix: any run of
|
||||
* non-alphanumeric characters becomes a single underscore. Server-reported
|
||||
* names/titles may contain spaces, dots or other punctuation.
|
||||
*/
|
||||
export function sanitizeServerPrefix(serverName: string): string {
|
||||
return serverName.replace(/[^a-zA-Z0-9_]+/g, '_').replace(/^_+|_+$/g, '')
|
||||
}
|
||||
|
||||
/** Format a tool name with the "{server}_{tool}" prefix (dots sanitized). */
|
||||
export function formatToolName(serverName: string, toolName: string): string {
|
||||
const serverPart = sanitizeServerPrefix(serverName)
|
||||
const sanitized = toolName.replace(/\./g, '_')
|
||||
return serverPart ? `${serverPart}_${sanitized}` : sanitized
|
||||
}
|
||||
|
||||
const MIN_STEM_LENGTH = 4
|
||||
|
||||
const FIELD_WEIGHTS = {
|
||||
name: 12,
|
||||
originalName: 10,
|
||||
server: 8,
|
||||
description: 5,
|
||||
} as const
|
||||
|
||||
export interface RankedToolMatch {
|
||||
server: string
|
||||
tool: ToolMetadata
|
||||
score: number
|
||||
}
|
||||
|
||||
export function normalizeSearchText(value: string): string {
|
||||
return value
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.replace(/[_./:-]+/g, ' ')
|
||||
.toLowerCase()
|
||||
}
|
||||
|
||||
export function tokenize(value: string): string[] {
|
||||
return normalizeSearchText(value)
|
||||
.split(/[^a-z0-9]+/)
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
export function scoreToolMatch(tool: ToolMetadata, server: string, query: string): number | null {
|
||||
const normalizedQuery = normalizeSearchText(query).trim()
|
||||
const queryTokens = tokenize(query)
|
||||
if (queryTokens.length === 0) return null
|
||||
|
||||
const fields = {
|
||||
name: normalizeSearchText(tool.name),
|
||||
originalName: normalizeSearchText(tool.originalName),
|
||||
server: normalizeSearchText(server),
|
||||
description: normalizeSearchText(tool.description),
|
||||
}
|
||||
let score = 0
|
||||
let phraseMatched = false
|
||||
let wholeFieldExact = false
|
||||
const matchedTokens = new Set<string>()
|
||||
|
||||
for (const [field, value] of Object.entries(fields) as Array<
|
||||
[keyof typeof FIELD_WEIGHTS, string]
|
||||
>) {
|
||||
const weight = FIELD_WEIGHTS[field]
|
||||
const fieldTokens = tokenize(value)
|
||||
if (value === normalizedQuery) {
|
||||
score += weight * 14
|
||||
phraseMatched = true
|
||||
wholeFieldExact = true
|
||||
} else if (value.startsWith(normalizedQuery)) {
|
||||
score += weight * 9
|
||||
phraseMatched = true
|
||||
} else if (value.includes(normalizedQuery)) {
|
||||
score += weight * 6
|
||||
phraseMatched = true
|
||||
}
|
||||
|
||||
for (const token of queryTokens) {
|
||||
if (fieldTokens.includes(token)) {
|
||||
score += weight * 4
|
||||
matchedTokens.add(token)
|
||||
} else if (
|
||||
fieldTokens.some(
|
||||
(fieldToken) =>
|
||||
fieldToken.startsWith(token) ||
|
||||
(fieldToken.length >= MIN_STEM_LENGTH && token.startsWith(fieldToken)),
|
||||
)
|
||||
) {
|
||||
score += weight * 2
|
||||
matchedTokens.add(token)
|
||||
} else if (value.includes(token)) {
|
||||
score += weight
|
||||
matchedTokens.add(token)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const coverage = matchedTokens.size / queryTokens.length
|
||||
if (!phraseMatched && (queryTokens.length <= 2 ? coverage !== 1 : coverage < 0.6)) return null
|
||||
|
||||
score += coverage === 1 ? 25 : Math.round(coverage * 10)
|
||||
const firstQueryToken = queryTokens[0]
|
||||
if (firstQueryToken !== undefined && tokenize(fields.name).includes(firstQueryToken)) score += 8
|
||||
if (wholeFieldExact) score += 20
|
||||
return score
|
||||
}
|
||||
|
||||
export function paginate<T>(
|
||||
items: T[],
|
||||
offset: number,
|
||||
limit: number,
|
||||
): { items: T[]; total: number; hasMore: boolean; nextOffset: number | null } {
|
||||
const safeOffset = Number.isFinite(offset) ? Math.max(0, Math.trunc(offset)) : 0
|
||||
const safeLimit = Number.isFinite(limit) ? Math.max(1, Math.trunc(limit)) : 1
|
||||
const total = items.length
|
||||
const page = items.slice(safeOffset, safeOffset + safeLimit)
|
||||
const nextOffset = safeOffset + page.length
|
||||
return {
|
||||
items: page,
|
||||
total,
|
||||
hasMore: nextOffset < total,
|
||||
nextOffset: nextOffset < total ? nextOffset : null,
|
||||
}
|
||||
}
|
||||
|
||||
export class McpToolRegistry {
|
||||
private readonly metadataByServer = new Map<string, ToolMetadata[]>()
|
||||
|
||||
/** Rebuild the metadata for one server from its discovered tools. */
|
||||
setTools(serverId: string, serverName: string, tools: McpTool[]): void {
|
||||
const metadata: ToolMetadata[] = tools.map((tool) => ({
|
||||
name: formatToolName(serverName, tool.name),
|
||||
originalName: tool.name,
|
||||
description: tool.description ?? '',
|
||||
...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
|
||||
}))
|
||||
metadata.sort((a, b) => a.name.localeCompare(b.name))
|
||||
this.metadataByServer.set(serverId, metadata)
|
||||
}
|
||||
|
||||
getTools(serverId: string): ToolMetadata[] {
|
||||
return this.metadataByServer.get(serverId) ?? []
|
||||
}
|
||||
|
||||
getAllTools(): Array<{ serverId: string; serverName: string; tool: ToolMetadata }> {
|
||||
const result: Array<{ serverId: string; serverName: string; tool: ToolMetadata }> = []
|
||||
for (const [serverId, metadata] of this.metadataByServer.entries()) {
|
||||
for (const tool of metadata) {
|
||||
result.push({ serverId, serverName: serverId, tool })
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
clear(serverId: string): void {
|
||||
this.metadataByServer.delete(serverId)
|
||||
}
|
||||
|
||||
clearAll(): void {
|
||||
this.metadataByServer.clear()
|
||||
}
|
||||
|
||||
/** Find a tool by prefixed or original name, optionally within one server. */
|
||||
findTool(name: string, serverId?: string): { serverId: string; tool: ToolMetadata } | undefined {
|
||||
for (const [sid, metadata] of this.metadataByServer.entries()) {
|
||||
if (serverId && sid !== serverId) continue
|
||||
const found = metadata.find((tool) => tool.name === name || tool.originalName === name)
|
||||
if (found) return { serverId: sid, tool: found }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Ranked search across all (or one) server's tools. */
|
||||
searchTools(
|
||||
query: string,
|
||||
serverId?: string,
|
||||
serverNames: Map<string, string> = new Map(),
|
||||
limit = 12,
|
||||
offset = 0,
|
||||
): { items: RankedToolMatch[]; total: number; hasMore: boolean; nextOffset: number | null } {
|
||||
const matches: RankedToolMatch[] = []
|
||||
for (const [sid, metadata] of this.metadataByServer.entries()) {
|
||||
if (serverId && sid !== serverId) continue
|
||||
const serverName = serverNames.get(sid) ?? sid
|
||||
for (const tool of metadata) {
|
||||
const score = scoreToolMatch(tool, serverName, query)
|
||||
if (score !== null) matches.push({ server: sid, tool, score })
|
||||
}
|
||||
}
|
||||
matches.sort((a, b) => b.score - a.score || a.tool.name.localeCompare(b.tool.name))
|
||||
return paginate(matches, offset, limit)
|
||||
}
|
||||
|
||||
/** "Did you mean" suggestions for a tool name. */
|
||||
rankSuggestions(
|
||||
name: string,
|
||||
limit: number,
|
||||
serverNames: Map<string, string> = new Map(),
|
||||
): string[] {
|
||||
return this.searchTools(name, undefined, serverNames, limit, 0).items.map((m) => m.tool.name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { toToolParameters, formatSchema } from './mcp-tool-schema'
|
||||
import { Compile } from 'typebox/compile'
|
||||
|
||||
describe('toToolParameters', () => {
|
||||
it('passes through a plain object schema', () => {
|
||||
const schema = {
|
||||
type: 'object',
|
||||
properties: { query: { type: 'string' } },
|
||||
required: ['query'],
|
||||
}
|
||||
const params = toToolParameters(schema)
|
||||
expect(params).toMatchObject({ type: 'object', properties: { query: { type: 'string' } } })
|
||||
// The resulting schema must compile with the same validator pi-ai uses.
|
||||
expect(() => Compile(params)).not.toThrow()
|
||||
})
|
||||
|
||||
it('strips $schema / $id / $comment keywords', () => {
|
||||
const params = toToolParameters({
|
||||
$schema: 'http://json-schema.org/draft-07/schema#',
|
||||
$id: 'https://example.com/tool.json',
|
||||
$comment: 'strip me',
|
||||
type: 'object',
|
||||
properties: { a: { type: 'string' } },
|
||||
})
|
||||
expect(JSON.stringify(params)).not.toContain('$schema')
|
||||
expect(JSON.stringify(params)).not.toContain('$id')
|
||||
expect(JSON.stringify(params)).not.toContain('$comment')
|
||||
})
|
||||
|
||||
it('supports $defs / $ref schemas', () => {
|
||||
const params = toToolParameters({
|
||||
type: 'object',
|
||||
properties: { q: { $ref: '#/$defs/query' } },
|
||||
$defs: { query: { type: 'string' } },
|
||||
required: ['q'],
|
||||
})
|
||||
const compiled = Compile(params)
|
||||
expect(compiled.Check({ q: 'hello' })).toBe(true)
|
||||
})
|
||||
|
||||
it('supports anyOf and enums', () => {
|
||||
const params = toToolParameters({
|
||||
type: 'object',
|
||||
properties: {
|
||||
value: { anyOf: [{ type: 'string' }, { type: 'number' }] },
|
||||
color: { type: 'string', enum: ['red', 'blue'] },
|
||||
},
|
||||
})
|
||||
const compiled = Compile(params)
|
||||
expect(compiled.Check({ value: 42, color: 'red' })).toBe(true)
|
||||
expect(compiled.Check({ value: 'x', color: 'green' })).toBe(false)
|
||||
})
|
||||
|
||||
it('supports additionalProperties and patternProperties', () => {
|
||||
const params = toToolParameters({
|
||||
type: 'object',
|
||||
properties: { a: { type: 'string' } },
|
||||
additionalProperties: false,
|
||||
})
|
||||
const compiled = Compile(params)
|
||||
expect(compiled.Check({ a: 'x' })).toBe(true)
|
||||
|
||||
const patterned = toToolParameters({
|
||||
type: 'object',
|
||||
patternProperties: { '^x-': { type: 'string' } },
|
||||
})
|
||||
expect(() => Compile(patterned)).not.toThrow()
|
||||
})
|
||||
|
||||
it('normalizes non-object roots to an object', () => {
|
||||
expect(toToolParameters({ type: 'string' })).toMatchObject({ type: 'object' })
|
||||
})
|
||||
|
||||
it('falls back to a permissive record for invalid schemas', () => {
|
||||
const params = toToolParameters({ type: 'object', properties: { bad: { type: 'not-a-type' } } })
|
||||
const compiled = Compile(params)
|
||||
// Fallback must accept arbitrary arguments.
|
||||
expect(compiled.Check({ anything: 123, nested: { x: 1 } })).toBe(true)
|
||||
})
|
||||
|
||||
it('handles undefined / empty input', () => {
|
||||
expect(toToolParameters(undefined)).toMatchObject({ type: 'object' })
|
||||
expect(toToolParameters(null)).toMatchObject({ type: 'object' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatSchema', () => {
|
||||
it('formats JSON Schema as indented text', () => {
|
||||
const text = formatSchema({ type: 'object', properties: { a: { type: 'string' } } })
|
||||
expect(text).toContain('"type": "object"')
|
||||
expect(text).toContain('"properties"')
|
||||
})
|
||||
|
||||
it('returns empty string for non-objects', () => {
|
||||
expect(formatSchema(undefined)).toBe('')
|
||||
expect(formatSchema(42)).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* MCP tool schema conversion
|
||||
*
|
||||
* Normalizes an MCP tool's JSON Schema `inputSchema` into a TypeBox-compatible
|
||||
* `TSchema` that the pi-ai harness can validate and providers can serialize.
|
||||
*
|
||||
* - Ensures `type: 'object'` (MCP tool arguments are always objects).
|
||||
* - Strips keywords the harness does not understand (`$schema`, `$id`, `$comment`).
|
||||
* - Verifies the schema compiles with `typebox/compile`; if it does not, falls
|
||||
* back to a permissive `Record<string, unknown>` so the tool still works
|
||||
* (arguments pass through to `callTool`).
|
||||
*/
|
||||
|
||||
import { Compile } from 'typebox/compile'
|
||||
import { Type, type TSchema } from '@sinclair/typebox'
|
||||
|
||||
const STRIPPED_KEYS = new Set(['$schema', '$id', '$comment'])
|
||||
|
||||
function normalizeInputSchema(schema: unknown): Record<string, unknown> {
|
||||
if (!schema || typeof schema !== 'object' || Array.isArray(schema)) {
|
||||
return { type: 'object' }
|
||||
}
|
||||
const source = schema as Record<string, unknown>
|
||||
const result: Record<string, unknown> = {}
|
||||
for (const [key, value] of Object.entries(source)) {
|
||||
if (STRIPPED_KEYS.has(key)) continue
|
||||
if (value === undefined) continue
|
||||
result[key] = value
|
||||
}
|
||||
// MCP tool parameters are always a JSON object.
|
||||
if (result.type !== 'object' && result.type !== undefined) {
|
||||
result.type = 'object'
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an MCP `inputSchema` into an AgentTool `parameters` schema.
|
||||
*/
|
||||
export function toToolParameters(inputSchema: unknown): TSchema {
|
||||
const normalized = normalizeInputSchema(inputSchema)
|
||||
try {
|
||||
Compile(normalized)
|
||||
return normalized as TSchema
|
||||
} catch {
|
||||
// Fall back to a permissive object schema so the tool remains usable.
|
||||
return Type.Record(Type.String(), Type.Unknown())
|
||||
}
|
||||
}
|
||||
|
||||
/** Format a JSON Schema as indented text (used by proxy describe/search). */
|
||||
export function formatSchema(schema: unknown, indent = ''): string {
|
||||
if (!schema || typeof schema !== 'object') return ''
|
||||
try {
|
||||
return JSON.stringify(schema, null, 2)
|
||||
.split('\n')
|
||||
.map((line) => `${indent}${line}`)
|
||||
.join('\n')
|
||||
} catch {
|
||||
return String(schema)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user