@ai-sdk/mcp 2.0.69 → 2.0.71

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.
@@ -19,6 +19,7 @@ const RequestSchema = z.object({
19
19
  /** @see https://modelcontextprotocol.io/specification/2025-06-18/client/elicitation */
20
20
  const ElicitationCapabilitySchema = z.object({ applyDefaults: z.optional(z.boolean()) }).loose();
21
21
  const ServerCapabilitiesSchema = z.looseObject({
22
+ events: z.looseObject({ listChanged: z.boolean().nullish() }).nullish(),
22
23
  experimental: z.optional(z.object({}).loose()),
23
24
  logging: z.optional(z.object({}).loose()),
24
25
  completions: z.optional(z.object({}).loose()),
@@ -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 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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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"}
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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AAK,QAAQ,MAAM,MAAM,IAAI,GAC/B,QAAQ;QAER,KAAK,QAAQ,MAAM,KAAK,SAAS,OAAO;EAE5C,CAAC;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.69",
3
+ "version": "2.0.71",
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.24",
35
- "@ai-sdk/provider-utils": "5.0.56",
34
+ "@ai-sdk/provider": "4.0.25",
35
+ "@ai-sdk/provider-utils": "5.0.57",
36
36
  "cross-spawn": "^7.0.6",
37
37
  "pkce-challenge": "^5.0.1"
38
38
  },
package/src/index.ts CHANGED
@@ -46,6 +46,30 @@ export {
46
46
  AuthorizationServerMismatchError,
47
47
  } from './error/oauth-error';
48
48
  export { MCPClientError } from './error/mcp-client-error';
49
+ export type { ManagedMCPClient as Experimental_ManagedMCPClient } from './tool/mcp-client';
50
+ export type {
51
+ MCPEventsAdapter as Experimental_MCPEventsAdapter,
52
+ ManagedSubscribeInput as Experimental_ManagedSubscribeInput,
53
+ ManagedSubscription as Experimental_ManagedSubscription,
54
+ ManagedMCPEvents as Experimental_ManagedMCPEvents,
55
+ } from './tool/mcp-events-adapter';
56
+ export {
57
+ createMCPEventWebhook as experimental_createMCPEventWebhook,
58
+ type MCPEventWebhookOptions as Experimental_MCPEventWebhookOptions,
59
+ } from './tool/mcp-event-webhook';
60
+ export type {
61
+ MCPEvent as Experimental_MCPEvent,
62
+ MCPEventControl as Experimental_MCPEventControl,
63
+ MCPEventDefinition as Experimental_MCPEventDefinition,
64
+ MCPEventStore as Experimental_MCPEventStore,
65
+ MCPEventSubscription as Experimental_MCPEventSubscription,
66
+ MCPEventSubscriptionInfo as Experimental_MCPEventSubscriptionInfo,
67
+ MCPEvents as Experimental_MCPEvents,
68
+ MCPEventsConfig as Experimental_MCPEventsConfig,
69
+ ListEventsResult as Experimental_ListEventsResult,
70
+ SubscribeEventOptions as Experimental_SubscribeEventOptions,
71
+ SubscribeEventResult as Experimental_SubscribeEventResult,
72
+ } from './tool/mcp-event-types';
49
73
  export type {
50
74
  OAuthAuthorizationServerInformation,
51
75
  OAuthClientProvider,
@@ -13,6 +13,13 @@ import {
13
13
  type ToolResultOutput,
14
14
  } from '@ai-sdk/provider-utils';
15
15
  import type { z } from 'zod/v4';
16
+ import { createMCPEvents } from './mcp-events';
17
+ import {
18
+ createManagedMCPEvents,
19
+ type ManagedMCPEvents,
20
+ type MCPEventsAdapter,
21
+ } from './mcp-events-adapter';
22
+ import type { MCPEvents, MCPEventsConfig } from './mcp-event-types';
16
23
  import { MCPClientError } from '../error/mcp-client-error';
17
24
  import type {
18
25
  JSONRPCError,
@@ -235,6 +242,8 @@ function mcpToModelOutput({
235
242
  }
236
243
 
237
244
  export interface MCPClientConfig {
245
+ /** Experimental events: choose a private durable store or a managed adapter. */
246
+ experimental_events?: MCPEventsConfig;
238
247
  /** Transport configuration for connecting to the MCP server */
239
248
  transport: MCPTransportConfig | MCPTransport;
240
249
  /**
@@ -286,15 +295,36 @@ export interface MCPClientConfig {
286
295
  capabilities?: ClientCapabilities;
287
296
  }
288
297
 
289
- export async function createMCPClient(
298
+ export type ManagedMCPClient = Omit<MCPClient, 'experimental_events'> & {
299
+ readonly experimental_events: ManagedMCPEvents;
300
+ };
301
+
302
+ export function createMCPClient(
303
+ config: MCPClientConfig & {
304
+ experimental_events: { adapter: MCPEventsAdapter };
305
+ },
306
+ ): Promise<ManagedMCPClient>;
307
+ export function createMCPClient(
308
+ config: MCPClientConfig & {
309
+ experimental_events?: { adapter?: never };
310
+ },
311
+ ): Promise<MCPClient>;
312
+ export function createMCPClient(
290
313
  config: MCPClientConfig,
291
- ): Promise<MCPClient> {
314
+ ): Promise<MCPClient | ManagedMCPClient>;
315
+ export async function createMCPClient(config: MCPClientConfig): Promise<
316
+ Omit<MCPClient, 'experimental_events'> & {
317
+ readonly experimental_events: MCPEvents | ManagedMCPEvents;
318
+ }
319
+ > {
292
320
  const client = new DefaultMCPClient(config);
293
321
  await client.init();
294
322
  return client;
295
323
  }
296
324
 
297
325
  export interface MCPClient {
326
+ /** Experimental event discovery and webhook subscription lifecycle. */
327
+ readonly experimental_events: MCPEvents;
298
328
  /**
299
329
  * Information about the connected MCP server, as reported during initialization.
300
330
  * @see https://modelcontextprotocol.io/specification/2025-11-25/schema#implementation
@@ -399,11 +429,12 @@ export interface MCPClient {
399
429
  * This client is meant to be used to communicate with a single server. To communicate and fetch tools across multiple servers, it's recommended to create a new client instance per server.
400
430
  *
401
431
  * Not supported:
402
- * - Accepting notifications
432
+ * - Accepting in-band notifications (webhook events use a separate HTTP handler)
403
433
  * - Automatic session persistence for Streamable HTTP transport
404
434
  * - Resumable SSE streams
405
435
  */
406
- class DefaultMCPClient implements MCPClient {
436
+ class DefaultMCPClient implements Omit<MCPClient, 'experimental_events'> {
437
+ readonly experimental_events: MCPEvents | ManagedMCPEvents;
407
438
  private transport: MCPTransport;
408
439
  private protocolVersionDiscovery: boolean;
409
440
  private onUncaughtError?: (error: unknown) => void;
@@ -434,6 +465,7 @@ class DefaultMCPClient implements MCPClient {
434
465
  ) => Promise<ElicitResult> | ElicitResult;
435
466
 
436
467
  constructor({
468
+ experimental_events: events,
437
469
  transport: transportConfig,
438
470
  name,
439
471
  clientName = name ?? 'ai-sdk-mcp-client',
@@ -445,6 +477,15 @@ class DefaultMCPClient implements MCPClient {
445
477
  initializationOptions,
446
478
  protocolVersionDiscovery = true,
447
479
  }: MCPClientConfig) {
480
+ if (
481
+ events?.adapter !== undefined &&
482
+ (events.store !== undefined || events.validateArguments !== undefined)
483
+ ) {
484
+ throw new MCPClientError({
485
+ message:
486
+ 'Configure experimental_events with either an adapter or a store, not both. Managed adapters own argument validation.',
487
+ });
488
+ }
448
489
  this.onUncaughtError = onUncaughtError;
449
490
  this.maxRetries = prepareMaxRetries(maxRetries);
450
491
  this.clientCapabilities = capabilities ?? {};
@@ -481,6 +522,14 @@ class DefaultMCPClient implements MCPClient {
481
522
  name: clientName,
482
523
  version,
483
524
  };
525
+ const directEvents = createMCPEvents({
526
+ request: args => this.request(args),
527
+ store: events?.store,
528
+ validateArguments: events?.validateArguments,
529
+ });
530
+ this.experimental_events = events?.adapter
531
+ ? createManagedMCPEvents(events.adapter, directEvents.list)
532
+ : directEvents;
484
533
  }
485
534
 
486
535
  get serverInfo(): Configuration {
@@ -714,6 +763,15 @@ class DefaultMCPClient implements MCPClient {
714
763
  });
715
764
  }
716
765
  break;
766
+ case 'events/list':
767
+ case 'events/subscribe':
768
+ case 'events/unsubscribe':
769
+ if (!this.serverCapabilities.events) {
770
+ throw new MCPClientError({
771
+ message: 'Server does not support events',
772
+ });
773
+ }
774
+ break;
717
775
  case 'tools/list':
718
776
  case 'tools/call':
719
777
  if (!this.serverCapabilities.tools) {
@@ -0,0 +1,79 @@
1
+ import {
2
+ convertBase64ToUint8Array,
3
+ convertUint8ArrayToBase64,
4
+ } from '@ai-sdk/provider-utils';
5
+ import { MCPClientError } from '../error/mcp-client-error';
6
+
7
+ export function createMCPEventSecret(): string {
8
+ return `whsec_${convertUint8ArrayToBase64(crypto.getRandomValues(new Uint8Array(32)))}`;
9
+ }
10
+
11
+ export function decodeMCPEventSecret(secret: string): Uint8Array {
12
+ const encoded = secret.slice(6);
13
+ if (!secret.startsWith('whsec_') || !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) {
14
+ throw new MCPClientError({ message: 'Invalid MCP event signing secret' });
15
+ }
16
+ const bytes = convertBase64ToUint8Array(encoded);
17
+ if (bytes.length < 24 || bytes.length > 64) {
18
+ throw new MCPClientError({
19
+ message: 'MCP event signing secrets must contain 24–64 random bytes',
20
+ });
21
+ }
22
+ return bytes;
23
+ }
24
+
25
+ /** Standard Webhooks v1: authenticate the exact body bytes using Web Crypto. */
26
+ export async function verifyMCPEventSignature({
27
+ headers,
28
+ body,
29
+ secret,
30
+ }: {
31
+ headers: Headers;
32
+ body: Uint8Array;
33
+ secret: string;
34
+ }): Promise<boolean> {
35
+ const id = headers.get('webhook-id');
36
+ const timestamp = headers.get('webhook-timestamp');
37
+ const signatures = headers.get('webhook-signature');
38
+ if (
39
+ !id ||
40
+ !timestamp ||
41
+ !signatures ||
42
+ !/^\d+$/.test(timestamp) ||
43
+ Math.abs(Date.now() / 1000 - Number(timestamp)) > 300
44
+ ) {
45
+ return false;
46
+ }
47
+
48
+ const key = await crypto.subtle.importKey(
49
+ 'raw',
50
+ new Uint8Array(decodeMCPEventSecret(secret)),
51
+ { name: 'HMAC', hash: 'SHA-256' },
52
+ false,
53
+ ['verify'],
54
+ );
55
+ const prefix = new TextEncoder().encode(`${id}.${timestamp}.`);
56
+ const message = new Uint8Array(prefix.length + body.length);
57
+ message.set(prefix);
58
+ message.set(body, prefix.length);
59
+
60
+ for (const signature of signatures.split(' ')) {
61
+ const [version, value] = signature.split(',');
62
+ if (version !== 'v1' || !value) continue;
63
+ try {
64
+ if (
65
+ await crypto.subtle.verify(
66
+ 'HMAC',
67
+ key,
68
+ new Uint8Array(convertBase64ToUint8Array(value)),
69
+ message,
70
+ )
71
+ ) {
72
+ return true;
73
+ }
74
+ } catch {
75
+ // A malformed signature must not hide another valid rotation signature.
76
+ }
77
+ }
78
+ return false;
79
+ }
@@ -0,0 +1,151 @@
1
+ import type { JSONObject } from '@ai-sdk/provider';
2
+ import type { MCPEventsAdapter } from './mcp-events-adapter';
3
+ import { z } from 'zod/v4';
4
+ import { ResultSchema, type RequestOptions } from './types';
5
+
6
+ const JsonSchemaSchema = z.union([
7
+ z.boolean(),
8
+ z.record(z.string(), z.unknown()),
9
+ ]);
10
+
11
+ export const MCPEventDefinitionSchema = z.looseObject({
12
+ name: z.string().min(1),
13
+ description: z.string().nullish(),
14
+ delivery: z.array(z.enum(['webhook', 'poll', 'push'])).min(1),
15
+ inputSchema: JsonSchemaSchema,
16
+ payloadSchema: JsonSchemaSchema,
17
+ });
18
+ export type MCPEventDefinition = z.infer<typeof MCPEventDefinitionSchema>;
19
+
20
+ export const ListEventsResultSchema = ResultSchema.extend({
21
+ events: z.array(MCPEventDefinitionSchema),
22
+ nextCursor: z.string().nullish(),
23
+ });
24
+ export type ListEventsResult = z.infer<typeof ListEventsResultSchema>;
25
+
26
+ export const SubscribeEventResultSchema = ResultSchema.extend({
27
+ id: z.string().min(1),
28
+ refreshBefore: z.iso.datetime({ offset: true }).nullable(),
29
+ cursor: z
30
+ .string()
31
+ .nullish()
32
+ .transform(cursor => cursor ?? null),
33
+ truncated: z.boolean(),
34
+ });
35
+ export type SubscribeEventResult = z.infer<typeof SubscribeEventResultSchema>;
36
+
37
+ export const MCPEventSchema = z.looseObject({
38
+ eventId: z.string().min(1),
39
+ name: z.string().min(1),
40
+ timestamp: z.iso.datetime({ offset: true }),
41
+ data: z.record(z.string(), z.unknown()),
42
+ cursor: z.string().nullish(),
43
+ });
44
+ export type MCPEvent = z.infer<typeof MCPEventSchema>;
45
+
46
+ export const MCPEventControlSchema = z
47
+ .discriminatedUnion('type', [
48
+ z.looseObject({ type: z.literal('gap'), cursor: z.string() }),
49
+ z.looseObject({
50
+ type: z.literal('terminated'),
51
+ error: z.looseObject({
52
+ code: z.number().int(),
53
+ message: z.string(),
54
+ data: z.unknown().nullish(),
55
+ }),
56
+ }),
57
+ ])
58
+ .transform(control =>
59
+ control.type === 'gap' ? { ...control, truncated: true as const } : control,
60
+ );
61
+ export type MCPEventControl = z.infer<typeof MCPEventControlSchema>;
62
+
63
+ /** Persisted privately by the application, including the signing secret. */
64
+ export type MCPEventSubscription = {
65
+ key: string;
66
+ id?: string;
67
+ name: string;
68
+ arguments: JSONObject;
69
+ definition: MCPEventDefinition;
70
+ delivery: { mode: 'webhook'; url: string; secret: string };
71
+ refreshBefore?: string | null;
72
+ cursor: string | null;
73
+ truncated: boolean;
74
+ ttlMs?: number | null;
75
+ maxAgeMs?: number;
76
+ status: 'pending' | 'active';
77
+ };
78
+
79
+ /** Subscription metadata safe to pass to event handlers; excludes the secret. */
80
+ export type MCPEventSubscriptionInfo = {
81
+ id: string;
82
+ name: string;
83
+ arguments: JSONObject;
84
+ delivery: { mode: 'webhook'; url: string };
85
+ refreshBefore: string | null;
86
+ };
87
+
88
+ /**
89
+ * Use durable, private storage scoped to one MCP server and authenticated
90
+ * principal. update must atomically merge only the supplied fields. Never
91
+ * expose these records to a browser: delivery.secret authenticates webhooks.
92
+ */
93
+ export interface MCPEventStore {
94
+ get(key: string): Promise<MCPEventSubscription | undefined>;
95
+ getById(id: string): Promise<MCPEventSubscription | undefined>;
96
+ set(subscription: MCPEventSubscription): Promise<void>;
97
+ update(key: string, patch: Partial<MCPEventSubscription>): Promise<void>;
98
+ delete(key: string): Promise<void>;
99
+ }
100
+
101
+ export type MCPEventsConfig =
102
+ | {
103
+ store: MCPEventStore;
104
+ adapter?: never;
105
+ /**
106
+ * Optionally validate subscription arguments using an application schema or
107
+ * the server's inputSchema. Throw to reject before persisting or subscribing.
108
+ */
109
+ validateArguments?: (args: {
110
+ definition: MCPEventDefinition;
111
+ arguments: JSONObject;
112
+ }) => void | PromiseLike<void>;
113
+ }
114
+ | {
115
+ adapter: MCPEventsAdapter;
116
+ store?: never;
117
+ validateArguments?: never;
118
+ };
119
+
120
+ export type SubscribeEventOptions = {
121
+ name: string;
122
+ arguments?: JSONObject;
123
+ delivery: {
124
+ mode: 'webhook';
125
+ /** HTTPS callback served by createMCPEventWebhook before subscribing. */
126
+ url: string;
127
+ /** Development only: allow HTTP callbacks to literal loopback addresses. */
128
+ allowInsecureLocalhost?: boolean;
129
+ /** Generated securely when omitted; persisted before the subscribe request. */
130
+ secret?: string;
131
+ };
132
+ cursor?: string | null;
133
+ ttlMs?: number | null;
134
+ maxAgeMs?: number;
135
+ options?: RequestOptions;
136
+ };
137
+
138
+ type MCPEventSubscriptionOptions = (
139
+ | { id: string; key?: never }
140
+ | { key: string; id?: never }
141
+ ) & { options?: RequestOptions };
142
+
143
+ export interface MCPEvents {
144
+ list(options?: {
145
+ params?: { cursor?: string };
146
+ options?: RequestOptions;
147
+ }): Promise<ListEventsResult>;
148
+ subscribe(options: SubscribeEventOptions): Promise<SubscribeEventResult>;
149
+ refresh(options: MCPEventSubscriptionOptions): Promise<SubscribeEventResult>;
150
+ unsubscribe(options: MCPEventSubscriptionOptions): Promise<void>;
151
+ }