@corsair-dev/mcp 0.1.27 → 0.1.29

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