eve 0.71.0 → 0.71.2
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 +24 -0
- package/dist/src/channel/agent-description.d.ts +33 -0
- package/dist/src/channel/agent-description.js +1 -0
- package/dist/src/channel/resolved-prompt.d.ts +12 -0
- package/dist/src/channel/resolved-prompt.js +1 -0
- package/dist/src/channel/routes.d.ts +7 -0
- package/dist/src/channel/tool-eligibility.d.ts +39 -0
- package/dist/src/channel/tool-eligibility.js +1 -0
- package/dist/src/cli/dev/tui/transcript.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@modelcontextprotocol/server/index.d.ts +18 -0
- package/dist/src/compiler/extension-compatibility.d.ts +2 -2
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/context/serialize.js +1 -1
- package/dist/src/eve-channel/request.js +1 -1
- package/dist/src/execution/cancelled-model-call-batch.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/proxied-deliver-step.js +1 -1
- package/dist/src/execution/publish-session-events.d.ts +5 -4
- package/dist/src/execution/publish-session-events.js +1 -1
- package/dist/src/execution/sandbox/bindings/docker-templates.d.ts +1 -1
- package/dist/src/execution/sandbox/bindings/docker-templates.js +1 -1
- package/dist/src/execution/sandbox/bindings/docker.js +1 -1
- package/dist/src/execution/sandbox/ensure.js +1 -1
- package/dist/src/execution/sandbox/prewarm.js +1 -1
- package/dist/src/execution/sandbox/read-file.js +3 -3
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/attachments/media-metadata.d.ts +2 -0
- package/dist/src/internal/attachments/media-metadata.js +1 -1
- package/dist/src/internal/authored-definition/source-identity.d.ts +17 -8
- package/dist/src/internal/authored-definition/source-identity.js +1 -1
- package/dist/src/internal/authored-module-map-loader.js +1 -1
- package/dist/src/internal/mcp/streamable-http-server.js +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.d.ts +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/workflow/cancel-expired-development-run.js +1 -1
- package/dist/src/internal/workflow/development-world-client.js +1 -1
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +9 -0
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +1 -1
- package/dist/src/public/channels/chat-sdk/input-actions.d.ts +4 -2
- package/dist/src/public/channels/chat-sdk/input-actions.js +1 -1
- package/dist/src/public/channels/discord/defaults.js +1 -1
- package/dist/src/public/channels/discord/discordChannel.d.ts +10 -0
- package/dist/src/public/channels/discord/discordChannel.js +1 -1
- package/dist/src/public/channels/discord/hitl.js +1 -1
- package/dist/src/public/channels/index.d.ts +1 -1
- package/dist/src/public/channels/slack/connections.d.ts +11 -11
- package/dist/src/public/channels/slack/connections.js +1 -1
- package/dist/src/public/channels/slack/defaults.js +1 -1
- package/dist/src/public/channels/teams/defaults.js +2 -2
- package/dist/src/public/channels/teams/teamsChannel.d.ts +8 -3
- package/dist/src/public/channels/teams/teamsChannel.js +1 -1
- package/dist/src/public/channels/telegram/defaults.d.ts +5 -2
- package/dist/src/public/channels/telegram/defaults.js +1 -1
- package/dist/src/public/channels/telegram/hitl.d.ts +23 -1
- package/dist/src/public/channels/telegram/hitl.js +2 -2
- package/dist/src/public/channels/telegram/telegramChannel.d.ts +1 -0
- package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
- package/dist/src/public/channels/twilio/defaults.d.ts +1 -1
- package/dist/src/public/channels/twilio/defaults.js +4 -2
- package/dist/src/public/definitions/channel.d.ts +1 -0
- package/dist/src/public/tools/result.js +1 -1
- package/dist/src/runtime/resolve-connection.js +1 -1
- package/dist/src/runtime/resolve-dynamic-tool.js +1 -1
- package/dist/src/runtime/resolve-tool.js +1 -1
- package/dist/src/runtime/sessions/compiled-agent-cache.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/subagents/hitl-proxy.d.ts +2 -0
- package/dist/src/subagents/hitl-proxy.js +1 -1
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/read-file.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/docs/channels/custom.mdx +1 -0
- package/docs/concepts/built-in-tools.md +1 -1
- package/docs/concepts/sessions-runs-and-streaming.md +1 -1
- package/docs/extensions.md +1 -1
- package/docs/guides/hooks.md +2 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.71.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 76e9079: Return a not-found or transient error before opening an unavailable session stream, and close streams after terminal failures.
|
|
8
|
+
- 52ebf7d: Discord now posts session budget prompts instead of failing on a button ID over 100 characters. Slack sends its private sign-in prompt for sign-ins that only have instructions. Teams sign-in cards show the confirmation code and instructions, Twilio texts sign-ins and their outcome, and the dev TUI labels a sign-in with its display name. Discord buttons posted before this update stop working once it's deployed.
|
|
9
|
+
|
|
10
|
+
## 0.71.1
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- 28f4063: Telegram, Discord, Teams, and `chatSdkChannel` now remove a question's or approval's buttons once it's answered and show the outcome, such as `Approved` or `Answered: Saturday`. This covers pressed buttons, typed replies, and requests withdrawn when a turn is cancelled. Adapters that can't edit messages keep the original prompt.
|
|
15
|
+
- cdad50a: A follow-up message cancelled before its first model call now keeps its own sender as `ctx.session.auth.current`. Previously the cancelled turn reverted to the previous caller, even when the follow-up was anonymous, so `turn.cancelled` hooks saw the wrong identity.
|
|
16
|
+
- b842fe0: Discord buttons now answer every pending request when a turn asks more than one at once, such as two questions, two tool approvals, or a question beside an approval. Before, only the first request's buttons reached the session; pressing another request's buttons failed with "the target session was not found via continuation token".
|
|
17
|
+
- 440b2f2: Fix Docker sandbox template pruning so `eve dev` removes stale template images again, and drop the intermediate `eve-sandbox-dockerfile` image once its template is committed.
|
|
18
|
+
- 8c026ee: Sessions saved before eve 0.64 that used a sandbox no longer fail every sandbox call with `Sandbox session state belongs to provider "undefined"` or the `Session checkpoint sandbox provider state is incompatible` handoff error. A sandbox record without a provider is treated as no sandbox, so the next sandbox call starts a fresh one.
|
|
19
|
+
- 58a68dd: Keep MCP connections over HTTP on the `2026-07-28` protocol when the server is slow to answer `server/discover`. Previously eve gave up after 1 s and fell back to the legacy handshake, which servers that only speak the new protocol reject with `Unsupported protocol version: 2025-11-25`.
|
|
20
|
+
- 5919154: MCP `tools/call` requests whose arguments don't match the tool's input schema now return `structuredContent.error` with code `invalid_input`, like every other rejected call, instead of only a text message.
|
|
21
|
+
- 738c8de: Detect PNG, JPEG, GIF, and WebP files from their bytes in `read_file`, so images with missing or incorrect filename extensions remain viewable. Text files are always read as text, even with an image extension, and unreadable binary files now get a clear error.
|
|
22
|
+
- 6c2e941: Channel route handlers now receive `describe()`, which returns the agent's name, description, and the compiled tools a caller can run outside a turn, with their JSON schemas, without the inspection detail of `GET /eve/v1/info`.
|
|
23
|
+
- 073281c: Fix a spurious `toolResultFrom` identity warning when one tool definition is mounted under more than one name, such as the code extension's `grep` tool in its worker subagent. `toolResultFrom` now matches results from every name that definition is mounted under.
|
|
24
|
+
- b842fe0: Pressing a Telegram question button again after the question is answered now sends that option to the agent as a new message, as it does on other channels. Before, the press was acknowledged and dropped. Button presses also act as the person who pressed them instead of an anonymous caller.
|
|
25
|
+
- 12ced99: A plain-text message that answers a pending `ctx.ask()` question is now recorded as `message.received`, stamped with its delivery id, before the `input.resolved` it produces. Clients rendering from the session stream now show what the person typed, and an optimistic copy of the message reconciles instead of lingering. The answer joins the open turn like a steering message, so the turn's later events carry its delivery id too. Model history is unchanged.
|
|
26
|
+
|
|
3
27
|
## 0.71.0
|
|
4
28
|
|
|
5
29
|
### Minor Changes
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { CompiledAgentManifest } from "#compiler/manifest.js";
|
|
2
|
+
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
|
|
3
|
+
import type { JsonObject } from "#shared/json.js";
|
|
4
|
+
/** One compiled tool a caller can invoke outside a turn. */
|
|
5
|
+
export interface AgentToolDescription {
|
|
6
|
+
readonly name: string;
|
|
7
|
+
readonly description: string;
|
|
8
|
+
readonly inputSchema: JsonObject;
|
|
9
|
+
readonly outputSchema?: JsonObject;
|
|
10
|
+
/** The tool declares an approval policy. */
|
|
11
|
+
readonly approval: boolean;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The caller-facing view of an agent: its name, description, and the compiled
|
|
15
|
+
* tools `invokeTool` can run, sorted by name. Unlike `GET /eve/v1/info`, it
|
|
16
|
+
* carries no paths, config, diagnostics, or other inspection detail, so
|
|
17
|
+
* channels can publish it as is. Tools added by dynamic resolvers and
|
|
18
|
+
* subagents are not listed.
|
|
19
|
+
*/
|
|
20
|
+
export interface AgentDescription {
|
|
21
|
+
readonly name: string;
|
|
22
|
+
readonly description?: string;
|
|
23
|
+
readonly tools: readonly AgentToolDescription[];
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The `describe` route handler arg for one compiled agent. The artifacts
|
|
27
|
+
* source resolves on first use, so routes that never call it pay nothing.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createAgentDescriptionRouteArgs(resolveCompiledArtifactsSource: () => RuntimeCompiledArtifactsSource): {
|
|
30
|
+
describe(): Promise<AgentDescription>;
|
|
31
|
+
};
|
|
32
|
+
/** Projects the root node of a compiled manifest onto {@link AgentDescription}. */
|
|
33
|
+
export declare function describeCompiledAgent(manifest: CompiledAgentManifest): AgentDescription;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isInvocableCompiledTool}from"#channel/tool-eligibility.js";import{loadCompiledManifest}from"#runtime/loaders/manifest.js";function createAgentDescriptionRouteArgs(e){return{async describe(){let t=e();return describeCompiledAgent(await loadCompiledManifest({compiledArtifactsSource:t}))}}}function describeCompiledAgent(e){let t=e.tools.filter(t=>isInvocableCompiledTool(e,t)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)).map(describeTool),n={name:e.config.name,tools:t};return e.config.description!==void 0&&(n.description=e.config.description),n}function describeTool(e){let t={name:e.name,description:e.description,inputSchema:e.inputSchema??{},approval:e.requiresApproval};return e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),t}export{createAgentDescriptionRouteArgs,describeCompiledAgent};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { InputResolution } from "#protocol/message.js";
|
|
2
|
+
import type { InputOption } from "#shared/input.js";
|
|
3
|
+
type PromptOption = Pick<InputOption, "id" | "label">;
|
|
4
|
+
/**
|
|
5
|
+
* How eve resolved a posted prompt, such as `Approved` or a chosen option's
|
|
6
|
+
* label. A request that ends without an answer, such as one withdrawn when its
|
|
7
|
+
* turn is cancelled, is no longer needed.
|
|
8
|
+
*/
|
|
9
|
+
export declare function resolvedPromptAnswer(resolution: InputResolution, options?: readonly PromptOption[]): string | undefined;
|
|
10
|
+
/** The line a prompt shows once resolved, such as `Approved` or `Answered: Saturday`. */
|
|
11
|
+
export declare function resolvedPromptLabel(resolution: InputResolution, options?: readonly PromptOption[]): string;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function resolvedPromptAnswer(e,t=[]){switch(e.outcome){case`approved`:return`Approved`;case`denied`:return`Cancelled`;case`answered`:{let n=e.response;return t.find(e=>e.id===n?.optionId)?.label??n?.text}default:return`No longer needed`}}function resolvedPromptLabel(e,t=[]){let n=resolvedPromptAnswer(e,t);return e.outcome===`answered`?n===void 0?`Answered`:`Answered: ${n}`:n??``}export{resolvedPromptAnswer,resolvedPromptLabel};
|
|
@@ -5,6 +5,7 @@ import type { InputResponse } from "#shared/input.js";
|
|
|
5
5
|
import type { Session } from "#channel/session.js";
|
|
6
6
|
import type { JsonObject } from "#shared/json.js";
|
|
7
7
|
import type { ChannelMethod } from "#public/definitions/channel.js";
|
|
8
|
+
import type { AgentDescription } from "#channel/agent-description.js";
|
|
8
9
|
type WebSocketHeaders = Headers | readonly (readonly [string, string])[] | Record<string, string>;
|
|
9
10
|
/**
|
|
10
11
|
* Second argument passed to every route handler. `from` binds local operations,
|
|
@@ -29,6 +30,12 @@ export interface RouteHandlerArgs<TState = undefined> {
|
|
|
29
30
|
waitUntil: (task: Promise<unknown>) => void;
|
|
30
31
|
/** Best-effort client IP reported by the host, or `null` when unavailable. */
|
|
31
32
|
requestIp: string | null;
|
|
33
|
+
/**
|
|
34
|
+
* Describes the agent for callers: its name, description, and the compiled
|
|
35
|
+
* tools that can run outside a turn, sorted by name. Carries none of the
|
|
36
|
+
* inspection detail of `GET /eve/v1/info`.
|
|
37
|
+
*/
|
|
38
|
+
describe(): Promise<AgentDescription>;
|
|
32
39
|
}
|
|
33
40
|
export interface SendPayload {
|
|
34
41
|
readonly message?: string | UserContent;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { CompiledToolDefinition } from "#compiler/manifest.js";
|
|
2
|
+
import type { AgentSourceOwner } from "#compiler/source-graph.js";
|
|
3
|
+
/** The part of a compiled manifest that records who contributed each source. */
|
|
4
|
+
export interface CompiledToolBindings {
|
|
5
|
+
readonly bindings: Readonly<Record<string, {
|
|
6
|
+
readonly owner: AgentSourceOwner;
|
|
7
|
+
}>>;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The one rule for whether a compiled tool can run outside a turn. `describe()`
|
|
11
|
+
* lists only tools for which it holds, and `invokeTool` refuses the rest.
|
|
12
|
+
*
|
|
13
|
+
* A tool is invocable when all three hold:
|
|
14
|
+
*
|
|
15
|
+
* 1. `hasExecute`: the tool has an `execute` function.
|
|
16
|
+
* 2. No `behavior.handling`. Handled tools (`dispatch`, `workflow-tool`,
|
|
17
|
+
* `provider-tool`, and any handling kind added later) are run by the
|
|
18
|
+
* harness or a provider, not by calling `execute`.
|
|
19
|
+
* 3. The owner of its source binding is not `"framework"`. This is a
|
|
20
|
+
* conservative phase-1 policy, stricter than the mechanical predicate in
|
|
21
|
+
* the research plan (`hasExecute` minus handled tools and framework
|
|
22
|
+
* actions). It is not a claim that every framework tool needs a turn: some,
|
|
23
|
+
* such as `load_skill` and `agent`, depend on the turn's harness or
|
|
24
|
+
* session, while others, such as `web_fetch`, could run without one. They
|
|
25
|
+
* are all withheld so that phase 1 publishes only tools the application or
|
|
26
|
+
* an extension authored; exposing individual framework tools is a later,
|
|
27
|
+
* explicit decision. An application or extension tool that overrides a
|
|
28
|
+
* framework tool name is owned by the application or extension and stays
|
|
29
|
+
* invocable.
|
|
30
|
+
*
|
|
31
|
+
* There is no background-tool marker in the compiled registry. A background
|
|
32
|
+
* tool is excluded only when one of these rules already covers it.
|
|
33
|
+
*
|
|
34
|
+
* Throws when the tool has no source binding, which a valid manifest never
|
|
35
|
+
* produces.
|
|
36
|
+
*/
|
|
37
|
+
export declare function isInvocableCompiledTool(manifest: CompiledToolBindings, tool: Pick<CompiledToolDefinition, "behavior" | "hasExecute" | "name" | "sourceId">): boolean;
|
|
38
|
+
/** Owner of the source binding that contributed a compiled tool. */
|
|
39
|
+
export declare function compiledToolOwner(manifest: CompiledToolBindings, tool: Pick<CompiledToolDefinition, "name" | "sourceId">): AgentSourceOwner;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function isInvocableCompiledTool(e,t){let n=compiledToolOwner(e,t);return t.hasExecute&&t.behavior?.handling===void 0&&n.kind!==`framework`}function compiledToolOwner(e,t){let n=Object.hasOwn(e.bindings,t.sourceId)?e.bindings[t.sourceId]:void 0;if(n===void 0)throw Error(`Compiled tool "${t.name}" has no source binding.`);return n.owner}export{compiledToolOwner,isInvocableCompiledTool};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FileContentCache}from"./file-content-cache.js";import{agentDisplayName,agentTaskLabel,isPanelRoutedTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{isTerminalToolCallPart}from"./terminal-tool-part.js";import{activeToolSteps,authorizationTerminalMessage,childToolCallIds,endLine,firstLine,followUpLine,formatAuthorization,isActive,isToolCallRow,nestedTaskRecord,startLine,subagentSteps,taskCallsById,taskNeedsApproval,toolBlock,toolState,userText,writeExistedFlag}from"./transcript-parts.js";import{signInLabel,waitingLabel}from"./task-activity.js";import{TaskRecords}from"./task-records.js";import{isTaskControlTool}from"#protocol/task-tools.js";import{stripTerminalControls}from"#cli/ui/terminal-text.js";import{agentCallTurns,agentToolSession,conversationAuthorizations,isAgentCallContentPending}from"#client/conversation-state.js";import{authorizationKey}from"#client/session-utils.js";const TASK_END_GRACE_MS=2e3;var ConversationTranscript=class{#e=new Map;#t=new FileContentCache;#n=new Map;#r=new Map;#i=new Set;#a=new TaskRecords;#o=new Map;#s=[];#c=new Set;#l=[];reset(){this.#e=new Map,this.#t.clear(),this.#n.clear(),this.#r=new Map,this.#i.clear(),this.#a.clear(),this.#o.clear(),this.#s=[],this.#c.clear(),this.#l=[]}get tasks(){return this.#l}get finishing(){return this.#l.some(e=>e.finishing===!0)}taskLabel(e,t){let n=e.tasks[t];if(n===void 0)return;let r=Object.values(n.calls),i=r.findLast(e=>e.status===`working`)??r.at(-1),a=i===void 0?void 0:this.#a.get(i.callId);return a===void 0?n.kind===`agent`?agentTaskLabel(agentDisplayName(stripTerminalControls(n.name))):stripTerminalControls(n.name):a.kind===`agent`?agentTaskLabel(a.name):a.name}stopWorking(e){let t=[];for(let n of this.#a.values())n.ended||(n.ended=!0,t.push(endLine(n,{status:`cancelled`},void 0,e.dot??`·`)));return this.#l=[],t}project(e,t){let{conversation:n,working:r}=e,i=Date.now(),a=[];this.#h(n.messages);let o=childToolCallIds(n),s=taskCallsById(n),c=new Set(e.data.withdrawnCallIds),l=e.data.toolLabels;for(let e of n.messages){if(e.role===`user`){let t=this.#g(e);t!==void 0&&a.push(t);continue}let u=e.parts.filter(e=>isToolCallRow(e)&&(e.state!==`input-streaming`||r)&&!isTaskControlTool(e.toolName)&&!c.has(e.toolCallId)&&e.toolMetadata?.eve?.inputRequest?.kind!==`session-limit`&&!s.has(e.toolCallId)&&!o.has(e.toolCallId)&&!isPanelRoutedTool(e.toolName)),d=new Map(u.map(e=>[e,toolState(e,n,r,!1)])),f=activeToolSteps(d);for(let[n,o]of e.parts.entries())if(o.type===`text`||o.type===`reasoning`){let i=this.#_(e,n,t,r);i!==void 0&&a.push(i)}else if(o.type===`authorization`)t.connectionAuth!==`hidden`&&a.push(this.#v(o));else if(o.type===`dynamic-tool`){let e=s.get(o.toolCallId);if(e!==void 0){let n=this.#d(o,e.task,l,t,i);n!==void 0&&a.push(n);continue}let n=d.get(o);if(n===void 0||t.tools===`hidden`)continue;let r=l[o.toolCallId];a.push(this.#y(o,n,f.has(o.stepIndex),r,t))}let p=e.metadata?.turnId;p!==void 0&&n.turns[p]?.status===`cancelled`&&a.push(this.#m(`cancelled:${p}`,[],()=>({kind:`notice`,body:`Cancelled.`,live:!1})))}for(let[n,r]of e.failures.entries())a.push(this.#b(n,r,t));let u=this.#u(a),d=this.#f(e,s,t,i);for(let e of d){let t=u.slice(-8).map(e=>e.id);this.#s.push({block:e,after:t}),this.#c.add(e.id),u.push(e)}return u}#u(e){let t=[...e];for(let{block:e,after:n}of this.#s){let r=t.length;for(let e=n.length-1;e>=0;--e){let i=t.findIndex(t=>t.id===n[e]);if(i!==-1){r=i+1;break}}t.splice(r,0,e)}return t}#d(e,t,n,r,i){if(!(t.kind===`agent`?r.subagents!==`hidden`:r.tools!==`hidden`))return;let a=n[e.toolCallId]?.start,o=this.#a.record(e,t,a,i);return o.callId===e.toolCallId?this.#m(`task:${o.callId}:start`,[o],()=>startLine(o)):this.#m(`task:${e.toolCallId}:message`,[o],()=>followUpLine(o,e,a))}#f(e,t,n,r){let{conversation:i,working:a}=e,o=Object.values(i.turns).at(-1),s=!a&&(e.data.sessionFailed||o?.status===`cancelled`||o?.status===`failed`),c=[],l=[],u={remaining:128};for(let e of this.#a.values()){if(e.ended)continue;let o=t.get(e.callId)?.task;if(o===void 0)continue;let d=e.callIds.flatMap(e=>{let n=t.get(e)?.call;return n===void 0?[]:[n]}),f=d.at(-1),p=this.#p(e,o,d,i,n,u);if(n.subagents===`full`)for(let e of p.rows)this.#c.has(e.id)||c.push(e);let m=d.every(e=>e.status!==`working`);m&&(e.settledAtMs??=r);let h=m&&p.pending&&a&&r-(e.settledAtMs??r)<2e3;if(m&&!h||!m&&s){e.ended=!0,c.push(endLine(e,m?f:{status:`cancelled`},p.tools,n.dot??`·`));continue}let g={callId:e.callId,kind:e.kind,name:e.name,toolName:e.toolName,input:e.input,label:e.label,purpose:e.purpose,children:p.children,omittedTasks:p.omittedTasks,omittedAttention:p.omittedAttention,startedAtMs:e.startedAtMs,childTools:new Map(p.tools.map(e=>[e.id,e]))};p.step!==void 0&&(g.step=p.step),h&&(g.finishing=!0),l.push(g)}return this.#l=l,c}#p(e,t,n,r,i,a,o=0){let s=t.kind===`agent`?agentToolSession(r,t):void 0,c=s===void 0||s.observation.status===`not-followed`?void 0:s.observation.conversation;if(s===void 0||c===void 0)return{tools:[],rows:[],pending:!1};let l=s.observation.status===`following`&&n.some(e=>isAgentCallContentPending(t,e,c)),u=agentCallTurns(t,c),d=new Set(n.flatMap(e=>u.get(e.callId)??[])),f=c.messages.filter(e=>e.role===`assistant`&&e.metadata?.turnId!==void 0&&d.has(e.metadata.turnId)),p=n.some(e=>e.status===`working`)||l,m=taskCallsById(c),h=[],g=[],_=[],v=new Set,y=0,b=!1,x=0;for(let t of f)for(let n of t.parts){if(x+=1,!isToolCallRow(n)||isTaskControlTool(n.toolName))continue;let t=m.get(n.toolCallId),r=toolState(n,c,p,t?.call.status===`working`),s=`subagent:${e.callId}:tool:${n.toolCallId}`,l=this.#m(s,[n,r.status,e.name],()=>{let a=this.#x(n.toolCallId,n,r,i,{isSubagent:t?.task.kind===`agent`});return{...toolBlock(n,r,a),kind:`subagent-tool`,subagentCallId:e.callId,agentName:e.name,depth:1,live:!1}}),u=t?.task.kind===`agent`?i.subagents!==`hidden`:i.tools!==`hidden`;if(t?.call.status===`working`&&u){if(v.has(t.task.taskId))continue;if(v.add(t.task.taskId),o>=8||a.remaining<=0){y+=1,b||=r.status===`approval`||taskNeedsApproval(c,t.task);continue}--a.remaining;let s=`${e.callId}/${n.toolCallId}`,u=this.#o.get(s);u===void 0&&(u=nestedTaskRecord(s,n,t.task,l),this.#o.set(s,u));let d=this.#p(u,t.task,Object.values(t.task.calls).filter(e=>e.status===`working`),c,i,a,o+1);_.push({...u,step:d.step,children:d.children,omittedTasks:d.omittedTasks,omittedAttention:d.omittedAttention,childTools:new Map(d.tools.map(e=>[e.id,e]))})}else g.push(l);h.push({order:x,block:l,settled:!isActive(r.status)})}let S=subagentSteps(f);for(let t of S){if(!t.finalized)continue;let n=`subagent:${e.callId}:step:${t.key}`,r=this.#m(n,[t.reasoning,t.message,e.name],()=>{let n={kind:`subagent-step`,subagentCallId:e.callId,agentName:e.name,depth:1,body:t.message,live:!1};return t.reasoning.length>0&&(n.reasoning=t.reasoning),n});h.push({order:t.order,block:r,settled:!0})}let C=h.filter(e=>e.settled).sort((e,t)=>e.order-t.order).map(e=>e.block),w=S.at(-1),T={tools:g,rows:C,children:_,omittedTasks:y,omittedAttention:b,pending:l};return w!==void 0&&(T.step=firstLine(w.message)??`Thinking`),T}#m(e,t,n){let r=this.#e.get(e);if(r!==void 0&&sameKey(r.key,t))return r.block;let i={...n(),id:e};return this.#e.set(e,{key:t,block:i}),i}#h(e){let t=new Map;for(let n of e)n.role===`user`&&n.metadata?.optimistic===!0&&t.set(n.id,userText(n));let n=[...this.#r].filter(([e])=>!t.has(e)),r=new Set(t.values());for(let t of e){if(t.role!==`user`||t.metadata?.optimistic===!0||this.#i.has(t.id))continue;let e=userText(t),i=n.findIndex(([,t])=>t===e);i===-1&&r.has(e)||(this.#i.add(t.id),i!==-1&&(this.#n.set(t.id,n[i][0]),n.splice(i,1)))}this.#r=t}#g(e){if(e.metadata?.optimistic!==!0&&!this.#i.has(e.id))return;let t=stripTerminalControls(userText(e));if(t.trim().length===0)return;let n=`user:${this.#n.get(e.id)??e.id}`;return this.#m(n,[t],()=>({kind:`user`,body:t,live:!1}))}#_(e,t,n,r){let i=e.parts[t];if(i?.type!==`text`&&i?.type!==`reasoning`||i.type===`reasoning`&&n.reasoning!==`full`)return;let a=stripTerminalControls(i.text).trim();if(a.length===0)return;let o=i.state===`streaming`&&r,s=`${i.type}:${i.id??`${e.id}:${t}`}`;return this.#m(s,[a,o],()=>i.type===`text`?{kind:`assistant`,body:a,live:o}:{kind:`reasoning`,body:a,collapsed:!1,live:o})}#v(e){return this.#m(`connection-auth:${authorizationKey(e)}`,[e],()=>{let t=e.state===`completed`?e.outcome:e.state,n=authorizationTerminalMessage(t);return{kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${t}`,body:formatAuthorization(e,n),preformatted:!0,live:n===void 0}})}#y(e,t,n,r,i){let a=n||isActive(t.status);return this.#m(`tool:${e.toolCallId}`,[e,t.status,a,i.tools,i.subagentNames,r],()=>{let n=this.#x(e.toolCallId,e,t,i,{label:r?.start,completeLabel:r?.complete});return{...toolBlock(e,t,n),kind:`tool`,live:a,expanded:i.tools===`full`}})}#b(e,t,n){let{message:r,hint:i,detail:a}=t;return this.#m(`failure:${e}`,[r,i,a],()=>{let e={kind:`error`,title:`Error`,body:stripTerminalControls(r),live:!1};return i!==void 0&&(e.hint=stripTerminalControls(i)),a!==void 0&&(e.detail=n.diagnosticsPath===void 0?stripTerminalControls(a):`details: ${n.diagnosticsPath}`),e})}#x(e,t,n,r,i={}){n.output!==void 0&&this.#t.observeRead(n.output);let a={};(i.isSubagent===!0||r.subagentNames?.includes(toolBaseName(t.toolName))===!0)&&(a.isSubagent=!0),i.label!==void 0&&(a.label=i.label),i.completeLabel!==void 0&&(a.completeLabel=i.completeLabel);let o=readWriteFileInput(t.toolName,t.input);if(o!==void 0){let t=this.#t.observeWrite({...o,callId:e});t!==void 0&&(a.previousContent=t);let r=writeExistedFlag(n.output);r!==void 0&&(a.existed=r)}return Object.keys(a).length>0?a:void 0}};function turnActivity(e,t){let{conversation:n}=e,r=n.activeTurnId===void 0?void 0:n.turns[n.activeTurnId],i=e.conversation.messages.findLast(e=>e.role===`assistant`),a=taskCallsById(n);if(i?.parts.some(e=>isTerminalToolCallPart(e)&&!isTaskControlTool(e.toolName)&&!a.has(e.toolCallId)&&(e.state===`input-available`||e.state===`approval-responded`))===!0)return`Running`;if(r===void 0||r.waiting===!0){let e=conversationAuthorizations(n).filter(e=>e.state===`required`&&e.awaitsCallback===!0);if(e.length>0)return signInLabel(e.map(e=>e.displayName))}if(r?.waiting===!0&&t.length>0)return waitingLabel(t);if(i===void 0)return`Thinking`;let o=i.parts.findLast(e=>e.type!==`step-start`);return o?.type===`text`&&o.state===`streaming`||o?.type===`dynamic-tool`&&o.state===`input-streaming`?`Generating`:`Thinking`}function sameKey(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{ConversationTranscript,TASK_END_GRACE_MS,turnActivity};
|
|
1
|
+
import{FileContentCache}from"./file-content-cache.js";import{agentDisplayName,agentTaskLabel,isPanelRoutedTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{isTerminalToolCallPart}from"./terminal-tool-part.js";import{activeToolSteps,authorizationTerminalMessage,childToolCallIds,endLine,firstLine,followUpLine,formatAuthorization,isActive,isToolCallRow,nestedTaskRecord,startLine,subagentSteps,taskCallsById,taskNeedsApproval,toolBlock,toolState,userText,writeExistedFlag}from"./transcript-parts.js";import{signInLabel,waitingLabel}from"./task-activity.js";import{TaskRecords}from"./task-records.js";import{isTaskControlTool}from"#protocol/task-tools.js";import{stripTerminalControls}from"#cli/ui/terminal-text.js";import{agentCallTurns,agentToolSession,conversationAuthorizations,isAgentCallContentPending}from"#client/conversation-state.js";import{authorizationKey}from"#client/session-utils.js";const TASK_END_GRACE_MS=2e3;var ConversationTranscript=class{#e=new Map;#t=new FileContentCache;#n=new Map;#r=new Map;#i=new Set;#a=new TaskRecords;#o=new Map;#s=[];#c=new Set;#l=[];reset(){this.#e=new Map,this.#t.clear(),this.#n.clear(),this.#r=new Map,this.#i.clear(),this.#a.clear(),this.#o.clear(),this.#s=[],this.#c.clear(),this.#l=[]}get tasks(){return this.#l}get finishing(){return this.#l.some(e=>e.finishing===!0)}taskLabel(e,t){let n=e.tasks[t];if(n===void 0)return;let r=Object.values(n.calls),i=r.findLast(e=>e.status===`working`)??r.at(-1),a=i===void 0?void 0:this.#a.get(i.callId);return a===void 0?n.kind===`agent`?agentTaskLabel(agentDisplayName(stripTerminalControls(n.name))):stripTerminalControls(n.name):a.kind===`agent`?agentTaskLabel(a.name):a.name}stopWorking(e){let t=[];for(let n of this.#a.values())n.ended||(n.ended=!0,t.push(endLine(n,{status:`cancelled`},void 0,e.dot??`·`)));return this.#l=[],t}project(e,t){let{conversation:n,working:r}=e,i=Date.now(),a=[];this.#h(n.messages);let o=childToolCallIds(n),s=taskCallsById(n),c=new Set(e.data.withdrawnCallIds),l=e.data.toolLabels;for(let e of n.messages){if(e.role===`user`){let t=this.#g(e);t!==void 0&&a.push(t);continue}let u=e.parts.filter(e=>isToolCallRow(e)&&(e.state!==`input-streaming`||r)&&!isTaskControlTool(e.toolName)&&!c.has(e.toolCallId)&&e.toolMetadata?.eve?.inputRequest?.kind!==`session-limit`&&!s.has(e.toolCallId)&&!o.has(e.toolCallId)&&!isPanelRoutedTool(e.toolName)),d=new Map(u.map(e=>[e,toolState(e,n,r,!1)])),f=activeToolSteps(d);for(let[n,o]of e.parts.entries())if(o.type===`text`||o.type===`reasoning`){let i=this.#_(e,n,t,r);i!==void 0&&a.push(i)}else if(o.type===`authorization`)t.connectionAuth!==`hidden`&&a.push(this.#v(o));else if(o.type===`dynamic-tool`){let e=s.get(o.toolCallId);if(e!==void 0){let n=this.#d(o,e.task,l,t,i);n!==void 0&&a.push(n);continue}let n=d.get(o);if(n===void 0||t.tools===`hidden`)continue;let r=l[o.toolCallId];a.push(this.#y(o,n,f.has(o.stepIndex),r,t))}let p=e.metadata?.turnId;p!==void 0&&n.turns[p]?.status===`cancelled`&&a.push(this.#m(`cancelled:${p}`,[],()=>({kind:`notice`,body:`Cancelled.`,live:!1})))}for(let[n,r]of e.failures.entries())a.push(this.#b(n,r,t));let u=this.#u(a),d=this.#f(e,s,t,i);for(let e of d){let t=u.slice(-8).map(e=>e.id);this.#s.push({block:e,after:t}),this.#c.add(e.id),u.push(e)}return u}#u(e){let t=[...e];for(let{block:e,after:n}of this.#s){let r=t.length;for(let e=n.length-1;e>=0;--e){let i=t.findIndex(t=>t.id===n[e]);if(i!==-1){r=i+1;break}}t.splice(r,0,e)}return t}#d(e,t,n,r,i){if(!(t.kind===`agent`?r.subagents!==`hidden`:r.tools!==`hidden`))return;let a=n[e.toolCallId]?.start,o=this.#a.record(e,t,a,i);return o.callId===e.toolCallId?this.#m(`task:${o.callId}:start`,[o],()=>startLine(o)):this.#m(`task:${e.toolCallId}:message`,[o],()=>followUpLine(o,e,a))}#f(e,t,n,r){let{conversation:i,working:a}=e,o=Object.values(i.turns).at(-1),s=!a&&(e.data.sessionFailed||o?.status===`cancelled`||o?.status===`failed`),c=[],l=[],u={remaining:128};for(let e of this.#a.values()){if(e.ended)continue;let o=t.get(e.callId)?.task;if(o===void 0)continue;let d=e.callIds.flatMap(e=>{let n=t.get(e)?.call;return n===void 0?[]:[n]}),f=d.at(-1),p=this.#p(e,o,d,i,n,u);if(n.subagents===`full`)for(let e of p.rows)this.#c.has(e.id)||c.push(e);let m=d.every(e=>e.status!==`working`);m&&(e.settledAtMs??=r);let h=m&&p.pending&&a&&r-(e.settledAtMs??r)<2e3;if(m&&!h||!m&&s){e.ended=!0,c.push(endLine(e,m?f:{status:`cancelled`},p.tools,n.dot??`·`));continue}let g={callId:e.callId,kind:e.kind,name:e.name,toolName:e.toolName,input:e.input,label:e.label,purpose:e.purpose,children:p.children,omittedTasks:p.omittedTasks,omittedAttention:p.omittedAttention,startedAtMs:e.startedAtMs,childTools:new Map(p.tools.map(e=>[e.id,e]))};p.step!==void 0&&(g.step=p.step),h&&(g.finishing=!0),l.push(g)}return this.#l=l,c}#p(e,t,n,r,i,a,o=0){let s=t.kind===`agent`?agentToolSession(r,t):void 0,c=s===void 0||s.observation.status===`not-followed`?void 0:s.observation.conversation;if(s===void 0||c===void 0)return{tools:[],rows:[],pending:!1};let l=s.observation.status===`following`&&n.some(e=>isAgentCallContentPending(t,e,c)),u=agentCallTurns(t,c),d=new Set(n.flatMap(e=>u.get(e.callId)??[])),f=c.messages.filter(e=>e.role===`assistant`&&e.metadata?.turnId!==void 0&&d.has(e.metadata.turnId)),p=n.some(e=>e.status===`working`)||l,m=taskCallsById(c),h=[],g=[],_=[],v=new Set,y=0,b=!1,x=0;for(let t of f)for(let n of t.parts){if(x+=1,!isToolCallRow(n)||isTaskControlTool(n.toolName))continue;let t=m.get(n.toolCallId),r=toolState(n,c,p,t?.call.status===`working`),s=`subagent:${e.callId}:tool:${n.toolCallId}`,l=this.#m(s,[n,r.status,e.name],()=>{let a=this.#x(n.toolCallId,n,r,i,{isSubagent:t?.task.kind===`agent`});return{...toolBlock(n,r,a),kind:`subagent-tool`,subagentCallId:e.callId,agentName:e.name,depth:1,live:!1}}),u=t?.task.kind===`agent`?i.subagents!==`hidden`:i.tools!==`hidden`;if(t?.call.status===`working`&&u){if(v.has(t.task.taskId))continue;if(v.add(t.task.taskId),o>=8||a.remaining<=0){y+=1,b||=r.status===`approval`||taskNeedsApproval(c,t.task);continue}--a.remaining;let s=`${e.callId}/${n.toolCallId}`,u=this.#o.get(s);u===void 0&&(u=nestedTaskRecord(s,n,t.task,l),this.#o.set(s,u));let d=this.#p(u,t.task,Object.values(t.task.calls).filter(e=>e.status===`working`),c,i,a,o+1);_.push({...u,step:d.step,children:d.children,omittedTasks:d.omittedTasks,omittedAttention:d.omittedAttention,childTools:new Map(d.tools.map(e=>[e.id,e]))})}else g.push(l);h.push({order:x,block:l,settled:!isActive(r.status)})}let S=subagentSteps(f);for(let t of S){if(!t.finalized)continue;let n=`subagent:${e.callId}:step:${t.key}`,r=this.#m(n,[t.reasoning,t.message,e.name],()=>{let n={kind:`subagent-step`,subagentCallId:e.callId,agentName:e.name,depth:1,body:t.message,live:!1};return t.reasoning.length>0&&(n.reasoning=t.reasoning),n});h.push({order:t.order,block:r,settled:!0})}let C=h.filter(e=>e.settled).sort((e,t)=>e.order-t.order).map(e=>e.block),w=S.at(-1),T={tools:g,rows:C,children:_,omittedTasks:y,omittedAttention:b,pending:l};return w!==void 0&&(T.step=firstLine(w.message)??`Thinking`),T}#m(e,t,n){let r=this.#e.get(e);if(r!==void 0&&sameKey(r.key,t))return r.block;let i={...n(),id:e};return this.#e.set(e,{key:t,block:i}),i}#h(e){let t=new Map;for(let n of e)n.role===`user`&&n.metadata?.optimistic===!0&&t.set(n.id,userText(n));let n=[...this.#r].filter(([e])=>!t.has(e)),r=new Set(t.values());for(let t of e){if(t.role!==`user`||t.metadata?.optimistic===!0||this.#i.has(t.id))continue;let e=userText(t),i=n.findIndex(([,t])=>t===e);i===-1&&r.has(e)||(this.#i.add(t.id),i!==-1&&(this.#n.set(t.id,n[i][0]),n.splice(i,1)))}this.#r=t}#g(e){if(e.metadata?.optimistic!==!0&&!this.#i.has(e.id))return;let t=stripTerminalControls(userText(e));if(t.trim().length===0)return;let n=`user:${this.#n.get(e.id)??e.id}`;return this.#m(n,[t],()=>({kind:`user`,body:t,live:!1}))}#_(e,t,n,r){let i=e.parts[t];if(i?.type!==`text`&&i?.type!==`reasoning`||i.type===`reasoning`&&n.reasoning!==`full`)return;let a=stripTerminalControls(i.text).trim();if(a.length===0)return;let o=i.state===`streaming`&&r,s=`${i.type}:${i.id??`${e.id}:${t}`}`;return this.#m(s,[a,o],()=>i.type===`text`?{kind:`assistant`,body:a,live:o}:{kind:`reasoning`,body:a,collapsed:!1,live:o})}#v(e){return this.#m(`connection-auth:${authorizationKey(e)}`,[e],()=>{let t=e.state===`completed`?e.outcome:e.state,n=authorizationTerminalMessage(t);return{kind:`connection-auth`,title:`${stripTerminalControls(e.displayName)} · authorization · ${t}`,body:formatAuthorization(e,n),preformatted:!0,live:n===void 0}})}#y(e,t,n,r,i){let a=n||isActive(t.status);return this.#m(`tool:${e.toolCallId}`,[e,t.status,a,i.tools,i.subagentNames,r],()=>{let n=this.#x(e.toolCallId,e,t,i,{label:r?.start,completeLabel:r?.complete});return{...toolBlock(e,t,n),kind:`tool`,live:a,expanded:i.tools===`full`}})}#b(e,t,n){let{message:r,hint:i,detail:a}=t;return this.#m(`failure:${e}`,[r,i,a],()=>{let e={kind:`error`,title:`Error`,body:stripTerminalControls(r),live:!1};return i!==void 0&&(e.hint=stripTerminalControls(i)),a!==void 0&&(e.detail=n.diagnosticsPath===void 0?stripTerminalControls(a):`details: ${n.diagnosticsPath}`),e})}#x(e,t,n,r,i={}){n.output!==void 0&&this.#t.observeRead(n.output);let a={};(i.isSubagent===!0||r.subagentNames?.includes(toolBaseName(t.toolName))===!0)&&(a.isSubagent=!0),i.label!==void 0&&(a.label=i.label),i.completeLabel!==void 0&&(a.completeLabel=i.completeLabel);let o=readWriteFileInput(t.toolName,t.input);if(o!==void 0){let t=this.#t.observeWrite({...o,callId:e});t!==void 0&&(a.previousContent=t);let r=writeExistedFlag(n.output);r!==void 0&&(a.existed=r)}return Object.keys(a).length>0?a:void 0}};function turnActivity(e,t){let{conversation:n}=e,r=n.activeTurnId===void 0?void 0:n.turns[n.activeTurnId],i=e.conversation.messages.findLast(e=>e.role===`assistant`),a=taskCallsById(n);if(i?.parts.some(e=>isTerminalToolCallPart(e)&&!isTaskControlTool(e.toolName)&&!a.has(e.toolCallId)&&(e.state===`input-available`||e.state===`approval-responded`))===!0)return`Running`;if(r===void 0||r.waiting===!0){let e=conversationAuthorizations(n).filter(e=>e.state===`required`&&e.awaitsCallback===!0);if(e.length>0)return signInLabel(e.map(e=>e.displayName))}if(r?.waiting===!0&&t.length>0)return waitingLabel(t);if(i===void 0)return`Thinking`;let o=i.parts.findLast(e=>e.type!==`step-start`);return o?.type===`text`&&o.state===`streaming`||o?.type===`dynamic-tool`&&o.state===`input-streaming`?`Generating`:`Thinking`}function sameKey(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{ConversationTranscript,TASK_END_GRACE_MS,turnActivity};
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
"zod": "4.5.4",
|
|
58
58
|
"zod-validation-error": "5.0.0"
|
|
59
59
|
},
|
|
60
|
-
"scriptHash": "
|
|
60
|
+
"scriptHash": "277be02e8bb80db55cb4e8f8b89fd9dbc1819089604a886604d433558d33d2e8",
|
|
61
61
|
"toolVersions": {
|
|
62
62
|
"rolldown": "1.2.9",
|
|
63
63
|
"typescript": "7.0.2"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{A as n,P as r,Q as i,St as a,U as o,V as s,ct as c,d as l,gt as u,j as d,k as f,lt as p,pt as m,r as h,s as g,st as _,yt as v}from"../../_chunks/workflow/dist-C3ZE62yI.js";import*as y from"#compiled/zod/index.js";import{z as b}from"#compiled/zod/index.js";let x;x=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function S(e){return(await x).getRandomValues(new Uint8Array(e))}async function C(e){let t=``;for(;t.length<e;){let n=await S(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function ee(e){return await C(e)}async function te(e){let t=await(await x).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function ne(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await ee(e);return{code_verifier:t,code_challenge:await te(t)}}var w=`2026-07-28`,T=`2025-11-25`,re=[w,T,`2025-06-18`,`2025-03-26`,`2024-11-05`],ie=b.optional(b.record(b.string(),b.unknown())),ae=b.looseObject({name:b.string(),version:b.string(),title:b.optional(b.string())}),E=b.looseObject({_meta:b.optional(b.object({}).loose())}),D=E.extend({resultType:b.optional(b.string())}),oe=b.object({method:b.string(),params:b.optional(E)}),se=b.object({applyDefaults:b.optional(b.boolean())}).loose(),ce=b.looseObject({experimental:b.optional(b.object({}).loose()),logging:b.optional(b.object({}).loose()),completions:b.optional(b.object({}).loose()),prompts:b.optional(b.looseObject({listChanged:b.optional(b.boolean())})),resources:b.optional(b.looseObject({subscribe:b.optional(b.boolean()),listChanged:b.optional(b.boolean())})),tools:b.optional(b.looseObject({listChanged:b.optional(b.boolean())})),elicitation:b.optional(se)});b.object({elicitation:b.optional(se)}).loose();var le=D.extend({supportedVersions:b.array(b.string()),capabilities:ce,instructions:b.optional(b.string()),ttlMs:b.optional(b.number()),cacheScope:b.optional(b.union([b.literal(`public`),b.literal(`private`)]))}),ue=D.extend({protocolVersion:b.string(),capabilities:ce,serverInfo:ae,instructions:b.optional(b.string())}),O=D.extend({nextCursor:b.optional(b.string())}),de=b.object({name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),inputSchema:b.looseObject({type:b.optional(b.unknown()),properties:b.optional(b.object({}).loose())}),outputSchema:b.optional(b.object({}).loose()),annotations:b.optional(b.object({title:b.optional(b.string()),readOnlyHint:b.optional(b.boolean()),destructiveHint:b.optional(b.boolean()),idempotentHint:b.optional(b.boolean()),openWorldHint:b.optional(b.boolean())}).loose()),_meta:ie}).loose(),fe=O.extend({tools:b.array(de)}),pe=b.object({type:b.literal(`text`),text:b.string()}).loose(),me=b.object({type:b.literal(`image`),data:b.base64(),mimeType:b.string()}).loose(),he=b.object({uri:b.string(),name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),mimeType:b.optional(b.string()),size:b.optional(b.number())}).loose(),ge=O.extend({resources:b.array(he)}),_e=b.object({uri:b.string(),name:b.optional(b.string()),title:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),ve=_e.extend({text:b.string()}),ye=_e.extend({blob:b.base64()}),be=b.object({type:b.literal(`resource`),resource:b.union([ve,ye])}).loose(),xe=b.object({type:b.literal(`resource_link`),uri:b.string(),name:b.string(),description:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),Se=b.object({type:b.string()}).loose().refine(e=>![`text`,`image`,`resource`,`resource_link`].includes(e.type),{message:`Known content types must match their schema`}),Ce=D.extend({content:b.array(b.union([pe,me,be,xe,Se])),structuredContent:b.optional(b.unknown()),isError:b.boolean().default(!1).optional()}),we=D.extend({content:b.never().optional(),structuredContent:b.json(),isError:b.boolean().default(!1).optional()}).transform(e=>({...e,content:[{type:`text`,text:JSON.stringify(e.structuredContent)}]})).pipe(Ce),Te=Ce.or(we).or(D.extend({toolResult:b.unknown().nonoptional()})),Ee=b.object({uriTemplate:b.string(),name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),De=D.extend({resourceTemplates:b.array(Ee)}),Oe=D.extend({contents:b.array(b.union([ve,ye]))}),ke=b.object({type:b.literal(`ref/prompt`),name:b.string()}).loose(),Ae=b.object({type:b.literal(`ref/resource`),uri:b.string()}).loose(),je=b.object({name:b.string(),value:b.string()}).loose();E.extend({ref:b.union([ke,Ae]),argument:je,context:b.optional(b.object({arguments:b.record(b.string(),b.string())}).loose())});var Me=D.extend({completion:b.object({values:b.array(b.string()).max(100),total:b.optional(b.number().int()),hasMore:b.optional(b.boolean())}).loose()}),Ne=b.object({name:b.string(),description:b.optional(b.string()),required:b.optional(b.boolean())}).loose(),Pe=b.object({name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),arguments:b.optional(b.array(Ne))}).loose(),Fe=O.extend({prompts:b.array(Pe)}),Ie=b.object({role:b.union([b.literal(`user`),b.literal(`assistant`)]),content:b.union([pe,me,be,xe])}).loose(),Le=D.extend({description:b.optional(b.string()),messages:b.array(Ie)}),Re=E.extend({message:b.string(),requestedSchema:b.unknown()}),k=oe.extend({method:b.literal(`elicitation/create`),params:Re}),ze=D.extend({action:b.union([b.literal(`accept`),b.literal(`decline`),b.literal(`cancel`)]),content:b.optional(b.record(b.string(),b.unknown()))}),A=`2.0`,Be=b.object({jsonrpc:b.literal(A),id:b.union([b.string(),b.number().int()])}).merge(oe).strict(),Ve=b.object({jsonrpc:b.literal(A),id:b.union([b.string(),b.number().int()]),result:D}).strict(),He=b.object({jsonrpc:b.literal(A),id:b.optional(b.union([b.string(),b.number().int()])),error:b.object({code:b.number().int(),message:b.string(),data:b.optional(b.unknown())})}).strict(),Ue=b.object({jsonrpc:b.literal(A)}).merge(b.object({method:b.string(),params:b.optional(E)})).strict(),We=b.union([Be,Ue,Ve,He]);function j(e){return We.parse(e)}async function M(e){return j(await i({text:e}))}var Ge=`vercel.ai.error.AI_MCPClientError`,Ke=Symbol.for(Ge),qe,Je,N=class extends (Je=e,qe=Ke,Je){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[qe]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,Ge)}},Ye=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,P=b.string().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:b.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),b.NEVER}).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`}),Xe=b.object({access_token:b.string(),id_token:b.string().optional(),token_type:b.string(),expires_in:b.number().optional(),scope:b.string().optional(),refresh_token:b.string().optional(),issuer:P.optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),Ze=b.looseObject({resource:b.string().url(),authorization_servers:b.array(P).optional(),jwks_uri:b.string().url().optional(),scopes_supported:b.array(b.string()).optional(),bearer_methods_supported:b.array(b.string()).optional(),resource_signing_alg_values_supported:b.array(b.string()).optional(),resource_name:b.string().optional(),resource_documentation:b.string().optional(),resource_policy_uri:b.string().url().optional(),resource_tos_uri:b.string().url().optional(),tls_client_certificate_bound_access_tokens:b.boolean().optional(),authorization_details_types_supported:b.array(b.string()).optional(),dpop_signing_alg_values_supported:b.array(b.string()).optional(),dpop_bound_access_tokens_required:b.boolean().optional()}),Qe=b.looseObject({issuer:b.string(),authorization_endpoint:P,token_endpoint:P,registration_endpoint:P.optional(),authorization_response_iss_parameter_supported:b.boolean().optional(),client_id_metadata_document_supported:b.boolean().optional(),scopes_supported:b.array(b.string()).optional(),response_types_supported:b.array(b.string()),grant_types_supported:b.array(b.string()).optional(),code_challenge_methods_supported:b.array(b.string()).optional(),token_endpoint_auth_methods_supported:b.array(b.string()).optional(),token_endpoint_auth_signing_alg_values_supported:b.array(b.string()).optional()}),$e=b.looseObject({issuer:b.string(),authorization_endpoint:P,token_endpoint:P,userinfo_endpoint:P.optional(),jwks_uri:P,registration_endpoint:P.optional(),authorization_response_iss_parameter_supported:b.boolean().optional(),client_id_metadata_document_supported:b.boolean().optional(),scopes_supported:b.array(b.string()).optional(),response_types_supported:b.array(b.string()),grant_types_supported:b.array(b.string()).optional(),subject_types_supported:b.array(b.string()),id_token_signing_alg_values_supported:b.array(b.string()),claims_supported:b.array(b.string()).optional(),token_endpoint_auth_methods_supported:b.array(b.string()).optional()}).merge(Qe.pick({code_challenge_methods_supported:!0})),et=b.object({client_id:b.string(),client_secret:b.string().optional(),client_id_issued_at:b.number().optional(),client_secret_expires_at:b.number().optional(),issuer:P.optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),tt=b.object({redirect_uris:b.array(P),application_type:b.union([b.literal(`native`),b.literal(`web`)]).optional(),token_endpoint_auth_method:b.string().optional(),grant_types:b.array(b.string()).optional(),response_types:b.array(b.string()).optional(),client_name:b.string().optional(),client_uri:P.optional(),logo_uri:P.optional(),scope:b.string().optional(),contacts:b.array(b.string()).optional(),tos_uri:P.optional(),policy_uri:b.string().optional(),jwks_uri:P.optional(),jwks:b.any().optional(),software_id:b.string().optional(),software_version:b.string().optional(),software_statement:b.string().optional()}).strip(),nt=b.object({error:b.string(),error_description:b.string().optional(),error_uri:b.string().optional()}),rt=tt.merge(et),it=`vercel.ai.error.AI_MCPClientOAuthError`,at=Symbol.for(it),ot,st,F=class extends (st=e,ot=at,st){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[ot]=!0}static isInstance(t){return e.hasMarker(t,it)}},I=class extends F{};I.errorCode=`server_error`;var L=class extends F{};L.errorCode=`invalid_client`;var R=class extends F{};R.errorCode=`invalid_grant`;var z=class extends F{};z.errorCode=`unauthorized_client`;var ct={[I.errorCode]:I,[L.errorCode]:L,[R.errorCode]:R,[z.errorCode]:z};function lt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function B(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function ut({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 V=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function H(e){return new URL(e).href}function U(e){let t=e.toLowerCase().replace(/\.+$/,``);return t===`localhost`||t.endsWith(`.localhost`)||t===`127.0.0.1`||t===`[::1]`||t===`::1`}function W(e,{allowLoopback:t=!1}={}){if(!t||e.protocol!==`http:`&&e.protocol!==`https:`||!U(e.hostname))try{u(e.href)}catch(t){throw new F({message:`OAuth endpoint URL is not allowed: ${e.href}`,cause:t})}}function G(e){let t=new URL(e);return U(t.hostname)?t.origin:void 0}function dt({callbackIssuer:e,expectedIssuer:t}){if(e!=null&&e!==t)throw new F({message:`OAuth authorization response issuer ${e} does not match expected issuer ${t}`})}function ft(e,t){return{issuer:t?.issuer??String(e),authorizationServerUrl:H(e),tokenEndpoint:H(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function pt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function mt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ht(e){if(e?.authorization_server&&e.token_endpoint)return{issuer:e.issuer,authorizationServerUrl:H(e.authorization_server),tokenEndpoint:H(e.token_endpoint)}}async function K({provider:e,clientInformation:t,tokens:n}){let r=ht(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{issuer:i.issuer,authorizationServerUrl:H(i.authorizationServerUrl),tokenEndpoint:H(i.tokenEndpoint)}:ht(t)}async function gt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(mt(t,n)),!0):!1}function _t(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new F({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function q({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 F({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function J(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 vt({scope:e,resourceMetadata:t,clientMetadata:n}){return e||(t?.scopes_supported)?.join(` `)||n.scope}function yt(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Y(e,t,r=fetch,i){try{return await d({url:e.href,fetch:async(e,a)=>n({url:e,init:{...a,headers:new Headers(a?.headers).has(`MCP-Protocol-Version`)?t:void 0},fetch:r,trustedOrigin:i,redirect:`manual`}),headers:t,trustedOrigin:i})}catch(n){if(n instanceof TypeError)return t?Y(e,void 0,r,i):void 0;throw n}}async function bt(e,t,n=fetch,r){return await Y(e,{"MCP-Protocol-Version":t},n,r)}function xt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function St(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??w,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=yt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await bt(o,a,n,r?.trustedOrigin);return!r?.metadataUrl&&xt(s,i.pathname)&&(s=await bt(new URL(`/.well-known/${t}`,i),a,n,r?.trustedOrigin)),s}async function Ct(e,t,n=fetch){let r=await St(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl,trustedOrigin:new URL(e).origin});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 Ze.parse(await r.json())}function wt(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 Tt(e,t){if(!(e.issuer===t||t===new URL(t).origin&&e.issuer===`${t}/`))throw new F({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Et(e,{fetchFn:t=fetch,protocolVersion:n=w,trustedOrigin:r}={}){let i={"MCP-Protocol-Version":n},a=wt(e);for(let{url:e,type:n,expectedIssuer:o}of a){let a=await Y(e,i,t,r);if(a){if(!a.ok){if(a.status>=400&&a.status<500)continue;throw Error(`HTTP ${a.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=Qe.parse(await a.json());return Tt(e,o),e}{let t=$e.parse(await a.json());if(Tt(t,o),!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 Dt(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 ne(),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`,B(o)),{authorizationUrl:l,codeVerifier:d}}function Ot(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 kt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:At(i,a,n);return;case`client_secret_post`:jt(i,a,r);return;case`none`:Mt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function At(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 jt(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 X(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}=nt.parse(await i({text:n}));return new(ct[e]||I)({message:t||``,cause:r})}catch(e){return new I({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Nt(e,{metadata:t,clientInformation:r,authorizationCode:i,codeVerifier:a,redirectUri:o,resource:s,addClientAuthentication:c,fetchFn:l}){let u=`authorization_code`,d=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),f=G(e);if(W(d,{allowLoopback:d.origin===f}),t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw Error(`Incompatible auth server: does not support grant type ${u}`);let p=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),m=new URLSearchParams({grant_type:u,code:i,code_verifier:a,redirect_uri:String(o)});c?await c(p,m,e,t):kt(Ot(r,t?.token_endpoint_auth_methods_supported??[]),r,p,m),s&&m.set(`resource`,B(s));let h=await n({url:d,init:{method:`POST`,headers:p,body:m},fetch:l,trustedOrigin:f});if(!h.ok)throw await X(h);return Xe.parse(await h.json())}async function Pt(e,{metadata:t,clientInformation:r,refreshToken:i,resource:a,addClientAuthentication:o,fetchFn:s}){let c=`refresh_token`,l;if(t){if(l=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL(`/token`,e);let u=G(e);W(l,{allowLoopback:l.origin===u});let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:c,refresh_token:i});o?await o(d,f,e,t):kt(Ot(r,t?.token_endpoint_auth_methods_supported??[]),r,d,f),a&&f.set(`resource`,B(a));let p=await n({url:l,init:{method:`POST`,headers:d,body:f},fetch:s,trustedOrigin:u});if(!p.ok)throw await X(p);return Xe.parse({refresh_token:i,...await p.json()})}async function Ft(e,{metadata:t,clientMetadata:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o=G(e);W(a,{allowLoopback:a.origin===o});let s=r.application_type??It(r.redirect_uris),c=await n({url:a,init:{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...r,application_type:s})},fetch:i,trustedOrigin:o});if(!c.ok)throw await X(c);return rt.parse(await c.json())}function It(e){return e.every(e=>{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&U(t.hostname)||t.protocol!==`http:`&&t.protocol!==`https:`})?`native`:`web`}async function Z(e,t){try{return await Rt(e,t)}catch(n){if(n instanceof L||n instanceof z)return await e.invalidateCredentials?.call(e,`all`),await Rt(e,t);if(n instanceof R)return await e.invalidateCredentials?.call(e,`tokens`),await Rt(e,t);throw n}}async function Lt(e,t,n){let r=lt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!ut({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 Rt(e,{serverUrl:t,authorizationCode:n,callbackState:r,callbackIssuer:i,scope:a,resourceMetadataUrl:o,fetchFn:s}){let c,l,u,d;_t(t,o);try{c=await Ct(t,{resourceMetadataUrl:o},s),c.authorization_servers&&c.authorization_servers.length>0&&(l=c.authorization_servers[0])}catch{}n!==void 0&&(u=await Promise.resolve(e.clientInformation()),u&&(d=await K({provider:e,clientInformation:u}))),l||=d?.authorizationServerUrl??t;let f=new URL(t),p=new URL(l),m=f.origin,h=p.origin,g=h===m||U(f.hostname)&&U(p.hostname)?h:void 0;g||W(new URL(l));let _=await Lt(t,e,c);await e.validateAuthorizationServerURL?.call(e,t,l);let v=await Et(l,{fetchFn:s,trustedOrigin:g}),y=ft(l,v),b=e.clientMetadata,x=vt({scope:a,resourceMetadata:c,clientMetadata:b});if(n===void 0&&(u=await Promise.resolve(e.clientInformation())),u?.issuer!=null){let t=d??await K({provider:e,clientInformation:u});t&&q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:y})}if(!u){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`);u=mt(await Ft(l,{metadata:v,clientMetadata:{...b,scope:x},fetchFn:s}),y),await e.saveClientInformation(u)}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=d??await K({provider:e,clientInformation:u});if(!t)throw new F({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});dt({callbackIssuer:i,expectedIssuer:t.issuer??v?.issuer??String(l)}),q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:y});let a=await e.codeVerifier(),o=await Nt(l,{metadata:v,clientInformation:u,authorizationCode:n,codeVerifier:a,redirectUri:e.redirectUrl,resource:_,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(pt(o,y)),`AUTHORIZED`}let S=await e.tokens();if(S?.refresh_token){let t=await K({provider:e,clientInformation:u,tokens:S});t?q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:y}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Pt(l,{metadata:v,clientInformation:u,refreshToken:S.refresh_token,resource:_,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(pt(t,y)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof F)||e instanceof I))throw e}}let C=e.state?await e.state():void 0;C&&e.saveState&&await e.saveState(C);let{authorizationUrl:ee,codeVerifier:te}=await Dt(l,{metadata:v,clientInformation:u,state:C,redirectUrl:e.redirectUrl,scope:x,resource:_});if(!await gt({provider:e,clientInformation:u,authorizationServerInformation:y}))throw new F({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(te),await e.redirectToAuthorization(ee),`REDIRECT`}function zt(e){return e===void 0||e===`message`}var Bt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??T};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return v(t,`ai-sdk/${Ye}`,r())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,o,s,c;try{let c=await this.commonHeaders({Accept:`text/event-stream`}),l=await this.fetchFn(this.url.href,{headers:c,signal:this.abortController?.signal,redirect:this.redirectMode});if(l.status===401&&this.authProvider&&!r){let{resourceMetadataUrl:e,scope:r}=J(l);this.resourceMetadataUrl=e;try{if(await Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,scope:r,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new V;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(o=this.onerror)==null||o.call(this,e),t(e)}return n(!0)}if(!l.ok||!l.body){let e=`MCP SSE Transport Error: ${l.status} ${l.statusText}`;l.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new N({message:e});return(s=this.onerror)==null||s.call(this,n),t(n)}let u=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new a).getReader(),d=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await u.read();if(t){if(this.connected)throw this.connected=!1,new N({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new N({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(zt(s))try{let e=await M(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new N({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),t(e)}};this.sseConnection={close:()=>u.cancel()},d()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(c=this.onerror)==null||c.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 N({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}=J(i);if(this.resourceMetadataUrl=e,await Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,scope:t,fetchFn:this.fetchFn})!==`AUTHORIZED`)throw new V;return o(!0)}if(!i.ok){let e=await i.text().catch(()=>null);throw new N({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()}},Vt=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Ht=/^=\?base64\?.*\?=$/;function Ut(e){return[...e].every(e=>{let t=e.charCodeAt(0);return t===9||t>=32&&t<=126})&&e.trim()===e&&!Ht.test(e)?e:`=?base64?${l(new TextEncoder().encode(e))}?=`}function Wt(e){if(!s(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&&s(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`||!Vt.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`&&s(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 Gt(e,t){let n=e;for(let e of t){if(!s(n))return;n=n[e]}return n}function Kt({bindings:e,args:t}){let n={};for(let r of e){let e=Gt(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}`]=Ut(String(e))}}return n}function qt(e){return e===void 0||e===`message`}var Jt=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??T,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??w)===w}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??T};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 v(n,`ai-sdk/${Ye}`,r())}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||=Z(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 N({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.protocolVersion!=null&&this.protocolVersion!==w&&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]),o=async(n=!1)=>{var r,s,c,l,u,d,f;try{let f=`method`in e&&e.method===`initialize`,p=f?void 0:this.sessionId,m={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:!f}),body:JSON.stringify(e),signal:i,redirect:this.redirectMode},h=await this.fetchFn(this.url.href,m);if(this.applySessionIdFromResponse(h),h.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=J(h);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,t)!==`AUTHORIZED`)throw new V}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return o(!0)}if(h.status===202){!this.isModernProtocol()&&!this.inboundSseConnection&&this.startInboundSse();return}if(!h.ok){let t=await h.text().catch(()=>null);if(`id`in e&&t!=null){let n=await M(t).catch(()=>void 0);if(n!=null&&`error`in n){(s=this.onmessage)==null||s.call(this,n.id==null?{...n,id:e.id}:n);return}}let n=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${h.status}): ${t}`;h.status===404&&(!this.isModernProtocol()&&p?(this.expireSessionId(p),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 N({message:n,statusCode:h.status,url:this.url.href,responseBody:t??void 0});throw(c=this.onerror)==null||c.call(this,r),r}if(!(`id`in e))return;let g=h.headers.get(`content-type`)||``;if(g.includes(`application/json`)){let e=await h.json(),t=Array.isArray(e)?e.map(e=>j(e)):[j(e)];for(let e of t)(l=this.onmessage)==null||l.call(this,e);return}if(g.includes(`text/event-stream`)){if(!h.body){let e=new N({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:h.status,url:this.url.href});throw(u=this.onerror)==null||u.call(this,e),e}let e=h.body.pipeThrough(new TextDecoderStream).pipeThrough(new a).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(qt(a))try{let e=await M(o);(n=this.onmessage)==null||n.call(this,e)}catch(e){let t=new N({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 _=new N({message:`MCP HTTP Transport Error: Unexpected content type: ${g}`,statusCode:h.status,url:this.url.href});throw(d=this.onerror)==null||d.call(this,_),_}catch(e){throw t?.signal?.aborted||(f=this.onerror)==null||f.call(this,e),e}};await o()}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`]=Ut(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 N({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},n)}startInboundSse(e=!1,t){this.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,o;if(!this.isModernProtocol())try{let o=this.sessionId,s=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(s[`last-event-id`]=t);let c=await this.fetchFn(this.url.href,{method:`GET`,headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(c),c.status===401&&this.authProvider&&!e){let{resourceMetadataUrl:e,scope:i}=J(c);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,i)!==`AUTHORIZED`){let e=new V;(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(c.status===405)return;if(!c.ok||!c.body){c.status===404&&o&&this.expireSessionId(o);let e=new N({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`,statusCode:c.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new a).getReader(),u=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await l.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),qt(i))try{let t=await M(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new N({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{l.cancel().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}},this.inboundReconnectAttempts=0,u().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;(o=this.onerror)==null||o.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function Yt(e){switch(e.type){case`sse`:return new Bt(e);case`http`:return new Jt({...e,initialProtocolVersion:e.initialProtocolVersion??w});default:throw new N({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Xt(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Zt=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,Qt=`ui/resourceUri`,$t={extensions:{[Zt]:{mimeTypes:[Q]}}};function en(e){let n=e?.ui;return t(n)?n:void 0}var tn=y.array(y.unknown()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),nn=y.looseObject({connectDomains:tn,resourceDomains:tn,frameDomains:tn}),rn=y.looseObject({prefersBorder:y.boolean().optional().catch(void 0),csp:nn.optional().catch(void 0),permissions:y.record(y.string(),y.unknown()).optional().catch(void 0)});function an(e){let n=(t(e)?e:void 0)?.ui;if(!t(n))return;let r=rn.safeParse(n);return r.success?r.data:void 0}function on(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function sn(e){let t=en(e._meta),n=t?.resourceUri??e._meta?.[Qt],r=on(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 cn(e){let t=[],n=[];for(let r of e.tools){let e=sn(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 ln({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(g(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:an(n._meta)}}async function un({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return ln({uri:t,resource:await e.readResource({uri:t,options:n})})}var dn=`1.0.0`,fn=0,pn=1e3,mn=[-32020,-32021,-32022],hn=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function gn(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function _n(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function vn(e){let t=gn(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(N.isInstance(e)&&e.code!=null)return!1;let n=_n(e);return n!=null&&hn.includes(n)}function yn(e){if(e==null)return fn;if(!Number.isInteger(e))throw new N({message:`maxRetries must be an integer`});if(e<0)throw new N({message:`maxRetries must be >= 0`});return e}function bn({timeout:e,maxTotalTimeout:t}){return e==null?t:t==null?e:Math.min(e,t)}function xn(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 Sn({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 Cn(e){let t=new wn(e);return await t.init(),t}var wn=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=dn,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:T,capabilities:{},serverInfo:this._serverInfo},this.protocolEra=`legacy`,this.protocolVersion=T,this.toolHeaderBindings=new Map,this.isClosed=!0,this.onUncaughtError=i,this.maxRetries=yn(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,this.initializationOptions=c,this.protocolVersionDiscovery=l,this.transport=Xt(e)?e:Yt(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new N({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){let e=this.initializationOptions?.signal,t=this.initializationOptions?bn(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 N({message:`MCP client initialization timed out after ${t}ms`}),n?.abort(a)},t));try{if(this.isClosed=!1,r?.throwIfAborted(),await xn(this.transport.start(),r),this.initialInitializeResult){let e=ue.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=T,this.setTransportProtocolVersion(this.protocolVersion);let e=await this.request({request:{method:`initialize`,params:{protocolVersion:T,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:ue,options:{signal:r}});if(e===void 0)throw new N({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`},{signal:r}),this}catch(t){try{await xn(this.transport.close({signal:r}),r)}catch{}throw this.onClose(),a??(e?.aborted?new N({message:`MCP client initialization was aborted`,cause:e.reason}):t)}finally{i!=null&&clearTimeout(i)}}async tryProtocolDiscovery(e){this.protocolEra=`modern`,this.protocolVersion=w,this.setTransportProtocolVersion(this.protocolVersion);try{let t=await this.request({request:{method:`server/discover`},resultSchema:le,options:{signal:e,timeout:pn}});return this.applyDiscoverResult(t),!0}catch(e){if(N.isInstance(e)&&e.code!=null&&mn.includes(e.code))throw e;return!1}}applyDiscoverResult(e){if(!e.supportedVersions.includes(this.protocolVersion))throw new N({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(!re.includes(e.protocolVersion))throw new N({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 N({message:`Server does not support completions`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new N({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new N({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new N({message:`Server does not support prompts`});break;default:throw new N({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new N({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=n==null?void 0:bn(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 N({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 N({message:`Modern MCP result is missing resultType`});if(e.result.resultType===`input_required`)throw new N({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=N.isInstance(e)?e:new N({message:`Failed to parse server response`,cause:e});g(t)}}),a?.addEventListener(`abort`,_,{once:!0}),o!=null&&(l=setTimeout(()=>{let e=new N({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:fe,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=Wt(e.inputSchema);return t.success?(this.toolHeaderBindings.set(e.name,t.bindings),!0):(this.onError(new N({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 Kt({bindings:t,args:n})}catch(t){throw new N({message:`Failed to create MCP headers for tool "${e.params.name}"`,cause:t})}}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():_({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:vn,createRetryError:({message:e,errors:t})=>new N({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){try{return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:Te,options:n})})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:ge,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Oe,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:De,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Fe,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Le,options:n})}catch(e){throw e}}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:Me,options:e})}async notification(e,t){let n={...e,jsonrpc:`2.0`};await xn(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:s,annotations:c,_meta:l}of e.tools){let e=i??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let u=this,d=t===`automatic`?void 0:t[r]?.outputSchema,p=sn({_meta:l}),h={clientName:this.clientInfo.name,toolName:r,...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:Q}}},g=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await u.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||d==null?i:u.extractStructuredContent(i,d,r)};n[r]={...t===`automatic`?f({description:a,title:e,metadata:h,inputSchema:o({...s,properties:s.properties??{},additionalProperties:!1}),execute:g,toModelOutput:Sn}):m({description:a,title:e,metadata:h,inputSchema:t[r].inputSchema,...d==null?{}:{outputSchema:d},execute:g,toModelOutput:Sn}),_meta:l}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await p({value:e.structuredContent,schema:h(t)});if(!r.success)throw new N({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 c({text:r.text,schema:t});if(!e.success)throw new N({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new N({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!==k)throw new N({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=k.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=ze.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new N({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){if(e.id==null){this.onError(new N({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 N({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new N({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},Tn=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 En(e){return l(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function Dn(e){let t=await crypto.subtle.digest(`SHA-256`,Tn.encode($({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return En(new Uint8Array(t))}function On(e,t){return e!==t}export{ze as ElicitResultSchema,k as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,V as UnauthorizedError,Z as auth,Cn as createMCPClient,Cn as experimental_createMCPClient,On as detectMCPAppResourceDrift,Dn as fingerprintMCPAppResource,$t as mcpAppClientCapabilities,un as readMCPAppResource,cn as splitMCPAppTools,j as validateJSONRPCMessage};
|
|
1
|
+
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{A as n,P as r,Q as i,St as a,U as o,V as s,ct as c,d as l,gt as u,j as d,k as f,lt as p,pt as m,r as h,s as g,st as _,yt as v}from"../../_chunks/workflow/dist-C3ZE62yI.js";import*as y from"#compiled/zod/index.js";import{z as b}from"#compiled/zod/index.js";let x;x=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function S(e){return(await x).getRandomValues(new Uint8Array(e))}async function C(e){let t=``;for(;t.length<e;){let n=await S(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function ee(e){return await C(e)}async function te(e){let t=await(await x).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function ne(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await ee(e);return{code_verifier:t,code_challenge:await te(t)}}var w=`2026-07-28`,T=`2025-11-25`,re=[w,T,`2025-06-18`,`2025-03-26`,`2024-11-05`],ie=b.optional(b.record(b.string(),b.unknown())),ae=b.looseObject({name:b.string(),version:b.string(),title:b.optional(b.string())}),E=b.looseObject({_meta:b.optional(b.object({}).loose())}),D=E.extend({resultType:b.optional(b.string())}),oe=b.object({method:b.string(),params:b.optional(E)}),se=b.object({applyDefaults:b.optional(b.boolean())}).loose(),ce=b.looseObject({experimental:b.optional(b.object({}).loose()),logging:b.optional(b.object({}).loose()),completions:b.optional(b.object({}).loose()),prompts:b.optional(b.looseObject({listChanged:b.optional(b.boolean())})),resources:b.optional(b.looseObject({subscribe:b.optional(b.boolean()),listChanged:b.optional(b.boolean())})),tools:b.optional(b.looseObject({listChanged:b.optional(b.boolean())})),elicitation:b.optional(se)});b.object({elicitation:b.optional(se)}).loose();var le=D.extend({supportedVersions:b.array(b.string()),capabilities:ce,instructions:b.optional(b.string()),ttlMs:b.optional(b.number()),cacheScope:b.optional(b.union([b.literal(`public`),b.literal(`private`)]))}),ue=D.extend({protocolVersion:b.string(),capabilities:ce,serverInfo:ae,instructions:b.optional(b.string())}),O=D.extend({nextCursor:b.optional(b.string())}),de=b.object({name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),inputSchema:b.looseObject({type:b.optional(b.unknown()),properties:b.optional(b.object({}).loose())}),outputSchema:b.optional(b.object({}).loose()),annotations:b.optional(b.object({title:b.optional(b.string()),readOnlyHint:b.optional(b.boolean()),destructiveHint:b.optional(b.boolean()),idempotentHint:b.optional(b.boolean()),openWorldHint:b.optional(b.boolean())}).loose()),_meta:ie}).loose(),fe=O.extend({tools:b.array(de)}),pe=b.object({type:b.literal(`text`),text:b.string()}).loose(),me=b.object({type:b.literal(`image`),data:b.base64(),mimeType:b.string()}).loose(),he=b.object({uri:b.string(),name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),mimeType:b.optional(b.string()),size:b.optional(b.number())}).loose(),ge=O.extend({resources:b.array(he)}),_e=b.object({uri:b.string(),name:b.optional(b.string()),title:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),ve=_e.extend({text:b.string()}),ye=_e.extend({blob:b.base64()}),be=b.object({type:b.literal(`resource`),resource:b.union([ve,ye])}).loose(),xe=b.object({type:b.literal(`resource_link`),uri:b.string(),name:b.string(),description:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),Se=b.object({type:b.string()}).loose().refine(e=>![`text`,`image`,`resource`,`resource_link`].includes(e.type),{message:`Known content types must match their schema`}),Ce=D.extend({content:b.array(b.union([pe,me,be,xe,Se])),structuredContent:b.optional(b.unknown()),isError:b.boolean().default(!1).optional()}),we=D.extend({content:b.never().optional(),structuredContent:b.json(),isError:b.boolean().default(!1).optional()}).transform(e=>({...e,content:[{type:`text`,text:JSON.stringify(e.structuredContent)}]})).pipe(Ce),Te=Ce.or(we).or(D.extend({toolResult:b.unknown().nonoptional()})),Ee=b.object({uriTemplate:b.string(),name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),mimeType:b.optional(b.string())}).loose(),De=D.extend({resourceTemplates:b.array(Ee)}),Oe=D.extend({contents:b.array(b.union([ve,ye]))}),ke=b.object({type:b.literal(`ref/prompt`),name:b.string()}).loose(),Ae=b.object({type:b.literal(`ref/resource`),uri:b.string()}).loose(),je=b.object({name:b.string(),value:b.string()}).loose();E.extend({ref:b.union([ke,Ae]),argument:je,context:b.optional(b.object({arguments:b.record(b.string(),b.string())}).loose())});var Me=D.extend({completion:b.object({values:b.array(b.string()).max(100),total:b.optional(b.number().int()),hasMore:b.optional(b.boolean())}).loose()}),Ne=b.object({name:b.string(),description:b.optional(b.string()),required:b.optional(b.boolean())}).loose(),Pe=b.object({name:b.string(),title:b.optional(b.string()),description:b.optional(b.string()),arguments:b.optional(b.array(Ne))}).loose(),Fe=O.extend({prompts:b.array(Pe)}),Ie=b.object({role:b.union([b.literal(`user`),b.literal(`assistant`)]),content:b.union([pe,me,be,xe])}).loose(),Le=D.extend({description:b.optional(b.string()),messages:b.array(Ie)}),Re=E.extend({message:b.string(),requestedSchema:b.unknown()}),k=oe.extend({method:b.literal(`elicitation/create`),params:Re}),ze=D.extend({action:b.union([b.literal(`accept`),b.literal(`decline`),b.literal(`cancel`)]),content:b.optional(b.record(b.string(),b.unknown()))}),A=`2.0`,Be=b.object({jsonrpc:b.literal(A),id:b.union([b.string(),b.number().int()])}).merge(oe).strict(),Ve=b.object({jsonrpc:b.literal(A),id:b.union([b.string(),b.number().int()]),result:D}).strict(),He=b.object({jsonrpc:b.literal(A),id:b.optional(b.union([b.string(),b.number().int()])),error:b.object({code:b.number().int(),message:b.string(),data:b.optional(b.unknown())})}).strict(),Ue=b.object({jsonrpc:b.literal(A)}).merge(b.object({method:b.string(),params:b.optional(E)})).strict(),We=b.union([Be,Ue,Ve,He]);function j(e){return We.parse(e)}async function M(e){return j(await i({text:e}))}var Ge=`vercel.ai.error.AI_MCPClientError`,Ke=Symbol.for(Ge),qe,Je,N=class extends (Je=e,qe=Ke,Je){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[qe]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,Ge)}},Ye=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,P=b.string().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:b.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),b.NEVER}).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`}),Xe=b.object({access_token:b.string(),id_token:b.string().optional(),token_type:b.string(),expires_in:b.number().optional(),scope:b.string().optional(),refresh_token:b.string().optional(),issuer:P.optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),Ze=b.looseObject({resource:b.string().url(),authorization_servers:b.array(P).optional(),jwks_uri:b.string().url().optional(),scopes_supported:b.array(b.string()).optional(),bearer_methods_supported:b.array(b.string()).optional(),resource_signing_alg_values_supported:b.array(b.string()).optional(),resource_name:b.string().optional(),resource_documentation:b.string().optional(),resource_policy_uri:b.string().url().optional(),resource_tos_uri:b.string().url().optional(),tls_client_certificate_bound_access_tokens:b.boolean().optional(),authorization_details_types_supported:b.array(b.string()).optional(),dpop_signing_alg_values_supported:b.array(b.string()).optional(),dpop_bound_access_tokens_required:b.boolean().optional()}),Qe=b.looseObject({issuer:b.string(),authorization_endpoint:P,token_endpoint:P,registration_endpoint:P.optional(),authorization_response_iss_parameter_supported:b.boolean().optional(),client_id_metadata_document_supported:b.boolean().optional(),scopes_supported:b.array(b.string()).optional(),response_types_supported:b.array(b.string()),grant_types_supported:b.array(b.string()).optional(),code_challenge_methods_supported:b.array(b.string()).optional(),token_endpoint_auth_methods_supported:b.array(b.string()).optional(),token_endpoint_auth_signing_alg_values_supported:b.array(b.string()).optional()}),$e=b.looseObject({issuer:b.string(),authorization_endpoint:P,token_endpoint:P,userinfo_endpoint:P.optional(),jwks_uri:P,registration_endpoint:P.optional(),authorization_response_iss_parameter_supported:b.boolean().optional(),client_id_metadata_document_supported:b.boolean().optional(),scopes_supported:b.array(b.string()).optional(),response_types_supported:b.array(b.string()),grant_types_supported:b.array(b.string()).optional(),subject_types_supported:b.array(b.string()),id_token_signing_alg_values_supported:b.array(b.string()),claims_supported:b.array(b.string()).optional(),token_endpoint_auth_methods_supported:b.array(b.string()).optional()}).merge(Qe.pick({code_challenge_methods_supported:!0})),et=b.object({client_id:b.string(),client_secret:b.string().optional(),client_id_issued_at:b.number().optional(),client_secret_expires_at:b.number().optional(),issuer:P.optional(),authorization_server:P.optional(),token_endpoint:P.optional()}).strip(),tt=b.object({redirect_uris:b.array(P),application_type:b.union([b.literal(`native`),b.literal(`web`)]).optional(),token_endpoint_auth_method:b.string().optional(),grant_types:b.array(b.string()).optional(),response_types:b.array(b.string()).optional(),client_name:b.string().optional(),client_uri:P.optional(),logo_uri:P.optional(),scope:b.string().optional(),contacts:b.array(b.string()).optional(),tos_uri:P.optional(),policy_uri:b.string().optional(),jwks_uri:P.optional(),jwks:b.any().optional(),software_id:b.string().optional(),software_version:b.string().optional(),software_statement:b.string().optional()}).strip(),nt=b.object({error:b.string(),error_description:b.string().optional(),error_uri:b.string().optional()}),rt=tt.merge(et),it=`vercel.ai.error.AI_MCPClientOAuthError`,at=Symbol.for(it),ot,st,F=class extends (st=e,ot=at,st){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[ot]=!0}static isInstance(t){return e.hasMarker(t,it)}},I=class extends F{};I.errorCode=`server_error`;var L=class extends F{};L.errorCode=`invalid_client`;var R=class extends F{};R.errorCode=`invalid_grant`;var z=class extends F{};z.errorCode=`unauthorized_client`;var ct={[I.errorCode]:I,[L.errorCode]:L,[R.errorCode]:R,[z.errorCode]:z};function lt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function B(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function ut({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 V=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function H(e){return new URL(e).href}function U(e){let t=e.toLowerCase().replace(/\.+$/,``);return t===`localhost`||t.endsWith(`.localhost`)||t===`127.0.0.1`||t===`[::1]`||t===`::1`}function W(e,{allowLoopback:t=!1}={}){if(!t||e.protocol!==`http:`&&e.protocol!==`https:`||!U(e.hostname))try{u(e.href)}catch(t){throw new F({message:`OAuth endpoint URL is not allowed: ${e.href}`,cause:t})}}function G(e){let t=new URL(e);return U(t.hostname)?t.origin:void 0}function dt({callbackIssuer:e,expectedIssuer:t}){if(e!=null&&e!==t)throw new F({message:`OAuth authorization response issuer ${e} does not match expected issuer ${t}`})}function ft(e,t){return{issuer:t?.issuer??String(e),authorizationServerUrl:H(e),tokenEndpoint:H(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function pt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function mt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ht(e){if(e?.authorization_server&&e.token_endpoint)return{issuer:e.issuer,authorizationServerUrl:H(e.authorization_server),tokenEndpoint:H(e.token_endpoint)}}async function K({provider:e,clientInformation:t,tokens:n}){let r=ht(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{issuer:i.issuer,authorizationServerUrl:H(i.authorizationServerUrl),tokenEndpoint:H(i.tokenEndpoint)}:ht(t)}async function gt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(mt(t,n)),!0):!1}function _t(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new F({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function q({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 F({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function J(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 vt({scope:e,resourceMetadata:t,clientMetadata:n}){return e||(t?.scopes_supported)?.join(` `)||n.scope}function yt(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Y(e,t,r=fetch,i){try{return await d({url:e.href,fetch:async(e,a)=>n({url:e,init:{...a,headers:new Headers(a?.headers).has(`MCP-Protocol-Version`)?t:void 0},fetch:r,trustedOrigin:i,redirect:`manual`}),headers:t,trustedOrigin:i})}catch(n){if(n instanceof TypeError)return t?Y(e,void 0,r,i):void 0;throw n}}async function bt(e,t,n=fetch,r){return await Y(e,{"MCP-Protocol-Version":t},n,r)}function xt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function St(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??w,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=yt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await bt(o,a,n,r?.trustedOrigin);return!r?.metadataUrl&&xt(s,i.pathname)&&(s=await bt(new URL(`/.well-known/${t}`,i),a,n,r?.trustedOrigin)),s}async function Ct(e,t,n=fetch){let r=await St(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl,trustedOrigin:new URL(e).origin});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 Ze.parse(await r.json())}function wt(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 Tt(e,t){if(!(e.issuer===t||t===new URL(t).origin&&e.issuer===`${t}/`))throw new F({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Et(e,{fetchFn:t=fetch,protocolVersion:n=w,trustedOrigin:r}={}){let i={"MCP-Protocol-Version":n},a=wt(e);for(let{url:e,type:n,expectedIssuer:o}of a){let a=await Y(e,i,t,r);if(a){if(!a.ok){if(a.status>=400&&a.status<500)continue;throw Error(`HTTP ${a.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=Qe.parse(await a.json());return Tt(e,o),e}{let t=$e.parse(await a.json());if(Tt(t,o),!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 Dt(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 ne(),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`,B(o)),{authorizationUrl:l,codeVerifier:d}}function Ot(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 kt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:At(i,a,n);return;case`client_secret_post`:jt(i,a,r);return;case`none`:Mt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function At(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 jt(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 X(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}=nt.parse(await i({text:n}));return new(ct[e]||I)({message:t||``,cause:r})}catch(e){return new I({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Nt(e,{metadata:t,clientInformation:r,authorizationCode:i,codeVerifier:a,redirectUri:o,resource:s,addClientAuthentication:c,fetchFn:l}){let u=`authorization_code`,d=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),f=G(e);if(W(d,{allowLoopback:d.origin===f}),t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw Error(`Incompatible auth server: does not support grant type ${u}`);let p=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),m=new URLSearchParams({grant_type:u,code:i,code_verifier:a,redirect_uri:String(o)});c?await c(p,m,e,t):kt(Ot(r,t?.token_endpoint_auth_methods_supported??[]),r,p,m),s&&m.set(`resource`,B(s));let h=await n({url:d,init:{method:`POST`,headers:p,body:m},fetch:l,trustedOrigin:f});if(!h.ok)throw await X(h);return Xe.parse(await h.json())}async function Pt(e,{metadata:t,clientInformation:r,refreshToken:i,resource:a,addClientAuthentication:o,fetchFn:s}){let c=`refresh_token`,l;if(t){if(l=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL(`/token`,e);let u=G(e);W(l,{allowLoopback:l.origin===u});let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:c,refresh_token:i});o?await o(d,f,e,t):kt(Ot(r,t?.token_endpoint_auth_methods_supported??[]),r,d,f),a&&f.set(`resource`,B(a));let p=await n({url:l,init:{method:`POST`,headers:d,body:f},fetch:s,trustedOrigin:u});if(!p.ok)throw await X(p);return Xe.parse({refresh_token:i,...await p.json()})}async function Ft(e,{metadata:t,clientMetadata:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o=G(e);W(a,{allowLoopback:a.origin===o});let s=r.application_type??It(r.redirect_uris),c=await n({url:a,init:{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...r,application_type:s})},fetch:i,trustedOrigin:o});if(!c.ok)throw await X(c);return rt.parse(await c.json())}function It(e){return e.every(e=>{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&U(t.hostname)||t.protocol!==`http:`&&t.protocol!==`https:`})?`native`:`web`}async function Z(e,t){try{return await Rt(e,t)}catch(n){if(n instanceof L||n instanceof z)return await e.invalidateCredentials?.call(e,`all`),await Rt(e,t);if(n instanceof R)return await e.invalidateCredentials?.call(e,`tokens`),await Rt(e,t);throw n}}async function Lt(e,t,n){let r=lt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!ut({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 Rt(e,{serverUrl:t,authorizationCode:n,callbackState:r,callbackIssuer:i,scope:a,resourceMetadataUrl:o,fetchFn:s}){let c,l,u,d;_t(t,o);try{c=await Ct(t,{resourceMetadataUrl:o},s),c.authorization_servers&&c.authorization_servers.length>0&&(l=c.authorization_servers[0])}catch{}n!==void 0&&(u=await Promise.resolve(e.clientInformation()),u&&(d=await K({provider:e,clientInformation:u}))),l||=d?.authorizationServerUrl??t;let f=new URL(t),p=new URL(l),m=f.origin,h=p.origin,g=h===m||U(f.hostname)&&U(p.hostname)?h:void 0;g||W(new URL(l));let _=await Lt(t,e,c);await e.validateAuthorizationServerURL?.call(e,t,l);let v=await Et(l,{fetchFn:s,trustedOrigin:g}),y=ft(l,v),b=e.clientMetadata,x=vt({scope:a,resourceMetadata:c,clientMetadata:b});if(n===void 0&&(u=await Promise.resolve(e.clientInformation())),u?.issuer!=null){let t=d??await K({provider:e,clientInformation:u});t&&q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:y})}if(!u){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`);u=mt(await Ft(l,{metadata:v,clientMetadata:{...b,scope:x},fetchFn:s}),y),await e.saveClientInformation(u)}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=d??await K({provider:e,clientInformation:u});if(!t)throw new F({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});dt({callbackIssuer:i,expectedIssuer:t.issuer??v?.issuer??String(l)}),q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:y});let a=await e.codeVerifier(),o=await Nt(l,{metadata:v,clientInformation:u,authorizationCode:n,codeVerifier:a,redirectUri:e.redirectUrl,resource:_,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(pt(o,y)),`AUTHORIZED`}let S=await e.tokens();if(S?.refresh_token){let t=await K({provider:e,clientInformation:u,tokens:S});t?q({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:y}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Pt(l,{metadata:v,clientInformation:u,refreshToken:S.refresh_token,resource:_,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(pt(t,y)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof F)||e instanceof I))throw e}}let C=e.state?await e.state():void 0;C&&e.saveState&&await e.saveState(C);let{authorizationUrl:ee,codeVerifier:te}=await Dt(l,{metadata:v,clientInformation:u,state:C,redirectUrl:e.redirectUrl,scope:x,resource:_});if(!await gt({provider:e,clientInformation:u,authorizationServerInformation:y}))throw new F({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(te),await e.redirectToAuthorization(ee),`REDIRECT`}function zt(e){return e===void 0||e===`message`}var Bt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??T};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return v(t,`ai-sdk/${Ye}`,r())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,o,s,c;try{let c=await this.commonHeaders({Accept:`text/event-stream`}),l=await this.fetchFn(this.url.href,{headers:c,signal:this.abortController?.signal,redirect:this.redirectMode});if(l.status===401&&this.authProvider&&!r){let{resourceMetadataUrl:e,scope:r}=J(l);this.resourceMetadataUrl=e;try{if(await Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,scope:r,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new V;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(o=this.onerror)==null||o.call(this,e),t(e)}return n(!0)}if(!l.ok||!l.body){let e=`MCP SSE Transport Error: ${l.status} ${l.statusText}`;l.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new N({message:e});return(s=this.onerror)==null||s.call(this,n),t(n)}let u=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new a).getReader(),d=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await u.read();if(t){if(this.connected)throw this.connected=!1,new N({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new N({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(zt(s))try{let e=await M(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new N({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),t(e)}};this.sseConnection={close:()=>u.cancel()},d()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(c=this.onerror)==null||c.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 N({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}=J(i);if(this.resourceMetadataUrl=e,await Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,scope:t,fetchFn:this.fetchFn})!==`AUTHORIZED`)throw new V;return o(!0)}if(!i.ok){let e=await i.text().catch(()=>null);throw new N({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()}},Vt=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Ht=/^=\?base64\?.*\?=$/;function Ut(e){return[...e].every(e=>{let t=e.charCodeAt(0);return t===9||t>=32&&t<=126})&&e.trim()===e&&!Ht.test(e)?e:`=?base64?${l(new TextEncoder().encode(e))}?=`}function Wt(e){if(!s(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&&s(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`||!Vt.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`&&s(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 Gt(e,t){let n=e;for(let e of t){if(!s(n))return;n=n[e]}return n}function Kt({bindings:e,args:t}){let n={};for(let r of e){let e=Gt(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}`]=Ut(String(e))}}return n}function qt(e){return e===void 0||e===`message`}var Jt=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??T,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??w)===w}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??T};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 v(n,`ai-sdk/${Ye}`,r())}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||=Z(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 N({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.protocolVersion!=null&&this.protocolVersion!==w&&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]),o=async(n=!1)=>{var r,s,c,l,u,d,f;try{let f=`method`in e&&e.method===`initialize`,p=f?void 0:this.sessionId,m={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:!f}),body:JSON.stringify(e),signal:i,redirect:this.redirectMode},h=await this.fetchFn(this.url.href,m);if(this.applySessionIdFromResponse(h),h.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=J(h);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,t)!==`AUTHORIZED`)throw new V}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return o(!0)}if(h.status===202){!this.isModernProtocol()&&!this.inboundSseConnection&&this.startInboundSse();return}if(!h.ok){let t=await h.text().catch(()=>null);if(`id`in e&&t!=null){let n=await M(t).catch(()=>void 0);if(n!=null&&`error`in n){(s=this.onmessage)==null||s.call(this,n.id==null?{...n,id:e.id}:n);return}}let n=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${h.status}): ${t}`;h.status===404&&(!this.isModernProtocol()&&p?(this.expireSessionId(p),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 N({message:n,statusCode:h.status,url:this.url.href,responseBody:t??void 0});throw(c=this.onerror)==null||c.call(this,r),r}if(!(`id`in e))return;let g=h.headers.get(`content-type`)||``;if(g.includes(`application/json`)){let e=await h.json(),t=Array.isArray(e)?e.map(e=>j(e)):[j(e)];for(let e of t)(l=this.onmessage)==null||l.call(this,e);return}if(g.includes(`text/event-stream`)){if(!h.body){let e=new N({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:h.status,url:this.url.href});throw(u=this.onerror)==null||u.call(this,e),e}let e=h.body.pipeThrough(new TextDecoderStream).pipeThrough(new a).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(qt(a))try{let e=await M(o);(n=this.onmessage)==null||n.call(this,e)}catch(e){let t=new N({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 _=new N({message:`MCP HTTP Transport Error: Unexpected content type: ${g}`,statusCode:h.status,url:this.url.href});throw(d=this.onerror)==null||d.call(this,_),_}catch(e){throw t?.signal?.aborted||(f=this.onerror)==null||f.call(this,e),e}};await o()}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`]=Ut(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 N({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},n)}startInboundSse(e=!1,t){this.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,o;if(!this.isModernProtocol())try{let o=this.sessionId,s=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(s[`last-event-id`]=t);let c=await this.fetchFn(this.url.href,{method:`GET`,headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(c),c.status===401&&this.authProvider&&!e){let{resourceMetadataUrl:e,scope:i}=J(c);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,i)!==`AUTHORIZED`){let e=new V;(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(c.status===405)return;if(!c.ok||!c.body){c.status===404&&o&&this.expireSessionId(o);let e=new N({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`,statusCode:c.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new a).getReader(),u=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await l.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),qt(i))try{let t=await M(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new N({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{l.cancel().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}},this.inboundReconnectAttempts=0,u().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;(o=this.onerror)==null||o.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function Yt(e){switch(e.type){case`sse`:return new Bt(e);case`http`:return new Jt({...e,initialProtocolVersion:e.initialProtocolVersion??w});default:throw new N({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Xt(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Zt=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,Qt=`ui/resourceUri`,$t={extensions:{[Zt]:{mimeTypes:[Q]}}};function en(e){let n=e?.ui;return t(n)?n:void 0}var tn=y.array(y.unknown()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),nn=y.looseObject({connectDomains:tn,resourceDomains:tn,frameDomains:tn}),rn=y.looseObject({prefersBorder:y.boolean().optional().catch(void 0),csp:nn.optional().catch(void 0),permissions:y.record(y.string(),y.unknown()).optional().catch(void 0)});function an(e){let n=(t(e)?e:void 0)?.ui;if(!t(n))return;let r=rn.safeParse(n);return r.success?r.data:void 0}function on(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function sn(e){let t=en(e._meta),n=t?.resourceUri??e._meta?.[Qt],r=on(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 cn(e){let t=[],n=[];for(let r of e.tools){let e=sn(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 ln({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(g(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:an(n._meta)}}async function un({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return ln({uri:t,resource:await e.readResource({uri:t,options:n})})}var dn=`1.0.0`,fn=0,pn=1e3,mn=[-32020,-32021,-32022],hn=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function gn(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function _n(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function vn(e){let t=gn(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(N.isInstance(e)&&e.code!=null)return!1;let n=_n(e);return n!=null&&hn.includes(n)}function yn(e){if(e==null)return fn;if(!Number.isInteger(e))throw new N({message:`maxRetries must be an integer`});if(e<0)throw new N({message:`maxRetries must be >= 0`});return e}function bn({timeout:e,maxTotalTimeout:t}){return e==null?t:t==null?e:Math.min(e,t)}function xn(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 Sn({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 Cn(e){let t=new wn(e);return await t.init(),t}var wn=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=dn,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:T,capabilities:{},serverInfo:this._serverInfo},this.protocolEra=`legacy`,this.protocolVersion=T,this.toolHeaderBindings=new Map,this.isClosed=!0,this.onUncaughtError=i,this.maxRetries=yn(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,this.initializationOptions=c,this.protocolVersionDiscovery=l,this.transport=Xt(e)?e:Yt(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new N({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){let e=this.initializationOptions?.signal,t=this.initializationOptions?bn(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 N({message:`MCP client initialization timed out after ${t}ms`}),n?.abort(a)},t));try{if(this.isClosed=!1,r?.throwIfAborted(),await xn(this.transport.start(),r),this.initialInitializeResult){let e=ue.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=T,this.setTransportProtocolVersion(this.protocolVersion);let e=await this.request({request:{method:`initialize`,params:{protocolVersion:T,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:ue,options:{signal:r}});if(e===void 0)throw new N({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`},{signal:r}),this}catch(t){try{await xn(this.transport.close({signal:r}),r)}catch{}throw this.onClose(),a??(e?.aborted?new N({message:`MCP client initialization was aborted`,cause:e.reason}):t)}finally{i!=null&&clearTimeout(i)}}async tryProtocolDiscovery(e){this.protocolEra=`modern`,this.protocolVersion=w,this.setTransportProtocolVersion(this.protocolVersion);try{let t=await this.request({request:{method:`server/discover`},resultSchema:le,options:{signal:e,timeout:this.transport instanceof Jt?void 0:pn}});return this.applyDiscoverResult(t),!0}catch(e){if(N.isInstance(e)&&e.code!=null&&mn.includes(e.code))throw e;return!1}}applyDiscoverResult(e){if(!e.supportedVersions.includes(this.protocolVersion))throw new N({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(!re.includes(e.protocolVersion))throw new N({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 N({message:`Server does not support completions`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new N({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new N({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new N({message:`Server does not support prompts`});break;default:throw new N({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new N({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=n==null?void 0:bn(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 N({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 N({message:`Modern MCP result is missing resultType`});if(e.result.resultType===`input_required`)throw new N({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=N.isInstance(e)?e:new N({message:`Failed to parse server response`,cause:e});g(t)}}),a?.addEventListener(`abort`,_,{once:!0}),o!=null&&(l=setTimeout(()=>{let e=new N({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:fe,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=Wt(e.inputSchema);return t.success?(this.toolHeaderBindings.set(e.name,t.bindings),!0):(this.onError(new N({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 Kt({bindings:t,args:n})}catch(t){throw new N({message:`Failed to create MCP headers for tool "${e.params.name}"`,cause:t})}}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():_({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:vn,createRetryError:({message:e,errors:t})=>new N({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){try{return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:Te,options:n})})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:ge,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Oe,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:De,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Fe,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Le,options:n})}catch(e){throw e}}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:Me,options:e})}async notification(e,t){let n={...e,jsonrpc:`2.0`};await xn(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:s,annotations:c,_meta:l}of e.tools){let e=i??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let u=this,d=t===`automatic`?void 0:t[r]?.outputSchema,p=sn({_meta:l}),h={clientName:this.clientInfo.name,toolName:r,...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:Q}}},g=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await u.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||d==null?i:u.extractStructuredContent(i,d,r)};n[r]={...t===`automatic`?f({description:a,title:e,metadata:h,inputSchema:o({...s,properties:s.properties??{},additionalProperties:!1}),execute:g,toModelOutput:Sn}):m({description:a,title:e,metadata:h,inputSchema:t[r].inputSchema,...d==null?{}:{outputSchema:d},execute:g,toModelOutput:Sn}),_meta:l}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await p({value:e.structuredContent,schema:h(t)});if(!r.success)throw new N({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 c({text:r.text,schema:t});if(!e.success)throw new N({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new N({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!==k)throw new N({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=k.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=ze.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new N({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){if(e.id==null){this.onError(new N({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 N({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new N({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},Tn=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 En(e){return l(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function Dn(e){let t=await crypto.subtle.digest(`SHA-256`,Tn.encode($({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return En(new Uint8Array(t))}function On(e,t){return e!==t}export{ze as ElicitResultSchema,k as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,V as UnauthorizedError,Z as auth,Cn as createMCPClient,Cn as experimental_createMCPClient,On as detectMCPAppResourceDrift,Dn as fingerprintMCPAppResource,$t as mcpAppClientCapabilities,un as readMCPAppResource,cn as splitMCPAppTools,j as validateJSONRPCMessage};
|
|
@@ -19,9 +19,27 @@ export interface McpToolAnnotations {
|
|
|
19
19
|
readonly readOnlyHint?: boolean;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
export interface StandardSchemaIssue {
|
|
23
|
+
readonly message: string;
|
|
24
|
+
readonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type StandardSchemaResult<TOutput> =
|
|
28
|
+
| { readonly value: TOutput; readonly issues?: undefined }
|
|
29
|
+
| { readonly issues: readonly StandardSchemaIssue[] };
|
|
30
|
+
|
|
22
31
|
export interface StandardSchemaWithJSON<TInput = unknown, TOutput = TInput> {
|
|
23
32
|
readonly "~standard": {
|
|
33
|
+
readonly version: 1;
|
|
34
|
+
readonly vendor: string;
|
|
24
35
|
readonly types?: { readonly input: TInput; readonly output: TOutput };
|
|
36
|
+
readonly validate: (
|
|
37
|
+
value: unknown,
|
|
38
|
+
) => StandardSchemaResult<TOutput> | Promise<StandardSchemaResult<TOutput>>;
|
|
39
|
+
readonly jsonSchema: {
|
|
40
|
+
readonly input: (options: { readonly target: string }) => Record<string, unknown>;
|
|
41
|
+
readonly output: (options: { readonly target: string }) => Record<string, unknown>;
|
|
42
|
+
};
|
|
25
43
|
};
|
|
26
44
|
}
|
|
27
45
|
|
|
@@ -97,8 +97,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
|
|
|
97
97
|
};
|
|
98
98
|
};
|
|
99
99
|
readonly channel: {
|
|
100
|
-
readonly current:
|
|
101
|
-
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45];
|
|
100
|
+
readonly current: 46;
|
|
101
|
+
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46];
|
|
102
102
|
readonly dropped: {
|
|
103
103
|
readonly 12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.";
|
|
104
104
|
readonly 19: "Continuation rekey was removed; channel extensions must use additive continuation.alias instead.";
|