@ai-sdk/mcp 2.0.72 → 2.0.74

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/tool/types.ts","../../src/tool/json-rpc-message.ts","../../src/error/mcp-client-error.ts","../../src/tool/mcp-stdio/get-environment.ts","../../src/tool/mcp-stdio/create-child-process.ts","../../src/tool/mcp-stdio/mcp-stdio-transport.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport type { JSONObject } from '@ai-sdk/provider';\nimport type { FlexibleSchema, Tool } from '@ai-sdk/provider-utils';\n\nexport const LATEST_PROTOCOL_VERSION = '2026-07-28';\nexport const LATEST_LEGACY_PROTOCOL_VERSION = '2025-11-25';\nexport const SUPPORTED_PROTOCOL_VERSIONS = [\n LATEST_PROTOCOL_VERSION,\n LATEST_LEGACY_PROTOCOL_VERSION,\n '2025-06-18',\n '2025-03-26',\n '2024-11-05',\n];\n\nexport type McpProviderMetadata = {\n clientName?: string;\n title?: string;\n toolName?: string;\n annotations?: McpToolAnnotations;\n app?: JSONObject;\n};\n\n/**\n * Behavioral hints reported by an MCP server for a tool.\n *\n * These annotations are untrusted unless the server itself is trusted.\n *\n * @see https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations\n */\nexport type McpToolAnnotations = {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n};\n\n/** MCP tool metadata - keys should follow MCP _meta key format specification */\nconst ToolMetaSchema = z.optional(z.record(z.string(), z.unknown()));\nexport type ToolMeta = z.infer<typeof ToolMetaSchema>;\n\nexport type ToolSchemas =\n | Record<\n string,\n {\n inputSchema: FlexibleSchema<JSONObject | unknown>;\n outputSchema?: FlexibleSchema<JSONObject | unknown>;\n }\n >\n | 'automatic'\n | undefined;\n\n/** Base MCP tool type with execute and _meta */\ntype McpToolBase<INPUT = unknown, OUTPUT = CallToolResult> = Tool<\n INPUT,\n OUTPUT\n> &\n Required<Pick<Tool<INPUT, OUTPUT>, 'execute'>> & {\n _meta?: ToolMeta;\n };\n\nexport type McpToolSet<TOOL_SCHEMAS extends ToolSchemas = 'automatic'> =\n TOOL_SCHEMAS extends Record<\n string,\n { inputSchema: FlexibleSchema<any>; outputSchema?: FlexibleSchema<any> }\n >\n ? {\n [K in keyof TOOL_SCHEMAS]: TOOL_SCHEMAS[K] extends {\n inputSchema: FlexibleSchema<infer INPUT>;\n outputSchema: FlexibleSchema<infer OUTPUT>;\n }\n ? McpToolBase<INPUT, OUTPUT>\n : TOOL_SCHEMAS[K] extends {\n inputSchema: FlexibleSchema<infer INPUT>;\n }\n ? McpToolBase<INPUT, CallToolResult>\n : never;\n }\n : Record<string, McpToolBase<unknown, CallToolResult>>;\n\nconst ClientOrServerImplementationSchema = z.looseObject({\n name: z.string(),\n version: z.string(),\n title: z.optional(z.string()),\n});\n\n// Maps to `Implementation` in the MCP specification\nexport type Configuration = z.infer<typeof ClientOrServerImplementationSchema>;\n\nexport const BaseParamsSchema = z.looseObject({\n _meta: z.optional(z.object({}).loose()),\n});\ntype BaseParams = z.infer<typeof BaseParamsSchema>;\nexport const ResultSchema = BaseParamsSchema.extend({\n resultType: z.optional(z.string()),\n});\n\nexport const RequestSchema = z.object({\n method: z.string(),\n params: z.optional(BaseParamsSchema),\n});\nexport type Request = z.infer<typeof RequestSchema>;\nexport type RequestOptions = {\n signal?: AbortSignal;\n timeout?: number;\n maxTotalTimeout?: number;\n};\n\nexport type Notification = z.infer<typeof RequestSchema>;\n\n/** @see https://modelcontextprotocol.io/specification/2025-06-18/client/elicitation */\nconst ElicitationCapabilitySchema = z\n .object({\n applyDefaults: z.optional(z.boolean()),\n })\n .loose();\n\nconst ServerCapabilitiesSchema = z.looseObject({\n events: z.looseObject({ listChanged: z.boolean().nullish() }).nullish(),\n experimental: z.optional(z.object({}).loose()),\n logging: z.optional(z.object({}).loose()),\n completions: z.optional(z.object({}).loose()),\n prompts: z.optional(\n z.looseObject({\n listChanged: z.optional(z.boolean()),\n }),\n ),\n resources: z.optional(\n z.looseObject({\n subscribe: z.optional(z.boolean()),\n listChanged: z.optional(z.boolean()),\n }),\n ),\n tools: z.optional(\n z.looseObject({\n listChanged: z.optional(z.boolean()),\n }),\n ),\n elicitation: z.optional(ElicitationCapabilitySchema),\n});\n\nexport type ServerCapabilities = z.infer<typeof ServerCapabilitiesSchema>;\nexport const ClientCapabilitiesSchema = z\n .object({\n elicitation: z.optional(ElicitationCapabilitySchema),\n })\n .loose();\n\nexport type ClientCapabilities = z.infer<typeof ClientCapabilitiesSchema>;\nexport type ElicitationCapability = z.infer<typeof ElicitationCapabilitySchema>;\n\nexport const DiscoverResultSchema = ResultSchema.extend({\n supportedVersions: z.array(z.string()),\n capabilities: ServerCapabilitiesSchema,\n instructions: z.optional(z.string()),\n ttlMs: z.optional(z.number()),\n cacheScope: z.optional(z.union([z.literal('public'), z.literal('private')])),\n});\nexport type DiscoverResult = z.infer<typeof DiscoverResultSchema>;\n\nexport const InitializeResultSchema = ResultSchema.extend({\n protocolVersion: z.string(),\n capabilities: ServerCapabilitiesSchema,\n serverInfo: ClientOrServerImplementationSchema,\n instructions: z.optional(z.string()),\n});\nexport type InitializeResult = z.infer<typeof InitializeResultSchema>;\n\nexport type PaginatedRequest = Request & {\n params?: BaseParams & {\n cursor?: string;\n };\n};\n\nconst PaginatedResultSchema = ResultSchema.extend({\n nextCursor: z.optional(z.string()),\n});\n\nconst ToolSchema = z\n .object({\n name: z.string(),\n /**\n * @see https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool\n */\n title: z.optional(z.string()),\n description: z.optional(z.string()),\n inputSchema: z.looseObject({\n type: z.optional(z.unknown()),\n properties: z.optional(z.object({}).loose()),\n }),\n /**\n * @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema\n */\n outputSchema: z.optional(z.object({}).loose()),\n annotations: z.optional(\n z\n .object({\n title: z.optional(z.string()),\n readOnlyHint: z.optional(z.boolean()),\n destructiveHint: z.optional(z.boolean()),\n idempotentHint: z.optional(z.boolean()),\n openWorldHint: z.optional(z.boolean()),\n })\n .loose(),\n ),\n _meta: ToolMetaSchema,\n })\n .loose();\nexport type MCPTool = z.infer<typeof ToolSchema>;\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema),\n});\nexport type ListToolsResult = z.infer<typeof ListToolsResultSchema>;\n\nconst TextContentSchema = z\n .object({\n type: z.literal('text'),\n text: z.string(),\n })\n .loose();\nconst ImageContentSchema = z\n .object({\n type: z.literal('image'),\n data: z.base64(),\n mimeType: z.string(),\n })\n .loose();\nexport const ResourceSchema = z\n .object({\n uri: z.string(),\n name: z.string(),\n title: z.optional(z.string()),\n description: z.optional(z.string()),\n mimeType: z.optional(z.string()),\n size: z.optional(z.number()),\n })\n .loose();\nexport type MCPResource = z.infer<typeof ResourceSchema>;\n\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema),\n});\nexport type ListResourcesResult = z.infer<typeof ListResourcesResultSchema>;\n\nconst ResourceContentsSchema = z\n .object({\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * Optional display name of the resource content.\n */\n name: z.optional(z.string()),\n /**\n * Optional human readable title.\n */\n title: z.optional(z.string()),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n })\n .loose();\nconst TextResourceContentsSchema = ResourceContentsSchema.extend({\n text: z.string(),\n});\nconst BlobResourceContentsSchema = ResourceContentsSchema.extend({\n blob: z.base64(),\n});\nconst EmbeddedResourceSchema = z\n .object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n })\n .loose();\nconst ResourceLinkContentSchema = z\n .object({\n type: z.literal('resource_link'),\n uri: z.string(),\n name: z.string(),\n description: z.optional(z.string()),\n mimeType: z.optional(z.string()),\n })\n .loose();\nconst UnknownContentSchema = z\n .object({ type: z.string() })\n .loose()\n .refine(\n content =>\n !['text', 'image', 'resource', 'resource_link'].includes(content.type),\n { message: 'Known content types must match their schema' },\n );\n\nconst CallToolResultWithContentSchema = ResultSchema.extend({\n content: z.array(\n z.union([\n TextContentSchema,\n ImageContentSchema,\n EmbeddedResourceSchema,\n ResourceLinkContentSchema,\n UnknownContentSchema,\n ]),\n ),\n /**\n * @see https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content\n */\n structuredContent: z.optional(z.unknown()),\n isError: z.boolean().default(false).optional(),\n});\n\nconst CallToolResultWithStructuredContentSchema = ResultSchema.extend({\n content: z.never().optional(),\n structuredContent: z.json(),\n isError: z.boolean().default(false).optional(),\n})\n .transform(\n (result): z.infer<typeof CallToolResultWithContentSchema> => ({\n ...result,\n content: [\n {\n type: 'text',\n text: JSON.stringify(result.structuredContent),\n },\n ],\n }),\n )\n .pipe(CallToolResultWithContentSchema);\n\nexport const CallToolResultSchema = CallToolResultWithContentSchema.or(\n CallToolResultWithStructuredContentSchema,\n).or(\n ResultSchema.extend({\n toolResult: z.unknown().nonoptional(),\n }),\n);\nexport type CallToolResult = z.infer<typeof CallToolResultSchema>;\n\nconst ResourceTemplateSchema = z\n .object({\n uriTemplate: z.string(),\n name: z.string(),\n title: z.optional(z.string()),\n description: z.optional(z.string()),\n mimeType: z.optional(z.string()),\n })\n .loose();\n\nexport const ListResourceTemplatesResultSchema = ResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema),\n});\nexport type ListResourceTemplatesResult = z.infer<\n typeof ListResourceTemplatesResultSchema\n>;\n\nexport const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(\n z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n ),\n});\nexport type ReadResourceResult = z.infer<typeof ReadResourceResultSchema>;\n\n// Completions\nconst PromptReferenceSchema = z\n .object({\n type: z.literal('ref/prompt'),\n name: z.string(),\n })\n .loose();\n\nconst ResourceReferenceSchema = z\n .object({\n type: z.literal('ref/resource'),\n uri: z.string(),\n })\n .loose();\n\nconst CompletionArgumentSchema = z\n .object({\n name: z.string(),\n value: z.string(),\n })\n .loose();\n\nexport const CompleteRequestParamsSchema = BaseParamsSchema.extend({\n ref: z.union([PromptReferenceSchema, ResourceReferenceSchema]),\n argument: CompletionArgumentSchema,\n context: z.optional(\n z\n .object({\n arguments: z.record(z.string(), z.string()),\n })\n .loose(),\n ),\n});\nexport type CompleteRequestParams = z.infer<typeof CompleteRequestParamsSchema>;\n\nexport const CompleteResultSchema = ResultSchema.extend({\n completion: z\n .object({\n values: z.array(z.string()).max(100),\n total: z.optional(z.number().int()),\n hasMore: z.optional(z.boolean()),\n })\n .loose(),\n});\nexport type CompleteResult = z.infer<typeof CompleteResultSchema>;\n\n// Prompts\nconst PromptArgumentSchema = z\n .object({\n name: z.string(),\n description: z.optional(z.string()),\n required: z.optional(z.boolean()),\n })\n .loose();\n\nexport const PromptSchema = z\n .object({\n name: z.string(),\n title: z.optional(z.string()),\n description: z.optional(z.string()),\n arguments: z.optional(z.array(PromptArgumentSchema)),\n })\n .loose();\nexport type MCPPrompt = z.infer<typeof PromptSchema>;\n\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema),\n});\nexport type ListPromptsResult = z.infer<typeof ListPromptsResultSchema>;\n\nconst PromptMessageSchema = z\n .object({\n role: z.union([z.literal('user'), z.literal('assistant')]),\n content: z.union([\n TextContentSchema,\n ImageContentSchema,\n EmbeddedResourceSchema,\n ResourceLinkContentSchema,\n ]),\n })\n .loose();\nexport type MCPPromptMessage = z.infer<typeof PromptMessageSchema>;\n\nexport const GetPromptResultSchema = ResultSchema.extend({\n description: z.optional(z.string()),\n messages: z.array(PromptMessageSchema),\n});\nexport type GetPromptResult = z.infer<typeof GetPromptResultSchema>;\n\nconst ElicitationRequestParamsSchema = BaseParamsSchema.extend({\n message: z.string(),\n requestedSchema: z.unknown(),\n});\n\nexport const ElicitationRequestSchema = RequestSchema.extend({\n method: z.literal('elicitation/create'),\n params: ElicitationRequestParamsSchema,\n});\n\nexport type ElicitationRequest = z.infer<typeof ElicitationRequestSchema>;\n\nexport const ElicitResultSchema = ResultSchema.extend({\n action: z.union([\n z.literal('accept'),\n z.literal('decline'),\n z.literal('cancel'),\n ]),\n content: z.optional(z.record(z.string(), z.unknown())),\n});\n\nexport type ElicitResult = z.infer<typeof ElicitResultSchema>;\n","import { parseJSON } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { BaseParamsSchema, RequestSchema, ResultSchema } from './types';\n\nconst JSONRPC_VERSION = '2.0';\n\nconst JSONRPCRequestSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: z.union([z.string(), z.number().int()]),\n })\n .merge(RequestSchema)\n .strict();\n\nexport type JSONRPCRequest = z.infer<typeof JSONRPCRequestSchema>;\n\nconst JSONRPCResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: z.union([z.string(), z.number().int()]),\n result: ResultSchema,\n })\n .strict();\n\nexport type JSONRPCResponse = z.infer<typeof JSONRPCResponseSchema>;\n\nconst JSONRPCErrorSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: z.optional(z.union([z.string(), z.number().int()])),\n error: z.object({\n code: z.number().int(),\n message: z.string(),\n data: z.optional(z.unknown()),\n }),\n })\n .strict();\n\nexport type JSONRPCError = z.infer<typeof JSONRPCErrorSchema>;\n\nconst JSONRPCNotificationSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n })\n .merge(\n z.object({\n method: z.string(),\n params: z.optional(BaseParamsSchema),\n }),\n )\n .strict();\n\nexport type JSONRPCNotification = z.infer<typeof JSONRPCNotificationSchema>;\n\nexport const JSONRPCMessageSchema = z.union([\n JSONRPCRequestSchema,\n JSONRPCNotificationSchema,\n JSONRPCResponseSchema,\n JSONRPCErrorSchema,\n]);\n\nexport type JSONRPCMessage = z.infer<typeof JSONRPCMessageSchema>;\n\nexport function validateJSONRPCMessage(message: unknown): JSONRPCMessage {\n return JSONRPCMessageSchema.parse(message);\n}\n\nexport async function parseJSONRPCMessage(\n text: string,\n): Promise<JSONRPCMessage> {\n return validateJSONRPCMessage(await parseJSON({ text }));\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_MCPClientError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * An error occurred with the MCP client.\n */\nexport class MCPClientError extends AISDKError {\n private readonly [symbol] = true;\n readonly data?: unknown;\n\n /**\n * JSON-RPC error code from the server response, per the JSON-RPC 2.0\n * spec (e.g. `-32601` method-not-found, `-32602` invalid-params, or\n * MCP-specific codes such as `-32002` resource-not-found). This is the\n * application-level error code populated from `error.code` in the\n * server's JSON-RPC error payload. Distinct from `statusCode`, which\n * is the HTTP transport status.\n */\n readonly code?: number;\n\n /**\n * HTTP status code from the failed response, when the error originated\n * from an HTTP-based transport. Undefined for stdio transport\n * errors and for failures that do not have an associated response\n * status (e.g. network errors, abort). Distinct from `code`, which is\n * the JSON-RPC application error code.\n */\n readonly statusCode?: number;\n\n /**\n * URL of the MCP endpoint the failing request was sent to, when the\n * error originated from an HTTP transport failure.\n */\n readonly url?: string;\n\n /**\n * Body of the failing HTTP response, decoded as text, when available.\n * Undefined when the body could not be read or the error did not have\n * an associated response.\n */\n readonly responseBody?: string;\n\n constructor({\n name = 'MCPClientError',\n message,\n cause,\n data,\n code,\n statusCode,\n url,\n responseBody,\n }: {\n name?: string;\n message: string;\n cause?: unknown;\n data?: unknown;\n code?: number;\n statusCode?: number;\n url?: string;\n responseBody?: string;\n }) {\n super({ name, message, cause });\n this.data = data;\n this.code = code;\n this.statusCode = statusCode;\n this.url = url;\n this.responseBody = responseBody;\n }\n\n static isInstance(error: unknown): error is MCPClientError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","/**\n * Constructs the environment variables for the child process.\n *\n * @param customEnv - Custom environment variables to merge with default environment variables.\n * @returns The environment variables for the child process.\n */\nexport function getEnvironment(\n customEnv?: Record<string, string>,\n): Record<string, string> {\n const isWindows = globalThis.process.platform === 'win32';\n const DEFAULT_INHERITED_ENV_VARS = isWindows\n ? [\n 'APPDATA',\n 'HOMEDRIVE',\n 'HOMEPATH',\n 'LOCALAPPDATA',\n 'PATH',\n 'PROCESSOR_ARCHITECTURE',\n 'SYSTEMDRIVE',\n 'SYSTEMROOT',\n 'TEMP',\n 'USERNAME',\n 'USERPROFILE',\n ]\n : ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER'];\n\n const env: Record<string, string> = customEnv ? { ...customEnv } : {};\n const customEnvKeys = new Set(\n Object.keys(env).map(key => (isWindows ? key.toUpperCase() : key)),\n );\n\n for (const key of DEFAULT_INHERITED_ENV_VARS) {\n if (customEnvKeys.has(key)) {\n continue;\n }\n\n const value = globalThis.process.env[key];\n if (value === undefined) {\n continue;\n }\n\n if (value.startsWith('()')) {\n continue;\n }\n\n env[key] = value;\n }\n\n return env;\n}\n","import type { ChildProcess } from 'node:child_process';\nimport spawn from 'cross-spawn';\nimport { getEnvironment } from './get-environment';\nimport type { StdioConfig } from './mcp-stdio-transport';\n\nexport function createChildProcess(\n config: StdioConfig,\n signal: AbortSignal,\n): ChildProcess {\n if (\n globalThis.process.platform === 'win32' &&\n [config.command, ...(config.args ?? [])].some(value => /[\\r\\n]/.test(value))\n ) {\n throw new TypeError(\n 'Stdio MCP commands and arguments must not contain line breaks on Windows.',\n );\n }\n\n return spawn(config.command, config.args ?? [], {\n env: getEnvironment(config.env),\n stdio: ['pipe', 'pipe', config.stderr ?? 'inherit'],\n shell: false,\n signal,\n windowsHide: globalThis.process.platform === 'win32' && isElectron(),\n cwd: config.cwd,\n });\n}\n\nfunction isElectron() {\n return 'type' in globalThis.process;\n}\n","import type { ChildProcess, IOType } from 'node:child_process';\nimport type { Stream } from 'node:stream';\nimport { parseJSONRPCMessage, type JSONRPCMessage } from '../json-rpc-message';\nimport type { MCPTransport } from '../mcp-transport';\nimport { MCPClientError } from '../../error/mcp-client-error';\nimport { createChildProcess } from './create-child-process';\n\nexport interface StdioConfig {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n stderr?: IOType | Stream | number;\n cwd?: string;\n}\n\nexport class StdioMCPTransport implements MCPTransport {\n readonly supportsProtocolVersionDiscovery = true;\n private process?: ChildProcess;\n private abortController: AbortController = new AbortController();\n private readBuffer: ReadBuffer = new ReadBuffer();\n private serverParams: StdioConfig;\n\n onclose?: () => void;\n onerror?: (error: unknown) => void;\n onmessage?: (message: JSONRPCMessage) => void;\n\n constructor(server: StdioConfig) {\n this.serverParams = server;\n }\n\n async start(): Promise<void> {\n if (this.process) {\n throw new MCPClientError({\n message: 'StdioMCPTransport already started.',\n });\n }\n\n return new Promise((resolve, reject) => {\n try {\n const process = createChildProcess(\n this.serverParams,\n this.abortController.signal,\n );\n\n this.process = process;\n\n this.process.on('error', error => {\n if (error.name === 'AbortError') {\n this.onclose?.();\n return;\n }\n\n reject(error);\n this.onerror?.(error);\n });\n\n this.process.on('spawn', () => {\n resolve();\n });\n\n this.process.on('close', _code => {\n this.process = undefined;\n this.onclose?.();\n });\n\n this.process.stdin?.on('error', error => {\n this.onerror?.(error);\n });\n\n this.process.stdout?.on('data', chunk => {\n this.readBuffer.append(chunk);\n void this.processReadBuffer();\n });\n\n this.process.stdout?.on('error', error => {\n this.onerror?.(error);\n });\n } catch (error) {\n reject(error);\n this.onerror?.(error);\n }\n });\n }\n\n private async processReadBuffer() {\n while (true) {\n const line = this.readBuffer.readLine();\n if (line === null) {\n break;\n }\n\n try {\n const message = await deserializeMessage(line);\n this.onmessage?.(message);\n } catch (error) {\n this.onerror?.(error as Error);\n }\n }\n }\n\n async close(): Promise<void> {\n this.abortController.abort();\n this.process = undefined;\n this.readBuffer.clear();\n }\n\n send(message: JSONRPCMessage): Promise<void> {\n return new Promise(resolve => {\n if (!this.process?.stdin) {\n throw new MCPClientError({\n message: 'StdioClientTransport not connected',\n });\n }\n\n const json = serializeMessage(message);\n if (this.process.stdin.write(json)) {\n resolve();\n } else {\n this.process.stdin.once('drain', resolve);\n }\n });\n }\n}\n\nclass ReadBuffer {\n private buffer?: Buffer;\n\n append(chunk: Buffer): void {\n this.buffer = this.buffer ? Buffer.concat([this.buffer, chunk]) : chunk;\n }\n\n readLine(): string | null {\n if (!this.buffer) return null;\n\n const index = this.buffer.indexOf('\\n');\n if (index === -1) {\n return null;\n }\n\n const line = this.buffer.toString('utf8', 0, index);\n this.buffer = this.buffer.subarray(index + 1);\n return line;\n }\n\n clear(): void {\n this.buffer = undefined;\n }\n}\n\nfunction serializeMessage(message: JSONRPCMessage): string {\n return JSON.stringify(message) + '\\n';\n}\n\nexport async function deserializeMessage(\n line: string,\n): Promise<JSONRPCMessage> {\n return parseJSONRPCMessage(line);\n}\n"],"mappings":";;;;;;AAsCA,MAAM,iBAAiB,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC;AA0CnE,MAAM,qCAAqC,EAAE,YAAY;CACvD,MAAM,EAAE,OAAO;CACf,SAAS,EAAE,OAAO;CAClB,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC;AAC9B,CAAC;AAKD,MAAa,mBAAmB,EAAE,YAAY,EAC5C,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EACxC,CAAC;AAED,MAAa,eAAe,iBAAiB,OAAO,EAClD,YAAY,EAAE,SAAS,EAAE,OAAO,CAAC,EACnC,CAAC;AAED,MAAa,gBAAgB,EAAE,OAAO;CACpC,QAAQ,EAAE,OAAO;CACjB,QAAQ,EAAE,SAAS,gBAAgB;AACrC,CAAC;;AAWD,MAAM,8BAA8B,EACjC,OAAO,EACN,eAAe,EAAE,SAAS,EAAE,QAAQ,CAAC,EACvC,CAAC,CAAC,CACD,MAAM;AAET,MAAM,2BAA2B,EAAE,YAAY;CAC7C,QAAQ,EAAE,YAAY,EAAE,aAAa,EAAE,QAAQ,CAA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IACZ,OAAO;EAGT,MAAM,OAAO,KAAK,OAAO,SAAS,QAAQ,GAAG,KAAK;EAClD,KAAK,SAAS,KAAK,OAAO,SAAS,QAAQ,CAAC;EAC5C,OAAO;CACT;CAEA,QAAc;EACZ,KAAK,SAAS,KAAA;CAChB;AACF;AAEA,SAAS,iBAAiB,SAAiC;CACzD,OAAO,KAAK,UAAU,OAAO,IAAI;AACnC;AAEA,eAAsB,mBACpB,MACyB;CACzB,OAAO,oBAAoB,IAAI;AACjC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/tool/types.ts","../../src/tool/json-rpc-message.ts","../../src/error/mcp-client-error.ts","../../src/tool/mcp-stdio/get-environment.ts","../../src/tool/mcp-stdio/create-child-process.ts","../../src/tool/mcp-stdio/mcp-stdio-transport.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport type { JSONObject } from '@ai-sdk/provider';\nimport type {\n FlexibleSchema,\n Tool,\n ToolExecutionOptions,\n} from '@ai-sdk/provider-utils';\n\nexport const LATEST_PROTOCOL_VERSION = '2026-07-28';\nexport const LATEST_LEGACY_PROTOCOL_VERSION = '2025-11-25';\nexport const SUPPORTED_PROTOCOL_VERSIONS = [\n LATEST_PROTOCOL_VERSION,\n LATEST_LEGACY_PROTOCOL_VERSION,\n '2025-06-18',\n '2025-03-26',\n '2024-11-05',\n];\n\nexport type McpProviderMetadata = {\n clientName?: string;\n title?: string;\n toolName?: string;\n annotations?: McpToolAnnotations;\n app?: JSONObject;\n};\n\n/**\n * Behavioral hints reported by an MCP server for a tool.\n *\n * These annotations are untrusted unless the server itself is trusted.\n *\n * @see https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations\n */\nexport type McpToolAnnotations = {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n};\n\n/** MCP tool metadata - keys should follow MCP _meta key format specification */\nconst ToolMetaSchema = z.optional(z.record(z.string(), z.unknown()));\nexport type ToolMeta = z.infer<typeof ToolMetaSchema>;\n\nexport type ToolSchemas =\n | Record<\n string,\n {\n inputSchema: FlexibleSchema<JSONObject | unknown>;\n outputSchema?: FlexibleSchema<JSONObject | unknown>;\n }\n >\n | 'automatic'\n | undefined;\n\n/** Base MCP tool type with execute and _meta */\ntype McpToolBase<INPUT = unknown, OUTPUT = CallToolResult> = Tool<\n INPUT,\n OUTPUT\n> & {\n execute: (\n input: INPUT,\n options?: ToolExecutionOptions<{}>,\n ) => ReturnType<NonNullable<Tool<INPUT, OUTPUT>['execute']>>;\n _meta?: ToolMeta;\n};\n\nexport type McpToolSet<TOOL_SCHEMAS extends ToolSchemas = 'automatic'> =\n TOOL_SCHEMAS extends Record<\n string,\n { inputSchema: FlexibleSchema<any>; outputSchema?: FlexibleSchema<any> }\n >\n ? {\n [K in keyof TOOL_SCHEMAS]: TOOL_SCHEMAS[K] extends {\n inputSchema: FlexibleSchema<infer INPUT>;\n outputSchema: FlexibleSchema<infer OUTPUT>;\n }\n ? McpToolBase<INPUT, OUTPUT>\n : TOOL_SCHEMAS[K] extends {\n inputSchema: FlexibleSchema<infer INPUT>;\n }\n ? McpToolBase<INPUT, CallToolResult>\n : never;\n }\n : Record<string, McpToolBase<unknown, CallToolResult>>;\n\nconst ClientOrServerImplementationSchema = z.looseObject({\n name: z.string(),\n version: z.string(),\n title: z.optional(z.string()),\n});\n\n// Maps to `Implementation` in the MCP specification\nexport type Configuration = z.infer<typeof ClientOrServerImplementationSchema>;\n\nexport const BaseParamsSchema = z.looseObject({\n _meta: z.optional(z.object({}).loose()),\n});\ntype BaseParams = z.infer<typeof BaseParamsSchema>;\nexport const ResultSchema = BaseParamsSchema.extend({\n resultType: z.optional(z.string()),\n});\n\nexport const RequestSchema = z.object({\n method: z.string(),\n params: z.optional(BaseParamsSchema),\n});\nexport type Request = z.infer<typeof RequestSchema>;\nexport type RequestOptions = {\n signal?: AbortSignal;\n timeout?: number;\n maxTotalTimeout?: number;\n};\n\nexport type Notification = z.infer<typeof RequestSchema>;\n\n/** @see https://modelcontextprotocol.io/specification/2025-06-18/client/elicitation */\nconst ElicitationCapabilitySchema = z\n .object({\n applyDefaults: z.optional(z.boolean()),\n })\n .loose();\n\nconst ServerCapabilitiesSchema = z.looseObject({\n events: z.looseObject({ listChanged: z.boolean().nullish() }).nullish(),\n experimental: z.optional(z.object({}).loose()),\n logging: z.optional(z.object({}).loose()),\n completions: z.optional(z.object({}).loose()),\n prompts: z.optional(\n z.looseObject({\n listChanged: z.optional(z.boolean()),\n }),\n ),\n resources: z.optional(\n z.looseObject({\n subscribe: z.optional(z.boolean()),\n listChanged: z.optional(z.boolean()),\n }),\n ),\n tools: z.optional(\n z.looseObject({\n listChanged: z.optional(z.boolean()),\n }),\n ),\n elicitation: z.optional(ElicitationCapabilitySchema),\n});\n\nexport type ServerCapabilities = z.infer<typeof ServerCapabilitiesSchema>;\nexport const ClientCapabilitiesSchema = z\n .object({\n elicitation: z.optional(ElicitationCapabilitySchema),\n })\n .loose();\n\nexport type ClientCapabilities = z.infer<typeof ClientCapabilitiesSchema>;\nexport type ElicitationCapability = z.infer<typeof ElicitationCapabilitySchema>;\n\nexport const DiscoverResultSchema = ResultSchema.extend({\n supportedVersions: z.array(z.string()),\n capabilities: ServerCapabilitiesSchema,\n instructions: z.optional(z.string()),\n ttlMs: z.optional(z.number()),\n cacheScope: z.optional(z.union([z.literal('public'), z.literal('private')])),\n});\nexport type DiscoverResult = z.infer<typeof DiscoverResultSchema>;\n\nexport const InitializeResultSchema = ResultSchema.extend({\n protocolVersion: z.string(),\n capabilities: ServerCapabilitiesSchema,\n serverInfo: ClientOrServerImplementationSchema,\n instructions: z.optional(z.string()),\n});\nexport type InitializeResult = z.infer<typeof InitializeResultSchema>;\n\nexport type PaginatedRequest = Request & {\n params?: BaseParams & {\n cursor?: string;\n };\n};\n\nconst PaginatedResultSchema = ResultSchema.extend({\n nextCursor: z.optional(z.string()),\n});\n\nconst ToolSchema = z\n .object({\n name: z.string(),\n /**\n * @see https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool\n */\n title: z.optional(z.string()),\n description: z.optional(z.string()),\n inputSchema: z.looseObject({\n type: z.optional(z.unknown()),\n properties: z.optional(z.object({}).loose()),\n }),\n /**\n * @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema\n */\n outputSchema: z.optional(z.object({}).loose()),\n annotations: z.optional(\n z\n .object({\n title: z.optional(z.string()),\n readOnlyHint: z.optional(z.boolean()),\n destructiveHint: z.optional(z.boolean()),\n idempotentHint: z.optional(z.boolean()),\n openWorldHint: z.optional(z.boolean()),\n })\n .loose(),\n ),\n _meta: ToolMetaSchema,\n })\n .loose();\nexport type MCPTool = z.infer<typeof ToolSchema>;\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema),\n});\nexport type ListToolsResult = z.infer<typeof ListToolsResultSchema>;\n\nconst TextContentSchema = z\n .object({\n type: z.literal('text'),\n text: z.string(),\n })\n .loose();\nconst ImageContentSchema = z\n .object({\n type: z.literal('image'),\n data: z.base64(),\n mimeType: z.string(),\n })\n .loose();\nexport const ResourceSchema = z\n .object({\n uri: z.string(),\n name: z.string(),\n title: z.optional(z.string()),\n description: z.optional(z.string()),\n mimeType: z.optional(z.string()),\n size: z.optional(z.number()),\n })\n .loose();\nexport type MCPResource = z.infer<typeof ResourceSchema>;\n\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema),\n});\nexport type ListResourcesResult = z.infer<typeof ListResourcesResultSchema>;\n\nconst ResourceContentsSchema = z\n .object({\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * Optional display name of the resource content.\n */\n name: z.optional(z.string()),\n /**\n * Optional human readable title.\n */\n title: z.optional(z.string()),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n })\n .loose();\nconst TextResourceContentsSchema = ResourceContentsSchema.extend({\n text: z.string(),\n});\nconst BlobResourceContentsSchema = ResourceContentsSchema.extend({\n blob: z.base64(),\n});\nconst EmbeddedResourceSchema = z\n .object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n })\n .loose();\nconst ResourceLinkContentSchema = z\n .object({\n type: z.literal('resource_link'),\n uri: z.string(),\n name: z.string(),\n description: z.optional(z.string()),\n mimeType: z.optional(z.string()),\n })\n .loose();\nconst UnknownContentSchema = z\n .object({ type: z.string() })\n .loose()\n .refine(\n content =>\n !['text', 'image', 'resource', 'resource_link'].includes(content.type),\n { message: 'Known content types must match their schema' },\n );\n\nconst CallToolResultWithContentSchema = ResultSchema.extend({\n content: z.array(\n z.union([\n TextContentSchema,\n ImageContentSchema,\n EmbeddedResourceSchema,\n ResourceLinkContentSchema,\n UnknownContentSchema,\n ]),\n ),\n /**\n * @see https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content\n */\n structuredContent: z.optional(z.unknown()),\n isError: z.boolean().default(false).optional(),\n});\n\nconst CallToolResultWithStructuredContentSchema = ResultSchema.extend({\n content: z.never().optional(),\n structuredContent: z.json(),\n isError: z.boolean().default(false).optional(),\n})\n .transform(\n (result): z.infer<typeof CallToolResultWithContentSchema> => ({\n ...result,\n content: [\n {\n type: 'text',\n text: JSON.stringify(result.structuredContent),\n },\n ],\n }),\n )\n .pipe(CallToolResultWithContentSchema);\n\nexport const CallToolResultSchema = CallToolResultWithContentSchema.or(\n CallToolResultWithStructuredContentSchema,\n).or(\n ResultSchema.extend({\n toolResult: z.unknown().nonoptional(),\n }),\n);\nexport type CallToolResult = z.infer<typeof CallToolResultSchema>;\n\nconst ResourceTemplateSchema = z\n .object({\n uriTemplate: z.string(),\n name: z.string(),\n title: z.optional(z.string()),\n description: z.optional(z.string()),\n mimeType: z.optional(z.string()),\n })\n .loose();\n\nexport const ListResourceTemplatesResultSchema = ResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema),\n});\nexport type ListResourceTemplatesResult = z.infer<\n typeof ListResourceTemplatesResultSchema\n>;\n\nexport const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(\n z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n ),\n});\nexport type ReadResourceResult = z.infer<typeof ReadResourceResultSchema>;\n\n// Completions\nconst PromptReferenceSchema = z\n .object({\n type: z.literal('ref/prompt'),\n name: z.string(),\n })\n .loose();\n\nconst ResourceReferenceSchema = z\n .object({\n type: z.literal('ref/resource'),\n uri: z.string(),\n })\n .loose();\n\nconst CompletionArgumentSchema = z\n .object({\n name: z.string(),\n value: z.string(),\n })\n .loose();\n\nexport const CompleteRequestParamsSchema = BaseParamsSchema.extend({\n ref: z.union([PromptReferenceSchema, ResourceReferenceSchema]),\n argument: CompletionArgumentSchema,\n context: z.optional(\n z\n .object({\n arguments: z.record(z.string(), z.string()),\n })\n .loose(),\n ),\n});\nexport type CompleteRequestParams = z.infer<typeof CompleteRequestParamsSchema>;\n\nexport const CompleteResultSchema = ResultSchema.extend({\n completion: z\n .object({\n values: z.array(z.string()).max(100),\n total: z.optional(z.number().int()),\n hasMore: z.optional(z.boolean()),\n })\n .loose(),\n});\nexport type CompleteResult = z.infer<typeof CompleteResultSchema>;\n\n// Prompts\nconst PromptArgumentSchema = z\n .object({\n name: z.string(),\n description: z.optional(z.string()),\n required: z.optional(z.boolean()),\n })\n .loose();\n\nexport const PromptSchema = z\n .object({\n name: z.string(),\n title: z.optional(z.string()),\n description: z.optional(z.string()),\n arguments: z.optional(z.array(PromptArgumentSchema)),\n })\n .loose();\nexport type MCPPrompt = z.infer<typeof PromptSchema>;\n\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema),\n});\nexport type ListPromptsResult = z.infer<typeof ListPromptsResultSchema>;\n\nconst PromptMessageSchema = z\n .object({\n role: z.union([z.literal('user'), z.literal('assistant')]),\n content: z.union([\n TextContentSchema,\n ImageContentSchema,\n EmbeddedResourceSchema,\n ResourceLinkContentSchema,\n ]),\n })\n .loose();\nexport type MCPPromptMessage = z.infer<typeof PromptMessageSchema>;\n\nexport const GetPromptResultSchema = ResultSchema.extend({\n description: z.optional(z.string()),\n messages: z.array(PromptMessageSchema),\n});\nexport type GetPromptResult = z.infer<typeof GetPromptResultSchema>;\n\nconst ElicitationRequestParamsSchema = BaseParamsSchema.extend({\n message: z.string(),\n requestedSchema: z.unknown(),\n});\n\nexport const ElicitationRequestSchema = RequestSchema.extend({\n method: z.literal('elicitation/create'),\n params: ElicitationRequestParamsSchema,\n});\n\nexport type ElicitationRequest = z.infer<typeof ElicitationRequestSchema>;\n\nexport const ElicitResultSchema = ResultSchema.extend({\n action: z.union([\n z.literal('accept'),\n z.literal('decline'),\n z.literal('cancel'),\n ]),\n content: z.optional(z.record(z.string(), z.unknown())),\n});\n\nexport type ElicitResult = z.infer<typeof ElicitResultSchema>;\n","import { parseJSON } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { BaseParamsSchema, RequestSchema, ResultSchema } from './types';\n\nconst JSONRPC_VERSION = '2.0';\n\nconst JSONRPCRequestSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: z.union([z.string(), z.number().int()]),\n })\n .merge(RequestSchema)\n .strict();\n\nexport type JSONRPCRequest = z.infer<typeof JSONRPCRequestSchema>;\n\nconst JSONRPCResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: z.union([z.string(), z.number().int()]),\n result: ResultSchema,\n })\n .strict();\n\nexport type JSONRPCResponse = z.infer<typeof JSONRPCResponseSchema>;\n\nconst JSONRPCErrorSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: z.optional(z.union([z.string(), z.number().int()])),\n error: z.object({\n code: z.number().int(),\n message: z.string(),\n data: z.optional(z.unknown()),\n }),\n })\n .strict();\n\nexport type JSONRPCError = z.infer<typeof JSONRPCErrorSchema>;\n\nconst JSONRPCNotificationSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n })\n .merge(\n z.object({\n method: z.string(),\n params: z.optional(BaseParamsSchema),\n }),\n )\n .strict();\n\nexport type JSONRPCNotification = z.infer<typeof JSONRPCNotificationSchema>;\n\nexport const JSONRPCMessageSchema = z.union([\n JSONRPCRequestSchema,\n JSONRPCNotificationSchema,\n JSONRPCResponseSchema,\n JSONRPCErrorSchema,\n]);\n\nexport type JSONRPCMessage = z.infer<typeof JSONRPCMessageSchema>;\n\nexport function validateJSONRPCMessage(message: unknown): JSONRPCMessage {\n return JSONRPCMessageSchema.parse(message);\n}\n\nexport async function parseJSONRPCMessage(\n text: string,\n): Promise<JSONRPCMessage> {\n return validateJSONRPCMessage(await parseJSON({ text }));\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_MCPClientError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * An error occurred with the MCP client.\n */\nexport class MCPClientError extends AISDKError {\n private readonly [symbol] = true;\n readonly data?: unknown;\n\n /**\n * JSON-RPC error code from the server response, per the JSON-RPC 2.0\n * spec (e.g. `-32601` method-not-found, `-32602` invalid-params, or\n * MCP-specific codes such as `-32002` resource-not-found). This is the\n * application-level error code populated from `error.code` in the\n * server's JSON-RPC error payload. Distinct from `statusCode`, which\n * is the HTTP transport status.\n */\n readonly code?: number;\n\n /**\n * HTTP status code from the failed response, when the error originated\n * from an HTTP-based transport. Undefined for stdio transport\n * errors and for failures that do not have an associated response\n * status (e.g. network errors, abort). Distinct from `code`, which is\n * the JSON-RPC application error code.\n */\n readonly statusCode?: number;\n\n /**\n * URL of the MCP endpoint the failing request was sent to, when the\n * error originated from an HTTP transport failure.\n */\n readonly url?: string;\n\n /**\n * Body of the failing HTTP response, decoded as text, when available.\n * Undefined when the body could not be read or the error did not have\n * an associated response.\n */\n readonly responseBody?: string;\n\n constructor({\n name = 'MCPClientError',\n message,\n cause,\n data,\n code,\n statusCode,\n url,\n responseBody,\n }: {\n name?: string;\n message: string;\n cause?: unknown;\n data?: unknown;\n code?: number;\n statusCode?: number;\n url?: string;\n responseBody?: string;\n }) {\n super({ name, message, cause });\n this.data = data;\n this.code = code;\n this.statusCode = statusCode;\n this.url = url;\n this.responseBody = responseBody;\n }\n\n static isInstance(error: unknown): error is MCPClientError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","/**\n * Constructs the environment variables for the child process.\n *\n * @param customEnv - Custom environment variables to merge with default environment variables.\n * @returns The environment variables for the child process.\n */\nexport function getEnvironment(\n customEnv?: Record<string, string>,\n): Record<string, string> {\n const isWindows = globalThis.process.platform === 'win32';\n const DEFAULT_INHERITED_ENV_VARS = isWindows\n ? [\n 'APPDATA',\n 'HOMEDRIVE',\n 'HOMEPATH',\n 'LOCALAPPDATA',\n 'PATH',\n 'PROCESSOR_ARCHITECTURE',\n 'SYSTEMDRIVE',\n 'SYSTEMROOT',\n 'TEMP',\n 'USERNAME',\n 'USERPROFILE',\n ]\n : ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER'];\n\n const env: Record<string, string> = customEnv ? { ...customEnv } : {};\n const customEnvKeys = new Set(\n Object.keys(env).map(key => (isWindows ? key.toUpperCase() : key)),\n );\n\n for (const key of DEFAULT_INHERITED_ENV_VARS) {\n if (customEnvKeys.has(key)) {\n continue;\n }\n\n const value = globalThis.process.env[key];\n if (value === undefined) {\n continue;\n }\n\n if (value.startsWith('()')) {\n continue;\n }\n\n env[key] = value;\n }\n\n return env;\n}\n","import type { ChildProcess } from 'node:child_process';\nimport spawn from 'cross-spawn';\nimport { getEnvironment } from './get-environment';\nimport type { StdioConfig } from './mcp-stdio-transport';\n\nexport function createChildProcess(\n config: StdioConfig,\n signal: AbortSignal,\n): ChildProcess {\n if (\n globalThis.process.platform === 'win32' &&\n [config.command, ...(config.args ?? [])].some(value => /[\\r\\n]/.test(value))\n ) {\n throw new TypeError(\n 'Stdio MCP commands and arguments must not contain line breaks on Windows.',\n );\n }\n\n return spawn(config.command, config.args ?? [], {\n env: getEnvironment(config.env),\n stdio: ['pipe', 'pipe', config.stderr ?? 'inherit'],\n shell: false,\n signal,\n windowsHide: globalThis.process.platform === 'win32' && isElectron(),\n cwd: config.cwd,\n });\n}\n\nfunction isElectron() {\n return 'type' in globalThis.process;\n}\n","import type { ChildProcess, IOType } from 'node:child_process';\nimport type { Stream } from 'node:stream';\nimport { parseJSONRPCMessage, type JSONRPCMessage } from '../json-rpc-message';\nimport type { MCPTransport } from '../mcp-transport';\nimport { MCPClientError } from '../../error/mcp-client-error';\nimport { createChildProcess } from './create-child-process';\n\nexport interface StdioConfig {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n stderr?: IOType | Stream | number;\n cwd?: string;\n}\n\nexport class StdioMCPTransport implements MCPTransport {\n readonly supportsProtocolVersionDiscovery = true;\n private process?: ChildProcess;\n private abortController: AbortController = new AbortController();\n private readBuffer: ReadBuffer = new ReadBuffer();\n private serverParams: StdioConfig;\n\n onclose?: () => void;\n onerror?: (error: unknown) => void;\n onmessage?: (message: JSONRPCMessage) => void;\n\n constructor(server: StdioConfig) {\n this.serverParams = server;\n }\n\n async start(): Promise<void> {\n if (this.process) {\n throw new MCPClientError({\n message: 'StdioMCPTransport already started.',\n });\n }\n\n return new Promise((resolve, reject) => {\n try {\n const process = createChildProcess(\n this.serverParams,\n this.abortController.signal,\n );\n\n this.process = process;\n\n this.process.on('error', error => {\n if (error.name === 'AbortError') {\n this.onclose?.();\n return;\n }\n\n reject(error);\n this.onerror?.(error);\n });\n\n this.process.on('spawn', () => {\n resolve();\n });\n\n this.process.on('close', _code => {\n this.process = undefined;\n this.onclose?.();\n });\n\n this.process.stdin?.on('error', error => {\n this.onerror?.(error);\n });\n\n this.process.stdout?.on('data', chunk => {\n this.readBuffer.append(chunk);\n void this.processReadBuffer();\n });\n\n this.process.stdout?.on('error', error => {\n this.onerror?.(error);\n });\n } catch (error) {\n reject(error);\n this.onerror?.(error);\n }\n });\n }\n\n private async processReadBuffer() {\n while (true) {\n const line = this.readBuffer.readLine();\n if (line === null) {\n break;\n }\n\n try {\n const message = await deserializeMessage(line);\n this.onmessage?.(message);\n } catch (error) {\n this.onerror?.(error as Error);\n }\n }\n }\n\n async close(): Promise<void> {\n this.abortController.abort();\n this.process = undefined;\n this.readBuffer.clear();\n }\n\n send(message: JSONRPCMessage): Promise<void> {\n return new Promise(resolve => {\n if (!this.process?.stdin) {\n throw new MCPClientError({\n message: 'StdioClientTransport not connected',\n });\n }\n\n const json = serializeMessage(message);\n if (this.process.stdin.write(json)) {\n resolve();\n } else {\n this.process.stdin.once('drain', resolve);\n }\n });\n }\n}\n\nclass ReadBuffer {\n private buffer?: Buffer;\n\n append(chunk: Buffer): void {\n this.buffer = this.buffer ? Buffer.concat([this.buffer, chunk]) : chunk;\n }\n\n readLine(): string | null {\n if (!this.buffer) return null;\n\n const index = this.buffer.indexOf('\\n');\n if (index === -1) {\n return null;\n }\n\n const line = this.buffer.toString('utf8', 0, index);\n this.buffer = this.buffer.subarray(index + 1);\n return line;\n }\n\n clear(): void {\n this.buffer = undefined;\n }\n}\n\nfunction serializeMessage(message: JSONRPCMessage): string {\n return JSON.stringify(message) + '\\n';\n}\n\nexport async function deserializeMessage(\n line: string,\n): Promise<JSONRPCMessage> {\n return parseJSONRPCMessage(line);\n}\n"],"mappings":";;;;;;AA0CA,MAAM,iBAAiB,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC;AA6CnE,MAAM,qCAAqC,EAAE,YAAY;CACvD,MAAM,EAAE,OAAO;CACf,SAAS,EAAE,OAAO;CAClB,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC;AAC9B,CAAC;AAKD,MAAa,mBAAmB,EAAE,YAAY,EAC5C,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EACxC,CAAC;AAED,MAAa,eAAe,iBAAiB,OAAO,EAClD,YAAY,EAAE,SAAS,EAAE,OAAO,CAAC,EACnC,CAAC;AAED,MAAa,gBAAgB,EAAE,OAAO;CACp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AAC;CACH;AACF;AAEA,IAAM,aAAN,MAAiB;CAGf,OAAO,OAAqB;EAC1B,KAAK,SAAS,KAAK,SAAS,OAAO,OAAO,CAAC,KAAK,QAAQ,KAAK,CAAC,IAAI;CACpE;CAEA,WAA0B;EACxB,IAAI,CAAC,KAAK,QAAQ,OAAO;EAEzB,MAAM,QAAQ,KAAK,OAAO,QAAQ,IAAI;EACtC,IAAI,UAAU,IACZ,OAAO;EAGT,MAAM,OAAO,KAAK,OAAO,SAAS,QAAQ,GAAG,KAAK;EAClD,KAAK,SAAS,KAAK,OAAO,SAAS,QAAQ,CAAC;EAC5C,OAAO;CACT;CAEA,QAAc;EACZ,KAAK,SAAS,KAAA;CAChB;AACF;AAEA,SAAS,iBAAiB,SAAiC;CACzD,OAAO,KAAK,UAAU,OAAO,IAAI;AACnC;AAEA,eAAsB,mBACpB,MACyB;CACzB,OAAO,oBAAoB,IAAI;AACjC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/mcp",
3
- "version": "2.0.72",
3
+ "version": "2.0.74",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -31,8 +31,8 @@
31
31
  }
