@corsair-dev/mcp 0.1.20 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,19 @@
1
1
  // src/adapters/anthropic-api.ts
2
- import { z as z2 } from "zod";
3
- import { zodToJsonSchema } from "zod-to-json-schema";
2
+ import { z as z3 } from "zod";
3
+
4
+ // src/core/json-schema.ts
5
+ import { z } from "zod";
6
+ import * as z4mini from "zod/v4-mini";
7
+ function shapeToJsonSchema(shape) {
8
+ return z4mini.toJSONSchema(z.object(shape), {
9
+ target: "draft-7",
10
+ io: "input"
11
+ });
12
+ }
4
13
 
5
14
  // src/core/tools.ts
6
15
  import { listOperations, setupCorsair } from "corsair";
7
- import { z } from "zod";
16
+ import { z as z2 } from "zod";
8
17
 
9
18
  // src/core/schema-format.ts
10
19
  import { formatDocSchemaShape, getSchema } from "corsair";
@@ -26,8 +35,8 @@ function buildCorsairToolDefs(options) {
26
35
  name: "list_operations",
27
36
  description: "List available Corsair operations. Without options returns all API endpoints across every plugin. Filter by plugin (e.g. 'slack') and/or type ('api' | 'webhooks' | 'db').",
28
37
  shape: {
29
- plugin: z.string().optional().describe("Plugin ID to filter by, e.g. 'slack' or 'github'"),
30
- type: z.enum(["api", "webhooks", "db"]).optional().describe("Operation type: 'api' (default), 'webhooks', or 'db'")
38
+ plugin: z2.string().optional().describe("Plugin ID to filter by, e.g. 'slack' or 'github'"),
39
+ type: z2.enum(["api", "webhooks", "db"]).optional().describe("Operation type: 'api' (default), 'webhooks', or 'db'")
31
40
  },
32
41
  handler: async ({ plugin, type }) => {
33
42
  const result = listOperations(corsair, {
@@ -43,7 +52,7 @@ function buildCorsairToolDefs(options) {
43
52
  name: "get_schema",
44
53
  description: "Get the schema and metadata for a Corsair operation path. Accepts API paths ('slack.api.channels.list'), webhook paths ('slack.webhooks.messages.message'), or DB paths ('slack.db.messages.search').",
45
54
  shape: {
46
- path: z.string().describe(
55
+ path: z2.string().describe(
47
56
  "Full dot-path from list_operations, e.g. 'slack.api.channels.list'"
48
57
  )
49
58
  },
@@ -61,7 +70,7 @@ function buildCorsairToolDefs(options) {
61
70
  name: "run_script",
62
71
  description: "Run a JavaScript script with `corsair` as the only variable in scope. Call Corsair operations, filter or transform the results inline, and return only what you need. The return value becomes the tool output.",
63
72
  shape: {
64
- code: z.string().describe(
73
+ code: z2.string().describe(
65
74
  'Async JS script with `corsair` in scope. Return the value you want. Example:\nconst result = await corsair.slack.api.channels.list({});\nconst channel = result.channels?.find(c => c.name === "general");\nreturn channel?.id;'
66
75
  )
67
76
  },
@@ -106,7 +115,7 @@ ${full}`
106
115
  name: "corsair_setup",
107
116
  description: "Helps the user configure Corsair. Call this to see if any keys or tokens need to be set up. It will also provide the instructions to set them up. For multi-tenant Corsair instances, pass tenantId to set up a specific tenant.",
108
117
  shape: {
109
- tenantId: z.string().optional().describe(
118
+ tenantId: z2.string().optional().describe(
110
119
  "Tenant ID to configure for multi-tenant Corsair instances. Defaults to the server's configured tenantId, then 'default'."
111
120
  )
112
121
  },
@@ -137,16 +146,16 @@ ${full}`
137
146
  name: "request_permission",
138
147
  description: "Request permission from the user to execute a protected endpoint. Call this when a script returns a [PERMISSION_REQUIRED] message. Returns an approval URL. After calling this, call ask_human with the approval URL so the user can review and approve.",
139
148
  shape: {
140
- endpoint: z.string().describe(
149
+ endpoint: z2.string().describe(
141
150
  'Full endpoint path from the PERMISSION_REQUIRED message, e.g. "slack.messages.post"'
142
151
  ),
143
- args: z.record(z.string(), z.unknown()).describe(
152
+ args: z2.record(z2.string(), z2.unknown()).describe(
144
153
  "The arguments object from the PERMISSION_REQUIRED message"
145
154
  ),
146
- description: z.string().describe(
155
+ description: z2.string().describe(
147
156
  'Short human-readable summary of what this action will do, e.g. "Post a message to #general in Slack"'
148
157
  ),
149
- jid: z.string().optional().describe(
158
+ jid: z2.string().optional().describe(
150
159
  "Optional chat/conversation ID for resuming after approval"
151
160
  )
152
161
  },
@@ -181,7 +190,7 @@ var BaseProvider = class {
181
190
  var AnthropicProvider = class extends BaseProvider {
182
191
  name = "anthropic";
183
192
  wrapTool(def) {
184
- const schema = zodToJsonSchema(z2.object(def.shape), { target: "openApi3" });
193
+ const schema = shapeToJsonSchema(def.shape);
185
194
  return {
186
195
  type: "custom",
187
196
  name: def.name,
@@ -196,7 +205,7 @@ var AnthropicProvider = class extends BaseProvider {
196
205
  return `Error: ${message}`;
197
206
  }
198
207
  },
199
- parse: (content) => z2.object(def.shape).parse(content)
208
+ parse: (content) => z3.object(def.shape).parse(content)
200
209
  };
201
210
  }
202
211
  };
@@ -205,19 +214,19 @@ var AnthropicProvider = class extends BaseProvider {
205
214
  var ClaudeProvider = class {
206
215
  name = "claude";
207
216
  async build(options) {
208
- const { tool } = await import(
217
+ const { tool: tool2 } = await import(
209
218
  /* webpackIgnore: true */
210
219
  /* turbopackIgnore: true */
211
220
  "@anthropic-ai/claude-agent-sdk"
212
221
  );
213
222
  return buildCorsairToolDefs(options).map(
214
- (def) => tool(def.name, def.description, def.shape, def.handler)
223
+ (def) => tool2(def.name, def.description, def.shape, def.handler)
215
224
  );
216
225
  }
217
226
  };
218
227
 
219
228
  // src/adapters/mastra.ts
220
- import { z as z3 } from "zod";
229
+ import { z as z4 } from "zod";
221
230
  var MastraProvider = class {
222
231
  name = "mastra";
223
232
  async build(options) {
@@ -230,7 +239,7 @@ var MastraProvider = class {
230
239
  (def) => createTool({
231
240
  id: def.name,
232
241
  description: def.description,
233
- inputSchema: z3.object(def.shape),
242
+ inputSchema: z4.object(def.shape),
234
243
  execute: async (inputData) => {
235
244
  const result = await def.handler(
236
245
  inputData
@@ -252,12 +261,11 @@ var MastraProvider = class {
252
261
  };
253
262
 
254
263
  // src/adapters/ollama.ts
255
- import { z as z4 } from "zod";
256
- import { zodToJsonSchema as zodToJsonSchema2 } from "zod-to-json-schema";
264
+ import { z as z5 } from "zod";
257
265
  var OllamaProvider = class extends BaseProvider {
258
266
  name = "ollama";
259
267
  wrapTool(def) {
260
- const schema = zodToJsonSchema2(z4.object(def.shape));
268
+ const schema = shapeToJsonSchema(def.shape);
261
269
  return {
262
270
  type: "function",
263
271
  function: {
@@ -277,7 +285,7 @@ var OllamaProvider = class extends BaseProvider {
277
285
  execute: async (args) => {
278
286
  try {
279
287
  const raw = typeof args === "string" ? JSON.parse(args) : args;
280
- const validated = z4.object(def.shape).parse(raw);
288
+ const validated = z5.object(def.shape).parse(raw);
281
289
  const result = await def.handler(validated);
282
290
  return result.content.filter((c) => c.type === "text").map((c) => "text" in c ? c.text : "").join("\n");
283
291
  } catch (err) {
@@ -299,19 +307,18 @@ function getOpenAIMcpConfig(baseUrl, headers) {
299
307
  }
300
308
 
301
309
  // src/adapters/openai-agents.ts
302
- import { z as z5 } from "zod";
303
- import { zodToJsonSchema as zodToJsonSchema3 } from "zod-to-json-schema";
310
+ import { z as z6 } from "zod";
304
311
  var OpenAIAgentsProvider = class {
305
312
  name = "openai-agents";
306
313
  build(options) {
307
- const { tool, ...mcpOptions } = options;
314
+ const { tool: tool2, ...mcpOptions } = options;
308
315
  return buildCorsairToolDefs(mcpOptions).map((def) => {
309
- const jsonSchema = zodToJsonSchema3(z5.object(def.shape));
316
+ const jsonSchema2 = shapeToJsonSchema(def.shape);
310
317
  const shapeKeys = new Set(Object.keys(def.shape));
311
- return tool({
318
+ return tool2({
312
319
  name: def.name,
313
320
  description: def.description,
314
- parameters: jsonSchema,
321
+ parameters: jsonSchema2,
315
322
  strict: false,
316
323
  execute: async (input) => {
317
324
  try {
@@ -323,7 +330,7 @@ var OpenAIAgentsProvider = class {
323
330
  }
324
331
  if (Object.keys(extra).length > 0) raw.args = extra;
325
332
  }
326
- const args = z5.object(def.shape).parse(raw);
333
+ const args = z6.object(def.shape).parse(raw);
327
334
  const result = await def.handler(args);
328
335
  return result.content.filter((c) => c.type === "text").map((c) => "text" in c ? c.text : "").join("\n");
329
336
  } catch (err) {
@@ -336,27 +343,4026 @@ var OpenAIAgentsProvider = class {
336
343
  }
337
344
  };
338
345
 
339
- // src/adapters/vercel-ai.ts
340
- async function createVercelAiMcpClient(options) {
341
- const { createMCPClient } = await import(
342
- /* webpackIgnore: true */
343
- /* turbopackIgnore: true */
344
- "@ai-sdk/mcp"
346
+ // ../../node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/dist/index.mjs
347
+ var marker = "vercel.ai.error";
348
+ var symbol = Symbol.for(marker);
349
+ var _a;
350
+ var _b;
351
+ var AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {
352
+ /**
353
+ * Creates an AI SDK Error.
354
+ *
355
+ * @param {Object} params - The parameters for creating the error.
356
+ * @param {string} params.name - The name of the error.
357
+ * @param {string} params.message - The error message.
358
+ * @param {unknown} [params.cause] - The underlying cause of the error.
359
+ */
360
+ constructor({
361
+ name: name142,
362
+ message,
363
+ cause
364
+ }) {
365
+ super(message);
366
+ this[_a] = true;
367
+ this.name = name142;
368
+ this.cause = cause;
369
+ }
370
+ /**
371
+ * Checks if the given error is an AI SDK Error.
372
+ * @param {unknown} error - The error to check.
373
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
374
+ */
375
+ static isInstance(error) {
376
+ return _AISDKError.hasMarker(error, marker);
377
+ }
378
+ static hasMarker(error, marker152) {
379
+ const markerSymbol = Symbol.for(marker152);
380
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
381
+ }
382
+ };
383
+ var name = "AI_APICallError";
384
+ var marker2 = `vercel.ai.error.${name}`;
385
+ var symbol2 = Symbol.for(marker2);
386
+ var _a2;
387
+ var _b2;
388
+ var APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {
389
+ constructor({
390
+ message,
391
+ url,
392
+ requestBodyValues,
393
+ statusCode,
394
+ responseHeaders,
395
+ responseBody,
396
+ cause,
397
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
398
+ statusCode === 409 || // conflict
399
+ statusCode === 429 || // too many requests
400
+ statusCode >= 500),
401
+ // server error
402
+ data
403
+ }) {
404
+ super({ name, message, cause });
405
+ this[_a2] = true;
406
+ this.url = url;
407
+ this.requestBodyValues = requestBodyValues;
408
+ this.statusCode = statusCode;
409
+ this.responseHeaders = responseHeaders;
410
+ this.responseBody = responseBody;
411
+ this.isRetryable = isRetryable;
412
+ this.data = data;
413
+ }
414
+ static isInstance(error) {
415
+ return AISDKError.hasMarker(error, marker2);
416
+ }
417
+ };
418
+ var name2 = "AI_EmptyResponseBodyError";
419
+ var marker3 = `vercel.ai.error.${name2}`;
420
+ var symbol3 = Symbol.for(marker3);
421
+ var _a3;
422
+ var _b3;
423
+ var EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {
424
+ // used in isInstance
425
+ constructor({ message = "Empty response body" } = {}) {
426
+ super({ name: name2, message });
427
+ this[_a3] = true;
428
+ }
429
+ static isInstance(error) {
430
+ return AISDKError.hasMarker(error, marker3);
431
+ }
432
+ };
433
+ function getErrorMessage(error) {
434
+ if (error == null) {
435
+ return "unknown error";
436
+ }
437
+ if (typeof error === "string") {
438
+ return error;
439
+ }
440
+ if (error instanceof Error) {
441
+ return error.message;
442
+ }
443
+ return JSON.stringify(error);
444
+ }
445
+ var name3 = "AI_InvalidArgumentError";
446
+ var marker4 = `vercel.ai.error.${name3}`;
447
+ var symbol4 = Symbol.for(marker4);
448
+ var _a4;
449
+ var _b4;
450
+ var InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {
451
+ constructor({
452
+ message,
453
+ cause,
454
+ argument
455
+ }) {
456
+ super({ name: name3, message, cause });
457
+ this[_a4] = true;
458
+ this.argument = argument;
459
+ }
460
+ static isInstance(error) {
461
+ return AISDKError.hasMarker(error, marker4);
462
+ }
463
+ };
464
+ var name4 = "AI_InvalidPromptError";
465
+ var marker5 = `vercel.ai.error.${name4}`;
466
+ var symbol5 = Symbol.for(marker5);
467
+ var _a5;
468
+ var _b5;
469
+ var InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {
470
+ constructor({
471
+ prompt,
472
+ message,
473
+ cause
474
+ }) {
475
+ super({ name: name4, message: `Invalid prompt: ${message}`, cause });
476
+ this[_a5] = true;
477
+ this.prompt = prompt;
478
+ }
479
+ static isInstance(error) {
480
+ return AISDKError.hasMarker(error, marker5);
481
+ }
482
+ };
483
+ var name5 = "AI_InvalidResponseDataError";
484
+ var marker6 = `vercel.ai.error.${name5}`;
485
+ var symbol6 = Symbol.for(marker6);
486
+ var _a6;
487
+ var _b6;
488
+ var InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {
489
+ constructor({
490
+ data,
491
+ message = `Invalid response data: ${JSON.stringify(data)}.`
492
+ }) {
493
+ super({ name: name5, message });
494
+ this[_a6] = true;
495
+ this.data = data;
496
+ }
497
+ static isInstance(error) {
498
+ return AISDKError.hasMarker(error, marker6);
499
+ }
500
+ };
501
+ var name6 = "AI_JSONParseError";
502
+ var marker7 = `vercel.ai.error.${name6}`;
503
+ var symbol7 = Symbol.for(marker7);
504
+ var _a7;
505
+ var _b7;
506
+ var JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {
507
+ constructor({ text, cause }) {
508
+ super({
509
+ name: name6,
510
+ message: `JSON parsing failed: Text: ${text}.
511
+ Error message: ${getErrorMessage(cause)}`,
512
+ cause
513
+ });
514
+ this[_a7] = true;
515
+ this.text = text;
516
+ }
517
+ static isInstance(error) {
518
+ return AISDKError.hasMarker(error, marker7);
519
+ }
520
+ };
521
+ var name7 = "AI_LoadAPIKeyError";
522
+ var marker8 = `vercel.ai.error.${name7}`;
523
+ var symbol8 = Symbol.for(marker8);
524
+ var _a8;
525
+ var _b8;
526
+ var LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {
527
+ // used in isInstance
528
+ constructor({ message }) {
529
+ super({ name: name7, message });
530
+ this[_a8] = true;
531
+ }
532
+ static isInstance(error) {
533
+ return AISDKError.hasMarker(error, marker8);
534
+ }
535
+ };
536
+ var name8 = "AI_LoadSettingError";
537
+ var marker9 = `vercel.ai.error.${name8}`;
538
+ var symbol9 = Symbol.for(marker9);
539
+ var _a9;
540
+ var _b9;
541
+ var LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {
542
+ // used in isInstance
543
+ constructor({ message }) {
544
+ super({ name: name8, message });
545
+ this[_a9] = true;
546
+ }
547
+ static isInstance(error) {
548
+ return AISDKError.hasMarker(error, marker9);
549
+ }
550
+ };
551
+ var name9 = "AI_NoContentGeneratedError";
552
+ var marker10 = `vercel.ai.error.${name9}`;
553
+ var symbol10 = Symbol.for(marker10);
554
+ var _a10;
555
+ var _b10;
556
+ var NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {
557
+ // used in isInstance
558
+ constructor({
559
+ message = "No content generated."
560
+ } = {}) {
561
+ super({ name: name9, message });
562
+ this[_a10] = true;
563
+ }
564
+ static isInstance(error) {
565
+ return AISDKError.hasMarker(error, marker10);
566
+ }
567
+ };
568
+ var name10 = "AI_NoSuchModelError";
569
+ var marker11 = `vercel.ai.error.${name10}`;
570
+ var symbol11 = Symbol.for(marker11);
571
+ var _a11;
572
+ var _b11;
573
+ var NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {
574
+ constructor({
575
+ errorName = name10,
576
+ modelId,
577
+ modelType,
578
+ message = `No such ${modelType}: ${modelId}`
579
+ }) {
580
+ super({ name: errorName, message });
581
+ this[_a11] = true;
582
+ this.modelId = modelId;
583
+ this.modelType = modelType;
584
+ }
585
+ static isInstance(error) {
586
+ return AISDKError.hasMarker(error, marker11);
587
+ }
588
+ };
589
+ var name11 = "AI_TooManyEmbeddingValuesForCallError";
590
+ var marker12 = `vercel.ai.error.${name11}`;
591
+ var symbol12 = Symbol.for(marker12);
592
+ var _a12;
593
+ var _b12;
594
+ var TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {
595
+ constructor(options) {
596
+ super({
597
+ name: name11,
598
+ message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`
599
+ });
600
+ this[_a12] = true;
601
+ this.provider = options.provider;
602
+ this.modelId = options.modelId;
603
+ this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
604
+ this.values = options.values;
605
+ }
606
+ static isInstance(error) {
607
+ return AISDKError.hasMarker(error, marker12);
608
+ }
609
+ };
610
+ var name12 = "AI_TypeValidationError";
611
+ var marker13 = `vercel.ai.error.${name12}`;
612
+ var symbol13 = Symbol.for(marker13);
613
+ var _a13;
614
+ var _b13;
615
+ var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
616
+ constructor({
617
+ value,
618
+ cause,
619
+ context
620
+ }) {
621
+ let contextPrefix = "Type validation failed";
622
+ if (context == null ? void 0 : context.field) {
623
+ contextPrefix += ` for ${context.field}`;
624
+ }
625
+ if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {
626
+ contextPrefix += " (";
627
+ const parts = [];
628
+ if (context.entityName) {
629
+ parts.push(context.entityName);
630
+ }
631
+ if (context.entityId) {
632
+ parts.push(`id: "${context.entityId}"`);
633
+ }
634
+ contextPrefix += parts.join(", ");
635
+ contextPrefix += ")";
636
+ }
637
+ super({
638
+ name: name12,
639
+ message: `${contextPrefix}: Value: ${JSON.stringify(value)}.
640
+ Error message: ${getErrorMessage(cause)}`,
641
+ cause
642
+ });
643
+ this[_a13] = true;
644
+ this.value = value;
645
+ this.context = context;
646
+ }
647
+ static isInstance(error) {
648
+ return AISDKError.hasMarker(error, marker13);
649
+ }
650
+ /**
651
+ * Wraps an error into a TypeValidationError.
652
+ * If the cause is already a TypeValidationError with the same value and context, it returns the cause.
653
+ * Otherwise, it creates a new TypeValidationError.
654
+ *
655
+ * @param {Object} params - The parameters for wrapping the error.
656
+ * @param {unknown} params.value - The value that failed validation.
657
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
658
+ * @param {TypeValidationContext} params.context - Optional context about what is being validated.
659
+ * @returns {TypeValidationError} A TypeValidationError instance.
660
+ */
661
+ static wrap({
662
+ value,
663
+ cause,
664
+ context
665
+ }) {
666
+ var _a152, _b152, _c;
667
+ if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a152 = cause.context) == null ? void 0 : _a152.field) === (context == null ? void 0 : context.field) && ((_b152 = cause.context) == null ? void 0 : _b152.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) {
668
+ return cause;
669
+ }
670
+ return new _TypeValidationError({ value, cause, context });
671
+ }
672
+ };
673
+ var name13 = "AI_UnsupportedFunctionalityError";
674
+ var marker14 = `vercel.ai.error.${name13}`;
675
+ var symbol14 = Symbol.for(marker14);
676
+ var _a14;
677
+ var _b14;
678
+ var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {
679
+ constructor({
680
+ functionality,
681
+ message = `'${functionality}' functionality not supported.`
682
+ }) {
683
+ super({ name: name13, message });
684
+ this[_a14] = true;
685
+ this.functionality = functionality;
686
+ }
687
+ static isInstance(error) {
688
+ return AISDKError.hasMarker(error, marker14);
689
+ }
690
+ };
691
+
692
+ // ../../node_modules/.pnpm/@ai-sdk+provider-utils@4.0.19_zod@4.1.13/node_modules/@ai-sdk/provider-utils/dist/index.mjs
693
+ import * as z42 from "zod/v4";
694
+ import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
695
+ import { ZodFirstPartyTypeKind } from "zod/v3";
696
+ import {
697
+ ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2
698
+ } from "zod/v3";
699
+
700
+ // ../../node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js
701
+ var ParseError = class extends Error {
702
+ constructor(message, options) {
703
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
704
+ }
705
+ };
706
+ function noop(_arg) {
707
+ }
708
+ function createParser(callbacks) {
709
+ if (typeof callbacks == "function")
710
+ throw new TypeError(
711
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
712
+ );
713
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
714
+ let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
715
+ function feed(newChunk) {
716
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
717
+ for (const line of complete)
718
+ parseLine(line);
719
+ incompleteLine = incomplete, isFirstChunk = false;
720
+ }
721
+ function parseLine(line) {
722
+ if (line === "") {
723
+ dispatchEvent();
724
+ return;
725
+ }
726
+ if (line.startsWith(":")) {
727
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
728
+ return;
729
+ }
730
+ const fieldSeparatorIndex = line.indexOf(":");
731
+ if (fieldSeparatorIndex !== -1) {
732
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
733
+ processField(field, value, line);
734
+ return;
735
+ }
736
+ processField(line, "", line);
737
+ }
738
+ function processField(field, value, line) {
739
+ switch (field) {
740
+ case "event":
741
+ eventType = value;
742
+ break;
743
+ case "data":
744
+ data = `${data}${value}
745
+ `;
746
+ break;
747
+ case "id":
748
+ id = value.includes("\0") ? void 0 : value;
749
+ break;
750
+ case "retry":
751
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
752
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
753
+ type: "invalid-retry",
754
+ value,
755
+ line
756
+ })
757
+ );
758
+ break;
759
+ default:
760
+ onError(
761
+ new ParseError(
762
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
763
+ { type: "unknown-field", field, value, line }
764
+ )
765
+ );
766
+ break;
767
+ }
768
+ }
769
+ function dispatchEvent() {
770
+ data.length > 0 && onEvent({
771
+ id,
772
+ event: eventType || void 0,
773
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
774
+ // then remove the last character from the data buffer.
775
+ data: data.endsWith(`
776
+ `) ? data.slice(0, -1) : data
777
+ }), id = void 0, data = "", eventType = "";
778
+ }
779
+ function reset(options = {}) {
780
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
781
+ }
782
+ return { feed, reset };
783
+ }
784
+ function splitLines(chunk) {
785
+ const lines = [];
786
+ let incompleteLine = "", searchIndex = 0;
787
+ for (; searchIndex < chunk.length; ) {
788
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
789
+ `, searchIndex);
790
+ let lineEnd = -1;
791
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
792
+ incompleteLine = chunk.slice(searchIndex);
793
+ break;
794
+ } else {
795
+ const line = chunk.slice(searchIndex, lineEnd);
796
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
797
+ ` && searchIndex++;
798
+ }
799
+ }
800
+ return [lines, incompleteLine];
801
+ }
802
+
803
+ // ../../node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js
804
+ var EventSourceParserStream = class extends TransformStream {
805
+ constructor({ onError, onRetry, onComment } = {}) {
806
+ let parser;
807
+ super({
808
+ start(controller) {
809
+ parser = createParser({
810
+ onEvent: (event) => {
811
+ controller.enqueue(event);
812
+ },
813
+ onError(error) {
814
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
815
+ },
816
+ onRetry,
817
+ onComment
818
+ });
819
+ },
820
+ transform(chunk) {
821
+ parser.feed(chunk);
822
+ }
823
+ });
824
+ }
825
+ };
826
+
827
+ // ../../node_modules/.pnpm/@ai-sdk+provider-utils@4.0.19_zod@4.1.13/node_modules/@ai-sdk/provider-utils/dist/index.mjs
828
+ var { btoa: btoa2, atob } = globalThis;
829
+ var name14 = "AI_DownloadError";
830
+ var marker15 = `vercel.ai.error.${name14}`;
831
+ var symbol15 = Symbol.for(marker15);
832
+ var _a15;
833
+ var _b15;
834
+ var DownloadError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) {
835
+ constructor({
836
+ url,
837
+ statusCode,
838
+ statusText,
839
+ cause,
840
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
841
+ }) {
842
+ super({ name: name14, message, cause });
843
+ this[_a15] = true;
844
+ this.url = url;
845
+ this.statusCode = statusCode;
846
+ this.statusText = statusText;
847
+ }
848
+ static isInstance(error) {
849
+ return AISDKError.hasMarker(error, marker15);
850
+ }
851
+ };
852
+ var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
853
+ var createIdGenerator = ({
854
+ prefix,
855
+ size = 16,
856
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
857
+ separator = "-"
858
+ } = {}) => {
859
+ const generator = () => {
860
+ const alphabetLength = alphabet.length;
861
+ const chars = new Array(size);
862
+ for (let i = 0; i < size; i++) {
863
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
864
+ }
865
+ return chars.join("");
866
+ };
867
+ if (prefix == null) {
868
+ return generator;
869
+ }
870
+ if (alphabet.includes(separator)) {
871
+ throw new InvalidArgumentError({
872
+ argument: "separator",
873
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
874
+ });
875
+ }
876
+ return () => `${prefix}${separator}${generator()}`;
877
+ };
878
+ var generateId = createIdGenerator();
879
+ function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
880
+ var _a23, _b23, _c;
881
+ if (globalThisAny.window) {
882
+ return `runtime/browser`;
883
+ }
884
+ if ((_a23 = globalThisAny.navigator) == null ? void 0 : _a23.userAgent) {
885
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
886
+ }
887
+ if ((_c = (_b23 = globalThisAny.process) == null ? void 0 : _b23.versions) == null ? void 0 : _c.node) {
888
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
889
+ }
890
+ if (globalThisAny.EdgeRuntime) {
891
+ return `runtime/vercel-edge`;
892
+ }
893
+ return "runtime/unknown";
894
+ }
895
+ function normalizeHeaders(headers) {
896
+ if (headers == null) {
897
+ return {};
898
+ }
899
+ const normalized = {};
900
+ if (headers instanceof Headers) {
901
+ headers.forEach((value, key) => {
902
+ normalized[key.toLowerCase()] = value;
903
+ });
904
+ } else {
905
+ if (!Array.isArray(headers)) {
906
+ headers = Object.entries(headers);
907
+ }
908
+ for (const [key, value] of headers) {
909
+ if (value != null) {
910
+ normalized[key.toLowerCase()] = value;
911
+ }
912
+ }
913
+ }
914
+ return normalized;
915
+ }
916
+ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
917
+ const normalizedHeaders = new Headers(normalizeHeaders(headers));
918
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
919
+ normalizedHeaders.set(
920
+ "user-agent",
921
+ [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
345
922
  );
346
- const { url, headers } = options;
347
- const client = await createMCPClient({
348
- transport: {
349
- type: "http",
350
- url,
351
- headers
923
+ return Object.fromEntries(normalizedHeaders.entries());
924
+ }
925
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
926
+ var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
927
+ function _parse(text) {
928
+ const obj = JSON.parse(text);
929
+ if (obj === null || typeof obj !== "object") {
930
+ return obj;
931
+ }
932
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
933
+ return obj;
934
+ }
935
+ return filter(obj);
936
+ }
937
+ function filter(obj) {
938
+ let next = [obj];
939
+ while (next.length) {
940
+ const nodes = next;
941
+ next = [];
942
+ for (const node of nodes) {
943
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
944
+ throw new SyntaxError("Object contains forbidden prototype property");
945
+ }
946
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
947
+ throw new SyntaxError("Object contains forbidden prototype property");
948
+ }
949
+ for (const key in node) {
950
+ const value = node[key];
951
+ if (value && typeof value === "object") {
952
+ next.push(value);
953
+ }
954
+ }
955
+ }
956
+ }
957
+ return obj;
958
+ }
959
+ function secureJsonParse(text) {
960
+ const { stackTraceLimit } = Error;
961
+ try {
962
+ Error.stackTraceLimit = 0;
963
+ } catch (e) {
964
+ return _parse(text);
965
+ }
966
+ try {
967
+ return _parse(text);
968
+ } finally {
969
+ Error.stackTraceLimit = stackTraceLimit;
970
+ }
971
+ }
972
+ function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
973
+ if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
974
+ jsonSchema2.additionalProperties = false;
975
+ const { properties } = jsonSchema2;
976
+ if (properties != null) {
977
+ for (const key of Object.keys(properties)) {
978
+ properties[key] = visit(properties[key]);
979
+ }
980
+ }
981
+ }
982
+ if (jsonSchema2.items != null) {
983
+ jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
984
+ }
985
+ if (jsonSchema2.anyOf != null) {
986
+ jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
987
+ }
988
+ if (jsonSchema2.allOf != null) {
989
+ jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
990
+ }
991
+ if (jsonSchema2.oneOf != null) {
992
+ jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
993
+ }
994
+ const { definitions } = jsonSchema2;
995
+ if (definitions != null) {
996
+ for (const key of Object.keys(definitions)) {
997
+ definitions[key] = visit(definitions[key]);
998
+ }
999
+ }
1000
+ return jsonSchema2;
1001
+ }
1002
+ function visit(def) {
1003
+ if (typeof def === "boolean") return def;
1004
+ return addAdditionalPropertiesToJsonSchema(def);
1005
+ }
1006
+ var ignoreOverride = Symbol(
1007
+ "Let zodToJsonSchema decide on which parser to use"
1008
+ );
1009
+ var defaultOptions = {
1010
+ name: void 0,
1011
+ $refStrategy: "root",
1012
+ basePath: ["#"],
1013
+ effectStrategy: "input",
1014
+ pipeStrategy: "all",
1015
+ dateStrategy: "format:date-time",
1016
+ mapStrategy: "entries",
1017
+ removeAdditionalStrategy: "passthrough",
1018
+ allowedAdditionalProperties: true,
1019
+ rejectedAdditionalProperties: false,
1020
+ definitionPath: "definitions",
1021
+ strictUnions: false,
1022
+ definitions: {},
1023
+ errorMessages: false,
1024
+ patternStrategy: "escape",
1025
+ applyRegexFlags: false,
1026
+ emailStrategy: "format:email",
1027
+ base64Strategy: "contentEncoding:base64",
1028
+ nameStrategy: "ref"
1029
+ };
1030
+ var getDefaultOptions = (options) => typeof options === "string" ? {
1031
+ ...defaultOptions,
1032
+ name: options
1033
+ } : {
1034
+ ...defaultOptions,
1035
+ ...options
1036
+ };
1037
+ function parseAnyDef() {
1038
+ return {};
1039
+ }
1040
+ function parseArrayDef(def, refs) {
1041
+ var _a23, _b23, _c;
1042
+ const res = {
1043
+ type: "array"
1044
+ };
1045
+ if (((_a23 = def.type) == null ? void 0 : _a23._def) && ((_c = (_b23 = def.type) == null ? void 0 : _b23._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
1046
+ res.items = parseDef(def.type._def, {
1047
+ ...refs,
1048
+ currentPath: [...refs.currentPath, "items"]
1049
+ });
1050
+ }
1051
+ if (def.minLength) {
1052
+ res.minItems = def.minLength.value;
1053
+ }
1054
+ if (def.maxLength) {
1055
+ res.maxItems = def.maxLength.value;
1056
+ }
1057
+ if (def.exactLength) {
1058
+ res.minItems = def.exactLength.value;
1059
+ res.maxItems = def.exactLength.value;
1060
+ }
1061
+ return res;
1062
+ }
1063
+ function parseBigintDef(def) {
1064
+ const res = {
1065
+ type: "integer",
1066
+ format: "int64"
1067
+ };
1068
+ if (!def.checks) return res;
1069
+ for (const check of def.checks) {
1070
+ switch (check.kind) {
1071
+ case "min":
1072
+ if (check.inclusive) {
1073
+ res.minimum = check.value;
1074
+ } else {
1075
+ res.exclusiveMinimum = check.value;
1076
+ }
1077
+ break;
1078
+ case "max":
1079
+ if (check.inclusive) {
1080
+ res.maximum = check.value;
1081
+ } else {
1082
+ res.exclusiveMaximum = check.value;
1083
+ }
1084
+ break;
1085
+ case "multipleOf":
1086
+ res.multipleOf = check.value;
1087
+ break;
1088
+ }
1089
+ }
1090
+ return res;
1091
+ }
1092
+ function parseBooleanDef() {
1093
+ return { type: "boolean" };
1094
+ }
1095
+ function parseBrandedDef(_def, refs) {
1096
+ return parseDef(_def.type._def, refs);
1097
+ }
1098
+ var parseCatchDef = (def, refs) => {
1099
+ return parseDef(def.innerType._def, refs);
1100
+ };
1101
+ function parseDateDef(def, refs, overrideDateStrategy) {
1102
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
1103
+ if (Array.isArray(strategy)) {
1104
+ return {
1105
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
1106
+ };
1107
+ }
1108
+ switch (strategy) {
1109
+ case "string":
1110
+ case "format:date-time":
1111
+ return {
1112
+ type: "string",
1113
+ format: "date-time"
1114
+ };
1115
+ case "format:date":
1116
+ return {
1117
+ type: "string",
1118
+ format: "date"
1119
+ };
1120
+ case "integer":
1121
+ return integerDateParser(def);
1122
+ }
1123
+ }
1124
+ var integerDateParser = (def) => {
1125
+ const res = {
1126
+ type: "integer",
1127
+ format: "unix-time"
1128
+ };
1129
+ for (const check of def.checks) {
1130
+ switch (check.kind) {
1131
+ case "min":
1132
+ res.minimum = check.value;
1133
+ break;
1134
+ case "max":
1135
+ res.maximum = check.value;
1136
+ break;
1137
+ }
1138
+ }
1139
+ return res;
1140
+ };
1141
+ function parseDefaultDef(_def, refs) {
1142
+ return {
1143
+ ...parseDef(_def.innerType._def, refs),
1144
+ default: _def.defaultValue()
1145
+ };
1146
+ }
1147
+ function parseEffectsDef(_def, refs) {
1148
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
1149
+ }
1150
+ function parseEnumDef(def) {
1151
+ return {
1152
+ type: "string",
1153
+ enum: Array.from(def.values)
1154
+ };
1155
+ }
1156
+ var isJsonSchema7AllOfType = (type) => {
1157
+ if ("type" in type && type.type === "string") return false;
1158
+ return "allOf" in type;
1159
+ };
1160
+ function parseIntersectionDef(def, refs) {
1161
+ const allOf = [
1162
+ parseDef(def.left._def, {
1163
+ ...refs,
1164
+ currentPath: [...refs.currentPath, "allOf", "0"]
1165
+ }),
1166
+ parseDef(def.right._def, {
1167
+ ...refs,
1168
+ currentPath: [...refs.currentPath, "allOf", "1"]
1169
+ })
1170
+ ].filter((x) => !!x);
1171
+ const mergedAllOf = [];
1172
+ allOf.forEach((schema) => {
1173
+ if (isJsonSchema7AllOfType(schema)) {
1174
+ mergedAllOf.push(...schema.allOf);
1175
+ } else {
1176
+ let nestedSchema = schema;
1177
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
1178
+ const { additionalProperties, ...rest } = schema;
1179
+ nestedSchema = rest;
1180
+ }
1181
+ mergedAllOf.push(nestedSchema);
352
1182
  }
353
1183
  });
354
- return client;
1184
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
355
1185
  }
356
-
357
- // src/core/base.ts
358
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
359
- import { z as z6 } from "zod";
1186
+ function parseLiteralDef(def) {
1187
+ const parsedType = typeof def.value;
1188
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
1189
+ return {
1190
+ type: Array.isArray(def.value) ? "array" : "object"
1191
+ };
1192
+ }
1193
+ return {
1194
+ type: parsedType === "bigint" ? "integer" : parsedType,
1195
+ const: def.value
1196
+ };
1197
+ }
1198
+ var emojiRegex = void 0;
1199
+ var zodPatterns = {
1200
+ /**
1201
+ * `c` was changed to `[cC]` to replicate /i flag
1202
+ */
1203
+ cuid: /^[cC][^\s-]{8,}$/,
1204
+ cuid2: /^[0-9a-z]+$/,
1205
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
1206
+ /**
1207
+ * `a-z` was added to replicate /i flag
1208
+ */
1209
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
1210
+ /**
1211
+ * Constructed a valid Unicode RegExp
1212
+ *
1213
+ * Lazily instantiate since this type of regex isn't supported
1214
+ * in all envs (e.g. React Native).
1215
+ *
1216
+ * See:
1217
+ * https://github.com/colinhacks/zod/issues/2433
1218
+ * Fix in Zod:
1219
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
1220
+ */
1221
+ emoji: () => {
1222
+ if (emojiRegex === void 0) {
1223
+ emojiRegex = RegExp(
1224
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
1225
+ "u"
1226
+ );
1227
+ }
1228
+ return emojiRegex;
1229
+ },
1230
+ /**
1231
+ * Unused
1232
+ */
1233
+ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
1234
+ /**
1235
+ * Unused
1236
+ */
1237
+ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
1238
+ ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
1239
+ /**
1240
+ * Unused
1241
+ */
1242
+ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
1243
+ ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
1244
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
1245
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
1246
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
1247
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1248
+ };
1249
+ function parseStringDef(def, refs) {
1250
+ const res = {
1251
+ type: "string"
1252
+ };
1253
+ if (def.checks) {
1254
+ for (const check of def.checks) {
1255
+ switch (check.kind) {
1256
+ case "min":
1257
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1258
+ break;
1259
+ case "max":
1260
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1261
+ break;
1262
+ case "email":
1263
+ switch (refs.emailStrategy) {
1264
+ case "format:email":
1265
+ addFormat(res, "email", check.message, refs);
1266
+ break;
1267
+ case "format:idn-email":
1268
+ addFormat(res, "idn-email", check.message, refs);
1269
+ break;
1270
+ case "pattern:zod":
1271
+ addPattern(res, zodPatterns.email, check.message, refs);
1272
+ break;
1273
+ }
1274
+ break;
1275
+ case "url":
1276
+ addFormat(res, "uri", check.message, refs);
1277
+ break;
1278
+ case "uuid":
1279
+ addFormat(res, "uuid", check.message, refs);
1280
+ break;
1281
+ case "regex":
1282
+ addPattern(res, check.regex, check.message, refs);
1283
+ break;
1284
+ case "cuid":
1285
+ addPattern(res, zodPatterns.cuid, check.message, refs);
1286
+ break;
1287
+ case "cuid2":
1288
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
1289
+ break;
1290
+ case "startsWith":
1291
+ addPattern(
1292
+ res,
1293
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
1294
+ check.message,
1295
+ refs
1296
+ );
1297
+ break;
1298
+ case "endsWith":
1299
+ addPattern(
1300
+ res,
1301
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
1302
+ check.message,
1303
+ refs
1304
+ );
1305
+ break;
1306
+ case "datetime":
1307
+ addFormat(res, "date-time", check.message, refs);
1308
+ break;
1309
+ case "date":
1310
+ addFormat(res, "date", check.message, refs);
1311
+ break;
1312
+ case "time":
1313
+ addFormat(res, "time", check.message, refs);
1314
+ break;
1315
+ case "duration":
1316
+ addFormat(res, "duration", check.message, refs);
1317
+ break;
1318
+ case "length":
1319
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1320
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1321
+ break;
1322
+ case "includes": {
1323
+ addPattern(
1324
+ res,
1325
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
1326
+ check.message,
1327
+ refs
1328
+ );
1329
+ break;
1330
+ }
1331
+ case "ip": {
1332
+ if (check.version !== "v6") {
1333
+ addFormat(res, "ipv4", check.message, refs);
1334
+ }
1335
+ if (check.version !== "v4") {
1336
+ addFormat(res, "ipv6", check.message, refs);
1337
+ }
1338
+ break;
1339
+ }
1340
+ case "base64url":
1341
+ addPattern(res, zodPatterns.base64url, check.message, refs);
1342
+ break;
1343
+ case "jwt":
1344
+ addPattern(res, zodPatterns.jwt, check.message, refs);
1345
+ break;
1346
+ case "cidr": {
1347
+ if (check.version !== "v6") {
1348
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1349
+ }
1350
+ if (check.version !== "v4") {
1351
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1352
+ }
1353
+ break;
1354
+ }
1355
+ case "emoji":
1356
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
1357
+ break;
1358
+ case "ulid": {
1359
+ addPattern(res, zodPatterns.ulid, check.message, refs);
1360
+ break;
1361
+ }
1362
+ case "base64": {
1363
+ switch (refs.base64Strategy) {
1364
+ case "format:binary": {
1365
+ addFormat(res, "binary", check.message, refs);
1366
+ break;
1367
+ }
1368
+ case "contentEncoding:base64": {
1369
+ res.contentEncoding = "base64";
1370
+ break;
1371
+ }
1372
+ case "pattern:zod": {
1373
+ addPattern(res, zodPatterns.base64, check.message, refs);
1374
+ break;
1375
+ }
1376
+ }
1377
+ break;
1378
+ }
1379
+ case "nanoid": {
1380
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
1381
+ }
1382
+ case "toLowerCase":
1383
+ case "toUpperCase":
1384
+ case "trim":
1385
+ break;
1386
+ default:
1387
+ /* @__PURE__ */ ((_) => {
1388
+ })(check);
1389
+ }
1390
+ }
1391
+ }
1392
+ return res;
1393
+ }
1394
+ function escapeLiteralCheckValue(literal, refs) {
1395
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1396
+ }
1397
+ var ALPHA_NUMERIC = new Set(
1398
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1399
+ );
1400
+ function escapeNonAlphaNumeric(source) {
1401
+ let result = "";
1402
+ for (let i = 0; i < source.length; i++) {
1403
+ if (!ALPHA_NUMERIC.has(source[i])) {
1404
+ result += "\\";
1405
+ }
1406
+ result += source[i];
1407
+ }
1408
+ return result;
1409
+ }
1410
+ function addFormat(schema, value, message, refs) {
1411
+ var _a23;
1412
+ if (schema.format || ((_a23 = schema.anyOf) == null ? void 0 : _a23.some((x) => x.format))) {
1413
+ if (!schema.anyOf) {
1414
+ schema.anyOf = [];
1415
+ }
1416
+ if (schema.format) {
1417
+ schema.anyOf.push({
1418
+ format: schema.format
1419
+ });
1420
+ delete schema.format;
1421
+ }
1422
+ schema.anyOf.push({
1423
+ format: value,
1424
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
1425
+ });
1426
+ } else {
1427
+ schema.format = value;
1428
+ }
1429
+ }
1430
+ function addPattern(schema, regex, message, refs) {
1431
+ var _a23;
1432
+ if (schema.pattern || ((_a23 = schema.allOf) == null ? void 0 : _a23.some((x) => x.pattern))) {
1433
+ if (!schema.allOf) {
1434
+ schema.allOf = [];
1435
+ }
1436
+ if (schema.pattern) {
1437
+ schema.allOf.push({
1438
+ pattern: schema.pattern
1439
+ });
1440
+ delete schema.pattern;
1441
+ }
1442
+ schema.allOf.push({
1443
+ pattern: stringifyRegExpWithFlags(regex, refs),
1444
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
1445
+ });
1446
+ } else {
1447
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
1448
+ }
1449
+ }
1450
+ function stringifyRegExpWithFlags(regex, refs) {
1451
+ var _a23;
1452
+ if (!refs.applyRegexFlags || !regex.flags) {
1453
+ return regex.source;
1454
+ }
1455
+ const flags = {
1456
+ i: regex.flags.includes("i"),
1457
+ // Case-insensitive
1458
+ m: regex.flags.includes("m"),
1459
+ // `^` and `$` matches adjacent to newline characters
1460
+ s: regex.flags.includes("s")
1461
+ // `.` matches newlines
1462
+ };
1463
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
1464
+ let pattern = "";
1465
+ let isEscaped = false;
1466
+ let inCharGroup = false;
1467
+ let inCharRange = false;
1468
+ for (let i = 0; i < source.length; i++) {
1469
+ if (isEscaped) {
1470
+ pattern += source[i];
1471
+ isEscaped = false;
1472
+ continue;
1473
+ }
1474
+ if (flags.i) {
1475
+ if (inCharGroup) {
1476
+ if (source[i].match(/[a-z]/)) {
1477
+ if (inCharRange) {
1478
+ pattern += source[i];
1479
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1480
+ inCharRange = false;
1481
+ } else if (source[i + 1] === "-" && ((_a23 = source[i + 2]) == null ? void 0 : _a23.match(/[a-z]/))) {
1482
+ pattern += source[i];
1483
+ inCharRange = true;
1484
+ } else {
1485
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1486
+ }
1487
+ continue;
1488
+ }
1489
+ } else if (source[i].match(/[a-z]/)) {
1490
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1491
+ continue;
1492
+ }
1493
+ }
1494
+ if (flags.m) {
1495
+ if (source[i] === "^") {
1496
+ pattern += `(^|(?<=[\r
1497
+ ]))`;
1498
+ continue;
1499
+ } else if (source[i] === "$") {
1500
+ pattern += `($|(?=[\r
1501
+ ]))`;
1502
+ continue;
1503
+ }
1504
+ }
1505
+ if (flags.s && source[i] === ".") {
1506
+ pattern += inCharGroup ? `${source[i]}\r
1507
+ ` : `[${source[i]}\r
1508
+ ]`;
1509
+ continue;
1510
+ }
1511
+ pattern += source[i];
1512
+ if (source[i] === "\\") {
1513
+ isEscaped = true;
1514
+ } else if (inCharGroup && source[i] === "]") {
1515
+ inCharGroup = false;
1516
+ } else if (!inCharGroup && source[i] === "[") {
1517
+ inCharGroup = true;
1518
+ }
1519
+ }
1520
+ try {
1521
+ new RegExp(pattern);
1522
+ } catch (e) {
1523
+ console.warn(
1524
+ `Could not convert regex pattern at ${refs.currentPath.join(
1525
+ "/"
1526
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
1527
+ );
1528
+ return regex.source;
1529
+ }
1530
+ return pattern;
1531
+ }
1532
+ function parseRecordDef(def, refs) {
1533
+ var _a23, _b23, _c, _d, _e, _f;
1534
+ const schema = {
1535
+ type: "object",
1536
+ additionalProperties: (_a23 = parseDef(def.valueType._def, {
1537
+ ...refs,
1538
+ currentPath: [...refs.currentPath, "additionalProperties"]
1539
+ })) != null ? _a23 : refs.allowedAdditionalProperties
1540
+ };
1541
+ if (((_b23 = def.keyType) == null ? void 0 : _b23._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1542
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1543
+ return {
1544
+ ...schema,
1545
+ propertyNames: keyType
1546
+ };
1547
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1548
+ return {
1549
+ ...schema,
1550
+ propertyNames: {
1551
+ enum: def.keyType._def.values
1552
+ }
1553
+ };
1554
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1555
+ const { type, ...keyType } = parseBrandedDef(
1556
+ def.keyType._def,
1557
+ refs
1558
+ );
1559
+ return {
1560
+ ...schema,
1561
+ propertyNames: keyType
1562
+ };
1563
+ }
1564
+ return schema;
1565
+ }
1566
+ function parseMapDef(def, refs) {
1567
+ if (refs.mapStrategy === "record") {
1568
+ return parseRecordDef(def, refs);
1569
+ }
1570
+ const keys = parseDef(def.keyType._def, {
1571
+ ...refs,
1572
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1573
+ }) || parseAnyDef();
1574
+ const values = parseDef(def.valueType._def, {
1575
+ ...refs,
1576
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1577
+ }) || parseAnyDef();
1578
+ return {
1579
+ type: "array",
1580
+ maxItems: 125,
1581
+ items: {
1582
+ type: "array",
1583
+ items: [keys, values],
1584
+ minItems: 2,
1585
+ maxItems: 2
1586
+ }
1587
+ };
1588
+ }
1589
+ function parseNativeEnumDef(def) {
1590
+ const object = def.values;
1591
+ const actualKeys = Object.keys(def.values).filter((key) => {
1592
+ return typeof object[object[key]] !== "number";
1593
+ });
1594
+ const actualValues = actualKeys.map((key) => object[key]);
1595
+ const parsedTypes = Array.from(
1596
+ new Set(actualValues.map((values) => typeof values))
1597
+ );
1598
+ return {
1599
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1600
+ enum: actualValues
1601
+ };
1602
+ }
1603
+ function parseNeverDef() {
1604
+ return { not: parseAnyDef() };
1605
+ }
1606
+ function parseNullDef() {
1607
+ return {
1608
+ type: "null"
1609
+ };
1610
+ }
1611
+ var primitiveMappings = {
1612
+ ZodString: "string",
1613
+ ZodNumber: "number",
1614
+ ZodBigInt: "integer",
1615
+ ZodBoolean: "boolean",
1616
+ ZodNull: "null"
1617
+ };
1618
+ function parseUnionDef(def, refs) {
1619
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1620
+ if (options.every(
1621
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1622
+ )) {
1623
+ const types = options.reduce((types2, x) => {
1624
+ const type = primitiveMappings[x._def.typeName];
1625
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1626
+ }, []);
1627
+ return {
1628
+ type: types.length > 1 ? types : types[0]
1629
+ };
1630
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1631
+ const types = options.reduce(
1632
+ (acc, x) => {
1633
+ const type = typeof x._def.value;
1634
+ switch (type) {
1635
+ case "string":
1636
+ case "number":
1637
+ case "boolean":
1638
+ return [...acc, type];
1639
+ case "bigint":
1640
+ return [...acc, "integer"];
1641
+ case "object":
1642
+ if (x._def.value === null) return [...acc, "null"];
1643
+ case "symbol":
1644
+ case "undefined":
1645
+ case "function":
1646
+ default:
1647
+ return acc;
1648
+ }
1649
+ },
1650
+ []
1651
+ );
1652
+ if (types.length === options.length) {
1653
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1654
+ return {
1655
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1656
+ enum: options.reduce(
1657
+ (acc, x) => {
1658
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1659
+ },
1660
+ []
1661
+ )
1662
+ };
1663
+ }
1664
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1665
+ return {
1666
+ type: "string",
1667
+ enum: options.reduce(
1668
+ (acc, x) => [
1669
+ ...acc,
1670
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1671
+ ],
1672
+ []
1673
+ )
1674
+ };
1675
+ }
1676
+ return asAnyOf(def, refs);
1677
+ }
1678
+ var asAnyOf = (def, refs) => {
1679
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1680
+ (x, i) => parseDef(x._def, {
1681
+ ...refs,
1682
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1683
+ })
1684
+ ).filter(
1685
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1686
+ );
1687
+ return anyOf.length ? { anyOf } : void 0;
1688
+ };
1689
+ function parseNullableDef(def, refs) {
1690
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1691
+ def.innerType._def.typeName
1692
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1693
+ return {
1694
+ type: [
1695
+ primitiveMappings[def.innerType._def.typeName],
1696
+ "null"
1697
+ ]
1698
+ };
1699
+ }
1700
+ const base = parseDef(def.innerType._def, {
1701
+ ...refs,
1702
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1703
+ });
1704
+ return base && { anyOf: [base, { type: "null" }] };
1705
+ }
1706
+ function parseNumberDef(def) {
1707
+ const res = {
1708
+ type: "number"
1709
+ };
1710
+ if (!def.checks) return res;
1711
+ for (const check of def.checks) {
1712
+ switch (check.kind) {
1713
+ case "int":
1714
+ res.type = "integer";
1715
+ break;
1716
+ case "min":
1717
+ if (check.inclusive) {
1718
+ res.minimum = check.value;
1719
+ } else {
1720
+ res.exclusiveMinimum = check.value;
1721
+ }
1722
+ break;
1723
+ case "max":
1724
+ if (check.inclusive) {
1725
+ res.maximum = check.value;
1726
+ } else {
1727
+ res.exclusiveMaximum = check.value;
1728
+ }
1729
+ break;
1730
+ case "multipleOf":
1731
+ res.multipleOf = check.value;
1732
+ break;
1733
+ }
1734
+ }
1735
+ return res;
1736
+ }
1737
+ function parseObjectDef(def, refs) {
1738
+ const result = {
1739
+ type: "object",
1740
+ properties: {}
1741
+ };
1742
+ const required = [];
1743
+ const shape = def.shape();
1744
+ for (const propName in shape) {
1745
+ let propDef = shape[propName];
1746
+ if (propDef === void 0 || propDef._def === void 0) {
1747
+ continue;
1748
+ }
1749
+ const propOptional = safeIsOptional(propDef);
1750
+ const parsedDef = parseDef(propDef._def, {
1751
+ ...refs,
1752
+ currentPath: [...refs.currentPath, "properties", propName],
1753
+ propertyPath: [...refs.currentPath, "properties", propName]
1754
+ });
1755
+ if (parsedDef === void 0) {
1756
+ continue;
1757
+ }
1758
+ result.properties[propName] = parsedDef;
1759
+ if (!propOptional) {
1760
+ required.push(propName);
1761
+ }
1762
+ }
1763
+ if (required.length) {
1764
+ result.required = required;
1765
+ }
1766
+ const additionalProperties = decideAdditionalProperties(def, refs);
1767
+ if (additionalProperties !== void 0) {
1768
+ result.additionalProperties = additionalProperties;
1769
+ }
1770
+ return result;
1771
+ }
1772
+ function decideAdditionalProperties(def, refs) {
1773
+ if (def.catchall._def.typeName !== "ZodNever") {
1774
+ return parseDef(def.catchall._def, {
1775
+ ...refs,
1776
+ currentPath: [...refs.currentPath, "additionalProperties"]
1777
+ });
1778
+ }
1779
+ switch (def.unknownKeys) {
1780
+ case "passthrough":
1781
+ return refs.allowedAdditionalProperties;
1782
+ case "strict":
1783
+ return refs.rejectedAdditionalProperties;
1784
+ case "strip":
1785
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1786
+ }
1787
+ }
1788
+ function safeIsOptional(schema) {
1789
+ try {
1790
+ return schema.isOptional();
1791
+ } catch (e) {
1792
+ return true;
1793
+ }
1794
+ }
1795
+ var parseOptionalDef = (def, refs) => {
1796
+ var _a23;
1797
+ if (refs.currentPath.toString() === ((_a23 = refs.propertyPath) == null ? void 0 : _a23.toString())) {
1798
+ return parseDef(def.innerType._def, refs);
1799
+ }
1800
+ const innerSchema = parseDef(def.innerType._def, {
1801
+ ...refs,
1802
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1803
+ });
1804
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1805
+ };
1806
+ var parsePipelineDef = (def, refs) => {
1807
+ if (refs.pipeStrategy === "input") {
1808
+ return parseDef(def.in._def, refs);
1809
+ } else if (refs.pipeStrategy === "output") {
1810
+ return parseDef(def.out._def, refs);
1811
+ }
1812
+ const a = parseDef(def.in._def, {
1813
+ ...refs,
1814
+ currentPath: [...refs.currentPath, "allOf", "0"]
1815
+ });
1816
+ const b = parseDef(def.out._def, {
1817
+ ...refs,
1818
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1819
+ });
1820
+ return {
1821
+ allOf: [a, b].filter((x) => x !== void 0)
1822
+ };
1823
+ };
1824
+ function parsePromiseDef(def, refs) {
1825
+ return parseDef(def.type._def, refs);
1826
+ }
1827
+ function parseSetDef(def, refs) {
1828
+ const items = parseDef(def.valueType._def, {
1829
+ ...refs,
1830
+ currentPath: [...refs.currentPath, "items"]
1831
+ });
1832
+ const schema = {
1833
+ type: "array",
1834
+ uniqueItems: true,
1835
+ items
1836
+ };
1837
+ if (def.minSize) {
1838
+ schema.minItems = def.minSize.value;
1839
+ }
1840
+ if (def.maxSize) {
1841
+ schema.maxItems = def.maxSize.value;
1842
+ }
1843
+ return schema;
1844
+ }
1845
+ function parseTupleDef(def, refs) {
1846
+ if (def.rest) {
1847
+ return {
1848
+ type: "array",
1849
+ minItems: def.items.length,
1850
+ items: def.items.map(
1851
+ (x, i) => parseDef(x._def, {
1852
+ ...refs,
1853
+ currentPath: [...refs.currentPath, "items", `${i}`]
1854
+ })
1855
+ ).reduce(
1856
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1857
+ []
1858
+ ),
1859
+ additionalItems: parseDef(def.rest._def, {
1860
+ ...refs,
1861
+ currentPath: [...refs.currentPath, "additionalItems"]
1862
+ })
1863
+ };
1864
+ } else {
1865
+ return {
1866
+ type: "array",
1867
+ minItems: def.items.length,
1868
+ maxItems: def.items.length,
1869
+ items: def.items.map(
1870
+ (x, i) => parseDef(x._def, {
1871
+ ...refs,
1872
+ currentPath: [...refs.currentPath, "items", `${i}`]
1873
+ })
1874
+ ).reduce(
1875
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1876
+ []
1877
+ )
1878
+ };
1879
+ }
1880
+ }
1881
+ function parseUndefinedDef() {
1882
+ return {
1883
+ not: parseAnyDef()
1884
+ };
1885
+ }
1886
+ function parseUnknownDef() {
1887
+ return parseAnyDef();
1888
+ }
1889
+ var parseReadonlyDef = (def, refs) => {
1890
+ return parseDef(def.innerType._def, refs);
1891
+ };
1892
+ var selectParser = (def, typeName, refs) => {
1893
+ switch (typeName) {
1894
+ case ZodFirstPartyTypeKind3.ZodString:
1895
+ return parseStringDef(def, refs);
1896
+ case ZodFirstPartyTypeKind3.ZodNumber:
1897
+ return parseNumberDef(def);
1898
+ case ZodFirstPartyTypeKind3.ZodObject:
1899
+ return parseObjectDef(def, refs);
1900
+ case ZodFirstPartyTypeKind3.ZodBigInt:
1901
+ return parseBigintDef(def);
1902
+ case ZodFirstPartyTypeKind3.ZodBoolean:
1903
+ return parseBooleanDef();
1904
+ case ZodFirstPartyTypeKind3.ZodDate:
1905
+ return parseDateDef(def, refs);
1906
+ case ZodFirstPartyTypeKind3.ZodUndefined:
1907
+ return parseUndefinedDef();
1908
+ case ZodFirstPartyTypeKind3.ZodNull:
1909
+ return parseNullDef();
1910
+ case ZodFirstPartyTypeKind3.ZodArray:
1911
+ return parseArrayDef(def, refs);
1912
+ case ZodFirstPartyTypeKind3.ZodUnion:
1913
+ case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1914
+ return parseUnionDef(def, refs);
1915
+ case ZodFirstPartyTypeKind3.ZodIntersection:
1916
+ return parseIntersectionDef(def, refs);
1917
+ case ZodFirstPartyTypeKind3.ZodTuple:
1918
+ return parseTupleDef(def, refs);
1919
+ case ZodFirstPartyTypeKind3.ZodRecord:
1920
+ return parseRecordDef(def, refs);
1921
+ case ZodFirstPartyTypeKind3.ZodLiteral:
1922
+ return parseLiteralDef(def);
1923
+ case ZodFirstPartyTypeKind3.ZodEnum:
1924
+ return parseEnumDef(def);
1925
+ case ZodFirstPartyTypeKind3.ZodNativeEnum:
1926
+ return parseNativeEnumDef(def);
1927
+ case ZodFirstPartyTypeKind3.ZodNullable:
1928
+ return parseNullableDef(def, refs);
1929
+ case ZodFirstPartyTypeKind3.ZodOptional:
1930
+ return parseOptionalDef(def, refs);
1931
+ case ZodFirstPartyTypeKind3.ZodMap:
1932
+ return parseMapDef(def, refs);
1933
+ case ZodFirstPartyTypeKind3.ZodSet:
1934
+ return parseSetDef(def, refs);
1935
+ case ZodFirstPartyTypeKind3.ZodLazy:
1936
+ return () => def.getter()._def;
1937
+ case ZodFirstPartyTypeKind3.ZodPromise:
1938
+ return parsePromiseDef(def, refs);
1939
+ case ZodFirstPartyTypeKind3.ZodNaN:
1940
+ case ZodFirstPartyTypeKind3.ZodNever:
1941
+ return parseNeverDef();
1942
+ case ZodFirstPartyTypeKind3.ZodEffects:
1943
+ return parseEffectsDef(def, refs);
1944
+ case ZodFirstPartyTypeKind3.ZodAny:
1945
+ return parseAnyDef();
1946
+ case ZodFirstPartyTypeKind3.ZodUnknown:
1947
+ return parseUnknownDef();
1948
+ case ZodFirstPartyTypeKind3.ZodDefault:
1949
+ return parseDefaultDef(def, refs);
1950
+ case ZodFirstPartyTypeKind3.ZodBranded:
1951
+ return parseBrandedDef(def, refs);
1952
+ case ZodFirstPartyTypeKind3.ZodReadonly:
1953
+ return parseReadonlyDef(def, refs);
1954
+ case ZodFirstPartyTypeKind3.ZodCatch:
1955
+ return parseCatchDef(def, refs);
1956
+ case ZodFirstPartyTypeKind3.ZodPipeline:
1957
+ return parsePipelineDef(def, refs);
1958
+ case ZodFirstPartyTypeKind3.ZodFunction:
1959
+ case ZodFirstPartyTypeKind3.ZodVoid:
1960
+ case ZodFirstPartyTypeKind3.ZodSymbol:
1961
+ return void 0;
1962
+ default:
1963
+ return /* @__PURE__ */ ((_) => void 0)(typeName);
1964
+ }
1965
+ };
1966
+ var getRelativePath = (pathA, pathB) => {
1967
+ let i = 0;
1968
+ for (; i < pathA.length && i < pathB.length; i++) {
1969
+ if (pathA[i] !== pathB[i]) break;
1970
+ }
1971
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1972
+ };
1973
+ function parseDef(def, refs, forceResolution = false) {
1974
+ var _a23;
1975
+ const seenItem = refs.seen.get(def);
1976
+ if (refs.override) {
1977
+ const overrideResult = (_a23 = refs.override) == null ? void 0 : _a23.call(
1978
+ refs,
1979
+ def,
1980
+ refs,
1981
+ seenItem,
1982
+ forceResolution
1983
+ );
1984
+ if (overrideResult !== ignoreOverride) {
1985
+ return overrideResult;
1986
+ }
1987
+ }
1988
+ if (seenItem && !forceResolution) {
1989
+ const seenSchema = get$ref(seenItem, refs);
1990
+ if (seenSchema !== void 0) {
1991
+ return seenSchema;
1992
+ }
1993
+ }
1994
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1995
+ refs.seen.set(def, newItem);
1996
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1997
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1998
+ if (jsonSchema2) {
1999
+ addMeta(def, refs, jsonSchema2);
2000
+ }
2001
+ if (refs.postProcess) {
2002
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
2003
+ newItem.jsonSchema = jsonSchema2;
2004
+ return postProcessResult;
2005
+ }
2006
+ newItem.jsonSchema = jsonSchema2;
2007
+ return jsonSchema2;
2008
+ }
2009
+ var get$ref = (item, refs) => {
2010
+ switch (refs.$refStrategy) {
2011
+ case "root":
2012
+ return { $ref: item.path.join("/") };
2013
+ case "relative":
2014
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
2015
+ case "none":
2016
+ case "seen": {
2017
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
2018
+ console.warn(
2019
+ `Recursive reference detected at ${refs.currentPath.join(
2020
+ "/"
2021
+ )}! Defaulting to any`
2022
+ );
2023
+ return parseAnyDef();
2024
+ }
2025
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
2026
+ }
2027
+ }
2028
+ };
2029
+ var addMeta = (def, refs, jsonSchema2) => {
2030
+ if (def.description) {
2031
+ jsonSchema2.description = def.description;
2032
+ }
2033
+ return jsonSchema2;
2034
+ };
2035
+ var getRefs = (options) => {
2036
+ const _options = getDefaultOptions(options);
2037
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
2038
+ return {
2039
+ ..._options,
2040
+ currentPath,
2041
+ propertyPath: void 0,
2042
+ seen: new Map(
2043
+ Object.entries(_options.definitions).map(([name23, def]) => [
2044
+ def._def,
2045
+ {
2046
+ def: def._def,
2047
+ path: [..._options.basePath, _options.definitionPath, name23],
2048
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
2049
+ jsonSchema: void 0
2050
+ }
2051
+ ])
2052
+ )
2053
+ };
2054
+ };
2055
+ var zod3ToJsonSchema = (schema, options) => {
2056
+ var _a23;
2057
+ const refs = getRefs(options);
2058
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
2059
+ (acc, [name32, schema2]) => {
2060
+ var _a32;
2061
+ return {
2062
+ ...acc,
2063
+ [name32]: (_a32 = parseDef(
2064
+ schema2._def,
2065
+ {
2066
+ ...refs,
2067
+ currentPath: [...refs.basePath, refs.definitionPath, name32]
2068
+ },
2069
+ true
2070
+ )) != null ? _a32 : parseAnyDef()
2071
+ };
2072
+ },
2073
+ {}
2074
+ ) : void 0;
2075
+ const name23 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
2076
+ const main = (_a23 = parseDef(
2077
+ schema._def,
2078
+ name23 === void 0 ? refs : {
2079
+ ...refs,
2080
+ currentPath: [...refs.basePath, refs.definitionPath, name23]
2081
+ },
2082
+ false
2083
+ )) != null ? _a23 : parseAnyDef();
2084
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
2085
+ if (title !== void 0) {
2086
+ main.title = title;
2087
+ }
2088
+ const combined = name23 === void 0 ? definitions ? {
2089
+ ...main,
2090
+ [refs.definitionPath]: definitions
2091
+ } : main : {
2092
+ $ref: [
2093
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
2094
+ refs.definitionPath,
2095
+ name23
2096
+ ].join("/"),
2097
+ [refs.definitionPath]: {
2098
+ ...definitions,
2099
+ [name23]: main
2100
+ }
2101
+ };
2102
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
2103
+ return combined;
2104
+ };
2105
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
2106
+ function jsonSchema(jsonSchema2, {
2107
+ validate
2108
+ } = {}) {
2109
+ return {
2110
+ [schemaSymbol]: true,
2111
+ _type: void 0,
2112
+ // should never be used directly
2113
+ get jsonSchema() {
2114
+ if (typeof jsonSchema2 === "function") {
2115
+ jsonSchema2 = jsonSchema2();
2116
+ }
2117
+ return jsonSchema2;
2118
+ },
2119
+ validate
2120
+ };
2121
+ }
2122
+ function isSchema(value) {
2123
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
2124
+ }
2125
+ function asSchema(schema) {
2126
+ return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
2127
+ }
2128
+ function standardSchema(standardSchema2) {
2129
+ return jsonSchema(
2130
+ () => addAdditionalPropertiesToJsonSchema(
2131
+ standardSchema2["~standard"].jsonSchema.input({
2132
+ target: "draft-07"
2133
+ })
2134
+ ),
2135
+ {
2136
+ validate: async (value) => {
2137
+ const result = await standardSchema2["~standard"].validate(value);
2138
+ return "value" in result ? { success: true, value: result.value } : {
2139
+ success: false,
2140
+ error: new TypeValidationError({
2141
+ value,
2142
+ cause: result.issues
2143
+ })
2144
+ };
2145
+ }
2146
+ }
2147
+ );
2148
+ }
2149
+ function zod3Schema(zodSchema2, options) {
2150
+ var _a23;
2151
+ const useReferences = (_a23 = options == null ? void 0 : options.useReferences) != null ? _a23 : false;
2152
+ return jsonSchema(
2153
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
2154
+ () => zod3ToJsonSchema(zodSchema2, {
2155
+ $refStrategy: useReferences ? "root" : "none"
2156
+ }),
2157
+ {
2158
+ validate: async (value) => {
2159
+ const result = await zodSchema2.safeParseAsync(value);
2160
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2161
+ }
2162
+ }
2163
+ );
2164
+ }
2165
+ function zod4Schema(zodSchema2, options) {
2166
+ var _a23;
2167
+ const useReferences = (_a23 = options == null ? void 0 : options.useReferences) != null ? _a23 : false;
2168
+ return jsonSchema(
2169
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
2170
+ () => addAdditionalPropertiesToJsonSchema(
2171
+ z42.toJSONSchema(zodSchema2, {
2172
+ target: "draft-7",
2173
+ io: "input",
2174
+ reused: useReferences ? "ref" : "inline"
2175
+ })
2176
+ ),
2177
+ {
2178
+ validate: async (value) => {
2179
+ const result = await z42.safeParseAsync(zodSchema2, value);
2180
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2181
+ }
2182
+ }
2183
+ );
2184
+ }
2185
+ function isZod4Schema(zodSchema2) {
2186
+ return "_zod" in zodSchema2;
2187
+ }
2188
+ function zodSchema(zodSchema2, options) {
2189
+ if (isZod4Schema(zodSchema2)) {
2190
+ return zod4Schema(zodSchema2, options);
2191
+ } else {
2192
+ return zod3Schema(zodSchema2, options);
2193
+ }
2194
+ }
2195
+ async function safeValidateTypes({
2196
+ value,
2197
+ schema,
2198
+ context
2199
+ }) {
2200
+ const actualSchema = asSchema(schema);
2201
+ try {
2202
+ if (actualSchema.validate == null) {
2203
+ return { success: true, value, rawValue: value };
2204
+ }
2205
+ const result = await actualSchema.validate(value);
2206
+ if (result.success) {
2207
+ return { success: true, value: result.value, rawValue: value };
2208
+ }
2209
+ return {
2210
+ success: false,
2211
+ error: TypeValidationError.wrap({ value, cause: result.error, context }),
2212
+ rawValue: value
2213
+ };
2214
+ } catch (error) {
2215
+ return {
2216
+ success: false,
2217
+ error: TypeValidationError.wrap({ value, cause: error, context }),
2218
+ rawValue: value
2219
+ };
2220
+ }
2221
+ }
2222
+ async function safeParseJSON({
2223
+ text,
2224
+ schema
2225
+ }) {
2226
+ try {
2227
+ const value = secureJsonParse(text);
2228
+ if (schema == null) {
2229
+ return { success: true, value, rawValue: value };
2230
+ }
2231
+ return await safeValidateTypes({ value, schema });
2232
+ } catch (error) {
2233
+ return {
2234
+ success: false,
2235
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
2236
+ rawValue: void 0
2237
+ };
2238
+ }
2239
+ }
2240
+ function tool(tool2) {
2241
+ return tool2;
2242
+ }
2243
+ function dynamicTool(tool2) {
2244
+ return { ...tool2, type: "dynamic" };
2245
+ }
2246
+
2247
+ // ../../node_modules/.pnpm/@ai-sdk+mcp@1.0.25_zod@4.1.13/node_modules/@ai-sdk/mcp/dist/index.mjs
2248
+ import { z as z22 } from "zod/v4";
2249
+ import { z as z7 } from "zod/v4";
2250
+
2251
+ // ../../node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js
2252
+ var crypto;
2253
+ crypto = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL
2254
+ globalThis.crypto ?? // Node.js >18
2255
+ import("crypto").then((m) => m.webcrypto);
2256
+ async function getRandomValues(size) {
2257
+ return (await crypto).getRandomValues(new Uint8Array(size));
2258
+ }
2259
+ async function random(size) {
2260
+ const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
2261
+ const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
2262
+ let result = "";
2263
+ while (result.length < size) {
2264
+ const randomBytes = await getRandomValues(size - result.length);
2265
+ for (const randomByte of randomBytes) {
2266
+ if (randomByte < evenDistCutoff) {
2267
+ result += mask[randomByte % mask.length];
2268
+ }
2269
+ }
2270
+ }
2271
+ return result;
2272
+ }
2273
+ async function generateVerifier(length) {
2274
+ return await random(length);
2275
+ }
2276
+ async function generateChallenge(code_verifier) {
2277
+ const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
2278
+ return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
2279
+ }
2280
+ async function pkceChallenge(length) {
2281
+ if (!length)
2282
+ length = 43;
2283
+ if (length < 43 || length > 128) {
2284
+ throw `Expected a length between 43 and 128. Received ${length}.`;
2285
+ }
2286
+ const verifier = await generateVerifier(length);
2287
+ const challenge = await generateChallenge(verifier);
2288
+ return {
2289
+ code_verifier: verifier,
2290
+ code_challenge: challenge
2291
+ };
2292
+ }
2293
+
2294
+ // ../../node_modules/.pnpm/@ai-sdk+mcp@1.0.25_zod@4.1.13/node_modules/@ai-sdk/mcp/dist/index.mjs
2295
+ import { z as z32 } from "zod/v4";
2296
+ var name15 = "AI_MCPClientError";
2297
+ var marker16 = `vercel.ai.error.${name15}`;
2298
+ var symbol16 = Symbol.for(marker16);
2299
+ var _a16;
2300
+ var _b16;
2301
+ var MCPClientError = class extends (_b16 = AISDKError, _a16 = symbol16, _b16) {
2302
+ constructor({
2303
+ name: name32 = "MCPClientError",
2304
+ message,
2305
+ cause,
2306
+ data,
2307
+ code
2308
+ }) {
2309
+ super({ name: name32, message, cause });
2310
+ this[_a16] = true;
2311
+ this.data = data;
2312
+ this.code = code;
2313
+ }
2314
+ static isInstance(error) {
2315
+ return AISDKError.hasMarker(error, marker16);
2316
+ }
2317
+ };
2318
+ var LATEST_PROTOCOL_VERSION = "2025-06-18";
2319
+ var SUPPORTED_PROTOCOL_VERSIONS = [
2320
+ LATEST_PROTOCOL_VERSION,
2321
+ "2025-03-26",
2322
+ "2024-11-05"
2323
+ ];
2324
+ var ToolMetaSchema = z7.optional(z7.record(z7.string(), z7.unknown()));
2325
+ var ClientOrServerImplementationSchema = z7.looseObject({
2326
+ name: z7.string(),
2327
+ version: z7.string()
2328
+ });
2329
+ var BaseParamsSchema = z7.looseObject({
2330
+ _meta: z7.optional(z7.object({}).loose())
2331
+ });
2332
+ var ResultSchema = BaseParamsSchema;
2333
+ var RequestSchema = z7.object({
2334
+ method: z7.string(),
2335
+ params: z7.optional(BaseParamsSchema)
2336
+ });
2337
+ var ElicitationCapabilitySchema = z7.object({
2338
+ applyDefaults: z7.optional(z7.boolean())
2339
+ }).loose();
2340
+ var ServerCapabilitiesSchema = z7.looseObject({
2341
+ experimental: z7.optional(z7.object({}).loose()),
2342
+ logging: z7.optional(z7.object({}).loose()),
2343
+ prompts: z7.optional(
2344
+ z7.looseObject({
2345
+ listChanged: z7.optional(z7.boolean())
2346
+ })
2347
+ ),
2348
+ resources: z7.optional(
2349
+ z7.looseObject({
2350
+ subscribe: z7.optional(z7.boolean()),
2351
+ listChanged: z7.optional(z7.boolean())
2352
+ })
2353
+ ),
2354
+ tools: z7.optional(
2355
+ z7.looseObject({
2356
+ listChanged: z7.optional(z7.boolean())
2357
+ })
2358
+ ),
2359
+ elicitation: z7.optional(ElicitationCapabilitySchema)
2360
+ });
2361
+ var ClientCapabilitiesSchema = z7.object({
2362
+ elicitation: z7.optional(ElicitationCapabilitySchema)
2363
+ }).loose();
2364
+ var InitializeResultSchema = ResultSchema.extend({
2365
+ protocolVersion: z7.string(),
2366
+ capabilities: ServerCapabilitiesSchema,
2367
+ serverInfo: ClientOrServerImplementationSchema,
2368
+ instructions: z7.optional(z7.string())
2369
+ });
2370
+ var PaginatedResultSchema = ResultSchema.extend({
2371
+ nextCursor: z7.optional(z7.string())
2372
+ });
2373
+ var ToolSchema = z7.object({
2374
+ name: z7.string(),
2375
+ /**
2376
+ * @see https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool
2377
+ */
2378
+ title: z7.optional(z7.string()),
2379
+ description: z7.optional(z7.string()),
2380
+ inputSchema: z7.object({
2381
+ type: z7.literal("object"),
2382
+ properties: z7.optional(z7.object({}).loose())
2383
+ }).loose(),
2384
+ /**
2385
+ * @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema
2386
+ */
2387
+ outputSchema: z7.optional(z7.object({}).loose()),
2388
+ annotations: z7.optional(
2389
+ z7.object({
2390
+ title: z7.optional(z7.string())
2391
+ }).loose()
2392
+ ),
2393
+ _meta: ToolMetaSchema
2394
+ }).loose();
2395
+ var ListToolsResultSchema = PaginatedResultSchema.extend({
2396
+ tools: z7.array(ToolSchema)
2397
+ });
2398
+ var TextContentSchema = z7.object({
2399
+ type: z7.literal("text"),
2400
+ text: z7.string()
2401
+ }).loose();
2402
+ var ImageContentSchema = z7.object({
2403
+ type: z7.literal("image"),
2404
+ data: z7.base64(),
2405
+ mimeType: z7.string()
2406
+ }).loose();
2407
+ var ResourceSchema = z7.object({
2408
+ uri: z7.string(),
2409
+ name: z7.string(),
2410
+ title: z7.optional(z7.string()),
2411
+ description: z7.optional(z7.string()),
2412
+ mimeType: z7.optional(z7.string()),
2413
+ size: z7.optional(z7.number())
2414
+ }).loose();
2415
+ var ListResourcesResultSchema = PaginatedResultSchema.extend({
2416
+ resources: z7.array(ResourceSchema)
2417
+ });
2418
+ var ResourceContentsSchema = z7.object({
2419
+ /**
2420
+ * The URI of this resource.
2421
+ */
2422
+ uri: z7.string(),
2423
+ /**
2424
+ * Optional display name of the resource content.
2425
+ */
2426
+ name: z7.optional(z7.string()),
2427
+ /**
2428
+ * Optional human readable title.
2429
+ */
2430
+ title: z7.optional(z7.string()),
2431
+ /**
2432
+ * The MIME type of this resource, if known.
2433
+ */
2434
+ mimeType: z7.optional(z7.string())
2435
+ }).loose();
2436
+ var TextResourceContentsSchema = ResourceContentsSchema.extend({
2437
+ text: z7.string()
2438
+ });
2439
+ var BlobResourceContentsSchema = ResourceContentsSchema.extend({
2440
+ blob: z7.base64()
2441
+ });
2442
+ var EmbeddedResourceSchema = z7.object({
2443
+ type: z7.literal("resource"),
2444
+ resource: z7.union([TextResourceContentsSchema, BlobResourceContentsSchema])
2445
+ }).loose();
2446
+ var CallToolResultSchema = ResultSchema.extend({
2447
+ content: z7.array(
2448
+ z7.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])
2449
+ ),
2450
+ /**
2451
+ * @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content
2452
+ */
2453
+ structuredContent: z7.optional(z7.unknown()),
2454
+ isError: z7.boolean().default(false).optional()
2455
+ }).or(
2456
+ ResultSchema.extend({
2457
+ toolResult: z7.unknown()
2458
+ })
2459
+ );
2460
+ var ResourceTemplateSchema = z7.object({
2461
+ uriTemplate: z7.string(),
2462
+ name: z7.string(),
2463
+ title: z7.optional(z7.string()),
2464
+ description: z7.optional(z7.string()),
2465
+ mimeType: z7.optional(z7.string())
2466
+ }).loose();
2467
+ var ListResourceTemplatesResultSchema = ResultSchema.extend({
2468
+ resourceTemplates: z7.array(ResourceTemplateSchema)
2469
+ });
2470
+ var ReadResourceResultSchema = ResultSchema.extend({
2471
+ contents: z7.array(
2472
+ z7.union([TextResourceContentsSchema, BlobResourceContentsSchema])
2473
+ )
2474
+ });
2475
+ var PromptArgumentSchema = z7.object({
2476
+ name: z7.string(),
2477
+ description: z7.optional(z7.string()),
2478
+ required: z7.optional(z7.boolean())
2479
+ }).loose();
2480
+ var PromptSchema = z7.object({
2481
+ name: z7.string(),
2482
+ title: z7.optional(z7.string()),
2483
+ description: z7.optional(z7.string()),
2484
+ arguments: z7.optional(z7.array(PromptArgumentSchema))
2485
+ }).loose();
2486
+ var ListPromptsResultSchema = PaginatedResultSchema.extend({
2487
+ prompts: z7.array(PromptSchema)
2488
+ });
2489
+ var PromptMessageSchema = z7.object({
2490
+ role: z7.union([z7.literal("user"), z7.literal("assistant")]),
2491
+ content: z7.union([
2492
+ TextContentSchema,
2493
+ ImageContentSchema,
2494
+ EmbeddedResourceSchema
2495
+ ])
2496
+ }).loose();
2497
+ var GetPromptResultSchema = ResultSchema.extend({
2498
+ description: z7.optional(z7.string()),
2499
+ messages: z7.array(PromptMessageSchema)
2500
+ });
2501
+ var ElicitationRequestParamsSchema = BaseParamsSchema.extend({
2502
+ message: z7.string(),
2503
+ requestedSchema: z7.unknown()
2504
+ });
2505
+ var ElicitationRequestSchema = RequestSchema.extend({
2506
+ method: z7.literal("elicitation/create"),
2507
+ params: ElicitationRequestParamsSchema
2508
+ });
2509
+ var ElicitResultSchema = ResultSchema.extend({
2510
+ action: z7.union([
2511
+ z7.literal("accept"),
2512
+ z7.literal("decline"),
2513
+ z7.literal("cancel")
2514
+ ]),
2515
+ content: z7.optional(z7.record(z7.string(), z7.unknown()))
2516
+ });
2517
+ var JSONRPC_VERSION = "2.0";
2518
+ var JSONRPCRequestSchema = z22.object({
2519
+ jsonrpc: z22.literal(JSONRPC_VERSION),
2520
+ id: z22.union([z22.string(), z22.number().int()])
2521
+ }).merge(RequestSchema).strict();
2522
+ var JSONRPCResponseSchema = z22.object({
2523
+ jsonrpc: z22.literal(JSONRPC_VERSION),
2524
+ id: z22.union([z22.string(), z22.number().int()]),
2525
+ result: ResultSchema
2526
+ }).strict();
2527
+ var JSONRPCErrorSchema = z22.object({
2528
+ jsonrpc: z22.literal(JSONRPC_VERSION),
2529
+ id: z22.union([z22.string(), z22.number().int()]),
2530
+ error: z22.object({
2531
+ code: z22.number().int(),
2532
+ message: z22.string(),
2533
+ data: z22.optional(z22.unknown())
2534
+ })
2535
+ }).strict();
2536
+ var JSONRPCNotificationSchema = z22.object({
2537
+ jsonrpc: z22.literal(JSONRPC_VERSION)
2538
+ }).merge(
2539
+ z22.object({
2540
+ method: z22.string(),
2541
+ params: z22.optional(BaseParamsSchema)
2542
+ })
2543
+ ).strict();
2544
+ var JSONRPCMessageSchema = z22.union([
2545
+ JSONRPCRequestSchema,
2546
+ JSONRPCNotificationSchema,
2547
+ JSONRPCResponseSchema,
2548
+ JSONRPCErrorSchema
2549
+ ]);
2550
+ var VERSION = typeof __PACKAGE_VERSION__ !== "undefined" ? __PACKAGE_VERSION__ : "0.0.0-test";
2551
+ var OAuthTokensSchema = z32.object({
2552
+ access_token: z32.string(),
2553
+ id_token: z32.string().optional(),
2554
+ // Optional for OAuth 2.1, but necessary in OpenID Connect
2555
+ token_type: z32.string(),
2556
+ expires_in: z32.number().optional(),
2557
+ scope: z32.string().optional(),
2558
+ refresh_token: z32.string().optional()
2559
+ }).strip();
2560
+ var SafeUrlSchema = z32.string().url().superRefine((val, ctx) => {
2561
+ if (!URL.canParse(val)) {
2562
+ ctx.addIssue({
2563
+ code: z32.ZodIssueCode.custom,
2564
+ message: "URL must be parseable",
2565
+ fatal: true
2566
+ });
2567
+ return z32.NEVER;
2568
+ }
2569
+ }).refine(
2570
+ (url) => {
2571
+ const u = new URL(url);
2572
+ return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:";
2573
+ },
2574
+ { message: "URL cannot use javascript:, data:, or vbscript: scheme" }
2575
+ );
2576
+ var OAuthProtectedResourceMetadataSchema = z32.object({
2577
+ resource: z32.string().url(),
2578
+ authorization_servers: z32.array(SafeUrlSchema).optional(),
2579
+ jwks_uri: z32.string().url().optional(),
2580
+ scopes_supported: z32.array(z32.string()).optional(),
2581
+ bearer_methods_supported: z32.array(z32.string()).optional(),
2582
+ resource_signing_alg_values_supported: z32.array(z32.string()).optional(),
2583
+ resource_name: z32.string().optional(),
2584
+ resource_documentation: z32.string().optional(),
2585
+ resource_policy_uri: z32.string().url().optional(),
2586
+ resource_tos_uri: z32.string().url().optional(),
2587
+ tls_client_certificate_bound_access_tokens: z32.boolean().optional(),
2588
+ authorization_details_types_supported: z32.array(z32.string()).optional(),
2589
+ dpop_signing_alg_values_supported: z32.array(z32.string()).optional(),
2590
+ dpop_bound_access_tokens_required: z32.boolean().optional()
2591
+ }).passthrough();
2592
+ var OAuthMetadataSchema = z32.object({
2593
+ issuer: z32.string(),
2594
+ authorization_endpoint: SafeUrlSchema,
2595
+ token_endpoint: SafeUrlSchema,
2596
+ registration_endpoint: SafeUrlSchema.optional(),
2597
+ scopes_supported: z32.array(z32.string()).optional(),
2598
+ response_types_supported: z32.array(z32.string()),
2599
+ grant_types_supported: z32.array(z32.string()).optional(),
2600
+ code_challenge_methods_supported: z32.array(z32.string()),
2601
+ token_endpoint_auth_methods_supported: z32.array(z32.string()).optional(),
2602
+ token_endpoint_auth_signing_alg_values_supported: z32.array(z32.string()).optional()
2603
+ }).passthrough();
2604
+ var OpenIdProviderMetadataSchema = z32.object({
2605
+ issuer: z32.string(),
2606
+ authorization_endpoint: SafeUrlSchema,
2607
+ token_endpoint: SafeUrlSchema,
2608
+ userinfo_endpoint: SafeUrlSchema.optional(),
2609
+ jwks_uri: SafeUrlSchema,
2610
+ registration_endpoint: SafeUrlSchema.optional(),
2611
+ scopes_supported: z32.array(z32.string()).optional(),
2612
+ response_types_supported: z32.array(z32.string()),
2613
+ grant_types_supported: z32.array(z32.string()).optional(),
2614
+ subject_types_supported: z32.array(z32.string()),
2615
+ id_token_signing_alg_values_supported: z32.array(z32.string()),
2616
+ claims_supported: z32.array(z32.string()).optional(),
2617
+ token_endpoint_auth_methods_supported: z32.array(z32.string()).optional()
2618
+ }).passthrough();
2619
+ var OpenIdProviderDiscoveryMetadataSchema = OpenIdProviderMetadataSchema.merge(
2620
+ OAuthMetadataSchema.pick({
2621
+ code_challenge_methods_supported: true
2622
+ })
2623
+ );
2624
+ var OAuthClientInformationSchema = z32.object({
2625
+ client_id: z32.string(),
2626
+ client_secret: z32.string().optional(),
2627
+ client_id_issued_at: z32.number().optional(),
2628
+ client_secret_expires_at: z32.number().optional()
2629
+ }).strip();
2630
+ var OAuthClientMetadataSchema = z32.object({
2631
+ redirect_uris: z32.array(SafeUrlSchema),
2632
+ token_endpoint_auth_method: z32.string().optional(),
2633
+ grant_types: z32.array(z32.string()).optional(),
2634
+ response_types: z32.array(z32.string()).optional(),
2635
+ client_name: z32.string().optional(),
2636
+ client_uri: SafeUrlSchema.optional(),
2637
+ logo_uri: SafeUrlSchema.optional(),
2638
+ scope: z32.string().optional(),
2639
+ contacts: z32.array(z32.string()).optional(),
2640
+ tos_uri: SafeUrlSchema.optional(),
2641
+ policy_uri: z32.string().optional(),
2642
+ jwks_uri: SafeUrlSchema.optional(),
2643
+ jwks: z32.any().optional(),
2644
+ software_id: z32.string().optional(),
2645
+ software_version: z32.string().optional(),
2646
+ software_statement: z32.string().optional()
2647
+ }).strip();
2648
+ var OAuthErrorResponseSchema = z32.object({
2649
+ error: z32.string(),
2650
+ error_description: z32.string().optional(),
2651
+ error_uri: z32.string().optional()
2652
+ });
2653
+ var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(
2654
+ OAuthClientInformationSchema
2655
+ );
2656
+ var name22 = "AI_MCPClientOAuthError";
2657
+ var marker22 = `vercel.ai.error.${name22}`;
2658
+ var symbol22 = Symbol.for(marker22);
2659
+ var _a22;
2660
+ var _b22;
2661
+ var MCPClientOAuthError = class extends (_b22 = AISDKError, _a22 = symbol22, _b22) {
2662
+ constructor({
2663
+ name: name32 = "MCPClientOAuthError",
2664
+ message,
2665
+ cause
2666
+ }) {
2667
+ super({ name: name32, message, cause });
2668
+ this[_a22] = true;
2669
+ }
2670
+ static isInstance(error) {
2671
+ return AISDKError.hasMarker(error, marker22);
2672
+ }
2673
+ };
2674
+ var ServerError = class extends MCPClientOAuthError {
2675
+ };
2676
+ ServerError.errorCode = "server_error";
2677
+ var InvalidClientError = class extends MCPClientOAuthError {
2678
+ };
2679
+ InvalidClientError.errorCode = "invalid_client";
2680
+ var InvalidGrantError = class extends MCPClientOAuthError {
2681
+ };
2682
+ InvalidGrantError.errorCode = "invalid_grant";
2683
+ var UnauthorizedClientError = class extends MCPClientOAuthError {
2684
+ };
2685
+ UnauthorizedClientError.errorCode = "unauthorized_client";
2686
+ var OAUTH_ERRORS = {
2687
+ [ServerError.errorCode]: ServerError,
2688
+ [InvalidClientError.errorCode]: InvalidClientError,
2689
+ [InvalidGrantError.errorCode]: InvalidGrantError,
2690
+ [UnauthorizedClientError.errorCode]: UnauthorizedClientError
2691
+ };
2692
+ function resourceUrlFromServerUrl(url) {
2693
+ const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href);
2694
+ resourceURL.hash = "";
2695
+ return resourceURL;
2696
+ }
2697
+ function checkResourceAllowed({
2698
+ requestedResource,
2699
+ configuredResource
2700
+ }) {
2701
+ const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href);
2702
+ const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href);
2703
+ if (requested.origin !== configured.origin) {
2704
+ return false;
2705
+ }
2706
+ if (requested.pathname.length < configured.pathname.length) {
2707
+ return false;
2708
+ }
2709
+ const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/";
2710
+ const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
2711
+ return requestedPath.startsWith(configuredPath);
2712
+ }
2713
+ var UnauthorizedError = class extends Error {
2714
+ constructor(message = "Unauthorized") {
2715
+ super(message);
2716
+ this.name = "UnauthorizedError";
2717
+ }
2718
+ };
2719
+ function extractResourceMetadataUrl(response) {
2720
+ var _a32;
2721
+ const header = (_a32 = response.headers.get("www-authenticate")) != null ? _a32 : response.headers.get("WWW-Authenticate");
2722
+ if (!header) {
2723
+ return void 0;
2724
+ }
2725
+ const [type, scheme] = header.split(" ");
2726
+ if (type.toLowerCase() !== "bearer" || !scheme) {
2727
+ return void 0;
2728
+ }
2729
+ const regex = /resource_metadata="([^"]*)"/;
2730
+ const match = header.match(regex);
2731
+ if (!match) {
2732
+ return void 0;
2733
+ }
2734
+ try {
2735
+ return new URL(match[1]);
2736
+ } catch (e) {
2737
+ return void 0;
2738
+ }
2739
+ }
2740
+ function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
2741
+ if (pathname.endsWith("/")) {
2742
+ pathname = pathname.slice(0, -1);
2743
+ }
2744
+ return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
2745
+ }
2746
+ async function fetchWithCorsRetry(url, headers, fetchFn = fetch) {
2747
+ try {
2748
+ return await fetchFn(url, { headers });
2749
+ } catch (error) {
2750
+ if (error instanceof TypeError) {
2751
+ if (headers) {
2752
+ return fetchWithCorsRetry(url, void 0, fetchFn);
2753
+ } else {
2754
+ return void 0;
2755
+ }
2756
+ }
2757
+ throw error;
2758
+ }
2759
+ }
2760
+ async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {
2761
+ const headers = {
2762
+ "MCP-Protocol-Version": protocolVersion
2763
+ };
2764
+ return await fetchWithCorsRetry(url, headers, fetchFn);
2765
+ }
2766
+ function shouldAttemptFallback(response, pathname) {
2767
+ return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
2768
+ }
2769
+ async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
2770
+ var _a32, _b32;
2771
+ const issuer = new URL(serverUrl);
2772
+ const protocolVersion = (_a32 = opts == null ? void 0 : opts.protocolVersion) != null ? _a32 : LATEST_PROTOCOL_VERSION;
2773
+ let url;
2774
+ if (opts == null ? void 0 : opts.metadataUrl) {
2775
+ url = new URL(opts.metadataUrl);
2776
+ } else {
2777
+ const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
2778
+ url = new URL(wellKnownPath, (_b32 = opts == null ? void 0 : opts.metadataServerUrl) != null ? _b32 : issuer);
2779
+ url.search = issuer.search;
2780
+ }
2781
+ let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);
2782
+ if (!(opts == null ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) {
2783
+ const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
2784
+ response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
2785
+ }
2786
+ return response;
2787
+ }
2788
+ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
2789
+ const response = await discoverMetadataWithFallback(
2790
+ serverUrl,
2791
+ "oauth-protected-resource",
2792
+ fetchFn,
2793
+ {
2794
+ protocolVersion: opts == null ? void 0 : opts.protocolVersion,
2795
+ metadataUrl: opts == null ? void 0 : opts.resourceMetadataUrl
2796
+ }
2797
+ );
2798
+ if (!response || response.status === 404) {
2799
+ throw new Error(
2800
+ `Resource server does not implement OAuth 2.0 Protected Resource Metadata.`
2801
+ );
2802
+ }
2803
+ if (!response.ok) {
2804
+ throw new Error(
2805
+ `HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`
2806
+ );
2807
+ }
2808
+ return OAuthProtectedResourceMetadataSchema.parse(await response.json());
2809
+ }
2810
+ function buildDiscoveryUrls(authorizationServerUrl) {
2811
+ const url = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
2812
+ const hasPath = url.pathname !== "/";
2813
+ const urlsToTry = [];
2814
+ if (!hasPath) {
2815
+ urlsToTry.push({
2816
+ url: new URL("/.well-known/oauth-authorization-server", url.origin),
2817
+ type: "oauth"
2818
+ });
2819
+ urlsToTry.push({
2820
+ url: new URL("/.well-known/openid-configuration", url.origin),
2821
+ type: "oidc"
2822
+ });
2823
+ return urlsToTry;
2824
+ }
2825
+ let pathname = url.pathname;
2826
+ if (pathname.endsWith("/")) {
2827
+ pathname = pathname.slice(0, -1);
2828
+ }
2829
+ urlsToTry.push({
2830
+ url: new URL(
2831
+ `/.well-known/oauth-authorization-server${pathname}`,
2832
+ url.origin
2833
+ ),
2834
+ type: "oauth"
2835
+ });
2836
+ urlsToTry.push({
2837
+ url: new URL("/.well-known/oauth-authorization-server", url.origin),
2838
+ type: "oauth"
2839
+ });
2840
+ urlsToTry.push({
2841
+ url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),
2842
+ type: "oidc"
2843
+ });
2844
+ urlsToTry.push({
2845
+ url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),
2846
+ type: "oidc"
2847
+ });
2848
+ return urlsToTry;
2849
+ }
2850
+ async function discoverAuthorizationServerMetadata(authorizationServerUrl, {
2851
+ fetchFn = fetch,
2852
+ protocolVersion = LATEST_PROTOCOL_VERSION
2853
+ } = {}) {
2854
+ var _a32;
2855
+ const headers = { "MCP-Protocol-Version": protocolVersion };
2856
+ const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
2857
+ for (const { url: endpointUrl, type } of urlsToTry) {
2858
+ const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
2859
+ if (!response) {
2860
+ continue;
2861
+ }
2862
+ if (!response.ok) {
2863
+ if (response.status >= 400 && response.status < 500) {
2864
+ continue;
2865
+ }
2866
+ throw new Error(
2867
+ `HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`
2868
+ );
2869
+ }
2870
+ if (type === "oauth") {
2871
+ return OAuthMetadataSchema.parse(await response.json());
2872
+ } else {
2873
+ const metadata = OpenIdProviderDiscoveryMetadataSchema.parse(
2874
+ await response.json()
2875
+ );
2876
+ if (!((_a32 = metadata.code_challenge_methods_supported) == null ? void 0 : _a32.includes("S256"))) {
2877
+ throw new Error(
2878
+ `Incompatible OIDC provider at ${endpointUrl}: does not support S256 code challenge method required by MCP specification`
2879
+ );
2880
+ }
2881
+ return metadata;
2882
+ }
2883
+ }
2884
+ return void 0;
2885
+ }
2886
+ async function startAuthorization(authorizationServerUrl, {
2887
+ metadata,
2888
+ clientInformation,
2889
+ redirectUrl,
2890
+ scope,
2891
+ state,
2892
+ resource
2893
+ }) {
2894
+ const responseType = "code";
2895
+ const codeChallengeMethod = "S256";
2896
+ let authorizationUrl;
2897
+ if (metadata) {
2898
+ authorizationUrl = new URL(metadata.authorization_endpoint);
2899
+ if (!metadata.response_types_supported.includes(responseType)) {
2900
+ throw new Error(
2901
+ `Incompatible auth server: does not support response type ${responseType}`
2902
+ );
2903
+ }
2904
+ if (!metadata.code_challenge_methods_supported || !metadata.code_challenge_methods_supported.includes(codeChallengeMethod)) {
2905
+ throw new Error(
2906
+ `Incompatible auth server: does not support code challenge method ${codeChallengeMethod}`
2907
+ );
2908
+ }
2909
+ } else {
2910
+ authorizationUrl = new URL("/authorize", authorizationServerUrl);
2911
+ }
2912
+ const challenge = await pkceChallenge();
2913
+ const codeVerifier = challenge.code_verifier;
2914
+ const codeChallenge = challenge.code_challenge;
2915
+ authorizationUrl.searchParams.set("response_type", responseType);
2916
+ authorizationUrl.searchParams.set("client_id", clientInformation.client_id);
2917
+ authorizationUrl.searchParams.set("code_challenge", codeChallenge);
2918
+ authorizationUrl.searchParams.set(
2919
+ "code_challenge_method",
2920
+ codeChallengeMethod
2921
+ );
2922
+ authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));
2923
+ if (state) {
2924
+ authorizationUrl.searchParams.set("state", state);
2925
+ }
2926
+ if (scope) {
2927
+ authorizationUrl.searchParams.set("scope", scope);
2928
+ }
2929
+ if (scope == null ? void 0 : scope.includes("offline_access")) {
2930
+ authorizationUrl.searchParams.append("prompt", "consent");
2931
+ }
2932
+ if (resource) {
2933
+ authorizationUrl.searchParams.set("resource", resource.href);
2934
+ }
2935
+ return { authorizationUrl, codeVerifier };
2936
+ }
2937
+ function selectClientAuthMethod(clientInformation, supportedMethods) {
2938
+ const hasClientSecret = clientInformation.client_secret !== void 0;
2939
+ if (supportedMethods.length === 0) {
2940
+ return hasClientSecret ? "client_secret_post" : "none";
2941
+ }
2942
+ if (hasClientSecret && supportedMethods.includes("client_secret_basic")) {
2943
+ return "client_secret_basic";
2944
+ }
2945
+ if (hasClientSecret && supportedMethods.includes("client_secret_post")) {
2946
+ return "client_secret_post";
2947
+ }
2948
+ if (supportedMethods.includes("none")) {
2949
+ return "none";
2950
+ }
2951
+ return hasClientSecret ? "client_secret_post" : "none";
2952
+ }
2953
+ function applyClientAuthentication(method, clientInformation, headers, params) {
2954
+ const { client_id, client_secret } = clientInformation;
2955
+ switch (method) {
2956
+ case "client_secret_basic":
2957
+ applyBasicAuth(client_id, client_secret, headers);
2958
+ return;
2959
+ case "client_secret_post":
2960
+ applyPostAuth(client_id, client_secret, params);
2961
+ return;
2962
+ case "none":
2963
+ applyPublicAuth(client_id, params);
2964
+ return;
2965
+ default:
2966
+ throw new Error(`Unsupported client authentication method: ${method}`);
2967
+ }
2968
+ }
2969
+ function applyBasicAuth(clientId, clientSecret, headers) {
2970
+ if (!clientSecret) {
2971
+ throw new Error(
2972
+ "client_secret_basic authentication requires a client_secret"
2973
+ );
2974
+ }
2975
+ const credentials = btoa(`${clientId}:${clientSecret}`);
2976
+ headers.set("Authorization", `Basic ${credentials}`);
2977
+ }
2978
+ function applyPostAuth(clientId, clientSecret, params) {
2979
+ params.set("client_id", clientId);
2980
+ if (clientSecret) {
2981
+ params.set("client_secret", clientSecret);
2982
+ }
2983
+ }
2984
+ function applyPublicAuth(clientId, params) {
2985
+ params.set("client_id", clientId);
2986
+ }
2987
+ async function parseErrorResponse(input) {
2988
+ const statusCode = input instanceof Response ? input.status : void 0;
2989
+ const body = input instanceof Response ? await input.text() : input;
2990
+ try {
2991
+ const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
2992
+ const { error, error_description, error_uri } = result;
2993
+ const errorClass = OAUTH_ERRORS[error] || ServerError;
2994
+ return new errorClass({
2995
+ message: error_description || "",
2996
+ cause: error_uri
2997
+ });
2998
+ } catch (error) {
2999
+ const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
3000
+ return new ServerError({ message: errorMessage });
3001
+ }
3002
+ }
3003
+ async function exchangeAuthorization(authorizationServerUrl, {
3004
+ metadata,
3005
+ clientInformation,
3006
+ authorizationCode,
3007
+ codeVerifier,
3008
+ redirectUri,
3009
+ resource,
3010
+ addClientAuthentication,
3011
+ fetchFn
3012
+ }) {
3013
+ var _a32;
3014
+ const grantType = "authorization_code";
3015
+ const tokenUrl = (metadata == null ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
3016
+ if ((metadata == null ? void 0 : metadata.grant_types_supported) && !metadata.grant_types_supported.includes(grantType)) {
3017
+ throw new Error(
3018
+ `Incompatible auth server: does not support grant type ${grantType}`
3019
+ );
3020
+ }
3021
+ const headers = new Headers({
3022
+ "Content-Type": "application/x-www-form-urlencoded",
3023
+ Accept: "application/json"
3024
+ });
3025
+ const params = new URLSearchParams({
3026
+ grant_type: grantType,
3027
+ code: authorizationCode,
3028
+ code_verifier: codeVerifier,
3029
+ redirect_uri: String(redirectUri)
3030
+ });
3031
+ if (addClientAuthentication) {
3032
+ addClientAuthentication(headers, params, authorizationServerUrl, metadata);
3033
+ } else {
3034
+ const supportedMethods = (_a32 = metadata == null ? void 0 : metadata.token_endpoint_auth_methods_supported) != null ? _a32 : [];
3035
+ const authMethod = selectClientAuthMethod(
3036
+ clientInformation,
3037
+ supportedMethods
3038
+ );
3039
+ applyClientAuthentication(authMethod, clientInformation, headers, params);
3040
+ }
3041
+ if (resource) {
3042
+ params.set("resource", resource.href);
3043
+ }
3044
+ const response = await (fetchFn != null ? fetchFn : fetch)(tokenUrl, {
3045
+ method: "POST",
3046
+ headers,
3047
+ body: params
3048
+ });
3049
+ if (!response.ok) {
3050
+ throw await parseErrorResponse(response);
3051
+ }
3052
+ return OAuthTokensSchema.parse(await response.json());
3053
+ }
3054
+ async function refreshAuthorization(authorizationServerUrl, {
3055
+ metadata,
3056
+ clientInformation,
3057
+ refreshToken,
3058
+ resource,
3059
+ addClientAuthentication,
3060
+ fetchFn
3061
+ }) {
3062
+ var _a32;
3063
+ const grantType = "refresh_token";
3064
+ let tokenUrl;
3065
+ if (metadata) {
3066
+ tokenUrl = new URL(metadata.token_endpoint);
3067
+ if (metadata.grant_types_supported && !metadata.grant_types_supported.includes(grantType)) {
3068
+ throw new Error(
3069
+ `Incompatible auth server: does not support grant type ${grantType}`
3070
+ );
3071
+ }
3072
+ } else {
3073
+ tokenUrl = new URL("/token", authorizationServerUrl);
3074
+ }
3075
+ const headers = new Headers({
3076
+ "Content-Type": "application/x-www-form-urlencoded",
3077
+ Accept: "application/json"
3078
+ });
3079
+ const params = new URLSearchParams({
3080
+ grant_type: grantType,
3081
+ refresh_token: refreshToken
3082
+ });
3083
+ if (addClientAuthentication) {
3084
+ addClientAuthentication(headers, params, authorizationServerUrl, metadata);
3085
+ } else {
3086
+ const supportedMethods = (_a32 = metadata == null ? void 0 : metadata.token_endpoint_auth_methods_supported) != null ? _a32 : [];
3087
+ const authMethod = selectClientAuthMethod(
3088
+ clientInformation,
3089
+ supportedMethods
3090
+ );
3091
+ applyClientAuthentication(authMethod, clientInformation, headers, params);
3092
+ }
3093
+ if (resource) {
3094
+ params.set("resource", resource.href);
3095
+ }
3096
+ const response = await (fetchFn != null ? fetchFn : fetch)(tokenUrl, {
3097
+ method: "POST",
3098
+ headers,
3099
+ body: params
3100
+ });
3101
+ if (!response.ok) {
3102
+ throw await parseErrorResponse(response);
3103
+ }
3104
+ return OAuthTokensSchema.parse({
3105
+ refresh_token: refreshToken,
3106
+ ...await response.json()
3107
+ });
3108
+ }
3109
+ async function registerClient(authorizationServerUrl, {
3110
+ metadata,
3111
+ clientMetadata,
3112
+ fetchFn
3113
+ }) {
3114
+ let registrationUrl;
3115
+ if (metadata) {
3116
+ if (!metadata.registration_endpoint) {
3117
+ throw new Error(
3118
+ "Incompatible auth server: does not support dynamic client registration"
3119
+ );
3120
+ }
3121
+ registrationUrl = new URL(metadata.registration_endpoint);
3122
+ } else {
3123
+ registrationUrl = new URL("/register", authorizationServerUrl);
3124
+ }
3125
+ const response = await (fetchFn != null ? fetchFn : fetch)(registrationUrl, {
3126
+ method: "POST",
3127
+ headers: {
3128
+ "Content-Type": "application/json"
3129
+ },
3130
+ body: JSON.stringify(clientMetadata)
3131
+ });
3132
+ if (!response.ok) {
3133
+ throw await parseErrorResponse(response);
3134
+ }
3135
+ return OAuthClientInformationFullSchema.parse(await response.json());
3136
+ }
3137
+ async function auth(provider, options) {
3138
+ var _a32, _b32;
3139
+ try {
3140
+ return await authInternal(provider, options);
3141
+ } catch (error) {
3142
+ if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {
3143
+ await ((_a32 = provider.invalidateCredentials) == null ? void 0 : _a32.call(provider, "all"));
3144
+ return await authInternal(provider, options);
3145
+ } else if (error instanceof InvalidGrantError) {
3146
+ await ((_b32 = provider.invalidateCredentials) == null ? void 0 : _b32.call(provider, "tokens"));
3147
+ return await authInternal(provider, options);
3148
+ }
3149
+ throw error;
3150
+ }
3151
+ }
3152
+ async function selectResourceURL(serverUrl, provider, resourceMetadata) {
3153
+ const defaultResource = resourceUrlFromServerUrl(serverUrl);
3154
+ if (provider.validateResourceURL) {
3155
+ return await provider.validateResourceURL(
3156
+ defaultResource,
3157
+ resourceMetadata == null ? void 0 : resourceMetadata.resource
3158
+ );
3159
+ }
3160
+ if (!resourceMetadata) {
3161
+ return void 0;
3162
+ }
3163
+ if (!checkResourceAllowed({
3164
+ requestedResource: defaultResource,
3165
+ configuredResource: resourceMetadata.resource
3166
+ })) {
3167
+ throw new Error(
3168
+ `Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`
3169
+ );
3170
+ }
3171
+ return new URL(resourceMetadata.resource);
3172
+ }
3173
+ async function authInternal(provider, {
3174
+ serverUrl,
3175
+ authorizationCode,
3176
+ scope,
3177
+ resourceMetadataUrl,
3178
+ fetchFn
3179
+ }) {
3180
+ let resourceMetadata;
3181
+ let authorizationServerUrl;
3182
+ try {
3183
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(
3184
+ serverUrl,
3185
+ { resourceMetadataUrl },
3186
+ fetchFn
3187
+ );
3188
+ if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
3189
+ authorizationServerUrl = resourceMetadata.authorization_servers[0];
3190
+ }
3191
+ } catch (e) {
3192
+ }
3193
+ if (!authorizationServerUrl) {
3194
+ authorizationServerUrl = serverUrl;
3195
+ }
3196
+ const resource = await selectResourceURL(
3197
+ serverUrl,
3198
+ provider,
3199
+ resourceMetadata
3200
+ );
3201
+ const metadata = await discoverAuthorizationServerMetadata(
3202
+ authorizationServerUrl,
3203
+ {
3204
+ fetchFn
3205
+ }
3206
+ );
3207
+ let clientInformation = await Promise.resolve(provider.clientInformation());
3208
+ if (!clientInformation) {
3209
+ if (authorizationCode !== void 0) {
3210
+ throw new Error(
3211
+ "Existing OAuth client information is required when exchanging an authorization code"
3212
+ );
3213
+ }
3214
+ if (!provider.saveClientInformation) {
3215
+ throw new Error(
3216
+ "OAuth client information must be saveable for dynamic registration"
3217
+ );
3218
+ }
3219
+ const fullInformation = await registerClient(authorizationServerUrl, {
3220
+ metadata,
3221
+ clientMetadata: provider.clientMetadata,
3222
+ fetchFn
3223
+ });
3224
+ await provider.saveClientInformation(fullInformation);
3225
+ clientInformation = fullInformation;
3226
+ }
3227
+ if (authorizationCode !== void 0) {
3228
+ const codeVerifier2 = await provider.codeVerifier();
3229
+ const tokens2 = await exchangeAuthorization(authorizationServerUrl, {
3230
+ metadata,
3231
+ clientInformation,
3232
+ authorizationCode,
3233
+ codeVerifier: codeVerifier2,
3234
+ redirectUri: provider.redirectUrl,
3235
+ resource,
3236
+ addClientAuthentication: provider.addClientAuthentication,
3237
+ fetchFn
3238
+ });
3239
+ await provider.saveTokens(tokens2);
3240
+ return "AUTHORIZED";
3241
+ }
3242
+ const tokens = await provider.tokens();
3243
+ if (tokens == null ? void 0 : tokens.refresh_token) {
3244
+ try {
3245
+ const newTokens = await refreshAuthorization(authorizationServerUrl, {
3246
+ metadata,
3247
+ clientInformation,
3248
+ refreshToken: tokens.refresh_token,
3249
+ resource,
3250
+ addClientAuthentication: provider.addClientAuthentication,
3251
+ fetchFn
3252
+ });
3253
+ await provider.saveTokens(newTokens);
3254
+ return "AUTHORIZED";
3255
+ } catch (error) {
3256
+ if (
3257
+ // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry.
3258
+ !(error instanceof MCPClientOAuthError) || error instanceof ServerError
3259
+ ) {
3260
+ } else {
3261
+ throw error;
3262
+ }
3263
+ }
3264
+ }
3265
+ const state = provider.state ? await provider.state() : void 0;
3266
+ const { authorizationUrl, codeVerifier } = await startAuthorization(
3267
+ authorizationServerUrl,
3268
+ {
3269
+ metadata,
3270
+ clientInformation,
3271
+ state,
3272
+ redirectUrl: provider.redirectUrl,
3273
+ scope: scope || provider.clientMetadata.scope,
3274
+ resource
3275
+ }
3276
+ );
3277
+ await provider.saveCodeVerifier(codeVerifier);
3278
+ await provider.redirectToAuthorization(authorizationUrl);
3279
+ return "REDIRECT";
3280
+ }
3281
+ var SseMCPTransport = class {
3282
+ constructor({
3283
+ url,
3284
+ headers,
3285
+ authProvider
3286
+ }) {
3287
+ this.connected = false;
3288
+ this.url = new URL(url);
3289
+ this.headers = headers;
3290
+ this.authProvider = authProvider;
3291
+ }
3292
+ async commonHeaders(base) {
3293
+ const headers = {
3294
+ ...this.headers,
3295
+ ...base,
3296
+ "mcp-protocol-version": LATEST_PROTOCOL_VERSION
3297
+ };
3298
+ if (this.authProvider) {
3299
+ const tokens = await this.authProvider.tokens();
3300
+ if (tokens == null ? void 0 : tokens.access_token) {
3301
+ headers["Authorization"] = `Bearer ${tokens.access_token}`;
3302
+ }
3303
+ }
3304
+ return withUserAgentSuffix(
3305
+ headers,
3306
+ `ai-sdk/${VERSION}`,
3307
+ getRuntimeEnvironmentUserAgent()
3308
+ );
3309
+ }
3310
+ async start() {
3311
+ return new Promise((resolve, reject) => {
3312
+ if (this.connected) {
3313
+ return resolve();
3314
+ }
3315
+ this.abortController = new AbortController();
3316
+ const establishConnection = async (triedAuth = false) => {
3317
+ var _a32, _b32, _c, _d, _e;
3318
+ try {
3319
+ const headers = await this.commonHeaders({
3320
+ Accept: "text/event-stream"
3321
+ });
3322
+ const response = await fetch(this.url.href, {
3323
+ headers,
3324
+ signal: (_a32 = this.abortController) == null ? void 0 : _a32.signal
3325
+ });
3326
+ if (response.status === 401 && this.authProvider && !triedAuth) {
3327
+ this.resourceMetadataUrl = extractResourceMetadataUrl(response);
3328
+ try {
3329
+ const result = await auth(this.authProvider, {
3330
+ serverUrl: this.url,
3331
+ resourceMetadataUrl: this.resourceMetadataUrl
3332
+ });
3333
+ if (result !== "AUTHORIZED") {
3334
+ const error = new UnauthorizedError();
3335
+ (_b32 = this.onerror) == null ? void 0 : _b32.call(this, error);
3336
+ return reject(error);
3337
+ }
3338
+ } catch (error) {
3339
+ (_c = this.onerror) == null ? void 0 : _c.call(this, error);
3340
+ return reject(error);
3341
+ }
3342
+ return establishConnection(true);
3343
+ }
3344
+ if (!response.ok || !response.body) {
3345
+ let errorMessage = `MCP SSE Transport Error: ${response.status} ${response.statusText}`;
3346
+ if (response.status === 405) {
3347
+ errorMessage += ". This server does not support SSE transport. Try using `http` transport instead";
3348
+ }
3349
+ const error = new MCPClientError({
3350
+ message: errorMessage
3351
+ });
3352
+ (_d = this.onerror) == null ? void 0 : _d.call(this, error);
3353
+ return reject(error);
3354
+ }
3355
+ const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream());
3356
+ const reader = stream.getReader();
3357
+ const processEvents = async () => {
3358
+ var _a42, _b42, _c2;
3359
+ try {
3360
+ while (true) {
3361
+ const { done, value } = await reader.read();
3362
+ if (done) {
3363
+ if (this.connected) {
3364
+ this.connected = false;
3365
+ throw new MCPClientError({
3366
+ message: "MCP SSE Transport Error: Connection closed unexpectedly"
3367
+ });
3368
+ }
3369
+ return;
3370
+ }
3371
+ const { event, data } = value;
3372
+ if (event === "endpoint") {
3373
+ this.endpoint = new URL(data, this.url);
3374
+ if (this.endpoint.origin !== this.url.origin) {
3375
+ throw new MCPClientError({
3376
+ message: `MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`
3377
+ });
3378
+ }
3379
+ this.connected = true;
3380
+ resolve();
3381
+ } else if (event === "message") {
3382
+ try {
3383
+ const message = JSONRPCMessageSchema.parse(
3384
+ JSON.parse(data)
3385
+ );
3386
+ (_a42 = this.onmessage) == null ? void 0 : _a42.call(this, message);
3387
+ } catch (error) {
3388
+ const e = new MCPClientError({
3389
+ message: "MCP SSE Transport Error: Failed to parse message",
3390
+ cause: error
3391
+ });
3392
+ (_b42 = this.onerror) == null ? void 0 : _b42.call(this, e);
3393
+ }
3394
+ }
3395
+ }
3396
+ } catch (error) {
3397
+ if (error instanceof Error && error.name === "AbortError") {
3398
+ return;
3399
+ }
3400
+ (_c2 = this.onerror) == null ? void 0 : _c2.call(this, error);
3401
+ reject(error);
3402
+ }
3403
+ };
3404
+ this.sseConnection = {
3405
+ close: () => reader.cancel()
3406
+ };
3407
+ processEvents();
3408
+ } catch (error) {
3409
+ if (error instanceof Error && error.name === "AbortError") {
3410
+ return;
3411
+ }
3412
+ (_e = this.onerror) == null ? void 0 : _e.call(this, error);
3413
+ reject(error);
3414
+ }
3415
+ };
3416
+ void establishConnection();
3417
+ });
3418
+ }
3419
+ async close() {
3420
+ var _a32, _b32, _c;
3421
+ this.connected = false;
3422
+ (_a32 = this.sseConnection) == null ? void 0 : _a32.close();
3423
+ (_b32 = this.abortController) == null ? void 0 : _b32.abort();
3424
+ (_c = this.onclose) == null ? void 0 : _c.call(this);
3425
+ }
3426
+ async send(message) {
3427
+ if (!this.endpoint || !this.connected) {
3428
+ throw new MCPClientError({
3429
+ message: "MCP SSE Transport Error: Not connected"
3430
+ });
3431
+ }
3432
+ const endpoint = this.endpoint;
3433
+ const attempt = async (triedAuth = false) => {
3434
+ var _a32, _b32, _c, _d, _e;
3435
+ try {
3436
+ const headers = await this.commonHeaders({
3437
+ "Content-Type": "application/json"
3438
+ });
3439
+ const init = {
3440
+ method: "POST",
3441
+ headers,
3442
+ body: JSON.stringify(message),
3443
+ signal: (_a32 = this.abortController) == null ? void 0 : _a32.signal
3444
+ };
3445
+ const response = await fetch(endpoint, init);
3446
+ if (response.status === 401 && this.authProvider && !triedAuth) {
3447
+ this.resourceMetadataUrl = extractResourceMetadataUrl(response);
3448
+ try {
3449
+ const result = await auth(this.authProvider, {
3450
+ serverUrl: this.url,
3451
+ resourceMetadataUrl: this.resourceMetadataUrl
3452
+ });
3453
+ if (result !== "AUTHORIZED") {
3454
+ const error = new UnauthorizedError();
3455
+ (_b32 = this.onerror) == null ? void 0 : _b32.call(this, error);
3456
+ return;
3457
+ }
3458
+ } catch (error) {
3459
+ (_c = this.onerror) == null ? void 0 : _c.call(this, error);
3460
+ return;
3461
+ }
3462
+ return attempt(true);
3463
+ }
3464
+ if (!response.ok) {
3465
+ const text = await response.text().catch(() => null);
3466
+ const error = new MCPClientError({
3467
+ message: `MCP SSE Transport Error: POSTing to endpoint (HTTP ${response.status}): ${text}`
3468
+ });
3469
+ (_d = this.onerror) == null ? void 0 : _d.call(this, error);
3470
+ return;
3471
+ }
3472
+ } catch (error) {
3473
+ (_e = this.onerror) == null ? void 0 : _e.call(this, error);
3474
+ return;
3475
+ }
3476
+ };
3477
+ await attempt();
3478
+ }
3479
+ };
3480
+ var HttpMCPTransport = class {
3481
+ constructor({
3482
+ url,
3483
+ headers,
3484
+ authProvider
3485
+ }) {
3486
+ this.inboundReconnectAttempts = 0;
3487
+ this.reconnectionOptions = {
3488
+ initialReconnectionDelay: 1e3,
3489
+ maxReconnectionDelay: 3e4,
3490
+ reconnectionDelayGrowFactor: 1.5,
3491
+ maxRetries: 2
3492
+ };
3493
+ this.url = new URL(url);
3494
+ this.headers = headers;
3495
+ this.authProvider = authProvider;
3496
+ }
3497
+ async commonHeaders(base) {
3498
+ const headers = {
3499
+ ...this.headers,
3500
+ ...base,
3501
+ "mcp-protocol-version": LATEST_PROTOCOL_VERSION
3502
+ };
3503
+ if (this.sessionId) {
3504
+ headers["mcp-session-id"] = this.sessionId;
3505
+ }
3506
+ if (this.authProvider) {
3507
+ const tokens = await this.authProvider.tokens();
3508
+ if (tokens == null ? void 0 : tokens.access_token) {
3509
+ headers["Authorization"] = `Bearer ${tokens.access_token}`;
3510
+ }
3511
+ }
3512
+ return withUserAgentSuffix(
3513
+ headers,
3514
+ `ai-sdk/${VERSION}`,
3515
+ getRuntimeEnvironmentUserAgent()
3516
+ );
3517
+ }
3518
+ async start() {
3519
+ if (this.abortController) {
3520
+ throw new MCPClientError({
3521
+ message: "MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."
3522
+ });
3523
+ }
3524
+ this.abortController = new AbortController();
3525
+ void this.openInboundSse();
3526
+ }
3527
+ async close() {
3528
+ var _a32, _b32, _c;
3529
+ (_a32 = this.inboundSseConnection) == null ? void 0 : _a32.close();
3530
+ try {
3531
+ if (this.sessionId && this.abortController && !this.abortController.signal.aborted) {
3532
+ const headers = await this.commonHeaders({});
3533
+ await fetch(this.url, {
3534
+ method: "DELETE",
3535
+ headers,
3536
+ signal: this.abortController.signal
3537
+ }).catch(() => void 0);
3538
+ }
3539
+ } catch (e) {
3540
+ }
3541
+ (_b32 = this.abortController) == null ? void 0 : _b32.abort();
3542
+ (_c = this.onclose) == null ? void 0 : _c.call(this);
3543
+ }
3544
+ async send(message) {
3545
+ const attempt = async (triedAuth = false) => {
3546
+ var _a32, _b32, _c, _d, _e, _f, _g;
3547
+ try {
3548
+ const headers = await this.commonHeaders({
3549
+ "Content-Type": "application/json",
3550
+ Accept: "application/json, text/event-stream"
3551
+ });
3552
+ const init = {
3553
+ method: "POST",
3554
+ headers,
3555
+ body: JSON.stringify(message),
3556
+ signal: (_a32 = this.abortController) == null ? void 0 : _a32.signal
3557
+ };
3558
+ const response = await fetch(this.url, init);
3559
+ const sessionId = response.headers.get("mcp-session-id");
3560
+ if (sessionId) {
3561
+ this.sessionId = sessionId;
3562
+ }
3563
+ if (response.status === 401 && this.authProvider && !triedAuth) {
3564
+ this.resourceMetadataUrl = extractResourceMetadataUrl(response);
3565
+ try {
3566
+ const result = await auth(this.authProvider, {
3567
+ serverUrl: this.url,
3568
+ resourceMetadataUrl: this.resourceMetadataUrl
3569
+ });
3570
+ if (result !== "AUTHORIZED") {
3571
+ const error2 = new UnauthorizedError();
3572
+ throw error2;
3573
+ }
3574
+ } catch (error2) {
3575
+ (_b32 = this.onerror) == null ? void 0 : _b32.call(this, error2);
3576
+ throw error2;
3577
+ }
3578
+ return attempt(true);
3579
+ }
3580
+ if (response.status === 202) {
3581
+ if (!this.inboundSseConnection) {
3582
+ void this.openInboundSse();
3583
+ }
3584
+ return;
3585
+ }
3586
+ if (!response.ok) {
3587
+ const text = await response.text().catch(() => null);
3588
+ let errorMessage = `MCP HTTP Transport Error: POSTing to endpoint (HTTP ${response.status}): ${text}`;
3589
+ if (response.status === 404) {
3590
+ errorMessage += ". This server does not support HTTP transport. Try using `sse` transport instead";
3591
+ }
3592
+ const error2 = new MCPClientError({
3593
+ message: errorMessage
3594
+ });
3595
+ (_c = this.onerror) == null ? void 0 : _c.call(this, error2);
3596
+ throw error2;
3597
+ }
3598
+ const isNotification = !("id" in message);
3599
+ if (isNotification) {
3600
+ return;
3601
+ }
3602
+ const contentType = response.headers.get("content-type") || "";
3603
+ if (contentType.includes("application/json")) {
3604
+ const data = await response.json();
3605
+ const messages = Array.isArray(data) ? data.map((m) => JSONRPCMessageSchema.parse(m)) : [JSONRPCMessageSchema.parse(data)];
3606
+ for (const m of messages) (_d = this.onmessage) == null ? void 0 : _d.call(this, m);
3607
+ return;
3608
+ }
3609
+ if (contentType.includes("text/event-stream")) {
3610
+ if (!response.body) {
3611
+ const error2 = new MCPClientError({
3612
+ message: "MCP HTTP Transport Error: text/event-stream response without body"
3613
+ });
3614
+ (_e = this.onerror) == null ? void 0 : _e.call(this, error2);
3615
+ throw error2;
3616
+ }
3617
+ const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream());
3618
+ const reader = stream.getReader();
3619
+ const processEvents = async () => {
3620
+ var _a42, _b42, _c2;
3621
+ try {
3622
+ while (true) {
3623
+ const { done, value } = await reader.read();
3624
+ if (done) return;
3625
+ const { event, data } = value;
3626
+ if (event === "message") {
3627
+ try {
3628
+ const msg = JSONRPCMessageSchema.parse(JSON.parse(data));
3629
+ (_a42 = this.onmessage) == null ? void 0 : _a42.call(this, msg);
3630
+ } catch (error2) {
3631
+ const e = new MCPClientError({
3632
+ message: "MCP HTTP Transport Error: Failed to parse message",
3633
+ cause: error2
3634
+ });
3635
+ (_b42 = this.onerror) == null ? void 0 : _b42.call(this, e);
3636
+ }
3637
+ }
3638
+ }
3639
+ } catch (error2) {
3640
+ if (error2 instanceof Error && error2.name === "AbortError") {
3641
+ return;
3642
+ }
3643
+ (_c2 = this.onerror) == null ? void 0 : _c2.call(this, error2);
3644
+ }
3645
+ };
3646
+ processEvents();
3647
+ return;
3648
+ }
3649
+ const error = new MCPClientError({
3650
+ message: `MCP HTTP Transport Error: Unexpected content type: ${contentType}`
3651
+ });
3652
+ (_f = this.onerror) == null ? void 0 : _f.call(this, error);
3653
+ throw error;
3654
+ } catch (error) {
3655
+ (_g = this.onerror) == null ? void 0 : _g.call(this, error);
3656
+ throw error;
3657
+ }
3658
+ };
3659
+ await attempt();
3660
+ }
3661
+ getNextReconnectionDelay(attempt) {
3662
+ const {
3663
+ initialReconnectionDelay,
3664
+ reconnectionDelayGrowFactor,
3665
+ maxReconnectionDelay
3666
+ } = this.reconnectionOptions;
3667
+ return Math.min(
3668
+ initialReconnectionDelay * Math.pow(reconnectionDelayGrowFactor, attempt),
3669
+ maxReconnectionDelay
3670
+ );
3671
+ }
3672
+ scheduleInboundSseReconnection() {
3673
+ var _a32;
3674
+ const { maxRetries } = this.reconnectionOptions;
3675
+ if (maxRetries > 0 && this.inboundReconnectAttempts >= maxRetries) {
3676
+ (_a32 = this.onerror) == null ? void 0 : _a32.call(
3677
+ this,
3678
+ new MCPClientError({
3679
+ message: `MCP HTTP Transport Error: Maximum reconnection attempts (${maxRetries}) exceeded.`
3680
+ })
3681
+ );
3682
+ return;
3683
+ }
3684
+ const delay = this.getNextReconnectionDelay(this.inboundReconnectAttempts);
3685
+ this.inboundReconnectAttempts += 1;
3686
+ setTimeout(async () => {
3687
+ var _a42;
3688
+ if ((_a42 = this.abortController) == null ? void 0 : _a42.signal.aborted) return;
3689
+ await this.openInboundSse(false, this.lastInboundEventId);
3690
+ }, delay);
3691
+ }
3692
+ // Open optional inbound SSE stream; best-effort and resumable
3693
+ async openInboundSse(triedAuth = false, resumeToken) {
3694
+ var _a32, _b32, _c, _d, _e, _f;
3695
+ try {
3696
+ const headers = await this.commonHeaders({
3697
+ Accept: "text/event-stream"
3698
+ });
3699
+ if (resumeToken) {
3700
+ headers["last-event-id"] = resumeToken;
3701
+ }
3702
+ const response = await fetch(this.url.href, {
3703
+ method: "GET",
3704
+ headers,
3705
+ signal: (_a32 = this.abortController) == null ? void 0 : _a32.signal
3706
+ });
3707
+ const sessionId = response.headers.get("mcp-session-id");
3708
+ if (sessionId) {
3709
+ this.sessionId = sessionId;
3710
+ }
3711
+ if (response.status === 401 && this.authProvider && !triedAuth) {
3712
+ this.resourceMetadataUrl = extractResourceMetadataUrl(response);
3713
+ try {
3714
+ const result = await auth(this.authProvider, {
3715
+ serverUrl: this.url,
3716
+ resourceMetadataUrl: this.resourceMetadataUrl
3717
+ });
3718
+ if (result !== "AUTHORIZED") {
3719
+ const error = new UnauthorizedError();
3720
+ (_b32 = this.onerror) == null ? void 0 : _b32.call(this, error);
3721
+ return;
3722
+ }
3723
+ } catch (error) {
3724
+ (_c = this.onerror) == null ? void 0 : _c.call(this, error);
3725
+ return;
3726
+ }
3727
+ return this.openInboundSse(true, resumeToken);
3728
+ }
3729
+ if (response.status === 405) {
3730
+ return;
3731
+ }
3732
+ if (!response.ok || !response.body) {
3733
+ const error = new MCPClientError({
3734
+ message: `MCP HTTP Transport Error: GET SSE failed: ${response.status} ${response.statusText}`
3735
+ });
3736
+ (_d = this.onerror) == null ? void 0 : _d.call(this, error);
3737
+ return;
3738
+ }
3739
+ const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream());
3740
+ const reader = stream.getReader();
3741
+ const processEvents = async () => {
3742
+ var _a42, _b42, _c2, _d2;
3743
+ try {
3744
+ while (true) {
3745
+ const { done, value } = await reader.read();
3746
+ if (done) return;
3747
+ const { event, data, id } = value;
3748
+ if (id) {
3749
+ this.lastInboundEventId = id;
3750
+ }
3751
+ if (event === "message") {
3752
+ try {
3753
+ const msg = JSONRPCMessageSchema.parse(JSON.parse(data));
3754
+ (_a42 = this.onmessage) == null ? void 0 : _a42.call(this, msg);
3755
+ } catch (error) {
3756
+ const e = new MCPClientError({
3757
+ message: "MCP HTTP Transport Error: Failed to parse message",
3758
+ cause: error
3759
+ });
3760
+ (_b42 = this.onerror) == null ? void 0 : _b42.call(this, e);
3761
+ }
3762
+ }
3763
+ }
3764
+ } catch (error) {
3765
+ if (error instanceof Error && error.name === "AbortError") {
3766
+ return;
3767
+ }
3768
+ (_c2 = this.onerror) == null ? void 0 : _c2.call(this, error);
3769
+ if (!((_d2 = this.abortController) == null ? void 0 : _d2.signal.aborted)) {
3770
+ this.scheduleInboundSseReconnection();
3771
+ }
3772
+ }
3773
+ };
3774
+ this.inboundSseConnection = {
3775
+ close: () => reader.cancel()
3776
+ };
3777
+ this.inboundReconnectAttempts = 0;
3778
+ processEvents();
3779
+ } catch (error) {
3780
+ if (error instanceof Error && error.name === "AbortError") {
3781
+ return;
3782
+ }
3783
+ (_e = this.onerror) == null ? void 0 : _e.call(this, error);
3784
+ if (!((_f = this.abortController) == null ? void 0 : _f.signal.aborted)) {
3785
+ this.scheduleInboundSseReconnection();
3786
+ }
3787
+ }
3788
+ }
3789
+ };
3790
+ function createMcpTransport(config) {
3791
+ switch (config.type) {
3792
+ case "sse":
3793
+ return new SseMCPTransport(config);
3794
+ case "http":
3795
+ return new HttpMCPTransport(config);
3796
+ default:
3797
+ throw new MCPClientError({
3798
+ message: "Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."
3799
+ });
3800
+ }
3801
+ }
3802
+ function isCustomMcpTransport(transport) {
3803
+ return "start" in transport && typeof transport.start === "function" && "send" in transport && typeof transport.send === "function" && "close" in transport && typeof transport.close === "function";
3804
+ }
3805
+ var CLIENT_VERSION = "1.0.0";
3806
+ function mcpToModelOutput({
3807
+ output
3808
+ }) {
3809
+ const result = output;
3810
+ if (!("content" in result) || !Array.isArray(result.content)) {
3811
+ return { type: "json", value: result };
3812
+ }
3813
+ const convertedContent = result.content.map(
3814
+ (part) => {
3815
+ if (part.type === "text" && "text" in part) {
3816
+ return { type: "text", text: part.text };
3817
+ }
3818
+ if (part.type === "image" && "data" in part && "mimeType" in part) {
3819
+ return {
3820
+ type: "image-data",
3821
+ data: part.data,
3822
+ mediaType: part.mimeType
3823
+ };
3824
+ }
3825
+ return { type: "text", text: JSON.stringify(part) };
3826
+ }
3827
+ );
3828
+ return { type: "content", value: convertedContent };
3829
+ }
3830
+ async function createMCPClient(config) {
3831
+ const client = new DefaultMCPClient(config);
3832
+ await client.init();
3833
+ return client;
3834
+ }
3835
+ var DefaultMCPClient = class {
3836
+ constructor({
3837
+ transport: transportConfig,
3838
+ name: name32 = "ai-sdk-mcp-client",
3839
+ version = CLIENT_VERSION,
3840
+ onUncaughtError,
3841
+ capabilities
3842
+ }) {
3843
+ this.requestMessageId = 0;
3844
+ this.responseHandlers = /* @__PURE__ */ new Map();
3845
+ this.serverCapabilities = {};
3846
+ this.isClosed = true;
3847
+ this.onUncaughtError = onUncaughtError;
3848
+ this.clientCapabilities = capabilities != null ? capabilities : {};
3849
+ if (isCustomMcpTransport(transportConfig)) {
3850
+ this.transport = transportConfig;
3851
+ } else {
3852
+ this.transport = createMcpTransport(transportConfig);
3853
+ }
3854
+ this.transport.onclose = () => this.onClose();
3855
+ this.transport.onerror = (error) => this.onError(error);
3856
+ this.transport.onmessage = (message) => {
3857
+ if ("method" in message) {
3858
+ if ("id" in message) {
3859
+ this.onRequestMessage(message);
3860
+ } else {
3861
+ this.onError(
3862
+ new MCPClientError({
3863
+ message: "Unsupported message type"
3864
+ })
3865
+ );
3866
+ }
3867
+ return;
3868
+ }
3869
+ this.onResponse(message);
3870
+ };
3871
+ this.clientInfo = {
3872
+ name: name32,
3873
+ version
3874
+ };
3875
+ }
3876
+ async init() {
3877
+ try {
3878
+ await this.transport.start();
3879
+ this.isClosed = false;
3880
+ const result = await this.request({
3881
+ request: {
3882
+ method: "initialize",
3883
+ params: {
3884
+ protocolVersion: LATEST_PROTOCOL_VERSION,
3885
+ capabilities: this.clientCapabilities,
3886
+ clientInfo: this.clientInfo
3887
+ }
3888
+ },
3889
+ resultSchema: InitializeResultSchema
3890
+ });
3891
+ if (result === void 0) {
3892
+ throw new MCPClientError({
3893
+ message: "Server sent invalid initialize result"
3894
+ });
3895
+ }
3896
+ if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
3897
+ throw new MCPClientError({
3898
+ message: `Server's protocol version is not supported: ${result.protocolVersion}`
3899
+ });
3900
+ }
3901
+ this.serverCapabilities = result.capabilities;
3902
+ await this.notification({
3903
+ method: "notifications/initialized"
3904
+ });
3905
+ return this;
3906
+ } catch (error) {
3907
+ await this.close();
3908
+ throw error;
3909
+ }
3910
+ }
3911
+ async close() {
3912
+ var _a32;
3913
+ if (this.isClosed) return;
3914
+ await ((_a32 = this.transport) == null ? void 0 : _a32.close());
3915
+ this.onClose();
3916
+ }
3917
+ assertCapability(method) {
3918
+ switch (method) {
3919
+ case "initialize":
3920
+ break;
3921
+ case "tools/list":
3922
+ case "tools/call":
3923
+ if (!this.serverCapabilities.tools) {
3924
+ throw new MCPClientError({
3925
+ message: `Server does not support tools`
3926
+ });
3927
+ }
3928
+ break;
3929
+ case "resources/list":
3930
+ case "resources/read":
3931
+ case "resources/templates/list":
3932
+ if (!this.serverCapabilities.resources) {
3933
+ throw new MCPClientError({
3934
+ message: `Server does not support resources`
3935
+ });
3936
+ }
3937
+ break;
3938
+ case "prompts/list":
3939
+ case "prompts/get":
3940
+ if (!this.serverCapabilities.prompts) {
3941
+ throw new MCPClientError({
3942
+ message: `Server does not support prompts`
3943
+ });
3944
+ }
3945
+ break;
3946
+ default:
3947
+ throw new MCPClientError({
3948
+ message: `Unsupported method: ${method}`
3949
+ });
3950
+ }
3951
+ }
3952
+ async request({
3953
+ request,
3954
+ resultSchema,
3955
+ options
3956
+ }) {
3957
+ return new Promise((resolve, reject) => {
3958
+ if (this.isClosed) {
3959
+ return reject(
3960
+ new MCPClientError({
3961
+ message: "Attempted to send a request from a closed client"
3962
+ })
3963
+ );
3964
+ }
3965
+ this.assertCapability(request.method);
3966
+ const signal = options == null ? void 0 : options.signal;
3967
+ signal == null ? void 0 : signal.throwIfAborted();
3968
+ const messageId = this.requestMessageId++;
3969
+ const jsonrpcRequest = {
3970
+ ...request,
3971
+ jsonrpc: "2.0",
3972
+ id: messageId
3973
+ };
3974
+ const cleanup2 = () => {
3975
+ this.responseHandlers.delete(messageId);
3976
+ };
3977
+ this.responseHandlers.set(messageId, (response) => {
3978
+ if (signal == null ? void 0 : signal.aborted) {
3979
+ return reject(
3980
+ new MCPClientError({
3981
+ message: "Request was aborted",
3982
+ cause: signal.reason
3983
+ })
3984
+ );
3985
+ }
3986
+ if (response instanceof Error) {
3987
+ return reject(response);
3988
+ }
3989
+ try {
3990
+ const result = resultSchema.parse(response.result);
3991
+ resolve(result);
3992
+ } catch (error) {
3993
+ const parseError = new MCPClientError({
3994
+ message: "Failed to parse server response",
3995
+ cause: error
3996
+ });
3997
+ reject(parseError);
3998
+ }
3999
+ });
4000
+ this.transport.send(jsonrpcRequest).catch((error) => {
4001
+ cleanup2();
4002
+ reject(error);
4003
+ });
4004
+ });
4005
+ }
4006
+ async listTools({
4007
+ params,
4008
+ options
4009
+ } = {}) {
4010
+ return this.request({
4011
+ request: { method: "tools/list", params },
4012
+ resultSchema: ListToolsResultSchema,
4013
+ options
4014
+ });
4015
+ }
4016
+ async callTool({
4017
+ name: name32,
4018
+ args,
4019
+ options
4020
+ }) {
4021
+ try {
4022
+ return this.request({
4023
+ request: { method: "tools/call", params: { name: name32, arguments: args } },
4024
+ resultSchema: CallToolResultSchema,
4025
+ options: {
4026
+ signal: options == null ? void 0 : options.abortSignal
4027
+ }
4028
+ });
4029
+ } catch (error) {
4030
+ throw error;
4031
+ }
4032
+ }
4033
+ async listResourcesInternal({
4034
+ params,
4035
+ options
4036
+ } = {}) {
4037
+ try {
4038
+ return this.request({
4039
+ request: { method: "resources/list", params },
4040
+ resultSchema: ListResourcesResultSchema,
4041
+ options
4042
+ });
4043
+ } catch (error) {
4044
+ throw error;
4045
+ }
4046
+ }
4047
+ async readResourceInternal({
4048
+ uri,
4049
+ options
4050
+ }) {
4051
+ try {
4052
+ return this.request({
4053
+ request: { method: "resources/read", params: { uri } },
4054
+ resultSchema: ReadResourceResultSchema,
4055
+ options
4056
+ });
4057
+ } catch (error) {
4058
+ throw error;
4059
+ }
4060
+ }
4061
+ async listResourceTemplatesInternal({
4062
+ options
4063
+ } = {}) {
4064
+ try {
4065
+ return this.request({
4066
+ request: { method: "resources/templates/list" },
4067
+ resultSchema: ListResourceTemplatesResultSchema,
4068
+ options
4069
+ });
4070
+ } catch (error) {
4071
+ throw error;
4072
+ }
4073
+ }
4074
+ async listPromptsInternal({
4075
+ params,
4076
+ options
4077
+ } = {}) {
4078
+ try {
4079
+ return this.request({
4080
+ request: { method: "prompts/list", params },
4081
+ resultSchema: ListPromptsResultSchema,
4082
+ options
4083
+ });
4084
+ } catch (error) {
4085
+ throw error;
4086
+ }
4087
+ }
4088
+ async getPromptInternal({
4089
+ name: name32,
4090
+ args,
4091
+ options
4092
+ }) {
4093
+ try {
4094
+ return this.request({
4095
+ request: { method: "prompts/get", params: { name: name32, arguments: args } },
4096
+ resultSchema: GetPromptResultSchema,
4097
+ options
4098
+ });
4099
+ } catch (error) {
4100
+ throw error;
4101
+ }
4102
+ }
4103
+ async notification(notification) {
4104
+ const jsonrpcNotification = {
4105
+ ...notification,
4106
+ jsonrpc: "2.0"
4107
+ };
4108
+ await this.transport.send(jsonrpcNotification);
4109
+ }
4110
+ /**
4111
+ * Returns a set of AI SDK tools from the MCP server.
4112
+ * This fetches tool definitions and wraps them with execute functions.
4113
+ * @returns A record of tool names to their implementations
4114
+ */
4115
+ async tools({
4116
+ schemas = "automatic"
4117
+ } = {}) {
4118
+ const definitions = await this.listTools();
4119
+ return this.toolsFromDefinitions(definitions, {
4120
+ schemas
4121
+ });
4122
+ }
4123
+ /**
4124
+ * Creates AI SDK tools from tool definitions without fetching from the server.
4125
+ */
4126
+ toolsFromDefinitions(definitions, { schemas = "automatic" } = {}) {
4127
+ var _a32, _b32;
4128
+ const tools = {};
4129
+ for (const {
4130
+ name: name32,
4131
+ title,
4132
+ description,
4133
+ inputSchema,
4134
+ annotations,
4135
+ _meta
4136
+ } of definitions.tools) {
4137
+ const resolvedTitle = title != null ? title : annotations == null ? void 0 : annotations.title;
4138
+ if (schemas !== "automatic" && !(name32 in schemas)) {
4139
+ continue;
4140
+ }
4141
+ const self = this;
4142
+ const outputSchema = schemas !== "automatic" ? (_a32 = schemas[name32]) == null ? void 0 : _a32.outputSchema : void 0;
4143
+ const execute = async (args, options) => {
4144
+ var _a42;
4145
+ (_a42 = options == null ? void 0 : options.abortSignal) == null ? void 0 : _a42.throwIfAborted();
4146
+ const result = await self.callTool({ name: name32, args, options });
4147
+ if (outputSchema != null) {
4148
+ return self.extractStructuredContent(result, outputSchema, name32);
4149
+ }
4150
+ return result;
4151
+ };
4152
+ const toolWithExecute = schemas === "automatic" ? dynamicTool({
4153
+ description,
4154
+ title: resolvedTitle,
4155
+ inputSchema: jsonSchema({
4156
+ ...inputSchema,
4157
+ properties: (_b32 = inputSchema.properties) != null ? _b32 : {},
4158
+ additionalProperties: false
4159
+ }),
4160
+ execute,
4161
+ toModelOutput: mcpToModelOutput
4162
+ }) : tool({
4163
+ description,
4164
+ title: resolvedTitle,
4165
+ inputSchema: schemas[name32].inputSchema,
4166
+ ...outputSchema != null ? { outputSchema } : {},
4167
+ execute,
4168
+ toModelOutput: mcpToModelOutput
4169
+ });
4170
+ tools[name32] = { ...toolWithExecute, _meta };
4171
+ }
4172
+ return tools;
4173
+ }
4174
+ /**
4175
+ * Extracts and validates structuredContent from a tool result.
4176
+ */
4177
+ async extractStructuredContent(result, outputSchema, toolName) {
4178
+ if ("structuredContent" in result && result.structuredContent != null) {
4179
+ const validationResult = await safeValidateTypes({
4180
+ value: result.structuredContent,
4181
+ schema: asSchema(outputSchema)
4182
+ });
4183
+ if (!validationResult.success) {
4184
+ throw new MCPClientError({
4185
+ message: `Tool "${toolName}" returned structuredContent that does not match the expected outputSchema`,
4186
+ cause: validationResult.error
4187
+ });
4188
+ }
4189
+ return validationResult.value;
4190
+ }
4191
+ if ("content" in result && Array.isArray(result.content)) {
4192
+ const textContent = result.content.find((c) => c.type === "text");
4193
+ if (textContent && "text" in textContent) {
4194
+ const parseResult = await safeParseJSON({
4195
+ text: textContent.text,
4196
+ schema: outputSchema
4197
+ });
4198
+ if (!parseResult.success) {
4199
+ throw new MCPClientError({
4200
+ message: `Tool "${toolName}" returned content that does not match the expected outputSchema`,
4201
+ cause: parseResult.error
4202
+ });
4203
+ }
4204
+ return parseResult.value;
4205
+ }
4206
+ }
4207
+ throw new MCPClientError({
4208
+ message: `Tool "${toolName}" did not return structuredContent or parseable text content`
4209
+ });
4210
+ }
4211
+ listResources({
4212
+ params,
4213
+ options
4214
+ } = {}) {
4215
+ return this.listResourcesInternal({ params, options });
4216
+ }
4217
+ readResource({
4218
+ uri,
4219
+ options
4220
+ }) {
4221
+ return this.readResourceInternal({ uri, options });
4222
+ }
4223
+ listResourceTemplates({
4224
+ options
4225
+ } = {}) {
4226
+ return this.listResourceTemplatesInternal({ options });
4227
+ }
4228
+ experimental_listPrompts({
4229
+ params,
4230
+ options
4231
+ } = {}) {
4232
+ return this.listPromptsInternal({ params, options });
4233
+ }
4234
+ experimental_getPrompt({
4235
+ name: name32,
4236
+ arguments: args,
4237
+ options
4238
+ }) {
4239
+ return this.getPromptInternal({ name: name32, args, options });
4240
+ }
4241
+ onElicitationRequest(schema, handler) {
4242
+ if (schema !== ElicitationRequestSchema) {
4243
+ throw new MCPClientError({
4244
+ message: "Unsupported request schema. Only ElicitationRequestSchema is supported."
4245
+ });
4246
+ }
4247
+ this.elicitationRequestHandler = handler;
4248
+ }
4249
+ async onRequestMessage(request) {
4250
+ try {
4251
+ if (request.method !== "elicitation/create") {
4252
+ await this.transport.send({
4253
+ jsonrpc: "2.0",
4254
+ id: request.id,
4255
+ error: {
4256
+ code: -32601,
4257
+ message: `Unsupported request method: ${request.method}`
4258
+ }
4259
+ });
4260
+ return;
4261
+ }
4262
+ if (!this.elicitationRequestHandler) {
4263
+ await this.transport.send({
4264
+ jsonrpc: "2.0",
4265
+ id: request.id,
4266
+ error: {
4267
+ code: -32601,
4268
+ message: "No elicitation handler registered on client"
4269
+ }
4270
+ });
4271
+ return;
4272
+ }
4273
+ const parsedRequest = ElicitationRequestSchema.safeParse({
4274
+ method: request.method,
4275
+ params: request.params
4276
+ });
4277
+ if (!parsedRequest.success) {
4278
+ await this.transport.send({
4279
+ jsonrpc: "2.0",
4280
+ id: request.id,
4281
+ error: {
4282
+ code: -32602,
4283
+ message: `Invalid elicitation request: ${parsedRequest.error.message}`,
4284
+ data: parsedRequest.error.issues
4285
+ }
4286
+ });
4287
+ return;
4288
+ }
4289
+ try {
4290
+ const result = await this.elicitationRequestHandler(parsedRequest.data);
4291
+ const validatedResult = ElicitResultSchema.parse(result);
4292
+ await this.transport.send({
4293
+ jsonrpc: "2.0",
4294
+ id: request.id,
4295
+ result: validatedResult
4296
+ });
4297
+ } catch (error) {
4298
+ await this.transport.send({
4299
+ jsonrpc: "2.0",
4300
+ id: request.id,
4301
+ error: {
4302
+ code: -32603,
4303
+ message: error instanceof Error ? error.message : "Failed to handle elicitation request"
4304
+ }
4305
+ });
4306
+ this.onError(error);
4307
+ }
4308
+ } catch (error) {
4309
+ this.onError(error);
4310
+ }
4311
+ }
4312
+ onClose() {
4313
+ if (this.isClosed) return;
4314
+ this.isClosed = true;
4315
+ const error = new MCPClientError({
4316
+ message: "Connection closed"
4317
+ });
4318
+ for (const handler of this.responseHandlers.values()) {
4319
+ handler(error);
4320
+ }
4321
+ this.responseHandlers.clear();
4322
+ }
4323
+ onError(error) {
4324
+ if (this.onUncaughtError) {
4325
+ this.onUncaughtError(error);
4326
+ }
4327
+ }
4328
+ onResponse(response) {
4329
+ const messageId = Number(response.id);
4330
+ const handler = this.responseHandlers.get(messageId);
4331
+ if (handler === void 0) {
4332
+ throw new MCPClientError({
4333
+ message: `Protocol error: Received a response for an unknown message ID: ${JSON.stringify(
4334
+ response
4335
+ )}`
4336
+ });
4337
+ }
4338
+ this.responseHandlers.delete(messageId);
4339
+ handler(
4340
+ "result" in response ? response : new MCPClientError({
4341
+ message: response.error.message,
4342
+ code: response.error.code,
4343
+ data: response.error.data,
4344
+ cause: response.error
4345
+ })
4346
+ );
4347
+ }
4348
+ };
4349
+
4350
+ // src/adapters/vercel-ai.ts
4351
+ async function createVercelAiMcpClient(options) {
4352
+ const { url, headers } = options;
4353
+ const client = await createMCPClient({
4354
+ transport: {
4355
+ type: "http",
4356
+ url,
4357
+ headers
4358
+ }
4359
+ });
4360
+ return client;
4361
+ }
4362
+
4363
+ // src/core/base.ts
4364
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4365
+ import { z as z8 } from "zod";
360
4366
  function createBaseMcpServer(options) {
361
4367
  const server = new McpServer({
362
4368
  name: "corsair",
@@ -366,7 +4372,7 @@ function createBaseMcpServer(options) {
366
4372
  for (const def of buildCorsairToolDefs(options)) {
367
4373
  server.registerTool(
368
4374
  def.name,
369
- { description: def.description, inputSchema: z6.object(def.shape) },
4375
+ { description: def.description, inputSchema: z8.object(def.shape) },
370
4376
  def.handler
371
4377
  );
372
4378
  }