eve 0.13.8 → 0.15.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 (237) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/src/channel/compiled-channel.js +2 -1
  3. package/dist/src/channel/routes.d.ts +5 -0
  4. package/dist/src/channel/send.js +1 -1
  5. package/dist/src/channel/types.d.ts +5 -0
  6. package/dist/src/cli/dev/tui/runner.js +1 -1
  7. package/dist/src/cli/dev/tui/setup-panel.d.ts +3 -4
  8. package/dist/src/cli/dev/tui/setup-panel.js +2 -2
  9. package/dist/src/cli/dev/tui/terminal-renderer.js +1 -1
  10. package/dist/src/compiled/.vendor-stamp.json +12 -8
  11. package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +2 -2
  12. package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
  13. package/dist/src/compiled/@ai-sdk/google/index.d.ts +25 -3
  14. package/dist/src/compiled/@ai-sdk/google/index.js +6 -6
  15. package/dist/src/compiled/@ai-sdk/mcp/index.d.ts +647 -30
  16. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  17. package/dist/src/compiled/@ai-sdk/openai/index.d.ts +8 -2
  18. package/dist/src/compiled/@ai-sdk/openai/index.js +2 -2
  19. package/dist/src/compiled/@ai-sdk/otel/index.d.ts +165 -28
  20. package/dist/src/compiled/@ai-sdk/otel/index.js +3 -3
  21. package/dist/src/compiled/@ai-sdk/provider/index.d.ts +10 -2
  22. package/dist/src/compiled/@ai-sdk/provider-utils/index.d.ts +2362 -0
  23. package/dist/src/compiled/@ai-sdk/provider-utils/index.js +1 -0
  24. package/dist/src/compiled/@workflow/serde/LICENSE.md +3 -0
  25. package/dist/src/compiled/@workflow/serde/index.d.ts +30 -0
  26. package/dist/src/compiled/@workflow/serde/index.js +1 -0
  27. package/dist/src/compiled/_chunks/workflow/{dist-C9PV_vnE.js → dist-D7CzPkf8.js} +1 -1
  28. package/dist/src/compiled/eventsource-parser/stream/LICENSE +21 -0
  29. package/dist/src/compiled/eventsource-parser/stream/index.d.ts +121 -0
  30. package/dist/src/compiled/eventsource-parser/stream/index.js +1 -0
  31. package/dist/src/compiled/experimental-ai-sdk-code-mode/approval-continuation.d.ts +7 -7
  32. package/dist/src/compiled/experimental-ai-sdk-code-mode/continuation-capability.d.ts +15 -4
  33. package/dist/src/compiled/experimental-ai-sdk-code-mode/index.d.ts +1 -1
  34. package/dist/src/compiled/experimental-ai-sdk-code-mode/index.js +15 -15
  35. package/dist/src/compiled/experimental-ai-sdk-code-mode/interrupt-continuation.d.ts +5 -5
  36. package/dist/src/compiled/experimental-ai-sdk-code-mode/runtime/protocol.d.ts +13 -2
  37. package/dist/src/compiled/experimental-ai-sdk-code-mode/types.d.ts +26 -0
  38. package/dist/src/compiled/json-schema/LICENSE +21 -0
  39. package/dist/src/compiled/json-schema/index.d.ts +749 -0
  40. package/dist/src/compiled/json-schema/index.js +1 -0
  41. package/dist/src/compiler/manifest.js +1 -1
  42. package/dist/src/compiler/normalize-agent-config.js +1 -1
  43. package/dist/src/context/build-dynamic-tools.js +1 -1
  44. package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
  45. package/dist/src/context/keys.d.ts +1 -1
  46. package/dist/src/evals/assertions/collector.d.ts +19 -6
  47. package/dist/src/evals/assertions/collector.js +1 -1
  48. package/dist/src/evals/assertions/run.d.ts +24 -17
  49. package/dist/src/evals/assertions/run.js +2 -2
  50. package/dist/src/evals/assertions/scoped.d.ts +17 -0
  51. package/dist/src/evals/assertions/scoped.js +1 -0
  52. package/dist/src/evals/context.d.ts +1 -0
  53. package/dist/src/evals/context.js +1 -1
  54. package/dist/src/evals/control-flow.d.ts +9 -0
  55. package/dist/src/evals/control-flow.js +1 -0
  56. package/dist/src/evals/define-eval.d.ts +1 -1
  57. package/dist/src/evals/define-eval.js +1 -1
  58. package/dist/src/evals/expect/index.d.ts +5 -3
  59. package/dist/src/evals/expect/index.js +1 -1
  60. package/dist/src/evals/index.d.ts +2 -2
  61. package/dist/src/evals/match.d.ts +50 -13
  62. package/dist/src/evals/match.js +1 -1
  63. package/dist/src/evals/runner/artifacts.js +1 -1
  64. package/dist/src/evals/runner/derive-run-facts.js +1 -1
  65. package/dist/src/evals/runner/execute-eval.js +1 -1
  66. package/dist/src/evals/runner/execute-task.d.ts +1 -0
  67. package/dist/src/evals/runner/execute-task.js +1 -1
  68. package/dist/src/evals/runner/reporters/braintrust.js +1 -1
  69. package/dist/src/evals/runner/reporters/console.js +1 -1
  70. package/dist/src/evals/runner/reporters/junit.js +3 -2
  71. package/dist/src/evals/runner/run-evals.js +1 -1
  72. package/dist/src/evals/runner/verdict.d.ts +1 -0
  73. package/dist/src/evals/runner/verdict.js +1 -1
  74. package/dist/src/evals/session.d.ts +9 -5
  75. package/dist/src/evals/session.js +1 -1
  76. package/dist/src/evals/types.d.ts +69 -47
  77. package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
  78. package/dist/src/execution/dispatch-workflow-runtime-actions-step.d.ts +12 -0
  79. package/dist/src/execution/dispatch-workflow-runtime-actions-step.js +1 -0
  80. package/dist/src/execution/next-driver-action.d.ts +1 -1
  81. package/dist/src/execution/node-step.js +1 -1
  82. package/dist/src/execution/session.js +3 -3
  83. package/dist/src/execution/turn-workflow.js +1 -1
  84. package/dist/src/execution/workflow-entry.js +1 -1
  85. package/dist/src/execution/workflow-runtime.d.ts +2 -11
  86. package/dist/src/execution/workflow-runtime.js +1 -1
  87. package/dist/src/execution/workflow-steps.d.ts +1 -1
  88. package/dist/src/execution/workflow-steps.js +1 -1
  89. package/dist/src/harness/action-result-helpers.d.ts +2 -2
  90. package/dist/src/harness/emission.d.ts +13 -27
  91. package/dist/src/harness/emission.js +1 -1
  92. package/dist/src/harness/execute-tool.d.ts +2 -2
  93. package/dist/src/harness/input-extraction.js +1 -1
  94. package/dist/src/harness/step-hooks.d.ts +3 -3
  95. package/dist/src/harness/step-hooks.js +1 -1
  96. package/dist/src/harness/tool-loop.js +1 -1
  97. package/dist/src/harness/tools.d.ts +4 -6
  98. package/dist/src/harness/tools.js +1 -1
  99. package/dist/src/harness/types.d.ts +4 -10
  100. package/dist/src/harness/workflow-continuation-security.d.ts +4 -0
  101. package/dist/src/harness/workflow-continuation-security.js +1 -0
  102. package/dist/src/harness/workflow-interrupt-state.d.ts +14 -0
  103. package/dist/src/harness/workflow-interrupt-state.js +1 -0
  104. package/dist/src/harness/workflow-lifecycle.d.ts +13 -0
  105. package/dist/src/harness/workflow-lifecycle.js +1 -0
  106. package/dist/src/harness/workflow-runtime-action-state.d.ts +9 -0
  107. package/dist/src/harness/workflow-runtime-action-state.js +1 -0
  108. package/dist/src/harness/workflow-sandbox.d.ts +22 -0
  109. package/dist/src/harness/workflow-sandbox.js +2 -0
  110. package/dist/src/harness/workflow-tool-description.d.ts +2 -2
  111. package/dist/src/harness/workflow-tool-description.js +16 -4
  112. package/dist/src/internal/application/compiled-artifacts.js +1 -1
  113. package/dist/src/internal/application/package.d.ts +12 -0
  114. package/dist/src/internal/application/package.js +1 -1
  115. package/dist/src/internal/application/paths.d.ts +6 -0
  116. package/dist/src/internal/application/paths.js +1 -1
  117. package/dist/src/internal/authored-definition/connection.js +1 -1
  118. package/dist/src/internal/authored-definition/core.js +1 -1
  119. package/dist/src/internal/authored-definition/schema-backed.js +1 -1
  120. package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
  121. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  122. package/dist/src/internal/nitro/host/workflow-sandbox-runtime-plugin.d.ts +1 -0
  123. package/dist/src/internal/nitro/host/workflow-sandbox-runtime-plugin.js +1 -0
  124. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js +1 -1
  125. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
  126. package/dist/src/internal/workflow/configure-world.d.ts +6 -0
  127. package/dist/src/internal/workflow/configure-world.js +1 -1
  128. package/dist/src/internal/workflow/runtime.d.ts +1 -0
  129. package/dist/src/internal/workflow/world-compatibility.d.ts +32 -0
  130. package/dist/src/internal/workflow/world-compatibility.js +1 -0
  131. package/dist/src/protocol/message.d.ts +7 -5
  132. package/dist/src/public/channels/slack/attachments.js +1 -1
  133. package/dist/src/public/channels/slack/auth.d.ts +2 -0
  134. package/dist/src/public/channels/slack/auth.js +1 -1
  135. package/dist/src/public/channels/slack/defaults.js +2 -2
  136. package/dist/src/public/channels/slack/inbound.d.ts +4 -11
  137. package/dist/src/public/channels/slack/inbound.js +1 -2
  138. package/dist/src/public/channels/slack/model-context.d.ts +28 -0
  139. package/dist/src/public/channels/slack/model-context.js +3 -0
  140. package/dist/src/public/channels/slack/slackChannel.d.ts +8 -0
  141. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  142. package/dist/src/public/connections/index.d.ts +1 -1
  143. package/dist/src/public/definitions/agent.d.ts +1 -1
  144. package/dist/src/public/definitions/approval.d.ts +40 -0
  145. package/dist/src/public/definitions/approval.js +1 -0
  146. package/dist/src/public/definitions/connections/mcp.d.ts +11 -9
  147. package/dist/src/public/definitions/connections/mcp.js +1 -1
  148. package/dist/src/public/definitions/connections/openapi.d.ts +9 -7
  149. package/dist/src/public/definitions/connections/openapi.js +1 -1
  150. package/dist/src/public/definitions/tool.d.ts +7 -20
  151. package/dist/src/public/index.d.ts +1 -1
  152. package/dist/src/public/tools/approval/approval-helpers.d.ts +7 -7
  153. package/dist/src/public/tools/approval/approval-helpers.js +1 -1
  154. package/dist/src/public/tools/approval/index.d.ts +1 -1
  155. package/dist/src/public/tools/index.d.ts +2 -1
  156. package/dist/src/public/tools/internal.js +1 -1
  157. package/dist/src/runtime/actions/types.d.ts +10 -11
  158. package/dist/src/runtime/agent/bootstrap.d.ts +1 -0
  159. package/dist/src/runtime/agent/bootstrap.js +1 -1
  160. package/dist/src/runtime/agent/mock-model-adapter.js +2 -3
  161. package/dist/src/runtime/connections/mcp-client.d.ts +3 -3
  162. package/dist/src/runtime/connections/mcp-client.js +1 -1
  163. package/dist/src/runtime/connections/registry.d.ts +2 -2
  164. package/dist/src/runtime/connections/resolve-authorization.d.ts +11 -0
  165. package/dist/src/runtime/connections/resolve-authorization.js +1 -0
  166. package/dist/src/runtime/connections/types.d.ts +27 -11
  167. package/dist/src/runtime/framework-tools/connection-search-dynamic.js +1 -1
  168. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  169. package/dist/src/runtime/resolve-agent.js +1 -1
  170. package/dist/src/runtime/resolve-connection.js +1 -1
  171. package/dist/src/runtime/resolve-tool.d.ts +1 -1
  172. package/dist/src/runtime/resolve-tool.js +1 -1
  173. package/dist/src/runtime/types.d.ts +8 -7
  174. package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
  175. package/dist/src/setup/primitives/pm/pnpm.js +6 -5
  176. package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
  177. package/dist/src/setup/scaffold/create/project.js +2 -2
  178. package/dist/src/setup/scaffold/update/channels.js +1 -1
  179. package/dist/src/shared/agent-definition.d.ts +11 -13
  180. package/dist/src/shared/dynamic-tool-definition.d.ts +3 -3
  181. package/dist/src/shared/tool-definition.d.ts +1 -2
  182. package/dist/src/shared/workflow-sandbox.d.ts +37 -0
  183. package/dist/src/shared/workflow-sandbox.js +1 -0
  184. package/docs/agent-config.md +43 -13
  185. package/docs/channels/custom.mdx +2 -2
  186. package/docs/channels/slack.mdx +7 -13
  187. package/docs/concepts/execution-model-and-durability.md +1 -1
  188. package/docs/concepts/sessions-runs-and-streaming.md +1 -1
  189. package/docs/connections/mcp.mdx +2 -2
  190. package/docs/connections/openapi.mdx +37 -2
  191. package/docs/connections/overview.mdx +72 -2
  192. package/docs/evals/assertions.mdx +97 -39
  193. package/docs/evals/cases.mdx +24 -15
  194. package/docs/evals/judge.mdx +2 -2
  195. package/docs/evals/overview.mdx +7 -5
  196. package/docs/evals/reporters.mdx +2 -2
  197. package/docs/evals/running.mdx +3 -1
  198. package/docs/evals/targets.mdx +2 -2
  199. package/docs/guides/auth-and-route-protection.md +48 -1
  200. package/docs/guides/client/streaming.mdx +1 -1
  201. package/docs/guides/deployment.md +5 -4
  202. package/docs/guides/dynamic-workflows.md +1 -7
  203. package/docs/guides/frontend/overview.mdx +1 -1
  204. package/docs/guides/frontend/use-eve-agent-svelte.mdx +1 -1
  205. package/docs/guides/frontend/use-eve-agent-vue.mdx +1 -1
  206. package/docs/guides/session-context.md +2 -1
  207. package/docs/reference/typescript-api.md +2 -2
  208. package/docs/subagents.mdx +2 -2
  209. package/docs/tools/human-in-the-loop.md +43 -6
  210. package/docs/tools/overview.mdx +3 -3
  211. package/docs/tutorial/connect-a-warehouse.mdx +2 -0
  212. package/docs/tutorial/first-agent.mdx +1 -1
  213. package/docs/tutorial/guard-the-spend.mdx +4 -3
  214. package/docs/tutorial/ship-it.mdx +1 -1
  215. package/package.json +14 -11
  216. package/dist/src/compiled/@ai-sdk/anthropic/_provider-utils.d.ts +0 -15
  217. package/dist/src/compiled/@ai-sdk/google/_provider-utils.d.ts +0 -11
  218. package/dist/src/compiled/@ai-sdk/openai/_provider-utils.d.ts +0 -15
  219. package/dist/src/compiled/@ai-sdk/provider/_json-schema.d.ts +0 -5
  220. package/dist/src/execution/dispatch-code-mode-runtime-actions-step.d.ts +0 -21
  221. package/dist/src/execution/dispatch-code-mode-runtime-actions-step.js +0 -1
  222. package/dist/src/harness/code-mode-interrupt-state.d.ts +0 -26
  223. package/dist/src/harness/code-mode-interrupt-state.js +0 -1
  224. package/dist/src/harness/code-mode-lifecycle.d.ts +0 -16
  225. package/dist/src/harness/code-mode-lifecycle.js +0 -1
  226. package/dist/src/harness/code-mode-runtime-action-state.d.ts +0 -6
  227. package/dist/src/harness/code-mode-runtime-action-state.js +0 -1
  228. package/dist/src/harness/code-mode.d.ts +0 -26
  229. package/dist/src/harness/code-mode.js +0 -1
  230. package/dist/src/harness/sandbox-surface.d.ts +0 -68
  231. package/dist/src/harness/sandbox-surface.js +0 -1
  232. package/dist/src/internal/nitro/host/code-mode-runtime-dependency-plugin.d.ts +0 -1
  233. package/dist/src/internal/nitro/host/code-mode-runtime-dependency-plugin.js +0 -1
  234. package/dist/src/runtime/framework-tools/code-mode-connection-auth.d.ts +0 -29
  235. package/dist/src/runtime/framework-tools/code-mode-connection-auth.js +0 -1
  236. package/dist/src/shared/code-mode.d.ts +0 -29
  237. package/dist/src/shared/code-mode.js +0 -1
