eve 0.31.3 → 0.32.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.
Files changed (205) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/src/chunks/{use-eve-agent-CF5D6jSV.js → use-eve-agent-CX87G1vU.js} +30 -5
  3. package/dist/src/chunks/{use-eve-agent-DbYZLG0h.js → use-eve-agent-DwyRde1N.js} +30 -5
  4. package/dist/src/cli/commands/integration-connect.d.ts +1 -0
  5. package/dist/src/cli/commands/integration-connect.js +1 -1
  6. package/dist/src/cli/commands/integration-setup.d.ts +4 -0
  7. package/dist/src/cli/commands/integration-setup.js +1 -1
  8. package/dist/src/cli/commands/register-integration-commands.js +1 -1
  9. package/dist/src/cli/commands/register-registry-commands.js +1 -1
  10. package/dist/src/cli/commands/registry-declared-setups.d.ts +23 -0
  11. package/dist/src/cli/commands/registry-declared-setups.js +1 -0
  12. package/dist/src/cli/commands/registry-metadata.d.ts +69 -0
  13. package/dist/src/cli/commands/registry-metadata.js +1 -1
  14. package/dist/src/cli/commands/registry-package.d.ts +3 -3
  15. package/dist/src/cli/commands/registry-package.js +1 -1
  16. package/dist/src/cli/commands/registry-presentation.d.ts +20 -0
  17. package/dist/src/cli/commands/registry-presentation.js +7 -0
  18. package/dist/src/cli/commands/registry-search-presentation.d.ts +16 -0
  19. package/dist/src/cli/commands/registry-search-presentation.js +6 -0
  20. package/dist/src/cli/commands/registry-setup-command.d.ts +5 -2
  21. package/dist/src/cli/commands/registry-setup-command.js +1 -2
  22. package/dist/src/cli/commands/registry.d.ts +16 -7
  23. package/dist/src/cli/commands/registry.js +1 -6
  24. package/dist/src/cli/commands/setup-answers.d.ts +2 -0
  25. package/dist/src/cli/commands/setup-answers.js +1 -0
  26. package/dist/src/cli/commands/setup-headless.d.ts +79 -0
  27. package/dist/src/cli/commands/setup-headless.js +1 -0
  28. package/dist/src/cli/dev/tui/runner.js +1 -1
  29. package/dist/src/cli/dev/tui/setup-commands.js +3 -3
  30. package/dist/src/cli/dev/tui/setup-flow.d.ts +8 -1
  31. package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
  32. package/dist/src/cli/dev/tui/traces/trace-conversation.d.ts +1 -1
  33. package/dist/src/cli/dev/tui/tui-prompter.js +1 -1
  34. package/dist/src/client/url.d.ts +5 -0
  35. package/dist/src/client/url.js +1 -1
  36. package/dist/src/compiled/.vendor-stamp.json +8 -8
  37. package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +33 -13
  38. package/dist/src/compiled/@ai-sdk/anthropic/index.js +4 -2
  39. package/dist/src/compiled/@ai-sdk/google/index.d.ts +50 -3
  40. package/dist/src/compiled/@ai-sdk/google/index.js +7 -7
  41. package/dist/src/compiled/@ai-sdk/mcp/index.d.ts +33 -3
  42. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  43. package/dist/src/compiled/@ai-sdk/openai/index.d.ts +140 -9
  44. package/dist/src/compiled/@ai-sdk/openai/index.js +9 -6
  45. package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
  46. package/dist/src/compiled/@ai-sdk/provider/index.d.ts +300 -6
  47. package/dist/src/compiled/@ai-sdk/provider-utils/index.d.ts +70 -20
  48. package/dist/src/compiled/@opentelemetry/api/index.d.ts +2 -1
  49. package/dist/src/compiled/@photon-ai/chat-adapter-imessage/index.js +1 -1
  50. package/dist/src/compiled/@vercel/otel/index.d.ts +6 -0
  51. package/dist/src/compiled/@vercel/sandbox/index.js +1 -1
  52. package/dist/src/compiled/_chunks/node/undici-CUIybhQ2.js +95 -0
  53. package/dist/src/compiled/_chunks/workflow/dist-eUxFublw.js +77 -0
  54. package/dist/src/compiled/shadcn-registry/index.js +309 -215
  55. package/dist/src/compiler/extension-compatibility.d.ts +10 -10
  56. package/dist/src/compiler/extension-compatibility.js +1 -1
  57. package/dist/src/context/build-callback-context.js +1 -1
  58. package/dist/src/execution/authorization-callback-match.d.ts +14 -0
  59. package/dist/src/execution/authorization-callback-match.js +1 -0
  60. package/dist/src/execution/next-driver-action.d.ts +1 -0
  61. package/dist/src/execution/parked-delivery-wait.d.ts +16 -1
  62. package/dist/src/execution/parked-delivery-wait.js +1 -1
  63. package/dist/src/execution/sandbox/abort-bound-session.d.ts +1 -1
  64. package/dist/src/execution/sandbox/bindings/docker.js +1 -1
  65. package/dist/src/execution/sandbox/bindings/just-bash-runtime.js +1 -1
  66. package/dist/src/execution/sandbox/bindings/microsandbox-lifecycle.js +1 -1
  67. package/dist/src/execution/sandbox/bindings/microsandbox-runtime.d.ts +1 -0
  68. package/dist/src/execution/sandbox/bindings/microsandbox-runtime.js +1 -1
  69. package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
  70. package/dist/src/execution/sandbox/ensure.js +1 -1
  71. package/dist/src/execution/session-command-inbox.d.ts +26 -1
  72. package/dist/src/execution/session-command-inbox.js +1 -1
  73. package/dist/src/execution/turn-execution-cursor.d.ts +1 -0
  74. package/dist/src/execution/turn-workflow.js +1 -1
  75. package/dist/src/execution/workflow-entry.js +1 -1
  76. package/dist/src/execution/workflow-steps.d.ts +3 -4
  77. package/dist/src/execution/workflow-steps.js +1 -1
  78. package/dist/src/harness/authorization.d.ts +24 -11
  79. package/dist/src/harness/authorization.js +1 -1
  80. package/dist/src/harness/input-extraction.js +1 -1
  81. package/dist/src/harness/input-requests.js +1 -1
  82. package/dist/src/harness/provider-tools.d.ts +1 -1
  83. package/dist/src/harness/provider-tools.js +1 -1
  84. package/dist/src/harness/tool-loop.js +2 -2
  85. package/dist/src/internal/application/package.js +1 -1
  86. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  87. package/dist/src/protocol/routes.d.ts +8 -6
  88. package/dist/src/protocol/routes.js +1 -1
  89. package/dist/src/public/channels/slack/attachments.js +1 -1
  90. package/dist/src/public/channels/slack/defaults.js +1 -1
  91. package/dist/src/public/channels/slack/hitl.d.ts +14 -1
  92. package/dist/src/public/channels/slack/hitl.js +2 -2
  93. package/dist/src/public/definitions/callback-context.d.ts +2 -2
  94. package/dist/src/public/definitions/sandbox.d.ts +1 -1
  95. package/dist/src/public/definitions/tool.d.ts +9 -9
  96. package/dist/src/public/sandbox/index.d.ts +1 -1
  97. package/dist/src/public/tools/web-search.d.ts +2 -2
  98. package/dist/src/runtime/connections/callback-route.d.ts +4 -5
  99. package/dist/src/runtime/connections/callback-route.js +1 -1
  100. package/dist/src/runtime/connections/scoped-authorization.js +1 -1
  101. package/dist/src/runtime/framework-tools/connection-search-dynamic.js +2 -2
  102. package/dist/src/runtime/framework-tools/todo.js +1 -1
  103. package/dist/src/runtime/input/types.d.ts +1 -4
  104. package/dist/src/sandbox/state.d.ts +1 -0
  105. package/dist/src/setup/ask-editable.d.ts +22 -0
  106. package/dist/src/setup/ask-editable.js +1 -0
  107. package/dist/src/setup/ask-signals.d.ts +23 -0
  108. package/dist/src/setup/ask-signals.js +1 -0
  109. package/dist/src/setup/ask.d.ts +24 -25
  110. package/dist/src/setup/ask.js +1 -1
  111. package/dist/src/setup/boxes/deploy-project.js +1 -1
  112. package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
  113. package/dist/src/setup/connection-connector.js +3 -2
  114. package/dist/src/setup/flows/registry-session.d.ts +33 -0
  115. package/dist/src/setup/flows/registry-session.js +1 -0
  116. package/dist/src/setup/flows/registry.d.ts +16 -0
  117. package/dist/src/setup/flows/registry.js +1 -1
  118. package/dist/src/setup/index.js +1 -1
  119. package/dist/src/setup/integrations/discord/setup.d.ts +19 -7
  120. package/dist/src/setup/integrations/discord/setup.js +4 -3
  121. package/dist/src/setup/integrations/github/setup.d.ts +36 -7
  122. package/dist/src/setup/integrations/github/setup.js +2 -2
  123. package/dist/src/setup/integrations/linear/setup.d.ts +21 -9
  124. package/dist/src/setup/integrations/linear/setup.js +2 -2
  125. package/dist/src/setup/integrations/photon/management.d.ts +8 -1
  126. package/dist/src/setup/integrations/photon/management.js +1 -1
  127. package/dist/src/setup/integrations/photon/setup-flow.d.ts +28 -24
  128. package/dist/src/setup/integrations/photon/setup-flow.js +3 -3
  129. package/dist/src/setup/integrations/photon/setup.d.ts +1 -3
  130. package/dist/src/setup/integrations/photon/setup.js +1 -1
  131. package/dist/src/setup/integrations/registry.d.ts +1 -1
  132. package/dist/src/setup/integrations/registry.js +1 -1
  133. package/dist/src/setup/integrations/runner.d.ts +14 -11
  134. package/dist/src/setup/integrations/runner.js +1 -1
  135. package/dist/src/setup/integrations/shared/prerequisite.d.ts +17 -0
  136. package/dist/src/setup/integrations/shared/prerequisite.js +1 -0
  137. package/dist/src/setup/integrations/shared/ui.d.ts +22 -15
  138. package/dist/src/setup/integrations/shared/ui.js +2 -2
  139. package/dist/src/setup/integrations/shared/vercel-project.d.ts +11 -0
  140. package/dist/src/setup/integrations/shared/vercel-project.js +1 -0
  141. package/dist/src/setup/integrations/slack/setup.d.ts +25 -10
  142. package/dist/src/setup/integrations/slack/setup.js +1 -1
  143. package/dist/src/setup/integrations/types.d.ts +43 -13
  144. package/dist/src/setup/integrations/types.js +1 -1
  145. package/dist/src/setup/integrations/web/setup.d.ts +22 -3
  146. package/dist/src/setup/integrations/web/setup.js +1 -1
  147. package/dist/src/setup/prompter.d.ts +8 -0
  148. package/dist/src/setup/question-options.d.ts +15 -0
  149. package/dist/src/setup/question-options.js +1 -0
  150. package/dist/src/setup/registry-setup-client.d.ts +3 -4
  151. package/dist/src/setup/registry-setup-client.js +2 -2
  152. package/dist/src/setup/registry-setup-completion.d.ts +3 -0
  153. package/dist/src/setup/registry-setup-completion.js +1 -0
  154. package/dist/src/setup/registry-setup-protocol.d.ts +22 -3
  155. package/dist/src/setup/registry-setup-protocol.js +1 -1
  156. package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
  157. package/dist/src/setup/scaffold/create/project.js +55 -3
  158. package/dist/src/setup/scaffold/update/channels.js +1 -1
  159. package/dist/src/setup/setup-question-wire.d.ts +48 -0
  160. package/dist/src/setup/setup-question-wire.js +1 -0
  161. package/dist/src/setup/slackbot.d.ts +5 -1
  162. package/dist/src/setup/slackbot.js +1 -1
  163. package/dist/src/setup/state.d.ts +2 -2
  164. package/dist/src/shared/sandbox-backend.d.ts +6 -0
  165. package/dist/src/shared/sandbox-session.d.ts +15 -0
  166. package/dist/src/shared/tool-definition.d.ts +2 -2
  167. package/dist/src/shared/tool-schema.d.ts +5 -4
  168. package/dist/src/shared/tool-schema.js +1 -1
  169. package/dist/src/svelte/index.js +1 -1
  170. package/dist/src/svelte/use-eve-agent.js +1 -1
  171. package/dist/src/tracing/agent-otel-provider.d.ts +5 -38
  172. package/dist/src/tracing/agent-otel-provider.js +2 -2
  173. package/dist/src/tracing/agent-span-id-generator.d.ts +15 -0
  174. package/dist/src/tracing/agent-span-id-generator.js +1 -0
  175. package/dist/src/tracing/agent-trace-context-store.d.ts +1 -1
  176. package/dist/src/tracing/agent-trace-context-store.js +1 -1
  177. package/dist/src/tracing/agent-trace-state.d.ts +41 -0
  178. package/dist/src/tracing/agent-trace-state.js +1 -0
  179. package/dist/src/tracing/local-instrumentation-runtime.js +1 -1
  180. package/dist/src/vue/index.js +1 -1
  181. package/dist/src/vue/use-eve-agent.js +1 -1
  182. package/docs/channels/chat-sdk.mdx +1 -1
  183. package/docs/channels/github.mdx +1 -1
  184. package/docs/channels/linear.mdx +1 -1
  185. package/docs/channels/overview.mdx +2 -2
  186. package/docs/channels/slack.mdx +154 -40
  187. package/docs/concepts/default-harness.md +3 -3
  188. package/docs/concepts/sessions-runs-and-streaming.md +1 -1
  189. package/docs/connections/mcp.mdx +6 -0
  190. package/docs/guides/dev-tui.md +58 -142
  191. package/docs/guides/dynamic-workflows.md +2 -0
  192. package/docs/guides/frontend/overview.mdx +4 -2
  193. package/docs/guides/hooks.md +25 -3
  194. package/docs/guides/session-context.md +18 -0
  195. package/docs/install-integrations.mdx +2 -0
  196. package/docs/reference/cli.md +5 -3
  197. package/docs/reference/typescript-api.md +1 -1
  198. package/docs/sandbox.mdx +25 -5
  199. package/docs/skills.mdx +12 -1
  200. package/docs/subagents.mdx +1 -1
  201. package/docs/tools/human-in-the-loop.md +1 -1
  202. package/docs/tutorial/ship-it.mdx +1 -1
  203. package/package.json +10 -10
  204. package/dist/src/compiled/_chunks/node/undici-DWL_MYmT.js +0 -95
  205. package/dist/src/compiled/_chunks/workflow/dist-CZxNEvEs.js +0 -79
