eve 0.52.4 → 0.53.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/dist/src/cli/commands/init-agent-workspace.d.ts +2 -0
- package/dist/src/cli/commands/init-agent-workspace.js +1 -1
- package/dist/src/cli/commands/init-install.d.ts +8 -0
- package/dist/src/cli/commands/init-install.js +1 -0
- package/dist/src/cli/commands/init.d.ts +3 -4
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/dev/tui/message-queue.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
- package/dist/src/cli/run.js +2 -2
- package/dist/src/cli/telemetry/index.d.ts +3 -0
- package/dist/src/cli/telemetry/index.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +17 -16
- package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +23 -2
- package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -4
- package/dist/src/compiled/@ai-sdk/google/index.d.ts +145 -33
- package/dist/src/compiled/@ai-sdk/google/index.js +10 -7
- package/dist/src/compiled/@ai-sdk/mcp/index.d.ts +176 -7
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/openai/index.d.ts +71 -40
- package/dist/src/compiled/@ai-sdk/openai/index.js +8 -8
- package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/provider/index.d.ts +225 -3
- package/dist/src/compiled/@ai-sdk/provider-utils/index.d.ts +220 -151
- package/dist/src/compiled/@workflow/core/create-hook.d.ts +3 -0
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/private.js +1 -1
- package/dist/src/compiled/@workflow/core/runtime/resume-hook.d.ts +59 -7
- package/dist/src/compiled/@workflow/core/runtime/run.d.ts +42 -0
- package/dist/src/compiled/@workflow/core/runtime/start.d.ts +31 -1
- package/dist/src/compiled/@workflow/core/runtime.d.ts +2 -2
- package/dist/src/compiled/@workflow/core/runtime.js +2 -2
- package/dist/src/compiled/@workflow/core/serialization.d.ts +22 -0
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/index.d.ts +37 -3
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/@workflow/world/attributes-validation.d.ts +68 -0
- package/dist/src/compiled/@workflow/world/index.d.ts +1 -1
- package/dist/src/compiled/@workflow/world/interfaces.d.ts +21 -0
- package/dist/src/compiled/@workflow/world-local/index.js +5 -5
- package/dist/src/compiled/@workflow/world-vercel/index.js +3 -3
- package/dist/src/compiled/_chunks/workflow/attribute-changes-C6H-fRVP.js +20 -0
- package/dist/src/compiled/_chunks/workflow/dist-DDeH-1ER.js +40 -0
- package/dist/src/compiled/_chunks/workflow/dist-DhncQSl7.js +74 -0
- package/dist/src/compiled/_chunks/workflow/{dist-BIO9Inoc.js → dist-xTushGCp.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/frames-DsEqSDes.js +3 -0
- package/dist/src/compiled/_chunks/workflow/{private-aXEeo0fU.js → private-CFJkQA7R.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/resume-hook-BRDLAb67.js +1 -0
- package/dist/src/compiled/_chunks/workflow/run-BM2OFphk.js +1 -0
- package/dist/src/compiled/_chunks/workflow/sleep-6cG0F99-.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{ws-transport-M7uk8HV8.js → ws-transport-DuK82LLz.js} +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +7 -6
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/compiler/normalize-manifest-helpers.js +1 -1
- package/dist/src/context/dynamic-model-lifecycle.js +1 -1
- package/dist/src/context/keys.d.ts +11 -2
- package/dist/src/context/keys.js +1 -1
- package/dist/src/evals/mock-model.js +1 -1
- package/dist/src/evals/runner/run-evals.d.ts +1 -1
- package/dist/src/evals/runner/run-evals.js +1 -1
- package/dist/src/execution/activity-cohort.d.ts +20 -0
- package/dist/src/execution/activity-cohort.js +1 -0
- package/dist/src/execution/authorization-callback-match.d.ts +1 -0
- package/dist/src/execution/authorization-callback-match.js +1 -1
- package/dist/src/execution/cancelled-model-call-batch.d.ts +15 -0
- package/dist/src/execution/cancelled-model-call-batch.js +1 -0
- package/dist/src/execution/coordination-dispatch-shared.js +1 -1
- package/dist/src/execution/model-call-batching.d.ts +11 -0
- package/dist/src/execution/model-call-batching.js +1 -0
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/session-activity-projection.d.ts +2 -0
- package/dist/src/execution/session-activity-projection.js +1 -1
- package/dist/src/execution/skills/instructions.js +1 -1
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-agent.d.ts +5 -5
- package/dist/src/execution/tools/subagent/invoke-agent.js +1 -1
- package/dist/src/execution/tools/subagent/start.js +1 -1
- package/dist/src/execution/tools/workflow/body.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/wire/session-inbox-resume.js +1 -1
- package/dist/src/execution/workflow-steps.d.ts +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/approval-delivery-coordinator.js +1 -1
- package/dist/src/harness/authorization.d.ts +1 -0
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/compaction.js +1 -1
- package/dist/src/harness/current-messages.d.ts +8 -2
- package/dist/src/harness/current-messages.js +1 -1
- package/dist/src/harness/hitl/approval-input-requests.js +1 -1
- package/dist/src/harness/input-requests.js +1 -1
- package/dist/src/harness/pending-input-batches.d.ts +4 -0
- package/dist/src/harness/pending-input-batches.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/turn-client-context.d.ts +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/core.js +1 -1
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/mock-model-identity.d.ts +2 -0
- package/dist/src/internal/mock-model-identity.js +1 -0
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
- package/dist/src/internal/workflow-bundle/authored-workflow-directives.js +1 -1
- package/dist/src/public/tools/index.d.ts +1 -0
- package/dist/src/public/tools/index.js +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/self-modification/agent.d.ts +2 -2
- package/dist/src/self-modification/agent.js +1 -1
- package/dist/src/self-modification/config.d.ts +15 -0
- package/dist/src/self-modification/config.js +1 -1
- package/dist/src/self-modification/extension/extension.d.ts +3 -0
- package/dist/src/self-modification/extension/extension.js +1 -1
- package/dist/src/self-modification/setup.d.ts +3 -0
- package/dist/src/self-modification/setup.js +25 -4
- package/dist/src/setup/integrations/self-modification/setup.js +1 -1
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/update/web-options.js +1 -1
- package/dist/src/shared/agent-definition.d.ts +11 -2
- package/dist/src/tasks/delivery-context.d.ts +2 -2
- package/dist/src/tasks/delivery-context.js +2 -18
- package/dist/src/tasks/delivery-policy.js +1 -1
- package/dist/src/tools/durable-callbacks.d.ts +18 -1
- package/dist/src/tools/durable-callbacks.js +1 -1
- package/dist/src/tools/workflow-definition.d.ts +38 -4
- package/docs/agent-config.md +44 -8
- package/docs/channels/overview.mdx +2 -0
- package/docs/channels/slack.mdx +2 -0
- package/docs/concepts/execution-model-and-durability.mdx +20 -2
- package/docs/evals/running.mdx +3 -1
- package/docs/guides/dev-tui.md +11 -11
- package/docs/guides/dynamic-capabilities.md +36 -1
- package/docs/guides/instrumentation.md +3 -2
- package/docs/instructions.mdx +1 -1
- package/docs/reference/cli.md +1 -1
- package/docs/reference/telemetry.md +1 -1
- package/docs/reference/typescript-api.md +36 -35
- package/docs/subagents/index.mdx +1 -1
- package/docs/tools/overview.mdx +4 -2
- package/docs/tools/workflows.mdx +15 -10
- package/package.json +17 -17
- package/dist/src/compiled/_chunks/workflow/attribute-changes-DpruylJZ.js +0 -20
- package/dist/src/compiled/_chunks/workflow/dist-ChzQSWQA.js +0 -65
- package/dist/src/compiled/_chunks/workflow/dist-veFIAdWV.js +0 -40
- package/dist/src/compiled/_chunks/workflow/frames-DKxlMf3X.js +0 -3
- package/dist/src/compiled/_chunks/workflow/resume-hook-DWDi_wCN.js +0 -1
- package/dist/src/compiled/_chunks/workflow/run-vsAdI41O.js +0 -1
- package/dist/src/compiled/_chunks/workflow/sleep-BKxoNDRv.js +0 -1
|
@@ -16,12 +16,13 @@ declare const JSONRPCResponseSchema: z.ZodObject<{
|
|
|
16
16
|
id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
|
|
17
17
|
result: z.ZodObject<{
|
|
18
18
|
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
19
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
19
20
|
}, z.core.$loose>;
|
|
20
21
|
}, z.core.$strict>;
|
|
21
22
|
type JSONRPCResponse = z.infer<typeof JSONRPCResponseSchema>;
|
|
22
23
|
declare const JSONRPCErrorSchema: z.ZodObject<{
|
|
23
24
|
jsonrpc: z.ZodLiteral<"2.0">;
|
|
24
|
-
id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]
|
|
25
|
+
id: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
25
26
|
error: z.ZodObject<{
|
|
26
27
|
code: z.ZodNumber;
|
|
27
28
|
message: z.ZodString;
|
|
@@ -55,10 +56,11 @@ declare const JSONRPCMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
|
55
56
|
id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
|
|
56
57
|
result: z.ZodObject<{
|
|
57
58
|
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
59
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
58
60
|
}, z.core.$loose>;
|
|
59
61
|
}, z.core.$strict>, z.ZodObject<{
|
|
60
62
|
jsonrpc: z.ZodLiteral<"2.0">;
|
|
61
|
-
id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]
|
|
63
|
+
id: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
62
64
|
error: z.ZodObject<{
|
|
63
65
|
code: z.ZodNumber;
|
|
64
66
|
message: z.ZodString;
|
|
@@ -78,6 +80,7 @@ declare const OAuthTokensSchema: z.ZodObject<{
|
|
|
78
80
|
expires_in: z.ZodOptional<z.ZodNumber>;
|
|
79
81
|
scope: z.ZodOptional<z.ZodString>;
|
|
80
82
|
refresh_token: z.ZodOptional<z.ZodString>;
|
|
83
|
+
issuer: z.ZodOptional<z.ZodString>;
|
|
81
84
|
authorization_server: z.ZodOptional<z.ZodString>;
|
|
82
85
|
token_endpoint: z.ZodOptional<z.ZodString>;
|
|
83
86
|
}, z.core.$strip>;
|
|
@@ -86,6 +89,8 @@ declare const OAuthMetadataSchema: z.ZodObject<{
|
|
|
86
89
|
authorization_endpoint: z.ZodString;
|
|
87
90
|
token_endpoint: z.ZodString;
|
|
88
91
|
registration_endpoint: z.ZodOptional<z.ZodString>;
|
|
92
|
+
authorization_response_iss_parameter_supported: z.ZodOptional<z.ZodBoolean>;
|
|
93
|
+
client_id_metadata_document_supported: z.ZodOptional<z.ZodBoolean>;
|
|
89
94
|
scopes_supported: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
90
95
|
response_types_supported: z.ZodArray<z.ZodString>;
|
|
91
96
|
grant_types_supported: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
@@ -105,6 +110,8 @@ declare const OpenIdProviderDiscoveryMetadataSchema: z.ZodObject<{
|
|
|
105
110
|
userinfo_endpoint: z.ZodOptional<z.ZodString>;
|
|
106
111
|
jwks_uri: z.ZodString;
|
|
107
112
|
registration_endpoint: z.ZodOptional<z.ZodString>;
|
|
113
|
+
authorization_response_iss_parameter_supported: z.ZodOptional<z.ZodBoolean>;
|
|
114
|
+
client_id_metadata_document_supported: z.ZodOptional<z.ZodBoolean>;
|
|
108
115
|
scopes_supported: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
109
116
|
response_types_supported: z.ZodArray<z.ZodString>;
|
|
110
117
|
grant_types_supported: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
@@ -119,11 +126,13 @@ declare const OAuthClientInformationSchema: z.ZodObject<{
|
|
|
119
126
|
client_secret: z.ZodOptional<z.ZodString>;
|
|
120
127
|
client_id_issued_at: z.ZodOptional<z.ZodNumber>;
|
|
121
128
|
client_secret_expires_at: z.ZodOptional<z.ZodNumber>;
|
|
129
|
+
issuer: z.ZodOptional<z.ZodString>;
|
|
122
130
|
authorization_server: z.ZodOptional<z.ZodString>;
|
|
123
131
|
token_endpoint: z.ZodOptional<z.ZodString>;
|
|
124
132
|
}, z.core.$strip>;
|
|
125
133
|
declare const OAuthClientMetadataSchema: z.ZodObject<{
|
|
126
134
|
redirect_uris: z.ZodArray<z.ZodString>;
|
|
135
|
+
application_type: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"native">, z.ZodLiteral<"web">]>>;
|
|
127
136
|
token_endpoint_auth_method: z.ZodOptional<z.ZodString>;
|
|
128
137
|
grant_types: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
129
138
|
response_types: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
@@ -149,6 +158,7 @@ type OAuthClientMetadata = z.infer<typeof OAuthClientMetadataSchema>;
|
|
|
149
158
|
|
|
150
159
|
type AuthResult = 'AUTHORIZED' | 'REDIRECT';
|
|
151
160
|
interface OAuthAuthorizationServerInformation {
|
|
161
|
+
issuer?: string;
|
|
152
162
|
authorizationServerUrl: string;
|
|
153
163
|
tokenEndpoint: string;
|
|
154
164
|
}
|
|
@@ -209,6 +219,10 @@ declare function auth(provider: OAuthClientProvider, options: {
|
|
|
209
219
|
serverUrl: string | URL;
|
|
210
220
|
authorizationCode?: string;
|
|
211
221
|
callbackState?: string;
|
|
222
|
+
/**
|
|
223
|
+
* Value of the `iss` parameter from the authorization response.
|
|
224
|
+
*/
|
|
225
|
+
callbackIssuer?: string;
|
|
212
226
|
scope?: string;
|
|
213
227
|
resourceMetadataUrl?: URL;
|
|
214
228
|
fetchFn?: FetchFunction;
|
|
@@ -223,6 +237,10 @@ type MCPTransportSendOptions = {
|
|
|
223
237
|
* Cancels the transport operation for this message.
|
|
224
238
|
*/
|
|
225
239
|
signal?: AbortSignal;
|
|
240
|
+
/**
|
|
241
|
+
* Request-specific HTTP headers produced from MCP tool parameters.
|
|
242
|
+
*/
|
|
243
|
+
headers?: Record<string, string>;
|
|
226
244
|
/**
|
|
227
245
|
* Associates an outgoing message with an incoming request.
|
|
228
246
|
*/
|
|
@@ -243,6 +261,18 @@ type MCPTransportCloseOptions = {
|
|
|
243
261
|
signal?: AbortSignal;
|
|
244
262
|
};
|
|
245
263
|
interface MCPTransport {
|
|
264
|
+
/**
|
|
265
|
+
* Whether this transport can probe for stateless MCP protocol versions.
|
|
266
|
+
*
|
|
267
|
+
* Custom transports default to the legacy initialization flow unless they
|
|
268
|
+
* explicitly opt in.
|
|
269
|
+
*/
|
|
270
|
+
supportsProtocolVersionDiscovery?: boolean;
|
|
271
|
+
/**
|
|
272
|
+
* Whether this transport mirrors x-mcp-header tool parameters into request
|
|
273
|
+
* headers.
|
|
274
|
+
*/
|
|
275
|
+
supportsMcpToolParameterHeaders?: boolean;
|
|
246
276
|
/**
|
|
247
277
|
* Initialize and start the transport
|
|
248
278
|
*/
|
|
@@ -343,8 +373,23 @@ type McpProviderMetadata = {
|
|
|
343
373
|
clientName?: string;
|
|
344
374
|
title?: string;
|
|
345
375
|
toolName?: string;
|
|
376
|
+
annotations?: McpToolAnnotations;
|
|
346
377
|
app?: JSONObject;
|
|
347
378
|
};
|
|
379
|
+
/**
|
|
380
|
+
* Behavioral hints reported by an MCP server for a tool.
|
|
381
|
+
*
|
|
382
|
+
* These annotations are untrusted unless the server itself is trusted.
|
|
383
|
+
*
|
|
384
|
+
* @see https://modelcontextprotocol.io/specification/2026-07-28/schema#toolannotations
|
|
385
|
+
*/
|
|
386
|
+
type McpToolAnnotations = {
|
|
387
|
+
title?: string;
|
|
388
|
+
readOnlyHint?: boolean;
|
|
389
|
+
destructiveHint?: boolean;
|
|
390
|
+
idempotentHint?: boolean;
|
|
391
|
+
openWorldHint?: boolean;
|
|
392
|
+
};
|
|
348
393
|
/** MCP tool metadata - keys should follow MCP _meta key format specification */
|
|
349
394
|
declare const ToolMetaSchema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
350
395
|
type ToolMeta = z.infer<typeof ToolMetaSchema>;
|
|
@@ -397,6 +442,7 @@ declare const ClientCapabilitiesSchema: z.ZodObject<{
|
|
|
397
442
|
type ClientCapabilities = z.infer<typeof ClientCapabilitiesSchema>;
|
|
398
443
|
declare const InitializeResultSchema: z.ZodObject<{
|
|
399
444
|
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
445
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
400
446
|
protocolVersion: z.ZodString;
|
|
401
447
|
capabilities: z.ZodObject<{
|
|
402
448
|
experimental: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
@@ -431,18 +477,23 @@ type PaginatedRequest = Request & {
|
|
|
431
477
|
};
|
|
432
478
|
declare const ListToolsResultSchema: z.ZodObject<{
|
|
433
479
|
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
480
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
434
481
|
nextCursor: z.ZodOptional<z.ZodString>;
|
|
435
482
|
tools: z.ZodArray<z.ZodObject<{
|
|
436
483
|
name: z.ZodString;
|
|
437
484
|
title: z.ZodOptional<z.ZodString>;
|
|
438
485
|
description: z.ZodOptional<z.ZodString>;
|
|
439
486
|
inputSchema: z.ZodObject<{
|
|
440
|
-
type: z.
|
|
487
|
+
type: z.ZodOptional<z.ZodUnknown>;
|
|
441
488
|
properties: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
442
489
|
}, z.core.$loose>;
|
|
443
490
|
outputSchema: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
444
491
|
annotations: z.ZodOptional<z.ZodObject<{
|
|
445
492
|
title: z.ZodOptional<z.ZodString>;
|
|
493
|
+
readOnlyHint: z.ZodOptional<z.ZodBoolean>;
|
|
494
|
+
destructiveHint: z.ZodOptional<z.ZodBoolean>;
|
|
495
|
+
idempotentHint: z.ZodOptional<z.ZodBoolean>;
|
|
496
|
+
openWorldHint: z.ZodOptional<z.ZodBoolean>;
|
|
446
497
|
}, z.core.$loose>>;
|
|
447
498
|
_meta: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
448
499
|
}, z.core.$loose>>;
|
|
@@ -450,6 +501,7 @@ declare const ListToolsResultSchema: z.ZodObject<{
|
|
|
450
501
|
type ListToolsResult = z.infer<typeof ListToolsResultSchema>;
|
|
451
502
|
declare const ListResourcesResultSchema: z.ZodObject<{
|
|
452
503
|
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
504
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
453
505
|
nextCursor: z.ZodOptional<z.ZodString>;
|
|
454
506
|
resources: z.ZodArray<z.ZodObject<{
|
|
455
507
|
uri: z.ZodString;
|
|
@@ -461,8 +513,106 @@ declare const ListResourcesResultSchema: z.ZodObject<{
|
|
|
461
513
|
}, z.core.$loose>>;
|
|
462
514
|
}, z.core.$loose>;
|
|
463
515
|
type ListResourcesResult = z.infer<typeof ListResourcesResultSchema>;
|
|
464
|
-
declare const CallToolResultSchema: z.ZodUnion<[z.ZodObject<{
|
|
516
|
+
declare const CallToolResultSchema: z.ZodUnion<[z.ZodUnion<[z.ZodObject<{
|
|
517
|
+
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
518
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
519
|
+
content: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
|
|
520
|
+
type: z.ZodLiteral<"text">;
|
|
521
|
+
text: z.ZodString;
|
|
522
|
+
}, z.core.$loose>, z.ZodObject<{
|
|
523
|
+
type: z.ZodLiteral<"image">;
|
|
524
|
+
data: z.ZodBase64;
|
|
525
|
+
mimeType: z.ZodString;
|
|
526
|
+
}, z.core.$loose>, z.ZodObject<{
|
|
527
|
+
type: z.ZodLiteral<"resource">;
|
|
528
|
+
resource: z.ZodUnion<readonly [z.ZodObject<{
|
|
529
|
+
uri: z.ZodString;
|
|
530
|
+
name: z.ZodOptional<z.ZodString>;
|
|
531
|
+
title: z.ZodOptional<z.ZodString>;
|
|
532
|
+
mimeType: z.ZodOptional<z.ZodString>;
|
|
533
|
+
text: z.ZodString;
|
|
534
|
+
}, z.core.$loose>, z.ZodObject<{
|
|
535
|
+
uri: z.ZodString;
|
|
536
|
+
name: z.ZodOptional<z.ZodString>;
|
|
537
|
+
title: z.ZodOptional<z.ZodString>;
|
|
538
|
+
mimeType: z.ZodOptional<z.ZodString>;
|
|
539
|
+
blob: z.ZodBase64;
|
|
540
|
+
}, z.core.$loose>]>;
|
|
541
|
+
}, z.core.$loose>, z.ZodObject<{
|
|
542
|
+
type: z.ZodLiteral<"resource_link">;
|
|
543
|
+
uri: z.ZodString;
|
|
544
|
+
name: z.ZodString;
|
|
545
|
+
description: z.ZodOptional<z.ZodString>;
|
|
546
|
+
mimeType: z.ZodOptional<z.ZodString>;
|
|
547
|
+
}, z.core.$loose>, z.ZodObject<{
|
|
548
|
+
type: z.ZodString;
|
|
549
|
+
}, z.core.$loose>]>>;
|
|
550
|
+
structuredContent: z.ZodOptional<z.ZodUnknown>;
|
|
551
|
+
isError: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
|
|
552
|
+
}, z.core.$loose>, z.ZodPipe<z.ZodPipe<z.ZodObject<{
|
|
465
553
|
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
554
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
555
|
+
content: z.ZodOptional<z.ZodNever>;
|
|
556
|
+
structuredContent: z.ZodJSONSchema;
|
|
557
|
+
isError: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
|
|
558
|
+
}, z.core.$loose>, z.ZodTransform<{
|
|
559
|
+
[x: string]: unknown;
|
|
560
|
+
content: ({
|
|
561
|
+
[x: string]: unknown;
|
|
562
|
+
type: "text";
|
|
563
|
+
text: string;
|
|
564
|
+
} | {
|
|
565
|
+
[x: string]: unknown;
|
|
566
|
+
type: "image";
|
|
567
|
+
data: string;
|
|
568
|
+
mimeType: string;
|
|
569
|
+
} | {
|
|
570
|
+
[x: string]: unknown;
|
|
571
|
+
type: "resource";
|
|
572
|
+
resource: {
|
|
573
|
+
[x: string]: unknown;
|
|
574
|
+
uri: string;
|
|
575
|
+
text: string;
|
|
576
|
+
name?: string | undefined;
|
|
577
|
+
title?: string | undefined;
|
|
578
|
+
mimeType?: string | undefined;
|
|
579
|
+
} | {
|
|
580
|
+
[x: string]: unknown;
|
|
581
|
+
uri: string;
|
|
582
|
+
blob: string;
|
|
583
|
+
name?: string | undefined;
|
|
584
|
+
title?: string | undefined;
|
|
585
|
+
mimeType?: string | undefined;
|
|
586
|
+
};
|
|
587
|
+
} | {
|
|
588
|
+
[x: string]: unknown;
|
|
589
|
+
type: "resource_link";
|
|
590
|
+
uri: string;
|
|
591
|
+
name: string;
|
|
592
|
+
description?: string | undefined;
|
|
593
|
+
mimeType?: string | undefined;
|
|
594
|
+
} | {
|
|
595
|
+
[x: string]: unknown;
|
|
596
|
+
type: string;
|
|
597
|
+
})[];
|
|
598
|
+
_meta?: {
|
|
599
|
+
[x: string]: unknown;
|
|
600
|
+
} | undefined;
|
|
601
|
+
resultType?: string | undefined;
|
|
602
|
+
structuredContent?: unknown;
|
|
603
|
+
isError?: boolean | undefined;
|
|
604
|
+
}, {
|
|
605
|
+
[x: string]: unknown;
|
|
606
|
+
structuredContent: z.core.util.JSONType;
|
|
607
|
+
_meta?: {
|
|
608
|
+
[x: string]: unknown;
|
|
609
|
+
} | undefined;
|
|
610
|
+
resultType?: string | undefined;
|
|
611
|
+
content?: undefined;
|
|
612
|
+
isError?: boolean | undefined;
|
|
613
|
+
}>>, z.ZodObject<{
|
|
614
|
+
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
615
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
466
616
|
content: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
|
|
467
617
|
type: z.ZodLiteral<"text">;
|
|
468
618
|
text: z.ZodString;
|
|
@@ -491,16 +641,20 @@ declare const CallToolResultSchema: z.ZodUnion<[z.ZodObject<{
|
|
|
491
641
|
name: z.ZodString;
|
|
492
642
|
description: z.ZodOptional<z.ZodString>;
|
|
493
643
|
mimeType: z.ZodOptional<z.ZodString>;
|
|
644
|
+
}, z.core.$loose>, z.ZodObject<{
|
|
645
|
+
type: z.ZodString;
|
|
494
646
|
}, z.core.$loose>]>>;
|
|
495
647
|
structuredContent: z.ZodOptional<z.ZodUnknown>;
|
|
496
648
|
isError: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
|
|
497
|
-
}, z.core.$loose>, z.ZodObject<{
|
|
649
|
+
}, z.core.$loose>>]>, z.ZodObject<{
|
|
498
650
|
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
499
|
-
|
|
651
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
652
|
+
toolResult: z.ZodNonOptional<z.ZodUnknown>;
|
|
500
653
|
}, z.core.$loose>]>;
|
|
501
654
|
type CallToolResult = z.infer<typeof CallToolResultSchema>;
|
|
502
655
|
declare const ListResourceTemplatesResultSchema: z.ZodObject<{
|
|
503
656
|
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
657
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
504
658
|
resourceTemplates: z.ZodArray<z.ZodObject<{
|
|
505
659
|
uriTemplate: z.ZodString;
|
|
506
660
|
name: z.ZodString;
|
|
@@ -512,6 +666,7 @@ declare const ListResourceTemplatesResultSchema: z.ZodObject<{
|
|
|
512
666
|
type ListResourceTemplatesResult = z.infer<typeof ListResourceTemplatesResultSchema>;
|
|
513
667
|
declare const ReadResourceResultSchema: z.ZodObject<{
|
|
514
668
|
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
669
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
515
670
|
contents: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
|
|
516
671
|
uri: z.ZodString;
|
|
517
672
|
name: z.ZodOptional<z.ZodString>;
|
|
@@ -547,6 +702,7 @@ declare const CompleteRequestParamsSchema: z.ZodObject<{
|
|
|
547
702
|
type CompleteRequestParams = z.infer<typeof CompleteRequestParamsSchema>;
|
|
548
703
|
declare const CompleteResultSchema: z.ZodObject<{
|
|
549
704
|
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
705
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
550
706
|
completion: z.ZodObject<{
|
|
551
707
|
values: z.ZodArray<z.ZodString>;
|
|
552
708
|
total: z.ZodOptional<z.ZodNumber>;
|
|
@@ -556,6 +712,7 @@ declare const CompleteResultSchema: z.ZodObject<{
|
|
|
556
712
|
type CompleteResult = z.infer<typeof CompleteResultSchema>;
|
|
557
713
|
declare const ListPromptsResultSchema: z.ZodObject<{
|
|
558
714
|
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
715
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
559
716
|
nextCursor: z.ZodOptional<z.ZodString>;
|
|
560
717
|
prompts: z.ZodArray<z.ZodObject<{
|
|
561
718
|
name: z.ZodString;
|
|
@@ -571,6 +728,7 @@ declare const ListPromptsResultSchema: z.ZodObject<{
|
|
|
571
728
|
type ListPromptsResult = z.infer<typeof ListPromptsResultSchema>;
|
|
572
729
|
declare const GetPromptResultSchema: z.ZodObject<{
|
|
573
730
|
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
731
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
574
732
|
description: z.ZodOptional<z.ZodString>;
|
|
575
733
|
messages: z.ZodArray<z.ZodObject<{
|
|
576
734
|
role: z.ZodUnion<readonly [z.ZodLiteral<"user">, z.ZodLiteral<"assistant">]>;
|
|
@@ -617,6 +775,7 @@ declare const ElicitationRequestSchema: z.ZodObject<{
|
|
|
617
775
|
type ElicitationRequest = z.infer<typeof ElicitationRequestSchema>;
|
|
618
776
|
declare const ElicitResultSchema: z.ZodObject<{
|
|
619
777
|
_meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
|
|
778
|
+
resultType: z.ZodOptional<z.ZodString>;
|
|
620
779
|
action: z.ZodUnion<readonly [z.ZodLiteral<"accept">, z.ZodLiteral<"decline">, z.ZodLiteral<"cancel">]>;
|
|
621
780
|
content: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
622
781
|
}, z.core.$loose>;
|
|
@@ -625,6 +784,16 @@ type ElicitResult = z.infer<typeof ElicitResultSchema>;
|
|
|
625
784
|
interface MCPClientConfig {
|
|
626
785
|
/** Transport configuration for connecting to the MCP server */
|
|
627
786
|
transport: MCPTransportConfig | MCPTransport;
|
|
787
|
+
/**
|
|
788
|
+
* Whether transports that support stateless protocol discovery should probe
|
|
789
|
+
* with `server/discover` before falling back to legacy initialization.
|
|
790
|
+
*
|
|
791
|
+
* Disable this for legacy servers that require `initialize` to be the first
|
|
792
|
+
* request.
|
|
793
|
+
*
|
|
794
|
+
* @default true
|
|
795
|
+
*/
|
|
796
|
+
protocolVersionDiscovery?: boolean;
|
|
628
797
|
/**
|
|
629
798
|
* Options that bound or cancel transport startup and the initialize request.
|
|
630
799
|
*/
|
|
@@ -807,4 +976,4 @@ declare function fingerprintMCPAppResource(resource: MCPAppResource): Promise<st
|
|
|
807
976
|
*/
|
|
808
977
|
declare function detectMCPAppResourceDrift(current: string, baseline: string): boolean;
|
|
809
978
|
|
|
810
|
-
export { type CallToolResult, type CompleteRequestParams, type CompleteResult, type Configuration, type ElicitResult, ElicitResultSchema, type ElicitationRequest, ElicitationRequestSchema, type InitializeResult, type JSONRPCError, type JSONRPCMessage, type JSONRPCNotification, type JSONRPCRequest, type JSONRPCResponse, type ListToolsResult, type MCPAppResource, type MCPAppResourceCSP, type MCPAppResourceMeta, type MCPClient, type ClientCapabilities as MCPClientCapabilities, type MCPClientConfig, type MCPTransport, type MCPTransportCloseOptions, type MCPTransportSendOptions, MCP_APP_MIME_TYPE, type McpProviderMetadata, type OAuthAuthorizationServerInformation, type OAuthClientInformation, type OAuthClientMetadata, type OAuthClientProvider, type OAuthTokens, UnauthorizedError, auth, createMCPClient, detectMCPAppResourceDrift, type MCPClient as experimental_MCPClient, type ClientCapabilities as experimental_MCPClientCapabilities, type MCPClientConfig as experimental_MCPClientConfig, createMCPClient as experimental_createMCPClient, fingerprintMCPAppResource, mcpAppClientCapabilities, readMCPAppResource, splitMCPAppTools, validateJSONRPCMessage };
|
|
979
|
+
export { type CallToolResult, type CompleteRequestParams, type CompleteResult, type Configuration, type ElicitResult, ElicitResultSchema, type ElicitationRequest, ElicitationRequestSchema, type InitializeResult, type JSONRPCError, type JSONRPCMessage, type JSONRPCNotification, type JSONRPCRequest, type JSONRPCResponse, type ListToolsResult, type MCPAppResource, type MCPAppResourceCSP, type MCPAppResourceMeta, type MCPClient, type ClientCapabilities as MCPClientCapabilities, type MCPClientConfig, type MCPTransport, type MCPTransportCloseOptions, type MCPTransportSendOptions, MCP_APP_MIME_TYPE, type McpProviderMetadata, type McpToolAnnotations, type OAuthAuthorizationServerInformation, type OAuthClientInformation, type OAuthClientMetadata, type OAuthClientProvider, type OAuthTokens, UnauthorizedError, auth, createMCPClient, detectMCPAppResourceDrift, type MCPClient as experimental_MCPClient, type ClientCapabilities as experimental_MCPClientCapabilities, type MCPClientConfig as experimental_MCPClientConfig, createMCPClient as experimental_createMCPClient, fingerprintMCPAppResource, mcpAppClientCapabilities, readMCPAppResource, splitMCPAppTools, validateJSONRPCMessage };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e,Ct as t,E as n,Et as r,H as i,Mt as a,Ot as o,P as s,Q as c,St as l,Tt as u,Vt as d,X as f,Z as p,_t as m,bt as h,gt as g,ht as _,jt as ee,kt as v,mt as te,n as ne,nt as re,o as ie,st as ae,u as oe,ut as y,wt as b,xt as x}from"../../_chunks/workflow/dist-ChzQSWQA.js";const se={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var ce;ce||={};let S;S=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function le(e){return(await S).getRandomValues(new Uint8Array(e))}async function ue(e){let t=``;for(;t.length<e;){let n=await le(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function de(e){return await ue(e)}async function fe(e){let t=await(await S).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function pe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await de(e);return{code_verifier:t,code_challenge:await fe(t)}}var C=`2025-11-25`,me=[C,`2025-06-18`,`2025-03-26`,`2024-11-05`],he=b(u(r(),v())),ge=x({name:r(),version:r(),title:b(r())}),w=x({_meta:b(t({}).loose())}),T=w,_e=t({method:r(),params:b(w)}),ve=t({applyDefaults:b(m())}).loose(),ye=x({experimental:b(t({}).loose()),logging:b(t({}).loose()),completions:b(t({}).loose()),prompts:b(x({listChanged:b(m())})),resources:b(x({subscribe:b(m()),listChanged:b(m())})),tools:b(x({listChanged:b(m())})),elicitation:b(ve)});t({elicitation:b(ve)}).loose();var be=T.extend({protocolVersion:r(),capabilities:ye,serverInfo:ge,instructions:b(r())}),E=T.extend({nextCursor:b(r())}),xe=t({name:r(),title:b(r()),description:b(r()),inputSchema:t({type:h(`object`),properties:b(t({}).loose())}).loose(),outputSchema:b(t({}).loose()),annotations:b(t({title:b(r())}).loose()),_meta:he}).loose(),Se=E.extend({tools:_(xe)}),D=t({type:h(`text`),text:r()}).loose(),Ce=t({type:h(`image`),data:g(),mimeType:r()}).loose(),we=t({uri:r(),name:r(),title:b(r()),description:b(r()),mimeType:b(r()),size:b(l())}).loose(),Te=E.extend({resources:_(we)}),O=t({uri:r(),name:b(r()),title:b(r()),mimeType:b(r())}).loose(),k=O.extend({text:r()}),Ee=O.extend({blob:g()}),De=t({type:h(`resource`),resource:o([k,Ee])}).loose(),Oe=t({type:h(`resource_link`),uri:r(),name:r(),description:b(r()),mimeType:b(r())}).loose(),ke=T.extend({content:_(o([D,Ce,De,Oe])),structuredContent:b(v()),isError:m().default(!1).optional()}).or(T.extend({toolResult:v()})),Ae=t({uriTemplate:r(),name:r(),title:b(r()),description:b(r()),mimeType:b(r())}).loose(),je=T.extend({resourceTemplates:_(Ae)}),Me=T.extend({contents:_(o([k,Ee]))}),Ne=t({type:h(`ref/prompt`),name:r()}).loose(),Pe=t({type:h(`ref/resource`),uri:r()}).loose(),Fe=t({name:r(),value:r()}).loose();w.extend({ref:o([Ne,Pe]),argument:Fe,context:b(t({arguments:u(r(),r())}).loose())});var Ie=T.extend({completion:t({values:_(r()).max(100),total:b(l().int()),hasMore:b(m())}).loose()}),Le=t({name:r(),description:b(r()),required:b(m())}).loose(),Re=t({name:r(),title:b(r()),description:b(r()),arguments:b(_(Le))}).loose(),ze=E.extend({prompts:_(Re)}),Be=t({role:o([h(`user`),h(`assistant`)]),content:o([D,Ce,De,Oe])}).loose(),Ve=T.extend({description:b(r()),messages:_(Be)}),He=w.extend({message:r(),requestedSchema:v()}),A=_e.extend({method:h(`elicitation/create`),params:He}),Ue=T.extend({action:o([h(`accept`),h(`decline`),h(`cancel`)]),content:b(u(r(),v()))}),j=`2.0`,We=t({jsonrpc:h(j),id:o([r(),l().int()])}).merge(_e).strict(),Ge=t({jsonrpc:h(j),id:o([r(),l().int()]),result:T}).strict(),Ke=t({jsonrpc:h(j),id:o([r(),l().int()]),error:t({code:l().int(),message:r(),data:b(v())})}).strict(),qe=t({jsonrpc:h(j)}).merge(t({method:r(),params:b(w)})).strict(),Je=o([We,qe,Ge,Ke]);function M(e){return Je.parse(e)}async function N(e){return M(await i({text:e}))}var Ye=`vercel.ai.error.AI_MCPClientError`,Xe=Symbol.for(Ye),Ze,Qe,P=class extends (Qe=a,Ze=Xe,Qe){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[Ze]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(e){return a.hasMarker(e,Ye)}},F=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,I=r().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:se.custom,message:`URL must be parseable`,fatal:!0}),ee}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),$e=t({access_token:r(),id_token:r().optional(),token_type:r(),expires_in:l().optional(),scope:r().optional(),refresh_token:r().optional(),authorization_server:I.optional(),token_endpoint:I.optional()}).strip(),et=x({resource:r().url(),authorization_servers:_(I).optional(),jwks_uri:r().url().optional(),scopes_supported:_(r()).optional(),bearer_methods_supported:_(r()).optional(),resource_signing_alg_values_supported:_(r()).optional(),resource_name:r().optional(),resource_documentation:r().optional(),resource_policy_uri:r().url().optional(),resource_tos_uri:r().url().optional(),tls_client_certificate_bound_access_tokens:m().optional(),authorization_details_types_supported:_(r()).optional(),dpop_signing_alg_values_supported:_(r()).optional(),dpop_bound_access_tokens_required:m().optional()}),tt=x({issuer:r(),authorization_endpoint:I,token_endpoint:I,registration_endpoint:I.optional(),scopes_supported:_(r()).optional(),response_types_supported:_(r()),grant_types_supported:_(r()).optional(),code_challenge_methods_supported:_(r()).optional(),token_endpoint_auth_methods_supported:_(r()).optional(),token_endpoint_auth_signing_alg_values_supported:_(r()).optional()}),nt=x({issuer:r(),authorization_endpoint:I,token_endpoint:I,userinfo_endpoint:I.optional(),jwks_uri:I,registration_endpoint:I.optional(),scopes_supported:_(r()).optional(),response_types_supported:_(r()),grant_types_supported:_(r()).optional(),subject_types_supported:_(r()),id_token_signing_alg_values_supported:_(r()),claims_supported:_(r()).optional(),token_endpoint_auth_methods_supported:_(r()).optional()}).merge(tt.pick({code_challenge_methods_supported:!0})),rt=t({client_id:r(),client_secret:r().optional(),client_id_issued_at:l().optional(),client_secret_expires_at:l().optional(),authorization_server:I.optional(),token_endpoint:I.optional()}).strip(),it=t({redirect_uris:_(I),token_endpoint_auth_method:r().optional(),grant_types:_(r()).optional(),response_types:_(r()).optional(),client_name:r().optional(),client_uri:I.optional(),logo_uri:I.optional(),scope:r().optional(),contacts:_(r()).optional(),tos_uri:I.optional(),policy_uri:r().optional(),jwks_uri:I.optional(),jwks:te().optional(),software_id:r().optional(),software_version:r().optional(),software_statement:r().optional()}).strip(),at=t({error:r(),error_description:r().optional(),error_uri:r().optional()}),ot=it.merge(rt),st=`vercel.ai.error.AI_MCPClientOAuthError`,ct=Symbol.for(st),lt,ut,L=class extends (ut=a,lt=ct,ut){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[lt]=!0}static isInstance(e){return a.hasMarker(e,st)}},R=class extends L{};R.errorCode=`server_error`;var z=class extends L{};z.errorCode=`invalid_client`;var B=class extends L{};B.errorCode=`invalid_grant`;var V=class extends L{};V.errorCode=`unauthorized_client`;var dt={[R.errorCode]:R,[z.errorCode]:z,[B.errorCode]:B,[V.errorCode]:V};function ft(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function H(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function pt({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var U=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function W(e){return new URL(e).href}function mt(e,t){return{authorizationServerUrl:W(e),tokenEndpoint:W(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function ht(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function gt(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function _t(e){if(e?.authorization_server&&e.token_endpoint)return{authorizationServerUrl:W(e.authorization_server),tokenEndpoint:W(e.token_endpoint)}}async function vt({provider:e,clientInformation:t,tokens:n}){let r=_t(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:W(i.authorizationServerUrl),tokenEndpoint:W(i.tokenEndpoint)}:_t(t)}async function yt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(gt(t,n)),!0):!1}function bt(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new L({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function xt({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new L({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function G(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=t.match(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function St(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function K(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?K(e,void 0,n):void 0;throw r}}async function Ct(e,t,n=fetch){return await K(e,{"MCP-Protocol-Version":t},n)}function wt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Tt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??C,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=St(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await Ct(o,a,n);return!r?.metadataUrl&&wt(s,i.pathname)&&(s=await Ct(new URL(`/.well-known/${t}`,i),a,n)),s}async function Et(e,t,n=fetch){let r=await Tt(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return et.parse(await r.json())}function Dt(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;return i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function Ot(e,t){if(e.issuer!==t)throw new L({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function kt(e,{fetchFn:t=fetch,protocolVersion:n=C}={}){let r={"MCP-Protocol-Version":n},i=Dt(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await K(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=tt.parse(await i.json());return Ot(e,a),e}{let t=nt.parse(await i.json());if(Ot(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function At(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await pe(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,H(o)),{authorizationUrl:l,codeVerifier:d}}function jt(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Mt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Nt(i,a,n);return;case`client_secret_post`:Pt(i,a,r);return;case`none`:Ft(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Nt(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Pt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Ft(e,t){t.set(`client_id`,e)}async function q(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=at.parse(await i({text:n}));return new(dt[e]||R)({message:t||``,cause:r})}catch(e){return new R({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function It(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?await s(d,f,e,t):Mt(jt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,H(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await q(p);return $e.parse(await p.json())}async function Lt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?await a(l,u,e,t):Mt(jt(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,H(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await q(d);return $e.parse({refresh_token:r,...await d.json()})}async function Rt(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await q(a);return ot.parse(await a.json())}async function J(e,t){try{return await Y(e,t)}catch(n){if(n instanceof z||n instanceof V)return await e.invalidateCredentials?.call(e,`all`),await Y(e,t);if(n instanceof B)return await e.invalidateCredentials?.call(e,`tokens`),await Y(e,t);throw n}}async function zt(e,t,n){let r=ft(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!pt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Y(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;bt(t,a);try{s=await Et(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await zt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await kt(c,{fetchFn:o}),d=mt(c,u),f=await Promise.resolve(e.clientInformation());if(!f){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);f=gt(await Rt(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o}),d),await e.saveClientInformation(f)}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=await vt({provider:e,clientInformation:f});if(!t)throw new L({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});xt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await It(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(ht(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await vt({provider:e,clientInformation:f,tokens:p});t?xt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Lt(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(ht(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof L)||e instanceof R))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:h,codeVerifier:g}=await At(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await yt({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new L({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(h),`REDIRECT`}function Bt(e){return e===void 0||e===`message`}var Vt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??C};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return ae(t,`ai-sdk/${F}`,n())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=G(c);try{if(await J(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new U;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new P({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new y).getReader(),u=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await l.read();if(t){if(this.connected)throw this.connected=!1,new P({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new P({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(Bt(s))try{let e=await N(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new P({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),t(e)}};this.sseConnection={close:()=>l.cancel()},u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(s=this.onerror)==null||s.call(this,e),t(e)}};n()})}async close(){var e,t,n;this.connected=!1,this.endpoint=void 0,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e,t){var n;if((n=t?.signal)==null||n.throwIfAborted(),!this.endpoint||!this.connected)throw new P({message:`MCP SSE Transport Error: Not connected`});let r=this.endpoint,i=this.abortController?.signal,a=t?.signal==null?i:i==null?t.signal:AbortSignal.any([i,t.signal]),o=async(n=!1)=>{var i,s,c,l;try{let t={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:a,redirect:this.redirectMode},l=await this.fetchFn(r.href,t);if(l.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=G(l);try{if(await J(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new U;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}return o(!0)}if(!l.ok){let e=await l.text().catch(()=>null),t=new P({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${l.status}): ${e}`});(c=this.onerror)==null||c.call(this,t);return}}catch(e){if(t?.signal?.aborted)throw e;(l=this.onerror)==null||l.call(this,e);return}};await o()}};function Ht(e){return e===void 0||e===`message`}var Ut=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders({base:e,includeSessionId:t=!0}){let r={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??C};if(t&&this.sessionId&&(r[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(r.Authorization=`Bearer ${e.access_token}`)}return ae(r,`ai-sdk/${F}`,n())}setSessionId(e){var t;this.sessionId!==e&&(this.sessionId=e,(t=this.onSessionIdChange)==null||t.call(this,e))}applySessionIdFromResponse(e){let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){var t;this.sessionId===e&&this.setSessionId(void 0),(t=this.onSessionExpired)==null||t.call(this,e)}authorizeOnce(e){return this.authProvider?(this.authPromise||=J(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new P({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.startInboundSse()}async close(e){var t,n,r,i,a;(t=this.inboundSseConnection)==null||t.close(),(n=this.abortController)==null||n.abort();try{if(this.sessionId&&this.terminateSessionOnClose&&this.abortController){(r=e?.signal)==null||r.throwIfAborted();let t=await this.commonHeaders({base:{}});(i=e?.signal)==null||i.throwIfAborted(),await this.fetchFn(this.url.href,{method:`DELETE`,headers:t,signal:e?.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(a=this.onclose)==null||a.call(this)}async send(e,t){var n;(n=t?.signal)==null||n.throwIfAborted();let r=this.abortController?.signal,i=t?.signal==null?r:r==null?t.signal:AbortSignal.any([r,t.signal]),a=async(n=!1)=>{var r,o,s,c,l,u;try{let u=`method`in e&&e.method===`initialize`,d=u?void 0:this.sessionId,f={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`},includeSessionId:!u}),body:JSON.stringify(e),signal:i,redirect:this.redirectMode},p=await this.fetchFn(this.url.href,f);if(this.applySessionIdFromResponse(p),p.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=G(p);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new U}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return a(!0)}if(p.status===202){this.inboundSseConnection||this.startInboundSse();return}if(!p.ok){let e=await p.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${e}`;p.status===404&&(d?(this.expireSessionId(d),t+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new P({message:t,statusCode:p.status,url:this.url.href,responseBody:e??void 0});throw(o=this.onerror)==null||o.call(this,n),n}if(!(`id`in e))return;let m=p.headers.get(`content-type`)||``;if(m.includes(`application/json`)){let e=await p.json(),t=Array.isArray(e)?e.map(e=>M(e)):[M(e)];for(let e of t)(s=this.onmessage)==null||s.call(this,e);return}if(m.includes(`text/event-stream`)){if(!p.body){let e=new P({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:p.status,url:this.url.href});throw(c=this.onerror)==null||c.call(this,e),e}let e=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new y).getReader();(async()=>{var n,r,i;try{for(;;){let{done:t,value:i}=await e.read();if(t)return;let{event:a,data:o}=i;if(Ht(a))try{let e=await N(o);(n=this.onmessage)==null||n.call(this,e)}catch(e){let t=new P({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(r=this.onerror)==null||r.call(this,t)}}}catch(e){if(t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`)return;(i=this.onerror)==null||i.call(this,e)}})().catch(e=>{var n;t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`||(n=this.onerror)==null||n.call(this,e)});return}let h=new P({message:`MCP HTTP Transport Error: Unexpected content type: ${m}`,statusCode:p.status,url:this.url.href});throw(l=this.onerror)==null||l.call(this,h),h}catch(e){throw t?.signal?.aborted||(u=this.onerror)==null||u.call(this,e),e}};await a()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new P({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},n)}startInboundSse(e=!1,t){this.openInboundSse(e,t).catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=this.sessionId,o=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(o[`last-event-id`]=t);let s=await this.fetchFn(this.url.href,{method:`GET`,headers:o,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(s),s.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=G(s);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new U;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(s.status===405)return;if(!s.ok||!s.body){s.status===404&&a&&this.expireSessionId(a);let e=new P({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new y).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),Ht(i))try{let t=await N(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new P({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{c.cancel().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}},this.inboundReconnectAttempts=0,l().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||((t=this.onerror)==null||t.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function Wt(e){switch(e.type){case`sse`:return new Vt(e);case`http`:return new Ut(e);default:throw new P({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Gt(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Kt=`io.modelcontextprotocol/ui`,X=`text/html;profile=mcp-app`,qt=`ui/resourceUri`,Jt={extensions:{[Kt]:{mimeTypes:[X]}}};function Yt(e){let t=e?.ui;return d(t)?t:void 0}var Z=_(v()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),Xt=x({connectDomains:Z,resourceDomains:Z,frameDomains:Z}),Zt=x({prefersBorder:m().optional().catch(void 0),csp:Xt.optional().catch(void 0),permissions:u(r(),v()).optional().catch(void 0)});function Qt(e){let t=(d(e)?e:void 0)?.ui;if(!d(t))return;let n=Zt.safeParse(t);return n.success?n.data:void 0}function $t(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function en(e){let t=Yt(e._meta),n=t?.resourceUri??e._meta?.[qt],r=$t(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function tn(e){let t=[],n=[];for(let r of e.tools){let e=en(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function nn({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(ie(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:X,html:r,meta:Qt(n._meta)}}async function rn({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return nn({uri:t,resource:await e.readResource({uri:t,options:n})})}var an=`1.0.0`,on=0,sn=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function cn(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function ln(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function un(e){let t=cn(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(P.isInstance(e)&&e.code!=null)return!1;let n=ln(e);return n!=null&&sn.includes(n)}function dn(e){if(e==null)return on;if(!Number.isInteger(e))throw new P({message:`maxRetries must be an integer`});if(e<0)throw new P({message:`maxRetries must be >= 0`});return e}function fn({timeout:e,maxTotalTimeout:t}){return e==null?t:t==null?e:Math.min(e,t)}function Q(e,t){return t==null?e:new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,a)},a=()=>{i(),r(t.reason)};if(t.aborted){a();return}t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{i(),n(e)}).catch(e=>{i(),r(e)})})}function pn({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function mn(e){let t=new hn(e);return await t.init(),t}var hn=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=an,onUncaughtError:i,maxRetries:a,capabilities:o,initialInitializeResult:s,initializationOptions:c}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:C,capabilities:{},serverInfo:this._serverInfo},this.isClosed=!0,this.onUncaughtError=i,this.maxRetries=dn(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,this.initializationOptions=c,this.transport=Gt(e)?e:Wt(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new P({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){let e=this.initializationOptions?.signal,t=this.initializationOptions?fn(this.initializationOptions):void 0,n=t==null?void 0:new AbortController,r=e==null?n?.signal:n==null?e:AbortSignal.any([e,n.signal]),i,a;t!=null&&(i=setTimeout(()=>{a=new P({message:`MCP client initialization timed out after ${t}ms`}),n?.abort(a)},t));try{if(this.isClosed=!1,r?.throwIfAborted(),await Q(this.transport.start(),r),this.initialInitializeResult){let e=be.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}let e=await this.request({request:{method:`initialize`,params:{protocolVersion:C,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:be,options:{signal:r}});if(e===void 0)throw new P({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`},{signal:r}),this}catch(t){try{await Q(this.transport.close({signal:r}),r)}catch{}throw this.onClose(),a??(e?.aborted?new P({message:`MCP client initialization was aborted`,cause:e.reason}):t)}finally{i!=null&&clearTimeout(i)}}applyInitializeResult(e){if(!me.includes(e.protocolVersion))throw new P({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this._initializeResult=e,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}send(e,t){return this.transport.send(e,t==null?void 0:{signal:t})}assertCapability(e){switch(e){case`initialize`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new P({message:`Server does not support completions`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new P({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new P({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new P({message:`Server does not support prompts`});break;default:throw new P({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new P({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=n==null?void 0:fn(n),s=o==null?void 0:new AbortController,c=a==null?s?.signal:s==null?a:AbortSignal.any([a,s.signal]),l,u=this.requestMessageId++,d={...e,jsonrpc:`2.0`,id:u},f=()=>{i(new P({message:`Request was aborted`,cause:a?.reason}))},p=()=>{this.responseHandlers.delete(u),a?.removeEventListener(`abort`,h),l!=null&&clearTimeout(l)},m=e=>{p(),i(e)},h=()=>{p(),f()};this.responseHandlers.set(u,e=>{if(a?.aborted)return p(),f();if(e instanceof Error)return m(e);try{let n=t.parse(e.result);p(),r(n)}catch(e){let t=new P({message:`Failed to parse server response`,cause:e});m(t)}}),a?.addEventListener(`abort`,h,{once:!0}),o!=null&&(l=setTimeout(()=>{let e=new P({message:`Request timed out after ${o}ms`});s?.abort(e),m(e)},o)),(c==null?this.transport.send(d):this.send(d,c)).catch(e=>{m(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:Se,options:t})}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():f({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:un,createRetryError:({message:e,errors:t})=>new P({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){try{return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:ke,options:n})})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:Te,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Me,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:je,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:ze,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Ve,options:n})}catch(e){throw e}}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:Ie,options:e})}async notification(e,t){let n={...e,jsonrpc:`2.0`};await Q(this.send(n,t?.signal),t?.signal)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(t,{schemas:n=`automatic`}={}){let r={};for(let{name:i,title:a,description:o,inputSchema:c,annotations:l,_meta:u}of t.tools){let t=a??l?.title;if(n!==`automatic`&&!Object.prototype.hasOwnProperty.call(n,i))continue;let d=this,f=n===`automatic`?void 0:n[i]?.outputSchema,p=en({_meta:u}),m={clientName:this.clientInfo.name,toolName:i,...t==null?{}:{title:t},...p?.resourceUri==null?{}:{app:{...p,mimeType:X}}},h=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let r=await d.callTool({name:i,arguments:e,options:{signal:t?.abortSignal}});return r.isError||f==null?r:d.extractStructuredContent(r,f,i)};r[i]={...n===`automatic`?e({description:o,title:t,metadata:m,inputSchema:s({...c,properties:c.properties??{},additionalProperties:!1}),execute:h,toModelOutput:pn}):re({description:o,title:t,metadata:m,inputSchema:n[i].inputSchema,...f==null?{}:{outputSchema:f},execute:h,toModelOutput:pn}),_meta:u}}return r}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await c({value:e.structuredContent,schema:ne(t)});if(!r.success)throw new P({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await p({text:r.text,schema:t});if(!e.success)throw new P({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new P({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==A)throw new P({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=A.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=Ue.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new P({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new P({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new P({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},gn=new TextEncoder;function $(e){if(typeof e!=`object`||!e)return JSON.stringify(e??null);if(Array.isArray(e))return`[${e.map($).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${$(t[e])}`).join(`,`)}}`}function _n(e){return oe(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function vn(e){let t=await crypto.subtle.digest(`SHA-256`,gn.encode($({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return _n(new Uint8Array(t))}function yn(e,t){return e!==t}export{Ue as ElicitResultSchema,A as ElicitationRequestSchema,X as MCP_APP_MIME_TYPE,U as UnauthorizedError,J as auth,mn as createMCPClient,mn as experimental_createMCPClient,yn as detectMCPAppResourceDrift,vn as fingerprintMCPAppResource,Jt as mcpAppClientCapabilities,rn as readMCPAppResource,tn as splitMCPAppTools,M as validateJSONRPCMessage};
|
|
1
|
+
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{B as n,Bt as r,Ct as i,Et as a,Ft as o,It as s,Lt as c,Mt as l,Nt as u,O as d,Pt as f,R as p,Rt as m,Tt as h,Ut as g,Vt as _,Y as v,at as ee,d as te,gt as ne,it as re,j as ie,jt as y,kt as ae,ot as oe,pt as se,r as ce,s as le,ut as ue,wt as b,yt as x}from"../../_chunks/workflow/dist-DhncQSl7.js";const de={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var fe;fe||={};let S;S=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function pe(e){return(await S).getRandomValues(new Uint8Array(e))}async function me(e){let t=``;for(;t.length<e;){let n=await pe(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function he(e){return await me(e)}async function ge(e){let t=await(await S).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function _e(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await he(e);return{code_verifier:t,code_challenge:await ge(t)}}var C=`2026-07-28`,w=`2025-11-25`,ve=[C,w,`2025-06-18`,`2025-03-26`,`2024-11-05`],ye=s(c(m(),_())),be=l({name:m(),version:m(),title:s(m())}),T=l({_meta:s(o({}).loose())}),E=T.extend({resultType:s(m())}),xe=o({method:m(),params:s(T)}),Se=o({applyDefaults:s(a())}).loose(),Ce=l({experimental:s(o({}).loose()),logging:s(o({}).loose()),completions:s(o({}).loose()),prompts:s(l({listChanged:s(a())})),resources:s(l({subscribe:s(a()),listChanged:s(a())})),tools:s(l({listChanged:s(a())})),elicitation:s(Se)});o({elicitation:s(Se)}).loose();var we=E.extend({supportedVersions:b(m()),capabilities:Ce,instructions:s(m()),ttlMs:s(f()),cacheScope:s(r([y(`public`),y(`private`)]))}),Te=E.extend({protocolVersion:m(),capabilities:Ce,serverInfo:be,instructions:s(m())}),D=E.extend({nextCursor:s(m())}),Ee=o({name:m(),title:s(m()),description:s(m()),inputSchema:l({type:s(_()),properties:s(o({}).loose())}),outputSchema:s(o({}).loose()),annotations:s(o({title:s(m()),readOnlyHint:s(a()),destructiveHint:s(a()),idempotentHint:s(a()),openWorldHint:s(a())}).loose()),_meta:ye}).loose(),De=D.extend({tools:b(Ee)}),Oe=o({type:y(`text`),text:m()}).loose(),ke=o({type:y(`image`),data:h(),mimeType:m()}).loose(),Ae=o({uri:m(),name:m(),title:s(m()),description:s(m()),mimeType:s(m()),size:s(f())}).loose(),je=D.extend({resources:b(Ae)}),Me=o({uri:m(),name:s(m()),title:s(m()),mimeType:s(m())}).loose(),Ne=Me.extend({text:m()}),Pe=Me.extend({blob:h()}),Fe=o({type:y(`resource`),resource:r([Ne,Pe])}).loose(),Ie=o({type:y(`resource_link`),uri:m(),name:m(),description:s(m()),mimeType:s(m())}).loose(),Le=o({type:m()}).loose().refine(e=>![`text`,`image`,`resource`,`resource_link`].includes(e.type),{message:`Known content types must match their schema`}),Re=E.extend({content:b(r([Oe,ke,Fe,Ie,Le])),structuredContent:s(_()),isError:a().default(!1).optional()}),ze=E.extend({content:u().optional(),structuredContent:ae(),isError:a().default(!1).optional()}).transform(e=>({...e,content:[{type:`text`,text:JSON.stringify(e.structuredContent)}]})).pipe(Re),Be=Re.or(ze).or(E.extend({toolResult:_().nonoptional()})),Ve=o({uriTemplate:m(),name:m(),title:s(m()),description:s(m()),mimeType:s(m())}).loose(),He=E.extend({resourceTemplates:b(Ve)}),Ue=E.extend({contents:b(r([Ne,Pe]))}),We=o({type:y(`ref/prompt`),name:m()}).loose(),Ge=o({type:y(`ref/resource`),uri:m()}).loose(),Ke=o({name:m(),value:m()}).loose();T.extend({ref:r([We,Ge]),argument:Ke,context:s(o({arguments:c(m(),m())}).loose())});var qe=E.extend({completion:o({values:b(m()).max(100),total:s(f().int()),hasMore:s(a())}).loose()}),Je=o({name:m(),description:s(m()),required:s(a())}).loose(),Ye=o({name:m(),title:s(m()),description:s(m()),arguments:s(b(Je))}).loose(),Xe=D.extend({prompts:b(Ye)}),Ze=o({role:r([y(`user`),y(`assistant`)]),content:r([Oe,ke,Fe,Ie])}).loose(),Qe=E.extend({description:s(m()),messages:b(Ze)}),$e=T.extend({message:m(),requestedSchema:_()}),O=xe.extend({method:y(`elicitation/create`),params:$e}),et=E.extend({action:r([y(`accept`),y(`decline`),y(`cancel`)]),content:s(c(m(),_()))}),k=`2.0`,tt=o({jsonrpc:y(k),id:r([m(),f().int()])}).merge(xe).strict(),nt=o({jsonrpc:y(k),id:r([m(),f().int()]),result:E}).strict(),rt=o({jsonrpc:y(k),id:s(r([m(),f().int()])),error:o({code:f().int(),message:m(),data:s(_())})}).strict(),it=o({jsonrpc:y(k)}).merge(o({method:m(),params:s(T)})).strict(),at=r([tt,it,nt,rt]);function A(e){return at.parse(e)}async function j(e){return A(await v({text:e}))}var ot=`vercel.ai.error.AI_MCPClientError`,st=Symbol.for(ot),ct,lt,M=class extends (lt=e,ct=st,lt){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[ct]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,ot)}},ut=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,N=m().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:de.custom,message:`URL must be parseable`,fatal:!0}),g}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),dt=o({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:f().optional(),scope:m().optional(),refresh_token:m().optional(),issuer:N.optional(),authorization_server:N.optional(),token_endpoint:N.optional()}).strip(),ft=l({resource:m().url(),authorization_servers:b(N).optional(),jwks_uri:m().url().optional(),scopes_supported:b(m()).optional(),bearer_methods_supported:b(m()).optional(),resource_signing_alg_values_supported:b(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:a().optional(),authorization_details_types_supported:b(m()).optional(),dpop_signing_alg_values_supported:b(m()).optional(),dpop_bound_access_tokens_required:a().optional()}),pt=l({issuer:m(),authorization_endpoint:N,token_endpoint:N,registration_endpoint:N.optional(),authorization_response_iss_parameter_supported:a().optional(),client_id_metadata_document_supported:a().optional(),scopes_supported:b(m()).optional(),response_types_supported:b(m()),grant_types_supported:b(m()).optional(),code_challenge_methods_supported:b(m()).optional(),token_endpoint_auth_methods_supported:b(m()).optional(),token_endpoint_auth_signing_alg_values_supported:b(m()).optional()}),mt=l({issuer:m(),authorization_endpoint:N,token_endpoint:N,userinfo_endpoint:N.optional(),jwks_uri:N,registration_endpoint:N.optional(),authorization_response_iss_parameter_supported:a().optional(),client_id_metadata_document_supported:a().optional(),scopes_supported:b(m()).optional(),response_types_supported:b(m()),grant_types_supported:b(m()).optional(),subject_types_supported:b(m()),id_token_signing_alg_values_supported:b(m()),claims_supported:b(m()).optional(),token_endpoint_auth_methods_supported:b(m()).optional()}).merge(pt.pick({code_challenge_methods_supported:!0})),ht=o({client_id:m(),client_secret:m().optional(),client_id_issued_at:f().optional(),client_secret_expires_at:f().optional(),issuer:N.optional(),authorization_server:N.optional(),token_endpoint:N.optional()}).strip(),gt=o({redirect_uris:b(N),application_type:r([y(`native`),y(`web`)]).optional(),token_endpoint_auth_method:m().optional(),grant_types:b(m()).optional(),response_types:b(m()).optional(),client_name:m().optional(),client_uri:N.optional(),logo_uri:N.optional(),scope:m().optional(),contacts:b(m()).optional(),tos_uri:N.optional(),policy_uri:m().optional(),jwks_uri:N.optional(),jwks:i().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),_t=o({error:m(),error_description:m().optional(),error_uri:m().optional()}),vt=gt.merge(ht),yt=`vercel.ai.error.AI_MCPClientOAuthError`,bt=Symbol.for(yt),xt,St,P=class extends (St=e,xt=bt,St){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[xt]=!0}static isInstance(t){return e.hasMarker(t,yt)}},F=class extends P{};F.errorCode=`server_error`;var I=class extends P{};I.errorCode=`invalid_client`;var L=class extends P{};L.errorCode=`invalid_grant`;var R=class extends P{};R.errorCode=`unauthorized_client`;var Ct={[F.errorCode]:F,[I.errorCode]:I,[L.errorCode]:L,[R.errorCode]:R};function wt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function z(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function Tt({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var B=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function V(e){return new URL(e).href}function Et(e){let t=e.toLowerCase().replace(/\.+$/,``);return t===`localhost`||t.endsWith(`.localhost`)||t===`127.0.0.1`||t===`[::1]`||t===`::1`}function H(e){if(e.protocol!==`http:`&&e.protocol!==`https:`||!Et(e.hostname))try{se(e.href)}catch(t){throw new P({message:`OAuth endpoint URL is not allowed: ${e.href}`,cause:t})}}function Dt({callbackIssuer:e,expectedIssuer:t}){if(e!=null&&e!==t)throw new P({message:`OAuth authorization response issuer ${e} does not match expected issuer ${t}`})}function Ot(e,t){return{issuer:t?.issuer??String(e),authorizationServerUrl:V(e),tokenEndpoint:V(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function kt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function At(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function jt(e){if(e?.authorization_server&&e.token_endpoint)return{issuer:e.issuer,authorizationServerUrl:V(e.authorization_server),tokenEndpoint:V(e.token_endpoint)}}async function U({provider:e,clientInformation:t,tokens:n}){let r=jt(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{issuer:i.issuer,authorizationServerUrl:V(i.authorizationServerUrl),tokenEndpoint:V(i.tokenEndpoint)}:jt(t)}async function Mt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(At(t,n)),!0):!1}function Nt(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new P({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function W({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.issuer!=null&&t.issuer!=null&&e.issuer!==t.issuer||e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new P({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function G(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=t.match(/(?:^|[,\s])resource_metadata="([^"]*)"/i),a=t.match(/(?:^|[,\s])scope="([^"]*)"/i)?.[1],o;try{o=i?new URL(i[1]):void 0}catch{}return{resourceMetadataUrl:o,scope:a}}function Pt({scope:e,resourceMetadata:t,clientMetadata:n}){return e||(t?.scopes_supported)?.join(` `)||n.scope}function Ft(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function K(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?K(e,void 0,n):void 0;throw r}}async function It(e,t,n=fetch){return await K(e,{"MCP-Protocol-Version":t},n)}function Lt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Rt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??C,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Ft(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await It(o,a,n);return!r?.metadataUrl&&Lt(s,i.pathname)&&(s=await It(new URL(`/.well-known/${t}`,i),a,n)),s}async function zt(e,t,n=fetch){let r=await Rt(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return ft.parse(await r.json())}function Bt(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;return i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function Vt(e,t){if(!(e.issuer===t||t===new URL(t).origin&&e.issuer===`${t}/`))throw new P({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Ht(e,{fetchFn:t=fetch,protocolVersion:n=C}={}){let r={"MCP-Protocol-Version":n},i=Bt(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await K(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=pt.parse(await i.json());return Vt(e,a),e}{let t=mt.parse(await i.json());if(Vt(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function Ut(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await _e(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,z(o)),{authorizationUrl:l,codeVerifier:d}}function Wt(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Gt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Kt(i,a,n);return;case`client_secret_post`:qt(i,a,r);return;case`none`:Jt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Kt(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function qt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Jt(e,t){t.set(`client_id`,e)}async function q(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=_t.parse(await v({text:n}));return new(Ct[e]||F)({message:t||``,cause:r})}catch(e){return new F({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Yt(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(H(u),t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?await s(d,f,e,t):Gt(Wt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,z(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f,redirect:`error`});if(!p.ok)throw await q(p);return dt.parse(await p.json())}async function Xt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);H(c);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?await a(l,u,e,t):Gt(Wt(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,z(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u,redirect:`error`});if(!d.ok)throw await q(d);return dt.parse({refresh_token:r,...await d.json()})}async function Zt(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);H(i);let a=n.application_type??Qt(n.redirect_uris),o=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,application_type:a}),redirect:`error`});if(!o.ok)throw await q(o);return vt.parse(await o.json())}function Qt(e){return e.every(e=>{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&Et(t.hostname)||t.protocol!==`http:`&&t.protocol!==`https:`})?`native`:`web`}async function J(e,t){try{return await Y(e,t)}catch(n){if(n instanceof I||n instanceof R)return await e.invalidateCredentials?.call(e,`all`),await Y(e,t);if(n instanceof L)return await e.invalidateCredentials?.call(e,`tokens`),await Y(e,t);throw n}}async function $t(e,t,n){let r=wt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Tt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Y(e,{serverUrl:t,authorizationCode:n,callbackState:r,callbackIssuer:i,scope:a,resourceMetadataUrl:o,fetchFn:s}){let c,l;Nt(t,o);try{c=await zt(t,{resourceMetadataUrl:o},s),c.authorization_servers&&c.authorization_servers.length>0&&(l=c.authorization_servers[0])}catch{}l||=t;let u=await $t(t,e,c);await e.validateAuthorizationServerURL?.call(e,t,l);let d=await Ht(l,{fetchFn:s}),f=Ot(l,d),p=e.clientMetadata,m=Pt({scope:a,resourceMetadata:c,clientMetadata:p}),h=await Promise.resolve(e.clientInformation());if(h?.issuer!=null){let t=await U({provider:e,clientInformation:h});t&&W({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:f})}if(!h){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);h=At(await Zt(l,{metadata:d,clientMetadata:{...p,scope:m},fetchFn:s}),f),await e.saveClientInformation(h)}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=await U({provider:e,clientInformation:h});if(!t)throw new P({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});Dt({callbackIssuer:i,expectedIssuer:t.issuer??d?.issuer??String(l)}),W({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:f});let a=await e.codeVerifier(),o=await Yt(l,{metadata:d,clientInformation:h,authorizationCode:n,codeVerifier:a,redirectUri:e.redirectUrl,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(kt(o,f)),`AUTHORIZED`}let g=await e.tokens();if(g?.refresh_token){let t=await U({provider:e,clientInformation:h,tokens:g});t?W({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:f}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Xt(l,{metadata:d,clientInformation:h,refreshToken:g.refresh_token,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(kt(t,f)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof P)||e instanceof F))throw e}}let _=e.state?await e.state():void 0;_&&e.saveState&&await e.saveState(_);let{authorizationUrl:v,codeVerifier:ee}=await Ut(l,{metadata:d,clientInformation:h,state:_,redirectUrl:e.redirectUrl,scope:m,resource:u});if(!await Mt({provider:e,clientInformation:h,authorizationServerInformation:f}))throw new P({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(ee),await e.redirectToAuthorization(v),`REDIRECT`}function en(e){return e===void 0||e===`message`}var tn=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??w};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return ne(t,`ai-sdk/${ut}`,ie())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){let{resourceMetadataUrl:e,scope:r}=G(c);this.resourceMetadataUrl=e;try{if(await J(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,scope:r,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new B;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new M({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new x).getReader(),u=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await l.read();if(t){if(this.connected)throw this.connected=!1,new M({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new M({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(en(s))try{let e=await j(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new M({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),t(e)}};this.sseConnection={close:()=>l.cancel()},u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(s=this.onerror)==null||s.call(this,e),t(e)}};n()})}async close(){var e,t,n;this.connected=!1,this.endpoint=void 0,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e,t){var n;if((n=t?.signal)==null||n.throwIfAborted(),!this.endpoint||!this.connected)throw new M({message:`MCP SSE Transport Error: Not connected`});let r=this.endpoint,i=this.abortController?.signal,a=t?.signal==null?i:i==null?t.signal:AbortSignal.any([i,t.signal]),o=async(n=!1)=>{var i;try{let t={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:a,redirect:this.redirectMode},i=await this.fetchFn(r.href,t);if(i.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=G(i);if(this.resourceMetadataUrl=e,await J(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,scope:t,fetchFn:this.fetchFn})!==`AUTHORIZED`)throw new B;return o(!0)}if(!i.ok){let e=await i.text().catch(()=>null);throw new M({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${i.status}): ${e}`,statusCode:i.status,url:r.href,responseBody:e??void 0})}}catch(e){throw t?.signal?.aborted||(i=this.onerror)==null||i.call(this,e),e}};await o()}},nn=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,rn=/^=\?base64\?.*\?=$/;function an(e){return[...e].every(e=>{let t=e.charCodeAt(0);return t===9||t>=32&&t<=126})&&e.trim()===e&&!rn.test(e)?e:`=?base64?${te(new TextEncoder().encode(e))}?=`}function on(e){if(!p(e))return{success:!1,error:`inputSchema must be a JSON Schema object`};let t=[],n=new Set,r,i=(e,a,o)=>{if(r==null&&p(e)){if(`x-mcp-header`in e){if(!o||a.length===0){r=`x-mcp-header is not on a statically reachable property`;return}let i=e[`x-mcp-header`];if(typeof i!=`string`||!nn.test(i)){r=`x-mcp-header must be a non-empty HTTP token`;return}let s=i.toLowerCase();if(n.has(s)){r=`x-mcp-header value "${i}" is not unique`;return}let c=e.type;if(c!==`boolean`&&c!==`integer`&&c!==`string`){r=`x-mcp-header can only annotate boolean, integer, or string properties`;return}n.add(s),t.push({headerName:i,path:a,valueType:c})}for(let[t,n]of Object.entries(e))if(t!==`x-mcp-header`){if(t===`properties`&&p(n))for(let[e,t]of Object.entries(n))i(t,[...a,e],o);else i(n,a,!1)}}};return i(e,[],!0),r==null?{success:!0,bindings:t}:{success:!1,error:r}}function sn(e,t){let n=e;for(let e of t){if(!p(n))return;n=n[e]}return n}function cn({bindings:e,args:t}){let n={};for(let r of e){let e=sn(t,r.path);if(e!=null){if(r.valueType===`string`&&typeof e!=`string`||r.valueType===`boolean`&&typeof e!=`boolean`||r.valueType===`integer`&&!Number.isSafeInteger(e))throw TypeError(`Tool argument "${r.path.join(`.`)}" does not match its x-mcp-header type`);n[`Mcp-Param-${r.headerName}`]=an(String(e))}}return n}function ln(e){return e===void 0||e===`message`}var un=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.supportsProtocolVersionDiscovery=!0,this.supportsMcpToolParameterHeaders=!0,this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a??w,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){var t;if(this.protocolVersion=e,this.abortController){if(this.isModernProtocol()){(t=this.inboundSseConnection)==null||t.close(),this.inboundSseConnection=void 0;return}this.inboundSseConnection||this.startInboundSse()}}isModernProtocol(){return(this.protocolVersion??C)===C}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??w};if(!this.isModernProtocol()&&t&&this.sessionId&&(n[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(n.Authorization=`Bearer ${e.access_token}`)}return ne(n,`ai-sdk/${ut}`,ie())}setSessionId(e){var t;this.sessionId!==e&&(this.sessionId=e,(t=this.onSessionIdChange)==null||t.call(this,e))}applySessionIdFromResponse(e){if(this.isModernProtocol())return;let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){var t;this.sessionId===e&&this.setSessionId(void 0),(t=this.onSessionExpired)==null||t.call(this,e)}authorizeOnce(e,t){return this.authProvider?(this.authPromise||=J(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,scope:t,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new M({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.protocolVersion!=null&&this.protocolVersion!==C&&this.startInboundSse()}async close(e){var t,n,r,i,a;(t=this.inboundSseConnection)==null||t.close(),(n=this.abortController)==null||n.abort();try{if(!this.isModernProtocol()&&this.sessionId&&this.terminateSessionOnClose&&this.abortController){(r=e?.signal)==null||r.throwIfAborted();let t=await this.commonHeaders({base:{}});(i=e?.signal)==null||i.throwIfAborted(),await this.fetchFn(this.url.href,{method:`DELETE`,headers:t,signal:e?.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(a=this.onclose)==null||a.call(this)}async send(e,t){var n;(n=t?.signal)==null||n.throwIfAborted();let r=this.abortController?.signal,i=t?.signal==null?r:r==null?t.signal:AbortSignal.any([r,t.signal]),a=async(n=!1)=>{var r,o,s,c,l,u,d;try{let d=`method`in e&&e.method===`initialize`,f=d?void 0:this.sessionId,p={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,...this.isModernProtocol()?t?.headers:{},...this.isModernProtocol()&&`method`in e&&`id`in e?this.getStandardRequestHeaders(e):{}},includeSessionId:!d}),body:JSON.stringify(e),signal:i,redirect:this.redirectMode},m=await this.fetchFn(this.url.href,p);if(this.applySessionIdFromResponse(m),m.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=G(m);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,t)!==`AUTHORIZED`)throw new B}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return a(!0)}if(m.status===202){!this.isModernProtocol()&&!this.inboundSseConnection&&this.startInboundSse();return}if(!m.ok){let t=await m.text().catch(()=>null);if(`id`in e&&t!=null){let n=await j(t).catch(()=>void 0);if(n!=null&&`error`in n){(o=this.onmessage)==null||o.call(this,n.id==null?{...n,id:e.id}:n);return}}let n=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${m.status}): ${t}`;m.status===404&&(!this.isModernProtocol()&&f?(this.expireSessionId(f),n+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):this.isModernProtocol()||(n+=". This server does not support HTTP transport. Try using `sse` transport instead"));let r=new M({message:n,statusCode:m.status,url:this.url.href,responseBody:t??void 0});throw(s=this.onerror)==null||s.call(this,r),r}if(!(`id`in e))return;let h=m.headers.get(`content-type`)||``;if(h.includes(`application/json`)){let e=await m.json(),t=Array.isArray(e)?e.map(e=>A(e)):[A(e)];for(let e of t)(c=this.onmessage)==null||c.call(this,e);return}if(h.includes(`text/event-stream`)){if(!m.body){let e=new M({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:m.status,url:this.url.href});throw(l=this.onerror)==null||l.call(this,e),e}let e=m.body.pipeThrough(new TextDecoderStream).pipeThrough(new x).getReader();(async()=>{var n,r,i;try{for(;;){let{done:t,value:i}=await e.read();if(t)return;let{event:a,data:o}=i;if(ln(a))try{let e=await j(o);(n=this.onmessage)==null||n.call(this,e)}catch(e){let t=new M({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(r=this.onerror)==null||r.call(this,t)}}}catch(e){if(t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`)return;(i=this.onerror)==null||i.call(this,e)}})().catch(e=>{var n;t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`||(n=this.onerror)==null||n.call(this,e)});return}let g=new M({message:`MCP HTTP Transport Error: Unexpected content type: ${h}`,statusCode:m.status,url:this.url.href});throw(u=this.onerror)==null||u.call(this,g),g}catch(e){throw t?.signal?.aborted||(d=this.onerror)==null||d.call(this,e),e}};await a()}getStandardRequestHeaders(e){let t={"Mcp-Method":e.method},n=e.params,r=e.method===`resources/read`?n?.uri:e.method===`tools/call`||e.method===`prompts/get`?n?.name:void 0;return typeof r==`string`&&(t[`Mcp-Name`]=an(r)),t}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new M({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},n)}startInboundSse(e=!1,t){this.isModernProtocol()||this.openInboundSse(e,t).catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}async openInboundSse(e=!1,t){var n,r,i,a;if(!this.isModernProtocol())try{let a=this.sessionId,o=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(o[`last-event-id`]=t);let s=await this.fetchFn(this.url.href,{method:`GET`,headers:o,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(s),s.status===401&&this.authProvider&&!e){let{resourceMetadataUrl:e,scope:i}=G(s);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,i)!==`AUTHORIZED`){let e=new B;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(s.status===405)return;if(!s.ok||!s.body){s.status===404&&a&&this.expireSessionId(a);let e=new M({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new x).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),ln(i))try{let t=await j(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new M({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{c.cancel().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}},this.inboundReconnectAttempts=0,l().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||((t=this.onerror)==null||t.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function dn(e){switch(e.type){case`sse`:return new tn(e);case`http`:return new un({...e,initialProtocolVersion:e.initialProtocolVersion??C});default:throw new M({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function fn(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var pn=`io.modelcontextprotocol/ui`,X=`text/html;profile=mcp-app`,mn=`ui/resourceUri`,hn={extensions:{[pn]:{mimeTypes:[X]}}};function gn(e){let n=e?.ui;return t(n)?n:void 0}var Z=b(_()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),_n=l({connectDomains:Z,resourceDomains:Z,frameDomains:Z}),vn=l({prefersBorder:a().optional().catch(void 0),csp:_n.optional().catch(void 0),permissions:c(m(),_()).optional().catch(void 0)});function yn(e){let n=(t(e)?e:void 0)?.ui;if(!t(n))return;let r=vn.safeParse(n);return r.success?r.data:void 0}function bn(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function xn(e){let t=gn(e._meta),n=t?.resourceUri??e._meta?.[mn],r=bn(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function Sn(e){let t=[],n=[];for(let r of e.tools){let e=xn(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function Cn({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(le(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:X,html:r,meta:yn(n._meta)}}async function wn({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Cn({uri:t,resource:await e.readResource({uri:t,options:n})})}var Tn=`1.0.0`,En=0,Dn=1e3,On=[-32020,-32021,-32022],kn=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function An(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function jn(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function Mn(e){let t=An(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(M.isInstance(e)&&e.code!=null)return!1;let n=jn(e);return n!=null&&kn.includes(n)}function Nn(e){if(e==null)return En;if(!Number.isInteger(e))throw new M({message:`maxRetries must be an integer`});if(e<0)throw new M({message:`maxRetries must be >= 0`});return e}function Pn({timeout:e,maxTotalTimeout:t}){return e==null?t:t==null?e:Math.min(e,t)}function Q(e,t){return t==null?e:new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,a)},a=()=>{i(),r(t.reason)};if(t.aborted){a();return}t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{i(),n(e)}).catch(e=>{i(),r(e)})})}function Fn({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function In(e){let t=new Ln(e);return await t.init(),t}var Ln=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Tn,onUncaughtError:i,maxRetries:a,capabilities:o,initialInitializeResult:s,initializationOptions:c,protocolVersionDiscovery:l=!0}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:w,capabilities:{},serverInfo:this._serverInfo},this.protocolEra=`legacy`,this.protocolVersion=w,this.toolHeaderBindings=new Map,this.isClosed=!0,this.onUncaughtError=i,this.maxRetries=Nn(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,this.initializationOptions=c,this.protocolVersionDiscovery=l,this.transport=fn(e)?e:dn(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new M({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){let e=this.initializationOptions?.signal,t=this.initializationOptions?Pn(this.initializationOptions):void 0,n=t==null?void 0:new AbortController,r=e==null?n?.signal:n==null?e:AbortSignal.any([e,n.signal]),i,a;t!=null&&(i=setTimeout(()=>{a=new M({message:`MCP client initialization timed out after ${t}ms`}),n?.abort(a)},t));try{if(this.isClosed=!1,r?.throwIfAborted(),await Q(this.transport.start(),r),this.initialInitializeResult){let e=Te.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}if(this.protocolVersionDiscovery&&this.transport.supportsProtocolVersionDiscovery&&await this.tryProtocolDiscovery(r))return this;this.protocolEra=`legacy`,this.protocolVersion=w,this.setTransportProtocolVersion(this.protocolVersion);let e=await this.request({request:{method:`initialize`,params:{protocolVersion:w,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Te,options:{signal:r}});if(e===void 0)throw new M({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`},{signal:r}),this}catch(t){try{await Q(this.transport.close({signal:r}),r)}catch{}throw this.onClose(),a??(e?.aborted?new M({message:`MCP client initialization was aborted`,cause:e.reason}):t)}finally{i!=null&&clearTimeout(i)}}async tryProtocolDiscovery(e){this.protocolEra=`modern`,this.protocolVersion=C,this.setTransportProtocolVersion(this.protocolVersion);try{let t=await this.request({request:{method:`server/discover`},resultSchema:we,options:{signal:e,timeout:Dn}});return this.applyDiscoverResult(t),!0}catch(e){if(M.isInstance(e)&&e.code!=null&&On.includes(e.code))throw e;return!1}}applyDiscoverResult(e){if(!e.supportedVersions.includes(this.protocolVersion))throw new M({message:`Server does not support the requested protocol version: ${this.protocolVersion}`});let t=e._meta?.[`io.modelcontextprotocol/serverInfo`];typeof t==`object`&&t&&`name`in t&&typeof t.name==`string`&&`version`in t&&typeof t.version==`string`&&(this._serverInfo=t),this.serverCapabilities=e.capabilities,this._serverInstructions=e.instructions,this._initializeResult={protocolVersion:this.protocolVersion,capabilities:e.capabilities,serverInfo:this._serverInfo,instructions:e.instructions}}setTransportProtocolVersion(e){this.transport.setProtocolVersion?this.transport.setProtocolVersion(e):this.transport.protocolVersion=e}applyInitializeResult(e){if(!ve.includes(e.protocolVersion))throw new M({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this.protocolEra=`legacy`,this.protocolVersion=e.protocolVersion,this._serverInfo=e.serverInfo,this._initializeResult=e,this.setTransportProtocolVersion(e.protocolVersion),this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}send(e,t){return t==null?this.transport.send(e):this.transport.send(e,t)}assertCapability(e){switch(e){case`initialize`:case`server/discover`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new M({message:`Server does not support completions`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new M({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new M({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new M({message:`Server does not support prompts`});break;default:throw new M({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new M({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=n==null?void 0:Pn(n),s=o==null?void 0:new AbortController,c=a==null?s?.signal:s==null?a:AbortSignal.any([a,s.signal]),l,u=this.requestMessageId++,d=this.protocolEra===`modern`?{...e,params:{...e.params,_meta:{...e.params?._meta,"io.modelcontextprotocol/protocolVersion":this.protocolVersion,"io.modelcontextprotocol/clientCapabilities":this.clientCapabilities,"io.modelcontextprotocol/clientInfo":this.clientInfo}}}:e,f={...d,jsonrpc:`2.0`,id:u},p=this.getToolRequestHeaders(d),m=()=>{i(new M({message:`Request was aborted`,cause:a?.reason}))},h=()=>{this.responseHandlers.delete(u),a?.removeEventListener(`abort`,_),l!=null&&clearTimeout(l)},g=e=>{h(),i(e)},_=()=>{h(),m()};this.responseHandlers.set(u,e=>{if(a?.aborted)return h(),m();if(e instanceof Error)return g(e);try{if(this.protocolEra===`modern`&&e.result.resultType==null)throw new M({message:`Modern MCP result is missing resultType`});if(e.result.resultType===`input_required`)throw new M({message:`Server requested additional input, but multi round-trip requests are not supported yet`});let n=t.parse(e.result);h(),r(n)}catch(e){let t=M.isInstance(e)?e:new M({message:`Failed to parse server response`,cause:e});g(t)}}),a?.addEventListener(`abort`,_,{once:!0}),o!=null&&(l=setTimeout(()=>{let e=new M({message:`Request timed out after ${o}ms`});s?.abort(e),g(e)},o));let v={...c==null?{}:{signal:c},...p==null?{}:{headers:p}};(Object.keys(v).length===0?this.send(f):this.send(f,v)).catch(e=>{g(e)})})}async listTools({params:e,options:t}={}){let n=await this.request({request:{method:`tools/list`,params:e},resultSchema:De,options:t});return this.prepareToolDefinitions(n,e?.cursor==null)}prepareToolDefinitions(e,t=!1){if(this.protocolEra!==`modern`||!this.transport.supportsMcpToolParameterHeaders)return e;t&&this.toolHeaderBindings.clear();let n=e.tools.filter(e=>{let t=on(e.inputSchema);return t.success?(this.toolHeaderBindings.set(e.name,t.bindings),!0):(this.onError(new M({message:`Ignoring MCP tool "${e.name}": ${t.error}`})),!1)});return{...e,tools:n}}getToolRequestHeaders(e){if(this.protocolEra!==`modern`||e.method!==`tools/call`||typeof e.params?.name!=`string`)return;let t=this.toolHeaderBindings.get(e.params.name);if(t==null||t.length===0)return;let n=e.params.arguments;if(typeof n==`object`&&n&&!Array.isArray(n))try{return cn({bindings:t,args:n})}catch(t){throw new M({message:`Failed to create MCP headers for tool "${e.params.name}"`,cause:t})}}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():re({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:Mn,createRetryError:({message:e,errors:t})=>new M({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){try{return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:Be,options:n})})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:je,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Ue,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:He,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Xe,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Qe,options:n})}catch(e){throw e}}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:qe,options:e})}async notification(e,t){let n={...e,jsonrpc:`2.0`};await Q(this.send(n,t?.signal==null?void 0:{signal:t.signal}),t?.signal)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools(),n=[...t.tools];for(;t.nextCursor!=null;)t=await this.listTools({params:{cursor:t.nextCursor}}),n.push(...t.tools);return this.toolsFromDefinitions({...t,tools:n},{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){e=this.prepareToolDefinitions(e);let r={};for(let{name:i,title:a,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=a??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,i))continue;let u=this,f=t===`automatic`?void 0:t[i]?.outputSchema,p=xn({_meta:l}),m={clientName:this.clientInfo.name,toolName:i,...e==null?{}:{title:e},...c==null?{}:{annotations:{...c.title==null?{}:{title:c.title},...c.readOnlyHint==null?{}:{readOnlyHint:c.readOnlyHint},...c.destructiveHint==null?{}:{destructiveHint:c.destructiveHint},...c.idempotentHint==null?{}:{idempotentHint:c.idempotentHint},...c.openWorldHint==null?{}:{openWorldHint:c.openWorldHint}}},...p?.resourceUri==null?{}:{app:{...p,mimeType:X}}},h=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let r=await u.callTool({name:i,arguments:e,options:{signal:t?.abortSignal}});return r.isError||f==null?r:u.extractStructuredContent(r,f,i)};r[i]={...t===`automatic`?d({description:o,title:e,metadata:m,inputSchema:n({...s,properties:s.properties??{},additionalProperties:!1}),execute:h,toModelOutput:Fn}):ue({description:o,title:e,metadata:m,inputSchema:t[i].inputSchema,...f==null?{}:{outputSchema:f},execute:h,toModelOutput:Fn}),_meta:l}}return r}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await oe({value:e.structuredContent,schema:ce(t)});if(!r.success)throw new M({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await ee({text:r.text,schema:t});if(!e.success)throw new M({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new M({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==O)throw new M({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=O.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=et.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new M({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){if(e.id==null){this.onError(new M({message:`Protocol error: Received a response without a message ID: ${JSON.stringify(e)}`}));return}let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new M({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new M({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},Rn=new TextEncoder;function $(e){if(typeof e!=`object`||!e)return JSON.stringify(e??null);if(Array.isArray(e))return`[${e.map($).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${$(t[e])}`).join(`,`)}}`}function zn(e){return te(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function Bn(e){let t=await crypto.subtle.digest(`SHA-256`,Rn.encode($({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return zn(new Uint8Array(t))}function Vn(e,t){return e!==t}export{et as ElicitResultSchema,O as ElicitationRequestSchema,X as MCP_APP_MIME_TYPE,B as UnauthorizedError,J as auth,In as createMCPClient,In as experimental_createMCPClient,Vn as detectMCPAppResourceDrift,Bn as fingerprintMCPAppResource,hn as mcpAppClientCapabilities,wn as readMCPAppResource,Sn as splitMCPAppTools,A as validateJSONRPCMessage};
|