@@ -1 +1 @@
1
- import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{$ as n,I as r,J as i,K as a,S as o,U as s,W as c,_t as l,at as u,bt as d,dt as f,ft as p,ht as m,i as ee,it as h,k as te,lt as g,mt as ne,n as re,ot as _,pt as v,rt as ie,ut as y,vt as b,y as ae}from"../../_chunks/workflow/dist-C9PV_vnE.js";const oe={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 se;se||={};let x;x=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function ce(e){return(await x).getRandomValues(new Uint8Array(e))}async function le(e){let t=``;for(;t.length<e;){let n=await ce(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function ue(e){return await le(e)}async function de(e){let t=await(await x).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function fe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await ue(e);return{code_verifier:t,code_challenge:await de(t)}}var pe=`vercel.ai.error.AI_MCPClientError`,me=Symbol.for(pe),he,ge,S=class extends (ge=e,he=me,ge){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[he]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,pe)}},C=`2025-11-25`,_e=[C,`2025-06-18`,`2025-03-26`,`2024-11-05`],ve=v(ne(m(),b())),ye=y({name:m(),version:m(),title:v(m())}),w=y({_meta:v(p({}).loose())}),T=w,be=p({method:m(),params:v(w)}),xe=p({applyDefaults:v(_())}).loose(),Se=y({experimental:v(p({}).loose()),logging:v(p({}).loose()),prompts:v(y({listChanged:v(_())})),resources:v(y({subscribe:v(_()),listChanged:v(_())})),tools:v(y({listChanged:v(_())})),elicitation:v(xe)});p({elicitation:v(xe)}).loose();var Ce=T.extend({protocolVersion:m(),capabilities:Se,serverInfo:ye,instructions:v(m())}),E=T.extend({nextCursor:v(m())}),we=p({name:m(),title:v(m()),description:v(m()),inputSchema:p({type:g(`object`),properties:v(p({}).loose())}).loose(),outputSchema:v(p({}).loose()),annotations:v(p({title:v(m())}).loose()),_meta:ve}).loose(),Te=E.extend({tools:h(we)}),D=p({type:g(`text`),text:m()}).loose(),O=p({type:g(`image`),data:u(),mimeType:m()}).loose(),Ee=p({uri:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m()),size:v(f())}).loose(),De=E.extend({resources:h(Ee)}),k=p({uri:m(),name:v(m()),title:v(m()),mimeType:v(m())}).loose(),A=k.extend({text:m()}),j=k.extend({blob:u()}),M=p({type:g(`resource`),resource:l([A,j])}).loose(),Oe=p({type:g(`resource_link`),uri:m(),name:m(),description:v(m()),mimeType:v(m())}).loose(),ke=T.extend({content:h(l([D,O,M,Oe])),structuredContent:v(b()),isError:_().default(!1).optional()}).or(T.extend({toolResult:b()})),Ae=p({uriTemplate:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m())}).loose(),je=T.extend({resourceTemplates:h(Ae)}),Me=T.extend({contents:h(l([A,j]))}),Ne=p({name:m(),description:v(m()),required:v(_())}).loose(),Pe=p({name:m(),title:v(m()),description:v(m()),arguments:v(h(Ne))}).loose(),Fe=E.extend({prompts:h(Pe)}),Ie=p({role:l([g(`user`),g(`assistant`)]),content:l([D,O,M,Oe])}).loose(),Le=T.extend({description:v(m()),messages:h(Ie)}),Re=w.extend({message:m(),requestedSchema:b()}),N=be.extend({method:g(`elicitation/create`),params:Re}),ze=T.extend({action:l([g(`accept`),g(`decline`),g(`cancel`)]),content:v(ne(m(),b()))}),P=`2.0`,Be=p({jsonrpc:g(P),id:l([m(),f().int()])}).merge(be).strict(),Ve=p({jsonrpc:g(P),id:l([m(),f().int()]),result:T}).strict(),He=p({jsonrpc:g(P),id:l([m(),f().int()]),error:p({code:f().int(),message:m(),data:v(b())})}).strict(),F=l([Be,p({jsonrpc:g(P)}).merge(p({method:m(),params:v(w)})).strict(),Ve,He]);async function I(e){return F.parse(await r({text:e}))}var Ue=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,L=m().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:oe.custom,message:`URL must be parseable`,fatal:!0}),d}).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`}),We=p({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:f().optional(),scope:m().optional(),refresh_token:m().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Ge=p({resource:m().url(),authorization_servers:h(L).optional(),jwks_uri:m().url().optional(),scopes_supported:h(m()).optional(),bearer_methods_supported:h(m()).optional(),resource_signing_alg_values_supported:h(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:_().optional(),authorization_details_types_supported:h(m()).optional(),dpop_signing_alg_values_supported:h(m()).optional(),dpop_bound_access_tokens_required:_().optional()}).passthrough(),R=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),code_challenge_methods_supported:h(m()),token_endpoint_auth_methods_supported:h(m()).optional(),token_endpoint_auth_signing_alg_values_supported:h(m()).optional()}).passthrough(),Ke=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,userinfo_endpoint:L.optional(),jwks_uri:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),subject_types_supported:h(m()),id_token_signing_alg_values_supported:h(m()),claims_supported:h(m()).optional(),token_endpoint_auth_methods_supported:h(m()).optional()}).passthrough().merge(R.pick({code_challenge_methods_supported:!0})),qe=p({client_id:m(),client_secret:m().optional(),client_id_issued_at:f().optional(),client_secret_expires_at:f().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Je=p({redirect_uris:h(L),token_endpoint_auth_method:m().optional(),grant_types:h(m()).optional(),response_types:h(m()).optional(),client_name:m().optional(),client_uri:L.optional(),logo_uri:L.optional(),scope:m().optional(),contacts:h(m()).optional(),tos_uri:L.optional(),policy_uri:m().optional(),jwks_uri:L.optional(),jwks:ie().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),Ye=p({error:m(),error_description:m().optional(),error_uri:m().optional()}),Xe=Je.merge(qe),Ze=`vercel.ai.error.AI_MCPClientOAuthError`,Qe=Symbol.for(Ze),$e,et,z=class extends (et=e,$e=Qe,et){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[$e]=!0}static isInstance(t){return e.hasMarker(t,Ze)}},B=class extends z{};B.errorCode=`server_error`;var V=class extends z{};V.errorCode=`invalid_client`;var H=class extends z{};H.errorCode=`invalid_grant`;var U=class extends z{};U.errorCode=`unauthorized_client`;var tt={[B.errorCode]:B,[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U};function nt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function W(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function rt({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 G=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function K(e){return new URL(e).href}function it(e,t){return{authorizationServerUrl:K(e),tokenEndpoint:K(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function at(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ot(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function st(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:K(e.authorization_server),tokenEndpoint:K(e.token_endpoint)}}async function ct({provider:e,clientInformation:t,tokens:n}){let r=st(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:K(i.authorizationServerUrl),tokenEndpoint:K(i.tokenEndpoint)}:st(t)}async function lt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(ot(t,n)),!0):!1}function ut(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new z({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function dt({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new z({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function q(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 ft(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?J(e,void 0,n):void 0;throw r}}async function pt(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function mt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function ht(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??C,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=ft(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await pt(o,a,n);return!r?.metadataUrl&&mt(s,i.pathname)&&(s=await pt(new URL(`/.well-known/${t}`,i),a,n)),s}async function gt(e,t,n=fetch){let r=await ht(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 Ge.parse(await r.json())}function _t(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;return i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function vt(e,t){if(e.issuer!==t)throw new z({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function yt(e,{fetchFn:t=fetch,protocolVersion:n=C}={}){let r={"MCP-Protocol-Version":n},i=_t(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await J(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=R.parse(await i.json());return vt(e,a),e}else{let t=Ke.parse(await i.json());if(vt(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function bt(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 fe(),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`,W(o)),{authorizationUrl:l,codeVerifier:d}}function xt(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 St(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Ct(i,a,n);return;case`client_secret_post`:wt(i,a,r);return;case`none`:Tt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Ct(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 wt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Tt(e,t){t.set(`client_id`,e)}async function Y(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:i}=Ye.parse(await r({text:n}));return new(tt[e]||B)({message:t||``,cause:i})}catch(e){return new B({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Et(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):St(xt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,W(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await Y(p);return We.parse(await p.json())}async function Dt(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):St(xt(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,W(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await Y(d);return We.parse({refresh_token:r,...await d.json()})}async function Ot(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 Y(a);return Xe.parse(await a.json())}async function X(e,t){try{return await Z(e,t)}catch(n){if(n instanceof V||n instanceof U)return await e.invalidateCredentials?.call(e,`all`),await Z(e,t);if(n instanceof H)return await e.invalidateCredentials?.call(e,`tokens`),await Z(e,t);throw n}}async function kt(e,t,n){let r=nt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!rt({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 Z(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;ut(t,a);try{s=await gt(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await kt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await yt(c,{fetchFn:o}),d=it(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=ot(await Ot(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 ct({provider:e,clientInformation:f});if(!t)throw new z({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await Et(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await ct({provider:e,clientInformation:f,tokens:p});t?dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Dt(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof z)||e instanceof B))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:ee,codeVerifier:h}=await bt(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await lt({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new z({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(ee),`REDIRECT`}function At(e){return e===void 0||e===`message`}var jt=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 i(t,`ai-sdk/${Ue}`,o())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let r=async(i=!1)=>{var a,o,s,c;try{let c=await this.commonHeaders({Accept:`text/event-stream`}),l=await this.fetchFn(this.url.href,{headers:c,signal:this.abortController?.signal,redirect:this.redirectMode});if(l.status===401&&this.authProvider&&!i){this.resourceMetadataUrl=q(l);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;return(a=this.onerror)==null||a.call(this,e),t(e)}}catch(e){return(o=this.onerror)==null||o.call(this,e),t(e)}return r(!0)}if(!l.ok||!l.body){let e=`MCP SSE Transport Error: ${l.status} ${l.statusText}`;l.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new S({message:e});return(s=this.onerror)==null||s.call(this,n),t(n)}let u=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),d=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await u.read();if(t){if(this.connected)throw this.connected=!1,new S({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 S({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(At(s))try{let e=await I(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new S({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:()=>u.cancel()},d()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(c=this.onerror)==null||c.call(this,e),t(e)}};r()})}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 S({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=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;(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 S({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 Mt(e){return e===void 0||e===`message`}var Nt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){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.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.sessionId&&(t[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return i(t,`ai-sdk/${Ue}`,o())}authorizeOnce(e){return this.authProvider?(this.authPromise||=X(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 S({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({});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(r=!1)=>{var i,a,o,s,c,l;try{let l={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`,Accept:`application/json, text/event-stream`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},u=await this.fetchFn(this.url.href,l),d=u.headers.get(`mcp-session-id`);if(d&&(this.sessionId=d),u.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(u);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new G}catch(e){throw(i=this.onerror)==null||i.call(this,e),e}return t(!0)}if(u.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!u.ok){let e=await u.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${u.status}): ${e}`;u.status===404&&(t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new S({message:t,statusCode:u.status,url:this.url.href,responseBody:e??void 0});throw(a=this.onerror)==null||a.call(this,n),n}if(!(`id`in e))return;let f=u.headers.get(`content-type`)||``;if(f.includes(`application/json`)){let e=await u.json(),t=Array.isArray(e)?e.map(e=>F.parse(e)):[F.parse(e)];for(let e of t)(o=this.onmessage)==null||o.call(this,e);return}if(f.includes(`text/event-stream`)){if(!u.body){let e=new S({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:u.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,e),e}let e=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).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(Mt(a))try{let e=await I(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new S({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)}})();return}let p=new S({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`,statusCode:u.status,url:this.url.href});throw(c=this.onerror)==null||c.call(this,p),p}catch(e){throw(l=this.onerror)==null||l.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 S({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var r,i,a,o;try{let o=await this.commonHeaders({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}),c=s.headers.get(`mcp-session-id`);if(c&&(this.sessionId=c),s.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(s);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new G;(r=this.onerror)==null||r.call(this,e);return}}catch(e){(i=this.onerror)==null||i.call(this,e);return}return this.openInboundSse(!0,t)}if(s.status===405)return;if(!s.ok||!s.body){let e=new S({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(a=this.onerror)==null||a.call(this,e);return}let l=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),u=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await l.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),Mt(i))try{let t=await I(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new S({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:()=>l.cancel()},this.inboundReconnectAttempts=0,u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function Pt(e){switch(e.type){case`sse`:return new jt(e);case`http`:return new Nt(e);default:throw new S({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Ft(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var It=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,Lt=`ui/resourceUri`,Rt={extensions:{[It]:{mimeTypes:[Q]}}};function zt(e){let n=e?.ui;return t(n)?n:void 0}function Bt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Vt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function Ht(e){let t=zt(e._meta),n=t?.resourceUri??e._meta?.[Lt],r=Vt(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 Ut(e){let t=[],n=[];for(let r of e.tools){let e=Ht(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 Wt({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(ee(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:Bt(n._meta)}}async function Gt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Wt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Kt=`1.0.0`;function qt({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 $(e){let t=new Jt(e);return await t.init(),t}var Jt=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Kt,onUncaughtError:i,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},Ft(e)?this.transport=e:this.transport=Pt(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 S({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:`initialize`,params:{protocolVersion:C,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Ce});if(e===void 0)throw new S({message:`Server sent invalid initialize result`});if(!_e.includes(e.protocolVersion))throw new S({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions,await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new S({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new S({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new S({message:`Server does not support prompts`});break;default:throw new S({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new S({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=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new S({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new S({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:Te,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return 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:De,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:Fe,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:Le,options:n})}catch(e){throw 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(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=i??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let u=this,d=t===`automatic`?void 0:t[r]?.outputSchema,f=Ht({_meta:l}),p={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...f?.resourceUri==null?{}:{app:{...f,mimeType:Q}}},m=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await u.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||d==null?i:u.extractStructuredContent(i,d,r)};n[r]={...t===`automatic`?ae({description:o,title:e,metadata:p,inputSchema:te({...s,properties:s.properties??{},additionalProperties:!1}),execute:m,toModelOutput:qt}):a({description:o,title:e,metadata:p,inputSchema:t[r].inputSchema,...d==null?{}:{outputSchema:d},execute:m,toModelOutput:qt}),_meta:l}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await c({value:e.structuredContent,schema:re(t)});if(!r.success)throw new S({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 s({text:r.text,schema:t});if(!e.success)throw new S({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new S({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})}onElicitationRequest(e,t){if(e!==N)throw new S({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=N.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=ze.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 S({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 S({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new S({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{ze as ElicitResultSchema,N as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,G as UnauthorizedError,X as auth,$ as createMCPClient,$ as experimental_createMCPClient,Rt as mcpAppClientCapabilities,Gt as readMCPAppResource,Ut as splitMCPAppTools};
1
+ import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{$ as n,I as r,J as i,K as a,S as o,U as s,W as c,_t as l,at as u,bt as d,dt as f,ft as p,ht as m,i as ee,it as h,k as te,lt as g,mt as ne,n as re,ot as _,pt as v,rt as ie,ut as y,vt as b,y as ae}from"../../_chunks/workflow/dist-D7CzPkf8.js";const oe={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 se;se||={};let x;x=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function ce(e){return(await x).getRandomValues(new Uint8Array(e))}async function le(e){let t=``;for(;t.length<e;){let n=await ce(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function ue(e){return await le(e)}async function de(e){let t=await(await x).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function fe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await ue(e);return{code_verifier:t,code_challenge:await de(t)}}var pe=`vercel.ai.error.AI_MCPClientError`,me=Symbol.for(pe),he,ge,S=class extends (ge=e,he=me,ge){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[he]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,pe)}},C=`2025-11-25`,_e=[C,`2025-06-18`,`2025-03-26`,`2024-11-05`],ve=v(ne(m(),b())),ye=y({name:m(),version:m(),title:v(m())}),w=y({_meta:v(p({}).loose())}),T=w,be=p({method:m(),params:v(w)}),xe=p({applyDefaults:v(_())}).loose(),Se=y({experimental:v(p({}).loose()),logging:v(p({}).loose()),prompts:v(y({listChanged:v(_())})),resources:v(y({subscribe:v(_()),listChanged:v(_())})),tools:v(y({listChanged:v(_())})),elicitation:v(xe)});p({elicitation:v(xe)}).loose();var Ce=T.extend({protocolVersion:m(),capabilities:Se,serverInfo:ye,instructions:v(m())}),E=T.extend({nextCursor:v(m())}),we=p({name:m(),title:v(m()),description:v(m()),inputSchema:p({type:g(`object`),properties:v(p({}).loose())}).loose(),outputSchema:v(p({}).loose()),annotations:v(p({title:v(m())}).loose()),_meta:ve}).loose(),Te=E.extend({tools:h(we)}),D=p({type:g(`text`),text:m()}).loose(),O=p({type:g(`image`),data:u(),mimeType:m()}).loose(),Ee=p({uri:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m()),size:v(f())}).loose(),De=E.extend({resources:h(Ee)}),k=p({uri:m(),name:v(m()),title:v(m()),mimeType:v(m())}).loose(),A=k.extend({text:m()}),j=k.extend({blob:u()}),M=p({type:g(`resource`),resource:l([A,j])}).loose(),Oe=p({type:g(`resource_link`),uri:m(),name:m(),description:v(m()),mimeType:v(m())}).loose(),ke=T.extend({content:h(l([D,O,M,Oe])),structuredContent:v(b()),isError:_().default(!1).optional()}).or(T.extend({toolResult:b()})),Ae=p({uriTemplate:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m())}).loose(),je=T.extend({resourceTemplates:h(Ae)}),Me=T.extend({contents:h(l([A,j]))}),Ne=p({name:m(),description:v(m()),required:v(_())}).loose(),Pe=p({name:m(),title:v(m()),description:v(m()),arguments:v(h(Ne))}).loose(),Fe=E.extend({prompts:h(Pe)}),Ie=p({role:l([g(`user`),g(`assistant`)]),content:l([D,O,M,Oe])}).loose(),Le=T.extend({description:v(m()),messages:h(Ie)}),Re=w.extend({message:m(),requestedSchema:b()}),N=be.extend({method:g(`elicitation/create`),params:Re}),ze=T.extend({action:l([g(`accept`),g(`decline`),g(`cancel`)]),content:v(ne(m(),b()))}),P=`2.0`,Be=p({jsonrpc:g(P),id:l([m(),f().int()])}).merge(be).strict(),Ve=p({jsonrpc:g(P),id:l([m(),f().int()]),result:T}).strict(),He=p({jsonrpc:g(P),id:l([m(),f().int()]),error:p({code:f().int(),message:m(),data:v(b())})}).strict(),F=l([Be,p({jsonrpc:g(P)}).merge(p({method:m(),params:v(w)})).strict(),Ve,He]);async function I(e){return F.parse(await r({text:e}))}var Ue=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,L=m().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:oe.custom,message:`URL must be parseable`,fatal:!0}),d}).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`}),We=p({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:f().optional(),scope:m().optional(),refresh_token:m().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Ge=p({resource:m().url(),authorization_servers:h(L).optional(),jwks_uri:m().url().optional(),scopes_supported:h(m()).optional(),bearer_methods_supported:h(m()).optional(),resource_signing_alg_values_supported:h(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:_().optional(),authorization_details_types_supported:h(m()).optional(),dpop_signing_alg_values_supported:h(m()).optional(),dpop_bound_access_tokens_required:_().optional()}).passthrough(),R=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),code_challenge_methods_supported:h(m()),token_endpoint_auth_methods_supported:h(m()).optional(),token_endpoint_auth_signing_alg_values_supported:h(m()).optional()}).passthrough(),Ke=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,userinfo_endpoint:L.optional(),jwks_uri:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),subject_types_supported:h(m()),id_token_signing_alg_values_supported:h(m()),claims_supported:h(m()).optional(),token_endpoint_auth_methods_supported:h(m()).optional()}).passthrough().merge(R.pick({code_challenge_methods_supported:!0})),qe=p({client_id:m(),client_secret:m().optional(),client_id_issued_at:f().optional(),client_secret_expires_at:f().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Je=p({redirect_uris:h(L),token_endpoint_auth_method:m().optional(),grant_types:h(m()).optional(),response_types:h(m()).optional(),client_name:m().optional(),client_uri:L.optional(),logo_uri:L.optional(),scope:m().optional(),contacts:h(m()).optional(),tos_uri:L.optional(),policy_uri:m().optional(),jwks_uri:L.optional(),jwks:ie().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),Ye=p({error:m(),error_description:m().optional(),error_uri:m().optional()}),Xe=Je.merge(qe),Ze=`vercel.ai.error.AI_MCPClientOAuthError`,Qe=Symbol.for(Ze),$e,et,z=class extends (et=e,$e=Qe,et){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[$e]=!0}static isInstance(t){return e.hasMarker(t,Ze)}},B=class extends z{};B.errorCode=`server_error`;var V=class extends z{};V.errorCode=`invalid_client`;var H=class extends z{};H.errorCode=`invalid_grant`;var U=class extends z{};U.errorCode=`unauthorized_client`;var tt={[B.errorCode]:B,[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U};function nt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function W(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function rt({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 G=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function K(e){return new URL(e).href}function it(e,t){return{authorizationServerUrl:K(e),tokenEndpoint:K(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function at(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ot(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function st(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:K(e.authorization_server),tokenEndpoint:K(e.token_endpoint)}}async function ct({provider:e,clientInformation:t,tokens:n}){let r=st(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:K(i.authorizationServerUrl),tokenEndpoint:K(i.tokenEndpoint)}:st(t)}async function lt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(ot(t,n)),!0):!1}function ut(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new z({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function dt({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new z({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function q(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 ft(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?J(e,void 0,n):void 0;throw r}}async function pt(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function mt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function ht(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??C,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=ft(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await pt(o,a,n);return!r?.metadataUrl&&mt(s,i.pathname)&&(s=await pt(new URL(`/.well-known/${t}`,i),a,n)),s}async function gt(e,t,n=fetch){let r=await ht(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 Ge.parse(await r.json())}function _t(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;return i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function vt(e,t){if(e.issuer!==t)throw new z({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function yt(e,{fetchFn:t=fetch,protocolVersion:n=C}={}){let r={"MCP-Protocol-Version":n},i=_t(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await J(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=R.parse(await i.json());return vt(e,a),e}else{let t=Ke.parse(await i.json());if(vt(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function bt(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 fe(),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`,W(o)),{authorizationUrl:l,codeVerifier:d}}function xt(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 St(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Ct(i,a,n);return;case`client_secret_post`:wt(i,a,r);return;case`none`:Tt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Ct(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 wt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Tt(e,t){t.set(`client_id`,e)}async function Y(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:i}=Ye.parse(await r({text:n}));return new(tt[e]||B)({message:t||``,cause:i})}catch(e){return new B({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Et(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):St(xt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,W(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await Y(p);return We.parse(await p.json())}async function Dt(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):St(xt(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,W(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await Y(d);return We.parse({refresh_token:r,...await d.json()})}async function Ot(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 Y(a);return Xe.parse(await a.json())}async function X(e,t){try{return await Z(e,t)}catch(n){if(n instanceof V||n instanceof U)return await e.invalidateCredentials?.call(e,`all`),await Z(e,t);if(n instanceof H)return await e.invalidateCredentials?.call(e,`tokens`),await Z(e,t);throw n}}async function kt(e,t,n){let r=nt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!rt({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 Z(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;ut(t,a);try{s=await gt(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await kt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await yt(c,{fetchFn:o}),d=it(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=ot(await Ot(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 ct({provider:e,clientInformation:f});if(!t)throw new z({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await Et(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await ct({provider:e,clientInformation:f,tokens:p});t?dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Dt(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof z)||e instanceof B))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:ee,codeVerifier:h}=await bt(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await lt({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new z({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(ee),`REDIRECT`}function At(e){return e===void 0||e===`message`}var jt=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 i(t,`ai-sdk/${Ue}`,o())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let r=async(i=!1)=>{var a,o,s,c;try{let c=await this.commonHeaders({Accept:`text/event-stream`}),l=await this.fetchFn(this.url.href,{headers:c,signal:this.abortController?.signal,redirect:this.redirectMode});if(l.status===401&&this.authProvider&&!i){this.resourceMetadataUrl=q(l);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;return(a=this.onerror)==null||a.call(this,e),t(e)}}catch(e){return(o=this.onerror)==null||o.call(this,e),t(e)}return r(!0)}if(!l.ok||!l.body){let e=`MCP SSE Transport Error: ${l.status} ${l.statusText}`;l.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new S({message:e});return(s=this.onerror)==null||s.call(this,n),t(n)}let u=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),d=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await u.read();if(t){if(this.connected)throw this.connected=!1,new S({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 S({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(At(s))try{let e=await I(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new S({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:()=>u.cancel()},d()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(c=this.onerror)==null||c.call(this,e),t(e)}};r()})}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 S({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=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;(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 S({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 Mt(e){return e===void 0||e===`message`}var Nt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){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.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.sessionId&&(t[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return i(t,`ai-sdk/${Ue}`,o())}authorizeOnce(e){return this.authProvider?(this.authPromise||=X(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 S({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({});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(r=!1)=>{var i,a,o,s,c,l;try{let l={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`,Accept:`application/json, text/event-stream`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},u=await this.fetchFn(this.url.href,l),d=u.headers.get(`mcp-session-id`);if(d&&(this.sessionId=d),u.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(u);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new G}catch(e){throw(i=this.onerror)==null||i.call(this,e),e}return t(!0)}if(u.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!u.ok){let e=await u.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${u.status}): ${e}`;u.status===404&&(t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new S({message:t,statusCode:u.status,url:this.url.href,responseBody:e??void 0});throw(a=this.onerror)==null||a.call(this,n),n}if(!(`id`in e))return;let f=u.headers.get(`content-type`)||``;if(f.includes(`application/json`)){let e=await u.json(),t=Array.isArray(e)?e.map(e=>F.parse(e)):[F.parse(e)];for(let e of t)(o=this.onmessage)==null||o.call(this,e);return}if(f.includes(`text/event-stream`)){if(!u.body){let e=new S({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:u.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,e),e}let e=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).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(Mt(a))try{let e=await I(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new S({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)}})();return}let p=new S({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`,statusCode:u.status,url:this.url.href});throw(c=this.onerror)==null||c.call(this,p),p}catch(e){throw(l=this.onerror)==null||l.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 S({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var r,i,a,o;try{let o=await this.commonHeaders({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}),c=s.headers.get(`mcp-session-id`);if(c&&(this.sessionId=c),s.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(s);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new G;(r=this.onerror)==null||r.call(this,e);return}}catch(e){(i=this.onerror)==null||i.call(this,e);return}return this.openInboundSse(!0,t)}if(s.status===405)return;if(!s.ok||!s.body){let e=new S({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(a=this.onerror)==null||a.call(this,e);return}let l=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),u=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await l.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),Mt(i))try{let t=await I(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new S({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:()=>l.cancel()},this.inboundReconnectAttempts=0,u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function Pt(e){switch(e.type){case`sse`:return new jt(e);case`http`:return new Nt(e);default:throw new S({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Ft(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var It=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,Lt=`ui/resourceUri`,Rt={extensions:{[It]:{mimeTypes:[Q]}}};function zt(e){let n=e?.ui;return t(n)?n:void 0}function Bt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Vt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function Ht(e){let t=zt(e._meta),n=t?.resourceUri??e._meta?.[Lt],r=Vt(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 Ut(e){let t=[],n=[];for(let r of e.tools){let e=Ht(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 Wt({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(ee(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:Bt(n._meta)}}async function Gt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Wt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Kt=`1.0.0`;function qt({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 $(e){let t=new Jt(e);return await t.init(),t}var Jt=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Kt,onUncaughtError:i,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},Ft(e)?this.transport=e:this.transport=Pt(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 S({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:`initialize`,params:{protocolVersion:C,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Ce});if(e===void 0)throw new S({message:`Server sent invalid initialize result`});if(!_e.includes(e.protocolVersion))throw new S({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions,await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new S({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new S({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new S({message:`Server does not support prompts`});break;default:throw new S({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new S({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=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new S({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new S({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:Te,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return 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:De,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:Fe,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:Le,options:n})}catch(e){throw 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(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=i??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let u=this,d=t===`automatic`?void 0:t[r]?.outputSchema,f=Ht({_meta:l}),p={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...f?.resourceUri==null?{}:{app:{...f,mimeType:Q}}},m=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await u.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||d==null?i:u.extractStructuredContent(i,d,r)};n[r]={...t===`automatic`?ae({description:o,title:e,metadata:p,inputSchema:te({...s,properties:s.properties??{},additionalProperties:!1}),execute:m,toModelOutput:qt}):a({description:o,title:e,metadata:p,inputSchema:t[r].inputSchema,...d==null?{}:{outputSchema:d},execute:m,toModelOutput:qt}),_meta:l}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await c({value:e.structuredContent,schema:re(t)});if(!r.success)throw new S({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 s({text:r.text,schema:t});if(!e.success)throw new S({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new S({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})}onElicitationRequest(e,t){if(e!==N)throw new S({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=N.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=ze.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 S({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 S({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new S({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{ze as ElicitResultSchema,N as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,G as UnauthorizedError,X as auth,$ as createMCPClient,$ as experimental_createMCPClient,Rt as mcpAppClientCapabilities,Gt as readMCPAppResource,Ut as splitMCPAppTools};
@@ -1,7 +1,7 @@
1
1
  import * as _ai_sdk_provider from '#compiled/@ai-sdk/provider/index.js';
2
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';
3
- import * as _ai_sdk_provider_utils from './_provider-utils.js';
4
- import { InferSchema, FetchFunction } from './_provider-utils.js';
3
+ import * as _ai_sdk_provider_utils from '#compiled/@ai-sdk/provider-utils/index.js';
4
+ import { InferSchema, FetchFunction } from '#compiled/@ai-sdk/provider-utils/index.js';
5
5
 
6
6
  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' | (string & {});
7
7
  declare const openaiLanguageModelChatOptions: _ai_sdk_provider_utils.LazySchema<{
@@ -244,9 +244,12 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
244
244
  output_tokens: number;
245
245
  input_tokens_details?: {
246
246
  cached_tokens?: number | null | undefined;
247
+ orchestration_input_tokens?: number | null | undefined;
248
+ orchestration_input_cached_tokens?: number | null | undefined;
247
249
  } | null | undefined;
248
250
  output_tokens_details?: {
249
251
  reasoning_tokens?: number | null | undefined;
252
+ orchestration_output_tokens?: number | null | undefined;
250
253
  } | null | undefined;
251
254
  };
252
255
  incomplete_details?: {
@@ -270,9 +273,12 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
270
273
  output_tokens: number;
271
274
  input_tokens_details?: {
272
275
  cached_tokens?: number | null | undefined;
276
+ orchestration_input_tokens?: number | null | undefined;
277
+ orchestration_input_cached_tokens?: number | null | undefined;
273
278
  } | null | undefined;
274
279
  output_tokens_details?: {
275
280
  reasoning_tokens?: number | null | undefined;
281
+ orchestration_output_tokens?: number | null | undefined;
276
282
  } | null | undefined;
277
283
  } | null | undefined;
278
284
  service_tier?: string | null | undefined;