eve 0.54.2 → 0.54.4

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 (146) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/src/cli/commands/init-agent-workspace.js +1 -1
  3. package/dist/src/cli/commands/init-project.d.ts +46 -0
  4. package/dist/src/cli/commands/init-project.js +1 -0
  5. package/dist/src/cli/commands/init-self-modification.d.ts +7 -0
  6. package/dist/src/cli/commands/init-self-modification.js +1 -0
  7. package/dist/src/cli/commands/init-target.js +2 -2
  8. package/dist/src/cli/commands/init-telemetry.d.ts +6 -0
  9. package/dist/src/cli/commands/init-telemetry.js +1 -0
  10. package/dist/src/cli/commands/init.d.ts +3 -0
  11. package/dist/src/cli/commands/init.js +1 -1
  12. package/dist/src/cli/dev/tui/setup-commands.js +1 -1
  13. package/dist/src/cli/telemetry/index.d.ts +1 -1
  14. package/dist/src/compiled/.vendor-stamp.json +8 -6
  15. package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
  16. package/dist/src/compiled/@ai-sdk/google/index.js +7 -7
  17. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  18. package/dist/src/compiled/@ai-sdk/openai/index.js +4 -4
  19. package/dist/src/compiled/@opentelemetry/api/index.d.ts +2 -0
  20. package/dist/src/compiled/@workflow/core/events-consumer.d.ts +26 -0
  21. package/dist/src/compiled/@workflow/core/flushable-stream.d.ts +41 -0
  22. package/dist/src/compiled/@workflow/core/index.js +2 -2
  23. package/dist/src/compiled/@workflow/core/replay-divergence.d.ts +25 -0
  24. package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +75 -1
  25. package/dist/src/compiled/@workflow/core/runtime/quickjs-entrypoint.d.ts +30 -8
  26. package/dist/src/compiled/@workflow/core/runtime/quickjs-log-view.d.ts +129 -0
  27. package/dist/src/compiled/@workflow/core/runtime/step-executor.d.ts +2 -21
  28. package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +0 -22
  29. package/dist/src/compiled/@workflow/core/runtime.js +3 -3
  30. package/dist/src/compiled/@workflow/core/serialization.d.ts +2 -2
  31. package/dist/src/compiled/@workflow/core/step/context-storage.d.ts +2 -0
  32. package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +36 -0
  33. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  34. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  35. package/dist/src/compiled/@workflow/world/analytics.d.ts +23 -23
  36. package/dist/src/compiled/@workflow/world/events.d.ts +4 -2
  37. package/dist/src/compiled/@workflow/world/queue.d.ts +84 -0
  38. package/dist/src/compiled/@workflow/world-local/index.js +5 -5
  39. package/dist/src/compiled/@workflow/world-vercel/index.js +18 -13
  40. package/dist/src/compiled/_chunks/workflow/attribute-changes-BAcgmlXp.js +20 -0
  41. package/dist/src/compiled/_chunks/workflow/coerce-ro2dOxbr.js +1 -0
  42. package/dist/src/compiled/_chunks/workflow/dist-KPieTJHT.js +25 -0
  43. package/dist/src/compiled/_chunks/workflow/dist-PLkAQ-U7.js +2 -0
  44. package/dist/src/compiled/_chunks/workflow/frames-BvATzM2t.js +3 -0
  45. package/dist/src/compiled/_chunks/workflow/{functions-C02-JHBK.js → functions-wMCGZAVk.js} +1 -1
  46. package/dist/src/compiled/_chunks/workflow/resume-hook-BEHe0Uut.js +1 -0
  47. package/dist/src/compiled/_chunks/workflow/run-ChHLjaCt.js +1 -0
  48. package/dist/src/compiled/_chunks/workflow/schemas-DR7NTzNe.js +50 -0
  49. package/dist/src/compiled/_chunks/workflow/sleep-BB2HuVie.js +1 -0
  50. package/dist/src/compiled/_chunks/workflow/{wrapper-BxECO5nh.js → wrapper-CKui_eTd.js} +2 -2
  51. package/dist/src/compiled/_chunks/workflow/ws-transport-CVezyWwZ.js +1 -0
  52. package/dist/src/compiled/just-secrets/LICENSE +21 -0
  53. package/dist/src/compiled/just-secrets/index.d.ts +20 -0
  54. package/dist/src/compiled/just-secrets/index.js +2 -0
  55. package/dist/src/compiled/just-secrets/windows.ps1 +138 -0
  56. package/dist/src/compiler/extension-compatibility.d.ts +12 -12
  57. package/dist/src/compiler/extension-compatibility.js +1 -1
  58. package/dist/src/compiler/normalize-manifest-helpers.d.ts +2 -1
  59. package/dist/src/compiler/normalize-manifest-helpers.js +1 -1
  60. package/dist/src/compiler/normalize-manifest.js +1 -1
  61. package/dist/src/compiler/resolve-workspace-subagent.d.ts +13 -0
  62. package/dist/src/compiler/resolve-workspace-subagent.js +1 -0
  63. package/dist/src/context/dynamic-model-lifecycle.d.ts +0 -6
  64. package/dist/src/context/dynamic-model-lifecycle.js +1 -1
  65. package/dist/src/context/dynamic-resolve-context.js +1 -1
  66. package/dist/src/context/effective-model.d.ts +5 -0
  67. package/dist/src/context/effective-model.js +1 -0
  68. package/dist/src/context/keys.d.ts +2 -0
  69. package/dist/src/context/keys.js +1 -1
  70. package/dist/src/dynamic/definition.d.ts +4 -0
  71. package/dist/src/eve-channel/index.js +1 -1
  72. package/dist/src/eve-channel/types.d.ts +9 -7
  73. package/dist/src/execution/durable-session-migrations/snapshot.d.ts +0 -16
  74. package/dist/src/execution/durable-session-migrations/snapshot.js +1 -1
  75. package/dist/src/execution/eve-workflow-attributes.d.ts +1 -1
  76. package/dist/src/execution/run-session-limits.js +1 -1
  77. package/dist/src/execution/session.js +1 -1
  78. package/dist/src/execution/tools/sleep-workflow.js +1 -1
  79. package/dist/src/execution/workflow-steps.js +1 -1
  80. package/dist/src/harness/compaction.js +1 -1
  81. package/dist/src/harness/messages.d.ts +1 -1
  82. package/dist/src/harness/messages.js +1 -1
  83. package/dist/src/harness/step-hooks.d.ts +16 -10
  84. package/dist/src/harness/step-hooks.js +1 -1
  85. package/dist/src/harness/tool-loop.js +2 -2
  86. package/dist/src/instrumentation/parent-lineage.js +1 -1
  87. package/dist/src/internal/application/package.js +1 -1
  88. package/dist/src/internal/nitro/routes/index.d.ts +6 -0
  89. package/dist/src/internal/nitro/routes/index.js +7 -7
  90. package/dist/src/internal/vercel/assemble-eve-services.js +1 -1
  91. package/dist/src/internal/vercel/build-agent-workspace.js +1 -1
  92. package/dist/src/internal/vercel/build-multi-agent-landing-page.d.ts +3 -0
  93. package/dist/src/internal/vercel/build-multi-agent-landing-page.js +1 -0
  94. package/dist/src/internal/vercel/eve-service-contribution.d.ts +4 -0
  95. package/dist/src/internal/vercel/eve-service-contribution.js +1 -1
  96. package/dist/src/internal/vercel/vercel-services-config.js +1 -1
  97. package/dist/src/protocol/baggage.d.ts +6 -0
  98. package/dist/src/protocol/baggage.js +1 -1
  99. package/dist/src/protocol/traceparent.d.ts +13 -0
  100. package/dist/src/protocol/traceparent.js +1 -1
  101. package/dist/src/public/definitions/workspace-agent.d.ts +25 -0
  102. package/dist/src/public/definitions/workspace-agent.js +1 -0
  103. package/dist/src/public/index.d.ts +1 -0
  104. package/dist/src/public/index.js +1 -1
  105. package/dist/src/public/models/openai/chatgpt/codex-app-server.d.ts +41 -0
  106. package/dist/src/public/models/openai/chatgpt/codex-app-server.js +1 -0
  107. package/dist/src/public/models/openai/chatgpt/credential-store.d.ts +26 -4
  108. package/dist/src/public/models/openai/chatgpt/credential-store.js +1 -1
  109. package/dist/src/public/models/openai/chatgpt/oauth.d.ts +6 -4
  110. package/dist/src/public/models/openai/chatgpt/token-broker.d.ts +7 -7
  111. package/dist/src/public/models/openai/chatgpt/token-broker.js +1 -1
  112. package/dist/src/public/models/openai/chatgpt/token.d.ts +13 -0
  113. package/dist/src/public/models/openai/chatgpt/token.js +1 -0
  114. package/dist/src/public/models/openai/chatgpt/transport.d.ts +2 -1
  115. package/dist/src/public/models/openai/index.d.ts +3 -2
  116. package/dist/src/public/vercel/index.d.ts +50 -0
  117. package/dist/src/public/vercel/index.js +1 -0
  118. package/dist/src/self-modification/setup.js +7 -2
  119. package/dist/src/setup/flows/chatgpt-auth.d.ts +2 -1
  120. package/dist/src/setup/flows/chatgpt-auth.js +1 -1
  121. package/dist/src/setup/flows/model.d.ts +0 -2
  122. package/dist/src/setup/flows/model.js +1 -1
  123. package/dist/src/setup/scaffold/create/project.js +1 -1
  124. package/dist/src/subagents/remote-dispatch.d.ts +3 -1
  125. package/dist/src/subagents/remote-dispatch.js +1 -1
  126. package/dist/src/tracing/agent-otel-attributes.js +1 -1
  127. package/dist/src/tracing/agent-otel-runtime-context.js +1 -1
  128. package/docs/agent-config.md +3 -3
  129. package/docs/guides/deployment/vercel.mdx +52 -1
  130. package/docs/guides/dynamic-capabilities.md +19 -7
  131. package/docs/guides/instrumentation-providers.md +1 -1
  132. package/docs/guides/instrumentation.md +25 -6
  133. package/docs/guides/remote-agents.md +5 -5
  134. package/docs/reference/cli.md +2 -2
  135. package/docs/reference/telemetry.md +1 -1
  136. package/docs/reference/typescript-api.md +14 -7
  137. package/docs/subagents/index.mdx +31 -0
  138. package/package.json +13 -6
  139. package/dist/src/compiled/_chunks/workflow/attribute-changes-C6H-fRVP.js +0 -20
  140. package/dist/src/compiled/_chunks/workflow/dist-DDeH-1ER.js +0 -40
  141. package/dist/src/compiled/_chunks/workflow/dist-DhncQSl7.js +0 -74
  142. package/dist/src/compiled/_chunks/workflow/frames-DsEqSDes.js +0 -3
  143. package/dist/src/compiled/_chunks/workflow/resume-hook-BRDLAb67.js +0 -1
  144. package/dist/src/compiled/_chunks/workflow/run-BM2OFphk.js +0 -1
  145. package/dist/src/compiled/_chunks/workflow/sleep-6cG0F99-.js +0 -1
  146. package/dist/src/compiled/_chunks/workflow/ws-transport-DuK82LLz.js +0 -1
