@ai-sdk/mcp 2.0.62 → 2.0.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,524 +1,446 @@
1
- // src/tool/json-rpc-message.ts
2
1
  import { parseJSON } from "@ai-sdk/provider-utils";
3
- import { z as z2 } from "zod/v4";
4
-
5
- // src/tool/types.ts
6
2
  import { z } from "zod/v4";
7
- var ToolMetaSchema = z.optional(z.record(z.string(), z.unknown()));
8
- var ClientOrServerImplementationSchema = z.looseObject({
9
- name: z.string(),
10
- version: z.string(),
11
- title: z.optional(z.string())
3
+ import { AISDKError } from "@ai-sdk/provider";
4
+ import spawn from "cross-spawn";
5
+ //#region src/tool/types.ts
6
+ /** MCP tool metadata - keys should follow MCP _meta key format specification */
7
+ const ToolMetaSchema = z.optional(z.record(z.string(), z.unknown()));
8
+ const ClientOrServerImplementationSchema = z.looseObject({
9
+ name: z.string(),
10
+ version: z.string(),
11
+ title: z.optional(z.string())
12
12
  });
13
- var BaseParamsSchema = z.looseObject({
14
- _meta: z.optional(z.object({}).loose())
13
+ const BaseParamsSchema = z.looseObject({ _meta: z.optional(z.object({}).loose()) });
14
+ const ResultSchema = BaseParamsSchema.extend({ resultType: z.optional(z.string()) });
15
+ const RequestSchema = z.object({
16
+ method: z.string(),
17
+ params: z.optional(BaseParamsSchema)
15
18
  });
16
- var ResultSchema = BaseParamsSchema.extend({
17
- resultType: z.optional(z.string())
19
+ /** @see https://modelcontextprotocol.io/specification/2025-06-18/client/elicitation */
20
+ const ElicitationCapabilitySchema = z.object({ applyDefaults: z.optional(z.boolean()) }).loose();
21
+ const ServerCapabilitiesSchema = z.looseObject({
22
+ experimental: z.optional(z.object({}).loose()),
23
+ logging: z.optional(z.object({}).loose()),
24
+ completions: z.optional(z.object({}).loose()),
25
+ prompts: z.optional(z.looseObject({ listChanged: z.optional(z.boolean()) })),
26
+ resources: z.optional(z.looseObject({
27
+ subscribe: z.optional(z.boolean()),
28
+ listChanged: z.optional(z.boolean())
29
+ })),
30
+ tools: z.optional(z.looseObject({ listChanged: z.optional(z.boolean()) })),
31
+ elicitation: z.optional(ElicitationCapabilitySchema)
18
32
  });
19
- var RequestSchema = z.object({
20
- method: z.string(),
21
- params: z.optional(BaseParamsSchema)
33
+ z.object({ elicitation: z.optional(ElicitationCapabilitySchema) }).loose();
34
+ ResultSchema.extend({
35
+ supportedVersions: z.array(z.string()),
36
+ capabilities: ServerCapabilitiesSchema,
37
+ instructions: z.optional(z.string()),
38
+ ttlMs: z.optional(z.number()),
39
+ cacheScope: z.optional(z.union([z.literal("public"), z.literal("private")]))
22
40
  });
23
- var ElicitationCapabilitySchema = z.object({
24
- applyDefaults: z.optional(z.boolean())
25
- }).loose();
26
- var ServerCapabilitiesSchema = z.looseObject({
27
- experimental: z.optional(z.object({}).loose()),
28
- logging: z.optional(z.object({}).loose()),
29
- completions: z.optional(z.object({}).loose()),
30
- prompts: z.optional(
31
- z.looseObject({
32
- listChanged: z.optional(z.boolean())
33
- })
34
- ),
35
- resources: z.optional(
36
- z.looseObject({
37
- subscribe: z.optional(z.boolean()),
38
- listChanged: z.optional(z.boolean())
39
- })
40
- ),
41
- tools: z.optional(
42
- z.looseObject({
43
- listChanged: z.optional(z.boolean())
44
- })
45
- ),
46
- elicitation: z.optional(ElicitationCapabilitySchema)
41
+ ResultSchema.extend({
42
+ protocolVersion: z.string(),
43
+ capabilities: ServerCapabilitiesSchema,
44
+ serverInfo: ClientOrServerImplementationSchema,
45
+ instructions: z.optional(z.string())
47
46
  });
48
- var ClientCapabilitiesSchema = z.object({
49
- elicitation: z.optional(ElicitationCapabilitySchema)
47
+ const PaginatedResultSchema = ResultSchema.extend({ nextCursor: z.optional(z.string()) });
48
+ const ToolSchema = z.object({
49
+ name: z.string(),
50
+ /**
51
+ * @see https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool
52
+ */
53
+ title: z.optional(z.string()),
54
+ description: z.optional(z.string()),
55
+ inputSchema: z.looseObject({
56
+ type: z.optional(z.unknown()),
57
+ properties: z.optional(z.object({}).loose())
58
+ }),
59
+ /**
60
+ * @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema
61
+ */
62
+ outputSchema: z.optional(z.object({}).loose()),
63
+ annotations: z.optional(z.object({
64
+ title: z.optional(z.string()),
65
+ readOnlyHint: z.optional(z.boolean()),
66
+ destructiveHint: z.optional(z.boolean()),
67
+ idempotentHint: z.optional(z.boolean()),
68
+ openWorldHint: z.optional(z.boolean())
69
+ }).loose()),
70
+ _meta: ToolMetaSchema
50
71
  }).loose();
51
- var DiscoverResultSchema = ResultSchema.extend({
52
- supportedVersions: z.array(z.string()),
53
- capabilities: ServerCapabilitiesSchema,
54
- instructions: z.optional(z.string()),
55
- ttlMs: z.optional(z.number()),
56
- cacheScope: z.optional(z.union([z.literal("public"), z.literal("private")]))
57
- });
58
- var InitializeResultSchema = ResultSchema.extend({
59
- protocolVersion: z.string(),
60
- capabilities: ServerCapabilitiesSchema,
61
- serverInfo: ClientOrServerImplementationSchema,
62
- instructions: z.optional(z.string())
63
- });
64
- var PaginatedResultSchema = ResultSchema.extend({
65
- nextCursor: z.optional(z.string())
66
- });
67
- var ToolSchema = z.object({
68
- name: z.string(),
69
- /**
70
- * @see https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool
71
- */
72
- title: z.optional(z.string()),
73
- description: z.optional(z.string()),
74
- inputSchema: z.looseObject({
75
- type: z.optional(z.unknown()),
76
- properties: z.optional(z.object({}).loose())
77
- }),
78
- /**
79
- * @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema
80
- */
81
- outputSchema: z.optional(z.object({}).loose()),
82
- annotations: z.optional(
83
- z.object({
84
- title: z.optional(z.string()),
85
- readOnlyHint: z.optional(z.boolean()),
86
- destructiveHint: z.optional(z.boolean()),
87
- idempotentHint: z.optional(z.boolean()),
88
- openWorldHint: z.optional(z.boolean())
89
- }).loose()
90
- ),
91
- _meta: ToolMetaSchema
72
+ PaginatedResultSchema.extend({ tools: z.array(ToolSchema) });
73
+ const TextContentSchema = z.object({
74
+ type: z.literal("text"),
75
+ text: z.string()
92
76
  }).loose();
93
- var ListToolsResultSchema = PaginatedResultSchema.extend({
94
- tools: z.array(ToolSchema)
95
- });
96
- var TextContentSchema = z.object({
97
- type: z.literal("text"),
98
- text: z.string()
99
- }).loose();
100
- var ImageContentSchema = z.object({
101
- type: z.literal("image"),
102
- data: z.base64(),
103
- mimeType: z.string()
77
+ const ImageContentSchema = z.object({
78
+ type: z.literal("image"),
79
+ data: z.base64(),
80
+ mimeType: z.string()
104
81
  }).loose();
105
- var ResourceSchema = z.object({
106
- uri: z.string(),
107
- name: z.string(),
108
- title: z.optional(z.string()),
109
- description: z.optional(z.string()),
110
- mimeType: z.optional(z.string()),
111
- size: z.optional(z.number())
82
+ const ResourceSchema = z.object({
83
+ uri: z.string(),
84
+ name: z.string(),
85
+ title: z.optional(z.string()),
86
+ description: z.optional(z.string()),
87
+ mimeType: z.optional(z.string()),
88
+ size: z.optional(z.number())
112
89
  }).loose();
113
- var ListResourcesResultSchema = PaginatedResultSchema.extend({
114
- resources: z.array(ResourceSchema)
115
- });
116
- var ResourceContentsSchema = z.object({
117
- /**
118
- * The URI of this resource.
119
- */
120
- uri: z.string(),
121
- /**
122
- * Optional display name of the resource content.
123
- */
124
- name: z.optional(z.string()),
125
- /**
126
- * Optional human readable title.
127
- */
128
- title: z.optional(z.string()),
129
- /**
130
- * The MIME type of this resource, if known.
131
- */
132
- mimeType: z.optional(z.string())
90
+ PaginatedResultSchema.extend({ resources: z.array(ResourceSchema) });
91
+ const ResourceContentsSchema = z.object({
92
+ /**
93
+ * The URI of this resource.
94
+ */
95
+ uri: z.string(),
96
+ /**
97
+ * Optional display name of the resource content.
98
+ */
99
+ name: z.optional(z.string()),
100
+ /**
101
+ * Optional human readable title.
102
+ */
103
+ title: z.optional(z.string()),
104
+ /**
105
+ * The MIME type of this resource, if known.
106
+ */
107
+ mimeType: z.optional(z.string())
133
108
  }).loose();
134
- var TextResourceContentsSchema = ResourceContentsSchema.extend({
135
- text: z.string()
136
- });
137
- var BlobResourceContentsSchema = ResourceContentsSchema.extend({
138
- blob: z.base64()
139
- });
140
- var EmbeddedResourceSchema = z.object({
141
- type: z.literal("resource"),
142
- resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema])
109
+ const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: z.string() });
110
+ const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: z.base64() });
111
+ const EmbeddedResourceSchema = z.object({
112
+ type: z.literal("resource"),
113
+ resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema])
143
114
  }).loose();
144
- var ResourceLinkContentSchema = z.object({
145
- type: z.literal("resource_link"),
146
- uri: z.string(),
147
- name: z.string(),
148
- description: z.optional(z.string()),
149
- mimeType: z.optional(z.string())
115
+ const ResourceLinkContentSchema = z.object({
116
+ type: z.literal("resource_link"),
117
+ uri: z.string(),
118
+ name: z.string(),
119
+ description: z.optional(z.string()),
120
+ mimeType: z.optional(z.string())
150
121
  }).loose();
151
- var UnknownContentSchema = z.object({ type: z.string() }).loose().refine(
152
- (content) => !["text", "image", "resource", "resource_link"].includes(content.type),
153
- { message: "Known content types must match their schema" }
154
- );
155
- var CallToolResultWithContentSchema = ResultSchema.extend({
156
- content: z.array(
157
- z.union([
158
- TextContentSchema,
159
- ImageContentSchema,
160
- EmbeddedResourceSchema,
161
- ResourceLinkContentSchema,
162
- UnknownContentSchema
163
- ])
164
- ),
165
- /**
166
- * @see https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content
167
- */
168
- structuredContent: z.optional(z.unknown()),
169
- isError: z.boolean().default(false).optional()
122
+ const UnknownContentSchema = z.object({ type: z.string() }).loose().refine((content) => ![
123
+ "text",
124
+ "image",
125
+ "resource",
126
+ "resource_link"
127
+ ].includes(content.type), { message: "Known content types must match their schema" });
128
+ const CallToolResultWithContentSchema = ResultSchema.extend({
129
+ content: z.array(z.union([
130
+ TextContentSchema,
131
+ ImageContentSchema,
132
+ EmbeddedResourceSchema,
133
+ ResourceLinkContentSchema,
134
+ UnknownContentSchema
135
+ ])),
136
+ /**
137
+ * @see https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content
138
+ */
139
+ structuredContent: z.optional(z.unknown()),
140
+ isError: z.boolean().default(false).optional()
170
141
  });
171
- var CallToolResultWithStructuredContentSchema = ResultSchema.extend({
172
- content: z.never().optional(),
173
- structuredContent: z.json(),
174
- isError: z.boolean().default(false).optional()
175
- }).transform(
176
- (result) => ({
177
- ...result,
178
- content: [
179
- {
180
- type: "text",
181
- text: JSON.stringify(result.structuredContent)
182
- }
183
- ]
184
- })
185
- ).pipe(CallToolResultWithContentSchema);
186
- var CallToolResultSchema = CallToolResultWithContentSchema.or(
187
- CallToolResultWithStructuredContentSchema
188
- ).or(
189
- ResultSchema.extend({
190
- toolResult: z.unknown().nonoptional()
191
- })
192
- );
193
- var ResourceTemplateSchema = z.object({
194
- uriTemplate: z.string(),
195
- name: z.string(),
196
- title: z.optional(z.string()),
197
- description: z.optional(z.string()),
198
- mimeType: z.optional(z.string())
142
+ const CallToolResultWithStructuredContentSchema = ResultSchema.extend({
143
+ content: z.never().optional(),
144
+ structuredContent: z.json(),
145
+ isError: z.boolean().default(false).optional()
146
+ }).transform((result) => ({
147
+ ...result,
148
+ content: [{
149
+ type: "text",
150
+ text: JSON.stringify(result.structuredContent)
151
+ }]
152
+ })).pipe(CallToolResultWithContentSchema);
153
+ CallToolResultWithContentSchema.or(CallToolResultWithStructuredContentSchema).or(ResultSchema.extend({ toolResult: z.unknown().nonoptional() }));
154
+ const ResourceTemplateSchema = z.object({
155
+ uriTemplate: z.string(),
156
+ name: z.string(),
157
+ title: z.optional(z.string()),
158
+ description: z.optional(z.string()),
159
+ mimeType: z.optional(z.string())
199
160
  }).loose();
200
- var ListResourceTemplatesResultSchema = ResultSchema.extend({
201
- resourceTemplates: z.array(ResourceTemplateSchema)
202
- });
203
- var ReadResourceResultSchema = ResultSchema.extend({
204
- contents: z.array(
205
- z.union([TextResourceContentsSchema, BlobResourceContentsSchema])
206
- )
207
- });
208
- var PromptReferenceSchema = z.object({
209
- type: z.literal("ref/prompt"),
210
- name: z.string()
161
+ ResultSchema.extend({ resourceTemplates: z.array(ResourceTemplateSchema) });
162
+ ResultSchema.extend({ contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) });
163
+ const PromptReferenceSchema = z.object({
164
+ type: z.literal("ref/prompt"),
165
+ name: z.string()
211
166
  }).loose();
212
- var ResourceReferenceSchema = z.object({
213
- type: z.literal("ref/resource"),
214
- uri: z.string()
167
+ const ResourceReferenceSchema = z.object({
168
+ type: z.literal("ref/resource"),
169
+ uri: z.string()
215
170
  }).loose();
216
- var CompletionArgumentSchema = z.object({
217
- name: z.string(),
218
- value: z.string()
171
+ const CompletionArgumentSchema = z.object({
172
+ name: z.string(),
173
+ value: z.string()
219
174
  }).loose();
220
- var CompleteRequestParamsSchema = BaseParamsSchema.extend({
221
- ref: z.union([PromptReferenceSchema, ResourceReferenceSchema]),
222
- argument: CompletionArgumentSchema,
223
- context: z.optional(
224
- z.object({
225
- arguments: z.record(z.string(), z.string())
226
- }).loose()
227
- )
228
- });
229
- var CompleteResultSchema = ResultSchema.extend({
230
- completion: z.object({
231
- values: z.array(z.string()).max(100),
232
- total: z.optional(z.number().int()),
233
- hasMore: z.optional(z.boolean())
234
- }).loose()
175
+ BaseParamsSchema.extend({
176
+ ref: z.union([PromptReferenceSchema, ResourceReferenceSchema]),
177
+ argument: CompletionArgumentSchema,
178
+ context: z.optional(z.object({ arguments: z.record(z.string(), z.string()) }).loose())
235
179
  });
236
- var PromptArgumentSchema = z.object({
237
- name: z.string(),
238
- description: z.optional(z.string()),
239
- required: z.optional(z.boolean())
180
+ ResultSchema.extend({ completion: z.object({
181
+ values: z.array(z.string()).max(100),
182
+ total: z.optional(z.number().int()),
183
+ hasMore: z.optional(z.boolean())
184
+ }).loose() });
185
+ const PromptArgumentSchema = z.object({
186
+ name: z.string(),
187
+ description: z.optional(z.string()),
188
+ required: z.optional(z.boolean())
240
189
  }).loose();
241
- var PromptSchema = z.object({
242
- name: z.string(),
243
- title: z.optional(z.string()),
244
- description: z.optional(z.string()),
245
- arguments: z.optional(z.array(PromptArgumentSchema))
190
+ const PromptSchema = z.object({
191
+ name: z.string(),
192
+ title: z.optional(z.string()),
193
+ description: z.optional(z.string()),
194
+ arguments: z.optional(z.array(PromptArgumentSchema))
246
195
  }).loose();
247
- var ListPromptsResultSchema = PaginatedResultSchema.extend({
248
- prompts: z.array(PromptSchema)
249
- });
250
- var PromptMessageSchema = z.object({
251
- role: z.union([z.literal("user"), z.literal("assistant")]),
252
- content: z.union([
253
- TextContentSchema,
254
- ImageContentSchema,
255
- EmbeddedResourceSchema,
256
- ResourceLinkContentSchema
257
- ])
196
+ PaginatedResultSchema.extend({ prompts: z.array(PromptSchema) });
197
+ const PromptMessageSchema = z.object({
198
+ role: z.union([z.literal("user"), z.literal("assistant")]),
199
+ content: z.union([
200
+ TextContentSchema,
201
+ ImageContentSchema,
202
+ EmbeddedResourceSchema,
203
+ ResourceLinkContentSchema
204
+ ])
258
205
  }).loose();
259
- var GetPromptResultSchema = ResultSchema.extend({
260
- description: z.optional(z.string()),
261
- messages: z.array(PromptMessageSchema)
206
+ ResultSchema.extend({
207
+ description: z.optional(z.string()),
208
+ messages: z.array(PromptMessageSchema)
262
209
  });
263
- var ElicitationRequestParamsSchema = BaseParamsSchema.extend({
264
- message: z.string(),
265
- requestedSchema: z.unknown()
210
+ const ElicitationRequestParamsSchema = BaseParamsSchema.extend({
211
+ message: z.string(),
212
+ requestedSchema: z.unknown()
266
213
  });
267
- var ElicitationRequestSchema = RequestSchema.extend({
268
- method: z.literal("elicitation/create"),
269
- params: ElicitationRequestParamsSchema
214
+ RequestSchema.extend({
215
+ method: z.literal("elicitation/create"),
216
+ params: ElicitationRequestParamsSchema
270
217
  });
271
- var ElicitResultSchema = ResultSchema.extend({
272
- action: z.union([
273
- z.literal("accept"),
274
- z.literal("decline"),
275
- z.literal("cancel")
276
- ]),
277
- content: z.optional(z.record(z.string(), z.unknown()))
218
+ ResultSchema.extend({
219
+ action: z.union([
220
+ z.literal("accept"),
221
+ z.literal("decline"),
222
+ z.literal("cancel")
223
+ ]),
224
+ content: z.optional(z.record(z.string(), z.unknown()))
278
225
  });
279
-
280
- // src/tool/json-rpc-message.ts
281
- var JSONRPC_VERSION = "2.0";
282
- var JSONRPCRequestSchema = z2.object({
283
- jsonrpc: z2.literal(JSONRPC_VERSION),
284
- id: z2.union([z2.string(), z2.number().int()])
226
+ //#endregion
227
+ //#region src/tool/json-rpc-message.ts
228
+ const JSONRPC_VERSION = "2.0";
229
+ const JSONRPCRequestSchema = z.object({
230
+ jsonrpc: z.literal(JSONRPC_VERSION),
231
+ id: z.union([z.string(), z.number().int()])
285
232
  }).merge(RequestSchema).strict();
286
- var JSONRPCResponseSchema = z2.object({
287
- jsonrpc: z2.literal(JSONRPC_VERSION),
288
- id: z2.union([z2.string(), z2.number().int()]),
289
- result: ResultSchema
233
+ const JSONRPCResponseSchema = z.object({
234
+ jsonrpc: z.literal(JSONRPC_VERSION),
235
+ id: z.union([z.string(), z.number().int()]),
236
+ result: ResultSchema
290
237
  }).strict();
291
- var JSONRPCErrorSchema = z2.object({
292
- jsonrpc: z2.literal(JSONRPC_VERSION),
293
- id: z2.optional(z2.union([z2.string(), z2.number().int()])),
294
- error: z2.object({
295
- code: z2.number().int(),
296
- message: z2.string(),
297
- data: z2.optional(z2.unknown())
298
- })
238
+ const JSONRPCErrorSchema = z.object({
239
+ jsonrpc: z.literal(JSONRPC_VERSION),
240
+ id: z.optional(z.union([z.string(), z.number().int()])),
241
+ error: z.object({
242
+ code: z.number().int(),
243
+ message: z.string(),
244
+ data: z.optional(z.unknown())
245
+ })
299
246
  }).strict();
300
- var JSONRPCNotificationSchema = z2.object({
301
- jsonrpc: z2.literal(JSONRPC_VERSION)
302
- }).merge(
303
- z2.object({
304
- method: z2.string(),
305
- params: z2.optional(BaseParamsSchema)
306
- })
307
- ).strict();
308
- var JSONRPCMessageSchema = z2.union([
309
- JSONRPCRequestSchema,
310
- JSONRPCNotificationSchema,
311
- JSONRPCResponseSchema,
312
- JSONRPCErrorSchema
247
+ const JSONRPCNotificationSchema = z.object({ jsonrpc: z.literal(JSONRPC_VERSION) }).merge(z.object({
248
+ method: z.string(),
249
+ params: z.optional(BaseParamsSchema)
250
+ })).strict();
251
+ const JSONRPCMessageSchema = z.union([
252
+ JSONRPCRequestSchema,
253
+ JSONRPCNotificationSchema,
254
+ JSONRPCResponseSchema,
255
+ JSONRPCErrorSchema
313
256
  ]);
314
257
  function validateJSONRPCMessage(message) {
315
- return JSONRPCMessageSchema.parse(message);
258
+ return JSONRPCMessageSchema.parse(message);
316
259
  }
317
260
  async function parseJSONRPCMessage(text) {
318
- return validateJSONRPCMessage(await parseJSON({ text }));
261
+ return validateJSONRPCMessage(await parseJSON({ text }));
319
262
  }
320
-
321
- // src/error/mcp-client-error.ts
322
- import { AISDKError } from "@ai-sdk/provider";
323
- var name = "AI_MCPClientError";
324
- var marker = `vercel.ai.error.${name}`;
325
- var symbol = Symbol.for(marker);
326
- var _a, _b;
327
- var MCPClientError = class extends (_b = AISDKError, _a = symbol, _b) {
328
- constructor({
329
- name: name2 = "MCPClientError",
330
- message,
331
- cause,
332
- data,
333
- code,
334
- statusCode,
335
- url,
336
- responseBody
337
- }) {
338
- super({ name: name2, message, cause });
339
- this[_a] = true;
340
- this.data = data;
341
- this.code = code;
342
- this.statusCode = statusCode;
343
- this.url = url;
344
- this.responseBody = responseBody;
345
- }
346
- static isInstance(error) {
347
- return AISDKError.hasMarker(error, marker);
348
- }
263
+ //#endregion
264
+ //#region src/error/mcp-client-error.ts
265
+ const marker = `vercel.ai.error.AI_MCPClientError`;
266
+ const symbol = Symbol.for(marker);
267
+ /**
268
+ * An error occurred with the MCP client.
269
+ */
270
+ var MCPClientError = class extends AISDKError {
271
+ constructor({ name = "MCPClientError", message, cause, data, code, statusCode, url, responseBody }) {
272
+ super({
273
+ name,
274
+ message,
275
+ cause
276
+ });
277
+ this[symbol] = true;
278
+ this.data = data;
279
+ this.code = code;
280
+ this.statusCode = statusCode;
281
+ this.url = url;
282
+ this.responseBody = responseBody;
283
+ }
284
+ static isInstance(error) {
285
+ return AISDKError.hasMarker(error, marker);
286
+ }
349
287
  };
350
-
351
- // src/tool/mcp-stdio/create-child-process.ts
352
- import spawn from "cross-spawn";
353
-
354
- // src/tool/mcp-stdio/get-environment.ts
288
+ //#endregion
289
+ //#region src/tool/mcp-stdio/get-environment.ts
290
+ /**
291
+ * Constructs the environment variables for the child process.
292
+ *
293
+ * @param customEnv - Custom environment variables to merge with default environment variables.
294
+ * @returns The environment variables for the child process.
295
+ */
355
296
  function getEnvironment(customEnv) {
356
- const isWindows = globalThis.process.platform === "win32";
357
- const DEFAULT_INHERITED_ENV_VARS = isWindows ? [
358
- "APPDATA",
359
- "HOMEDRIVE",
360
- "HOMEPATH",
361
- "LOCALAPPDATA",
362
- "PATH",
363
- "PROCESSOR_ARCHITECTURE",
364
- "SYSTEMDRIVE",
365
- "SYSTEMROOT",
366
- "TEMP",
367
- "USERNAME",
368
- "USERPROFILE"
369
- ] : ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"];
370
- const env = customEnv ? { ...customEnv } : {};
371
- const customEnvKeys = new Set(
372
- Object.keys(env).map((key) => isWindows ? key.toUpperCase() : key)
373
- );
374
- for (const key of DEFAULT_INHERITED_ENV_VARS) {
375
- if (customEnvKeys.has(key)) {
376
- continue;
377
- }
378
- const value = globalThis.process.env[key];
379
- if (value === void 0) {
380
- continue;
381
- }
382
- if (value.startsWith("()")) {
383
- continue;
384
- }
385
- env[key] = value;
386
- }
387
- return env;
297
+ const isWindows = globalThis.process.platform === "win32";
298
+ const DEFAULT_INHERITED_ENV_VARS = isWindows ? [
299
+ "APPDATA",
300
+ "HOMEDRIVE",
301
+ "HOMEPATH",
302
+ "LOCALAPPDATA",
303
+ "PATH",
304
+ "PROCESSOR_ARCHITECTURE",
305
+ "SYSTEMDRIVE",
306
+ "SYSTEMROOT",
307
+ "TEMP",
308
+ "USERNAME",
309
+ "USERPROFILE"
310
+ ] : [
311
+ "HOME",
312
+ "LOGNAME",
313
+ "PATH",
314
+ "SHELL",
315
+ "TERM",
316
+ "USER"
317
+ ];
318
+ const env = customEnv ? { ...customEnv } : {};
319
+ const customEnvKeys = new Set(Object.keys(env).map((key) => isWindows ? key.toUpperCase() : key));
320
+ for (const key of DEFAULT_INHERITED_ENV_VARS) {
321
+ if (customEnvKeys.has(key)) continue;
322
+ const value = globalThis.process.env[key];
323
+ if (value === void 0) continue;
324
+ if (value.startsWith("()")) continue;
325
+ env[key] = value;
326
+ }
327
+ return env;
388
328
  }
389
-
390
- // src/tool/mcp-stdio/create-child-process.ts
329
+ //#endregion
330
+ //#region src/tool/mcp-stdio/create-child-process.ts
391
331
  function createChildProcess(config, signal) {
392
- if (globalThis.process.platform === "win32" && [config.command, ...config.args ?? []].some((value) => /[\r\n]/.test(value))) {
393
- throw new TypeError(
394
- "Stdio MCP commands and arguments must not contain line breaks on Windows."
395
- );
396
- }
397
- return spawn(config.command, config.args ?? [], {
398
- env: getEnvironment(config.env),
399
- stdio: ["pipe", "pipe", config.stderr ?? "inherit"],
400
- shell: false,
401
- signal,
402
- windowsHide: globalThis.process.platform === "win32" && isElectron(),
403
- cwd: config.cwd
404
- });
332
+ if (globalThis.process.platform === "win32" && [config.command, ...config.args ?? []].some((value) => /[\r\n]/.test(value))) throw new TypeError("Stdio MCP commands and arguments must not contain line breaks on Windows.");
333
+ return spawn(config.command, config.args ?? [], {
334
+ env: getEnvironment(config.env),
335
+ stdio: [
336
+ "pipe",
337
+ "pipe",
338
+ config.stderr ?? "inherit"
339
+ ],
340
+ shell: false,
341
+ signal,
342
+ windowsHide: globalThis.process.platform === "win32" && isElectron(),
343
+ cwd: config.cwd
344
+ });
405
345
  }
406
346
  function isElectron() {
407
- return "type" in globalThis.process;
347
+ return "type" in globalThis.process;
408
348
  }
409
-
410
- // src/tool/mcp-stdio/mcp-stdio-transport.ts
349
+ //#endregion
350
+ //#region src/tool/mcp-stdio/mcp-stdio-transport.ts
411
351
  var StdioMCPTransport = class {
412
- constructor(server) {
413
- this.supportsProtocolVersionDiscovery = true;
414
- this.abortController = new AbortController();
415
- this.readBuffer = new ReadBuffer();
416
- this.serverParams = server;
417
- }
418
- async start() {
419
- if (this.process) {
420
- throw new MCPClientError({
421
- message: "StdioMCPTransport already started."
422
- });
423
- }
424
- return new Promise((resolve, reject) => {
425
- try {
426
- const process = createChildProcess(
427
- this.serverParams,
428
- this.abortController.signal
429
- );
430
- this.process = process;
431
- this.process.on("error", (error) => {
432
- if (error.name === "AbortError") {
433
- this.onclose?.();
434
- return;
435
- }
436
- reject(error);
437
- this.onerror?.(error);
438
- });
439
- this.process.on("spawn", () => {
440
- resolve();
441
- });
442
- this.process.on("close", (_code) => {
443
- this.process = void 0;
444
- this.onclose?.();
445
- });
446
- this.process.stdin?.on("error", (error) => {
447
- this.onerror?.(error);
448
- });
449
- this.process.stdout?.on("data", (chunk) => {
450
- this.readBuffer.append(chunk);
451
- void this.processReadBuffer();
452
- });
453
- this.process.stdout?.on("error", (error) => {
454
- this.onerror?.(error);
455
- });
456
- } catch (error) {
457
- reject(error);
458
- this.onerror?.(error);
459
- }
460
- });
461
- }
462
- async processReadBuffer() {
463
- while (true) {
464
- const line = this.readBuffer.readLine();
465
- if (line === null) {
466
- break;
467
- }
468
- try {
469
- const message = await deserializeMessage(line);
470
- this.onmessage?.(message);
471
- } catch (error) {
472
- this.onerror?.(error);
473
- }
474
- }
475
- }
476
- async close() {
477
- this.abortController.abort();
478
- this.process = void 0;
479
- this.readBuffer.clear();
480
- }
481
- send(message) {
482
- return new Promise((resolve) => {
483
- if (!this.process?.stdin) {
484
- throw new MCPClientError({
485
- message: "StdioClientTransport not connected"
486
- });
487
- }
488
- const json = serializeMessage(message);
489
- if (this.process.stdin.write(json)) {
490
- resolve();
491
- } else {
492
- this.process.stdin.once("drain", resolve);
493
- }
494
- });
495
- }
352
+ constructor(server) {
353
+ this.supportsProtocolVersionDiscovery = true;
354
+ this.abortController = new AbortController();
355
+ this.readBuffer = new ReadBuffer();
356
+ this.serverParams = server;
357
+ }
358
+ async start() {
359
+ if (this.process) throw new MCPClientError({ message: "StdioMCPTransport already started." });
360
+ return new Promise((resolve, reject) => {
361
+ try {
362
+ const process = createChildProcess(this.serverParams, this.abortController.signal);
363
+ this.process = process;
364
+ this.process.on("error", (error) => {
365
+ if (error.name === "AbortError") {
366
+ this.onclose?.();
367
+ return;
368
+ }
369
+ reject(error);
370
+ this.onerror?.(error);
371
+ });
372
+ this.process.on("spawn", () => {
373
+ resolve();
374
+ });
375
+ this.process.on("close", (_code) => {
376
+ this.process = void 0;
377
+ this.onclose?.();
378
+ });
379
+ this.process.stdin?.on("error", (error) => {
380
+ this.onerror?.(error);
381
+ });
382
+ this.process.stdout?.on("data", (chunk) => {
383
+ this.readBuffer.append(chunk);
384
+ this.processReadBuffer();
385
+ });
386
+ this.process.stdout?.on("error", (error) => {
387
+ this.onerror?.(error);
388
+ });
389
+ } catch (error) {
390
+ reject(error);
391
+ this.onerror?.(error);
392
+ }
393
+ });
394
+ }
395
+ async processReadBuffer() {
396
+ while (true) {
397
+ const line = this.readBuffer.readLine();
398
+ if (line === null) break;
399
+ try {
400
+ const message = await deserializeMessage(line);
401
+ this.onmessage?.(message);
402
+ } catch (error) {
403
+ this.onerror?.(error);
404
+ }
405
+ }
406
+ }
407
+ async close() {
408
+ this.abortController.abort();
409
+ this.process = void 0;
410
+ this.readBuffer.clear();
411
+ }
412
+ send(message) {
413
+ return new Promise((resolve) => {
414
+ if (!this.process?.stdin) throw new MCPClientError({ message: "StdioClientTransport not connected" });
415
+ const json = serializeMessage(message);
416
+ if (this.process.stdin.write(json)) resolve();
417
+ else this.process.stdin.once("drain", resolve);
418
+ });
419
+ }
496
420
  };
497
421
  var ReadBuffer = class {
498
- append(chunk) {
499
- this.buffer = this.buffer ? Buffer.concat([this.buffer, chunk]) : chunk;
500
- }
501
- readLine() {
502
- if (!this.buffer) return null;
503
- const index = this.buffer.indexOf("\n");
504
- if (index === -1) {
505
- return null;
506
- }
507
- const line = this.buffer.toString("utf8", 0, index);
508
- this.buffer = this.buffer.subarray(index + 1);
509
- return line;
510
- }
511
- clear() {
512
- this.buffer = void 0;
513
- }
422
+ append(chunk) {
423
+ this.buffer = this.buffer ? Buffer.concat([this.buffer, chunk]) : chunk;
424
+ }
425
+ readLine() {
426
+ if (!this.buffer) return null;
427
+ const index = this.buffer.indexOf("\n");
428
+ if (index === -1) return null;
429
+ const line = this.buffer.toString("utf8", 0, index);
430
+ this.buffer = this.buffer.subarray(index + 1);
431
+ return line;
432
+ }
433
+ clear() {
434
+ this.buffer = void 0;
435
+ }
514
436
  };
515
437
  function serializeMessage(message) {
516
- return JSON.stringify(message) + "\n";
438
+ return JSON.stringify(message) + "\n";
517
439
  }
518
440
  async function deserializeMessage(line) {
519
- return parseJSONRPCMessage(line);
441
+ return parseJSONRPCMessage(line);
520
442
  }
521
- export {
522
- StdioMCPTransport as Experimental_StdioMCPTransport
523
- };
443
+ //#endregion
444
+ export { StdioMCPTransport as Experimental_StdioMCPTransport };
445
+
524
446
  //# sourceMappingURL=index.js.map