experimental-ash 0.30.0 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/src/cli/run.d.ts +0 -1
- package/dist/src/cli/run.js +2 -2
- package/dist/src/compiled/.vendor-stamp.json +6 -6
- package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +2 -2
- package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
- package/dist/src/compiled/@ai-sdk/anthropic/package.json +1 -1
- package/dist/src/compiled/@ai-sdk/google/index.d.ts +14 -1
- package/dist/src/compiled/@ai-sdk/google/index.js +6 -6
- package/dist/src/compiled/@ai-sdk/google/package.json +1 -1
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/mcp/package.json +1 -1
- package/dist/src/compiled/@ai-sdk/openai/index.js +2 -2
- package/dist/src/compiled/@ai-sdk/openai/package.json +1 -1
- package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/otel/package.json +1 -1
- package/dist/src/compiled/@vercel/sandbox/index.d.ts +34 -11
- package/dist/src/compiled/_chunks/workflow/{dist-DZZY3Zyp.js → dist-Dl-X5RB3.js} +1 -1
- package/dist/src/compiled/just-bash/index.d.ts +48 -0
- package/dist/src/execution/await-authorization-orchestrator.d.ts +2 -0
- package/dist/src/execution/await-authorization-orchestrator.js +1 -1
- package/dist/src/execution/code-mode-authorization-lifecycle.d.ts +15 -0
- package/dist/src/execution/code-mode-authorization-lifecycle.js +1 -0
- package/dist/src/execution/connection-auth-steps.d.ts +15 -0
- package/dist/src/execution/connection-auth-steps.js +1 -1
- package/dist/src/execution/connection-auth-tool-result.d.ts +2 -0
- package/dist/src/execution/connection-auth-tool-result.js +1 -0
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/node-step.d.ts +12 -1
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/sandbox/bash-tool.js +1 -1
- package/dist/src/execution/sandbox/bindings/local.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/sandbox/glob-tool.js +1 -1
- package/dist/src/execution/sandbox/grep-tool.js +1 -1
- package/dist/src/execution/sandbox/ripgrep-probe.js +1 -1
- package/dist/src/execution/sandbox/session.d.ts +3 -1
- package/dist/src/execution/sandbox/session.js +1 -1
- package/dist/src/execution/sandbox/shell-quote.d.ts +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-callback-url.d.ts +12 -0
- package/dist/src/execution/workflow-callback-url.js +1 -0
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-steps.d.ts +2 -0
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/code-mode-approval.d.ts +22 -0
- package/dist/src/harness/code-mode-approval.js +1 -0
- package/dist/src/harness/code-mode.d.ts +31 -0
- package/dist/src/harness/code-mode.js +1 -0
- package/dist/src/harness/input-extraction.js +1 -1
- package/dist/src/harness/step-hooks.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/host/build-application.js +1 -1
- package/dist/src/internal/nitro/host/code-mode-worker-asset.d.ts +18 -0
- package/dist/src/internal/nitro/host/code-mode-worker-asset.js +1 -0
- package/dist/src/internal/nitro/host/configure-nitro-routes.js +3 -3
- package/dist/src/internal/nitro/host/create-application-nitro.d.ts +0 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.d.ts +0 -1
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
- package/dist/src/internal/nitro/host/dispatch-schedule-in-dev.d.ts +41 -0
- package/dist/src/internal/nitro/host/dispatch-schedule-in-dev.js +1 -0
- package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
- package/dist/src/internal/nitro/host/start-development-server.d.ts +6 -1
- package/dist/src/internal/nitro/host/start-development-server.js +1 -1
- package/dist/src/internal/nitro/routes/dev-schedule-dispatch.d.ts +15 -0
- package/dist/src/internal/nitro/routes/dev-schedule-dispatch.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/approval-continuation.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/approval-response.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/code-mode-tool.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/continuation-capability.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/errors.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/fetch-policy.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/host-interrupt.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/index.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/interrupt-continuation.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/options.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/run-code-mode.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/runtime/manager.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/runtime/max-workers.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/runtime-assets.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/serialization.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/source-cache.js +4 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/telemetry.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/tool-invocation.js +1 -0
- package/dist/src/node_modules/.pnpm/experimental-ai-sdk-code-mode@1.0.7_ai@7.0.0-canary.154_zod@4.4.3_/node_modules/experimental-ai-sdk-code-mode/dist/tool-prompt.js +9 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/index.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js +3 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js +2 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js +60 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js +3 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js +1 -0
- package/dist/src/node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js +1 -0
- package/dist/src/protocol/routes.d.ts +20 -0
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/definitions/sandbox.d.ts +1 -1
- package/dist/src/public/sandbox/index.d.ts +1 -1
- package/dist/src/runtime/agent/mock-model-adapter.js +4 -3
- package/dist/src/runtime/framework-tools/code-mode-connection-auth.d.ts +32 -0
- package/dist/src/runtime/framework-tools/code-mode-connection-auth.js +1 -0
- package/dist/src/runtime/framework-tools/connection-search.d.ts +3 -0
- package/dist/src/runtime/framework-tools/connection-search.js +1 -1
- package/dist/src/runtime/framework-tools/connection-tools.d.ts +18 -1
- package/dist/src/runtime/framework-tools/connection-tools.js +1 -1
- package/dist/src/runtime/resolve-agent-graph.js +1 -1
- package/dist/src/shared/code-mode.d.ts +2 -0
- package/dist/src/shared/code-mode.js +1 -0
- package/dist/src/shared/sandbox-session.d.ts +38 -10
- package/package.json +9 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{Bi as n}from"../../_chunks/workflow/core-XWIi7wKc.js";import{At as r,Dt as i,En as a,Et as o,Nn as s,Rn as c,Tn as l,Tt as u,Xn as d,Zn as f,dn as p,fn as m,wn as h}from"../../_chunks/workflow/schemas-DmgDnhW3.js";import{n as ee}from"../../_chunks/workflow/compat-DcEvieoj.js";import{F as te,G as ne,H as re,O as ie,Q as g,S as _,U as ae,i as oe,n as se,q as v,y as ce}from"../../_chunks/workflow/dist-DZZY3Zyp.js";let y;y=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function le(e){return(await y).getRandomValues(new Uint8Array(e))}async function ue(e){let t=``;for(;t.length<e;){let n=await le(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function de(e){return await ue(e)}async function fe(e){let t=await(await y).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function pe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await de(e);return{code_verifier:t,code_challenge:await fe(t)}}var me=`vercel.ai.error.AI_MCPClientError`,he=Symbol.for(me),ge,_e,b=class extends (_e=e,ge=he,_e){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i}){super({name:e,message:t,cause:n}),this[ge]=!0,this.data=r,this.code=i}static isInstance(t){return e.hasMarker(t,me)}},x=`2025-11-25`,ve=[x,`2025-06-18`,`2025-03-26`,`2024-11-05`],ye=a(s(c(),f())),be=m({name:c(),version:c(),title:a(c())}),S=m({_meta:a(l({}).loose())}),C=S,w=l({method:c(),params:a(S)}),T=l({applyDefaults:a(r())}).loose(),xe=m({experimental:a(l({}).loose()),logging:a(l({}).loose()),prompts:a(m({listChanged:a(r())})),resources:a(m({subscribe:a(r()),listChanged:a(r())})),tools:a(m({listChanged:a(r())})),elicitation:a(T)});l({elicitation:a(T)}).loose();var Se=C.extend({protocolVersion:c(),capabilities:xe,serverInfo:be,instructions:a(c())}),E=C.extend({nextCursor:a(c())}),Ce=l({name:c(),title:a(c()),description:a(c()),inputSchema:l({type:p(`object`),properties:a(l({}).loose())}).loose(),outputSchema:a(l({}).loose()),annotations:a(l({title:a(c())}).loose()),_meta:ye}).loose(),we=E.extend({tools:o(Ce)}),D=l({type:p(`text`),text:c()}).loose(),O=l({type:p(`image`),data:i(),mimeType:c()}).loose(),Te=l({uri:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c()),size:a(h())}).loose(),Ee=E.extend({resources:o(Te)}),k=l({uri:c(),name:a(c()),title:a(c()),mimeType:a(c())}).loose(),A=k.extend({text:c()}),j=k.extend({blob:i()}),M=l({type:p(`resource`),resource:d([A,j])}).loose(),N=l({type:p(`resource_link`),uri:c(),name:c(),description:a(c()),mimeType:a(c())}).loose(),De=C.extend({content:o(d([D,O,M,N])),structuredContent:a(f()),isError:r().default(!1).optional()}).or(C.extend({toolResult:f()})),Oe=l({uriTemplate:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c())}).loose(),ke=C.extend({resourceTemplates:o(Oe)}),Ae=C.extend({contents:o(d([A,j]))}),je=l({name:c(),description:a(c()),required:a(r())}).loose(),Me=l({name:c(),title:a(c()),description:a(c()),arguments:a(o(je))}).loose(),Ne=E.extend({prompts:o(Me)}),Pe=l({role:d([p(`user`),p(`assistant`)]),content:d([D,O,M,N])}).loose(),Fe=C.extend({description:a(c()),messages:o(Pe)}),Ie=S.extend({message:c(),requestedSchema:f()}),P=w.extend({method:p(`elicitation/create`),params:Ie}),F=C.extend({action:d([p(`accept`),p(`decline`),p(`cancel`)]),content:a(s(c(),f()))}),I=`2.0`,Le=l({jsonrpc:p(I),id:d([c(),h().int()])}).merge(w).strict(),Re=l({jsonrpc:p(I),id:d([c(),h().int()]),result:C}).strict(),ze=l({jsonrpc:p(I),id:d([c(),h().int()]),error:l({code:h().int(),message:c(),data:a(f())})}).strict(),L=d([Le,l({jsonrpc:p(I)}).merge(l({method:c(),params:a(S)})).strict(),Re,ze]);async function R(e){return L.parse(await te({text:e}))}var Be=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,Ve=l({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:h().optional(),scope:c().optional(),refresh_token:c().optional()}).strip(),z=c().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ee.custom,message:`URL must be parseable`,fatal:!0}),n}).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`}),He=l({resource:c().url(),authorization_servers:o(z).optional(),jwks_uri:c().url().optional(),scopes_supported:o(c()).optional(),bearer_methods_supported:o(c()).optional(),resource_signing_alg_values_supported:o(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:r().optional(),authorization_details_types_supported:o(c()).optional(),dpop_signing_alg_values_supported:o(c()).optional(),dpop_bound_access_tokens_required:r().optional()}).passthrough(),Ue=l({issuer:c(),authorization_endpoint:z,token_endpoint:z,registration_endpoint:z.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),code_challenge_methods_supported:o(c()),token_endpoint_auth_methods_supported:o(c()).optional(),token_endpoint_auth_signing_alg_values_supported:o(c()).optional()}).passthrough(),We=l({issuer:c(),authorization_endpoint:z,token_endpoint:z,userinfo_endpoint:z.optional(),jwks_uri:z,registration_endpoint:z.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),subject_types_supported:o(c()),id_token_signing_alg_values_supported:o(c()),claims_supported:o(c()).optional(),token_endpoint_auth_methods_supported:o(c()).optional()}).passthrough().merge(Ue.pick({code_challenge_methods_supported:!0})),Ge=l({client_id:c(),client_secret:c().optional(),client_id_issued_at:h().optional(),client_secret_expires_at:h().optional()}).strip(),Ke=l({redirect_uris:o(z),token_endpoint_auth_method:c().optional(),grant_types:o(c()).optional(),response_types:o(c()).optional(),client_name:c().optional(),client_uri:z.optional(),logo_uri:z.optional(),scope:c().optional(),contacts:o(c()).optional(),tos_uri:z.optional(),policy_uri:c().optional(),jwks_uri:z.optional(),jwks:u().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),qe=l({error:c(),error_description:c().optional(),error_uri:c().optional()}),Je=Ke.merge(Ge),Ye=`vercel.ai.error.AI_MCPClientOAuthError`,Xe=Symbol.for(Ye),Ze,Qe,B=class extends (Qe=e,Ze=Xe,Qe){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[Ze]=!0}static isInstance(t){return e.hasMarker(t,Ye)}},V=class extends B{};V.errorCode=`server_error`;var H=class extends B{};H.errorCode=`invalid_client`;var U=class extends B{};U.errorCode=`invalid_grant`;var W=class extends B{};W.errorCode=`unauthorized_client`;var $e={[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U,[W.errorCode]:W};function et(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function G(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 K=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function q(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=t.match(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function nt(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?J(e,void 0,n):void 0;throw r}}async function rt(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function it(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function at(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??x,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=nt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await rt(o,a,n);return!r?.metadataUrl&&it(s,i.pathname)&&(s=await rt(new URL(`/.well-known/${t}`,i),a,n)),s}async function ot(e,t,n=fetch){let r=await at(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 He.parse(await r.json())}function st(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function ct(e,{fetchFn:t=fetch,protocolVersion:n=x}={}){let r={"MCP-Protocol-Version":n},i=st(e);for(let{url:e,type:n}of i){let i=await J(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`)return Ue.parse(await i.json());{let t=We.parse(await i.json());if(!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 lt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await pe(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,G(o)),{authorizationUrl:l,codeVerifier:d}}function ut(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 dt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:ft(i,a,n);return;case`client_secret_post`:pt(i,a,r);return;case`none`:mt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function ft(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function pt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function mt(e,t){t.set(`client_id`,e)}async function Y(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=qe.parse(await te({text:n}));return new($e[e]||V)({message:t||``,cause:r})}catch(e){return new V({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function ht(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?s(d,f,e,t):dt(ut(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,G(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await Y(p);return Ve.parse(await p.json())}async function gt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?a(l,u,e,t):dt(ut(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,G(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await Y(d);return Ve.parse({refresh_token:r,...await d.json()})}async function _t(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Y(a);return Je.parse(await a.json())}async function X(e,t){try{return await Z(e,t)}catch(n){if(n instanceof H||n instanceof W)return await e.invalidateCredentials?.call(e,`all`),await Z(e,t);if(n instanceof U)return await e.invalidateCredentials?.call(e,`tokens`),await Z(e,t);throw n}}async function vt(e,t,n){let r=et(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 Z(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;try{s=await ot(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await vt(t,e,s),u=await ct(c,{fetchFn:o}),d=await Promise.resolve(e.clientInformation());if(!d){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`);let t=await _t(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o});await e.saveClientInformation(t),d=t}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 e.codeVerifier(),i=await ht(c,{metadata:u,clientInformation:d,authorizationCode:n,codeVerifier:t,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(i),`AUTHORIZED`}let f=await e.tokens();if(f?.refresh_token)try{let t=await gt(c,{metadata:u,clientInformation:d,refreshToken:f.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof B)||e instanceof V))throw e}let p=e.state?await e.state():void 0;p&&e.saveState&&await e.saveState(p);let{authorizationUrl:m,codeVerifier:h}=await lt(c,{metadata:u,clientInformation:d,state:p,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(m),`REDIRECT`}var yt=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}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??x};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return v(t,`ai-sdk/${Be}`,_())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;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 b({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader(),u=async()=>{var n,r,i;try{for(;;){let{done:t,value:i}=await l.read();if(t){if(this.connected)throw this.connected=!1,new b({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:a,data:o}=i;if(a===`endpoint`){if(this.endpoint=new URL(o,this.url),this.endpoint.origin!==this.url.origin)throw new b({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(a===`message`)try{let e=await R(o);(n=this.onmessage)==null||n.call(this,e)}catch(e){let t=new b({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(r=this.onerror)==null||r.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(i=this.onerror)==null||i.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,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new b({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new b({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}},bt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??x};if(this.sessionId&&(t[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return v(t,`ai-sdk/${Be}`,_())}async start(){if(this.abortController)throw new b({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(n=!1)=>{var r,i,a,o,s,c;try{let c={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`,Accept:`application/json, text/event-stream`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},l=await this.fetchFn(this.url.href,c),u=l.headers.get(`mcp-session-id`);if(u&&(this.sessionId=u),l.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=q(l);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`)throw new K}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(l.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!l.ok){let e=await l.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${l.status}): ${e}`;l.status===404&&(t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new b({message:t});throw(i=this.onerror)==null||i.call(this,n),n}if(!(`id`in e))return;let d=l.headers.get(`content-type`)||``;if(d.includes(`application/json`)){let e=await l.json(),t=Array.isArray(e)?e.map(e=>L.parse(e)):[L.parse(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(d.includes(`text/event-stream`)){if(!l.body){let e=new b({message:`MCP HTTP Transport Error: text/event-stream response without body`});throw(o=this.onerror)==null||o.call(this,e),e}let e=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(a===`message`)try{let e=await R(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})();return}let f=new b({message:`MCP HTTP Transport Error: Unexpected content type: ${d}`});throw(s=this.onerror)==null||s.call(this,f),f}catch(e){throw(c=this.onerror)==null||c.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new b({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=await this.commonHeaders({Accept:`text/event-stream`});t&&(a[`last-event-id`]=t);let o=await this.fetchFn(this.url.href,{method:`GET`,headers:a,signal:this.abortController?.signal,redirect:this.redirectMode}),s=o.headers.get(`mcp-session-id`);if(s&&(this.sessionId=s),o.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(o);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;(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(o.status===405)return;if(!o.ok||!o.body){let e=new b({message:`MCP HTTP Transport Error: GET SSE failed: ${o.status} ${o.statusText}`});(i=this.onerror)==null||i.call(this,e);return}let c=o.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).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),i===`message`)try{let t=await R(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new b({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()},this.inboundReconnectAttempts=0,l()}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 xt(e){switch(e.type){case`sse`:return new yt(e);case`http`:return new bt(e);default:throw new b({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function St(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Ct=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,wt=`ui/resourceUri`,Tt={extensions:{[Ct]:{mimeTypes:[Q]}}};function Et(e){let n=e?.ui;return t(n)?n:void 0}function Dt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Ot(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function kt(e){let t=Et(e._meta),n=t?.resourceUri??e._meta?.[wt],r=Ot(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 At(e){let t=[],n=[];for(let r of e.tools){let e=kt(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 jt({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(oe(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:Dt(n._meta)}}async function Mt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return jt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Nt=`1.0.0`;function Pt({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function $(e){let t=new Ft(e);return await t.init(),t}var Ft=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Nt,onUncaughtError:i,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},St(e)?this.transport=e:this.transport=xt(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 b({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:`initialize`,params:{protocolVersion:x,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Se});if(e===void 0)throw new b({message:`Server sent invalid initialize result`});if(!ve.includes(e.protocolVersion))throw new b({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions,await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new b({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new b({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new b({message:`Server does not support prompts`});break;default:throw new b({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new b({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new b({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new b({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:we,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:De,options:n})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:Ee,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Ae,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:ke,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Ne,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:Fe,options:n})}catch(e){throw e}}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:a,inputSchema:o,annotations:s,_meta:c}of e.tools){let e=i??s?.title;if(t!==`automatic`&&!(r in t))continue;let l=this,u=t===`automatic`?void 0:t[r]?.outputSchema,d=kt({_meta:c}),f={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...d?.resourceUri==null?{}:{app:{...d,mimeType:Q}}},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`?ce({description:a,title:e,metadata:f,inputSchema:ie({...o,properties:o.properties??{},additionalProperties:!1}),execute:p,toModelOutput:Pt}):ne({description:a,title:e,metadata:f,inputSchema:t[r].inputSchema,...u==null?{}:{outputSchema:u},execute:p,toModelOutput:Pt}),_meta:c}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await ae({value:e.structuredContent,schema:se(t)});if(!r.success)throw new b({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 re({text:r.text,schema:t});if(!e.success)throw new b({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new b({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}onElicitationRequest(e,t){if(e!==P)throw new b({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{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=P.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=F.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 b({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new b({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new b({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{F as ElicitResultSchema,P as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,K as UnauthorizedError,X as auth,$ as createMCPClient,$ as experimental_createMCPClient,Tt as mcpAppClientCapabilities,Mt as readMCPAppResource,At as splitMCPAppTools};
|
|
1
|
+
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{Bi as n}from"../../_chunks/workflow/core-XWIi7wKc.js";import{At as r,Dt as i,En as a,Et as o,Nn as s,Rn as c,Tn as l,Tt as u,Xn as d,Zn as f,dn as p,fn as m,wn as h}from"../../_chunks/workflow/schemas-DmgDnhW3.js";import{n as ee}from"../../_chunks/workflow/compat-DcEvieoj.js";import{F as te,G as ne,H as re,O as ie,Q as g,S as _,U as ae,i as oe,n as se,q as v,y as ce}from"../../_chunks/workflow/dist-Dl-X5RB3.js";let y;y=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function le(e){return(await y).getRandomValues(new Uint8Array(e))}async function ue(e){let t=``;for(;t.length<e;){let n=await le(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function de(e){return await ue(e)}async function fe(e){let t=await(await y).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function pe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await de(e);return{code_verifier:t,code_challenge:await fe(t)}}var me=`vercel.ai.error.AI_MCPClientError`,he=Symbol.for(me),ge,_e,b=class extends (_e=e,ge=he,_e){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[ge]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,me)}},x=`2025-11-25`,ve=[x,`2025-06-18`,`2025-03-26`,`2024-11-05`],ye=a(s(c(),f())),be=m({name:c(),version:c(),title:a(c())}),S=m({_meta:a(l({}).loose())}),C=S,w=l({method:c(),params:a(S)}),T=l({applyDefaults:a(r())}).loose(),xe=m({experimental:a(l({}).loose()),logging:a(l({}).loose()),prompts:a(m({listChanged:a(r())})),resources:a(m({subscribe:a(r()),listChanged:a(r())})),tools:a(m({listChanged:a(r())})),elicitation:a(T)});l({elicitation:a(T)}).loose();var Se=C.extend({protocolVersion:c(),capabilities:xe,serverInfo:be,instructions:a(c())}),E=C.extend({nextCursor:a(c())}),Ce=l({name:c(),title:a(c()),description:a(c()),inputSchema:l({type:p(`object`),properties:a(l({}).loose())}).loose(),outputSchema:a(l({}).loose()),annotations:a(l({title:a(c())}).loose()),_meta:ye}).loose(),we=E.extend({tools:o(Ce)}),D=l({type:p(`text`),text:c()}).loose(),O=l({type:p(`image`),data:i(),mimeType:c()}).loose(),Te=l({uri:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c()),size:a(h())}).loose(),Ee=E.extend({resources:o(Te)}),k=l({uri:c(),name:a(c()),title:a(c()),mimeType:a(c())}).loose(),A=k.extend({text:c()}),j=k.extend({blob:i()}),M=l({type:p(`resource`),resource:d([A,j])}).loose(),N=l({type:p(`resource_link`),uri:c(),name:c(),description:a(c()),mimeType:a(c())}).loose(),De=C.extend({content:o(d([D,O,M,N])),structuredContent:a(f()),isError:r().default(!1).optional()}).or(C.extend({toolResult:f()})),Oe=l({uriTemplate:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c())}).loose(),ke=C.extend({resourceTemplates:o(Oe)}),Ae=C.extend({contents:o(d([A,j]))}),je=l({name:c(),description:a(c()),required:a(r())}).loose(),Me=l({name:c(),title:a(c()),description:a(c()),arguments:a(o(je))}).loose(),Ne=E.extend({prompts:o(Me)}),Pe=l({role:d([p(`user`),p(`assistant`)]),content:d([D,O,M,N])}).loose(),Fe=C.extend({description:a(c()),messages:o(Pe)}),Ie=S.extend({message:c(),requestedSchema:f()}),P=w.extend({method:p(`elicitation/create`),params:Ie}),F=C.extend({action:d([p(`accept`),p(`decline`),p(`cancel`)]),content:a(s(c(),f()))}),I=`2.0`,Le=l({jsonrpc:p(I),id:d([c(),h().int()])}).merge(w).strict(),Re=l({jsonrpc:p(I),id:d([c(),h().int()]),result:C}).strict(),ze=l({jsonrpc:p(I),id:d([c(),h().int()]),error:l({code:h().int(),message:c(),data:a(f())})}).strict(),L=d([Le,l({jsonrpc:p(I)}).merge(l({method:c(),params:a(S)})).strict(),Re,ze]);async function R(e){return L.parse(await te({text:e}))}var Be=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,Ve=l({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:h().optional(),scope:c().optional(),refresh_token:c().optional()}).strip(),z=c().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ee.custom,message:`URL must be parseable`,fatal:!0}),n}).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`}),He=l({resource:c().url(),authorization_servers:o(z).optional(),jwks_uri:c().url().optional(),scopes_supported:o(c()).optional(),bearer_methods_supported:o(c()).optional(),resource_signing_alg_values_supported:o(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:r().optional(),authorization_details_types_supported:o(c()).optional(),dpop_signing_alg_values_supported:o(c()).optional(),dpop_bound_access_tokens_required:r().optional()}).passthrough(),Ue=l({issuer:c(),authorization_endpoint:z,token_endpoint:z,registration_endpoint:z.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),code_challenge_methods_supported:o(c()),token_endpoint_auth_methods_supported:o(c()).optional(),token_endpoint_auth_signing_alg_values_supported:o(c()).optional()}).passthrough(),We=l({issuer:c(),authorization_endpoint:z,token_endpoint:z,userinfo_endpoint:z.optional(),jwks_uri:z,registration_endpoint:z.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),subject_types_supported:o(c()),id_token_signing_alg_values_supported:o(c()),claims_supported:o(c()).optional(),token_endpoint_auth_methods_supported:o(c()).optional()}).passthrough().merge(Ue.pick({code_challenge_methods_supported:!0})),Ge=l({client_id:c(),client_secret:c().optional(),client_id_issued_at:h().optional(),client_secret_expires_at:h().optional()}).strip(),Ke=l({redirect_uris:o(z),token_endpoint_auth_method:c().optional(),grant_types:o(c()).optional(),response_types:o(c()).optional(),client_name:c().optional(),client_uri:z.optional(),logo_uri:z.optional(),scope:c().optional(),contacts:o(c()).optional(),tos_uri:z.optional(),policy_uri:c().optional(),jwks_uri:z.optional(),jwks:u().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),qe=l({error:c(),error_description:c().optional(),error_uri:c().optional()}),Je=Ke.merge(Ge),Ye=`vercel.ai.error.AI_MCPClientOAuthError`,Xe=Symbol.for(Ye),Ze,Qe,B=class extends (Qe=e,Ze=Xe,Qe){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[Ze]=!0}static isInstance(t){return e.hasMarker(t,Ye)}},V=class extends B{};V.errorCode=`server_error`;var H=class extends B{};H.errorCode=`invalid_client`;var U=class extends B{};U.errorCode=`invalid_grant`;var W=class extends B{};W.errorCode=`unauthorized_client`;var $e={[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U,[W.errorCode]:W};function et(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function G(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 K=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function q(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=t.match(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function nt(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?J(e,void 0,n):void 0;throw r}}async function rt(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function it(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function at(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??x,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=nt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await rt(o,a,n);return!r?.metadataUrl&&it(s,i.pathname)&&(s=await rt(new URL(`/.well-known/${t}`,i),a,n)),s}async function ot(e,t,n=fetch){let r=await at(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 He.parse(await r.json())}function st(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function ct(e,{fetchFn:t=fetch,protocolVersion:n=x}={}){let r={"MCP-Protocol-Version":n},i=st(e);for(let{url:e,type:n}of i){let i=await J(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`)return Ue.parse(await i.json());{let t=We.parse(await i.json());if(!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 lt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await pe(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,G(o)),{authorizationUrl:l,codeVerifier:d}}function ut(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 dt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:ft(i,a,n);return;case`client_secret_post`:pt(i,a,r);return;case`none`:mt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function ft(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function pt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function mt(e,t){t.set(`client_id`,e)}async function Y(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=qe.parse(await te({text:n}));return new($e[e]||V)({message:t||``,cause:r})}catch(e){return new V({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function ht(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?s(d,f,e,t):dt(ut(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,G(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await Y(p);return Ve.parse(await p.json())}async function gt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?a(l,u,e,t):dt(ut(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,G(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await Y(d);return Ve.parse({refresh_token:r,...await d.json()})}async function _t(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Y(a);return Je.parse(await a.json())}async function X(e,t){try{return await Z(e,t)}catch(n){if(n instanceof H||n instanceof W)return await e.invalidateCredentials?.call(e,`all`),await Z(e,t);if(n instanceof U)return await e.invalidateCredentials?.call(e,`tokens`),await Z(e,t);throw n}}async function vt(e,t,n){let r=et(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 Z(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;try{s=await ot(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await vt(t,e,s),u=await ct(c,{fetchFn:o}),d=await Promise.resolve(e.clientInformation());if(!d){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`);let t=await _t(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o});await e.saveClientInformation(t),d=t}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 e.codeVerifier(),i=await ht(c,{metadata:u,clientInformation:d,authorizationCode:n,codeVerifier:t,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(i),`AUTHORIZED`}let f=await e.tokens();if(f?.refresh_token)try{let t=await gt(c,{metadata:u,clientInformation:d,refreshToken:f.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof B)||e instanceof V))throw e}let p=e.state?await e.state():void 0;p&&e.saveState&&await e.saveState(p);let{authorizationUrl:m,codeVerifier:h}=await lt(c,{metadata:u,clientInformation:d,state:p,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(m),`REDIRECT`}var yt=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}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??x};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return v(t,`ai-sdk/${Be}`,_())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;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 b({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader(),u=async()=>{var n,r,i;try{for(;;){let{done:t,value:i}=await l.read();if(t){if(this.connected)throw this.connected=!1,new b({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:a,data:o}=i;if(a===`endpoint`){if(this.endpoint=new URL(o,this.url),this.endpoint.origin!==this.url.origin)throw new b({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(a===`message`)try{let e=await R(o);(n=this.onmessage)==null||n.call(this,e)}catch(e){let t=new b({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(r=this.onerror)==null||r.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(i=this.onerror)==null||i.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,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new b({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new b({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}},bt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??x};if(this.sessionId&&(t[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return v(t,`ai-sdk/${Be}`,_())}authorizeOnce(e){return this.authProvider?(this.authPromise||=X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new b({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(n=!1)=>{var r,i,a,o,s,c;try{let c={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`,Accept:`application/json, text/event-stream`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},l=await this.fetchFn(this.url.href,c),u=l.headers.get(`mcp-session-id`);if(u&&(this.sessionId=u),l.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=q(l);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new K}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(l.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!l.ok){let e=await l.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${l.status}): ${e}`;l.status===404&&(t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new b({message:t,statusCode:l.status,url:this.url.href,responseBody:e??void 0});throw(i=this.onerror)==null||i.call(this,n),n}if(!(`id`in e))return;let d=l.headers.get(`content-type`)||``;if(d.includes(`application/json`)){let e=await l.json(),t=Array.isArray(e)?e.map(e=>L.parse(e)):[L.parse(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(d.includes(`text/event-stream`)){if(!l.body){let e=new b({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:l.status,url:this.url.href});throw(o=this.onerror)==null||o.call(this,e),e}let e=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(a===`message`)try{let e=await R(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})();return}let f=new b({message:`MCP HTTP Transport Error: Unexpected content type: ${d}`,statusCode:l.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,f),f}catch(e){throw(c=this.onerror)==null||c.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new b({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=await this.commonHeaders({Accept:`text/event-stream`});t&&(a[`last-event-id`]=t);let o=await this.fetchFn(this.url.href,{method:`GET`,headers:a,signal:this.abortController?.signal,redirect:this.redirectMode}),s=o.headers.get(`mcp-session-id`);if(s&&(this.sessionId=s),o.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(o);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new K;(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(o.status===405)return;if(!o.ok||!o.body){let e=new b({message:`MCP HTTP Transport Error: GET SSE failed: ${o.status} ${o.statusText}`,statusCode:o.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=o.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).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),i===`message`)try{let t=await R(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new b({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()},this.inboundReconnectAttempts=0,l()}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 xt(e){switch(e.type){case`sse`:return new yt(e);case`http`:return new bt(e);default:throw new b({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function St(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Ct=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,wt=`ui/resourceUri`,Tt={extensions:{[Ct]:{mimeTypes:[Q]}}};function Et(e){let n=e?.ui;return t(n)?n:void 0}function Dt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Ot(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function kt(e){let t=Et(e._meta),n=t?.resourceUri??e._meta?.[wt],r=Ot(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 At(e){let t=[],n=[];for(let r of e.tools){let e=kt(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 jt({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(oe(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:Dt(n._meta)}}async function Mt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return jt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Nt=`1.0.0`;function Pt({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function $(e){let t=new Ft(e);return await t.init(),t}var Ft=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Nt,onUncaughtError:i,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},St(e)?this.transport=e:this.transport=xt(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 b({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:`initialize`,params:{protocolVersion:x,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Se});if(e===void 0)throw new b({message:`Server sent invalid initialize result`});if(!ve.includes(e.protocolVersion))throw new b({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions,await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new b({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new b({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new b({message:`Server does not support prompts`});break;default:throw new b({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new b({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new b({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new b({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:we,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:De,options:n})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:Ee,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Ae,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:ke,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Ne,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:Fe,options:n})}catch(e){throw e}}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:a,inputSchema:o,annotations:s,_meta:c}of e.tools){let e=i??s?.title;if(t!==`automatic`&&!(r in t))continue;let l=this,u=t===`automatic`?void 0:t[r]?.outputSchema,d=kt({_meta:c}),f={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...d?.resourceUri==null?{}:{app:{...d,mimeType:Q}}},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`?ce({description:a,title:e,metadata:f,inputSchema:ie({...o,properties:o.properties??{},additionalProperties:!1}),execute:p,toModelOutput:Pt}):ne({description:a,title:e,metadata:f,inputSchema:t[r].inputSchema,...u==null?{}:{outputSchema:u},execute:p,toModelOutput:Pt}),_meta:c}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await ae({value:e.structuredContent,schema:se(t)});if(!r.success)throw new b({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 re({text:r.text,schema:t});if(!e.success)throw new b({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new b({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}onElicitationRequest(e,t){if(e!==P)throw new b({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{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=P.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=F.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 b({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new b({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new b({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{F as ElicitResultSchema,P as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,K as UnauthorizedError,X as auth,$ as createMCPClient,$ as experimental_createMCPClient,Tt as mcpAppClientCapabilities,Mt as readMCPAppResource,At as splitMCPAppTools};
|