@ai-sdk/mcp 2.0.78 → 2.0.80

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.
@@ -125,6 +125,7 @@ interface StdioConfig {
125
125
  env?: Record<string, string>;
126
126
  stderr?: IOType | Stream | number;
127
127
  cwd?: string;
128
+ shell?: boolean | string;
128
129
  }
129
130
  declare class StdioMCPTransport implements MCPTransport {
130
131
  readonly supportsProtocolVersionDiscovery = true;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/tool/json-rpc-message.ts","../../src/tool/mcp-transport.ts","../../src/tool/mcp-stdio/mcp-stdio-transport.ts"],"mappings":";;;;;;cAsDa,sBAAoB,EAAA,mBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAK/B,EAAA,KAAA;KAEU,iBAAiB,EAAE,aAAa;;;;;;;KCjDhC;;;;EAIV,SAAS;;;;EAKT,UAAU;;;;EAKV;;;;EAKA;;;;EAKA,qBAAqB;;KAGX;;;;EAIV,SAAS;;UAGM;;;;;;;EAOf;;;;;EAMA;;;;EAKA,SAAS;;;;;;EAOT,KACE,SAAS,gBACT,UAAU,0BACT;;;;;EAMH,MAAM,UAAU,2BAA2B;;;;EAK3C;;;;EAKA,WAAW,OAAO;;;;EAKlB,aAAa,SAAS;;;;EAKtB;;;;EAKA,oBAAoB;;;;UClGL;EACf;EACA;EACA,MAAM;EACN,SAAS,SAAS;EAClB;;cAGW,6BAA6B;WAC/B;UACD;UACA;UACA;UACA;EAER;EACA,WAAW;EACX,aAAa,SAAS;EAEV,YAAA,QAAQ;EAId,SAAS;UAsDD;EAgBR,SAAS;EAMf,KAAK,SAAS,iBAAiB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/tool/json-rpc-message.ts","../../src/tool/mcp-transport.ts","../../src/tool/mcp-stdio/mcp-stdio-transport.ts"],"mappings":";;;;;;cAsDa,sBAAoB,EAAA,mBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAK/B,EAAA,KAAA;KAEU,iBAAiB,EAAE,aAAa;;;;;;;KCjDhC;;;;EAIV,SAAS;;;;EAKT,UAAU;;;;EAKV;;;;EAKA;;;;EAKA,qBAAqB;;KAGX;;;;EAIV,SAAS;;UAGM;;;;;;;EAOf;;;;;EAMA;;;;EAKA,SAAS;;;;;;EAOT,KACE,SAAS,gBACT,UAAU,0BACT;;;;;EAMH,MAAM,UAAU,2BAA2B;;;;EAK3C;;;;EAKA,WAAW,OAAO;;;;EAKlB,aAAa,SAAS;;;;EAKtB;;;;EAKA,oBAAoB;;;;UClGL;EACf;EACA;EACA,MAAM;EACN,SAAS,SAAS;EAClB;EACA;;cAGW,6BAA6B;WAC/B;UACD;UACA;UACA;UACA;EAER;EACA,WAAW;EACX,aAAa,SAAS;EAEV,YAAA,QAAQ;EAId,SAAS;UAsDD;EAgBR,SAAS;EAMf,KAAK,SAAS,iBAAiB"}
@@ -338,7 +338,7 @@ function createChildProcess(config, signal) {
338
338
  "pipe",
339
339
  config.stderr ?? "inherit"
340
340
  ],
341
- shell: false,
341
+ shell: config.shell ?? false,
342
342
  signal,
343
343
  windowsHide: globalThis.process.platform === "win32" && isElectron(),
344
344
  cwd: config.cwd
@@ -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 {\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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UAAU,MAAM,mBAAmB,IAAI;IAC7C,KAAK,YAAY,OAAO;GAC1B,SAAS,OAAO;IACd,KAAK,UAAU,KAAc;GAC/B;EACF;CACF;CAEA,MAAM,QAAuB;EAC3B,KAAK,gBAAgB,MAAM;EAC3B,KAAK,UAAU,KAAA;EACf,KAAK,WAAW,MAAM;CACxB;CAEA,KAAK,SAAwC;EAC3C,OAAO,IAAI,SAAQ,YAAW;GAC5B,IAAI,CAAC,KAAK,SAAS,OACjB,MAAM,IAAI,eAAe,EACvB,SAAS,qCACX,CAAC;GAGH,MAAM,OAAO,iBAAiB,OAAO;GACrC,IAAI,KAAK,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"}
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: config.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 shell?: boolean | 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;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,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,QAAQ;CACtE,cAAc,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;CAC7C,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;CACxC,aAAa,EA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,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.78",
3
+ "version": "2.0.80",
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.29",
35
- "@ai-sdk/provider-utils": "5.0.62",
34
+ "@ai-sdk/provider": "4.0.31",
35
+ "@ai-sdk/provider-utils": "5.0.64",
36
36
  "cross-spawn": "^7.0.6",
37
37
  "pkce-challenge": "^5.0.1"
38
38
  },
@@ -41,6 +41,7 @@
41
41
  "@types/cross-spawn": "^6.0.6",
42
42
  "@types/node": "22.19.19",
43
43
  "@vercel/ai-tsconfig": "0.0.0",
44
+ "@vercel/ai-tsdown-config": "0.0.0",
44
45
  "tsdown": "^0.23.0",
45
46
  "typescript": "6.0.3",
46
47
  "vitest": "^4.1.11",
@@ -164,7 +164,8 @@ export class SseMCPTransport implements MCPTransport {
164
164
  }
165
165
 
166
166
  if (!response.ok || !response.body) {
167
- let errorMessage = `MCP SSE Transport Error: ${response.status} ${response.statusText}`;
167
+ const text = await response.text().catch(() => null);
168
+ let errorMessage = `MCP SSE Transport Error: ${response.status} ${response.statusText}${text ? `: ${text}` : ''}`;
168
169
 
169
170
  if (response.status === 405) {
170
171
  errorMessage +=
@@ -173,6 +174,9 @@ export class SseMCPTransport implements MCPTransport {
173
174
 
174
175
  const error = new MCPClientError({
175
176
  message: errorMessage,
177
+ statusCode: response.status,
178
+ url: this.url.href,
179
+ responseBody: text ?? undefined,
176
180
  });
177
181
  this.onerror?.(error);
178
182
  return reject(error);
@@ -19,7 +19,7 @@ export function createChildProcess(
19
19
  return spawn(config.command, config.args ?? [], {
20
20
  env: getEnvironment(config.env),
21
21
  stdio: ['pipe', 'pipe', config.stderr ?? 'inherit'],
22
- shell: false,
22
+ shell: config.shell ?? false,
23
23
  signal,
24
24
  windowsHide: globalThis.process.platform === 'win32' && isElectron(),
25
25
  cwd: config.cwd,
@@ -11,6 +11,7 @@ export interface StdioConfig {
11
11
  env?: Record<string, string>;
12
12
  stderr?: IOType | Stream | number;
13
13
  cwd?: string;
14
+ shell?: boolean | string;
14
15
  }
15
16
 
16
17
  export class StdioMCPTransport implements MCPTransport {
package/src/tool/oauth.ts CHANGED
@@ -94,6 +94,11 @@ export interface OAuthClientProvider {
94
94
  ): void | Promise<void>;
95
95
  get redirectUrl(): string | URL;
96
96
  get clientMetadata(): OAuthClientMetadata;
97
+ /**
98
+ * Returns client credentials. Pre-registered confidential clients must specify
99
+ * their authorization server's `issuer` or provide stored authorization server
100
+ * information. `validateAuthorizationServerURL` does not replace this binding.
101
+ */
97
102
  clientInformation():
98
103
  | OAuthClientInformation
99
104
  | undefined
@@ -121,6 +126,7 @@ export interface OAuthClientProvider {
121
126
  /**
122
127
  * Validates an authorization server URL discovered from MCP protected resource
123
128
  * metadata before the client fetches its OAuth metadata.
129
+ * This additional restriction does not bind client credentials to that server.
124
130
  */
125
131
  validateAuthorizationServerURL?(
126
132
  serverUrl: string | URL,
@@ -1299,11 +1305,20 @@ export async function auth(
1299
1305
  await provider.invalidateCredentials?.('all');
1300
1306
  return await authInternal(provider, options);
1301
1307
  } else if (error instanceof InvalidGrantError && refreshAttempt.tokens) {
1308
+ // Keep the binding validated before the refresh, even when deleting the
1309
+ // rejected tokens removes the provider's only copy of that binding.
1310
+ const retryAuthorizationServerInformation =
1311
+ getAuthorizationServerInformationFromCredentials(refreshAttempt.tokens);
1302
1312
  // Only invalidate the tokens used by a failed refresh.
1303
1313
  await provider.invalidateCredentials?.('tokens', {
1304
1314
  tokens: refreshAttempt.tokens,
1305
1315
  });
1306
- return await authInternal(provider, options);
1316
+ return await authInternal(
1317
+ provider,
1318
+ options,
1319
+ undefined,
1320
+ retryAuthorizationServerInformation,
1321
+ );
1307
1322
  }
1308
1323
 
1309
1324
  throw error;
@@ -1361,6 +1376,7 @@ async function authInternal(
1361
1376
  fetchFn?: FetchFunction;
1362
1377
  },
1363
1378
  refreshAttempt?: { tokens?: OAuthTokens },
1379
+ retryAuthorizationServerInformation?: OAuthAuthorizationServerInformation,
1364
1380
  ): Promise<AuthResult> {
1365
1381
  let resourceMetadata: OAuthProtectedResourceMetadata | undefined;
1366
1382
  let authorizationServerUrl: string | URL | undefined;
@@ -1451,6 +1467,12 @@ async function authInternal(
1451
1467
  );
1452
1468
  const currentAuthorizationServerInformation =
1453
1469
  createAuthorizationServerInformation(authorizationServerUrl, metadata);
1470
+ if (retryAuthorizationServerInformation) {
1471
+ assertAuthorizationServerInformationMatches({
1472
+ storedAuthorizationServerInformation: retryAuthorizationServerInformation,
1473
+ currentAuthorizationServerInformation,
1474
+ });
1475
+ }
1454
1476
  const clientMetadata = provider.clientMetadata;
1455
1477
  const selectedScope = selectScope({
1456
1478
  scope,
@@ -1462,19 +1484,58 @@ async function authInternal(
1462
1484
  if (authorizationCode === undefined) {
1463
1485
  clientInformation = await Promise.resolve(provider.clientInformation());
1464
1486
  }
1465
- if (clientInformation?.issuer != null) {
1487
+ const tokens =
1488
+ authorizationCode === undefined ? await provider.tokens() : undefined;
1489
+ if (clientInformation) {
1490
+ // A flow pin must never override the issuer attached to the credentials.
1491
+ if (
1492
+ clientInformation.issuer != null &&
1493
+ clientInformation.issuer !== currentAuthorizationServerInformation.issuer
1494
+ ) {
1495
+ throw new AuthorizationServerMismatchError({
1496
+ message:
1497
+ 'OAuth authorization server does not match the issuer of the client credentials',
1498
+ });
1499
+ }
1500
+
1501
+ const clientAuthorizationServerInformation =
1502
+ getAuthorizationServerInformationFromCredentials(clientInformation);
1503
+ if (clientAuthorizationServerInformation) {
1504
+ assertAuthorizationServerInformationMatches({
1505
+ storedAuthorizationServerInformation:
1506
+ clientAuthorizationServerInformation,
1507
+ currentAuthorizationServerInformation,
1508
+ });
1509
+ }
1510
+
1466
1511
  const storedAuthorizationServerInformation =
1467
1512
  callbackAuthorizationServerInformation ??
1468
1513
  (await getStoredAuthorizationServerInformation({
1469
1514
  provider,
1470
1515
  clientInformation,
1471
- }));
1516
+ tokens,
1517
+ })) ??
1518
+ retryAuthorizationServerInformation;
1472
1519
  if (storedAuthorizationServerInformation) {
1473
1520
  assertAuthorizationServerInformationMatches({
1474
1521
  storedAuthorizationServerInformation,
1475
1522
  currentAuthorizationServerInformation,
1476
1523
  });
1477
1524
  }
1525
+
1526
+ // Do not turn an MCP server's choice of AS into a trust binding for an
1527
+ // existing secret. Dynamic registration below binds newly issued credentials.
1528
+ if (
1529
+ (clientInformation.client_secret != null ||
1530
+ provider.addClientAuthentication) &&
1531
+ clientInformation.issuer == null &&
1532
+ !storedAuthorizationServerInformation
1533
+ ) {
1534
+ throw new AuthorizationServerMismatchError({
1535
+ message:
1536
+ 'OAuth client credentials must be bound to an authorization server: configure their issuer or store authorization server information',
1537
+ });
1538
+ }
1478
1539
  }
1479
1540
 
1480
1541
  if (!clientInformation) {
@@ -1562,8 +1623,6 @@ async function authInternal(
1562
1623
  return 'AUTHORIZED';
1563
1624
  }
1564
1625
 
1565
- const tokens = await provider.tokens();
1566
-
1567
1626
  /** Refresh only when stored credentials match the current AS pin */
1568
1627
  if (tokens?.refresh_token) {
1569
1628
  const storedAuthorizationServerInformation =