32
32
  },
33
33
  "dependencies": {
34
- "@ai-sdk/provider": "4.0.26",
35
- "@ai-sdk/provider-utils": "5.0.58",
34
+ "@ai-sdk/provider": "4.0.27",
35
+ "@ai-sdk/provider-utils": "5.0.59",
36
36
  "cross-spawn": "^7.0.6",
37
37
  "pkce-challenge": "^5.0.1"
38
38
  },
package/src/index.ts CHANGED
@@ -48,7 +48,8 @@ export {
48
48
  export { MCPClientError } from './error/mcp-client-error';
49
49
  export type { ManagedMCPClient as Experimental_ManagedMCPClient } from './tool/mcp-client';
50
50
  export type {
51
- MCPEventsAdapter as Experimental_MCPEventsAdapter,
51
+ MCPEventOperations as Experimental_MCPEventOperations,
52
+ MCPEventAdapter as Experimental_MCPEventAdapter,
52
53
  ManagedSubscribeInput as Experimental_ManagedSubscribeInput,
53
54
  ManagedSubscription as Experimental_ManagedSubscription,
54
55
  ManagedMCPEvents as Experimental_ManagedMCPEvents,
@@ -16,8 +16,9 @@ import type { z } from 'zod/v4';
16
16
  import { createMCPEvents } from './mcp-events';
17
17
  import {
18
18
  createManagedMCPEvents,
19
+ validateMCPEventOperations,
19
20
  type ManagedMCPEvents,
20
- type MCPEventsAdapter,
21
+ type MCPEventAdapter,
21
22
  } from './mcp-events-adapter';
22
23
  import type { MCPEvents, MCPEventsConfig } from './mcp-event-types';
23
24
  import { MCPClientError } from '../error/mcp-client-error';
@@ -301,7 +302,9 @@ export type ManagedMCPClient = Omit<MCPClient, 'experimental_events'> & {
301
302
 
302
303
  export function createMCPClient(
303
304
  config: MCPClientConfig & {
304
- experimental_events: { adapter: MCPEventsAdapter };
305
+ experimental_events: {
306
+ adapter: MCPEventAdapter;
307
+ };
305
308
  },
306
309
  ): Promise<ManagedMCPClient>;
307
310
  export function createMCPClient(
@@ -486,6 +489,24 @@ class DefaultMCPClient implements Omit<MCPClient, 'experimental_events'> {
486
489
  'Configure experimental_events with either an adapter or a store, not both. Managed adapters own argument validation.',
487
490
  });
488
491
  }
492
+ if (
493
+ events?.adapter !== undefined &&
494
+ typeof events.adapter?.createAdapter !== 'function'
495
+ ) {
496
+ throw new MCPClientError({
497
+ message:
498
+ 'experimental_events.adapter must implement createAdapter. Wrap bound operations with { createAdapter: () => operations }.',
499
+ });
500
+ }
501
+ const operations = events?.adapter?.createAdapter({
502
+ transport: isCustomMcpTransport(transportConfig)
503
+ ? { type: 'custom' }
504
+ : { type: transportConfig.type, url: transportConfig.url },
505
+ });
506
+ if (events?.adapter !== undefined) {
507
+ validateMCPEventOperations(operations);
508
+ }
509
+
489
510
  this.onUncaughtError = onUncaughtError;
490
511
  this.maxRetries = prepareMaxRetries(maxRetries);
491
512
  this.clientCapabilities = capabilities ?? {};
@@ -527,8 +548,8 @@ class DefaultMCPClient implements Omit<MCPClient, 'experimental_events'> {
527
548
  store: events?.store,
528
549
  validateArguments: events?.validateArguments,
529
550
  });
530
- this.experimental_events = events?.adapter
531
- ? createManagedMCPEvents(events.adapter, directEvents.list)
551
+ this.experimental_events = operations
552
+ ? createManagedMCPEvents(operations, directEvents.list)
532
553
  : directEvents;
533
554
  }
