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:
Yiling-J
2026-08-11 11:01:38 +08:00
committed by GitHub
parent 1daeaf51ef
commit 1b5cbf936a
149 changed files with 16076 additions and 24 deletions
+486
View File
@@ -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'))
},
}
}