@mcpjam/sdk 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.cjs +590 -239
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +589 -235
- package/dist/index.js.map +1 -1
- package/dist/mcp-client-manager/index.cjs +102 -14
- package/dist/mcp-client-manager/index.cjs.map +1 -1
- package/dist/mcp-client-manager/index.d.cts +19 -21
- package/dist/mcp-client-manager/index.d.ts +19 -21
- package/dist/mcp-client-manager/index.js +102 -16
- package/dist/mcp-client-manager/index.js.map +1 -1
- package/package.json +5 -7
- package/dist/chunk-PZ5AY32C.js +0 -10
- package/dist/chunk-PZ5AY32C.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../mcp-client-manager/index.ts","../../mcp-client-manager/tool-converters.ts"],"sourcesContent":["import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { ClientOptions } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport {\n getDefaultEnvironment,\n StdioClientTransport,\n} from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport type { StreamableHTTPClientTransportOptions } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { DEFAULT_REQUEST_TIMEOUT_MSEC } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport {\n CallToolResultSchema,\n ElicitRequestSchema,\n ResourceListChangedNotificationSchema,\n ResourceUpdatedNotificationSchema,\n PromptListChangedNotificationSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type {\n ElicitRequest,\n ElicitResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n convertMCPToolsToVercelTools,\n type ConvertedToolSet,\n type ToolSchemaOverrides,\n} from \"./tool-converters.js\";\nimport type { ToolCallOptions, ToolSet } from \"ai\";\ntype ClientCapabilityOptions = NonNullable<ClientOptions[\"capabilities\"]>;\n\ntype BaseServerConfig = {\n capabilities?: ClientCapabilityOptions;\n timeout?: number;\n version?: string;\n onError?: (error: unknown) => void;\n};\n\ntype StdioServerConfig = BaseServerConfig & {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n\n url?: never;\n requestInit?: never;\n eventSourceInit?: never;\n authProvider?: never;\n reconnectionOptions?: never;\n sessionId?: never;\n preferSSE?: never;\n};\n\ntype HttpServerConfig = BaseServerConfig & {\n url: URL;\n requestInit?: StreamableHTTPClientTransportOptions[\"requestInit\"];\n eventSourceInit?: SSEClientTransportOptions[\"eventSourceInit\"];\n authProvider?: StreamableHTTPClientTransportOptions[\"authProvider\"];\n reconnectionOptions?: StreamableHTTPClientTransportOptions[\"reconnectionOptions\"];\n sessionId?: StreamableHTTPClientTransportOptions[\"sessionId\"];\n preferSSE?: boolean;\n\n command?: never;\n args?: never;\n env?: never;\n};\n\nexport type MCPServerConfig = StdioServerConfig | HttpServerConfig;\nexport type MCPClientManagerConfig = Record<string, MCPServerConfig>;\n\ntype NotificationSchema = Parameters<Client[\"setNotificationHandler\"]>[0];\ntype NotificationHandler = Parameters<Client[\"setNotificationHandler\"]>[1];\n\ninterface ManagedClientState {\n config: MCPServerConfig;\n timeout: number;\n client?: Client;\n transport?: Transport;\n promise?: Promise<Client>;\n}\n\n// Pending state is tracked inside ManagedClientState.promise\n\ntype ClientRequestOptions = RequestOptions;\ntype CallToolOptions = RequestOptions;\n\ntype ListResourcesParams = Parameters<Client[\"listResources\"]>[0];\ntype ListResourceTemplatesParams = Parameters<\n Client[\"listResourceTemplates\"]\n>[0];\ntype ReadResourceParams = Parameters<Client[\"readResource\"]>[0];\ntype SubscribeResourceParams = Parameters<Client[\"subscribeResource\"]>[0];\ntype UnsubscribeResourceParams = Parameters<Client[\"unsubscribeResource\"]>[0];\ntype ListPromptsParams = Parameters<Client[\"listPrompts\"]>[0];\ntype GetPromptParams = Parameters<Client[\"getPrompt\"]>[0];\ntype ListToolsResult = Awaited<ReturnType<Client[\"listTools\"]>>;\n\nexport type MCPConnectionStatus = \"connected\" | \"connecting\" | \"disconnected\";\ntype ServerSummary = {\n id: string;\n status: MCPConnectionStatus;\n config?: MCPServerConfig;\n};\n\nexport type ExecuteToolArguments = Record<string, unknown>;\nexport type ElicitationHandler = (\n params: ElicitRequest[\"params\"],\n) => Promise<ElicitResult> | ElicitResult;\n\nexport class MCPClientManager {\n private readonly clientStates = new Map<string, ManagedClientState>();\n private readonly notificationHandlers = new Map<\n string,\n Map<NotificationSchema, Set<NotificationHandler>>\n >();\n private readonly elicitationHandlers = new Map<string, ElicitationHandler>();\n private readonly toolsMetadataCache = new Map<string, Map<string, any>>();\n private readonly defaultClientVersion: string;\n private readonly defaultCapabilities: ClientCapabilityOptions;\n private readonly defaultTimeout: number;\n // Global elicitation callback support (used by streaming chat endpoint)\n private elicitationCallback?: (request: {\n requestId: string;\n message: string;\n schema: unknown;\n }) => Promise<ElicitResult> | ElicitResult;\n private readonly pendingElicitations = new Map<\n string,\n {\n resolve: (value: ElicitResult) => void;\n reject: (error: unknown) => void;\n }\n >();\n\n constructor(\n servers: MCPClientManagerConfig = {},\n options: {\n defaultClientVersion?: string;\n defaultCapabilities?: ClientCapabilityOptions;\n defaultTimeout?: number;\n } = {},\n ) {\n this.defaultClientVersion = options.defaultClientVersion ?? \"1.0.0\";\n this.defaultCapabilities = { ...(options.defaultCapabilities ?? {}) };\n this.defaultTimeout =\n options.defaultTimeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n\n for (const [id, config] of Object.entries(servers)) {\n void this.connectToServer(id, config);\n }\n }\n\n listServers(): string[] {\n return Array.from(this.clientStates.keys());\n }\n\n hasServer(serverId: string): boolean {\n return this.clientStates.has(serverId);\n }\n\n getServerSummaries(): ServerSummary[] {\n return Array.from(this.clientStates.entries()).map(([serverId, state]) => ({\n id: serverId,\n status: this.resolveConnectionStatus(state),\n config: state.config,\n }));\n }\n\n getConnectionStatus(serverId: string): MCPConnectionStatus {\n return this.resolveConnectionStatus(this.clientStates.get(serverId));\n }\n\n getServerConfig(serverId: string): MCPServerConfig | undefined {\n return this.clientStates.get(serverId)?.config;\n }\n\n async connectToServer(\n serverId: string,\n config: MCPServerConfig,\n ): Promise<Client> {\n if (this.clientStates.has(serverId)) {\n throw new Error(`MCP server \"${serverId}\" is already connected.`);\n }\n const timeout = this.getTimeout(config);\n const state = this.clientStates.get(serverId) ?? {\n config,\n timeout,\n };\n // Update config/timeout on every call\n state.config = config;\n state.timeout = timeout;\n // If already connected, return the client\n if (state.client) {\n this.clientStates.set(serverId, state);\n return state.client;\n }\n // If connection is in-flight, reuse the promise\n if (state.promise) {\n this.clientStates.set(serverId, state);\n return state.promise;\n }\n\n const connectionPromise = (async () => {\n const client = new Client(\n {\n name: serverId,\n version: config.version ?? this.defaultClientVersion,\n },\n {\n capabilities: this.buildCapabilities(config),\n },\n );\n\n this.applyNotificationHandlers(serverId, client);\n this.applyElicitationHandler(serverId, client);\n\n if (config.onError) {\n client.onerror = (error) => {\n config.onError?.(error);\n };\n }\n\n client.onclose = () => {\n this.resetState(serverId);\n };\n\n let transport: Transport;\n if (this.isStdioConfig(config)) {\n transport = await this.connectViaStdio(client, config, timeout);\n } else {\n transport = await this.connectViaHttp(\n serverId,\n client,\n config,\n timeout,\n );\n }\n\n state.client = client;\n state.transport = transport;\n // clear pending\n state.promise = undefined;\n this.clientStates.set(serverId, state);\n\n return client;\n })().catch((error) => {\n // Clear pending but keep config so the server remains registered\n state.promise = undefined;\n state.client = undefined;\n state.transport = undefined;\n this.clientStates.set(serverId, state);\n throw error;\n });\n\n state.promise = connectionPromise;\n this.clientStates.set(serverId, state);\n return connectionPromise;\n }\n\n async disconnectServer(serverId: string): Promise<void> {\n const client = this.getClientById(serverId);\n try {\n await client.close();\n } finally {\n if (client.transport) {\n await this.safeCloseTransport(client.transport);\n }\n this.resetState(serverId);\n }\n }\n\n removeServer(serverId: string): void {\n this.resetState(serverId);\n this.notificationHandlers.delete(serverId);\n this.elicitationHandlers.delete(serverId);\n }\n\n async disconnectAllServers(): Promise<void> {\n const serverIds = this.listServers();\n await Promise.all(\n serverIds.map((serverId) => this.disconnectServer(serverId)),\n );\n\n for (const serverId of serverIds) {\n this.resetState(serverId);\n this.notificationHandlers.delete(serverId);\n this.elicitationHandlers.delete(serverId);\n }\n }\n\n async listTools(\n serverId: string,\n params?: Parameters<Client[\"listTools\"]>[0],\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n try {\n const result = await client.listTools(\n params,\n this.withTimeout(serverId, options),\n );\n\n const metadataMap = new Map<string, any>();\n for (const tool of result.tools) {\n if (tool._meta) {\n metadataMap.set(tool.name, tool._meta);\n }\n }\n this.toolsMetadataCache.set(serverId, metadataMap);\n\n return result;\n } catch (error) {\n if (this.isMethodUnavailableError(error, \"tools/list\")) {\n this.toolsMetadataCache.set(serverId, new Map());\n return { tools: [] } as Awaited<ReturnType<Client[\"listTools\"]>>;\n }\n throw error;\n }\n }\n\n async getTools(serverIds?: string[]): Promise<ListToolsResult> {\n const targetServerIds =\n serverIds && serverIds.length > 0 ? serverIds : this.listServers();\n\n const toolLists = await Promise.all(\n targetServerIds.map(async (serverId) => {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n const result = await client.listTools(\n undefined,\n this.withTimeout(serverId),\n );\n\n const metadataMap = new Map<string, any>();\n for (const tool of result.tools) {\n if (tool._meta) {\n metadataMap.set(tool.name, tool._meta);\n }\n }\n this.toolsMetadataCache.set(serverId, metadataMap);\n\n return result.tools;\n }),\n );\n return { tools: toolLists.flat() } as ListToolsResult;\n }\n\n getAllToolsMetadata(serverId: string): Record<string, Record<string, any>> {\n const metadataMap = this.toolsMetadataCache.get(serverId);\n return metadataMap ? Object.fromEntries(metadataMap) : {};\n }\n\n pingServer(serverId: string, options?: RequestOptions) {\n const client = this.getClientById(serverId);\n try {\n client.ping(options);\n } catch (error) {\n throw new Error(\n `Failed to ping MCP server \"${serverId}\": ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n async getToolsForAiSdk(\n serverIds?: string[] | string,\n options: { schemas?: ToolSchemaOverrides | \"automatic\" } = {},\n ): Promise<ToolSet> {\n const ids = Array.isArray(serverIds)\n ? serverIds\n : serverIds\n ? [serverIds]\n : this.listServers();\n\n const loadForServer = async (id: string): Promise<ToolSet> => {\n await this.ensureConnected(id);\n const listToolsResult = await this.listTools(id);\n return convertMCPToolsToVercelTools(listToolsResult, {\n schemas: options.schemas,\n callTool: async ({ name, args, options: callOptions }) => {\n const requestOptions = callOptions?.abortSignal\n ? { signal: callOptions.abortSignal }\n : undefined;\n const result = await this.executeTool(\n id,\n name,\n (args ?? {}) as ExecuteToolArguments,\n requestOptions,\n );\n return CallToolResultSchema.parse(result);\n },\n });\n };\n\n const perServerTools = await Promise.all(\n ids.map(async (id) => {\n try {\n const tools = await loadForServer(id);\n // Attach server id metadata to each tool object for downstream extraction\n for (const [name, tool] of Object.entries(tools)) {\n (tool as any)._serverId = id;\n }\n return tools;\n } catch (error) {\n if (this.isMethodUnavailableError(error, \"tools/list\")) {\n return {} as ToolSet;\n }\n throw error;\n }\n }),\n );\n\n // Flatten into a single ToolSet (last-in wins for name collisions)\n const flattened: ToolSet = {};\n for (const toolset of perServerTools) {\n for (const [name, tool] of Object.entries(toolset)) {\n flattened[name] = tool;\n }\n }\n\n return flattened;\n }\n\n async executeTool(\n serverId: string,\n toolName: string,\n args: ExecuteToolArguments = {},\n options?: CallToolOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n return client.callTool(\n {\n name: toolName,\n arguments: args,\n },\n CallToolResultSchema,\n this.withTimeout(serverId, options),\n );\n }\n\n async listResources(\n serverId: string,\n params?: ListResourcesParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n try {\n return await client.listResources(\n params,\n this.withTimeout(serverId, options),\n );\n } catch (error) {\n if (this.isMethodUnavailableError(error, \"resources/list\")) {\n return {\n resources: [],\n } as Awaited<ReturnType<Client[\"listResources\"]>>;\n }\n throw error;\n }\n }\n\n async readResource(\n serverId: string,\n params: ReadResourceParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n return client.readResource(params, this.withTimeout(serverId, options));\n }\n\n async subscribeResource(\n serverId: string,\n params: SubscribeResourceParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n return client.subscribeResource(\n params,\n this.withTimeout(serverId, options),\n );\n }\n\n async unsubscribeResource(\n serverId: string,\n params: UnsubscribeResourceParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n return client.unsubscribeResource(\n params,\n this.withTimeout(serverId, options),\n );\n }\n\n async listResourceTemplates(\n serverId: string,\n params?: ListResourceTemplatesParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n return client.listResourceTemplates(\n params,\n this.withTimeout(serverId, options),\n );\n }\n\n async listPrompts(\n serverId: string,\n params?: ListPromptsParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n try {\n return await client.listPrompts(\n params,\n this.withTimeout(serverId, options),\n );\n } catch (error) {\n if (this.isMethodUnavailableError(error, \"prompts/list\")) {\n return {\n prompts: [],\n } as Awaited<ReturnType<Client[\"listPrompts\"]>>;\n }\n throw error;\n }\n }\n\n async getPrompt(\n serverId: string,\n params: GetPromptParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n return client.getPrompt(params, this.withTimeout(serverId, options));\n }\n\n getSessionIdByServer(serverId: string): string | undefined {\n const state = this.clientStates.get(serverId);\n if (!state?.transport) {\n throw new Error(`Unknown MCP server \"${serverId}\".`);\n }\n if (state.transport instanceof StreamableHTTPClientTransport) {\n return state.transport.sessionId;\n }\n throw new Error(\n `Server \"${serverId}\" must be Streamable HTTP to get the session ID.`,\n );\n }\n\n addNotificationHandler(\n serverId: string,\n schema: NotificationSchema,\n handler: NotificationHandler,\n ): void {\n const serverHandlers = this.notificationHandlers.get(serverId) ?? new Map();\n const handlersForSchema =\n serverHandlers.get(schema) ?? new Set<NotificationHandler>();\n handlersForSchema.add(handler);\n serverHandlers.set(schema, handlersForSchema);\n this.notificationHandlers.set(serverId, serverHandlers);\n\n const client = this.clientStates.get(serverId)?.client;\n if (client) {\n client.setNotificationHandler(\n schema,\n this.createNotificationDispatcher(serverId, schema),\n );\n }\n }\n\n onResourceListChanged(serverId: string, handler: NotificationHandler): void {\n this.addNotificationHandler(\n serverId,\n ResourceListChangedNotificationSchema,\n handler,\n );\n }\n\n onResourceUpdated(serverId: string, handler: NotificationHandler): void {\n this.addNotificationHandler(\n serverId,\n ResourceUpdatedNotificationSchema,\n handler,\n );\n }\n\n onPromptListChanged(serverId: string, handler: NotificationHandler): void {\n this.addNotificationHandler(\n serverId,\n PromptListChangedNotificationSchema,\n handler,\n );\n }\n\n getClient(serverId: string): Client | undefined {\n return this.clientStates.get(serverId)?.client;\n }\n\n setElicitationHandler(serverId: string, handler: ElicitationHandler): void {\n if (!this.clientStates.has(serverId)) {\n throw new Error(`Unknown MCP server \"${serverId}\".`);\n }\n\n this.elicitationHandlers.set(serverId, handler);\n\n const client = this.clientStates.get(serverId)?.client;\n if (client) {\n this.applyElicitationHandler(serverId, client);\n }\n }\n\n clearElicitationHandler(serverId: string): void {\n this.elicitationHandlers.delete(serverId);\n const client = this.clientStates.get(serverId)?.client;\n if (client) {\n client.removeRequestHandler(\"elicitation/create\");\n }\n }\n\n // Global elicitation callback API (no serverId required)\n setElicitationCallback(\n callback: (request: {\n requestId: string;\n message: string;\n schema: unknown;\n }) => Promise<ElicitResult> | ElicitResult,\n ): void {\n this.elicitationCallback = callback;\n // Apply to all connected clients that don't have a server-specific handler\n for (const [serverId, state] of this.clientStates.entries()) {\n const client = state.client;\n if (!client) continue;\n if (this.elicitationHandlers.has(serverId)) {\n // Respect server-specific handler\n this.applyElicitationHandler(serverId, client);\n } else {\n this.applyElicitationHandler(serverId, client);\n }\n }\n }\n\n clearElicitationCallback(): void {\n this.elicitationCallback = undefined;\n // Reconfigure clients: keep server-specific handlers, otherwise remove\n for (const [serverId, state] of this.clientStates.entries()) {\n const client = state.client;\n if (!client) continue;\n if (this.elicitationHandlers.has(serverId)) {\n this.applyElicitationHandler(serverId, client);\n } else {\n client.removeRequestHandler(\"elicitation/create\");\n }\n }\n }\n\n // Expose the pending elicitation map so callers can add resolvers\n getPendingElicitations(): Map<\n string,\n {\n resolve: (value: ElicitResult) => void;\n reject: (error: unknown) => void;\n }\n > {\n return this.pendingElicitations;\n }\n\n // Helper to resolve a pending elicitation from outside\n respondToElicitation(requestId: string, response: ElicitResult): boolean {\n const pending = this.pendingElicitations.get(requestId);\n if (!pending) return false;\n try {\n pending.resolve(response);\n return true;\n } finally {\n this.pendingElicitations.delete(requestId);\n }\n }\n\n private async connectViaStdio(\n client: Client,\n config: StdioServerConfig,\n timeout: number,\n ): Promise<Transport> {\n const transport = new StdioClientTransport({\n command: config.command,\n args: config.args,\n env: { ...getDefaultEnvironment(), ...(config.env ?? {}) },\n });\n await client.connect(transport, { timeout });\n return transport;\n }\n\n private async connectViaHttp(\n serverId: string,\n client: Client,\n config: HttpServerConfig,\n timeout: number,\n ): Promise<Transport> {\n const preferSSE = config.preferSSE ?? config.url.pathname.endsWith(\"/sse\");\n let streamableError: unknown;\n\n if (!preferSSE) {\n const streamableTransport = new StreamableHTTPClientTransport(\n config.url,\n {\n requestInit: config.requestInit,\n reconnectionOptions: config.reconnectionOptions,\n authProvider: config.authProvider,\n sessionId: config.sessionId,\n },\n );\n\n try {\n await client.connect(streamableTransport, {\n timeout: Math.min(timeout, 3000),\n });\n return streamableTransport;\n } catch (error) {\n streamableError = error;\n await this.safeCloseTransport(streamableTransport);\n }\n }\n\n const sseTransport = new SSEClientTransport(config.url, {\n requestInit: config.requestInit,\n eventSourceInit: config.eventSourceInit,\n authProvider: config.authProvider,\n });\n\n try {\n await client.connect(sseTransport, { timeout });\n return sseTransport;\n } catch (error) {\n await this.safeCloseTransport(sseTransport);\n const streamableMessage = streamableError\n ? ` Streamable HTTP error: ${this.formatError(streamableError)}.`\n : \"\";\n throw new Error(\n `Failed to connect to MCP server \"${serverId}\" using HTTP transports.${streamableMessage} SSE error: ${this.formatError(error)}.`,\n );\n }\n }\n\n private async safeCloseTransport(transport: Transport): Promise<void> {\n try {\n await transport.close();\n } catch {\n // Ignore close errors during cleanup.\n }\n }\n\n private applyNotificationHandlers(serverId: string, client: Client): void {\n const serverHandlers = this.notificationHandlers.get(serverId);\n if (!serverHandlers) {\n return;\n }\n\n for (const [schema] of serverHandlers) {\n client.setNotificationHandler(\n schema,\n this.createNotificationDispatcher(serverId, schema),\n );\n }\n }\n\n private createNotificationDispatcher(\n serverId: string,\n schema: NotificationSchema,\n ): NotificationHandler {\n return (notification) => {\n const serverHandlers = this.notificationHandlers.get(serverId);\n const handlersForSchema = serverHandlers?.get(schema);\n if (!handlersForSchema || handlersForSchema.size === 0) {\n return;\n }\n for (const handler of handlersForSchema) {\n try {\n handler(notification);\n } catch {\n // Swallow individual handler errors to avoid breaking other listeners.\n }\n }\n };\n }\n\n private applyElicitationHandler(serverId: string, client: Client): void {\n const serverSpecific = this.elicitationHandlers.get(serverId);\n if (serverSpecific) {\n client.setRequestHandler(ElicitRequestSchema, async (request) =>\n serverSpecific(request.params),\n );\n return;\n }\n\n if (this.elicitationCallback) {\n client.setRequestHandler(ElicitRequestSchema, async (request) => {\n const reqId = `elicit_${Date.now()}_${Math.random()\n .toString(36)\n .slice(2, 9)}`;\n return await this.elicitationCallback!({\n requestId: reqId,\n message: (request.params as any)?.message,\n schema:\n (request.params as any)?.requestedSchema ??\n (request.params as any)?.schema,\n });\n });\n return;\n }\n }\n\n private async ensureConnected(serverId: string): Promise<void> {\n const state = this.clientStates.get(serverId);\n if (state?.client) {\n return;\n }\n\n if (!state) {\n throw new Error(`Unknown MCP server \"${serverId}\".`);\n }\n if (state.promise) {\n await state.promise;\n return;\n }\n await this.connectToServer(serverId, state.config);\n }\n\n private resetState(serverId: string): void {\n this.clientStates.delete(serverId);\n this.toolsMetadataCache.delete(serverId);\n }\n\n private resolveConnectionStatus(\n state: ManagedClientState | undefined,\n ): MCPConnectionStatus {\n if (!state) {\n return \"disconnected\";\n }\n if (state.client) {\n return \"connected\";\n }\n if (state.promise) {\n return \"connecting\";\n }\n return \"disconnected\";\n }\n\n private withTimeout(\n serverId: string,\n options?: RequestOptions,\n ): RequestOptions {\n const state = this.clientStates.get(serverId);\n const timeout =\n state?.timeout ??\n (state ? this.getTimeout(state.config) : this.defaultTimeout);\n\n if (!options) {\n return { timeout };\n }\n\n if (options.timeout === undefined) {\n return { ...options, timeout };\n }\n\n return options;\n }\n\n private buildCapabilities(config: MCPServerConfig): ClientCapabilityOptions {\n const capabilities: ClientCapabilityOptions = {\n ...this.defaultCapabilities,\n ...(config.capabilities ?? {}),\n };\n\n if (!capabilities.elicitation) {\n capabilities.elicitation = {};\n }\n\n return capabilities;\n }\n\n private formatError(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n }\n\n private isMethodUnavailableError(error: unknown, method: string): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n const message = error.message.toLowerCase();\n const methodTokens = new Set<string>();\n const pushToken = (token: string) => {\n if (token) {\n methodTokens.add(token.toLowerCase());\n }\n };\n\n pushToken(method);\n for (const part of method.split(/[\\/:._-]/)) {\n pushToken(part);\n }\n const indicators = [\n \"method not found\",\n \"not implemented\",\n \"unsupported\",\n \"does not support\",\n \"unimplemented\",\n ];\n const indicatorMatch = indicators.some((indicator) =>\n message.includes(indicator),\n );\n if (!indicatorMatch) {\n return false;\n }\n\n if (Array.from(methodTokens).some((token) => message.includes(token))) {\n return true;\n }\n\n return true;\n }\n\n private getTimeout(config: MCPServerConfig): number {\n return config.timeout ?? this.defaultTimeout;\n }\n\n private isStdioConfig(config: MCPServerConfig): config is StdioServerConfig {\n return \"command\" in config;\n }\n\n private getClientById(serverId: string): Client {\n const state = this.clientStates.get(serverId);\n if (!state?.client) {\n throw new Error(`MCP server \"${serverId}\" is not connected.`);\n }\n return state.client;\n }\n}\n\nexport type MCPPromptListResult = Awaited<\n ReturnType<MCPClientManager[\"listPrompts\"]>\n>;\nexport type MCPPrompt = MCPPromptListResult[\"prompts\"][number];\nexport type MCPGetPromptResult = Awaited<\n ReturnType<MCPClientManager[\"getPrompt\"]>\n>;\nexport type MCPResourceListResult = Awaited<\n ReturnType<MCPClientManager[\"listResources\"]>\n>;\nexport type MCPResource = MCPResourceListResult[\"resources\"][number];\nexport type MCPReadResourceResult = Awaited<\n ReturnType<MCPClientManager[\"readResource\"]>\n>;\nexport type MCPServerSummary = ServerSummary;\nexport type MCPConvertedToolSet<\n SCHEMAS extends ToolSchemaOverrides | \"automatic\",\n> = ConvertedToolSet<SCHEMAS>;\nexport type MCPToolSchemaOverrides = ToolSchemaOverrides;\n","import type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport {\n CallToolResult,\n CallToolResultSchema,\n ListToolsResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n dynamicTool,\n jsonSchema,\n tool as defineTool,\n type Tool,\n type ToolCallOptions,\n ToolSet,\n} from \"ai\";\nimport type { FlexibleSchema } from \"@ai-sdk/provider-utils\";\n\nconst ensureJsonSchemaObject = (schema: unknown): JSONSchema7 => {\n if (schema && typeof schema === \"object\") {\n const record = schema as Record<string, unknown>;\n const base: JSONSchema7 = record.jsonSchema\n ? ensureJsonSchemaObject(record.jsonSchema)\n : (record as JSONSchema7);\n\n // Many MCP tools omit the top-level type; Anthropic requires an object schema.\n if (!(\"type\" in base) || base.type === undefined) {\n base.type = \"object\";\n }\n if (base.type === \"object\") {\n base.properties = (base.properties ?? {}) as Record<\n string,\n JSONSchema7Definition\n >;\n if (base.additionalProperties === undefined) {\n base.additionalProperties = false;\n }\n }\n\n return base;\n }\n\n return {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n } satisfies JSONSchema7;\n};\n\ntype CallToolExecutor = (params: {\n name: string;\n args: unknown;\n options: ToolCallOptions;\n}) => Promise<CallToolResult>;\n\nexport type ToolSchemaOverrides = Record<\n string,\n { inputSchema: FlexibleSchema<unknown> }\n>;\n\nexport type ConvertedToolSet<\n SCHEMAS extends ToolSchemaOverrides | \"automatic\",\n> = SCHEMAS extends ToolSchemaOverrides\n ? { [K in keyof SCHEMAS]: Tool }\n : Record<string, Tool>;\n\ntype ConvertOptions<TOOL_SCHEMAS extends ToolSchemaOverrides | \"automatic\"> = {\n schemas?: TOOL_SCHEMAS;\n callTool: CallToolExecutor;\n};\n\nexport async function convertMCPToolsToVercelTools(\n listToolsResult: ListToolsResult,\n {\n schemas = \"automatic\",\n callTool,\n }: ConvertOptions<ToolSchemaOverrides | \"automatic\">,\n): Promise<ToolSet> {\n const tools: ToolSet = {};\n\n for (const toolDescription of listToolsResult.tools) {\n const { name, description, inputSchema } = toolDescription;\n\n const execute = async (args: unknown, options: ToolCallOptions) => {\n options?.abortSignal?.throwIfAborted?.();\n const result = await callTool({ name, args, options });\n return CallToolResultSchema.parse(result);\n };\n\n let vercelTool: Tool;\n if (schemas === \"automatic\") {\n const normalizedInputSchema = ensureJsonSchemaObject(inputSchema);\n vercelTool = dynamicTool({\n description,\n inputSchema: jsonSchema({\n type: \"object\",\n properties: normalizedInputSchema.properties ?? {},\n additionalProperties:\n (normalizedInputSchema as any).additionalProperties ?? false,\n }),\n execute,\n });\n } else {\n const overrides = schemas;\n if (!(name in overrides)) {\n // If overrides are provided, only include tools explicitly listed\n continue;\n }\n vercelTool = defineTool({\n description,\n inputSchema: overrides[name].inputSchema,\n execute,\n });\n }\n\n tools[name] = vercelTool;\n }\n\n return tools;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAuB;AAEvB,iBAAmC;AAEnC,mBAGO;AACP,4BAA8C;AAE9C,sBAA6C;AAG7C,IAAAA,gBAMO;;;AClBP,mBAIO;AACP,gBAOO;AAGP,IAAM,yBAAyB,CAAC,WAAiC;AAhBjE;AAiBE,MAAI,UAAU,OAAO,WAAW,UAAU;AACxC,UAAM,SAAS;AACf,UAAM,OAAoB,OAAO,aAC7B,uBAAuB,OAAO,UAAU,IACvC;AAGL,QAAI,EAAE,UAAU,SAAS,KAAK,SAAS,QAAW;AAChD,WAAK,OAAO;AAAA,IACd;AACA,QAAI,KAAK,SAAS,UAAU;AAC1B,WAAK,cAAc,UAAK,eAAL,YAAmB,CAAC;AAIvC,UAAI,KAAK,yBAAyB,QAAW;AAC3C,aAAK,uBAAuB;AAAA,MAC9B;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,YAAY,CAAC;AAAA,IACb,sBAAsB;AAAA,EACxB;AACF;AAwBA,eAAsB,6BACpB,iBACA;AAAA,EACE,UAAU;AAAA,EACV;AACF,GACkB;AA3EpB;AA4EE,QAAM,QAAiB,CAAC;AAExB,aAAW,mBAAmB,gBAAgB,OAAO;AACnD,UAAM,EAAE,MAAM,aAAa,YAAY,IAAI;AAE3C,UAAM,UAAU,OAAO,MAAe,YAA6B;AAjFvE,UAAAC,KAAAC;AAkFM,OAAAA,OAAAD,MAAA,mCAAS,gBAAT,gBAAAA,IAAsB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AAS,KAAK,CAAC,GAAG;AACrE,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AAAA,EAEQ,WAAW,QAAiC;AAz6BtD;AA06BI,YAAO,YAAO,YAAP,YAAkB,KAAK;AAAA,EAChC;AAAA,EAEQ,cAAc,QAAsD;AAC1E,WAAO,aAAa;AAAA,EACtB;AAAA,EAEQ,cAAc,UAA0B;AAC9C,UAAM,QAAQ,KAAK,aAAa,IAAI,QAAQ;AAC5C,QAAI,EAAC,+BAAO,SAAQ;AAClB,YAAM,IAAI,MAAM,eAAe,QAAQ,qBAAqB;AAAA,IAC9D;AACA,WAAO,MAAM;AAAA,EACf;AACF;","names":["import_types","_a","_b","defineTool","_a"]}
|
|
1
|
+
{"version":3,"sources":["../../src/mcp-client-manager/index.ts","../../src/mcp-client-manager/tool-converters.ts"],"sourcesContent":["import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { ClientOptions } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport {\n getDefaultEnvironment,\n StdioClientTransport,\n} from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport type { StreamableHTTPClientTransportOptions } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { DEFAULT_REQUEST_TIMEOUT_MSEC } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport type { TransportSendOptions } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport {\n CallToolResultSchema,\n ElicitRequestSchema,\n ResourceListChangedNotificationSchema,\n ResourceUpdatedNotificationSchema,\n PromptListChangedNotificationSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type {\n ElicitRequest,\n ElicitResult,\n JSONRPCMessage,\n MessageExtraInfo,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n convertMCPToolsToVercelTools,\n type ConvertedToolSet,\n type ToolSchemaOverrides,\n} from \"./tool-converters.js\";\nimport type { ToolCallOptions, ToolSet } from \"ai\";\ntype ClientCapabilityOptions = NonNullable<ClientOptions[\"capabilities\"]>;\n\ntype BaseServerConfig = {\n capabilities?: ClientCapabilityOptions;\n timeout?: number;\n version?: string;\n onError?: (error: unknown) => void;\n // Enable simple console logging of JSON-RPC traffic for this server\n logJsonRpc?: boolean;\n // Custom logger for JSON-RPC traffic; overrides logJsonRpc when provided\n rpcLogger?: (event: {\n direction: \"send\" | \"receive\";\n message: unknown;\n serverId: string;\n }) => void;\n};\n\ntype StdioServerConfig = BaseServerConfig & {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n\n url?: never;\n requestInit?: never;\n eventSourceInit?: never;\n authProvider?: never;\n reconnectionOptions?: never;\n sessionId?: never;\n preferSSE?: never;\n};\n\ntype HttpServerConfig = BaseServerConfig & {\n url: URL;\n requestInit?: StreamableHTTPClientTransportOptions[\"requestInit\"];\n eventSourceInit?: SSEClientTransportOptions[\"eventSourceInit\"];\n authProvider?: StreamableHTTPClientTransportOptions[\"authProvider\"];\n reconnectionOptions?: StreamableHTTPClientTransportOptions[\"reconnectionOptions\"];\n sessionId?: StreamableHTTPClientTransportOptions[\"sessionId\"];\n preferSSE?: boolean;\n\n command?: never;\n args?: never;\n env?: never;\n};\n\nexport type MCPServerConfig = StdioServerConfig | HttpServerConfig;\nexport type MCPClientManagerConfig = Record<string, MCPServerConfig>;\n\ntype NotificationSchema = Parameters<Client[\"setNotificationHandler\"]>[0];\ntype NotificationHandler = Parameters<Client[\"setNotificationHandler\"]>[1];\n\ninterface ManagedClientState {\n config: MCPServerConfig;\n timeout: number;\n client?: Client;\n transport?: Transport;\n promise?: Promise<Client>;\n}\n\n// Pending state is tracked inside ManagedClientState.promise\n\ntype ClientRequestOptions = RequestOptions;\ntype CallToolOptions = RequestOptions;\n\ntype ListResourcesParams = Parameters<Client[\"listResources\"]>[0];\ntype ListResourceTemplatesParams = Parameters<\n Client[\"listResourceTemplates\"]\n>[0];\ntype ReadResourceParams = Parameters<Client[\"readResource\"]>[0];\ntype SubscribeResourceParams = Parameters<Client[\"subscribeResource\"]>[0];\ntype UnsubscribeResourceParams = Parameters<Client[\"unsubscribeResource\"]>[0];\ntype ListPromptsParams = Parameters<Client[\"listPrompts\"]>[0];\ntype GetPromptParams = Parameters<Client[\"getPrompt\"]>[0];\ntype ListToolsResult = Awaited<ReturnType<Client[\"listTools\"]>>;\n\nexport type MCPConnectionStatus = \"connected\" | \"connecting\" | \"disconnected\";\ntype ServerSummary = {\n id: string;\n status: MCPConnectionStatus;\n config?: MCPServerConfig;\n};\n\nexport type ExecuteToolArguments = Record<string, unknown>;\nexport type ElicitationHandler = (\n params: ElicitRequest[\"params\"],\n) => Promise<ElicitResult> | ElicitResult;\n\nexport class MCPClientManager {\n private readonly clientStates = new Map<string, ManagedClientState>();\n private readonly notificationHandlers = new Map<\n string,\n Map<NotificationSchema, Set<NotificationHandler>>\n >();\n private readonly elicitationHandlers = new Map<string, ElicitationHandler>();\n private readonly toolsMetadataCache = new Map<string, Map<string, any>>();\n private readonly defaultClientVersion: string;\n private readonly defaultClientName: string | undefined;\n private readonly defaultCapabilities: ClientCapabilityOptions;\n private readonly defaultTimeout: number;\n private defaultLogJsonRpc: boolean = false;\n\n private defaultRpcLogger?: (event: {\n direction: \"send\" | \"receive\";\n message: unknown;\n serverId: string;\n }) => void;\n private elicitationCallback?: (request: {\n requestId: string;\n message: string;\n schema: unknown;\n }) => Promise<ElicitResult> | ElicitResult;\n private readonly pendingElicitations = new Map<\n string,\n {\n resolve: (value: ElicitResult) => void;\n reject: (error: unknown) => void;\n }\n >();\n\n constructor(\n servers: MCPClientManagerConfig = {},\n options: {\n defaultClientName?: string;\n defaultClientVersion?: string;\n defaultCapabilities?: ClientCapabilityOptions;\n defaultTimeout?: number;\n defaultLogJsonRpc?: boolean;\n rpcLogger?: (event: {\n direction: \"send\" | \"receive\";\n message: unknown;\n serverId: string;\n }) => void;\n } = {},\n ) {\n this.defaultClientVersion = options.defaultClientVersion ?? \"1.0.0\";\n this.defaultClientName = options.defaultClientName ?? undefined;\n this.defaultCapabilities = { ...(options.defaultCapabilities ?? {}) };\n this.defaultTimeout =\n options.defaultTimeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n this.defaultLogJsonRpc = options.defaultLogJsonRpc ?? false;\n this.defaultRpcLogger = options.rpcLogger;\n\n for (const [id, config] of Object.entries(servers)) {\n void this.connectToServer(id, config);\n }\n }\n\n listServers(): string[] {\n return Array.from(this.clientStates.keys());\n }\n\n hasServer(serverId: string): boolean {\n return this.clientStates.has(serverId);\n }\n\n getServerSummaries(): ServerSummary[] {\n return Array.from(this.clientStates.entries()).map(([serverId, state]) => ({\n id: serverId,\n status: this.resolveConnectionStatus(state),\n config: state.config,\n }));\n }\n\n getConnectionStatus(serverId: string): MCPConnectionStatus {\n return this.resolveConnectionStatus(this.clientStates.get(serverId));\n }\n\n getServerConfig(serverId: string): MCPServerConfig | undefined {\n return this.clientStates.get(serverId)?.config;\n }\n\n async connectToServer(\n serverId: string,\n config: MCPServerConfig,\n ): Promise<Client> {\n if (this.clientStates.has(serverId)) {\n throw new Error(`MCP server \"${serverId}\" is already connected.`);\n }\n const timeout = this.getTimeout(config);\n const state = this.clientStates.get(serverId) ?? {\n config,\n timeout,\n };\n // Update config/timeout on every call\n state.config = config;\n state.timeout = timeout;\n // If already connected, return the client\n if (state.client) {\n this.clientStates.set(serverId, state);\n return state.client;\n }\n // If connection is in-flight, reuse the promise\n if (state.promise) {\n this.clientStates.set(serverId, state);\n return state.promise;\n }\n\n const connectionPromise = (async () => {\n const client = new Client(\n {\n name: this.defaultClientName ? `${this.defaultClientName}` : serverId,\n version: config.version ?? this.defaultClientVersion,\n },\n {\n capabilities: this.buildCapabilities(config),\n },\n );\n\n this.applyNotificationHandlers(serverId, client);\n this.applyElicitationHandler(serverId, client);\n\n if (config.onError) {\n client.onerror = (error) => {\n config.onError?.(error);\n };\n }\n\n client.onclose = () => {\n this.resetState(serverId);\n };\n\n let transport: Transport;\n if (this.isStdioConfig(config)) {\n transport = await this.connectViaStdio(\n serverId,\n client,\n config,\n timeout,\n );\n } else {\n transport = await this.connectViaHttp(\n serverId,\n client,\n config,\n timeout,\n );\n }\n\n state.client = client;\n state.transport = transport;\n // clear pending\n state.promise = undefined;\n this.clientStates.set(serverId, state);\n\n return client;\n })().catch((error) => {\n // Clear pending but keep config so the server remains registered\n state.promise = undefined;\n state.client = undefined;\n state.transport = undefined;\n this.clientStates.set(serverId, state);\n throw error;\n });\n\n state.promise = connectionPromise;\n this.clientStates.set(serverId, state);\n return connectionPromise;\n }\n\n async disconnectServer(serverId: string): Promise<void> {\n const client = this.getClientById(serverId);\n try {\n await client.close();\n } finally {\n if (client.transport) {\n await this.safeCloseTransport(client.transport);\n }\n this.resetState(serverId);\n }\n }\n\n removeServer(serverId: string): void {\n this.resetState(serverId);\n this.notificationHandlers.delete(serverId);\n this.elicitationHandlers.delete(serverId);\n }\n\n async disconnectAllServers(): Promise<void> {\n const serverIds = this.listServers();\n await Promise.all(\n serverIds.map((serverId) => this.disconnectServer(serverId)),\n );\n\n for (const serverId of serverIds) {\n this.resetState(serverId);\n this.notificationHandlers.delete(serverId);\n this.elicitationHandlers.delete(serverId);\n }\n }\n\n async listTools(\n serverId: string,\n params?: Parameters<Client[\"listTools\"]>[0],\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n try {\n const result = await client.listTools(\n params,\n this.withTimeout(serverId, options),\n );\n\n const metadataMap = new Map<string, any>();\n for (const tool of result.tools) {\n if (tool._meta) {\n metadataMap.set(tool.name, tool._meta);\n }\n }\n this.toolsMetadataCache.set(serverId, metadataMap);\n\n return result;\n } catch (error) {\n if (this.isMethodUnavailableError(error, \"tools/list\")) {\n this.toolsMetadataCache.set(serverId, new Map());\n return { tools: [] } as Awaited<ReturnType<Client[\"listTools\"]>>;\n }\n throw error;\n }\n }\n\n async getTools(serverIds?: string[]): Promise<ListToolsResult> {\n const targetServerIds =\n serverIds && serverIds.length > 0 ? serverIds : this.listServers();\n\n const toolLists = await Promise.all(\n targetServerIds.map(async (serverId) => {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n const result = await client.listTools(\n undefined,\n this.withTimeout(serverId),\n );\n\n const metadataMap = new Map<string, any>();\n for (const tool of result.tools) {\n if (tool._meta) {\n metadataMap.set(tool.name, tool._meta);\n }\n }\n this.toolsMetadataCache.set(serverId, metadataMap);\n\n return result.tools;\n }),\n );\n return { tools: toolLists.flat() } as ListToolsResult;\n }\n\n getAllToolsMetadata(serverId: string): Record<string, Record<string, any>> {\n const metadataMap = this.toolsMetadataCache.get(serverId);\n return metadataMap ? Object.fromEntries(metadataMap) : {};\n }\n\n pingServer(serverId: string, options?: RequestOptions) {\n const client = this.getClientById(serverId);\n try {\n client.ping(options);\n } catch (error) {\n throw new Error(\n `Failed to ping MCP server \"${serverId}\": ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n async getToolsForAiSdk(\n serverIds?: string[] | string,\n options: { schemas?: ToolSchemaOverrides | \"automatic\" } = {},\n ): Promise<ToolSet> {\n const ids = Array.isArray(serverIds)\n ? serverIds\n : serverIds\n ? [serverIds]\n : this.listServers();\n\n const loadForServer = async (id: string): Promise<ToolSet> => {\n await this.ensureConnected(id);\n const listToolsResult = await this.listTools(id);\n return convertMCPToolsToVercelTools(listToolsResult, {\n schemas: options.schemas,\n callTool: async ({ name, args, options: callOptions }) => {\n const requestOptions = callOptions?.abortSignal\n ? { signal: callOptions.abortSignal }\n : undefined;\n const result = await this.executeTool(\n id,\n name,\n (args ?? {}) as ExecuteToolArguments,\n requestOptions,\n );\n return CallToolResultSchema.parse(result);\n },\n });\n };\n\n const perServerTools = await Promise.all(\n ids.map(async (id) => {\n try {\n const tools = await loadForServer(id);\n // Attach server id metadata to each tool object for downstream extraction\n for (const [name, tool] of Object.entries(tools)) {\n (tool as any)._serverId = id;\n }\n return tools;\n } catch (error) {\n if (this.isMethodUnavailableError(error, \"tools/list\")) {\n return {} as ToolSet;\n }\n throw error;\n }\n }),\n );\n\n // Flatten into a single ToolSet (last-in wins for name collisions)\n const flattened: ToolSet = {};\n for (const toolset of perServerTools) {\n for (const [name, tool] of Object.entries(toolset)) {\n flattened[name] = tool;\n }\n }\n\n return flattened;\n }\n\n async executeTool(\n serverId: string,\n toolName: string,\n args: ExecuteToolArguments = {},\n options?: CallToolOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n return client.callTool(\n {\n name: toolName,\n arguments: args,\n },\n CallToolResultSchema,\n this.withTimeout(serverId, options),\n );\n }\n\n async listResources(\n serverId: string,\n params?: ListResourcesParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n try {\n return await client.listResources(\n params,\n this.withTimeout(serverId, options),\n );\n } catch (error) {\n if (this.isMethodUnavailableError(error, \"resources/list\")) {\n return {\n resources: [],\n } as Awaited<ReturnType<Client[\"listResources\"]>>;\n }\n throw error;\n }\n }\n\n async readResource(\n serverId: string,\n params: ReadResourceParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n return client.readResource(params, this.withTimeout(serverId, options));\n }\n\n async subscribeResource(\n serverId: string,\n params: SubscribeResourceParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n return client.subscribeResource(\n params,\n this.withTimeout(serverId, options),\n );\n }\n\n async unsubscribeResource(\n serverId: string,\n params: UnsubscribeResourceParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n return client.unsubscribeResource(\n params,\n this.withTimeout(serverId, options),\n );\n }\n\n async listResourceTemplates(\n serverId: string,\n params?: ListResourceTemplatesParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n return client.listResourceTemplates(\n params,\n this.withTimeout(serverId, options),\n );\n }\n\n async listPrompts(\n serverId: string,\n params?: ListPromptsParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n try {\n return await client.listPrompts(\n params,\n this.withTimeout(serverId, options),\n );\n } catch (error) {\n if (this.isMethodUnavailableError(error, \"prompts/list\")) {\n return {\n prompts: [],\n } as Awaited<ReturnType<Client[\"listPrompts\"]>>;\n }\n throw error;\n }\n }\n\n async getPrompt(\n serverId: string,\n params: GetPromptParams,\n options?: ClientRequestOptions,\n ) {\n await this.ensureConnected(serverId);\n const client = this.getClientById(serverId);\n return client.getPrompt(params, this.withTimeout(serverId, options));\n }\n\n getSessionIdByServer(serverId: string): string | undefined {\n const state = this.clientStates.get(serverId);\n if (!state?.transport) {\n throw new Error(`Unknown MCP server \"${serverId}\".`);\n }\n if (state.transport instanceof StreamableHTTPClientTransport) {\n return state.transport.sessionId;\n }\n throw new Error(\n `Server \"${serverId}\" must be Streamable HTTP to get the session ID.`,\n );\n }\n\n addNotificationHandler(\n serverId: string,\n schema: NotificationSchema,\n handler: NotificationHandler,\n ): void {\n const serverHandlers = this.notificationHandlers.get(serverId) ?? new Map();\n const handlersForSchema =\n serverHandlers.get(schema) ?? new Set<NotificationHandler>();\n handlersForSchema.add(handler);\n serverHandlers.set(schema, handlersForSchema);\n this.notificationHandlers.set(serverId, serverHandlers);\n\n const client = this.clientStates.get(serverId)?.client;\n if (client) {\n client.setNotificationHandler(\n schema,\n this.createNotificationDispatcher(serverId, schema),\n );\n }\n }\n\n onResourceListChanged(serverId: string, handler: NotificationHandler): void {\n this.addNotificationHandler(\n serverId,\n ResourceListChangedNotificationSchema,\n handler,\n );\n }\n\n onResourceUpdated(serverId: string, handler: NotificationHandler): void {\n this.addNotificationHandler(\n serverId,\n ResourceUpdatedNotificationSchema,\n handler,\n );\n }\n\n onPromptListChanged(serverId: string, handler: NotificationHandler): void {\n this.addNotificationHandler(\n serverId,\n PromptListChangedNotificationSchema,\n handler,\n );\n }\n\n getClient(serverId: string): Client | undefined {\n return this.clientStates.get(serverId)?.client;\n }\n\n setElicitationHandler(serverId: string, handler: ElicitationHandler): void {\n if (!this.clientStates.has(serverId)) {\n throw new Error(`Unknown MCP server \"${serverId}\".`);\n }\n\n this.elicitationHandlers.set(serverId, handler);\n\n const client = this.clientStates.get(serverId)?.client;\n if (client) {\n this.applyElicitationHandler(serverId, client);\n }\n }\n\n clearElicitationHandler(serverId: string): void {\n this.elicitationHandlers.delete(serverId);\n const client = this.clientStates.get(serverId)?.client;\n if (client) {\n client.removeRequestHandler(\"elicitation/create\");\n }\n }\n\n // Global elicitation callback API (no serverId required)\n setElicitationCallback(\n callback: (request: {\n requestId: string;\n message: string;\n schema: unknown;\n }) => Promise<ElicitResult> | ElicitResult,\n ): void {\n this.elicitationCallback = callback;\n // Apply to all connected clients that don't have a server-specific handler\n for (const [serverId, state] of this.clientStates.entries()) {\n const client = state.client;\n if (!client) continue;\n if (this.elicitationHandlers.has(serverId)) {\n // Respect server-specific handler\n this.applyElicitationHandler(serverId, client);\n } else {\n this.applyElicitationHandler(serverId, client);\n }\n }\n }\n\n clearElicitationCallback(): void {\n this.elicitationCallback = undefined;\n // Reconfigure clients: keep server-specific handlers, otherwise remove\n for (const [serverId, state] of this.clientStates.entries()) {\n const client = state.client;\n if (!client) continue;\n if (this.elicitationHandlers.has(serverId)) {\n this.applyElicitationHandler(serverId, client);\n } else {\n client.removeRequestHandler(\"elicitation/create\");\n }\n }\n }\n\n // Expose the pending elicitation map so callers can add resolvers\n getPendingElicitations(): Map<\n string,\n {\n resolve: (value: ElicitResult) => void;\n reject: (error: unknown) => void;\n }\n > {\n return this.pendingElicitations;\n }\n\n // Helper to resolve a pending elicitation from outside\n respondToElicitation(requestId: string, response: ElicitResult): boolean {\n const pending = this.pendingElicitations.get(requestId);\n if (!pending) return false;\n try {\n pending.resolve(response);\n return true;\n } finally {\n this.pendingElicitations.delete(requestId);\n }\n }\n\n private async connectViaStdio(\n serverId: string,\n client: Client,\n config: StdioServerConfig,\n timeout: number,\n ): Promise<Transport> {\n const underlying = new StdioClientTransport({\n command: config.command,\n args: config.args,\n env: { ...getDefaultEnvironment(), ...(config.env ?? {}) },\n });\n const wrapped = this.wrapTransportForLogging(serverId, config, underlying);\n await client.connect(wrapped, { timeout });\n return underlying;\n }\n\n private async connectViaHttp(\n serverId: string,\n client: Client,\n config: HttpServerConfig,\n timeout: number,\n ): Promise<Transport> {\n const preferSSE = config.preferSSE ?? config.url.pathname.endsWith(\"/sse\");\n let streamableError: unknown;\n\n if (!preferSSE) {\n const streamableTransport = new StreamableHTTPClientTransport(\n config.url,\n {\n requestInit: config.requestInit,\n reconnectionOptions: config.reconnectionOptions,\n authProvider: config.authProvider,\n sessionId: config.sessionId,\n },\n );\n\n try {\n const wrapped = this.wrapTransportForLogging(\n serverId,\n config,\n streamableTransport,\n );\n await client.connect(wrapped, {\n timeout: Math.min(timeout, 3000),\n });\n return streamableTransport;\n } catch (error) {\n streamableError = error;\n await this.safeCloseTransport(streamableTransport);\n }\n }\n\n const sseTransport = new SSEClientTransport(config.url, {\n requestInit: config.requestInit,\n eventSourceInit: config.eventSourceInit,\n authProvider: config.authProvider,\n });\n\n try {\n const wrapped = this.wrapTransportForLogging(\n serverId,\n config,\n sseTransport,\n );\n await client.connect(wrapped, { timeout });\n return sseTransport;\n } catch (error) {\n await this.safeCloseTransport(sseTransport);\n const streamableMessage = streamableError\n ? ` Streamable HTTP error: ${this.formatError(streamableError)}.`\n : \"\";\n throw new Error(\n `Failed to connect to MCP server \"${serverId}\" using HTTP transports.${streamableMessage} SSE error: ${this.formatError(error)}.`,\n );\n }\n }\n\n private async safeCloseTransport(transport: Transport): Promise<void> {\n try {\n await transport.close();\n } catch {\n // Ignore close errors during cleanup.\n }\n }\n\n private applyNotificationHandlers(serverId: string, client: Client): void {\n const serverHandlers = this.notificationHandlers.get(serverId);\n if (!serverHandlers) {\n return;\n }\n\n for (const [schema] of serverHandlers) {\n client.setNotificationHandler(\n schema,\n this.createNotificationDispatcher(serverId, schema),\n );\n }\n }\n\n private createNotificationDispatcher(\n serverId: string,\n schema: NotificationSchema,\n ): NotificationHandler {\n return (notification) => {\n const serverHandlers = this.notificationHandlers.get(serverId);\n const handlersForSchema = serverHandlers?.get(schema);\n if (!handlersForSchema || handlersForSchema.size === 0) {\n return;\n }\n for (const handler of handlersForSchema) {\n try {\n handler(notification);\n } catch {\n // Swallow individual handler errors to avoid breaking other listeners.\n }\n }\n };\n }\n\n private applyElicitationHandler(serverId: string, client: Client): void {\n const serverSpecific = this.elicitationHandlers.get(serverId);\n if (serverSpecific) {\n client.setRequestHandler(ElicitRequestSchema, async (request) =>\n serverSpecific(request.params),\n );\n return;\n }\n\n if (this.elicitationCallback) {\n client.setRequestHandler(ElicitRequestSchema, async (request) => {\n const reqId = `elicit_${Date.now()}_${Math.random()\n .toString(36)\n .slice(2, 9)}`;\n return await this.elicitationCallback!({\n requestId: reqId,\n message: (request.params as any)?.message,\n schema:\n (request.params as any)?.requestedSchema ??\n (request.params as any)?.schema,\n });\n });\n return;\n }\n }\n\n private async ensureConnected(serverId: string): Promise<void> {\n const state = this.clientStates.get(serverId);\n if (state?.client) {\n return;\n }\n\n if (!state) {\n throw new Error(`Unknown MCP server \"${serverId}\".`);\n }\n if (state.promise) {\n await state.promise;\n return;\n }\n await this.connectToServer(serverId, state.config);\n }\n\n private resetState(serverId: string): void {\n this.clientStates.delete(serverId);\n this.toolsMetadataCache.delete(serverId);\n }\n\n private resolveConnectionStatus(\n state: ManagedClientState | undefined,\n ): MCPConnectionStatus {\n if (!state) {\n return \"disconnected\";\n }\n if (state.client) {\n return \"connected\";\n }\n if (state.promise) {\n return \"connecting\";\n }\n return \"disconnected\";\n }\n\n private withTimeout(\n serverId: string,\n options?: RequestOptions,\n ): RequestOptions {\n const state = this.clientStates.get(serverId);\n const timeout =\n state?.timeout ??\n (state ? this.getTimeout(state.config) : this.defaultTimeout);\n\n if (!options) {\n return { timeout };\n }\n\n if (options.timeout === undefined) {\n return { ...options, timeout };\n }\n\n return options;\n }\n\n private buildCapabilities(config: MCPServerConfig): ClientCapabilityOptions {\n const capabilities: ClientCapabilityOptions = {\n ...this.defaultCapabilities,\n ...(config.capabilities ?? {}),\n };\n\n if (!capabilities.elicitation) {\n capabilities.elicitation = {};\n }\n\n return capabilities;\n }\n\n private formatError(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n }\n\n // Returns a transport that logs JSON-RPC traffic if enabled for this server\n private wrapTransportForLogging(\n serverId: string,\n config: MCPServerConfig,\n transport: Transport,\n ): Transport {\n const logger = this.resolveRpcLogger(serverId, config);\n if (!logger) return transport;\n const log: (event: {\n direction: \"send\" | \"receive\";\n message: unknown;\n serverId: string;\n }) => void = logger;\n\n // Wrapper that proxies to the underlying transport while emitting logs\n const self = this;\n class LoggingTransport implements Transport {\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void;\n constructor(private readonly inner: Transport) {\n this.inner.onmessage = (\n message: JSONRPCMessage,\n extra?: MessageExtraInfo,\n ) => {\n try {\n log({ direction: \"receive\", message, serverId });\n } catch {\n // ignore logger errors\n }\n this.onmessage?.(message, extra);\n };\n this.inner.onclose = () => {\n this.onclose?.();\n };\n this.inner.onerror = (error: Error) => {\n this.onerror?.(error);\n };\n }\n async start(): Promise<void> {\n if (typeof (this.inner as any).start === \"function\") {\n await (this.inner as any).start();\n }\n }\n async send(\n message: JSONRPCMessage,\n options?: TransportSendOptions,\n ): Promise<void> {\n try {\n log({ direction: \"send\", message, serverId });\n } catch {\n // ignore logger errors\n }\n await this.inner.send(message as any, options as any);\n }\n async close(): Promise<void> {\n await this.inner.close();\n }\n get sessionId(): string | undefined {\n return (this.inner as any).sessionId;\n }\n setProtocolVersion?(version: string): void {\n if (typeof this.inner.setProtocolVersion === \"function\") {\n this.inner.setProtocolVersion(version);\n }\n }\n }\n\n return new LoggingTransport(transport);\n }\n\n private resolveRpcLogger(\n serverId: string,\n config: MCPServerConfig,\n ):\n | ((event: {\n direction: \"send\" | \"receive\";\n message: unknown;\n serverId: string;\n }) => void)\n | undefined {\n if (config.rpcLogger) return config.rpcLogger;\n if (config.logJsonRpc || this.defaultLogJsonRpc) {\n return ({ direction, message, serverId: id }) => {\n let printable: string;\n try {\n printable =\n typeof message === \"string\" ? message : JSON.stringify(message);\n } catch {\n printable = String(message);\n }\n // eslint-disable-next-line no-console\n console.debug(`[MCP:${id}] ${direction.toUpperCase()} ${printable}`);\n };\n }\n if (this.defaultRpcLogger) return this.defaultRpcLogger;\n return undefined;\n }\n\n private isMethodUnavailableError(error: unknown, method: string): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n const message = error.message.toLowerCase();\n const methodTokens = new Set<string>();\n const pushToken = (token: string) => {\n if (token) {\n methodTokens.add(token.toLowerCase());\n }\n };\n\n pushToken(method);\n for (const part of method.split(/[\\/:._-]/)) {\n pushToken(part);\n }\n const indicators = [\n \"method not found\",\n \"not implemented\",\n \"unsupported\",\n \"does not support\",\n \"unimplemented\",\n ];\n const indicatorMatch = indicators.some((indicator) =>\n message.includes(indicator),\n );\n if (!indicatorMatch) {\n return false;\n }\n\n if (Array.from(methodTokens).some((token) => message.includes(token))) {\n return true;\n }\n\n return true;\n }\n\n private getTimeout(config: MCPServerConfig): number {\n return config.timeout ?? this.defaultTimeout;\n }\n\n private isStdioConfig(config: MCPServerConfig): config is StdioServerConfig {\n return \"command\" in config;\n }\n\n private getClientById(serverId: string): Client {\n const state = this.clientStates.get(serverId);\n if (!state?.client) {\n throw new Error(`MCP server \"${serverId}\" is not connected.`);\n }\n return state.client;\n }\n}\n\nexport type MCPPromptListResult = Awaited<\n ReturnType<MCPClientManager[\"listPrompts\"]>\n>;\nexport type MCPPrompt = MCPPromptListResult[\"prompts\"][number];\nexport type MCPGetPromptResult = Awaited<\n ReturnType<MCPClientManager[\"getPrompt\"]>\n>;\nexport type MCPResourceListResult = Awaited<\n ReturnType<MCPClientManager[\"listResources\"]>\n>;\nexport type MCPResource = MCPResourceListResult[\"resources\"][number];\nexport type MCPReadResourceResult = Awaited<\n ReturnType<MCPClientManager[\"readResource\"]>\n>;\nexport type MCPServerSummary = ServerSummary;\nexport type MCPConvertedToolSet<\n SCHEMAS extends ToolSchemaOverrides | \"automatic\",\n> = ConvertedToolSet<SCHEMAS>;\nexport type MCPToolSchemaOverrides = ToolSchemaOverrides;\n","import type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport {\n CallToolResult,\n CallToolResultSchema,\n ListToolsResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n dynamicTool,\n jsonSchema,\n tool as defineTool,\n type Tool,\n type ToolCallOptions,\n ToolSet,\n} from \"ai\";\nimport type { FlexibleSchema } from \"@ai-sdk/provider-utils\";\n\nconst ensureJsonSchemaObject = (schema: unknown): JSONSchema7 => {\n if (schema && typeof schema === \"object\") {\n const record = schema as Record<string, unknown>;\n const base: JSONSchema7 = record.jsonSchema\n ? ensureJsonSchemaObject(record.jsonSchema)\n : (record as JSONSchema7);\n\n // Many MCP tools omit the top-level type; Anthropic requires an object schema.\n if (!(\"type\" in base) || base.type === undefined) {\n base.type = \"object\";\n }\n if (base.type === \"object\") {\n base.properties = (base.properties ?? {}) as Record<\n string,\n JSONSchema7Definition\n >;\n if (base.additionalProperties === undefined) {\n base.additionalProperties = false;\n }\n }\n\n return base;\n }\n\n return {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n } satisfies JSONSchema7;\n};\n\ntype CallToolExecutor = (params: {\n name: string;\n args: unknown;\n options: ToolCallOptions;\n}) => Promise<CallToolResult>;\n\nexport type ToolSchemaOverrides = Record<\n string,\n { inputSchema: FlexibleSchema<unknown> }\n>;\n\nexport type ConvertedToolSet<\n SCHEMAS extends ToolSchemaOverrides | \"automatic\",\n> = SCHEMAS extends ToolSchemaOverrides\n ? { [K in keyof SCHEMAS]: Tool }\n : Record<string, Tool>;\n\ntype ConvertOptions<TOOL_SCHEMAS extends ToolSchemaOverrides | \"automatic\"> = {\n schemas?: TOOL_SCHEMAS;\n callTool: CallToolExecutor;\n};\n\nexport async function convertMCPToolsToVercelTools(\n listToolsResult: ListToolsResult,\n {\n schemas = \"automatic\",\n callTool,\n }: ConvertOptions<ToolSchemaOverrides | \"automatic\">,\n): Promise<ToolSet> {\n const tools: ToolSet = {};\n\n for (const toolDescription of listToolsResult.tools) {\n const { name, description, inputSchema } = toolDescription;\n\n const execute = async (args: unknown, options: ToolCallOptions) => {\n options?.abortSignal?.throwIfAborted?.();\n const result = await callTool({ name, args, options });\n return CallToolResultSchema.parse(result);\n };\n\n let vercelTool: Tool;\n if (schemas === \"automatic\") {\n const normalizedInputSchema = ensureJsonSchemaObject(inputSchema);\n vercelTool = dynamicTool({\n description,\n inputSchema: jsonSchema({\n type: \"object\",\n properties: normalizedInputSchema.properties ?? {},\n additionalProperties:\n (normalizedInputSchema as any).additionalProperties ?? false,\n }),\n execute,\n });\n } else {\n const overrides = schemas;\n if (!(name in overrides)) {\n // If overrides are provided, only include tools explicitly listed\n continue;\n }\n vercelTool = defineTool({\n description,\n inputSchema: overrides[name].inputSchema,\n execute,\n });\n }\n\n tools[name] = vercelTool;\n }\n\n return tools;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAuB;AAEvB,iBAAmC;AAEnC,mBAGO;AACP,4BAA8C;AAE9C,sBAA6C;AAI7C,IAAAA,gBAMO;;;ACnBP,mBAIO;AACP,gBAOO;AAGP,IAAM,yBAAyB,CAAC,WAAiC;AAhBjE;AAiBE,MA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3C,gBAAU,IAAI;AAAA,IAChB;AACA,UAAM,aAAa;AAAA,MACjB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,UAAM,iBAAiB,WAAW;AAAA,MAAK,CAAC,cACtC,QAAQ,SAAS,SAAS;AAAA,IAC5B;AACA,QAAI,CAAC,gBAAgB;AACnB,aAAO;AAAA,IACT;AAEA,QAAI,MAAM,KAAK,YAAY,EAAE,KAAK,CAAC,UAAU,QAAQ,SAAS,KAAK,CAAC,GAAG;AACrE,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AAAA,EAEQ,WAAW,QAAiC;AAzjCtD;AA0jCI,YAAO,YAAO,YAAP,YAAkB,KAAK;AAAA,EAChC;AAAA,EAEQ,cAAc,QAAsD;AAC1E,WAAO,aAAa;AAAA,EACtB;AAAA,EAEQ,cAAc,UAA0B;AAC9C,UAAM,QAAQ,KAAK,aAAa,IAAI,QAAQ;AAC5C,QAAI,EAAC,+BAAO,SAAQ;AAClB,YAAM,IAAI,MAAM,eAAe,QAAQ,qBAAqB;AAAA,IAC9D;AACA,WAAO,MAAM;AAAA,EACf;AACF;","names":["import_types","_a","_b","defineTool","_a"]}
|
|
@@ -20,6 +20,12 @@ type BaseServerConfig = {
|
|
|
20
20
|
timeout?: number;
|
|
21
21
|
version?: string;
|
|
22
22
|
onError?: (error: unknown) => void;
|
|
23
|
+
logJsonRpc?: boolean;
|
|
24
|
+
rpcLogger?: (event: {
|
|
25
|
+
direction: "send" | "receive";
|
|
26
|
+
message: unknown;
|
|
27
|
+
serverId: string;
|
|
28
|
+
}) => void;
|
|
23
29
|
};
|
|
24
30
|
type StdioServerConfig = BaseServerConfig & {
|
|
25
31
|
command: string;
|
|
@@ -73,14 +79,24 @@ declare class MCPClientManager {
|
|
|
73
79
|
private readonly elicitationHandlers;
|
|
74
80
|
private readonly toolsMetadataCache;
|
|
75
81
|
private readonly defaultClientVersion;
|
|
82
|
+
private readonly defaultClientName;
|
|
76
83
|
private readonly defaultCapabilities;
|
|
77
84
|
private readonly defaultTimeout;
|
|
85
|
+
private defaultLogJsonRpc;
|
|
86
|
+
private defaultRpcLogger?;
|
|
78
87
|
private elicitationCallback?;
|
|
79
88
|
private readonly pendingElicitations;
|
|
80
89
|
constructor(servers?: MCPClientManagerConfig, options?: {
|
|
90
|
+
defaultClientName?: string;
|
|
81
91
|
defaultClientVersion?: string;
|
|
82
92
|
defaultCapabilities?: ClientCapabilityOptions;
|
|
83
93
|
defaultTimeout?: number;
|
|
94
|
+
defaultLogJsonRpc?: boolean;
|
|
95
|
+
rpcLogger?: (event: {
|
|
96
|
+
direction: "send" | "receive";
|
|
97
|
+
message: unknown;
|
|
98
|
+
serverId: string;
|
|
99
|
+
}) => void;
|
|
84
100
|
});
|
|
85
101
|
listServers(): string[];
|
|
86
102
|
hasServer(serverId: string): boolean;
|
|
@@ -1591,6 +1607,8 @@ declare class MCPClientManager {
|
|
|
1591
1607
|
private withTimeout;
|
|
1592
1608
|
private buildCapabilities;
|
|
1593
1609
|
private formatError;
|
|
1610
|
+
private wrapTransportForLogging;
|
|
1611
|
+
private resolveRpcLogger;
|
|
1594
1612
|
private isMethodUnavailableError;
|
|
1595
1613
|
private getTimeout;
|
|
1596
1614
|
private isStdioConfig;
|
|
@@ -1606,24 +1624,4 @@ type MCPServerSummary = ServerSummary;
|
|
|
1606
1624
|
type MCPConvertedToolSet<SCHEMAS extends ToolSchemaOverrides | "automatic"> = ConvertedToolSet<SCHEMAS>;
|
|
1607
1625
|
type MCPToolSchemaOverrides = ToolSchemaOverrides;
|
|
1608
1626
|
|
|
1609
|
-
type
|
|
1610
|
-
type index_ExecuteToolArguments = ExecuteToolArguments;
|
|
1611
|
-
type index_MCPClientManager = MCPClientManager;
|
|
1612
|
-
declare const index_MCPClientManager: typeof MCPClientManager;
|
|
1613
|
-
type index_MCPClientManagerConfig = MCPClientManagerConfig;
|
|
1614
|
-
type index_MCPConnectionStatus = MCPConnectionStatus;
|
|
1615
|
-
type index_MCPConvertedToolSet<SCHEMAS extends ToolSchemaOverrides | "automatic"> = MCPConvertedToolSet<SCHEMAS>;
|
|
1616
|
-
type index_MCPGetPromptResult = MCPGetPromptResult;
|
|
1617
|
-
type index_MCPPrompt = MCPPrompt;
|
|
1618
|
-
type index_MCPPromptListResult = MCPPromptListResult;
|
|
1619
|
-
type index_MCPReadResourceResult = MCPReadResourceResult;
|
|
1620
|
-
type index_MCPResource = MCPResource;
|
|
1621
|
-
type index_MCPResourceListResult = MCPResourceListResult;
|
|
1622
|
-
type index_MCPServerConfig = MCPServerConfig;
|
|
1623
|
-
type index_MCPServerSummary = MCPServerSummary;
|
|
1624
|
-
type index_MCPToolSchemaOverrides = MCPToolSchemaOverrides;
|
|
1625
|
-
declare namespace index {
|
|
1626
|
-
export { type index_ElicitationHandler as ElicitationHandler, type index_ExecuteToolArguments as ExecuteToolArguments, index_MCPClientManager as MCPClientManager, type index_MCPClientManagerConfig as MCPClientManagerConfig, type index_MCPConnectionStatus as MCPConnectionStatus, type index_MCPConvertedToolSet as MCPConvertedToolSet, type index_MCPGetPromptResult as MCPGetPromptResult, type index_MCPPrompt as MCPPrompt, type index_MCPPromptListResult as MCPPromptListResult, type index_MCPReadResourceResult as MCPReadResourceResult, type index_MCPResource as MCPResource, type index_MCPResourceListResult as MCPResourceListResult, type index_MCPServerConfig as MCPServerConfig, type index_MCPServerSummary as MCPServerSummary, type index_MCPToolSchemaOverrides as MCPToolSchemaOverrides };
|
|
1627
|
-
}
|
|
1628
|
-
|
|
1629
|
-
export { type ElicitationHandler, type ExecuteToolArguments, MCPClientManager, type MCPClientManagerConfig, type MCPConnectionStatus, type MCPConvertedToolSet, type MCPGetPromptResult, type MCPPrompt, type MCPPromptListResult, type MCPReadResourceResult, type MCPResource, type MCPResourceListResult, type MCPServerConfig, type MCPServerSummary, type MCPToolSchemaOverrides, index as i };
|
|
1627
|
+
export { type ElicitationHandler, type ExecuteToolArguments, MCPClientManager, type MCPClientManagerConfig, type MCPConnectionStatus, type MCPConvertedToolSet, type MCPGetPromptResult, type MCPPrompt, type MCPPromptListResult, type MCPReadResourceResult, type MCPResource, type MCPResourceListResult, type MCPServerConfig, type MCPServerSummary, type MCPToolSchemaOverrides };
|
|
@@ -20,6 +20,12 @@ type BaseServerConfig = {
|
|
|
20
20
|
timeout?: number;
|
|
21
21
|
version?: string;
|
|
22
22
|
onError?: (error: unknown) => void;
|
|
23
|
+
logJsonRpc?: boolean;
|
|
24
|
+
rpcLogger?: (event: {
|
|
25
|
+
direction: "send" | "receive";
|
|
26
|
+
message: unknown;
|
|
27
|
+
serverId: string;
|
|
28
|
+
}) => void;
|
|
23
29
|
};
|
|
24
30
|
type StdioServerConfig = BaseServerConfig & {
|
|
25
31
|
command: string;
|
|
@@ -73,14 +79,24 @@ declare class MCPClientManager {
|
|
|
73
79
|
private readonly elicitationHandlers;
|
|
74
80
|
private readonly toolsMetadataCache;
|
|
75
81
|
private readonly defaultClientVersion;
|
|
82
|
+
private readonly defaultClientName;
|
|
76
83
|
private readonly defaultCapabilities;
|
|
77
84
|
private readonly defaultTimeout;
|
|
85
|
+
private defaultLogJsonRpc;
|
|
86
|
+
private defaultRpcLogger?;
|
|
78
87
|
private elicitationCallback?;
|
|
79
88
|
private readonly pendingElicitations;
|
|
80
89
|
constructor(servers?: MCPClientManagerConfig, options?: {
|
|
90
|
+
defaultClientName?: string;
|
|
81
91
|
defaultClientVersion?: string;
|
|
82
92
|
defaultCapabilities?: ClientCapabilityOptions;
|
|
83
93
|
defaultTimeout?: number;
|
|
94
|
+
defaultLogJsonRpc?: boolean;
|
|
95
|
+
rpcLogger?: (event: {
|
|
96
|
+
direction: "send" | "receive";
|
|
97
|
+
message: unknown;
|
|
98
|
+
serverId: string;
|
|
99
|
+
}) => void;
|
|
84
100
|
});
|
|
85
101
|
listServers(): string[];
|
|
86
102
|
hasServer(serverId: string): boolean;
|
|
@@ -1591,6 +1607,8 @@ declare class MCPClientManager {
|
|
|
1591
1607
|
private withTimeout;
|
|
1592
1608
|
private buildCapabilities;
|
|
1593
1609
|
private formatError;
|
|
1610
|
+
private wrapTransportForLogging;
|
|
1611
|
+
private resolveRpcLogger;
|
|
1594
1612
|
private isMethodUnavailableError;
|
|
1595
1613
|
private getTimeout;
|
|
1596
1614
|
private isStdioConfig;
|
|
@@ -1606,24 +1624,4 @@ type MCPServerSummary = ServerSummary;
|
|
|
1606
1624
|
type MCPConvertedToolSet<SCHEMAS extends ToolSchemaOverrides | "automatic"> = ConvertedToolSet<SCHEMAS>;
|
|
1607
1625
|
type MCPToolSchemaOverrides = ToolSchemaOverrides;
|
|
1608
1626
|
|
|
1609
|
-
type
|
|
1610
|
-
type index_ExecuteToolArguments = ExecuteToolArguments;
|
|
1611
|
-
type index_MCPClientManager = MCPClientManager;
|
|
1612
|
-
declare const index_MCPClientManager: typeof MCPClientManager;
|
|
1613
|
-
type index_MCPClientManagerConfig = MCPClientManagerConfig;
|
|
1614
|
-
type index_MCPConnectionStatus = MCPConnectionStatus;
|
|
1615
|
-
type index_MCPConvertedToolSet<SCHEMAS extends ToolSchemaOverrides | "automatic"> = MCPConvertedToolSet<SCHEMAS>;
|
|
1616
|
-
type index_MCPGetPromptResult = MCPGetPromptResult;
|
|
1617
|
-
type index_MCPPrompt = MCPPrompt;
|
|
1618
|
-
type index_MCPPromptListResult = MCPPromptListResult;
|
|
1619
|
-
type index_MCPReadResourceResult = MCPReadResourceResult;
|
|
1620
|
-
type index_MCPResource = MCPResource;
|
|
1621
|
-
type index_MCPResourceListResult = MCPResourceListResult;
|
|
1622
|
-
type index_MCPServerConfig = MCPServerConfig;
|
|
1623
|
-
type index_MCPServerSummary = MCPServerSummary;
|
|
1624
|
-
type index_MCPToolSchemaOverrides = MCPToolSchemaOverrides;
|
|
1625
|
-
declare namespace index {
|
|
1626
|
-
export { type index_ElicitationHandler as ElicitationHandler, type index_ExecuteToolArguments as ExecuteToolArguments, index_MCPClientManager as MCPClientManager, type index_MCPClientManagerConfig as MCPClientManagerConfig, type index_MCPConnectionStatus as MCPConnectionStatus, type index_MCPConvertedToolSet as MCPConvertedToolSet, type index_MCPGetPromptResult as MCPGetPromptResult, type index_MCPPrompt as MCPPrompt, type index_MCPPromptListResult as MCPPromptListResult, type index_MCPReadResourceResult as MCPReadResourceResult, type index_MCPResource as MCPResource, type index_MCPResourceListResult as MCPResourceListResult, type index_MCPServerConfig as MCPServerConfig, type index_MCPServerSummary as MCPServerSummary, type index_MCPToolSchemaOverrides as MCPToolSchemaOverrides };
|
|
1627
|
-
}
|
|
1628
|
-
|
|
1629
|
-
export { type ElicitationHandler, type ExecuteToolArguments, MCPClientManager, type MCPClientManagerConfig, type MCPConnectionStatus, type MCPConvertedToolSet, type MCPGetPromptResult, type MCPPrompt, type MCPPromptListResult, type MCPReadResourceResult, type MCPResource, type MCPResourceListResult, type MCPServerConfig, type MCPServerSummary, type MCPToolSchemaOverrides, index as i };
|
|
1627
|
+
export { type ElicitationHandler, type ExecuteToolArguments, MCPClientManager, type MCPClientManagerConfig, type MCPConnectionStatus, type MCPConvertedToolSet, type MCPGetPromptResult, type MCPPrompt, type MCPPromptListResult, type MCPReadResourceResult, type MCPResource, type MCPResourceListResult, type MCPServerConfig, type MCPServerSummary, type MCPToolSchemaOverrides };
|
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
// mcp-client-manager/index.ts
|
|
1
|
+
// src/mcp-client-manager/index.ts
|
|
4
2
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
5
3
|
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
6
4
|
import {
|
|
@@ -17,7 +15,7 @@ import {
|
|
|
17
15
|
PromptListChangedNotificationSchema
|
|
18
16
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
19
17
|
|
|
20
|
-
// mcp-client-manager/tool-converters.ts
|
|
18
|
+
// src/mcp-client-manager/tool-converters.ts
|
|
21
19
|
import {
|
|
22
20
|
CallToolResultSchema
|
|
23
21
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
@@ -90,18 +88,22 @@ async function convertMCPToolsToVercelTools(listToolsResult, {
|
|
|
90
88
|
return tools;
|
|
91
89
|
}
|
|
92
90
|
|
|
93
|
-
// mcp-client-manager/index.ts
|
|
91
|
+
// src/mcp-client-manager/index.ts
|
|
94
92
|
var MCPClientManager = class {
|
|
95
93
|
constructor(servers = {}, options = {}) {
|
|
96
94
|
this.clientStates = /* @__PURE__ */ new Map();
|
|
97
95
|
this.notificationHandlers = /* @__PURE__ */ new Map();
|
|
98
96
|
this.elicitationHandlers = /* @__PURE__ */ new Map();
|
|
99
97
|
this.toolsMetadataCache = /* @__PURE__ */ new Map();
|
|
98
|
+
this.defaultLogJsonRpc = false;
|
|
100
99
|
this.pendingElicitations = /* @__PURE__ */ new Map();
|
|
101
|
-
var _a, _b, _c;
|
|
100
|
+
var _a, _b, _c, _d, _e;
|
|
102
101
|
this.defaultClientVersion = (_a = options.defaultClientVersion) != null ? _a : "1.0.0";
|
|
103
|
-
this.
|
|
104
|
-
this.
|
|
102
|
+
this.defaultClientName = (_b = options.defaultClientName) != null ? _b : void 0;
|
|
103
|
+
this.defaultCapabilities = { ...(_c = options.defaultCapabilities) != null ? _c : {} };
|
|
104
|
+
this.defaultTimeout = (_d = options.defaultTimeout) != null ? _d : DEFAULT_REQUEST_TIMEOUT_MSEC;
|
|
105
|
+
this.defaultLogJsonRpc = (_e = options.defaultLogJsonRpc) != null ? _e : false;
|
|
106
|
+
this.defaultRpcLogger = options.rpcLogger;
|
|
105
107
|
for (const [id, config] of Object.entries(servers)) {
|
|
106
108
|
void this.connectToServer(id, config);
|
|
107
109
|
}
|
|
@@ -150,7 +152,7 @@ var MCPClientManager = class {
|
|
|
150
152
|
var _a2;
|
|
151
153
|
const client = new Client(
|
|
152
154
|
{
|
|
153
|
-
name: serverId,
|
|
155
|
+
name: this.defaultClientName ? `${this.defaultClientName}` : serverId,
|
|
154
156
|
version: (_a2 = config.version) != null ? _a2 : this.defaultClientVersion
|
|
155
157
|
},
|
|
156
158
|
{
|
|
@@ -170,7 +172,12 @@ var MCPClientManager = class {
|
|
|
170
172
|
};
|
|
171
173
|
let transport;
|
|
172
174
|
if (this.isStdioConfig(config)) {
|
|
173
|
-
transport = await this.connectViaStdio(
|
|
175
|
+
transport = await this.connectViaStdio(
|
|
176
|
+
serverId,
|
|
177
|
+
client,
|
|
178
|
+
config,
|
|
179
|
+
timeout
|
|
180
|
+
);
|
|
174
181
|
} else {
|
|
175
182
|
transport = await this.connectViaHttp(
|
|
176
183
|
serverId,
|
|
@@ -516,15 +523,16 @@ var MCPClientManager = class {
|
|
|
516
523
|
this.pendingElicitations.delete(requestId);
|
|
517
524
|
}
|
|
518
525
|
}
|
|
519
|
-
async connectViaStdio(client, config, timeout) {
|
|
526
|
+
async connectViaStdio(serverId, client, config, timeout) {
|
|
520
527
|
var _a;
|
|
521
|
-
const
|
|
528
|
+
const underlying = new StdioClientTransport({
|
|
522
529
|
command: config.command,
|
|
523
530
|
args: config.args,
|
|
524
531
|
env: { ...getDefaultEnvironment(), ...(_a = config.env) != null ? _a : {} }
|
|
525
532
|
});
|
|
526
|
-
|
|
527
|
-
|
|
533
|
+
const wrapped = this.wrapTransportForLogging(serverId, config, underlying);
|
|
534
|
+
await client.connect(wrapped, { timeout });
|
|
535
|
+
return underlying;
|
|
528
536
|
}
|
|
529
537
|
async connectViaHttp(serverId, client, config, timeout) {
|
|
530
538
|
var _a;
|
|
@@ -541,7 +549,12 @@ var MCPClientManager = class {
|
|
|
541
549
|
}
|
|
542
550
|
);
|
|
543
551
|
try {
|
|
544
|
-
|
|
552
|
+
const wrapped = this.wrapTransportForLogging(
|
|
553
|
+
serverId,
|
|
554
|
+
config,
|
|
555
|
+
streamableTransport
|
|
556
|
+
);
|
|
557
|
+
await client.connect(wrapped, {
|
|
545
558
|
timeout: Math.min(timeout, 3e3)
|
|
546
559
|
});
|
|
547
560
|
return streamableTransport;
|
|
@@ -556,7 +569,12 @@ var MCPClientManager = class {
|
|
|
556
569
|
authProvider: config.authProvider
|
|
557
570
|
});
|
|
558
571
|
try {
|
|
559
|
-
|
|
572
|
+
const wrapped = this.wrapTransportForLogging(
|
|
573
|
+
serverId,
|
|
574
|
+
config,
|
|
575
|
+
sseTransport
|
|
576
|
+
);
|
|
577
|
+
await client.connect(wrapped, { timeout });
|
|
560
578
|
return sseTransport;
|
|
561
579
|
} catch (error) {
|
|
562
580
|
await this.safeCloseTransport(sseTransport);
|
|
@@ -684,6 +702,74 @@ var MCPClientManager = class {
|
|
|
684
702
|
return String(error);
|
|
685
703
|
}
|
|
686
704
|
}
|
|
705
|
+
// Returns a transport that logs JSON-RPC traffic if enabled for this server
|
|
706
|
+
wrapTransportForLogging(serverId, config, transport) {
|
|
707
|
+
const logger = this.resolveRpcLogger(serverId, config);
|
|
708
|
+
if (!logger) return transport;
|
|
709
|
+
const log = logger;
|
|
710
|
+
const self = this;
|
|
711
|
+
class LoggingTransport {
|
|
712
|
+
constructor(inner) {
|
|
713
|
+
this.inner = inner;
|
|
714
|
+
this.inner.onmessage = (message, extra) => {
|
|
715
|
+
var _a;
|
|
716
|
+
try {
|
|
717
|
+
log({ direction: "receive", message, serverId });
|
|
718
|
+
} catch {
|
|
719
|
+
}
|
|
720
|
+
(_a = this.onmessage) == null ? void 0 : _a.call(this, message, extra);
|
|
721
|
+
};
|
|
722
|
+
this.inner.onclose = () => {
|
|
723
|
+
var _a;
|
|
724
|
+
(_a = this.onclose) == null ? void 0 : _a.call(this);
|
|
725
|
+
};
|
|
726
|
+
this.inner.onerror = (error) => {
|
|
727
|
+
var _a;
|
|
728
|
+
(_a = this.onerror) == null ? void 0 : _a.call(this, error);
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
async start() {
|
|
732
|
+
if (typeof this.inner.start === "function") {
|
|
733
|
+
await this.inner.start();
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
async send(message, options) {
|
|
737
|
+
try {
|
|
738
|
+
log({ direction: "send", message, serverId });
|
|
739
|
+
} catch {
|
|
740
|
+
}
|
|
741
|
+
await this.inner.send(message, options);
|
|
742
|
+
}
|
|
743
|
+
async close() {
|
|
744
|
+
await this.inner.close();
|
|
745
|
+
}
|
|
746
|
+
get sessionId() {
|
|
747
|
+
return this.inner.sessionId;
|
|
748
|
+
}
|
|
749
|
+
setProtocolVersion(version) {
|
|
750
|
+
if (typeof this.inner.setProtocolVersion === "function") {
|
|
751
|
+
this.inner.setProtocolVersion(version);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
return new LoggingTransport(transport);
|
|
756
|
+
}
|
|
757
|
+
resolveRpcLogger(serverId, config) {
|
|
758
|
+
if (config.rpcLogger) return config.rpcLogger;
|
|
759
|
+
if (config.logJsonRpc || this.defaultLogJsonRpc) {
|
|
760
|
+
return ({ direction, message, serverId: id }) => {
|
|
761
|
+
let printable;
|
|
762
|
+
try {
|
|
763
|
+
printable = typeof message === "string" ? message : JSON.stringify(message);
|
|
764
|
+
} catch {
|
|
765
|
+
printable = String(message);
|
|
766
|
+
}
|
|
767
|
+
console.debug(`[MCP:${id}] ${direction.toUpperCase()} ${printable}`);
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
if (this.defaultRpcLogger) return this.defaultRpcLogger;
|
|
771
|
+
return void 0;
|
|
772
|
+
}
|
|
687
773
|
isMethodUnavailableError(error, method) {
|
|
688
774
|
if (!(error instanceof Error)) {
|
|
689
775
|
return false;
|