@@ -1 +1 @@
1
- import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{B as n,Bt as r,Ct as i,Et as a,Ft as o,It as s,Lt as c,Mt as l,Nt as u,O as d,Pt as f,R as p,Rt as m,Tt as h,Ut as g,Vt as _,Y as v,at as ee,d as te,gt as ne,it as re,j as ie,jt as y,kt as ae,ot as oe,pt as se,r as ce,s as le,ut as ue,wt as b,yt as x}from"../../_chunks/workflow/dist-DhncQSl7.js";const de={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var fe;fe||={};let S;S=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function pe(e){return(await S).getRandomValues(new Uint8Array(e))}async function me(e){let t=``;for(;t.length<e;){let n=await pe(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function he(e){return await me(e)}async function ge(e){let t=await(await S).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function _e(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await he(e);return{code_verifier:t,code_challenge:await ge(t)}}var C=`2026-07-28`,w=`2025-11-25`,ve=[C,w,`2025-06-18`,`2025-03-26`,`2024-11-05`],ye=s(c(m(),_())),be=l({name:m(),version:m(),title:s(m())}),T=l({_meta:s(o({}).loose())}),E=T.extend({resultType:s(m())}),xe=o({method:m(),params:s(T)}),Se=o({applyDefaults:s(a())}).loose(),Ce=l({experimental:s(o({}).loose()),logging:s(o({}).loose()),completions:s(o({}).loose()),prompts:s(l({listChanged:s(a())})),resources:s(l({subscribe:s(a()),listChanged:s(a())})),tools:s(l({listChanged:s(a())})),elicitation:s(Se)});o({elicitation:s(Se)}).loose();var we=E.extend({supportedVersions:b(m()),capabilities:Ce,instructions:s(m()),ttlMs:s(f()),cacheScope:s(r([y(`public`),y(`private`)]))}),Te=E.extend({protocolVersion:m(),capabilities:Ce,serverInfo:be,instructions:s(m())}),D=E.extend({nextCursor:s(m())}),Ee=o({name:m(),title:s(m()),description:s(m()),inputSchema:l({type:s(_()),properties:s(o({}).loose())}),outputSchema:s(o({}).loose()),annotations:s(o({title:s(m()),readOnlyHint:s(a()),destructiveHint:s(a()),idempotentHint:s(a()),openWorldHint:s(a())}).loose()),_meta:ye}).loose(),De=D.extend({tools:b(Ee)}),Oe=o({type:y(`text`),text:m()}).loose(),ke=o({type:y(`image`),data:h(),mimeType:m()}).loose(),Ae=o({uri:m(),name:m(),title:s(m()),description:s(m()),mimeType:s(m()),size:s(f())}).loose(),je=D.extend({resources:b(Ae)}),Me=o({uri:m(),name:s(m()),title:s(m()),mimeType:s(m())}).loose(),Ne=Me.extend({text:m()}),Pe=Me.extend({blob:h()}),Fe=o({type:y(`resource`),resource:r([Ne,Pe])}).loose(),Ie=o({type:y(`resource_link`),uri:m(),name:m(),description:s(m()),mimeType:s(m())}).loose(),Le=o({type:m()}).loose().refine(e=>![`text`,`image`,`resource`,`resource_link`].includes(e.type),{message:`Known content types must match their schema`}),Re=E.extend({content:b(r([Oe,ke,Fe,Ie,Le])),structuredContent:s(_()),isError:a().default(!1).optional()}),ze=E.extend({content:u().optional(),structuredContent:ae(),isError:a().default(!1).optional()}).transform(e=>({...e,content:[{type:`text`,text:JSON.stringify(e.structuredContent)}]})).pipe(Re),Be=Re.or(ze).or(E.extend({toolResult:_().nonoptional()})),Ve=o({uriTemplate:m(),name:m(),title:s(m()),description:s(m()),mimeType:s(m())}).loose(),He=E.extend({resourceTemplates:b(Ve)}),Ue=E.extend({contents:b(r([Ne,Pe]))}),We=o({type:y(`ref/prompt`),name:m()}).loose(),Ge=o({type:y(`ref/resource`),uri:m()}).loose(),Ke=o({name:m(),value:m()}).loose();T.extend({ref:r([We,Ge]),argument:Ke,context:s(o({arguments:c(m(),m())}).loose())});var qe=E.extend({completion:o({values:b(m()).max(100),total:s(f().int()),hasMore:s(a())}).loose()}),Je=o({name:m(),description:s(m()),required:s(a())}).loose(),Ye=o({name:m(),title:s(m()),description:s(m()),arguments:s(b(Je))}).loose(),Xe=D.extend({prompts:b(Ye)}),Ze=o({role:r([y(`user`),y(`assistant`)]),content:r([Oe,ke,Fe,Ie])}).loose(),Qe=E.extend({description:s(m()),messages:b(Ze)}),$e=T.extend({message:m(),requestedSchema:_()}),O=xe.extend({method:y(`elicitation/create`),params:$e}),et=E.extend({action:r([y(`accept`),y(`decline`),y(`cancel`)]),content:s(c(m(),_()))}),k=`2.0`,tt=o({jsonrpc:y(k),id:r([m(),f().int()])}).merge(xe).strict(),nt=o({jsonrpc:y(k),id:r([m(),f().int()]),result:E}).strict(),rt=o({jsonrpc:y(k),id:s(r([m(),f().int()])),error:o({code:f().int(),message:m(),data:s(_())})}).strict(),it=o({jsonrpc:y(k)}).merge(o({method:m(),params:s(T)})).strict(),at=r([tt,it,nt,rt]);function A(e){return at.parse(e)}async function j(e){return A(await v({text:e}))}var ot=`vercel.ai.error.AI_MCPClientError`,st=Symbol.for(ot),ct,lt,M=class extends (lt=e,ct=st,lt){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[ct]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,ot)}},ut=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,N=m().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:de.custom,message:`URL must be parseable`,fatal:!0}),g}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),dt=o({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:f().optional(),scope:m().optional(),refresh_token:m().optional(),issuer:N.optional(),authorization_server:N.optional(),token_endpoint:N.optional()}).strip(),ft=l({resource:m().url(),authorization_servers:b(N).optional(),jwks_uri:m().url().optional(),scopes_supported:b(m()).optional(),bearer_methods_supported:b(m()).optional(),resource_signing_alg_values_supported:b(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:a().optional(),authorization_details_types_supported:b(m()).optional(),dpop_signing_alg_values_supported:b(m()).optional(),dpop_bound_access_tokens_required:a().optional()}),pt=l({issuer:m(),authorization_endpoint:N,token_endpoint:N,registration_endpoint:N.optional(),authorization_response_iss_parameter_supported:a().optional(),client_id_metadata_document_supported:a().optional(),scopes_supported:b(m()).optional(),response_types_supported:b(m()),grant_types_supported:b(m()).optional(),code_challenge_methods_supported:b(m()).optional(),token_endpoint_auth_methods_supported:b(m()).optional(),token_endpoint_auth_signing_alg_values_supported:b(m()).optional()}),mt=l({issuer:m(),authorization_endpoint:N,token_endpoint:N,userinfo_endpoint:N.optional(),jwks_uri:N,registration_endpoint:N.optional(),authorization_response_iss_parameter_supported:a().optional(),client_id_metadata_document_supported:a().optional(),scopes_supported:b(m()).optional(),response_types_supported:b(m()),grant_types_supported:b(m()).optional(),subject_types_supported:b(m()),id_token_signing_alg_values_supported:b(m()),claims_supported:b(m()).optional(),token_endpoint_auth_methods_supported:b(m()).optional()}).merge(pt.pick({code_challenge_methods_supported:!0})),ht=o({client_id:m(),client_secret:m().optional(),client_id_issued_at:f().optional(),client_secret_expires_at:f().optional(),issuer:N.optional(),authorization_server:N.optional(),token_endpoint:N.optional()}).strip(),gt=o({redirect_uris:b(N),application_type:r([y(`native`),y(`web`)]).optional(),token_endpoint_auth_method:m().optional(),grant_types:b(m()).optional(),response_types:b(m()).optional(),client_name:m().optional(),client_uri:N.optional(),logo_uri:N.optional(),scope:m().optional(),contacts:b(m()).optional(),tos_uri:N.optional(),policy_uri:m().optional(),jwks_uri:N.optional(),jwks:i().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),_t=o({error:m(),error_description:m().optional(),error_uri:m().optional()}),vt=gt.merge(ht),yt=`vercel.ai.error.AI_MCPClientOAuthError`,bt=Symbol.for(yt),xt,St,P=class extends (St=e,xt=bt,St){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[xt]=!0}static isInstance(t){return e.hasMarker(t,yt)}},F=class extends P{};F.errorCode=`server_error`;var I=class extends P{};I.errorCode=`invalid_client`;var L=class extends P{};L.errorCode=`invalid_grant`;var R=class extends P{};R.errorCode=`unauthorized_client`;var Ct={[F.errorCode]:F,[I.errorCode]:I,[L.errorCode]:L,[R.errorCode]:R};function wt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function z(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function Tt({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var B=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function V(e){return new URL(e).href}function Et(e){let t=e.toLowerCase().replace(/\.+$/,``);return t===`localhost`||t.endsWith(`.localhost`)||t===`127.0.0.1`||t===`[::1]`||t===`::1`}function H(e){if(e.protocol!==`http:`&&e.protocol!==`https:`||!Et(e.hostname))try{se(e.href)}catch(t){throw new P({message:`OAuth endpoint URL is not allowed: ${e.href}`,cause:t})}}function Dt({callbackIssuer:e,expectedIssuer:t}){if(e!=null&&e!==t)throw new P({message:`OAuth authorization response issuer ${e} does not match expected issuer ${t}`})}function Ot(e,t){return{issuer:t?.issuer??String(e),authorizationServerUrl:V(e),tokenEndpoint:V(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function kt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function At(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function jt(e){if(e?.authorization_server&&e.token_endpoint)return{issuer:e.issuer,authorizationServerUrl:V(e.authorization_server),tokenEndpoint:V(e.token_endpoint)}}async function U({provider:e,clientInformation:t,tokens:n}){let r=jt(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{issuer:i.issuer,authorizationServerUrl:V(i.authorizationServerUrl),tokenEndpoint:V(i.tokenEndpoint)}:jt(t)}async function Mt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(At(t,n)),!0):!1}function Nt(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new P({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function W({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.issuer!=null&&t.issuer!=null&&e.issuer!==t.issuer||e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new P({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function G(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=t.match(/(?:^|[,\s])resource_metadata="([^"]*)"/i),a=t.match(/(?:^|[,\s])scope="([^"]*)"/i)?.[1],o;try{o=i?new URL(i[1]):void 0}catch{}return{resourceMetadataUrl:o,scope:a}}function Pt({scope:e,resourceMetadata:t,clientMetadata:n}){return e||(t?.scopes_supported)?.join(` `)||n.scope}function Ft(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function K(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?K(e,void 0,n):void 0;throw r}}async function It(e,t,n=fetch){return await K(e,{"MCP-Protocol-Version":t},n)}function Lt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Rt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??C,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Ft(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await It(o,a,n);return!r?.metadataUrl&&Lt(s,i.pathname)&&(s=await It(new URL(`/.well-known/${t}`,i),a,n)),s}async function zt(e,t,n=fetch){let r=await Rt(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return ft.parse(await r.json())}function Bt(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;return i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function Vt(e,t){if(!(e.issuer===t||t===new URL(t).origin&&e.issuer===`${t}/`))throw new P({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Ht(e,{fetchFn:t=fetch,protocolVersion:n=C}={}){let r={"MCP-Protocol-Version":n},i=Bt(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await K(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=pt.parse(await i.json());return Vt(e,a),e}{let t=mt.parse(await i.json());if(Vt(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function Ut(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await _e(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,z(o)),{authorizationUrl:l,codeVerifier:d}}function Wt(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Gt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Kt(i,a,n);return;case`client_secret_post`:qt(i,a,r);return;case`none`:Jt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Kt(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function qt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Jt(e,t){t.set(`client_id`,e)}async function q(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=_t.parse(await v({text:n}));return new(Ct[e]||F)({message:t||``,cause:r})}catch(e){return new F({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Yt(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(H(u),t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?await s(d,f,e,t):Gt(Wt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,z(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f,redirect:`error`});if(!p.ok)throw await q(p);return dt.parse(await p.json())}async function Xt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);H(c);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?await a(l,u,e,t):Gt(Wt(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,z(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u,redirect:`error`});if(!d.ok)throw await q(d);return dt.parse({refresh_token:r,...await d.json()})}async function Zt(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);H(i);let a=n.application_type??Qt(n.redirect_uris),o=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,application_type:a}),redirect:`error`});if(!o.ok)throw await q(o);return vt.parse(await o.json())}function Qt(e){return e.every(e=>{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&Et(t.hostname)||t.protocol!==`http:`&&t.protocol!==`https:`})?`native`:`web`}async function J(e,t){try{return await Y(e,t)}catch(n){if(n instanceof I||n instanceof R)return await e.invalidateCredentials?.call(e,`all`),await Y(e,t);if(n instanceof L)return await e.invalidateCredentials?.call(e,`tokens`),await Y(e,t);throw n}}async function $t(e,t,n){let r=wt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Tt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Y(e,{serverUrl:t,authorizationCode:n,callbackState:r,callbackIssuer:i,scope:a,resourceMetadataUrl:o,fetchFn:s}){let c,l;Nt(t,o);try{c=await zt(t,{resourceMetadataUrl:o},s),c.authorization_servers&&c.authorization_servers.length>0&&(l=c.authorization_servers[0])}catch{}l||=t;let u=await $t(t,e,c);await e.validateAuthorizationServerURL?.call(e,t,l);let d=await Ht(l,{fetchFn:s}),f=Ot(l,d),p=e.clientMetadata,m=Pt({scope:a,resourceMetadata:c,clientMetadata:p}),h=await Promise.resolve(e.clientInformation());if(h?.issuer!=null){let t=await U({provider:e,clientInformation:h});t&&W({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:f})}if(!h){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);h=At(await Zt(l,{metadata:d,clientMetadata:{...p,scope:m},fetchFn:s}),f),await e.saveClientInformation(h)}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=await U({provider:e,clientInformation:h});if(!t)throw new P({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});Dt({callbackIssuer:i,expectedIssuer:t.issuer??d?.issuer??String(l)}),W({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:f});let a=await e.codeVerifier(),o=await Yt(l,{metadata:d,clientInformation:h,authorizationCode:n,codeVerifier:a,redirectUri:e.redirectUrl,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(kt(o,f)),`AUTHORIZED`}let g=await e.tokens();if(g?.refresh_token){let t=await U({provider:e,clientInformation:h,tokens:g});t?W({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:f}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Xt(l,{metadata:d,clientInformation:h,refreshToken:g.refresh_token,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(kt(t,f)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof P)||e instanceof F))throw e}}let _=e.state?await e.state():void 0;_&&e.saveState&&await e.saveState(_);let{authorizationUrl:v,codeVerifier:ee}=await Ut(l,{metadata:d,clientInformation:h,state:_,redirectUrl:e.redirectUrl,scope:m,resource:u});if(!await Mt({provider:e,clientInformation:h,authorizationServerInformation:f}))throw new P({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(ee),await e.redirectToAuthorization(v),`REDIRECT`}function en(e){return e===void 0||e===`message`}var tn=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??w};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return ne(t,`ai-sdk/${ut}`,ie())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){let{resourceMetadataUrl:e,scope:r}=G(c);this.resourceMetadataUrl=e;try{if(await J(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,scope:r,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new B;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new M({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new x).getReader(),u=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await l.read();if(t){if(this.connected)throw this.connected=!1,new M({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new M({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(en(s))try{let e=await j(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new M({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),t(e)}};this.sseConnection={close:()=>l.cancel()},u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(s=this.onerror)==null||s.call(this,e),t(e)}};n()})}async close(){var e,t,n;this.connected=!1,this.endpoint=void 0,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e,t){var n;if((n=t?.signal)==null||n.throwIfAborted(),!this.endpoint||!this.connected)throw new M({message:`MCP SSE Transport Error: Not connected`});let r=this.endpoint,i=this.abortController?.signal,a=t?.signal==null?i:i==null?t.signal:AbortSignal.any([i,t.signal]),o=async(n=!1)=>{var i;try{let t={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:a,redirect:this.redirectMode},i=await this.fetchFn(r.href,t);if(i.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=G(i);if(this.resourceMetadataUrl=e,await J(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,scope:t,fetchFn:this.fetchFn})!==`AUTHORIZED`)throw new B;return o(!0)}if(!i.ok){let e=await i.text().catch(()=>null);throw new M({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${i.status}): ${e}`,statusCode:i.status,url:r.href,responseBody:e??void 0})}}catch(e){throw t?.signal?.aborted||(i=this.onerror)==null||i.call(this,e),e}};await o()}},nn=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,rn=/^=\?base64\?.*\?=$/;function an(e){return[...e].every(e=>{let t=e.charCodeAt(0);return t===9||t>=32&&t<=126})&&e.trim()===e&&!rn.test(e)?e:`=?base64?${te(new TextEncoder().encode(e))}?=`}function on(e){if(!p(e))return{success:!1,error:`inputSchema must be a JSON Schema object`};let t=[],n=new Set,r,i=(e,a,o)=>{if(r==null&&p(e)){if(`x-mcp-header`in e){if(!o||a.length===0){r=`x-mcp-header is not on a statically reachable property`;return}let i=e[`x-mcp-header`];if(typeof i!=`string`||!nn.test(i)){r=`x-mcp-header must be a non-empty HTTP token`;return}let s=i.toLowerCase();if(n.has(s)){r=`x-mcp-header value "${i}" is not unique`;return}let c=e.type;if(c!==`boolean`&&c!==`integer`&&c!==`string`){r=`x-mcp-header can only annotate boolean, integer, or string properties`;return}n.add(s),t.push({headerName:i,path:a,valueType:c})}for(let[t,n]of Object.entries(e))if(t!==`x-mcp-header`){if(t===`properties`&&p(n))for(let[e,t]of Object.entries(n))i(t,[...a,e],o);else i(n,a,!1)}}};return i(e,[],!0),r==null?{success:!0,bindings:t}:{success:!1,error:r}}function sn(e,t){let n=e;for(let e of t){if(!p(n))return;n=n[e]}return n}function cn({bindings:e,args:t}){let n={};for(let r of e){let e=sn(t,r.path);if(e!=null){if(r.valueType===`string`&&typeof e!=`string`||r.valueType===`boolean`&&typeof e!=`boolean`||r.valueType===`integer`&&!Number.isSafeInteger(e))throw TypeError(`Tool argument "${r.path.join(`.`)}" does not match its x-mcp-header type`);n[`Mcp-Param-${r.headerName}`]=an(String(e))}}return n}function ln(e){return e===void 0||e===`message`}var un=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.supportsProtocolVersionDiscovery=!0,this.supportsMcpToolParameterHeaders=!0,this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a??w,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){var t;if(this.protocolVersion=e,this.abortController){if(this.isModernProtocol()){(t=this.inboundSseConnection)==null||t.close(),this.inboundSseConnection=void 0;return}this.inboundSseConnection||this.startInboundSse()}}isModernProtocol(){return(this.protocolVersion??C)===C}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??w};if(!this.isModernProtocol()&&t&&this.sessionId&&(n[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(n.Authorization=`Bearer ${e.access_token}`)}return ne(n,`ai-sdk/${ut}`,ie())}setSessionId(e){var t;this.sessionId!==e&&(this.sessionId=e,(t=this.onSessionIdChange)==null||t.call(this,e))}applySessionIdFromResponse(e){if(this.isModernProtocol())return;let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){var t;this.sessionId===e&&this.setSessionId(void 0),(t=this.onSessionExpired)==null||t.call(this,e)}authorizeOnce(e,t){return this.authProvider?(this.authPromise||=J(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,scope:t,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new M({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.protocolVersion!=null&&this.protocolVersion!==C&&this.startInboundSse()}async close(e){var t,n,r,i,a;(t=this.inboundSseConnection)==null||t.close(),(n=this.abortController)==null||n.abort();try{if(!this.isModernProtocol()&&this.sessionId&&this.terminateSessionOnClose&&this.abortController){(r=e?.signal)==null||r.throwIfAborted();let t=await this.commonHeaders({base:{}});(i=e?.signal)==null||i.throwIfAborted(),await this.fetchFn(this.url.href,{method:`DELETE`,headers:t,signal:e?.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(a=this.onclose)==null||a.call(this)}async send(e,t){var n;(n=t?.signal)==null||n.throwIfAborted();let r=this.abortController?.signal,i=t?.signal==null?r:r==null?t.signal:AbortSignal.any([r,t.signal]),a=async(n=!1)=>{var r,o,s,c,l,u,d;try{let d=`method`in e&&e.method===`initialize`,f=d?void 0:this.sessionId,p={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,...this.isModernProtocol()?t?.headers:{},...this.isModernProtocol()&&`method`in e&&`id`in e?this.getStandardRequestHeaders(e):{}},includeSessionId:!d}),body:JSON.stringify(e),signal:i,redirect:this.redirectMode},m=await this.fetchFn(this.url.href,p);if(this.applySessionIdFromResponse(m),m.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=G(m);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,t)!==`AUTHORIZED`)throw new B}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return a(!0)}if(m.status===202){!this.isModernProtocol()&&!this.inboundSseConnection&&this.startInboundSse();return}if(!m.ok){let t=await m.text().catch(()=>null);if(`id`in e&&t!=null){let n=await j(t).catch(()=>void 0);if(n!=null&&`error`in n){(o=this.onmessage)==null||o.call(this,n.id==null?{...n,id:e.id}:n);return}}let n=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${m.status}): ${t}`;m.status===404&&(!this.isModernProtocol()&&f?(this.expireSessionId(f),n+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):this.isModernProtocol()||(n+=". This server does not support HTTP transport. Try using `sse` transport instead"));let r=new M({message:n,statusCode:m.status,url:this.url.href,responseBody:t??void 0});throw(s=this.onerror)==null||s.call(this,r),r}if(!(`id`in e))return;let h=m.headers.get(`content-type`)||``;if(h.includes(`application/json`)){let e=await m.json(),t=Array.isArray(e)?e.map(e=>A(e)):[A(e)];for(let e of t)(c=this.onmessage)==null||c.call(this,e);return}if(h.includes(`text/event-stream`)){if(!m.body){let e=new M({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:m.status,url:this.url.href});throw(l=this.onerror)==null||l.call(this,e),e}let e=m.body.pipeThrough(new TextDecoderStream).pipeThrough(new x).getReader();(async()=>{var n,r,i;try{for(;;){let{done:t,value:i}=await e.read();if(t)return;let{event:a,data:o}=i;if(ln(a))try{let e=await j(o);(n=this.onmessage)==null||n.call(this,e)}catch(e){let t=new M({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(r=this.onerror)==null||r.call(this,t)}}}catch(e){if(t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`)return;(i=this.onerror)==null||i.call(this,e)}})().catch(e=>{var n;t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`||(n=this.onerror)==null||n.call(this,e)});return}let g=new M({message:`MCP HTTP Transport Error: Unexpected content type: ${h}`,statusCode:m.status,url:this.url.href});throw(u=this.onerror)==null||u.call(this,g),g}catch(e){throw t?.signal?.aborted||(d=this.onerror)==null||d.call(this,e),e}};await a()}getStandardRequestHeaders(e){let t={"Mcp-Method":e.method},n=e.params,r=e.method===`resources/read`?n?.uri:e.method===`tools/call`||e.method===`prompts/get`?n?.name:void 0;return typeof r==`string`&&(t[`Mcp-Name`]=an(r)),t}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new M({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},n)}startInboundSse(e=!1,t){this.isModernProtocol()||this.openInboundSse(e,t).catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}async openInboundSse(e=!1,t){var n,r,i,a;if(!this.isModernProtocol())try{let a=this.sessionId,o=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(o[`last-event-id`]=t);let s=await this.fetchFn(this.url.href,{method:`GET`,headers:o,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(s),s.status===401&&this.authProvider&&!e){let{resourceMetadataUrl:e,scope:i}=G(s);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,i)!==`AUTHORIZED`){let e=new B;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(s.status===405)return;if(!s.ok||!s.body){s.status===404&&a&&this.expireSessionId(a);let e=new M({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new x).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),ln(i))try{let t=await j(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new M({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{c.cancel().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}},this.inboundReconnectAttempts=0,l().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||((t=this.onerror)==null||t.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function dn(e){switch(e.type){case`sse`:return new tn(e);case`http`:return new un({...e,initialProtocolVersion:e.initialProtocolVersion??C});default:throw new M({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function fn(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var pn=`io.modelcontextprotocol/ui`,X=`text/html;profile=mcp-app`,mn=`ui/resourceUri`,hn={extensions:{[pn]:{mimeTypes:[X]}}};function gn(e){let n=e?.ui;return t(n)?n:void 0}var Z=b(_()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),_n=l({connectDomains:Z,resourceDomains:Z,frameDomains:Z}),vn=l({prefersBorder:a().optional().catch(void 0),csp:_n.optional().catch(void 0),permissions:c(m(),_()).optional().catch(void 0)});function yn(e){let n=(t(e)?e:void 0)?.ui;if(!t(n))return;let r=vn.safeParse(n);return r.success?r.data:void 0}function bn(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function xn(e){let t=gn(e._meta),n=t?.resourceUri??e._meta?.[mn],r=bn(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function Sn(e){let t=[],n=[];for(let r of e.tools){let e=xn(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function Cn({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(le(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:X,html:r,meta:yn(n._meta)}}async function wn({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Cn({uri:t,resource:await e.readResource({uri:t,options:n})})}var Tn=`1.0.0`,En=0,Dn=1e3,On=[-32020,-32021,-32022],kn=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function An(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function jn(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function Mn(e){let t=An(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(M.isInstance(e)&&e.code!=null)return!1;let n=jn(e);return n!=null&&kn.includes(n)}function Nn(e){if(e==null)return En;if(!Number.isInteger(e))throw new M({message:`maxRetries must be an integer`});if(e<0)throw new M({message:`maxRetries must be >= 0`});return e}function Pn({timeout:e,maxTotalTimeout:t}){return e==null?t:t==null?e:Math.min(e,t)}function Q(e,t){return t==null?e:new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,a)},a=()=>{i(),r(t.reason)};if(t.aborted){a();return}t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{i(),n(e)}).catch(e=>{i(),r(e)})})}function Fn({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function In(e){let t=new Ln(e);return await t.init(),t}var Ln=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Tn,onUncaughtError:i,maxRetries:a,capabilities:o,initialInitializeResult:s,initializationOptions:c,protocolVersionDiscovery:l=!0}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:w,capabilities:{},serverInfo:this._serverInfo},this.protocolEra=`legacy`,this.protocolVersion=w,this.toolHeaderBindings=new Map,this.isClosed=!0,this.onUncaughtError=i,this.maxRetries=Nn(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,this.initializationOptions=c,this.protocolVersionDiscovery=l,this.transport=fn(e)?e:dn(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new M({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){let e=this.initializationOptions?.signal,t=this.initializationOptions?Pn(this.initializationOptions):void 0,n=t==null?void 0:new AbortController,r=e==null?n?.signal:n==null?e:AbortSignal.any([e,n.signal]),i,a;t!=null&&(i=setTimeout(()=>{a=new M({message:`MCP client initialization timed out after ${t}ms`}),n?.abort(a)},t));try{if(this.isClosed=!1,r?.throwIfAborted(),await Q(this.transport.start(),r),this.initialInitializeResult){let e=Te.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}if(this.protocolVersionDiscovery&&this.transport.supportsProtocolVersionDiscovery&&await this.tryProtocolDiscovery(r))return this;this.protocolEra=`legacy`,this.protocolVersion=w,this.setTransportProtocolVersion(this.protocolVersion);let e=await this.request({request:{method:`initialize`,params:{protocolVersion:w,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Te,options:{signal:r}});if(e===void 0)throw new M({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`},{signal:r}),this}catch(t){try{await Q(this.transport.close({signal:r}),r)}catch{}throw this.onClose(),a??(e?.aborted?new M({message:`MCP client initialization was aborted`,cause:e.reason}):t)}finally{i!=null&&clearTimeout(i)}}async tryProtocolDiscovery(e){this.protocolEra=`modern`,this.protocolVersion=C,this.setTransportProtocolVersion(this.protocolVersion);try{let t=await this.request({request:{method:`server/discover`},resultSchema:we,options:{signal:e,timeout:Dn}});return this.applyDiscoverResult(t),!0}catch(e){if(M.isInstance(e)&&e.code!=null&&On.includes(e.code))throw e;return!1}}applyDiscoverResult(e){if(!e.supportedVersions.includes(this.protocolVersion))throw new M({message:`Server does not support the requested protocol version: ${this.protocolVersion}`});let t=e._meta?.[`io.modelcontextprotocol/serverInfo`];typeof t==`object`&&t&&`name`in t&&typeof t.name==`string`&&`version`in t&&typeof t.version==`string`&&(this._serverInfo=t),this.serverCapabilities=e.capabilities,this._serverInstructions=e.instructions,this._initializeResult={protocolVersion:this.protocolVersion,capabilities:e.capabilities,serverInfo:this._serverInfo,instructions:e.instructions}}setTransportProtocolVersion(e){this.transport.setProtocolVersion?this.transport.setProtocolVersion(e):this.transport.protocolVersion=e}applyInitializeResult(e){if(!ve.includes(e.protocolVersion))throw new M({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this.protocolEra=`legacy`,this.protocolVersion=e.protocolVersion,this._serverInfo=e.serverInfo,this._initializeResult=e,this.setTransportProtocolVersion(e.protocolVersion),this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}send(e,t){return t==null?this.transport.send(e):this.transport.send(e,t)}assertCapability(e){switch(e){case`initialize`:case`server/discover`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new M({message:`Server does not support completions`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new M({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new M({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new M({message:`Server does not support prompts`});break;default:throw new M({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new M({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=n==null?void 0:Pn(n),s=o==null?void 0:new AbortController,c=a==null?s?.signal:s==null?a:AbortSignal.any([a,s.signal]),l,u=this.requestMessageId++,d=this.protocolEra===`modern`?{...e,params:{...e.params,_meta:{...e.params?._meta,"io.modelcontextprotocol/protocolVersion":this.protocolVersion,"io.modelcontextprotocol/clientCapabilities":this.clientCapabilities,"io.modelcontextprotocol/clientInfo":this.clientInfo}}}:e,f={...d,jsonrpc:`2.0`,id:u},p=this.getToolRequestHeaders(d),m=()=>{i(new M({message:`Request was aborted`,cause:a?.reason}))},h=()=>{this.responseHandlers.delete(u),a?.removeEventListener(`abort`,_),l!=null&&clearTimeout(l)},g=e=>{h(),i(e)},_=()=>{h(),m()};this.responseHandlers.set(u,e=>{if(a?.aborted)return h(),m();if(e instanceof Error)return g(e);try{if(this.protocolEra===`modern`&&e.result.resultType==null)throw new M({message:`Modern MCP result is missing resultType`});if(e.result.resultType===`input_required`)throw new M({message:`Server requested additional input, but multi round-trip requests are not supported yet`});let n=t.parse(e.result);h(),r(n)}catch(e){let t=M.isInstance(e)?e:new M({message:`Failed to parse server response`,cause:e});g(t)}}),a?.addEventListener(`abort`,_,{once:!0}),o!=null&&(l=setTimeout(()=>{let e=new M({message:`Request timed out after ${o}ms`});s?.abort(e),g(e)},o));let v={...c==null?{}:{signal:c},...p==null?{}:{headers:p}};(Object.keys(v).length===0?this.send(f):this.send(f,v)).catch(e=>{g(e)})})}async listTools({params:e,options:t}={}){let n=await this.request({request:{method:`tools/list`,params:e},resultSchema:De,options:t});return this.prepareToolDefinitions(n,e?.cursor==null)}prepareToolDefinitions(e,t=!1){if(this.protocolEra!==`modern`||!this.transport.supportsMcpToolParameterHeaders)return e;t&&this.toolHeaderBindings.clear();let n=e.tools.filter(e=>{let t=on(e.inputSchema);return t.success?(this.toolHeaderBindings.set(e.name,t.bindings),!0):(this.onError(new M({message:`Ignoring MCP tool "${e.name}": ${t.error}`})),!1)});return{...e,tools:n}}getToolRequestHeaders(e){if(this.protocolEra!==`modern`||e.method!==`tools/call`||typeof e.params?.name!=`string`)return;let t=this.toolHeaderBindings.get(e.params.name);if(t==null||t.length===0)return;let n=e.params.arguments;if(typeof n==`object`&&n&&!Array.isArray(n))try{return cn({bindings:t,args:n})}catch(t){throw new M({message:`Failed to create MCP headers for tool "${e.params.name}"`,cause:t})}}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():re({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:Mn,createRetryError:({message:e,errors:t})=>new M({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){try{return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:Be,options:n})})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:je,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Ue,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:He,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Xe,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Qe,options:n})}catch(e){throw e}}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:qe,options:e})}async notification(e,t){let n={...e,jsonrpc:`2.0`};await Q(this.send(n,t?.signal==null?void 0:{signal:t.signal}),t?.signal)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools(),n=[...t.tools];for(;t.nextCursor!=null;)t=await this.listTools({params:{cursor:t.nextCursor}}),n.push(...t.tools);return this.toolsFromDefinitions({...t,tools:n},{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){e=this.prepareToolDefinitions(e);let r={};for(let{name:i,title:a,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=a??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,i))continue;let u=this,f=t===`automatic`?void 0:t[i]?.outputSchema,p=xn({_meta:l}),m={clientName:this.clientInfo.name,toolName:i,...e==null?{}:{title:e},...c==null?{}:{annotations:{...c.title==null?{}:{title:c.title},...c.readOnlyHint==null?{}:{readOnlyHint:c.readOnlyHint},...c.destructiveHint==null?{}:{destructiveHint:c.destructiveHint},...c.idempotentHint==null?{}:{idempotentHint:c.idempotentHint},...c.openWorldHint==null?{}:{openWorldHint:c.openWorldHint}}},...p?.resourceUri==null?{}:{app:{...p,mimeType:X}}},h=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let r=await u.callTool({name:i,arguments:e,options:{signal:t?.abortSignal}});return r.isError||f==null?r:u.extractStructuredContent(r,f,i)};r[i]={...t===`automatic`?d({description:o,title:e,metadata:m,inputSchema:n({...s,properties:s.properties??{},additionalProperties:!1}),execute:h,toModelOutput:Fn}):ue({description:o,title:e,metadata:m,inputSchema:t[i].inputSchema,...f==null?{}:{outputSchema:f},execute:h,toModelOutput:Fn}),_meta:l}}return r}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await oe({value:e.structuredContent,schema:ce(t)});if(!r.success)throw new M({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await ee({text:r.text,schema:t});if(!e.success)throw new M({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new M({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==O)throw new M({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=O.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=et.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new M({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){if(e.id==null){this.onError(new M({message:`Protocol error: Received a response without a message ID: ${JSON.stringify(e)}`}));return}let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new M({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new M({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},Rn=new TextEncoder;function $(e){if(typeof e!=`object`||!e)return JSON.stringify(e??null);if(Array.isArray(e))return`[${e.map($).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${$(t[e])}`).join(`,`)}}`}function zn(e){return te(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function Bn(e){let t=await crypto.subtle.digest(`SHA-256`,Rn.encode($({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return zn(new Uint8Array(t))}function Vn(e,t){return e!==t}export{et as ElicitResultSchema,O as ElicitationRequestSchema,X as MCP_APP_MIME_TYPE,B as UnauthorizedError,J as auth,In as createMCPClient,In as experimental_createMCPClient,Vn as detectMCPAppResourceDrift,Bn as fingerprintMCPAppResource,hn as mcpAppClientCapabilities,wn as readMCPAppResource,Sn as splitMCPAppTools,A as validateJSONRPCMessage};
1
+ import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{C as n,O as r,Z as i,_ as a,b as o,c as s,g as c,k as l,l as u,m as d,s as f,u as p,v as m,w as h,x as g,y as _}from"../../_chunks/workflow/schemas-DR7NTzNe.js";import{B as v,O as ee,R as y,Y as te,at as ne,d as re,gt as b,it as ie,j as ae,ot as oe,pt as se,r as ce,s as le,ut as ue,yt as x}from"../../_chunks/workflow/dist-KPieTJHT.js";const de={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var fe;fe||={};let S;S=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function pe(e){return(await S).getRandomValues(new Uint8Array(e))}async function me(e){let t=``;for(;t.length<e;){let n=await pe(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function he(e){return await me(e)}async function ge(e){let t=await(await S).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function _e(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await he(e);return{code_verifier:t,code_challenge:await ge(t)}}var C=`2026-07-28`,w=`2025-11-25`,ve=[C,w,`2025-06-18`,`2025-03-26`,`2024-11-05`],ye=g(n(h(),l())),be=a({name:h(),version:h(),title:g(h())}),T=a({_meta:g(o({}).loose())}),E=T.extend({resultType:g(h())}),xe=o({method:h(),params:g(T)}),Se=o({applyDefaults:g(p())}).loose(),Ce=a({experimental:g(o({}).loose()),logging:g(o({}).loose()),completions:g(o({}).loose()),prompts:g(a({listChanged:g(p())})),resources:g(a({subscribe:g(p()),listChanged:g(p())})),tools:g(a({listChanged:g(p())})),elicitation:g(Se)});o({elicitation:g(Se)}).loose();var we=E.extend({supportedVersions:s(h()),capabilities:Ce,instructions:g(h()),ttlMs:g(_()),cacheScope:g(r([c(`public`),c(`private`)]))}),Te=E.extend({protocolVersion:h(),capabilities:Ce,serverInfo:be,instructions:g(h())}),D=E.extend({nextCursor:g(h())}),Ee=o({name:h(),title:g(h()),description:g(h()),inputSchema:a({type:g(l()),properties:g(o({}).loose())}),outputSchema:g(o({}).loose()),annotations:g(o({title:g(h()),readOnlyHint:g(p()),destructiveHint:g(p()),idempotentHint:g(p()),openWorldHint:g(p())}).loose()),_meta:ye}).loose(),De=D.extend({tools:s(Ee)}),Oe=o({type:c(`text`),text:h()}).loose(),ke=o({type:c(`image`),data:u(),mimeType:h()}).loose(),Ae=o({uri:h(),name:h(),title:g(h()),description:g(h()),mimeType:g(h()),size:g(_())}).loose(),je=D.extend({resources:s(Ae)}),Me=o({uri:h(),name:g(h()),title:g(h()),mimeType:g(h())}).loose(),Ne=Me.extend({text:h()}),Pe=Me.extend({blob:u()}),Fe=o({type:c(`resource`),resource:r([Ne,Pe])}).loose(),Ie=o({type:c(`resource_link`),uri:h(),name:h(),description:g(h()),mimeType:g(h())}).loose(),Le=o({type:h()}).loose().refine(e=>![`text`,`image`,`resource`,`resource_link`].includes(e.type),{message:`Known content types must match their schema`}),Re=E.extend({content:s(r([Oe,ke,Fe,Ie,Le])),structuredContent:g(l()),isError:p().default(!1).optional()}),ze=E.extend({content:m().optional(),structuredContent:d(),isError:p().default(!1).optional()}).transform(e=>({...e,content:[{type:`text`,text:JSON.stringify(e.structuredContent)}]})).pipe(Re),Be=Re.or(ze).or(E.extend({toolResult:l().nonoptional()})),Ve=o({uriTemplate:h(),name:h(),title:g(h()),description:g(h()),mimeType:g(h())}).loose(),He=E.extend({resourceTemplates:s(Ve)}),Ue=E.extend({contents:s(r([Ne,Pe]))}),We=o({type:c(`ref/prompt`),name:h()}).loose(),Ge=o({type:c(`ref/resource`),uri:h()}).loose(),Ke=o({name:h(),value:h()}).loose();T.extend({ref:r([We,Ge]),argument:Ke,context:g(o({arguments:n(h(),h())}).loose())});var qe=E.extend({completion:o({values:s(h()).max(100),total:g(_().int()),hasMore:g(p())}).loose()}),Je=o({name:h(),description:g(h()),required:g(p())}).loose(),Ye=o({name:h(),title:g(h()),description:g(h()),arguments:g(s(Je))}).loose(),Xe=D.extend({prompts:s(Ye)}),Ze=o({role:r([c(`user`),c(`assistant`)]),content:r([Oe,ke,Fe,Ie])}).loose(),Qe=E.extend({description:g(h()),messages:s(Ze)}),$e=T.extend({message:h(),requestedSchema:l()}),O=xe.extend({method:c(`elicitation/create`),params:$e}),et=E.extend({action:r([c(`accept`),c(`decline`),c(`cancel`)]),content:g(n(h(),l()))}),k=`2.0`,tt=o({jsonrpc:c(k),id:r([h(),_().int()])}).merge(xe).strict(),nt=o({jsonrpc:c(k),id:r([h(),_().int()]),result:E}).strict(),rt=o({jsonrpc:c(k),id:g(r([h(),_().int()])),error:o({code:_().int(),message:h(),data:g(l())})}).strict(),it=o({jsonrpc:c(k)}).merge(o({method:h(),params:g(T)})).strict(),at=r([tt,it,nt,rt]);function A(e){return at.parse(e)}async function j(e){return A(await te({text:e}))}var ot=`vercel.ai.error.AI_MCPClientError`,st=Symbol.for(ot),ct,lt,M=class extends (lt=e,ct=st,lt){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[ct]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,ot)}},ut=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,N=h().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:de.custom,message:`URL must be parseable`,fatal:!0}),i}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),dt=o({access_token:h(),id_token:h().optional(),token_type:h(),expires_in:_().optional(),scope:h().optional(),refresh_token:h().optional(),issuer:N.optional(),authorization_server:N.optional(),token_endpoint:N.optional()}).strip(),ft=a({resource:h().url(),authorization_servers:s(N).optional(),jwks_uri:h().url().optional(),scopes_supported:s(h()).optional(),bearer_methods_supported:s(h()).optional(),resource_signing_alg_values_supported:s(h()).optional(),resource_name:h().optional(),resource_documentation:h().optional(),resource_policy_uri:h().url().optional(),resource_tos_uri:h().url().optional(),tls_client_certificate_bound_access_tokens:p().optional(),authorization_details_types_supported:s(h()).optional(),dpop_signing_alg_values_supported:s(h()).optional(),dpop_bound_access_tokens_required:p().optional()}),pt=a({issuer:h(),authorization_endpoint:N,token_endpoint:N,registration_endpoint:N.optional(),authorization_response_iss_parameter_supported:p().optional(),client_id_metadata_document_supported:p().optional(),scopes_supported:s(h()).optional(),response_types_supported:s(h()),grant_types_supported:s(h()).optional(),code_challenge_methods_supported:s(h()).optional(),token_endpoint_auth_methods_supported:s(h()).optional(),token_endpoint_auth_signing_alg_values_supported:s(h()).optional()}),mt=a({issuer:h(),authorization_endpoint:N,token_endpoint:N,userinfo_endpoint:N.optional(),jwks_uri:N,registration_endpoint:N.optional(),authorization_response_iss_parameter_supported:p().optional(),client_id_metadata_document_supported:p().optional(),scopes_supported:s(h()).optional(),response_types_supported:s(h()),grant_types_supported:s(h()).optional(),subject_types_supported:s(h()),id_token_signing_alg_values_supported:s(h()),claims_supported:s(h()).optional(),token_endpoint_auth_methods_supported:s(h()).optional()}).merge(pt.pick({code_challenge_methods_supported:!0})),ht=o({client_id:h(),client_secret:h().optional(),client_id_issued_at:_().optional(),client_secret_expires_at:_().optional(),issuer:N.optional(),authorization_server:N.optional(),token_endpoint:N.optional()}).strip(),gt=o({redirect_uris:s(N),application_type:r([c(`native`),c(`web`)]).optional(),token_endpoint_auth_method:h().optional(),grant_types:s(h()).optional(),response_types:s(h()).optional(),client_name:h().optional(),client_uri:N.optional(),logo_uri:N.optional(),scope:h().optional(),contacts:s(h()).optional(),tos_uri:N.optional(),policy_uri:h().optional(),jwks_uri:N.optional(),jwks:f().optional(),software_id:h().optional(),software_version:h().optional(),software_statement:h().optional()}).strip(),_t=o({error:h(),error_description:h().optional(),error_uri:h().optional()}),vt=gt.merge(ht),yt=`vercel.ai.error.AI_MCPClientOAuthError`,bt=Symbol.for(yt),xt,St,P=class extends (St=e,xt=bt,St){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[xt]=!0}static isInstance(t){return e.hasMarker(t,yt)}},F=class extends P{};F.errorCode=`server_error`;var I=class extends P{};I.errorCode=`invalid_client`;var L=class extends P{};L.errorCode=`invalid_grant`;var R=class extends P{};R.errorCode=`unauthorized_client`;var Ct={[F.errorCode]:F,[I.errorCode]:I,[L.errorCode]:L,[R.errorCode]:R};function wt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function z(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function Tt({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var B=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function V(e){return new URL(e).href}function Et(e){let t=e.toLowerCase().replace(/\.+$/,``);return t===`localhost`||t.endsWith(`.localhost`)||t===`127.0.0.1`||t===`[::1]`||t===`::1`}function H(e){if(e.protocol!==`http:`&&e.protocol!==`https:`||!Et(e.hostname))try{se(e.href)}catch(t){throw new P({message:`OAuth endpoint URL is not allowed: ${e.href}`,cause:t})}}function Dt({callbackIssuer:e,expectedIssuer:t}){if(e!=null&&e!==t)throw new P({message:`OAuth authorization response issuer ${e} does not match expected issuer ${t}`})}function Ot(e,t){return{issuer:t?.issuer??String(e),authorizationServerUrl:V(e),tokenEndpoint:V(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function kt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function At(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function jt(e){if(e?.authorization_server&&e.token_endpoint)return{issuer:e.issuer,authorizationServerUrl:V(e.authorization_server),tokenEndpoint:V(e.token_endpoint)}}async function U({provider:e,clientInformation:t,tokens:n}){let r=jt(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{issuer:i.issuer,authorizationServerUrl:V(i.authorizationServerUrl),tokenEndpoint:V(i.tokenEndpoint)}:jt(t)}async function Mt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(At(t,n)),!0):!1}function Nt(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new P({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function W({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.issuer!=null&&t.issuer!=null&&e.issuer!==t.issuer||e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new P({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function G(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=t.match(/(?:^|[,\s])resource_metadata="([^"]*)"/i),a=t.match(/(?:^|[,\s])scope="([^"]*)"/i)?.[1],o;try{o=i?new URL(i[1]):void 0}catch{}return{resourceMetadataUrl:o,scope:a}}function Pt({scope:e,resourceMetadata:t,clientMetadata:n}){return e||(t?.scopes_supported)?.join(` `)||n.scope}function Ft(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function K(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?K(e,void 0,n):void 0;throw r}}async function It(e,t,n=fetch){return await K(e,{"MCP-Protocol-Version":t},n)}function Lt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Rt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??C,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Ft(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await It(o,a,n);return!r?.metadataUrl&&Lt(s,i.pathname)&&(s=await It(new URL(`/.well-known/${t}`,i),a,n)),s}async function zt(e,t,n=fetch){let r=await Rt(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return ft.parse(await r.json())}function Bt(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;return i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function Vt(e,t){if(!(e.issuer===t||t===new URL(t).origin&&e.issuer===`${t}/`))throw new P({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Ht(e,{fetchFn:t=fetch,protocolVersion:n=C}={}){let r={"MCP-Protocol-Version":n},i=Bt(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await K(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=pt.parse(await i.json());return Vt(e,a),e}{let t=mt.parse(await i.json());if(Vt(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function Ut(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await _e(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,z(o)),{authorizationUrl:l,codeVerifier:d}}function Wt(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Gt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Kt(i,a,n);return;case`client_secret_post`:qt(i,a,r);return;case`none`:Jt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Kt(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function qt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Jt(e,t){t.set(`client_id`,e)}async function q(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=_t.parse(await te({text:n}));return new(Ct[e]||F)({message:t||``,cause:r})}catch(e){return new F({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Yt(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(H(u),t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?await s(d,f,e,t):Gt(Wt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,z(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f,redirect:`error`});if(!p.ok)throw await q(p);return dt.parse(await p.json())}async function Xt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);H(c);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?await a(l,u,e,t):Gt(Wt(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,z(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u,redirect:`error`});if(!d.ok)throw await q(d);return dt.parse({refresh_token:r,...await d.json()})}async function Zt(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);H(i);let a=n.application_type??Qt(n.redirect_uris),o=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,application_type:a}),redirect:`error`});if(!o.ok)throw await q(o);return vt.parse(await o.json())}function Qt(e){return e.every(e=>{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&Et(t.hostname)||t.protocol!==`http:`&&t.protocol!==`https:`})?`native`:`web`}async function J(e,t){try{return await Y(e,t)}catch(n){if(n instanceof I||n instanceof R)return await e.invalidateCredentials?.call(e,`all`),await Y(e,t);if(n instanceof L)return await e.invalidateCredentials?.call(e,`tokens`),await Y(e,t);throw n}}async function $t(e,t,n){let r=wt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Tt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Y(e,{serverUrl:t,authorizationCode:n,callbackState:r,callbackIssuer:i,scope:a,resourceMetadataUrl:o,fetchFn:s}){let c,l;Nt(t,o);try{c=await zt(t,{resourceMetadataUrl:o},s),c.authorization_servers&&c.authorization_servers.length>0&&(l=c.authorization_servers[0])}catch{}l||=t;let u=await $t(t,e,c);await e.validateAuthorizationServerURL?.call(e,t,l);let d=await Ht(l,{fetchFn:s}),f=Ot(l,d),p=e.clientMetadata,m=Pt({scope:a,resourceMetadata:c,clientMetadata:p}),h=await Promise.resolve(e.clientInformation());if(h?.issuer!=null){let t=await U({provider:e,clientInformation:h});t&&W({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:f})}if(!h){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);h=At(await Zt(l,{metadata:d,clientMetadata:{...p,scope:m},fetchFn:s}),f),await e.saveClientInformation(h)}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=await U({provider:e,clientInformation:h});if(!t)throw new P({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});Dt({callbackIssuer:i,expectedIssuer:t.issuer??d?.issuer??String(l)}),W({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:f});let a=await e.codeVerifier(),o=await Yt(l,{metadata:d,clientInformation:h,authorizationCode:n,codeVerifier:a,redirectUri:e.redirectUrl,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(kt(o,f)),`AUTHORIZED`}let g=await e.tokens();if(g?.refresh_token){let t=await U({provider:e,clientInformation:h,tokens:g});t?W({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:f}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Xt(l,{metadata:d,clientInformation:h,refreshToken:g.refresh_token,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(kt(t,f)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof P)||e instanceof F))throw e}}let _=e.state?await e.state():void 0;_&&e.saveState&&await e.saveState(_);let{authorizationUrl:v,codeVerifier:ee}=await Ut(l,{metadata:d,clientInformation:h,state:_,redirectUrl:e.redirectUrl,scope:m,resource:u});if(!await Mt({provider:e,clientInformation:h,authorizationServerInformation:f}))throw new P({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(ee),await e.redirectToAuthorization(v),`REDIRECT`}function en(e){return e===void 0||e===`message`}var tn=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??w};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return b(t,`ai-sdk/${ut}`,ae())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){let{resourceMetadataUrl:e,scope:r}=G(c);this.resourceMetadataUrl=e;try{if(await J(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,scope:r,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new B;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new M({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new x).getReader(),u=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await l.read();if(t){if(this.connected)throw this.connected=!1,new M({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new M({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(en(s))try{let e=await j(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new M({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),t(e)}};this.sseConnection={close:()=>l.cancel()},u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(s=this.onerror)==null||s.call(this,e),t(e)}};n()})}async close(){var e,t,n;this.connected=!1,this.endpoint=void 0,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e,t){var n;if((n=t?.signal)==null||n.throwIfAborted(),!this.endpoint||!this.connected)throw new M({message:`MCP SSE Transport Error: Not connected`});let r=this.endpoint,i=this.abortController?.signal,a=t?.signal==null?i:i==null?t.signal:AbortSignal.any([i,t.signal]),o=async(n=!1)=>{var i;try{let t={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:a,redirect:this.redirectMode},i=await this.fetchFn(r.href,t);if(i.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=G(i);if(this.resourceMetadataUrl=e,await J(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,scope:t,fetchFn:this.fetchFn})!==`AUTHORIZED`)throw new B;return o(!0)}if(!i.ok){let e=await i.text().catch(()=>null);throw new M({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${i.status}): ${e}`,statusCode:i.status,url:r.href,responseBody:e??void 0})}}catch(e){throw t?.signal?.aborted||(i=this.onerror)==null||i.call(this,e),e}};await o()}},nn=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,rn=/^=\?base64\?.*\?=$/;function an(e){return[...e].every(e=>{let t=e.charCodeAt(0);return t===9||t>=32&&t<=126})&&e.trim()===e&&!rn.test(e)?e:`=?base64?${re(new TextEncoder().encode(e))}?=`}function on(e){if(!y(e))return{success:!1,error:`inputSchema must be a JSON Schema object`};let t=[],n=new Set,r,i=(e,a,o)=>{if(r==null&&y(e)){if(`x-mcp-header`in e){if(!o||a.length===0){r=`x-mcp-header is not on a statically reachable property`;return}let i=e[`x-mcp-header`];if(typeof i!=`string`||!nn.test(i)){r=`x-mcp-header must be a non-empty HTTP token`;return}let s=i.toLowerCase();if(n.has(s)){r=`x-mcp-header value "${i}" is not unique`;return}let c=e.type;if(c!==`boolean`&&c!==`integer`&&c!==`string`){r=`x-mcp-header can only annotate boolean, integer, or string properties`;return}n.add(s),t.push({headerName:i,path:a,valueType:c})}for(let[t,n]of Object.entries(e))if(t!==`x-mcp-header`){if(t===`properties`&&y(n))for(let[e,t]of Object.entries(n))i(t,[...a,e],o);else i(n,a,!1)}}};return i(e,[],!0),r==null?{success:!0,bindings:t}:{success:!1,error:r}}function sn(e,t){let n=e;for(let e of t){if(!y(n))return;n=n[e]}return n}function cn({bindings:e,args:t}){let n={};for(let r of e){let e=sn(t,r.path);if(e!=null){if(r.valueType===`string`&&typeof e!=`string`||r.valueType===`boolean`&&typeof e!=`boolean`||r.valueType===`integer`&&!Number.isSafeInteger(e))throw TypeError(`Tool argument "${r.path.join(`.`)}" does not match its x-mcp-header type`);n[`Mcp-Param-${r.headerName}`]=an(String(e))}}return n}function ln(e){return e===void 0||e===`message`}var un=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.supportsProtocolVersionDiscovery=!0,this.supportsMcpToolParameterHeaders=!0,this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a??w,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){var t;if(this.protocolVersion=e,this.abortController){if(this.isModernProtocol()){(t=this.inboundSseConnection)==null||t.close(),this.inboundSseConnection=void 0;return}this.inboundSseConnection||this.startInboundSse()}}isModernProtocol(){return(this.protocolVersion??C)===C}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??w};if(!this.isModernProtocol()&&t&&this.sessionId&&(n[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(n.Authorization=`Bearer ${e.access_token}`)}return b(n,`ai-sdk/${ut}`,ae())}setSessionId(e){var t;this.sessionId!==e&&(this.sessionId=e,(t=this.onSessionIdChange)==null||t.call(this,e))}applySessionIdFromResponse(e){if(this.isModernProtocol())return;let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){var t;this.sessionId===e&&this.setSessionId(void 0),(t=this.onSessionExpired)==null||t.call(this,e)}authorizeOnce(e,t){return this.authProvider?(this.authPromise||=J(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,scope:t,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new M({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.protocolVersion!=null&&this.protocolVersion!==C&&this.startInboundSse()}async close(e){var t,n,r,i,a;(t=this.inboundSseConnection)==null||t.close(),(n=this.abortController)==null||n.abort();try{if(!this.isModernProtocol()&&this.sessionId&&this.terminateSessionOnClose&&this.abortController){(r=e?.signal)==null||r.throwIfAborted();let t=await this.commonHeaders({base:{}});(i=e?.signal)==null||i.throwIfAborted(),await this.fetchFn(this.url.href,{method:`DELETE`,headers:t,signal:e?.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(a=this.onclose)==null||a.call(this)}async send(e,t){var n;(n=t?.signal)==null||n.throwIfAborted();let r=this.abortController?.signal,i=t?.signal==null?r:r==null?t.signal:AbortSignal.any([r,t.signal]),a=async(n=!1)=>{var r,o,s,c,l,u,d;try{let d=`method`in e&&e.method===`initialize`,f=d?void 0:this.sessionId,p={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,...this.isModernProtocol()?t?.headers:{},...this.isModernProtocol()&&`method`in e&&`id`in e?this.getStandardRequestHeaders(e):{}},includeSessionId:!d}),body:JSON.stringify(e),signal:i,redirect:this.redirectMode},m=await this.fetchFn(this.url.href,p);if(this.applySessionIdFromResponse(m),m.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=G(m);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,t)!==`AUTHORIZED`)throw new B}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return a(!0)}if(m.status===202){!this.isModernProtocol()&&!this.inboundSseConnection&&this.startInboundSse();return}if(!m.ok){let t=await m.text().catch(()=>null);if(`id`in e&&t!=null){let n=await j(t).catch(()=>void 0);if(n!=null&&`error`in n){(o=this.onmessage)==null||o.call(this,n.id==null?{...n,id:e.id}:n);return}}let n=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${m.status}): ${t}`;m.status===404&&(!this.isModernProtocol()&&f?(this.expireSessionId(f),n+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):this.isModernProtocol()||(n+=". This server does not support HTTP transport. Try using `sse` transport instead"));let r=new M({message:n,statusCode:m.status,url:this.url.href,responseBody:t??void 0});throw(s=this.onerror)==null||s.call(this,r),r}if(!(`id`in e))return;let h=m.headers.get(`content-type`)||``;if(h.includes(`application/json`)){let e=await m.json(),t=Array.isArray(e)?e.map(e=>A(e)):[A(e)];for(let e of t)(c=this.onmessage)==null||c.call(this,e);return}if(h.includes(`text/event-stream`)){if(!m.body){let e=new M({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:m.status,url:this.url.href});throw(l=this.onerror)==null||l.call(this,e),e}let e=m.body.pipeThrough(new TextDecoderStream).pipeThrough(new x).getReader();(async()=>{var n,r,i;try{for(;;){let{done:t,value:i}=await e.read();if(t)return;let{event:a,data:o}=i;if(ln(a))try{let e=await j(o);(n=this.onmessage)==null||n.call(this,e)}catch(e){let t=new M({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(r=this.onerror)==null||r.call(this,t)}}}catch(e){if(t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`)return;(i=this.onerror)==null||i.call(this,e)}})().catch(e=>{var n;t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`||(n=this.onerror)==null||n.call(this,e)});return}let g=new M({message:`MCP HTTP Transport Error: Unexpected content type: ${h}`,statusCode:m.status,url:this.url.href});throw(u=this.onerror)==null||u.call(this,g),g}catch(e){throw t?.signal?.aborted||(d=this.onerror)==null||d.call(this,e),e}};await a()}getStandardRequestHeaders(e){let t={"Mcp-Method":e.method},n=e.params,r=e.method===`resources/read`?n?.uri:e.method===`tools/call`||e.method===`prompts/get`?n?.name:void 0;return typeof r==`string`&&(t[`Mcp-Name`]=an(r)),t}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new M({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},n)}startInboundSse(e=!1,t){this.isModernProtocol()||this.openInboundSse(e,t).catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}async openInboundSse(e=!1,t){var n,r,i,a;if(!this.isModernProtocol())try{let a=this.sessionId,o=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(o[`last-event-id`]=t);let s=await this.fetchFn(this.url.href,{method:`GET`,headers:o,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(s),s.status===401&&this.authProvider&&!e){let{resourceMetadataUrl:e,scope:i}=G(s);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,i)!==`AUTHORIZED`){let e=new B;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(s.status===405)return;if(!s.ok||!s.body){s.status===404&&a&&this.expireSessionId(a);let e=new M({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new x).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),ln(i))try{let t=await j(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new M({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{c.cancel().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}},this.inboundReconnectAttempts=0,l().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||((t=this.onerror)==null||t.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function dn(e){switch(e.type){case`sse`:return new tn(e);case`http`:return new un({...e,initialProtocolVersion:e.initialProtocolVersion??C});default:throw new M({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function fn(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var pn=`io.modelcontextprotocol/ui`,X=`text/html;profile=mcp-app`,mn=`ui/resourceUri`,hn={extensions:{[pn]:{mimeTypes:[X]}}};function gn(e){let n=e?.ui;return t(n)?n:void 0}var Z=s(l()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),_n=a({connectDomains:Z,resourceDomains:Z,frameDomains:Z}),vn=a({prefersBorder:p().optional().catch(void 0),csp:_n.optional().catch(void 0),permissions:n(h(),l()).optional().catch(void 0)});function yn(e){let n=(t(e)?e:void 0)?.ui;if(!t(n))return;let r=vn.safeParse(n);return r.success?r.data:void 0}function bn(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function xn(e){let t=gn(e._meta),n=t?.resourceUri??e._meta?.[mn],r=bn(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function Sn(e){let t=[],n=[];for(let r of e.tools){let e=xn(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function Cn({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(le(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:X,html:r,meta:yn(n._meta)}}async function wn({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Cn({uri:t,resource:await e.readResource({uri:t,options:n})})}var Tn=`1.0.0`,En=0,Dn=1e3,On=[-32020,-32021,-32022],kn=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function An(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function jn(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function Mn(e){let t=An(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(M.isInstance(e)&&e.code!=null)return!1;let n=jn(e);return n!=null&&kn.includes(n)}function Nn(e){if(e==null)return En;if(!Number.isInteger(e))throw new M({message:`maxRetries must be an integer`});if(e<0)throw new M({message:`maxRetries must be >= 0`});return e}function Pn({timeout:e,maxTotalTimeout:t}){return e==null?t:t==null?e:Math.min(e,t)}function Q(e,t){return t==null?e:new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,a)},a=()=>{i(),r(t.reason)};if(t.aborted){a();return}t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{i(),n(e)}).catch(e=>{i(),r(e)})})}function Fn({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function In(e){let t=new Ln(e);return await t.init(),t}var Ln=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Tn,onUncaughtError:i,maxRetries:a,capabilities:o,initialInitializeResult:s,initializationOptions:c,protocolVersionDiscovery:l=!0}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:w,capabilities:{},serverInfo:this._serverInfo},this.protocolEra=`legacy`,this.protocolVersion=w,this.toolHeaderBindings=new Map,this.isClosed=!0,this.onUncaughtError=i,this.maxRetries=Nn(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,this.initializationOptions=c,this.protocolVersionDiscovery=l,this.transport=fn(e)?e:dn(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new M({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){let e=this.initializationOptions?.signal,t=this.initializationOptions?Pn(this.initializationOptions):void 0,n=t==null?void 0:new AbortController,r=e==null?n?.signal:n==null?e:AbortSignal.any([e,n.signal]),i,a;t!=null&&(i=setTimeout(()=>{a=new M({message:`MCP client initialization timed out after ${t}ms`}),n?.abort(a)},t));try{if(this.isClosed=!1,r?.throwIfAborted(),await Q(this.transport.start(),r),this.initialInitializeResult){let e=Te.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}if(this.protocolVersionDiscovery&&this.transport.supportsProtocolVersionDiscovery&&await this.tryProtocolDiscovery(r))return this;this.protocolEra=`legacy`,this.protocolVersion=w,this.setTransportProtocolVersion(this.protocolVersion);let e=await this.request({request:{method:`initialize`,params:{protocolVersion:w,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Te,options:{signal:r}});if(e===void 0)throw new M({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`},{signal:r}),this}catch(t){try{await Q(this.transport.close({signal:r}),r)}catch{}throw this.onClose(),a??(e?.aborted?new M({message:`MCP client initialization was aborted`,cause:e.reason}):t)}finally{i!=null&&clearTimeout(i)}}async tryProtocolDiscovery(e){this.protocolEra=`modern`,this.protocolVersion=C,this.setTransportProtocolVersion(this.protocolVersion);try{let t=await this.request({request:{method:`server/discover`},resultSchema:we,options:{signal:e,timeout:Dn}});return this.applyDiscoverResult(t),!0}catch(e){if(M.isInstance(e)&&e.code!=null&&On.includes(e.code))throw e;return!1}}applyDiscoverResult(e){if(!e.supportedVersions.includes(this.protocolVersion))throw new M({message:`Server does not support the requested protocol version: ${this.protocolVersion}`});let t=e._meta?.[`io.modelcontextprotocol/serverInfo`];typeof t==`object`&&t&&`name`in t&&typeof t.name==`string`&&`version`in t&&typeof t.version==`string`&&(this._serverInfo=t),this.serverCapabilities=e.capabilities,this._serverInstructions=e.instructions,this._initializeResult={protocolVersion:this.protocolVersion,capabilities:e.capabilities,serverInfo:this._serverInfo,instructions:e.instructions}}setTransportProtocolVersion(e){this.transport.setProtocolVersion?this.transport.setProtocolVersion(e):this.transport.protocolVersion=e}applyInitializeResult(e){if(!ve.includes(e.protocolVersion))throw new M({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this.protocolEra=`legacy`,this.protocolVersion=e.protocolVersion,this._serverInfo=e.serverInfo,this._initializeResult=e,this.setTransportProtocolVersion(e.protocolVersion),this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}send(e,t){return t==null?this.transport.send(e):this.transport.send(e,t)}assertCapability(e){switch(e){case`initialize`:case`server/discover`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new M({message:`Server does not support completions`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new M({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new M({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new M({message:`Server does not support prompts`});break;default:throw new M({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new M({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=n==null?void 0:Pn(n),s=o==null?void 0:new AbortController,c=a==null?s?.signal:s==null?a:AbortSignal.any([a,s.signal]),l,u=this.requestMessageId++,d=this.protocolEra===`modern`?{...e,params:{...e.params,_meta:{...e.params?._meta,"io.modelcontextprotocol/protocolVersion":this.protocolVersion,"io.modelcontextprotocol/clientCapabilities":this.clientCapabilities,"io.modelcontextprotocol/clientInfo":this.clientInfo}}}:e,f={...d,jsonrpc:`2.0`,id:u},p=this.getToolRequestHeaders(d),m=()=>{i(new M({message:`Request was aborted`,cause:a?.reason}))},h=()=>{this.responseHandlers.delete(u),a?.removeEventListener(`abort`,_),l!=null&&clearTimeout(l)},g=e=>{h(),i(e)},_=()=>{h(),m()};this.responseHandlers.set(u,e=>{if(a?.aborted)return h(),m();if(e instanceof Error)return g(e);try{if(this.protocolEra===`modern`&&e.result.resultType==null)throw new M({message:`Modern MCP result is missing resultType`});if(e.result.resultType===`input_required`)throw new M({message:`Server requested additional input, but multi round-trip requests are not supported yet`});let n=t.parse(e.result);h(),r(n)}catch(e){let t=M.isInstance(e)?e:new M({message:`Failed to parse server response`,cause:e});g(t)}}),a?.addEventListener(`abort`,_,{once:!0}),o!=null&&(l=setTimeout(()=>{let e=new M({message:`Request timed out after ${o}ms`});s?.abort(e),g(e)},o));let v={...c==null?{}:{signal:c},...p==null?{}:{headers:p}};(Object.keys(v).length===0?this.send(f):this.send(f,v)).catch(e=>{g(e)})})}async listTools({params:e,options:t}={}){let n=await this.request({request:{method:`tools/list`,params:e},resultSchema:De,options:t});return this.prepareToolDefinitions(n,e?.cursor==null)}prepareToolDefinitions(e,t=!1){if(this.protocolEra!==`modern`||!this.transport.supportsMcpToolParameterHeaders)return e;t&&this.toolHeaderBindings.clear();let n=e.tools.filter(e=>{let t=on(e.inputSchema);return t.success?(this.toolHeaderBindings.set(e.name,t.bindings),!0):(this.onError(new M({message:`Ignoring MCP tool "${e.name}": ${t.error}`})),!1)});return{...e,tools:n}}getToolRequestHeaders(e){if(this.protocolEra!==`modern`||e.method!==`tools/call`||typeof e.params?.name!=`string`)return;let t=this.toolHeaderBindings.get(e.params.name);if(t==null||t.length===0)return;let n=e.params.arguments;if(typeof n==`object`&&n&&!Array.isArray(n))try{return cn({bindings:t,args:n})}catch(t){throw new M({message:`Failed to create MCP headers for tool "${e.params.name}"`,cause:t})}}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():ie({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:Mn,createRetryError:({message:e,errors:t})=>new M({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){try{return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:Be,options:n})})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:je,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Ue,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:He,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Xe,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Qe,options:n})}catch(e){throw e}}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:qe,options:e})}async notification(e,t){let n={...e,jsonrpc:`2.0`};await Q(this.send(n,t?.signal==null?void 0:{signal:t.signal}),t?.signal)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools(),n=[...t.tools];for(;t.nextCursor!=null;)t=await this.listTools({params:{cursor:t.nextCursor}}),n.push(...t.tools);return this.toolsFromDefinitions({...t,tools:n},{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){e=this.prepareToolDefinitions(e);let n={};for(let{name:r,title:i,description:a,inputSchema:o,annotations:s,_meta:c}of e.tools){let e=i??s?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let l=this,u=t===`automatic`?void 0:t[r]?.outputSchema,d=xn({_meta:c}),f={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...s==null?{}:{annotations:{...s.title==null?{}:{title:s.title},...s.readOnlyHint==null?{}:{readOnlyHint:s.readOnlyHint},...s.destructiveHint==null?{}:{destructiveHint:s.destructiveHint},...s.idempotentHint==null?{}:{idempotentHint:s.idempotentHint},...s.openWorldHint==null?{}:{openWorldHint:s.openWorldHint}}},...d?.resourceUri==null?{}:{app:{...d,mimeType:X}}},p=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await l.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||u==null?i:l.extractStructuredContent(i,u,r)};n[r]={...t===`automatic`?ee({description:a,title:e,metadata:f,inputSchema:v({...o,properties:o.properties??{},additionalProperties:!1}),execute:p,toModelOutput:Fn}):ue({description:a,title:e,metadata:f,inputSchema:t[r].inputSchema,...u==null?{}:{outputSchema:u},execute:p,toModelOutput:Fn}),_meta:c}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await oe({value:e.structuredContent,schema:ce(t)});if(!r.success)throw new M({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await ne({text:r.text,schema:t});if(!e.success)throw new M({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new M({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==O)throw new M({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=O.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=et.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new M({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){if(e.id==null){this.onError(new M({message:`Protocol error: Received a response without a message ID: ${JSON.stringify(e)}`}));return}let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new M({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new M({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},Rn=new TextEncoder;function $(e){if(typeof e!=`object`||!e)return JSON.stringify(e??null);if(Array.isArray(e))return`[${e.map($).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${$(t[e])}`).join(`,`)}}`}function zn(e){return re(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function Bn(e){let t=await crypto.subtle.digest(`SHA-256`,Rn.encode($({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return zn(new Uint8Array(t))}function Vn(e,t){return e!==t}export{et as ElicitResultSchema,O as ElicitationRequestSchema,X as MCP_APP_MIME_TYPE,B as UnauthorizedError,J as auth,In as createMCPClient,In as experimental_createMCPClient,Vn as detectMCPAppResourceDrift,Bn as fingerprintMCPAppResource,hn as mcpAppClientCapabilities,wn as readMCPAppResource,Sn as splitMCPAppTools,A as validateJSONRPCMessage};