@corsair-dev/mcp 0.1.22 → 0.1.24

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