@@ -218,6 +218,30 @@ declare function auth(provider: OAuthClientProvider, options: {
218
218
  * Transport interface for MCP (Model Context Protocol) communication.
219
219
  * Maps to the `Transport` interface in the MCP spec.
220
220
  */
221
+ type MCPTransportSendOptions = {
222
+ /**
223
+ * Cancels the transport operation for this message.
224
+ */
225
+ signal?: AbortSignal;
226
+ /**
227
+ * Associates an outgoing message with an incoming request.
228
+ */
229
+ relatedRequestId?: string | number;
230
+ /**
231
+ * Resumes a previously interrupted request.
232
+ */
233
+ resumptionToken?: string;
234
+ /**
235
+ * Receives updated resumption tokens from transports that support them.
236
+ */
237
+ onresumptiontoken?: (token: string) => void;
238
+ };
239
+ type MCPTransportCloseOptions = {
240
+ /**
241
+ * Cancels transport cleanup.
242
+ */
243
+ signal?: AbortSignal;
244
+ };
221
245
  interface MCPTransport {
222
246
  /**
223
247
  * Initialize and start the transport
@@ -226,12 +250,14 @@ interface MCPTransport {
226
250
  /**
227
251
  * Send a JSON-RPC message through the transport
228
252
  * @param message The JSON-RPC message to send
253
+ * @param options Optional request-scoped cancellation options
229
254
  */
230
- send(message: JSONRPCMessage): Promise<void>;
255
+ send(message: JSONRPCMessage, options?: MCPTransportSendOptions): Promise<void>;
231
256
  /**
232
257
  * Clean up and close the transport
258
+ * @param options Optional cancellation options for transport cleanup
233
259
  */
234
- close(): Promise<void>;
260
+ close(options?: MCPTransportCloseOptions): Promise<void>;
235
261
  /**
236
262
  * Event handler for transport closure
237
263
  */
@@ -599,6 +625,10 @@ type ElicitResult = z.infer<typeof ElicitResultSchema>;
599
625
  interface MCPClientConfig {
600
626
  /** Transport configuration for connecting to the MCP server */
601
627
  transport: MCPTransportConfig | MCPTransport;
628
+ /**
629
+ * Options that bound or cancel transport startup and the initialize request.
630
+ */
631
+ initializationOptions?: RequestOptions;
602
632
  /** Optional callback for uncaught errors */
603
633
  onUncaughtError?: (error: unknown) => void;
604
634
  /**
@@ -777,4 +807,4 @@ declare function fingerprintMCPAppResource(resource: MCPAppResource): Promise<st
777
807
  */
778
808
  declare function detectMCPAppResourceDrift(current: string, baseline: string): boolean;
779
809
 
780
- 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, 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 };
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 };
@@ -1 +1 @@
1
- import{A as e,C as t,G as n,K as r,L as i,Mt as a,St as o,Tt as s,W as c,X as l,_t as u,a as d,b as f,ct as p,et as m,gt as h,ht as g,l as ee,lt as te,mt as _,n as ne,pt as v,rt as y,st as re,ut as b,vt as x,wt as ie,xt as S,yt as C}from"../../_chunks/workflow/dist-CZxNEvEs.js";const ae={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 oe;oe||={};let w;w=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function se(e){return(await w).getRandomValues(new Uint8Array(e))}async function ce(e){let t=``;for(;t.length<e;){let n=await se(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function le(e){return await ce(e)}async function ue(e){let t=await(await w).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function de(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await le(e);return{code_verifier:t,code_challenge:await ue(t)}}var T=`2025-11-25`,fe=[T,`2025-06-18`,`2025-03-26`,`2024-11-05`],pe=u(x(C(),o())),me=_({name:C(),version:C(),title:u(C())}),E=_({_meta:u(h({}).loose())}),D=E,he=h({method:C(),params:u(E)}),ge=h({applyDefaults:u(b())}).loose(),_e=_({experimental:u(h({}).loose()),logging:u(h({}).loose()),completions:u(h({}).loose()),prompts:u(_({listChanged:u(b())})),resources:u(_({subscribe:u(b()),listChanged:u(b())})),tools:u(_({listChanged:u(b())})),elicitation:u(ge)});h({elicitation:u(ge)}).loose();var ve=D.extend({protocolVersion:C(),capabilities:_e,serverInfo:me,instructions:u(C())}),O=D.extend({nextCursor:u(C())}),ye=h({name:C(),title:u(C()),description:u(C()),inputSchema:h({type:v(`object`),properties:u(h({}).loose())}).loose(),outputSchema:u(h({}).loose()),annotations:u(h({title:u(C())}).loose()),_meta:pe}).loose(),be=O.extend({tools:p(ye)}),xe=h({type:v(`text`),text:C()}).loose(),Se=h({type:v(`image`),data:te(),mimeType:C()}).loose(),Ce=h({uri:C(),name:C(),title:u(C()),description:u(C()),mimeType:u(C()),size:u(g())}).loose(),we=O.extend({resources:p(Ce)}),Te=h({uri:C(),name:u(C()),title:u(C()),mimeType:u(C())}).loose(),Ee=Te.extend({text:C()}),De=Te.extend({blob:te()}),Oe=h({type:v(`resource`),resource:S([Ee,De])}).loose(),ke=h({type:v(`resource_link`),uri:C(),name:C(),description:u(C()),mimeType:u(C())}).loose(),Ae=D.extend({content:p(S([xe,Se,Oe,ke])),structuredContent:u(o()),isError:b().default(!1).optional()}).or(D.extend({toolResult:o()})),je=h({uriTemplate:C(),name:C(),title:u(C()),description:u(C()),mimeType:u(C())}).loose(),Me=D.extend({resourceTemplates:p(je)}),Ne=D.extend({contents:p(S([Ee,De]))}),Pe=h({type:v(`ref/prompt`),name:C()}).loose(),Fe=h({type:v(`ref/resource`),uri:C()}).loose(),Ie=h({name:C(),value:C()}).loose();E.extend({ref:S([Pe,Fe]),argument:Ie,context:u(h({arguments:x(C(),C())}).loose())});var Le=D.extend({completion:h({values:p(C()).max(100),total:u(g().int()),hasMore:u(b())}).loose()}),Re=h({name:C(),description:u(C()),required:u(b())}).loose(),ze=h({name:C(),title:u(C()),description:u(C()),arguments:u(p(Re))}).loose(),Be=O.extend({prompts:p(ze)}),Ve=h({role:S([v(`user`),v(`assistant`)]),content:S([xe,Se,Oe,ke])}).loose(),He=D.extend({description:u(C()),messages:p(Ve)}),Ue=E.extend({message:C(),requestedSchema:o()}),k=he.extend({method:v(`elicitation/create`),params:Ue}),We=D.extend({action:S([v(`accept`),v(`decline`),v(`cancel`)]),content:u(x(C(),o()))}),A=`2.0`,Ge=h({jsonrpc:v(A),id:S([C(),g().int()])}).merge(he).strict(),Ke=h({jsonrpc:v(A),id:S([C(),g().int()]),result:D}).strict(),qe=h({jsonrpc:v(A),id:S([C(),g().int()]),error:h({code:g().int(),message:C(),data:u(o())})}).strict(),Je=S([Ge,h({jsonrpc:v(A)}).merge(h({method:C(),params:u(E)})).strict(),Ke,qe]);function j(e){return Je.parse(e)}async function M(e){return j(await i({text:e}))}var Ye=`vercel.ai.error.AI_MCPClientError`,Xe=Symbol.for(Ye),Ze,Qe,N=class extends (Qe=s,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 s.hasMarker(e,Ye)}},$e=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,P=C().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ae.custom,message:`URL must be parseable`,fatal:!0}),ie}).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`}),F=h({access_token:C(),id_token:C().optional(),token_type:C(),expires_in:g().optional(),scope:C().optional(),refresh_token:C().optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),et=_({resource:C().url(),authorization_servers:p(P).optional(),jwks_uri:C().url().optional(),scopes_supported:p(C()).optional(),bearer_methods_supported:p(C()).optional(),resource_signing_alg_values_supported:p(C()).optional(),resource_name:C().optional(),resource_documentation:C().optional(),resource_policy_uri:C().url().optional(),resource_tos_uri:C().url().optional(),tls_client_certificate_bound_access_tokens:b().optional(),authorization_details_types_supported:p(C()).optional(),dpop_signing_alg_values_supported:p(C()).optional(),dpop_bound_access_tokens_required:b().optional()}),I=_({issuer:C(),authorization_endpoint:P,token_endpoint:P,registration_endpoint:P.optional(),scopes_supported:p(C()).optional(),response_types_supported:p(C()),grant_types_supported:p(C()).optional(),code_challenge_methods_supported:p(C()).optional(),token_endpoint_auth_methods_supported:p(C()).optional(),token_endpoint_auth_signing_alg_values_supported:p(C()).optional()}),tt=_({issuer:C(),authorization_endpoint:P,token_endpoint:P,userinfo_endpoint:P.optional(),jwks_uri:P,registration_endpoint:P.optional(),scopes_supported:p(C()).optional(),response_types_supported:p(C()),grant_types_supported:p(C()).optional(),subject_types_supported:p(C()),id_token_signing_alg_values_supported:p(C()),claims_supported:p(C()).optional(),token_endpoint_auth_methods_supported:p(C()).optional()}).merge(I.pick({code_challenge_methods_supported:!0})),nt=h({client_id:C(),client_secret:C().optional(),client_id_issued_at:g().optional(),client_secret_expires_at:g().optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),rt=h({redirect_uris:p(P),token_endpoint_auth_method:C().optional(),grant_types:p(C()).optional(),response_types:p(C()).optional(),client_name:C().optional(),client_uri:P.optional(),logo_uri:P.optional(),scope:C().optional(),contacts:p(C()).optional(),tos_uri:P.optional(),policy_uri:C().optional(),jwks_uri:P.optional(),jwks:re().optional(),software_id:C().optional(),software_version:C().optional(),software_statement:C().optional()}).strip(),it=h({error:C(),error_description:C().optional(),error_uri:C().optional()}),at=rt.merge(nt),ot=`vercel.ai.error.AI_MCPClientOAuthError`,st=Symbol.for(ot),ct,lt,L=class extends (lt=s,ct=st,lt){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[ct]=!0}static isInstance(e){return s.hasMarker(e,ot)}},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 ut={[R.errorCode]:R,[z.errorCode]:z,[B.errorCode]:B,[V.errorCode]:V};function dt(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 ft({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 pt(e,t){return{authorizationServerUrl:W(e),tokenEndpoint:W(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function mt(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ht(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function gt(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:W(e.authorization_server),tokenEndpoint:W(e.token_endpoint)}}async function G({provider:e,clientInformation:t,tokens:n}){let r=gt(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:W(i.authorizationServerUrl),tokenEndpoint:W(i.tokenEndpoint)}:gt(t)}async function _t({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(ht(t,n)),!0):!1}function vt(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 yt({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 K(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 bt(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function q(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?q(e,void 0,n):void 0;throw r}}async function xt(e,t,n=fetch){return await q(e,{"MCP-Protocol-Version":t},n)}function St(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Ct(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??T,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=bt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await xt(o,a,n);return!r?.metadataUrl&&St(s,i.pathname)&&(s=await xt(new URL(`/.well-known/${t}`,i),a,n)),s}async function wt(e,t,n=fetch){let r=await Ct(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 Tt(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 Et(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 Dt(e,{fetchFn:t=fetch,protocolVersion:n=T}={}){let r={"MCP-Protocol-Version":n},i=Tt(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await q(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=I.parse(await i.json());return Et(e,a),e}else{let t=tt.parse(await i.json());if(Et(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 Ot(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 de(),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 kt(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 At(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:jt(i,a,n);return;case`client_secret_post`:Mt(i,a,r);return;case`none`:Nt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function jt(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 Mt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Nt(e,t){t.set(`client_id`,e)}async function J(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}=it.parse(await i({text:n}));return new(ut[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 Pt(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):At(kt(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 J(p);return F.parse(await p.json())}async function Ft(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):At(kt(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 J(d);return F.parse({refresh_token:r,...await d.json()})}async function It(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 J(a);return at.parse(await a.json())}async function Y(e,t){try{return await X(e,t)}catch(n){if(n instanceof z||n instanceof V)return await e.invalidateCredentials?.call(e,`all`),await X(e,t);if(n instanceof B)return await e.invalidateCredentials?.call(e,`tokens`),await X(e,t);throw n}}async function Lt(e,t,n){let r=dt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!ft({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 X(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;vt(t,a);try{s=await wt(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await Lt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await Dt(c,{fetchFn:o}),d=pt(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=ht(await It(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 G({provider:e,clientInformation:f});if(!t)throw new L({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});yt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await Pt(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(mt(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await G({provider:e,clientInformation:f,tokens:p});t?yt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Ft(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(mt(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 Ot(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await _t({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 Rt(e){return e===void 0||e===`message`}var zt=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 n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??T};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(n.Authorization=`Bearer ${e.access_token}`)}return m(n,`ai-sdk/${$e}`,t())}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=K(c);try{if(await Y(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 N({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 N({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 N({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(Rt(s))try{let e=await M(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new N({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){if(!this.endpoint||!this.connected)throw new N({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=K(c);try{if(await Y(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){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new N({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}};function Bt(e){return e===void 0||e===`message`}var Vt=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:n=!0}){let r={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??T};if(n&&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 m(r,`ai-sdk/${$e}`,t())}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||=Y(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 N({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.startInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.terminateSessionOnClose&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({base:{}});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(n=!1)=>{var r,i,a,o,s,c;try{let c=`method`in e&&e.method===`initialize`,l=c?void 0:this.sessionId,u={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`},includeSessionId:!c}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},d=await this.fetchFn(this.url.href,u);if(this.applySessionIdFromResponse(d),d.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=K(d);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new U}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(d.status===202){this.inboundSseConnection||this.startInboundSse();return}if(!d.ok){let e=await d.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${d.status}): ${e}`;d.status===404&&(l?(this.expireSessionId(l),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 N({message:t,statusCode:d.status,url:this.url.href,responseBody:e??void 0});throw(i=this.onerror)==null||i.call(this,n),n}if(!(`id`in e))return;let f=d.headers.get(`content-type`)||``;if(f.includes(`application/json`)){let e=await d.json(),t=Array.isArray(e)?e.map(e=>j(e)):[j(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(f.includes(`text/event-stream`)){if(!d.body){let e=new N({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:d.status,url:this.url.href});throw(o=this.onerror)==null||o.call(this,e),e}let e=d.body.pipeThrough(new TextDecoderStream).pipeThrough(new y).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(Bt(a))try{let e=await M(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new N({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)});return}let p=new N({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`,statusCode:d.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,p),p}catch(e){throw(c=this.onerror)==null||c.call(this,e),e}};await 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 N({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=K(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 N({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),Bt(i))try{let t=await M(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new N({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 Ht(e){switch(e.type){case`sse`:return new zt(e);case`http`:return new Vt(e);default:throw new N({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Ut(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Wt=`io.modelcontextprotocol/ui`,Z=`text/html;profile=mcp-app`,Gt=`ui/resourceUri`,Kt={extensions:{[Wt]:{mimeTypes:[Z]}}};function qt(e){let t=e?.ui;return a(t)?t:void 0}var Q=p(o()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),Jt=_({connectDomains:Q,resourceDomains:Q,frameDomains:Q}),Yt=_({prefersBorder:b().optional().catch(void 0),csp:Jt.optional().catch(void 0),permissions:x(C(),o()).optional().catch(void 0)});function Xt(e){let t=(a(e)?e:void 0)?.ui;if(!a(t))return;let n=Yt.safeParse(t);return n.success?n.data:void 0}function Zt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function Qt(e){let t=qt(e._meta),n=t?.resourceUri??e._meta?.[Gt],r=Zt(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 $t(e){let t=[],n=[];for(let r of e.tools){let e=Qt(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 en({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(d(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Z,html:r,meta:Xt(n._meta)}}async function tn({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return en({uri:t,resource:await e.readResource({uri:t,options:n})})}var nn=`1.0.0`,rn=0,an=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function on(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function sn(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function cn(e){let t=on(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(N.isInstance(e)&&e.code!=null)return!1;let n=sn(e);return n!=null&&an.includes(n)}function ln(e){if(e==null)return rn;if(!Number.isInteger(e))throw new N({message:`maxRetries must be an integer`});if(e<0)throw new N({message:`maxRetries must be >= 0`});return e}function un({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 dn(e){let t=new fn(e);return await t.init(),t}var fn=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=nn,onUncaughtError:i,maxRetries:a,capabilities:o,initialInitializeResult:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:T,capabilities:{},serverInfo:this._serverInfo},this.isClosed=!0,this.onUncaughtError=i,this.maxRetries=ln(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,Ut(e)?this.transport=e:this.transport=Ht(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 N({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(){try{if(await this.transport.start(),this.isClosed=!1,this.initialInitializeResult){let e=ve.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}let e=await this.request({request:{method:`initialize`,params:{protocolVersion:T,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:ve});if(e===void 0)throw new N({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}applyInitializeResult(e){if(!fe.includes(e.protocolVersion))throw new N({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())}assertCapability(e){switch(e){case`initialize`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new N({message:`Server does not support completions`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new N({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new N({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new N({message:`Server does not support prompts`});break;default:throw new N({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new N({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{i(new N({message:`Request was aborted`,cause:a?.reason}))},l=()=>{this.responseHandlers.delete(o),a?.removeEventListener(`abort`,d)},u=e=>{l(),i(e)},d=()=>{l(),c()};this.responseHandlers.set(o,e=>{if(a?.aborted)return l(),c();if(e instanceof Error)return u(e);try{let n=t.parse(e.result);l(),r(n)}catch(e){let t=new N({message:`Failed to parse server response`,cause:e});u(t)}}),a?.addEventListener(`abort`,d,{once:!0}),this.transport.send(s).catch(e=>{u(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:be,options:t})}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():c({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:cn,createRetryError:({message:e,errors:t})=>new N({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:Ae,options:n})})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:we,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Ne,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:Me,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Be,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:He,options:n})}catch(e){throw e}}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:Le,options:e})}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}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:s,annotations:c,_meta:u}of t.tools){let t=a??c?.title;if(n!==`automatic`&&!Object.prototype.hasOwnProperty.call(n,i))continue;let d=this,p=n===`automatic`?void 0:n[i]?.outputSchema,m=Qt({_meta:u}),h={clientName:this.clientInfo.name,toolName:i,...t==null?{}:{title:t},...m?.resourceUri==null?{}:{app:{...m,mimeType:Z}}},g=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||p==null?r:d.extractStructuredContent(r,p,i)};r[i]={...n===`automatic`?f({description:o,title:t,metadata:h,inputSchema:e({...s,properties:s.properties??{},additionalProperties:!1}),execute:g,toModelOutput:un}):l({description:o,title:t,metadata:h,inputSchema:n[i].inputSchema,...p==null?{}:{outputSchema:p},execute:g,toModelOutput:un}),_meta:u}}return r}async extractStructuredContent(e,t,i){if(`structuredContent`in e&&e.structuredContent!=null){let n=await r({value:e.structuredContent,schema:ne(t)});if(!n.success)throw new N({message:`Tool "${i}" returned structuredContent that does not match the expected outputSchema`,cause:n.error});return n.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 n({text:r.text,schema:t});if(!e.success)throw new N({message:`Tool "${i}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new N({message:`Tool "${i}" 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!==k)throw new N({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=k.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=We.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 N({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 N({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new N({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},pn=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 mn(e){return ee(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function hn(e){let t=await crypto.subtle.digest(`SHA-256`,pn.encode($({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return mn(new Uint8Array(t))}function gn(e,t){return e!==t}export{We as ElicitResultSchema,k as ElicitationRequestSchema,Z as MCP_APP_MIME_TYPE,U as UnauthorizedError,Y as auth,dn as createMCPClient,dn as experimental_createMCPClient,gn as detectMCPAppResourceDrift,hn as fingerprintMCPAppResource,Kt as mcpAppClientCapabilities,tn as readMCPAppResource,$t as splitMCPAppTools,j as validateJSONRPCMessage};
1
+ import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{C as n,Ct as r,E as i,Et as a,H as o,Ot as s,P as c,Q as l,St as u,Tt 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-eUxFublw.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(d(a(),v())),ge=x({name:a(),version:a(),title:b(a())}),w=x({_meta:b(r({}).loose())}),T=w,_e=r({method:a(),params:b(w)}),ve=r({applyDefaults:b(m())}).loose(),ye=x({experimental:b(r({}).loose()),logging:b(r({}).loose()),completions:b(r({}).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)});r({elicitation:b(ve)}).loose();var be=T.extend({protocolVersion:a(),capabilities:ye,serverInfo:ge,instructions:b(a())}),E=T.extend({nextCursor:b(a())}),xe=r({name:a(),title:b(a()),description:b(a()),inputSchema:r({type:h(`object`),properties:b(r({}).loose())}).loose(),outputSchema:b(r({}).loose()),annotations:b(r({title:b(a())}).loose()),_meta:he}).loose(),Se=E.extend({tools:_(xe)}),Ce=r({type:h(`text`),text:a()}).loose(),we=r({type:h(`image`),data:g(),mimeType:a()}).loose(),Te=r({uri:a(),name:a(),title:b(a()),description:b(a()),mimeType:b(a()),size:b(u())}).loose(),Ee=E.extend({resources:_(Te)}),D=r({uri:a(),name:b(a()),title:b(a()),mimeType:b(a())}).loose(),O=D.extend({text:a()}),k=D.extend({blob:g()}),De=r({type:h(`resource`),resource:s([O,k])}).loose(),Oe=r({type:h(`resource_link`),uri:a(),name:a(),description:b(a()),mimeType:b(a())}).loose(),ke=T.extend({content:_(s([Ce,we,De,Oe])),structuredContent:b(v()),isError:m().default(!1).optional()}).or(T.extend({toolResult:v()})),Ae=r({uriTemplate:a(),name:a(),title:b(a()),description:b(a()),mimeType:b(a())}).loose(),je=T.extend({resourceTemplates:_(Ae)}),Me=T.extend({contents:_(s([O,k]))}),Ne=r({type:h(`ref/prompt`),name:a()}).loose(),Pe=r({type:h(`ref/resource`),uri:a()}).loose(),Fe=r({name:a(),value:a()}).loose();w.extend({ref:s([Ne,Pe]),argument:Fe,context:b(r({arguments:d(a(),a())}).loose())});var Ie=T.extend({completion:r({values:_(a()).max(100),total:b(u().int()),hasMore:b(m())}).loose()}),Le=r({name:a(),description:b(a()),required:b(m())}).loose(),Re=r({name:a(),title:b(a()),description:b(a()),arguments:b(_(Le))}).loose(),ze=E.extend({prompts:_(Re)}),Be=r({role:s([h(`user`),h(`assistant`)]),content:s([Ce,we,De,Oe])}).loose(),Ve=T.extend({description:b(a()),messages:_(Be)}),He=w.extend({message:a(),requestedSchema:v()}),A=_e.extend({method:h(`elicitation/create`),params:He}),Ue=T.extend({action:s([h(`accept`),h(`decline`),h(`cancel`)]),content:b(d(a(),v()))}),j=`2.0`,We=r({jsonrpc:h(j),id:s([a(),u().int()])}).merge(_e).strict(),Ge=r({jsonrpc:h(j),id:s([a(),u().int()]),result:T}).strict(),Ke=r({jsonrpc:h(j),id:s([a(),u().int()]),error:r({code:u().int(),message:a(),data:b(v())})}).strict(),qe=s([We,r({jsonrpc:h(j)}).merge(r({method:a(),params:b(w)})).strict(),Ge,Ke]);function M(e){return qe.parse(e)}async function N(e){return M(await o({text:e}))}var Je=`vercel.ai.error.AI_MCPClientError`,Ye=Symbol.for(Je),Xe,Ze,P=class extends (Ze=e,Xe=Ye,Ze){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[Xe]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,Je)}},Qe=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,F=a().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=r({access_token:a(),id_token:a().optional(),token_type:a(),expires_in:u().optional(),scope:a().optional(),refresh_token:a().optional(),authorization_server:F.optional(),token_endpoint:F.optional()}).strip(),et=x({resource:a().url(),authorization_servers:_(F).optional(),jwks_uri:a().url().optional(),scopes_supported:_(a()).optional(),bearer_methods_supported:_(a()).optional(),resource_signing_alg_values_supported:_(a()).optional(),resource_name:a().optional(),resource_documentation:a().optional(),resource_policy_uri:a().url().optional(),resource_tos_uri:a().url().optional(),tls_client_certificate_bound_access_tokens:m().optional(),authorization_details_types_supported:_(a()).optional(),dpop_signing_alg_values_supported:_(a()).optional(),dpop_bound_access_tokens_required:m().optional()}),tt=x({issuer:a(),authorization_endpoint:F,token_endpoint:F,registration_endpoint:F.optional(),scopes_supported:_(a()).optional(),response_types_supported:_(a()),grant_types_supported:_(a()).optional(),code_challenge_methods_supported:_(a()).optional(),token_endpoint_auth_methods_supported:_(a()).optional(),token_endpoint_auth_signing_alg_values_supported:_(a()).optional()}),nt=x({issuer:a(),authorization_endpoint:F,token_endpoint:F,userinfo_endpoint:F.optional(),jwks_uri:F,registration_endpoint:F.optional(),scopes_supported:_(a()).optional(),response_types_supported:_(a()),grant_types_supported:_(a()).optional(),subject_types_supported:_(a()),id_token_signing_alg_values_supported:_(a()),claims_supported:_(a()).optional(),token_endpoint_auth_methods_supported:_(a()).optional()}).merge(tt.pick({code_challenge_methods_supported:!0})),rt=r({client_id:a(),client_secret:a().optional(),client_id_issued_at:u().optional(),client_secret_expires_at:u().optional(),authorization_server:F.optional(),token_endpoint:F.optional()}).strip(),it=r({redirect_uris:_(F),token_endpoint_auth_method:a().optional(),grant_types:_(a()).optional(),response_types:_(a()).optional(),client_name:a().optional(),client_uri:F.optional(),logo_uri:F.optional(),scope:a().optional(),contacts:_(a()).optional(),tos_uri:F.optional(),policy_uri:a().optional(),jwks_uri:F.optional(),jwks:te().optional(),software_id:a().optional(),software_version:a().optional(),software_statement:a().optional()}).strip(),at=r({error:a(),error_description:a().optional(),error_uri:a().optional()}),ot=it.merge(rt),st=`vercel.ai.error.AI_MCPClientOAuthError`,ct=Symbol.for(st),lt,ut,I=class extends (ut=e,lt=ct,ut){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[lt]=!0}static isInstance(t){return e.hasMarker(t,st)}},L=class extends I{};L.errorCode=`server_error`;var R=class extends I{};R.errorCode=`invalid_client`;var z=class extends I{};z.errorCode=`invalid_grant`;var B=class extends I{};B.errorCode=`unauthorized_client`;var dt={[L.errorCode]:L,[R.errorCode]:R,[z.errorCode]:z,[B.errorCode]:B};function ft(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function V(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 H=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function U(e){return new URL(e).href}function mt(e,t){return{authorizationServerUrl:U(e),tokenEndpoint:U(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:U(e.authorization_server),tokenEndpoint:U(e.token_endpoint)}}async function W({provider:e,clientInformation:t,tokens:n}){let r=_t(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:U(i.authorizationServerUrl),tokenEndpoint:U(i.tokenEndpoint)}:_t(t)}async function vt({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 yt(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new I({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function bt({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new I({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 xt(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 St(e,t,n=fetch){return await K(e,{"MCP-Protocol-Version":t},n)}function Ct(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function wt(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=xt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await St(o,a,n);return!r?.metadataUrl&&Ct(s,i.pathname)&&(s=await St(new URL(`/.well-known/${t}`,i),a,n)),s}async function Tt(e,t,n=fetch){let r=await wt(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 Et(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 Dt(e,t){if(e.issuer!==t)throw new I({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Ot(e,{fetchFn:t=fetch,protocolVersion:n=C}={}){let r={"MCP-Protocol-Version":n},i=Et(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 Dt(e,a),e}else{let t=nt.parse(await i.json());if(Dt(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 kt(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`,V(o)),{authorizationUrl:l,codeVerifier:d}}function At(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 jt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Mt(i,a,n);return;case`client_secret_post`:Nt(i,a,r);return;case`none`:Pt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Mt(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 Nt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Pt(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 o({text:n}));return new(dt[e]||L)({message:t||``,cause:r})}catch(e){return new L({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Ft(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):jt(At(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,V(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 It(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):jt(At(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,V(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 Lt(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 R||n instanceof B)return await e.invalidateCredentials?.call(e,`all`),await Y(e,t);if(n instanceof z)return await e.invalidateCredentials?.call(e,`tokens`),await Y(e,t);throw n}}async function Rt(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;yt(t,a);try{s=await Tt(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await Rt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await Ot(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 Lt(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 W({provider:e,clientInformation:f});if(!t)throw new I({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});bt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await Ft(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 W({provider:e,clientInformation:f,tokens:p});t?bt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await It(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 I)||e instanceof L))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:h,codeVerifier:g}=await kt(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await vt({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new I({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(h),`REDIRECT`}function zt(e){return e===void 0||e===`message`}var Bt=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/${Qe}`,i())}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 H;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(zt(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 H;(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 Vt(e){return e===void 0||e===`message`}var Ht=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 n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??C};if(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 ae(n,`ai-sdk/${Qe}`,i())}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 H}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(Vt(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 H;(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),Vt(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 Ut(e){switch(e.type){case`sse`:return new Bt(e);case`http`:return new Ht(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 Wt(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Gt=`io.modelcontextprotocol/ui`,X=`text/html;profile=mcp-app`,Kt=`ui/resourceUri`,qt={extensions:{[Gt]:{mimeTypes:[X]}}};function Jt(e){let n=e?.ui;return t(n)?n:void 0}var Z=_(v()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),Yt=x({connectDomains:Z,resourceDomains:Z,frameDomains:Z}),Xt=x({prefersBorder:m().optional().catch(void 0),csp:Yt.optional().catch(void 0),permissions:d(a(),v()).optional().catch(void 0)});function Zt(e){let n=(t(e)?e:void 0)?.ui;if(!t(n))return;let r=Xt.safeParse(n);return r.success?r.data:void 0}function Qt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function $t(e){let t=Jt(e._meta),n=t?.resourceUri??e._meta?.[Kt],r=Qt(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 en(e){let t=[],n=[];for(let r of e.tools){let e=$t(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 tn({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:Zt(n._meta)}}async function nn({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return tn({uri:t,resource:await e.readResource({uri:t,options:n})})}var rn=`1.0.0`,an=0,on=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function sn(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function cn(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function ln(e){let t=sn(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(P.isInstance(e)&&e.code!=null)return!1;let n=cn(e);return n!=null&&on.includes(n)}function un(e){if(e==null)return an;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 dn({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 pn(e){let t=new mn(e);return await t.init(),t}var mn=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=rn,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=un(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,this.initializationOptions=c,Wt(e)?this.transport=e:this.transport=Ut(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?dn(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:dn(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:ln,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:Ee,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(e,{schemas:t=`automatic`}={}){let r={};for(let{name:i,title:a,description:o,inputSchema:s,annotations:l,_meta:u}of e.tools){let e=a??l?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,i))continue;let d=this,f=t===`automatic`?void 0:t[i]?.outputSchema,p=$t({_meta:u}),m={clientName:this.clientInfo.name,toolName:i,...e==null?{}:{title:e},...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]={...t===`automatic`?n({description:o,title:e,metadata:m,inputSchema:c({...s,properties:s.properties??{},additionalProperties:!1}),execute:h,toModelOutput:fn}):re({description:o,title:e,metadata:m,inputSchema:t[i].inputSchema,...f==null?{}:{outputSchema:f},execute:h,toModelOutput:fn}),_meta:u}}return r}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await l({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}))}},hn=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 gn(e){return oe(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function _n(e){let t=await crypto.subtle.digest(`SHA-256`,hn.encode($({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return gn(new Uint8Array(t))}function vn(e,t){return e!==t}export{Ue as ElicitResultSchema,A as ElicitationRequestSchema,X as MCP_APP_MIME_TYPE,H as UnauthorizedError,J as auth,pn as createMCPClient,pn as experimental_createMCPClient,vn as detectMCPAppResourceDrift,_n as fingerprintMCPAppResource,qt as mcpAppClientCapabilities,nn as readMCPAppResource,en as splitMCPAppTools,M as validateJSONRPCMessage};
@@ -1,7 +1,7 @@
1
1
  import * as _ai_sdk_provider from '#compiled/@ai-sdk/provider/index.js';
2
- import { JSONValue, ProviderV4, LanguageModelV4, EmbeddingModelV4, ImageModelV4, TranscriptionModelV4, SpeechModelV4, Experimental_RealtimeFactoryV4, FilesV4, SkillsV4, Experimental_RealtimeModelV4, Experimental_RealtimeModelV4ClientSecretOptions, Experimental_RealtimeModelV4ClientSecretResult, Experimental_RealtimeModelV4ServerEvent, Experimental_RealtimeModelV4ClientEvent, Experimental_RealtimeModelV4SessionConfig } from '#compiled/@ai-sdk/provider/index.js';
2
+ import { JSONValue, ProviderV4, Experimental_BatchLanguageModelV4, LanguageModelV4, EmbeddingModelV4, ImageModelV4, TranscriptionModelV4, Experimental_SpeechTranslationModelV4, SpeechModelV4, Experimental_RealtimeFactoryV4, FilesV4, SkillsV4, Experimental_RealtimeModelV4, Experimental_RealtimeModelV4ClientSecretOptions, Experimental_RealtimeModelV4ClientSecretResult, Experimental_RealtimeModelV4ServerEvent, Experimental_RealtimeModelV4ClientEvent, Experimental_RealtimeModelV4SessionConfig, JSONObject, Experimental_SpeechTranslationModelV4StreamOptions } from '#compiled/@ai-sdk/provider/index.js';
3
3
  import * as _ai_sdk_provider_utils from '#compiled/@ai-sdk/provider-utils/index.js';
4
- import { InferSchema, FetchFunction, WebSocketConstructor } from '#compiled/@ai-sdk/provider-utils/index.js';
4
+ import { InferSchema, FetchFunction, WebSocketConstructor, WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE } from '#compiled/@ai-sdk/provider-utils/index.js';
5
5
  import { z } from '#compiled/zod/index.js';
6
6
 
7
7
  type OpenAIChatModelId = 'o1' | 'o1-2024-12-17' | 'o3-mini' | 'o3-mini-2025-01-31' | 'o3' | 'o3-2025-04-16' | 'o4-mini' | 'o4-mini-2025-04-16' | 'gpt-4.1' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-audio-preview' | 'gpt-4o-audio-preview-2024-12-17' | 'gpt-4o-audio-preview-2025-06-03' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4o-mini-audio-preview' | 'gpt-4o-mini-audio-preview-2024-12-17' | 'gpt-4o-search-preview' | 'gpt-4o-search-preview-2025-03-11' | 'gpt-4o-mini-search-preview' | 'gpt-4o-mini-search-preview-2025-03-11' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-16k' | 'gpt-5' | 'gpt-5-2025-08-07' | 'gpt-5-mini' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano' | 'gpt-5-nano-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-5.1' | 'gpt-5.1-2025-11-13' | 'gpt-5.1-chat-latest' | 'gpt-5.2' | 'gpt-5.2-2025-12-11' | 'gpt-5.2-chat-latest' | 'gpt-5.2-pro' | 'gpt-5.2-pro-2025-12-11' | 'gpt-5.3-chat-latest' | 'gpt-5.4' | 'gpt-5.4-2026-03-05' | 'gpt-5.4-mini' | 'gpt-5.4-mini-2026-03-17' | 'gpt-5.4-nano' | 'gpt-5.4-nano-2026-03-17' | 'gpt-5.4-pro' | 'gpt-5.4-pro-2026-03-05' | 'gpt-5.5' | 'gpt-5.5-2026-04-23' | 'gpt-5.6' | 'gpt-5.6-luna' | 'gpt-5.6-sol' | 'gpt-5.6-terra' | (string & {});
@@ -15,7 +15,7 @@ declare const openaiLanguageModelChatOptions: _ai_sdk_provider_utils.LazySchema<
15
15
  store?: boolean | undefined;
16
16
  metadata?: Record<string, string> | undefined;
17
17
  prediction?: Record<string, any> | undefined;
18
- serviceTier?: "default" | "auto" | "flex" | "priority" | undefined;
18
+ serviceTier?: "default" | "auto" | "flex" | "priority" | "fast" | undefined;
19
19
  strictJsonSchema?: boolean | undefined;
20
20
  textVerbosity?: "low" | "medium" | "high" | undefined;
21
21
  promptCacheKey?: string | undefined;
@@ -144,8 +144,15 @@ declare const webSearchToolFactory: _ai_sdk_provider_utils.ProviderExecutedToolF
144
144
  * Allowed domains for the search.
145
145
  * If not provided, all domains are allowed.
146
146
  * Subdomains of the provided domains are allowed as well.
147
+ * Omit the HTTP or HTTPS prefix. Maximum 100 domains.
147
148
  */
148
149
  allowedDomains?: string[];
150
+ /**
151
+ * Blocked domains for the search.
152
+ * Subdomains of the provided domains are blocked as well.
153
+ * Omit the HTTP or HTTPS prefix. Maximum 100 domains.
154
+ */
155
+ blockedDomains?: string[];
149
156
  };
150
157
  /**
151
158
  * Search context size to use for the web search.
@@ -233,6 +240,7 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
233
240
  type: "response.output_text.delta";
234
241
  item_id: string;
235
242
  delta: string;
243
+ output_index?: number | null | undefined;
236
244
  logprobs?: {
237
245
  token: string;
238
246
  logprob: number;
@@ -304,6 +312,14 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
304
312
  model: string;
305
313
  service_tier?: string | null | undefined;
306
314
  };
315
+ } | {
316
+ type: "response.in_progress";
317
+ response: {
318
+ id: string;
319
+ created_at: number;
320
+ model: string;
321
+ service_tier?: string | null | undefined;
322
+ };
307
323
  } | {
308
324
  type: "response.output_item.added";
309
325
  output_index: number;
@@ -414,6 +430,24 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
414
430
  name: string;
415
431
  arguments: string;
416
432
  namespace?: string | null | undefined;
433
+ caller?: {
434
+ type: "direct";
435
+ } | {
436
+ type: "program";
437
+ caller_id: string;
438
+ } | null | undefined;
439
+ } | {
440
+ type: "program";
441
+ id: string;
442
+ call_id: string;
443
+ code: string;
444
+ fingerprint: string;
445
+ } | {
446
+ type: "program_output";
447
+ id: string;
448
+ call_id: string;
449
+ result: string;
450
+ status: "completed" | "incomplete";
417
451
  } | {
418
452
  type: "web_search_call";
419
453
  id: string;
@@ -608,6 +642,18 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
608
642
  code?: string | null | undefined;
609
643
  message?: string | null | undefined;
610
644
  }[] | null | undefined;
645
+ } | {
646
+ type: "program";
647
+ id: string;
648
+ call_id: string;
649
+ code: string;
650
+ fingerprint: string;
651
+ } | {
652
+ type: "program_output";
653
+ id: string;
654
+ call_id: string;
655
+ result: string;
656
+ status: "completed" | "incomplete";
611
657
  } | {
612
658
  type: "message";
613
659
  id: string;
@@ -622,8 +668,14 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
622
668
  call_id: string;
623
669
  name: string;
624
670
  arguments: string;
625
- status: "completed";
671
+ status: "completed" | "in_progress" | "incomplete";
626
672
  namespace?: string | null | undefined;
673
+ caller?: {
674
+ type: "direct";
675
+ } | {
676
+ type: "program";
677
+ caller_id: string;
678
+ } | null | undefined;
627
679
  } | {
628
680
  type: "custom_tool_call";
629
681
  id: string;
@@ -844,15 +896,18 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
844
896
  type: "response.reasoning_summary_part.added";
845
897
  item_id: string;
846
898
  summary_index: number;
899
+ output_index?: number | null | undefined;
847
900
  } | {
848
901
  type: "response.reasoning_summary_text.delta";
849
902
  item_id: string;
850
903
  summary_index: number;
851
904
  delta: string;
905
+ output_index?: number | null | undefined;
852
906
  } | {
853
907
  type: "response.reasoning_summary_part.done";
854
908
  item_id: string;
855
909
  summary_index: number;
910
+ output_index?: number | null | undefined;
856
911
  } | {
857
912
  type: "response.apply_patch_call_operation_diff.delta";
858
913
  item_id: string;
@@ -1253,6 +1308,17 @@ declare const openaiTools: {
1253
1308
  output?: string | null;
1254
1309
  error?: _ai_sdk_provider.JSONValue;
1255
1310
  }, {}>;
1311
+ /**
1312
+ * Programmatic Tool Calling lets OpenAI Responses models write and execute
1313
+ * JavaScript that orchestrates eligible tools.
1314
+ */
1315
+ programmaticToolCalling: () => _ai_sdk_provider_utils.Experimental_ToolCallerTool<_ai_sdk_provider_utils.ProviderExecutedTool<{
1316
+ code: string;
1317
+ fingerprint: string;
1318
+ }, {
1319
+ result: string;
1320
+ status: "completed" | "incomplete";
1321
+ }, {}>>;
1256
1322
  /**
1257
1323
  * Tool search allows the model to dynamically search for and load deferred
1258
1324
  * tools into the model's context as needed. This helps reduce overall token
@@ -1300,7 +1366,7 @@ declare const openaiLanguageModelResponsesOptionsSchema: _ai_sdk_provider_utils.
1300
1366
  reasoningContext?: "auto" | "current_turn" | "all_turns" | undefined;
1301
1367
  reasoningSummary?: string | null | undefined;
1302
1368
  safetyIdentifier?: string | null | undefined;
1303
- serviceTier?: "default" | "auto" | "flex" | "priority" | null | undefined;
1369
+ serviceTier?: "default" | "auto" | "flex" | "priority" | "fast" | null | undefined;
1304
1370
  store?: boolean | null | undefined;
1305
1371
  passThroughUnsupportedFiles?: boolean | undefined;
1306
1372
  strictJsonSchema?: boolean | null | undefined;
@@ -1341,12 +1407,16 @@ declare const openAITranscriptionModelOptions: _ai_sdk_provider_utils.LazySchema
1341
1407
  }>;
1342
1408
  type OpenAITranscriptionModelOptions = InferSchema<typeof openAITranscriptionModelOptions>;
1343
1409
 
1410
+ type OpenAISpeechTranslationModelId = 'gpt-realtime-translate' | (string & {});
1411
+ declare const openAISpeechTranslationModelOptions: _ai_sdk_provider_utils.LazySchema<Record<string, never>>;
1412
+ type OpenAISpeechTranslationModelOptions = InferSchema<typeof openAISpeechTranslationModelOptions>;
1413
+
1344
1414
  interface OpenAIProvider extends ProviderV4 {
1345
- (modelId: OpenAIResponsesModelId): LanguageModelV4;
1415
+ (modelId: OpenAIResponsesModelId): Experimental_BatchLanguageModelV4;
1346
1416
  /**
1347
1417
  * Creates an OpenAI model for text generation.
1348
1418
  */
1349
- languageModel(modelId: OpenAIResponsesModelId): LanguageModelV4;
1419
+ languageModel(modelId: OpenAIResponsesModelId): Experimental_BatchLanguageModelV4;
1350
1420
  /**
1351
1421
  * Creates an OpenAI chat model for text generation.
1352
1422
  */
@@ -1354,7 +1424,7 @@ interface OpenAIProvider extends ProviderV4 {
1354
1424
  /**
1355
1425
  * Creates an OpenAI responses API model for text generation.
1356
1426
  */
1357
- responses(modelId: OpenAIResponsesModelId): LanguageModelV4;
1427
+ responses(modelId: OpenAIResponsesModelId): Experimental_BatchLanguageModelV4;
1358
1428
  /**
1359
1429
  * Creates an OpenAI completion model for text generation.
1360
1430
  */
@@ -1387,6 +1457,14 @@ interface OpenAIProvider extends ProviderV4 {
1387
1457
  * Creates a model for transcription.
1388
1458
  */
1389
1459
  transcription(modelId: OpenAITranscriptionModelId): TranscriptionModelV4;
1460
+ /**
1461
+ * Creates an experimental model for streaming speech translation.
1462
+ */
1463
+ translation(modelId: OpenAISpeechTranslationModelId): Experimental_SpeechTranslationModelV4;
1464
+ /**
1465
+ * Creates an experimental model for streaming speech translation.
1466
+ */
1467
+ speechTranslationModel(modelId: OpenAISpeechTranslationModelId): Experimental_SpeechTranslationModelV4;
1390
1468
  /**
1391
1469
  * Creates a model for speech generation.
1392
1470
  */
@@ -1479,6 +1557,59 @@ declare class OpenAIRealtimeModel implements Experimental_RealtimeModelV4 {
1479
1557
  buildSessionConfig(config: Experimental_RealtimeModelV4SessionConfig): Record<string, unknown>;
1480
1558
  }
1481
1559
 
1560
+ type OpenAIToolOptions = {
1561
+ allowedCallers?: Array<'direct' | 'programmatic'>;
1562
+ deferLoading?: boolean;
1563
+ outputSchema?: JSONObject;
1564
+ namespace?: {
1565
+ name: string;
1566
+ description: string;
1567
+ };
1568
+ };
1569
+
1570
+ type OpenAIConfig = {
1571
+ provider: string;
1572
+ url: (options: {
1573
+ modelId: string;
1574
+ path: string;
1575
+ }) => string;
1576
+ headers?: () => Record<string, string | undefined>;
1577
+ fetch?: FetchFunction;
1578
+ webSocket?: WebSocketConstructor;
1579
+ generateId?: () => string;
1580
+ /**
1581
+ * This is soft-deprecated. Use provider references (e.g. `{ openai: 'file-abc123' }`)
1582
+ * in file part data instead. File ID prefixes used to identify file IDs
1583
+ * in Responses API. When undefined, all string file data is treated as
1584
+ * base64 content.
1585
+ *
1586
+ * TODO: remove in v8
1587
+ */
1588
+ fileIdPrefixes?: readonly string[];
1589
+ };
1590
+
1591
+ interface OpenAISpeechTranslationModelConfig extends OpenAIConfig {
1592
+ _internal?: {
1593
+ currentDate?: () => Date;
1594
+ };
1595
+ }
1596
+ declare class OpenAISpeechTranslationModel implements Experimental_SpeechTranslationModelV4 {
1597
+ readonly modelId: OpenAISpeechTranslationModelId;
1598
+ private readonly config;
1599
+ readonly specificationVersion = "v4";
1600
+ static [WORKFLOW_SERIALIZE](model: OpenAISpeechTranslationModel): {
1601
+ modelId: string;
1602
+ config: _ai_sdk_provider.JSONObject;
1603
+ };
1604
+ static [WORKFLOW_DESERIALIZE](options: {
1605
+ modelId: OpenAISpeechTranslationModelId;
1606
+ config: OpenAISpeechTranslationModelConfig;
1607
+ }): OpenAISpeechTranslationModel;
1608
+ get provider(): string;
1609
+ constructor(modelId: OpenAISpeechTranslationModelId, config: OpenAISpeechTranslationModelConfig);
1610
+ doStream(options: Experimental_SpeechTranslationModelV4StreamOptions): Promise<Awaited<ReturnType<Experimental_SpeechTranslationModelV4['doStream']>>>;
1611
+ }
1612
+
1482
1613
  declare const openaiFilesOptionsSchema: _ai_sdk_provider_utils.LazySchema<{
1483
1614
  purpose?: string | undefined;
1484
1615
  expiresAfter?: number | undefined;
@@ -1595,4 +1726,4 @@ type OpenaiResponsesSourceDocumentProviderMetadata = {
1595
1726
 
1596
1727
  declare const VERSION: string;
1597
1728
 
1598
- export { OpenAIRealtimeModel as Experimental_OpenAIRealtimeModel, type OpenAIRealtimeModelConfig as Experimental_OpenAIRealtimeModelConfig, type OpenAILanguageModelChatOptions as OpenAIChatLanguageModelOptions, type OpenAIComputerAction, type OpenAIComputerSafetyCheck, type OpenAIEmbeddingModelOptions, type OpenAIFilesOptions, type OpenAIImageModelEditOptions, type OpenAIImageModelGenerationOptions, type OpenAIImageModelOptions, type OpenAILanguageModelChatOptions, type OpenAILanguageModelCompletionOptions, type OpenAILanguageModelResponsesOptions, type OpenAIProvider, type OpenAIProviderSettings, type OpenAILanguageModelResponsesOptions as OpenAIResponsesProviderOptions, type OpenAISpeechModelOptions, type OpenAITranscriptionModelOptions, type OpenaiResponsesCompactionProviderMetadata, type OpenaiResponsesProviderMetadata, type OpenaiResponsesReasoningProviderMetadata, type OpenaiResponsesSourceDocumentProviderMetadata, type OpenaiResponsesTextProviderMetadata, VERSION, createOpenAI, openai };
1729
+ export { OpenAIRealtimeModel as Experimental_OpenAIRealtimeModel, type OpenAIRealtimeModelConfig as Experimental_OpenAIRealtimeModelConfig, OpenAISpeechTranslationModel as Experimental_OpenAISpeechTranslationModel, type OpenAISpeechTranslationModelId as Experimental_OpenAISpeechTranslationModelId, type OpenAISpeechTranslationModelOptions as Experimental_OpenAISpeechTranslationModelOptions, OpenAISpeechTranslationModel as Experimental_OpenAITranslationModel, type OpenAISpeechTranslationModelId as Experimental_OpenAITranslationModelId, type OpenAISpeechTranslationModelOptions as Experimental_OpenAITranslationModelOptions, type OpenAILanguageModelChatOptions as OpenAIChatLanguageModelOptions, type OpenAIComputerAction, type OpenAIComputerSafetyCheck, type OpenAIEmbeddingModelOptions, type OpenAIFilesOptions, type OpenAIImageModelEditOptions, type OpenAIImageModelGenerationOptions, type OpenAIImageModelOptions, type OpenAILanguageModelChatOptions, type OpenAILanguageModelCompletionOptions, type OpenAILanguageModelResponsesOptions, type OpenAIProvider, type OpenAIProviderSettings, type OpenAILanguageModelResponsesOptions as OpenAIResponsesProviderOptions, type OpenAISpeechModelOptions, type OpenAIToolOptions, type OpenAITranscriptionModelOptions, type OpenaiResponsesCompactionProviderMetadata, type OpenaiResponsesProviderMetadata, type OpenaiResponsesReasoningProviderMetadata, type OpenaiResponsesSourceDocumentProviderMetadata, type OpenaiResponsesTextProviderMetadata, VERSION, createOpenAI, openai };