534
555
 
@@ -1281,7 +1302,7 @@ class DefaultMCPClient implements Omit<MCPClient, 'experimental_events'> {
1281
1302
 
1282
1303
  const execute = async (
1283
1304
  args: any,
1284
- options: ToolExecutionOptions<{}>,
1305
+ options?: ToolExecutionOptions<{}>,
1285
1306
  ): Promise<unknown> => {
1286
1307
  options?.abortSignal?.throwIfAborted();
1287
1308
  const result = await self.callTool({
@@ -1,5 +1,5 @@
1
1
  import type { JSONObject } from '@ai-sdk/provider';
2
- import type { MCPEventsAdapter } from './mcp-events-adapter';
2
+ import type { MCPEventAdapter } from './mcp-events-adapter';
3
3
  import { z } from 'zod/v4';
4
4
  import { ResultSchema, type RequestOptions } from './types';
5
5
 
@@ -112,7 +112,7 @@ export type MCPEventsConfig =
112
112
  }) => void | PromiseLike<void>;
113
113
  }
114
114
  | {
115
- adapter: MCPEventsAdapter;
115
+ adapter: MCPEventAdapter;
116
116
  store?: never;
117
117
  validateArguments?: never;
118
118
  };
@@ -1,4 +1,5 @@
1
1
  import type { JSONObject } from '@ai-sdk/provider';
2
+ import { MCPClientError } from '../error/mcp-client-error';
2
3
  import type { MCPEvents } from './mcp-event-types';
3
4
  import type { RequestOptions } from './types';
4
5
 
@@ -39,7 +40,7 @@ export type ManagedSubscribeInput = {
39
40
  * Implementations must honor request options and preserve actionable errors.
40
41
  * Cancelling a request does not cancel an already accepted remote subscription.
41
42
  */
42
- export interface MCPEventsAdapter {
43
+ export interface MCPEventOperations {
43
44
  subscribe(input: ManagedSubscribeInput): Promise<ManagedSubscription>;
44
45
 
45
46
  getSubscription(input: {
@@ -63,20 +64,69 @@ export interface MCPEventsAdapter {
63
64
  }): Promise<ManagedSubscription>;
64
65
  }
65
66
 
67
+ /**
68
+ * Creates bound subscription operations once per client, before the transport starts.
69
+ * Receives transport metadata, not credentials or a live transport instance.
70
+ * HTTP/SSE URLs are the configured endpoints, not resolved redirect targets.
71
+ * Custom transports have no standard URL and receive only their type.
72
+ */
73
+ export interface MCPEventAdapter {
74
+ createAdapter(context: {
75
+ transport: { type: 'http' | 'sse'; url: string } | { type: 'custom' };
76
+ }): MCPEventOperations;
77
+ }
78
+
79
+ /** Validate JavaScript integrations before opening the MCP transport. */
80
+ export function validateMCPEventOperations(
81
+ operations: unknown,
82
+ ): asserts operations is MCPEventOperations {
83
+ if (
84
+ operations != null &&
85
+ (typeof operations === 'object' || typeof operations === 'function') &&
86
+ 'then' in operations &&
87
+ typeof operations.then === 'function'
88
+ ) {
89
+ // Consume a rejected async factory result so the configuration error does
90
+ // not also cause an unhandled rejection. Async factories are not supported.
91
+ void Promise.resolve(operations).catch(() => {});
92
+ throw new MCPClientError({
93
+ message:
94
+ 'experimental_events.adapter.createAdapter() must return operations synchronously. Promise and thenable results are not supported.',
95
+ });
96
+ }
97
+ if (
98
+ typeof operations !== 'object' ||
99
+ operations === null ||
100
+ !('subscribe' in operations) ||
101
+ typeof operations.subscribe !== 'function' ||
102
+ !('getSubscription' in operations) ||
103
+ typeof operations.getSubscription !== 'function' ||
104
+ !('listSubscriptions' in operations) ||
105
+ typeof operations.listSubscriptions !== 'function' ||
106
+ !('unsubscribe' in operations) ||
107
+ typeof operations.unsubscribe !== 'function'
108
+ ) {
109
+ throw new MCPClientError({
110
+ message:
111
+ 'experimental_events.adapter.createAdapter() must return an object implementing subscribe, getSubscription, listSubscriptions, and unsubscribe.',
112
+ });
113
+ }
114
+ }
115
+
66
116
  /** Catalog discovery uses MCP; all subscription operations use the adapter. */
67
- export interface ManagedMCPEvents extends MCPEventsAdapter {
117
+ export interface ManagedMCPEvents extends MCPEventOperations {
68
118
  list: MCPEvents['list'];
69
119
  }
70
120
 
71
121
  export function createManagedMCPEvents(
72
- adapter: MCPEventsAdapter,
122
+ operations: MCPEventOperations,
73
123
  list: MCPEvents['list'],
74
124
  ): ManagedMCPEvents {
75
125
  return {
76
126
  list,
77
- subscribe: input => adapter.subscribe(input),
78
- getSubscription: input => adapter.getSubscription(input),
79
- listSubscriptions: input => adapter.listSubscriptions(input),
80
- unsubscribe: input => adapter.unsubscribe(input),
127
+ subscribe: input => operations.subscribe(input),
128
+ getSubscription: input => operations.getSubscription(input),
129
+ listSubscriptions: input => operations.listSubscriptions(input),
130
+ unsubscribe: input => operations.unsubscribe(input),
81
131
  };
82
132
  }
package/src/tool/types.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import { z } from 'zod/v4';
2
2
  import type { JSONObject } from '@ai-sdk/provider';
3
- import type { FlexibleSchema, Tool } from '@ai-sdk/provider-utils';
3
+ import type {
4
+ FlexibleSchema,
5
+ Tool,
6
+ ToolExecutionOptions,
7
+ } from '@ai-sdk/provider-utils';
4
8
 
5
9
  export const LATEST_PROTOCOL_VERSION = '2026-07-28';
6
10
  export const LATEST_LEGACY_PROTOCOL_VERSION = '2025-11-25';
@@ -54,10 +58,13 @@ export type ToolSchemas =
54
58
  type McpToolBase<INPUT = unknown, OUTPUT = CallToolResult> = Tool<
55
59
  INPUT,
56
60
  OUTPUT
57
- > &
58
- Required<Pick<Tool<INPUT, OUTPUT>, 'execute'>> & {
59
- _meta?: ToolMeta;
60
- };
61
+ > & {
62
+ execute: (
63
+ input: INPUT,
64
+ options?: ToolExecutionOptions<{}>,
65
+ ) => ReturnType<NonNullable<Tool<INPUT, OUTPUT>['execute']>>;
66
+ _meta?: ToolMeta;
67
+ };
61
68
 
62
69
  export type McpToolSet<TOOL_SCHEMAS extends ToolSchemas = 'automatic'> =
63
70
  TOOL_SCHEMAS extends Record<