@dudko.dev/agent-web 0.0.43 → 0.0.44
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/README.md +55 -2
- package/dist/agent-web.js +158 -158
- package/dist/agent-web.js.map +1 -1
- package/dist/{chunk-DAREMCXF.js → chunk-236RCVAZ.js} +40 -8
- package/dist/chunk-236RCVAZ.js.map +1 -0
- package/dist/{chunk-2MLHZ6LQ.js → chunk-Y4MIIBPB.js} +2 -2
- package/dist/{chunk-ZSZSSJS4.js → chunk-Y6CD3WOK.js} +176 -10
- package/dist/chunk-Y6CD3WOK.js.map +1 -0
- package/dist/{chunk-YPCHD6DV.js → chunk-YGWIOO27.js} +31 -12
- package/dist/chunk-YGWIOO27.js.map +1 -0
- package/dist/index.cjs +1052 -93
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1724 -1464
- package/dist/index.d.ts +1724 -1464
- package/dist/index.js +806 -74
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +136 -5
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts +5 -2
- package/dist/mcp.d.ts +5 -2
- package/dist/mcp.js +19 -8
- package/dist/mcp.js.map +1 -1
- package/dist/{sandbox-3VRX47UY.js → sandbox-7CGSIIIZ.js} +4 -4
- package/dist/sandbox-worker.cjs +30 -11
- package/dist/sandbox-worker.cjs.map +1 -1
- package/dist/sandbox-worker.js +1 -1
- package/dist/{elicitation-DS-84_bF.d.cts → vault-Mar2CY0J.d.cts} +526 -526
- package/dist/{elicitation-DS-84_bF.d.ts → vault-Mar2CY0J.d.ts} +526 -526
- package/package.json +1 -1
- package/dist/chunk-DAREMCXF.js.map +0 -1
- package/dist/chunk-YPCHD6DV.js.map +0 -1
- package/dist/chunk-ZSZSSJS4.js.map +0 -1
- /package/dist/{chunk-2MLHZ6LQ.js.map → chunk-Y4MIIBPB.js.map} +0 -0
- /package/dist/{sandbox-3VRX47UY.js.map → sandbox-7CGSIIIZ.js.map} +0 -0
package/dist/mcp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/http.ts","../src/mcp/elicitation.ts","../src/mcp/listen.ts","../src/mcp/oauth.ts","../src/mcp/index.ts","../src/mcp/enterprise-oauth.ts"],"sourcesContent":["import {\n auth,\n Client,\n SdkError,\n SdkErrorCode,\n StreamableHTTPClientTransport,\n UnauthorizedError,\n type CallToolResult,\n type ClientOptions,\n type FetchLike,\n type JsonSchemaType,\n type JsonSchemaValidator,\n type OAuthClientProvider,\n type StreamableHTTPReconnectionOptions,\n} from '@modelcontextprotocol/client'\nimport { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/client/validators/cf-worker'\nimport { dynamicTool, jsonSchema, type ToolSet } from 'ai'\nimport {\n describeMcpAppPolicy,\n MCP_APP_MAX_DOWNLOAD_BYTES,\n mcpAppDownloadOf,\n mcpAppsModeOf,\n type McpAppDownloadResource,\n type McpAppsMode,\n MCP_APP_MIME_TYPE,\n MCP_APPS_EXTENSION,\n mcpAppResourceOf,\n mcpAppToolMeta,\n mcpAppToolResultOf,\n type McpAppResource,\n type McpAppToolResult,\n type McpAppVisibility,\n} from './apps.js'\nimport {\n createMcpElicitationSession,\n resolveMcpElicitationOptions,\n type McpElicitationCallInfo,\n type McpElicitationDeps,\n type McpElicitationEvent,\n type McpElicitationHandler,\n type McpElicitationOptions,\n type McpElicitationSession,\n} from './elicitation.js'\nimport { createMcpListenSupervisor, type McpListenSupervisor } from './listen.js'\nimport {\n createMcpSkillCatalog,\n markMcpSkills,\n MCP_SKILLS_EXTENSION,\n mcpSkillsSettingOf,\n type McpSkillSource,\n type McpSkillsClientLike,\n type McpSkillsSetting,\n} from './skills.js'\nimport { assertSecureOAuthUrl } from './oauth.js'\nimport {\n cleanMcpInstructions,\n dropStructuredDuplicates,\n isStructuredContent,\n markMcpTool,\n MCP_MODERN_PROTOCOL_VERSION,\n MCP_MODERN_REFUSED_HINT,\n MCP_MODERN_REQUEST_HEADERS,\n mcpInputRequiredMessage,\n mcpProtocolMode,\n mcpVersionNegotiation,\n outputSchemaNote,\n withStructuredContent,\n type McpProtocolMode,\n type McpServerInstructions,\n type McpServerProtocol,\n} from './shared.js'\n\n/**\n * A remote MCP server reached over StreamableHTTP. Browsers can ONLY speak the\n * HTTP transport — stdio (child processes) is Node-only and intentionally\n * unsupported here. This connector lives behind the `@dudko.dev/agent-web/mcp`\n * subpath so `@modelcontextprotocol/client` never enters the core bundle.\n *\n * Three ways to authenticate, in ascending order of capability:\n * 1. `headers` — a static token you already hold.\n * 2. `getHeaders` — resolved once per connect, for tokens you mint yourself.\n * 3. `authProvider` — full OAuth 2.1: the SDK discovers the authorization\n * server, dynamically registers the client (DCR), runs PKCE, and — the\n * part 1 and 2 cannot do — transparently REFRESHES the access token when\n * the server answers 401 mid-run. See `./oauth`.\n */\nexport interface McpHttpServerConfig {\n url: string\n headers?: Record<string, string>\n /** Called at connect time to provide fresh headers (e.g. a rotating Bearer). */\n getHeaders?: () => Promise<Record<string, string>> | Record<string, string>\n /**\n * OAuth client provider (see `./oauth` for a browser implementation). The\n * transport sends its access token, refreshes on 401 and retries the request.\n * Do NOT also set an `Authorization` entry in `headers`: request headers are\n * merged last and would shadow the OAuth token.\n */\n authProvider?: OAuthClientProvider\n /** Custom fetch for every request: proxying, instrumentation, retries. */\n fetch?: FetchLike\n /** Overrides for the SSE reconnect backoff. Merged over the defaults below. */\n reconnection?: Partial<StreamableHTTPReconnectionOptions>\n /** Give up on this server after this many ms of connect + listing (overrides the option). */\n connectTimeoutMs?: number\n /**\n * Which revisions of the protocol this connection may use. Default `'legacy'`:\n * the 2025 revisions (the `initialize` handshake), exactly what was sent before\n * this option existed. `'auto'` asks the server first (`server/discover`) and\n * speaks 2026-07-28 to one that offers it, the 2025 handshake to any other;\n * `'modern'` is 2026-07-28 only, and a server that does not offer it fails the\n * connect. Decided once, at connect: a tool call is never retried in another\n * revision.\n *\n * CORS: 2026-07-28 adds the request headers `Mcp-Method` and `Mcp-Name` (and\n * sends `MCP-Protocol-Version` on every request, the first included). A server\n * whose `Access-Control-Allow-Headers` does not list them cannot be reached\n * that way from a page: `'modern'` then fails, and `'auto'` falls back to the\n * 2025 revisions with a warning that names the headers. See the README, \"CORS\".\n *\n * On 2026-07-28 there is no session; a tool-list change arrives over a\n * `subscriptions/listen` stream this connector opens - and opens again, with\n * backoff, when it ends while the connection is open (then `onToolsChanged`\n * fires once: a change in the gap was announced to nobody) - and an\n * `input_required` result fails the call unless the connection was given\n * `onElicitation` (see `ConnectMcpOptions`).\n */\n protocol?: McpProtocolMode\n /**\n * EXPERIMENTAL (the Skills extension is Beta): load the skills this server serves\n * (`io.modelcontextprotocol/skills`) into the agent's skills catalog, as `<server>/<skill>`.\n * Off by default: without it the extension is not declared and nothing of it is sent. Needs\n * the 2026-07-28 revision (`protocol: 'auto'` or `'modern'`): the extension is written against\n * it. The skills come with the server's tools (each mounted tool carries them, like the\n * server's instructions), so merging `tools` into the agent's config is all a host does. Their\n * text is third-party - knowledge only, never policy; see the README, \"MCP skills\".\n * `true`, or `{ consent, dynamic }`: `consent` is when a person is asked before one of its\n * skills enters the model's context - `'once-per-skill'` (default, or the agent's\n * `mcpSkills.consent`), `'ask'` (every run) or `'never'` (a server you vetted); `dynamic: true`\n * also takes its GENERATED skills (`\"resources\": \"dynamic\"`, no checksums - declined by\n * default), each read whole into a snapshot in memory before anyone is asked, approved and used\n * as that copy only (README, \"MCP skills\").\n */\n skills?: McpSkillsSetting\n /**\n * MCP Apps for THIS server, over the connection's `apps`: `false` keeps its apps off while\n * other servers' are shown - nothing is declared to it, no app of it is read, no `mcp.app`\n * event is told, and a tool it marks for its app only (`visibility` without `'model'`) is\n * not mounted; its other tools are the model's, as plain tools. `true` turns them on for this\n * server alone. Left out, the connection's `apps` decides.\n */\n apps?: boolean\n}\n\nexport interface McpCatalogEntry {\n name: string\n description: string\n server: string\n /** The server marked the tool read-only (`annotations.readOnlyHint`). */\n readOnly?: boolean\n /**\n * With `apps: true`: the MCP App (`ui://…`) the tool declares. Its results then come with an\n * `mcp.app` event, and the host can show the app (`ConnectedMcp.apps`).\n */\n app?: string\n}\n\nexport interface McpServerResult {\n name: string\n connected: boolean\n error?: string\n /**\n * The server demands OAuth and we have no usable token. When the config\n * carried a `BrowserOAuthProvider`, its `authorizationUrl` now holds the page\n * to send the user to; reconnect once they are back.\n */\n needsAuthorization?: boolean\n}\n\nexport interface ConnectedMcp {\n /** Discovered tools, keyed by \"server__tool\", ready to merge into config.tools. */\n tools: ToolSet\n catalog: McpCatalogEntry[]\n /** Per-server connect outcome. */\n results: McpServerResult[]\n /**\n * The `instructions` each connected server returned in its `initialize`\n * result, in declaration order; servers that sent none are absent. Read once\n * per connection. Third-party text: the agent shows it to the model under a\n * preamble that says so (`config.mcpInstructions`, on by default) — each\n * mounted tool carries its server's instructions, so merging `tools` into\n * the agent's config is all a host does.\n */\n instructions: McpServerInstructions[]\n /**\n * The protocol revision negotiated with each connected server, in declaration\n * order: `2025-…` after the `initialize` handshake (always, for a server\n * without `protocol`), `2026-07-28` when `protocol: 'auto'` or `'modern'`\n * found a server that offers it. Fixed for the life of the connection.\n */\n protocols: McpServerProtocol[]\n /**\n * Re-list one server's tools and rewrite its entries in `tools`/`catalog`.\n * Both are mutated in place, so anything holding a reference (including a\n * live agent config) sees the new set. Throws if the server isn't connected.\n * With `skills: true` it lists the server's skills again too (an agent built\n * after the refresh has the new ones; one built before keeps what it read).\n */\n refreshServer: (name: string) => Promise<void>\n close: () => Promise<void>\n /**\n * MCP Apps, present only on a connection made with `apps: true`: read an app's HTML and make\n * the tool calls an app asks for. See {@link McpAppsConnection}.\n */\n apps?: McpAppsConnection\n}\n\n/** A tool of a server as an app of that server sees it (see `McpAppsConnection.appTool`). */\nexport interface McpAppTool {\n /** The server's own name for the tool. */\n name: string\n /**\n * The name the agent's consent rules match: the key the tool is mounted under, or the key it\n * would have (`server__tool`) when it is for apps only and not mounted.\n */\n key: string\n description: string\n inputSchema: unknown\n /** `annotations.readOnlyHint`: the consent gate lets it through in 'ask-writes'. */\n readOnly: boolean\n visibility: McpAppVisibility[]\n /** The app it declares, if any. */\n resourceUri?: string\n}\n\n/**\n * The host's side of MCP Apps for one connection (`apps: true`). Every call names the server:\n * an app may read and call only what its own server declared.\n *\n * - `readUiResource` reads an app's document with `resources/read` - only a `ui://` URI that a\n * tool of THAT server declares in its current listing, from that server and nowhere else;\n * checked (MIME type, size, URI) and cached per connection.\n * - `appTool` is a server's tool an app may call: listed, with `visibility` including `'app'`.\n * - `callAppTool` sends that tool call and returns the raw result for the app. It does NOT ask\n * the user: a host calls it only after its consent, e.g. `Agent.approveAppToolCall`.\n */\nexport interface McpAppsConnection {\n readUiResource: (\n server: string,\n uri: string,\n options?: { signal?: AbortSignal },\n ) => Promise<McpAppResource>\n appTool: (server: string, name: string) => McpAppTool | undefined\n /**\n * A resource of that server for a file its app asks the host to save (`ui/download-file` with\n * a `resource_link`): `resources/read` on THAT server only - never a fetch of the URI - its\n * `text` or base64 `blob` as bytes, at most `maxBytes` (default `MCP_APP_MAX_DOWNLOAD_BYTES`),\n * not cached. Only a server whose apps are on. It does NOT ask the user, nor judge the type:\n * the host does both before it saves anything.\n */\n readResource: (\n server: string,\n uri: string,\n options?: { signal?: AbortSignal; maxBytes?: number },\n ) => Promise<McpAppDownloadResource>\n callAppTool: (\n server: string,\n name: string,\n args: Record<string, unknown>,\n options?: { signal?: AbortSignal },\n ) => Promise<McpAppToolResult>\n}\n\nexport interface ConnectMcpOptions {\n clientName?: string\n clientVersion?: string\n onLog?: (level: 'info' | 'warn' | 'error', message: string) => void\n /**\n * Fires when a server pushes `notifications/tools/list_changed`. Call\n * `refreshServer(name)` from a point where no run is reading `tools` — this\n * connector deliberately does not refresh behind a running agent's back.\n * On a 2026-07-28 connection (`protocol`) the notice arrives over a\n * `subscriptions/listen` stream, opened only when this callback is given and\n * opened again when it ends (backoff from 1 s to 60 s, at most 10 attempts in\n * a row; never after a 401 / 403 / 404 / 405). Once a stream is back this\n * callback fires as for a notice, since a change in the gap was not announced.\n * On a server with `skills: true` it also fires for a resource list change\n * (`notifications/resources/list_changed`): that is how a change of its\n * skills is announced, and `refreshServer` lists them again. It fires too,\n * once per loaded skill, when a directory read (`resources/directory/read`,\n * a server that declared `directoryRead`) shows that a skill changed on the\n * server since it was loaded.\n */\n onToolsChanged?: (server: string) => void\n /**\n * Per-server deadline for connect + tool listing (default 30 000 ms). A\n * server that misses it is reported failed and closed; the others still\n * mount — one hanging server no longer holds every other one hostage.\n */\n connectTimeoutMs?: number\n /**\n * MCP elicitation: a server may ask the user for input in the middle of a tool\n * call (a form, or - with `elicitation.url` - a link to open), and this\n * callback answers: accept with the form's values, decline, or cancel. The\n * HOST decides, never the model: the question is not shown to the model, and\n * the answer goes only to the server that asked - not into the model's\n * context, an event, a log or a run checkpoint.\n *\n * Without the callback the capability is not declared, a server cannot ask,\n * and nothing is sent that was not sent before. The server's message and form\n * are third-party text: cleaned, capped and restricted to a flat form before\n * the callback sees them; the answer is checked against the form before it is\n * sent. A link (URL mode) is only handed to the callback: this package never\n * fetches or opens it. A callback that throws or does not answer in time\n * cancels the question and fails the tool call; nothing is retried.\n *\n * Inside an agent run the two events `mcp.elicitation-requested` /\n * `mcp.elicitation-answered` are emitted (the answered one never carries a\n * value). On the 2025 revisions the calls to a server with this option run\n * one at a time: its question does not say which call it belongs to.\n */\n onElicitation?: McpElicitationHandler\n /**\n * Its settings: `timeoutMs` (default 300 000: a human is answering; the\n * step's `chatTimeoutMs` stops while a question waits),\n * `maxPerToolCall` (5), `maxPerRun` (20), `url` (also accept URL mode; default\n * false), `subagents` (let a call made by a helper - a subagent - ask too;\n * default false: its question is cancelled without the callback being called).\n */\n elicitation?: McpElicitationOptions\n /**\n * MCP Apps (the `io.modelcontextprotocol/ui` extension): declare the extension in the\n * handshake, read each tool's `_meta.ui` (its `ui://` app and its `visibility`), emit an\n * `mcp.app` event in a run when such a tool returns, and give the host `ConnectedMcp.apps` to\n * read the app and make the calls it asks for. A tool whose `visibility` leaves out `'model'`\n * is then not mounted (it is for its app only). The app's HTML never reaches the model.\n *\n * Off by default: nothing is declared, `_meta` is not read, every tool is mounted as before and\n * the wire is unchanged. A server's own `apps` (`McpHttpServerConfig.apps`) wins over this one.\n */\n apps?: boolean\n}\n\n/**\n * The longest delay a timer takes (2^31 - 1 ms): the SDK's own request timeout\n * is set to it for a 2025 tool call that may ask the user something, whose time\n * is kept by the elicitation session instead (it does not count the time a\n * question waits).\n */\nconst MAX_TIMER_MS = 2_147_483_647\n\n/**\n * What an MCP tool reads of the call that reached it, structurally (this entry\n * does not import the core): the run context the agent passes as\n * `options.agentRun`, and the mark a subagent tool puts on a host tool's call.\n */\ninterface ToolCallOptions {\n abortSignal?: AbortSignal\n agentRun?: {\n emit?: (event: never) => void\n step?: unknown\n signal?: AbortSignal\n runId?: string\n subagent?: { id: string; depth: number }\n elicitations?: { count: number }\n /** The run's clock: stopped while a question waits, so the step's limit does not run. */\n clock?: { pause: () => () => void }\n }\n subagentCall?: {\n id: string\n depth: number\n elicitations?: { count: number }\n /** Stops the clock of the run that delegated, for a call that reaches here without a run. */\n pause?: () => () => void\n }\n}\n\n/** Hard stop for a server whose pagination never ends (the Node sibling's cap and name). */\nexport const MAX_TOOL_LIST_PAGES = 100\n/**\n * 2026-07-28: how long the `subscriptions/listen` stream may take to be\n * acknowledged before the connect goes on without tool-list change notices\n * (the Node sibling's bound and name).\n */\nexport const MCP_LISTEN_ACK_TIMEOUT_MS = 10_000\n\n/** The SDK's typed error with this code (by name too: a second copy of the SDK is another class). */\nconst isSdkError = (err: unknown, code: SdkErrorCode): boolean =>\n (err instanceof SdkError || (err instanceof Error && err.name === 'SdkError')) &&\n (err as { code?: unknown }).code === code\n\n/**\n * Every tool of a server, following `nextCursor` (up to MAX_TOOL_LIST_PAGES\n * pages; a repeated cursor ends the walk). Servers with hundreds of tools\n * paginate; reading only the first page silently drops the rest.\n *\n * Page by page through `client.request`, not `client.listTools()`: called\n * without a cursor, the typed verb of the 2.x SDK walks every page itself,\n * throws past its own page cap, answers without asking when the server did not\n * advertise the tools capability, and fills the cache that switches on the\n * SDK's output-schema check in `callTool` (which this module does itself, see\n * `outputSchemaViolation`). The raw request does none of that.\n */\nexport const listAllTools = async (\n client: Pick<Client, 'request'>,\n onTruncated?: () => void,\n): Promise<McpToolDescriptor[]> => {\n const all: McpToolDescriptor[] = []\n let cursor: string | undefined\n const seen = new Set<string>()\n for (let page = 0; page < MAX_TOOL_LIST_PAGES; page += 1) {\n const res = await client.request({\n method: 'tools/list',\n params: cursor ? { cursor } : undefined,\n })\n all.push(...(res.tools as McpToolDescriptor[]))\n const next = typeof res.nextCursor === 'string' && res.nextCursor ? res.nextCursor : undefined\n if (!next || seen.has(next)) return all\n seen.add(next)\n cursor = next\n }\n onTruncated?.()\n return all\n}\n\nclass ConnectTimeoutError extends Error {}\n\nconst withTimeout = <T>(p: Promise<T>, ms: number, label: string): Promise<T> => {\n if (!(ms > 0)) return p\n let timer: ReturnType<typeof setTimeout> | undefined\n return Promise.race([\n p.finally(() => clearTimeout(timer)),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new ConnectTimeoutError(`${label} timed out after ${ms} ms`)),\n ms,\n )\n }),\n ])\n}\n\n// Providers cap tool names at 64 chars (^[a-zA-Z0-9_-]{1,64}$). We enforce the\n// same limit on the prefixed \"server__tool\" so one server can't poison a run.\nconst MAX_TOOL_NAME_LEN = 64\n\n// Browsers drop long-lived SSE streams on tab-throttling and flaky networks far\n// more often than a server does; the SDK's default (2 retries) gives up too\n// early for an agent that may idle between steps.\nconst DEFAULT_RECONNECTION: StreamableHTTPReconnectionOptions = {\n maxReconnectionDelay: 30_000,\n initialReconnectionDelay: 1_000,\n reconnectionDelayGrowFactor: 1.5,\n maxRetries: 5,\n}\n\n// MCP names may contain characters providers reject (dots, slashes, spaces);\n// map them into the allowed alphabet. callTool still uses the ORIGINAL name.\nconst sanitizeName = (s: string): string => s.replace(/[^a-zA-Z0-9_-]/g, '_')\n\n/**\n * Sanitizing can map two distinct MCP names onto one key (\"a.b\" and \"a-b\" both\n * become \"a_b\"). Suffix instead of dropping: a tool the model can't see is a\n * silent capability loss, and the disambiguated name still resolves back to the\n * original on dispatch.\n */\nconst uniqueKey = (base: string, taken: ToolSet): string => {\n // hasOwn, not truthiness: a tool named so that the key lands on \"__proto__\"\n // would otherwise read as already taken through the prototype chain.\n if (!Object.hasOwn(taken, base)) return base\n for (let n = 2; n < 100; n++) {\n const suffix = `_${n}`\n const candidate = base.slice(0, MAX_TOOL_NAME_LEN - suffix.length) + suffix\n if (!Object.hasOwn(taken, candidate)) return candidate\n }\n return ''\n}\n\n/**\n * Flatten an MCP tool result's content into something a model can read. Unlike\n * the Node sibling this NEVER spills to a filesystem (there isn't one in the\n * browser): all-text content is joined; mixed content passes through as an\n * array of text + raw parts for the host to handle.\n */\nexport const flattenContent = (content: unknown): unknown => {\n if (!Array.isArray(content)) return content\n const parts = content as Array<Record<string, unknown>>\n const allText =\n parts.length > 0 && parts.every((p) => p?.type === 'text' && typeof p.text === 'string')\n if (allText) return parts.map((p) => p.text as string).join('\\n')\n return parts.map((p) => (p?.type === 'text' && typeof p.text === 'string' ? p.text : p))\n}\n\ninterface McpToolDescriptor {\n name: string\n description?: string\n inputSchema: unknown\n outputSchema?: unknown\n annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean; title?: string }\n _meta?: unknown\n}\n\n/** The longest compile error repeated in a refusal (the SDK clips at the same length). */\nconst OUTPUT_SCHEMA_ERROR_MAX_CHARS = 200\n\n/**\n * Why a tool result does not follow the `outputSchema` its tool declared, or\n * `undefined` when it does. The rule and the wording are those of the SDK's\n * `Client.callTool`: a tool with an output schema must answer with\n * `structuredContent`, and that value must validate. An `isError` result is\n * not checked.\n *\n * The check is made here, on a result that was received, instead of inside\n * `callTool`, which throws on a violation and takes the result with it: the\n * call RAN on the server, so its result goes to the model with a note.\n *\n * The Node package carries the same function; change both.\n */\nexport const outputSchemaViolation = (\n toolName: string,\n result: Pick<CallToolResult, 'structuredContent' | 'isError'>,\n validate: JsonSchemaValidator<unknown>,\n): string | undefined => {\n if (result.isError === true) return undefined\n if (result.structuredContent === undefined) {\n return `Tool ${toolName} has an output schema but did not return structured content`\n }\n try {\n const checked = validate(result.structuredContent)\n return checked.valid\n ? undefined\n : `Structured content does not match the tool's output schema: ${checked.errorMessage}`\n } catch (err) {\n return `Failed to validate structured content: ${err instanceof Error ? err.message : String(err)}`\n }\n}\n\ninterface ServerConnect {\n name: string\n client?: Client\n /** What the server said in its initialize result ('' when nothing). */\n instructions?: string\n /** The revision the connection negotiated. */\n protocol?: Omit<McpServerProtocol, 'server'>\n listed?: McpToolDescriptor[]\n /** 2026-07-28 with `onToolsChanged`: what keeps the listen stream open. */\n listener?: McpListenSupervisor\n /** `skills: true` on a 2026-07-28 connection to a server that offers the extension. */\n skills?: { source: McpSkillSource; refresh: () => Promise<void> }\n error?: string\n needsAuthorization?: boolean\n}\n\n/**\n * The enterprise-managed provider (`enterprise-oauth.ts`), recognised by shape\n * so a host's own subclass, or one from another bundle of this package, counts.\n */\ntype EnterpriseLog = (level: 'info' | 'warn' | 'error', message: string) => void\n\ninterface EnterpriseProviderShape {\n extension: string\n authorize: (opts: { fetch?: FetchLike; onLog?: EnterpriseLog }) => Promise<void>\n transportFetch: (base?: FetchLike, log?: EnterpriseLog) => FetchLike\n}\n\nconst asEnterpriseProvider = (\n provider: OAuthClientProvider,\n): EnterpriseProviderShape | undefined => {\n const p = provider as Partial<Record<keyof EnterpriseProviderShape, unknown>>\n return typeof p.extension === 'string' &&\n typeof p.authorize === 'function' &&\n typeof p.transportFetch === 'function'\n ? (provider as unknown as EnterpriseProviderShape)\n : undefined\n}\n\n/** Thrown by the refresh-only view when the SDK reaches for a redirect. */\nclass RefreshOnlyAbort extends Error {}\n\n/**\n * A view of the provider that can renew a token but can never start an\n * interactive authorization.\n *\n * `auth()` does not have a refresh-only mode: when a refresh fails for a reason\n * it deems recoverable (a 5xx from the token endpoint, a network blip) it falls\n * through to a brand-new authorization — issuing a state and a PKCE verifier,\n * overwriting the stored pair, and calling `redirectToAuthorization`. The\n * transport then does its own `auth()` on the first 401, overwriting them\n * again, so the user comes back holding a code the second pair can't verify.\n * Blocking the three redirect-path methods aborts the escalation before\n * anything is overwritten; the transport's 401 handling stays the single owner\n * of interactive authorization.\n */\nconst refreshOnly = (p: OAuthClientProvider): OAuthClientProvider => ({\n // Must stay truthy: `auth()` reads a missing redirectUrl as \"non-interactive\n // grant\" and would try to fetch a token without one.\n get redirectUrl() {\n return p.redirectUrl\n },\n get clientMetadata() {\n return p.clientMetadata\n },\n get clientMetadataUrl() {\n return p.clientMetadataUrl\n },\n // The second argument is the authorization server the SDK resolved: a\n // provider that keeps credentials per issuer reads and writes by it.\n clientInformation: (ctx) => p.clientInformation(ctx),\n saveClientInformation: p.saveClientInformation?.bind(p),\n tokens: (ctx) => p.tokens(ctx),\n saveTokens: (t, ctx) => p.saveTokens(t, ctx),\n invalidateCredentials: p.invalidateCredentials?.bind(p),\n addClientAuthentication: p.addClientAuthentication?.bind(p),\n validateResourceURL: p.validateResourceURL?.bind(p),\n // What a refresh request is made of, when the provider says so.\n scopeForRefresh: p.scopeForRefresh?.bind(p),\n dpop: p.dpop?.bind(p),\n codeVerifier: () => p.codeVerifier(),\n state: () => {\n throw new RefreshOnlyAbort()\n },\n saveCodeVerifier: () => {\n throw new RefreshOnlyAbort()\n },\n redirectToAuthorization: () => {\n throw new RefreshOnlyAbort()\n },\n})\n\n/**\n * An access token that is already expired produces a guaranteed 401 on the\n * first request. When the provider tells us so AND we hold a refresh token,\n * renew before connecting: one round-trip saved, and a run that starts on a\n * stale token doesn't surface a spurious auth error to the model.\n *\n * Best-effort by design — anything that goes wrong here is left to the\n * transport's own 401 handling, which is the path that knows how to ask the\n * user for a new authorization.\n */\nconst refreshIfExpired = async (\n provider: OAuthClientProvider,\n serverUrl: string,\n fetchFn: FetchLike | undefined,\n log: NonNullable<ConnectMcpOptions['onLog']>,\n name: string,\n // The host's own `onLog`, when it gave one: left undefined otherwise, so the\n // enterprise provider falls back to the package's logger for its detail.\n detailLog?: EnterpriseLog,\n): Promise<void> => {\n const check = (provider as { isAccessTokenExpired?: () => boolean | Promise<boolean> })\n .isAccessTokenExpired\n if (typeof check !== 'function') return\n if (!(await check.call(provider))) return\n const enterprise = asEnterpriseProvider(provider)\n if (enterprise) {\n // No human step and no refresh token (the ID-JAG replaces it): get the\n // token now. A refusal by the IdP or the authorization server is final -\n // asking again through the 401 path would only repeat the exchange - so it\n // fails this server with the error that names who refused. Only a\n // discovery failure is left to the transport: the server's 401 may say\n // where its metadata lives, or it may need no authorization at all.\n try {\n await enterprise.authorize({ fetch: fetchFn, onLog: detailLog })\n } catch (err) {\n if ((err as { hop?: unknown })?.hop !== 'discovery') throw err\n log('info', `[mcp] ${name}: ${err instanceof Error ? err.message : String(err)}; continuing`)\n }\n return\n }\n const tokens = await provider.tokens()\n // Nothing to refresh with: let the 401 path ask for a new authorization.\n if (!tokens?.refresh_token) return\n try {\n await auth(refreshOnly(provider), { serverUrl, fetchFn })\n } catch (err) {\n log(\n 'info',\n err instanceof RefreshOnlyAbort\n ? `[mcp] ${name}: the stored token could not be refreshed; a new authorization is needed`\n : `[mcp] ${name}: proactive token refresh failed (${\n err instanceof Error ? err.message : String(err)\n }); continuing`,\n )\n }\n}\n\n/**\n * A fetch the browser refused for CORS reasons is indistinguishable, from\n * JavaScript, from a server that is simply down: both surface as a bare\n * `TypeError`. The reason is deliberately withheld, and the browser prints it\n * only to the devtools console — which is why this failure is usually read as a\n * client bug and debugged in the wrong place for a long time.\n */\nconst isNetworkLevelFailure = (err: unknown): boolean =>\n err instanceof TypeError || /failed to fetch|networkerror|load failed/i.test(String(err))\n\n/**\n * Work out WHY the browser blocked us, by asking a question it will answer.\n *\n * A request carrying only `content-type` needs the same preflight as the real\n * one but asks for nothing else. So if the plain request gets through while the\n * transport's did not, the origin is fine and a *header* is the problem — and\n * the header the transport adds is `MCP-Protocol-Version`, which the spec has\n * required on every post-initialize request since 2025-06-18 and which server\n * CORS lists written before that date do not include. That is the shape of the\n * bug that lets OAuth and `initialize` succeed and then kills the connection\n * moments later, looking for all the world like the consent step failed.\n *\n * With `protocol: 'auto'` or `'modern'` the transport also sends the request\n * headers of the 2026-07-28 revision, on the very first request. The browser\n * will not say which header a preflight refused either, so each one is tried on\n * its own: the ones that do not get through are the ones missing from the\n * server's `Access-Control-Allow-Headers`, and they are named.\n *\n * Exported because a UI wants to say this too, not just log it.\n */\nexport const diagnoseMcpCors = async (\n url: string,\n fetchFn: FetchLike = globalThis.fetch,\n opts: { protocol?: McpProtocolMode } = {},\n): Promise<string | undefined> => {\n const body = JSON.stringify({ jsonrpc: '2.0', id: 0, method: 'ping' })\n let plain: Response\n try {\n plain = await fetchFn(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body,\n })\n } catch {\n return (\n `the browser blocked every request to ${url}, including a plain one. ` +\n 'The server is unreachable, or it does not answer the CORS preflight for this ' +\n 'origin: it must return Access-Control-Allow-Origin (and handle OPTIONS) on the ' +\n 'MCP endpoint, the OAuth endpoints and the /.well-known documents.'\n )\n }\n const hints: string[] = []\n const modern = opts.protocol === 'auto' || opts.protocol === 'modern'\n if (modern) {\n // One request per header, each asking the preflight for that header alone.\n // Whatever the server answers is an answer: only a blocked request counts.\n const refused: string[] = []\n for (const [header, value] of [\n ['MCP-Protocol-Version', MCP_MODERN_PROTOCOL_VERSION],\n [MCP_MODERN_REQUEST_HEADERS[0], 'ping'],\n [MCP_MODERN_REQUEST_HEADERS[1], 'cors-check'],\n ] as const) {\n try {\n await fetchFn(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', [header]: value },\n body,\n })\n } catch {\n refused.push(header)\n }\n }\n if (refused.length > 0) {\n hints.push(\n `a plain request to ${url} succeeded (HTTP ${plain.status}), but one carrying ` +\n `${refused.join(' / ')} was blocked: the server's Access-Control-Allow-Headers ` +\n `does not list ${refused.length === 1 ? 'it' : 'them'}. The ${MCP_MODERN_PROTOCOL_VERSION} ` +\n `revision of the protocol (protocol: '${opts.protocol}') sends MCP-Protocol-Version, ` +\n `${MCP_MODERN_REQUEST_HEADERS.join(' and ')} on every request: add ` +\n `${refused.join(', ')} to Access-Control-Allow-Headers, alongside Content-Type and ` +\n `Authorization (and any Mcp-Param-* header the server's tools declare).`,\n )\n }\n }\n if (hints.length === 0) {\n hints.push(\n `a plain request to ${url} succeeded (HTTP ${plain.status}) but the transport's did not, ` +\n 'so the origin is allowed and a request HEADER is being refused. Add ' +\n 'MCP-Protocol-Version (required on every request after initialize) and Last-Event-ID ' +\n \"to the server's Access-Control-Allow-Headers, alongside Content-Type, Authorization \" +\n 'and mcp-session-id.' +\n (modern\n ? ` With protocol: '${opts.protocol}', ${MCP_MODERN_REQUEST_HEADERS.join(' and ')} too.`\n : ''),\n )\n }\n // A 401 whose challenge JS cannot read means OAuth discovery cannot start\n // from a browser at all, so say so while we are here.\n if (plain.status === 401 && !plain.headers.get('www-authenticate')) {\n hints.push(\n 'The server also answers 401 without exposing WWW-Authenticate: add it to ' +\n 'Access-Control-Expose-Headers, or a browser client cannot read the challenge ' +\n 'and OAuth discovery never starts.',\n )\n }\n return hints.join(' ')\n}\n\n/** Says that `diagnoseMcpCors` found request headers the server's CORS policy refuses. */\nconst NAMES_REFUSED_HEADERS = /was blocked: the server's Access-Control-Allow-Headers/\n\nconst warnTruncated = (log: NonNullable<ConnectMcpOptions['onLog']>, name: string): void =>\n log(\n 'warn',\n `[mcp] ${name}: tools/list still paginating after ${MAX_TOOL_LIST_PAGES} pages; the rest of the tools are not mounted`,\n )\n\nconst openConnection = async (\n name: string,\n cfg: McpHttpServerConfig,\n opts: ConnectMcpOptions,\n log: NonNullable<ConnectMcpOptions['onLog']>,\n elicitation: McpElicitationSession | undefined,\n): Promise<ServerConnect> => {\n let client: Client | undefined\n let listener: McpListenSupervisor | undefined\n let timedOut = false\n const timeoutMs = cfg.connectTimeoutMs ?? opts.connectTimeoutMs ?? 30_000\n // What the version probe (`protocol: 'auto' | 'modern'`) ran into.\n const probe: ProbeState = { blocked: false }\n const attempt = connectAndList(\n name,\n cfg,\n opts,\n log,\n probe,\n (c) => {\n client = c\n // Created after the deadline already passed: nobody will ever use it.\n if (timedOut) void c.close().catch(() => {})\n },\n (l) => {\n listener = l\n if (timedOut) l.stop()\n },\n elicitation,\n )\n // A handshake that completes after the deadline must not leave a live session behind.\n attempt.then(\n (r) => {\n if (!timedOut) return\n r.listener?.stop()\n void r.client?.close().catch(() => {})\n },\n () => {},\n )\n try {\n return await withTimeout(attempt, timeoutMs, 'connect')\n } catch (err) {\n if (err instanceof ConnectTimeoutError) timedOut = true\n // The client may be live even though we ended up here (listTools() failing\n // after a successful connect, or the deadline passing mid-listing). Close\n // it, or the SSE stream leaks for the lifetime of the tab - and its listen\n // stream first, or a retry outlives it.\n listener?.stop()\n if (client) await client.close().catch(() => {})\n const needsAuthorization = err instanceof UnauthorizedError\n let message = err instanceof Error ? err.message : String(err)\n // `protocol: 'modern'` against a server that did not offer the revision:\n // the SDK's sentence, plus which option to turn.\n if (cfg.protocol === 'modern' && isSdkError(err, SdkErrorCode.EraNegotiationFailed)) {\n message = `${message} - ${MCP_MODERN_REFUSED_HINT}`\n }\n // Turn \"TypeError: Failed to fetch\" into the sentence the reader needs.\n // Only on the failure path, so the extra request costs nothing in normal use.\n if (!needsAuthorization && !(err instanceof ConnectTimeoutError)) {\n if (isNetworkLevelFailure(err)) {\n const hint = await diagnoseMcpCors(cfg.url, cfg.fetch, {\n protocol: probe.mode,\n }).catch(() => undefined)\n if (hint) message = `${message} - ${hint}`\n } else if (probe.blocked) {\n // The version probe never reached the server, and what failed\n // afterwards is another error (a page's SDK reads a blocked probe as\n // \"a 2025 server\" and goes on). Said only when a header is the cause.\n const hint = await diagnoseMcpCors(cfg.url, cfg.fetch, {\n protocol: probe.mode,\n }).catch(() => undefined)\n if (hint && NAMES_REFUSED_HEADERS.test(hint)) message = `${message} - ${hint}`\n }\n }\n log(\n 'error',\n needsAuthorization\n ? `[mcp] ${name}: authorization required - send the user to the provider's authorizationUrl`\n : `[mcp] ${name}: failed to connect - ${message}`,\n )\n return { name, error: message, needsAuthorization }\n }\n}\n\n/** What the version probe of one connect ran into (see `openConnection`). */\ninterface ProbeState {\n /** The configured mode, once it was read. */\n mode?: McpProtocolMode\n /** A request of the probe was blocked before it reached the server (CORS, or no network). */\n blocked: boolean\n}\n\n/**\n * 2026-07-28: ask the server for tool-list change notices, and ask again while the\n * connection is open (`./listen`: backoff, final errors, the re-list once a stream\n * is back). Best effort - a server that does not announce them, or a stream that\n * cannot be opened, leaves a connection whose tools still work; `refreshServer`\n * still re-lists.\n */\nconst listenForToolChanges = async (\n name: string,\n client: Client,\n log: NonNullable<ConnectMcpOptions['onLog']>,\n announce: () => void,\n onListener: (listener: McpListenSupervisor) => void,\n skills: boolean,\n): Promise<void> => {\n if (!client.getServerCapabilities()?.tools?.listChanged) {\n log('info', `[mcp] ${name}: the server does not announce tool list changes`)\n return\n }\n // `skills: true`: a change of the server's skills comes as a resource list change (the\n // extension is built on resources), on the same stream.\n const resources = skills && client.getServerCapabilities()?.resources?.listChanged === true\n const listener = createMcpListenSupervisor({\n server: name,\n listen: (signal) =>\n client.listen(\n { toolsListChanged: true, ...(resources ? { resourcesListChanged: true } : {}) },\n { timeout: MCP_LISTEN_ACK_TIMEOUT_MS, signal },\n ),\n log,\n // Changes made while no stream was open: the path a notice takes, so the host\n // sees what a notice causes.\n onResubscribed: announce,\n })\n onListener(listener)\n await listener.start()\n}\n\nconst connectAndList = async (\n name: string,\n cfg: McpHttpServerConfig,\n opts: ConnectMcpOptions,\n log: NonNullable<ConnectMcpOptions['onLog']>,\n probe: ProbeState,\n onClient: (client: Client) => void,\n onListener: (listener: McpListenSupervisor) => void,\n elicitation: McpElicitationSession | undefined,\n): Promise<ServerConnect> => {\n // Read first: a `protocol` that is none of the three names is a\n // configuration error, said before anything is sent.\n const mode = mcpProtocolMode(cfg.protocol, name)\n probe.mode = mode\n if (cfg.headers && cfg.getHeaders) {\n throw new Error(`MCP server \"${name}\": specify either headers or getHeaders, not both`)\n }\n const headers = cfg.getHeaders ? await cfg.getHeaders() : cfg.headers\n if (cfg.authProvider) {\n if (headers && 'Authorization' in headers) {\n log(\n 'warn',\n `[mcp] ${name}: an explicit Authorization header shadows the OAuth token from authProvider`,\n )\n }\n assertSecureOAuthUrl(cfg.url, name)\n await refreshIfExpired(cfg.authProvider, cfg.url, cfg.fetch, log, name, opts.onLog)\n }\n const transport = new StreamableHTTPClientTransport(new URL(cfg.url), {\n requestInit: headers ? { headers } : undefined,\n authProvider: cfg.authProvider,\n // A 403 `insufficient_scope` in the middle of a session. A provider\n // without a human step (no `redirectUrl`: the enterprise one) may ask\n // again for the wider scope, once per request - the SDK's cap. One WITH a\n // human step - in a browser nearly all of them - never does: the SDK would\n // skip the refresh and start a new authorization from inside a tool call,\n // replacing the stored state and PKCE verifier each time the model tried\n // the tool again. The call fails with the scope the server asked for, and\n // the host decides. The Node sibling's rule.\n onInsufficientScope: cfg.authProvider?.redirectUrl ? 'throw' : 'reauthorize',\n // The enterprise provider reports a refused grant itself: a short typed\n // error for the caller, the server's words (redacted) to the log.\n fetch:\n (cfg.authProvider &&\n asEnterpriseProvider(cfg.authProvider)?.transportFetch(cfg.fetch, opts.onLog)) ||\n cfg.fetch,\n reconnectionOptions: { ...DEFAULT_RECONNECTION, ...cfg.reconnection },\n })\n // Without these, a dropped SSE stream or a transport-level protocol error\n // is swallowed and the agent just stops getting results.\n // The version probe asks a question a 2025 server answers with an HTTP\n // error: that answer is the expected \"no\", not a fault of the connection. A\n // probe that was BLOCKED is remembered: a page's SDK reads it as \"a 2025\n // server\" too, and only this callback saw the difference.\n let probing = mode !== 'legacy'\n transport.onerror = (err) => {\n if (!probing) {\n log('warn', `[mcp] ${name}: transport error - ${err.message}`)\n return\n }\n if (isNetworkLevelFailure(err)) probe.blocked = true\n log('info', `[mcp] ${name}: version probe (server/discover) - ${err.message}`)\n }\n // info, not warn: an ordinary close() ends here too, and a routine\n // teardown logged as a warning trains people to ignore warnings.\n transport.onclose = () => log('info', `[mcp] ${name}: transport closed`)\n\n const enterprise = cfg.authProvider ? asEnterpriseProvider(cfg.authProvider) : undefined\n // Without `protocol` (or with 'legacy') nothing is added here: the client is\n // built with exactly the options it always had.\n const negotiation = mcpVersionNegotiation(mode)\n // MCP Apps: declared only where they are on for this server (`apps` of the server, else of\n // the connection); a server whose apps are declined is not told of them.\n const apps = mcpAppsModeOf(cfg.apps, opts.apps) === 'on'\n // `skills: true` (experimental): the Skills extension is written against 2026-07-28, so it is\n // declared only where that revision may be spoken; never on a 'legacy' connection.\n const skillsSetting = mcpSkillsSettingOf(cfg.skills, name)\n const skillsWanted = skillsSetting.on && mode !== 'legacy'\n if (skillsSetting.on && mode === 'legacy') {\n log(\n 'warn',\n `[mcp] ${name}: skills: true needs protocol 'auto' or 'modern' (the Skills extension is written against 2026-07-28); no skills are requested`,\n )\n }\n const clientOptions: ClientOptions | undefined =\n enterprise || negotiation || elicitation || apps || skillsWanted\n ? {\n // An extension is opt-in: it is declared only by the client that uses\n // it. So is elicitation: without `onElicitation` no capability is\n // declared, and a server cannot ask. MCP Apps: only with `apps`.\n ...(enterprise || elicitation || apps || skillsWanted\n ? {\n capabilities: {\n ...(enterprise || apps || skillsWanted\n ? {\n extensions: {\n ...(enterprise ? { [enterprise.extension]: {} } : {}),\n ...(apps\n ? { [MCP_APPS_EXTENSION]: { mimeTypes: [MCP_APP_MIME_TYPE] } }\n : {}),\n ...(skillsWanted ? { [MCP_SKILLS_EXTENSION]: {} } : {}),\n },\n }\n : {}),\n ...(elicitation ? { elicitation: elicitation.capability } : {}),\n },\n }\n : {}),\n ...(negotiation\n ? {\n versionNegotiation: negotiation,\n // 2026-07-28: an `input_required` result is NOT answered and the\n // call is NOT sent again by the SDK (its default would try\n // both). Without `onElicitation` it fails the tool call; with\n // it, `execute` answers it through the session, which keeps\n // the caps the SDK's own loop does not have.\n inputRequired: { autoFulfill: false },\n }\n : {}),\n }\n : undefined\n const client = new Client(\n { name: opts.clientName ?? 'agent-web', version: opts.clientVersion ?? '0.0.0' },\n clientOptions,\n )\n if (elicitation) {\n // 2025 revisions: the server's question is a request of its own. (On\n // 2026-07-28 the SDK drops inbound requests; the question is then the tool\n // call's `input_required` result.)\n client.setRequestHandler('elicitation/create', (request) =>\n elicitation.onRequest(request.params),\n )\n }\n onClient(client)\n await client.connect(transport)\n probing = false\n const era = client.getProtocolEra() ?? 'legacy'\n const version = client.getNegotiatedProtocolVersion() ?? ''\n if (mode !== 'legacy') {\n log(\n 'info',\n `[mcp] ${name}: protocol ${version} (${\n era === 'modern' ? 'modern: stateless, no session' : 'legacy: the initialize handshake'\n }; configured '${mode}')`,\n )\n // 'auto' on the 2025 revisions although the probe never reached the\n // server: when a CORS header is why, the server may well speak 2026-07-28.\n if (era === 'legacy' && probe.blocked) {\n const hint = await diagnoseMcpCors(cfg.url, cfg.fetch, { protocol: mode }).catch(\n () => undefined,\n )\n log(\n 'warn',\n `[mcp] ${name}: the version probe (server/discover) was blocked before it reached the server, so the connection uses ${version}${\n hint && NAMES_REFUSED_HEADERS.test(hint) ? ` - ${hint}` : ''\n }`,\n )\n }\n }\n\n // `skills: true`: only on 2026-07-28 (the revision the extension is written against), and only\n // from a server that declares it. Listed here; nothing of a skill is read yet. The SDK's skills\n // client is loaded only then: a connection without skills does not carry it.\n let skills: ServerConnect['skills']\n if (skillsWanted) {\n if (era !== 'modern') {\n log(\n 'info',\n `[mcp] ${name}: skills: true, but the connection uses ${version} - the Skills extension needs 2026-07-28; no skills`,\n )\n } else if (!client.getServerCapabilities()?.extensions?.[MCP_SKILLS_EXTENSION]) {\n log('info', `[mcp] ${name}: the server does not offer skills (${MCP_SKILLS_EXTENSION})`)\n } else {\n const { SkillsClient } = await import('@modelcontextprotocol/client/ext/skills')\n // A directory read that shows a skill changed on the server (`directoryRead`) is announced\n // the way a resource list change is: `onToolsChanged`, for a refresh between runs.\n const notify = opts.onToolsChanged\n skills = createMcpSkillCatalog(\n name,\n new SkillsClient(client, { skipInvalid: true }) as unknown as McpSkillsClientLike,\n (level, message) => log(level, message),\n {\n ...(skillsSetting.consent ? { consent: skillsSetting.consent } : {}),\n ...(skillsSetting.dynamic ? { dynamic: true } : {}),\n ...(notify ? { onChanged: () => notify(name) } : {}),\n },\n )\n await skills.refresh()\n }\n }\n\n // Subscribe BEFORE the first list call: a server that mutates its tool set\n // during init would otherwise lose the notification in the window between\n // connect() and listTools().\n let listener: McpListenSupervisor | undefined\n if (opts.onToolsChanged) {\n const notify = opts.onToolsChanged\n const announce = (): void => notify(name)\n client.setNotificationHandler('notifications/tools/list_changed', announce)\n // A change of the server's skills is a resource list change: the refresh re-lists both.\n if (skills) client.setNotificationHandler('notifications/resources/list_changed', announce)\n // 2026-07-28 has no stream a server may write to unasked: the notice above\n // arrives only on a `subscriptions/listen` stream the client opens, and\n // opens again when it ends. (The 2025 revisions send it on the GET stream\n // the transport opens, and resumes, by itself.)\n if (era === 'modern') {\n await listenForToolChanges(\n name,\n client,\n log,\n announce,\n (l) => {\n listener = l\n onListener(l)\n },\n Boolean(skills),\n )\n }\n }\n\n const listed = await listAllTools(client, () => warnTruncated(log, name))\n // Read once, here: the text is fixed for the life of this connection.\n return {\n name,\n client,\n listed,\n ...(listener ? { listener } : {}),\n instructions: cleanMcpInstructions(client.getInstructions()),\n protocol: { version, era },\n ...(skills ? { skills } : {}),\n }\n}\n\n/**\n * Connect to one or more HTTP MCP servers and return their tools + catalogue.\n * Servers connect concurrently; tools, catalogue, and results merge in the\n * caller's declaration order, so the outcome is deterministic.\n */\nexport const connectMcpHttp = async (\n servers: Record<string, McpHttpServerConfig>,\n opts: ConnectMcpOptions = {},\n): Promise<ConnectedMcp> => {\n const log = opts.onLog ?? (() => {})\n // Read first: a setting that is not a usable number is a configuration error.\n const elicitationOptions = resolveMcpElicitationOptions(opts.elicitation)\n const elicitationDeps: McpElicitationDeps | undefined = opts.onElicitation\n ? { handler: opts.onElicitation, options: elicitationOptions, log }\n : undefined\n // One per server, made before its client: the capability it declares is part\n // of the handshake.\n const elicitationSessions = new Map<string, McpElicitationSession>()\n const elicitationSessionOf = (name: string): McpElicitationSession | undefined => {\n if (!elicitationDeps) return undefined\n let session = elicitationSessions.get(name)\n if (!session) {\n session = createMcpElicitationSession(name, elicitationDeps)\n elicitationSessions.set(name, session)\n }\n return session\n }\n const clients = new Map<string, Client>()\n const tools: ToolSet = {}\n const catalog: McpCatalogEntry[] = []\n const results: McpServerResult[] = []\n const instructions: McpServerInstructions[] = []\n const instructionsOf = new Map<string, string>()\n const protocols: McpServerProtocol[] = []\n // 2026-07-28, with `onToolsChanged`: per connected server, what keeps its\n // listen stream open (`./listen`). Stopped before the clients are closed.\n const listeners = new Map<string, McpListenSupervisor>()\n // server name → the tool keys it currently owns, so a refresh can remove\n // exactly its own entries.\n const mountedKeys = new Map<string, string[]>()\n // server name → its skills (`skills: true`, 2026-07-28, the server offers the extension).\n const skillCatalogs = new Map<string, NonNullable<ServerConnect['skills']>>()\n // MCP Apps (`apps: true`): per server, the tools as an app sees them (every listed tool, by\n // its own name) and the app documents read so far (by URI; a failed read is not kept). Each\n // server has a mode of its own (`McpHttpServerConfig.apps` over `ConnectMcpOptions.apps`).\n const appsModes = new Map<string, McpAppsMode>(\n Object.entries(servers).map(([name, cfg]) => [name, mcpAppsModeOf(cfg.apps, opts.apps)]),\n )\n const appsOn = [...appsModes.values()].includes('on')\n const appToolsOf = new Map<string, Map<string, McpAppTool>>()\n const appResources = new Map<string, Map<string, Promise<McpAppResource>>>()\n let appEventSeq = 0\n\n /**\n * One `tools/call` to a server, for the model or for an app: through the elicitation session\n * when the connection has one (on the 2025 revisions the session runs a server's calls one at\n * a time - an app's call too, or a question could be put to the wrong call), else the plain\n * request. A request that fails throws: there is no result.\n */\n const requestToolCall = async (\n name: string,\n client: Client,\n key: string,\n toolName: string,\n args: Record<string, unknown>,\n options: ToolCallOptions | undefined,\n ): Promise<CallToolResult> => {\n const elicitation = elicitationSessionOf(name)\n try {\n if (elicitation) {\n // The server may ask the user something during this call\n // (`onElicitation`). The session answers - on the 2025 revisions\n // a request of the server's own, on 2026-07-28 an\n // `input_required` result followed by the same call sent again\n // with the answers and the server's state - and keeps the caps;\n // see elicitation.ts.\n const call = options\n const run = call?.agentRun\n const signal = call?.abortSignal ?? run?.signal\n const emit = run?.emit as ((event: unknown) => void) | undefined\n const step = run?.step\n // A call made by a helper says so: the agent marks its own\n // helpers' calls, a subagent tool the calls of its host tools.\n const helper = run?.subagent ?? call?.subagentCall\n // One count per run the host started: a subagent tool's child counts on the\n // run that delegated to it.\n const counter = call?.subagentCall?.elicitations ?? run?.elicitations\n // While the user is asked, the step's time limit does not run: the clock of the run\n // the call belongs to (or of the run that delegated it, from a worker's host tool).\n // An app's call made outside a run has no clock, and nothing to pause.\n const pause = run?.clock?.pause ?? call?.subagentCall?.pause\n const era = client.getProtocolEra() ?? 'legacy'\n const info: McpElicitationCallInfo = {\n tool: key,\n toolName,\n ...(signal ? { signal } : {}),\n ...(emit\n ? {\n emit: (event: McpElicitationEvent) =>\n emit(\n event.type === 'mcp.elicitation-requested' && step ? { ...event, step } : event,\n ),\n }\n : {}),\n ...(run?.runId ? { runId: run.runId } : {}),\n ...(helper ? { subagent: { id: helper.id, depth: helper.depth } } : {}),\n ...(counter ? { run: counter } : {}),\n ...(pause ? { pause } : {}),\n }\n return await elicitation.call(\n era,\n info,\n (leg) =>\n client.request(\n {\n method: 'tools/call',\n params: { name: toolName, arguments: args, ...leg.retry },\n },\n {\n ...(leg.signal ? { signal: leg.signal } : {}),\n ...(leg.ownTimeout ? { timeout: MAX_TIMER_MS } : {}),\n // Hand an `input_required` result back instead of failing\n // on it: the session answers it.\n ...(era === 'modern' ? { allowInputRequired: true } : {}),\n },\n ) as Promise<CallToolResult>,\n )\n }\n return await client.request(\n { method: 'tools/call', params: { name: toolName, arguments: args } },\n options?.abortSignal ? { signal: options.abortSignal } : undefined,\n )\n } catch (err) {\n // 2026-07-28: the server answered `input_required` (it wants the\n // user asked something, or the call sent again with a state). Not\n // supported here, and the call is not repeated.\n if (isSdkError(err, SdkErrorCode.UnsupportedResultType)) {\n throw new Error(mcpInputRequiredMessage(toolName))\n }\n throw err\n }\n }\n\n const mountTools = (name: string, client: Client, listed: McpToolDescriptor[]): void => {\n const prefix = `${sanitizeName(name)}__`\n // Drop this server's existing entries first, mutating in place so external\n // references (an agent's live ToolSet) stay valid. We delete the keys this\n // server actually mounted rather than everything matching its prefix:\n // sanitizing can make two server names share a prefix (\"docs.v1\" and\n // \"docs/v1\"), and one server's prefix can nest inside another's (\"a\" and\n // \"a__b\") — either way a prefix sweep would silently unmount a DIFFERENT\n // server's tools.\n for (const k of mountedKeys.get(name) ?? []) {\n delete tools[k]\n }\n for (let i = catalog.length - 1; i >= 0; i--) {\n if (catalog[i].server === name) catalog.splice(i, 1)\n }\n const keys: string[] = []\n const appTools = new Map<string, McpAppTool>()\n // The SDK's own validator, the one its browser build uses by default\n // (@cfworker/json-schema: no code generation, so it runs under a CSP without\n // 'unsafe-eval'; dialect by `$schema`). One per mount, compiled lazily.\n let schemaValidator: CfWorkerJsonSchemaValidator | undefined\n\n let mounted = 0\n const appsMode = appsModes.get(name) ?? 'off'\n for (const t of listed) {\n const prefixed = prefix + sanitizeName(t.name)\n // MCP Apps: read only with apps on for this server - or declined, for `visibility` alone. A\n // tool for its app only is not the model's either way.\n const ui = appsMode !== 'off' ? mcpAppToolMeta(t) : undefined\n if (appsMode === 'on' && ui?.refusedUri !== undefined) {\n log(\n 'warn',\n `[mcp] ${name}: tool \"${t.name}\" declares an app that is not a ui:// URI (${ui.refusedUri}); ignored`,\n )\n }\n if (ui && !ui.visibility.includes('model')) {\n if (appsMode === 'declined') {\n log(\n 'info',\n `[mcp] ${name}: tool \"${t.name}\" is for its app only, and apps are off for this server; not mounted`,\n )\n continue\n }\n if (ui.visibility.includes('app')) {\n appTools.set(t.name, {\n name: t.name,\n key: prefixed,\n description: t.description ?? '',\n inputSchema: t.inputSchema,\n readOnly: t.annotations?.readOnlyHint === true,\n visibility: ui.visibility,\n ...(ui.resourceUri ? { resourceUri: ui.resourceUri } : {}),\n })\n }\n log('info', `[mcp] ${name}: tool \"${t.name}\" is for its app only; not mounted`)\n continue\n }\n if (prefixed.length > MAX_TOOL_NAME_LEN) {\n log(\n 'warn',\n `[mcp] ${name}: tool \"${t.name}\" exceeds the ${MAX_TOOL_NAME_LEN}-char name limit; skipping`,\n )\n continue\n }\n const key = uniqueKey(prefixed, tools)\n if (!key) {\n log('warn', `[mcp] ${name}: cannot find a free name for tool \"${t.name}\"; skipping`)\n continue\n }\n if (key !== prefixed) {\n log('warn', `[mcp] ${name}: tool name \"${prefixed}\" already taken; mounted as \"${key}\"`)\n }\n const description = t.description ?? ''\n const readOnly = t.annotations?.readOnlyHint === true\n const appUri = appsMode === 'on' ? ui?.resourceUri : undefined\n if (appsMode === 'on' && ui?.visibility.includes('app')) {\n appTools.set(t.name, {\n name: t.name,\n key,\n description,\n inputSchema: t.inputSchema,\n readOnly,\n visibility: ui.visibility,\n ...(appUri ? { resourceUri: appUri } : {}),\n })\n }\n // Compiled on the first call, as the SDK does, and once per mount.\n let outputValidator: JsonSchemaValidator<unknown> | undefined\n const outputValidatorOf = (): JsonSchemaValidator<unknown> | undefined => {\n if (!t.outputSchema || outputValidator) return outputValidator\n try {\n schemaValidator ??= new CfWorkerJsonSchemaValidator()\n outputValidator = schemaValidator.getValidator(t.outputSchema as JsonSchemaType)\n } catch (err) {\n // Before anything is sent, so nothing ran on the server: a schema\n // that cannot be compiled is refused as the SDK refuses it, and never\n // silently skipped.\n const reason = (err instanceof Error ? err.message : String(err)).slice(\n 0,\n OUTPUT_SCHEMA_ERROR_MAX_CHARS,\n )\n throw new Error(`Tool '${t.name}' has an invalid outputSchema: ${reason}`)\n }\n return outputValidator\n }\n tools[key] = dynamicTool({\n description,\n inputSchema: jsonSchema(t.inputSchema as Parameters<typeof jsonSchema>[0]),\n execute: async (args, options) => {\n // Throws before anything is sent when the schema cannot be compiled.\n const validate = outputValidatorOf()\n // `client.request`, not `client.callTool`: the typed verb also checks\n // the result against the tool's outputSchema and throws when it does\n // not fit - taking with it a result that DID arrive. The request is\n // the same on the wire, in both eras: on 2026-07-28 the transport\n // derives `Mcp-Method` and `Mcp-Name` from the message itself,\n // whoever built it. Only the `Mcp-Param-*` headers are the typed\n // verb's own - a mirror of arguments a tool marked with\n // `x-mcp-header`, for intermediaries; this client does not send them\n // (so a server's CORS list needs none of them for this client). A\n // request that fails (transport, protocol, abort) throws here: there\n // is no result, and the throw is recorded as a failed call.\n const res = await requestToolCall(\n name,\n client,\n key,\n t.name,\n (args ?? {}) as Record<string, unknown>,\n options as ToolCallOptions | undefined,\n )\n // MCP Apps: the app of this tool can show the result. Told to the run (a UI is\n // listening there), with the call's arguments and the result the app is given -\n // never the app itself, which the host reads with `apps.readUiResource`.\n if (appUri) {\n const run = (options as ToolCallOptions | undefined)?.agentRun\n const emit = run?.emit as ((event: unknown) => void) | undefined\n if (emit) {\n const result = mcpAppToolResultOf(res)\n emit({\n type: 'mcp.app',\n id: `mcp-app-${Date.now().toString(36)}-${(appEventSeq += 1)}`,\n server: name,\n tool: key,\n toolName: t.name,\n resourceUri: appUri,\n input: (args ?? {}) as Record<string, unknown>,\n ...(result ? { result } : {}),\n ...(run?.step ? { step: run.step } : {}),\n })\n }\n }\n // A result arrived. When it does not follow the tool's outputSchema\n // (no structuredContent, or one that does not match) it is passed on\n // with a note rather than reported as a failure — a tool the model is\n // told failed is a tool it calls again, and this one may write.\n let schemaNote: string | undefined\n const violation = validate && outputSchemaViolation(t.name, res, validate)\n if (violation) {\n schemaNote = outputSchemaNote(t.name, violation)\n log(\n 'warn',\n `[mcp] ${key}: result does not follow the declared outputSchema - ${violation}; passed on with a note`,\n )\n }\n // An MCP failure is a NORMAL response with isError set — surface it\n // as a thrown error so both tool paths record a failed call instead\n // of feeding the error text to the model as a success.\n if (res.isError) {\n const flat = flattenContent(res.content)\n throw new Error(typeof flat === 'string' ? flat : JSON.stringify(flat))\n }\n // A server that returns structured content also sends it serialized\n // as text (the specification's backwards-compatible form): the model\n // gets the value once, and whatever else the content holds beside it.\n const structured = isStructuredContent(res.structuredContent)\n ? res.structuredContent\n : undefined\n const flat = flattenContent(\n structured ? dropStructuredDuplicates(res.content, structured) : res.content,\n )\n return withStructuredContent(flat, structured, schemaNote)\n },\n })\n // The agent's consent gate lets read-only tools through in 'ask-writes'.\n if (readOnly) (tools[key] as { readOnly?: boolean }).readOnly = true\n // Which server the tool came from, and that server's instructions: the\n // agent shows the notes of the servers whose tools it actually mounts.\n markMcpTool(tools[key], name, instructionsOf.get(name))\n // And its skills (`skills: true`): they come with its tools, like its instructions.\n const skillSource = skillCatalogs.get(name)?.source\n if (skillSource) markMcpSkills(tools[key], skillSource)\n catalog.push({\n name: key,\n description,\n server: name,\n ...(readOnly ? { readOnly } : {}),\n ...(appUri ? { app: appUri } : {}),\n })\n keys.push(key)\n mounted += 1\n }\n mountedKeys.set(name, keys)\n if (appsMode === 'on') {\n appToolsOf.set(name, appTools)\n // A new listing may declare other apps: what was read for the old one is read again.\n appResources.delete(name)\n }\n log('info', `[mcp] ${name}: ${mounted} tools mounted`)\n }\n\n const connects = await Promise.all(\n Object.entries(servers).map(([name, cfg]) =>\n openConnection(name, cfg, opts, log, elicitationSessionOf(name)),\n ),\n )\n\n for (const server of connects) {\n if (!server.client || !server.listed) {\n results.push({\n name: server.name,\n connected: false,\n error: server.error,\n ...(server.needsAuthorization ? { needsAuthorization: true } : {}),\n })\n continue\n }\n clients.set(server.name, server.client)\n if (server.listener) listeners.set(server.name, server.listener)\n if (server.instructions) {\n log(\n 'info',\n `[mcp] ${server.name}: the server sent instructions (${server.instructions.length} chars)`,\n )\n instructions.push({ server: server.name, instructions: server.instructions })\n instructionsOf.set(server.name, server.instructions)\n }\n if (server.protocol) protocols.push({ server: server.name, ...server.protocol })\n if (server.skills) skillCatalogs.set(server.name, server.skills)\n mountTools(server.name, server.client, server.listed)\n results.push({ name: server.name, connected: true })\n }\n\n const connectedClient = (server: string): Client => {\n const client = clients.get(server)\n if (!client) throw new Error(`MCP server \"${server}\" is not connected`)\n return client\n }\n\n const apps: McpAppsConnection | undefined = appsOn\n ? {\n readUiResource: (server, uri, readOptions) => {\n let client: Client\n try {\n client = connectedClient(server)\n } catch (err) {\n return Promise.reject(err)\n }\n // Only an app a tool of THIS server declares: an app cannot be pointed at another\n // server's resources, nor at a resource its server did not tie to a tool.\n const declared = [...(appToolsOf.get(server)?.values() ?? [])].some(\n (t) => t.resourceUri === uri,\n )\n if (!declared) {\n return Promise.reject(\n new Error(`no tool of MCP server \"${server}\" declares the app ${uri}`),\n )\n }\n let cache = appResources.get(server)\n if (!cache) {\n cache = new Map()\n appResources.set(server, cache)\n }\n const cached = cache.get(uri)\n if (cached) return cached\n const reading = client\n .request(\n { method: 'resources/read', params: { uri } },\n readOptions?.signal ? { signal: readOptions.signal } : undefined,\n )\n .then((result) => {\n const resource = mcpAppResourceOf(server, uri, result)\n // The audit trail the specification asks a host for: what the app may reach.\n log('info', `[mcp] ${server}: app ${uri} - ${describeMcpAppPolicy(resource)}`)\n return resource\n })\n // A failed read is not kept: the next one asks again.\n reading.catch(() => {\n if (appResources.get(server)?.get(uri) === reading) cache.delete(uri)\n })\n cache.set(uri, reading)\n return reading\n },\n appTool: (server, toolName) => {\n const tool = appToolsOf.get(server)?.get(toolName)\n return tool ? { ...tool, visibility: [...tool.visibility] } : undefined\n },\n readResource: async (server, uri, readOptions) => {\n const client = connectedClient(server)\n // Only a server whose apps are on: a declined one's app never runs here.\n if (!appToolsOf.has(server)) {\n throw new Error(`MCP Apps are off for the MCP server \"${server}\"`)\n }\n if (\n typeof uri !== 'string' ||\n uri.length === 0 ||\n uri.length > 2048 ||\n // eslint-disable-next-line no-control-regex\n /[\\u0000-\\u001f\\u007f\\s]/.test(uri)\n ) {\n throw new Error('a resource URI is one line of at most 2048 characters')\n }\n log('info', `[mcp] ${server}: an app's download reads ${uri.slice(0, 200)}`)\n const result = await client.request(\n { method: 'resources/read', params: { uri } },\n readOptions?.signal ? { signal: readOptions.signal } : undefined,\n )\n return mcpAppDownloadOf(uri, result, readOptions?.maxBytes ?? MCP_APP_MAX_DOWNLOAD_BYTES)\n },\n callAppTool: async (server, toolName, args, callOptions) => {\n const client = connectedClient(server)\n const tool = appToolsOf.get(server)?.get(toolName)\n // The specification: a call from an app to a tool whose visibility leaves out\n // 'app' (or that its server does not list) is refused, and never reaches the server.\n if (!tool) {\n throw new Error(`MCP server \"${server}\" has no tool \"${toolName}\" that an app may call`)\n }\n if (typeof args !== 'object' || args === null || Array.isArray(args)) {\n throw new Error(`the arguments of \"${toolName}\" must be an object`)\n }\n log('info', `[mcp] ${server}: an app called ${toolName}`)\n const res = await requestToolCall(\n server,\n client,\n tool.key,\n toolName,\n args,\n callOptions?.signal ? { abortSignal: callOptions.signal } : undefined,\n )\n return (\n mcpAppToolResultOf(res) ?? {\n content: [{ type: 'text', text: 'The result was too large to hand to the app.' }],\n isError: true,\n }\n )\n },\n }\n : undefined\n\n return {\n tools,\n catalog,\n results,\n instructions,\n protocols,\n refreshServer: async (name: string) => {\n const client = clients.get(name)\n if (!client) throw new Error(`MCP server \"${name}\" is not connected`)\n // Its skills too (`skills: true`): a change of them reaches here the way a tool change does.\n await skillCatalogs.get(name)?.refresh()\n mountTools(name, client, await listAllTools(client, () => warnTruncated(log, name)))\n },\n close: async () => {\n // The listen streams first: a pending retry or an attempt in flight must not\n // outlive (or be logged against) a client that is going away.\n for (const listener of listeners.values()) listener.stop()\n listeners.clear()\n appResources.clear()\n await Promise.allSettled([...clients.values()].map((c) => c.close()))\n },\n ...(apps ? { apps } : {}),\n }\n}\n","/**\n * MCP elicitation, the part the two agent packages share: a server asks the user for input in\n * the middle of a tool call, the HOST answers through a callback, and the call goes on. Pure, no\n * imports: the limits, what a request must look like before a host sees it, what an answer must\n * look like before a server sees it, the one function that asks, and the two ways a tool call\n * with questions is driven (`elicitation/create` requests on the 2025 revisions, `input_required`\n * results on 2026-07-28).\n *\n * A consent boundary. The server's text is third-party data: cleaned and capped here, shown only\n * to the host's callback and in the `mcp.elicitation-requested` event, never put into a prompt.\n * The answer goes to the server that asked and nowhere else: nothing in this file logs, emits or\n * returns a value the user entered - events and errors carry field NAMES only.\n *\n * This file is a COPY, byte for byte, in `@dudko.dev/agent` (`src/mcp-elicitation.ts`) and\n * `@dudko.dev/agent-web` (`src/mcp/elicitation.ts`): change both. The Node package's\n * `tests/mcp-elicitation-shared.test.ts` compares the two files and tests every guard here; each\n * needs a mutation check.\n */\n\n// ── limits ───────────────────────────────────────────────────────────────\n\n/** How long one question waits for the host's answer, by default: a human is reading it. */\nexport const MCP_ELICITATION_TIMEOUT_MS = 300_000\n/**\n * The longest wait a timer holds (2^31 - 1 ms, about 24.8 days). `setTimeout` fires a longer one -\n * Infinity included - after about 1 ms, so a `timeoutMs` past it is taken as no limit at all.\n */\nexport const MCP_ELICITATION_TIMEOUT_MAX_MS = 2_147_483_647\n/** The most questions one tool call may ask, by default. */\nexport const MCP_ELICITATION_MAX_PER_TOOL_CALL = 5\n/** The most questions one run may be asked, by default (its helpers' calls included). */\nexport const MCP_ELICITATION_MAX_PER_RUN = 20\n/** The most of a server's message a host is shown, in characters. */\nexport const MCP_ELICITATION_MESSAGE_MAX_CHARS = 2000\n/** The most of a field's title or of an option's title. */\nexport const MCP_ELICITATION_LABEL_MAX_CHARS = 200\n/** The most of a field's description. */\nexport const MCP_ELICITATION_DESCRIPTION_MAX_CHARS = 500\n/** A form with more fields is refused. */\nexport const MCP_ELICITATION_MAX_FIELDS = 50\n/** A select with more options is refused. */\nexport const MCP_ELICITATION_MAX_OPTIONS = 100\n/** A field name, or an option's value, longer than this is refused (they go back verbatim). */\nexport const MCP_ELICITATION_NAME_MAX_CHARS = 200\n/** A link longer than this is refused. */\nexport const MCP_ELICITATION_URL_MAX_CHARS = 2048\n/** The longest text a field without its own `maxLength` may be answered with. */\nexport const MCP_ELICITATION_VALUE_MAX_CHARS = 10_000\n/** Ends a text that a cap cut. */\nexport const MCP_ELICITATION_TRUNCATED = '... [truncated]'\n/** 2026-07-28: the most `input_required` answers one tool call may take before it fails. */\nexport const MCP_INPUT_REQUIRED_MAX_ROUNDS = 10\n/** 2026-07-28: the pause before a round that only says \"call me again\" is answered. */\nexport const MCP_INPUT_REQUIRED_PACING_MS = 250\n/**\n * 2025 revisions: how long a tool call may take, NOT counting the time a question of its own\n * waits for the user. (The SDK's request timeout, a minute, would otherwise end a call whose\n * form is still being filled in.)\n */\nexport const MCP_TOOL_CALL_TIMEOUT_MS = 60_000\n\n// ── types ────────────────────────────────────────────────────────────────\n\n/** One field of a form: the flat subset of JSON Schema the specification allows, nothing else. */\nexport interface McpElicitationFieldSchema {\n type: 'string' | 'number' | 'integer' | 'boolean' | 'array'\n title?: string\n description?: string\n default?: string | number | boolean | string[]\n /** string */\n minLength?: number\n maxLength?: number\n format?: 'email' | 'uri' | 'date' | 'date-time'\n /** string: single-select, plain (`enumNames`: the older titled form). */\n enum?: string[]\n enumNames?: string[]\n /** string: single-select with titles. */\n oneOf?: { const: string; title: string }[]\n /** number / integer */\n minimum?: number\n maximum?: number\n /** array: multi-select. */\n minItems?: number\n maxItems?: number\n items?: { type?: 'string'; enum?: string[]; anyOf?: { const: string; title: string }[] }\n}\n\n/** The form a server asks for, as a host is shown it: checked, cleaned and capped. */\nexport interface McpElicitationSchema {\n type: 'object'\n properties: Record<string, McpElicitationFieldSchema>\n required?: string[]\n}\n\n/** What the host's callback is given. Every string in it is third-party text. */\nexport interface McpElicitationRequest {\n /** Unique per question; the same id is in the two events. */\n id: string\n /** The server that asks: its key in the host's configuration. */\n server: string\n /** The tool call during which it asks: the tool's name as the model called it. */\n tool: string\n mode: 'form' | 'url'\n /** The server's words, cleaned and capped (MCP_ELICITATION_MESSAGE_MAX_CHARS). */\n message: string\n /** Form mode: the fields to fill in. */\n requestedSchema?: McpElicitationSchema\n /**\n * URL mode: the link the server wants the user to open. It is only handed over: nothing in\n * these packages fetches or opens it. https, or http on a loopback host.\n */\n url?: string\n /** URL mode on the 2025 revisions: the server's id for this interaction. */\n elicitationId?: string\n runId?: string\n /** Set when a helper the model started is the one whose call asks (`elicitation.subagents`). */\n subagent?: { id: string; depth: number }\n}\n\nexport type McpElicitationContent = Record<string, string | number | boolean | string[]>\n\n/**\n * The host's answer. `accept` carries the form's values (form mode) or nothing (URL mode: it\n * says the user agreed to open the link); `decline` is a no; `cancel` is \"dismissed\".\n */\nexport type McpElicitationResult =\n | { action: 'accept'; content?: McpElicitationContent }\n | { action: 'decline' }\n | { action: 'cancel' }\n\nexport interface McpElicitationContext {\n /** Aborted when the answer is no longer wanted: the run stopped, or the time ran out. */\n signal: AbortSignal\n}\n\n/** `onElicitation`: the host decides, never the model. */\nexport type McpElicitationHandler = (\n request: McpElicitationRequest,\n ctx: McpElicitationContext,\n) => McpElicitationResult | Promise<McpElicitationResult>\n\n/** The `elicitation` settings beside `onElicitation`. */\nexport interface McpElicitationOptions {\n /**\n * How long one question waits for an answer. Default 300 000. `0` or `Infinity` = no limit of\n * its own (the question waits until the run is stopped), and so is a value above 2^31 - 1 (about\n * 24.8 days, the most a timer holds). Negative or NaN: a configuration error.\n */\n timeoutMs?: number\n /** Questions one tool call may ask. Default 5. */\n maxPerToolCall?: number\n /** Questions one run may be asked. Default 20. */\n maxPerRun?: number\n /** Also accept URL mode (a link to open). Default false: only forms are declared. */\n url?: boolean\n /**\n * Let a tool call made by a helper (a subagent) ask the user too. Default false: such a\n * question is cancelled without the callback being called.\n */\n subagents?: boolean\n}\n\nexport interface McpResolvedElicitationOptions {\n /** 0 = no limit of its own; otherwise at most {@link MCP_ELICITATION_TIMEOUT_MAX_MS}. */\n timeoutMs: number\n maxPerToolCall: number\n maxPerRun: number\n url: boolean\n subagents: boolean\n}\n\n/** Why a question was answered without the host deciding. */\nexport type McpElicitationReason =\n | 'unsupported-schema'\n | 'unsupported-mode'\n | 'insecure-url'\n | 'invalid-request'\n | 'subagent'\n | 'cap-per-call'\n | 'cap-per-run'\n | 'handler-error'\n | 'timeout'\n | 'invalid-answer'\n | 'aborted'\n | 'step-timeout'\n | 'after-failure'\n | 'no-tool-call'\n\n/** The two events of a question. Neither ever carries a value the user entered. */\nexport type McpElicitationEvent =\n | {\n type: 'mcp.elicitation-requested'\n id: string\n server: string\n tool: string\n mode: 'form' | 'url'\n message: string\n requestedSchema?: McpElicitationSchema\n url?: string\n subagent?: { id: string; depth: number }\n }\n | {\n type: 'mcp.elicitation-answered'\n id: string\n server: string\n tool: string\n action: 'accept' | 'decline' | 'cancel'\n /** true when nobody decided: a guard, a cap, a timeout, a failed handler. */\n automatic: boolean\n reason?: McpElicitationReason\n /** The names of the fields an accepted form was answered with. Names only. */\n fields?: string[]\n }\n\n/** A failure of this boundary; `toJSON` keeps the message when a trace is serialised. */\nexport class McpElicitationError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'McpElicitationError'\n }\n\n toJSON(): string {\n return this.message\n }\n}\n\n// ── settings ─────────────────────────────────────────────────────────────\n\nconst shownValue = (value: unknown): string =>\n typeof value === 'number' ? String(value) : (JSON.stringify(value) ?? String(value))\n\nconst settingOf = (value: unknown, name: string, fallback: number, min: number): number => {\n if (value === undefined || value === null) {\n return fallback\n }\n if (typeof value !== 'number' || !Number.isFinite(value) || value < min) {\n throw new Error(\n `elicitation.${name} must be a number of at least ${min} (got ${shownValue(value)})`,\n )\n }\n return Math.floor(value)\n}\n\n// `timeoutMs`: 0, Infinity and anything past what a timer holds are no limit (0); a positive\n// fraction waits at least 1 ms rather than becoming \"no limit\".\nconst timeoutOf = (value: unknown): number => {\n if (value === undefined || value === null) {\n return MCP_ELICITATION_TIMEOUT_MS\n }\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {\n throw new Error(\n `elicitation.timeoutMs must be a number of at least 0 (0 or Infinity: no limit) (got ${shownValue(value)})`,\n )\n }\n return value === 0 || value > MCP_ELICITATION_TIMEOUT_MAX_MS ? 0 : Math.max(1, Math.floor(value))\n}\n\n/** The settings with their defaults. A value that is not a usable number is a configuration error. */\nexport const resolveMcpElicitationOptions = (\n raw: McpElicitationOptions | undefined,\n): McpResolvedElicitationOptions => ({\n timeoutMs: timeoutOf(raw?.timeoutMs),\n maxPerToolCall: settingOf(\n raw?.maxPerToolCall,\n 'maxPerToolCall',\n MCP_ELICITATION_MAX_PER_TOOL_CALL,\n 1,\n ),\n maxPerRun: settingOf(raw?.maxPerRun, 'maxPerRun', MCP_ELICITATION_MAX_PER_RUN, 1),\n url: raw?.url === true,\n subagents: raw?.subagents === true,\n})\n\n/**\n * The `elicitation` capability a client with a handler declares: the form always, URL mode only\n * when the host asked for it. (No handler: no capability at all - the caller declares nothing.)\n */\nexport const mcpElicitationCapability = (\n options: Pick<McpResolvedElicitationOptions, 'url'>,\n): { form: Record<string, never>; url?: Record<string, never> } =>\n options.url ? { form: {}, url: {} } : { form: {} }\n\n// ── the request, before a host sees it ───────────────────────────────────\n\n// C0 / C1 controls (tab and newline stay), zero-width and bidirectional-override characters.\nconst INVISIBLE = /[\\u0000-\\u0008\\u000B-\\u001F\\u007F-\\u009F---]/g\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** Third-party text as a host may show it: a string, invisible characters removed, capped. */\nexport const cleanMcpElicitationText = (raw: unknown, max: number): string => {\n if (typeof raw !== 'string') {\n return ''\n }\n const text = raw.replace(/\\r\\n?/g, '\\n').replace(INVISIBLE, '').trim()\n return text.length > max ? `${text.slice(0, Math.max(0, max))}${MCP_ELICITATION_TRUNCATED}` : text\n}\n\n// A string that goes back to the server verbatim (a field name, an option's value): it is\n// never altered, so one that would have to be is not usable.\nconst isVerbatim = (value: unknown): value is string =>\n typeof value === 'string' &&\n value.length > 0 &&\n value.length <= MCP_ELICITATION_NAME_MAX_CHARS &&\n value.replace(INVISIBLE, '') === value &&\n !/[\\r\\n\\t]/.test(value)\n\nconst UNSAFE_NAMES: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])\n\n// A field's name in a sentence a model or a log may read.\nconst fieldLabel = (name: string): string =>\n JSON.stringify(cleanMcpElicitationText(name, 64).replace(/\\s+/g, ' '))\n\ntype Checked<T> = { ok: true; value: T } | { ok: false; reason: string }\n\nconst bad = (reason: string): { ok: false; reason: string } => ({ ok: false, reason })\n\nconst label = (raw: unknown, max: number): string | undefined => {\n const text = cleanMcpElicitationText(raw, max)\n return text ? text : undefined\n}\n\nconst count = (raw: unknown): number | undefined | null =>\n raw === undefined\n ? undefined\n : typeof raw === 'number' && Number.isInteger(raw) && raw >= 0\n ? raw\n : null\n\nconst plainOptions = (raw: unknown): string[] | undefined =>\n Array.isArray(raw) &&\n raw.length > 0 &&\n raw.length <= MCP_ELICITATION_MAX_OPTIONS &&\n raw.every(isVerbatim)\n ? [...(raw as string[])]\n : undefined\n\nconst titledOptions = (raw: unknown): { const: string; title: string }[] | undefined => {\n if (!Array.isArray(raw) || raw.length === 0 || raw.length > MCP_ELICITATION_MAX_OPTIONS) {\n return undefined\n }\n const out: { const: string; title: string }[] = []\n for (const option of raw) {\n if (!isPlainObject(option) || !isVerbatim(option.const)) {\n return undefined\n }\n out.push({\n const: option.const,\n title: label(option.title, MCP_ELICITATION_LABEL_MAX_CHARS) ?? option.const,\n })\n }\n return out\n}\n\nconst FORMATS: ReadonlySet<string> = new Set(['email', 'uri', 'date', 'date-time'])\n\nconst normalizeField = (name: string, raw: unknown): Checked<McpElicitationFieldSchema> => {\n const at = `field ${fieldLabel(name)}`\n if (!isPlainObject(raw)) {\n return bad(`${at} is not a schema`)\n }\n const type = raw.type\n if (\n type !== 'string' &&\n type !== 'number' &&\n type !== 'integer' &&\n type !== 'boolean' &&\n type !== 'array'\n ) {\n return bad(\n `${at} has an unsupported type (${cleanMcpElicitationText(typeof type === 'string' ? type : typeof type, 20)}); a form may hold only strings, numbers, booleans and selects`,\n )\n }\n // A nested form, whatever its `type` says.\n if (raw.properties !== undefined || raw.additionalProperties !== undefined) {\n return bad(`${at} is a nested object; a form is flat`)\n }\n const field: McpElicitationFieldSchema = { type }\n const title = label(raw.title, MCP_ELICITATION_LABEL_MAX_CHARS)\n if (title) {\n field.title = title\n }\n const description = label(raw.description, MCP_ELICITATION_DESCRIPTION_MAX_CHARS)\n if (description) {\n field.description = description\n }\n if (type === 'string') {\n if (raw.enum !== undefined && raw.oneOf !== undefined) {\n return bad(`${at} has both \"enum\" and \"oneOf\"`)\n }\n if (raw.enum !== undefined) {\n const options = plainOptions(raw.enum)\n if (!options) {\n return bad(`${at} has options that cannot be shown`)\n }\n field.enum = options\n if (Array.isArray(raw.enumNames) && raw.enumNames.length === options.length) {\n field.enumNames = raw.enumNames.map(\n (n, i) => label(n, MCP_ELICITATION_LABEL_MAX_CHARS) ?? options[i],\n )\n }\n } else if (raw.oneOf !== undefined) {\n const options = titledOptions(raw.oneOf)\n if (!options) {\n return bad(`${at} has options that cannot be shown`)\n }\n field.oneOf = options\n } else {\n const min = count(raw.minLength)\n const max = count(raw.maxLength)\n if (min === null || max === null) {\n return bad(`${at} has a length limit that is not a whole number`)\n }\n if (min !== undefined) {\n field.minLength = min\n }\n if (max !== undefined) {\n field.maxLength = max\n }\n if (raw.format !== undefined) {\n if (typeof raw.format !== 'string' || !FORMATS.has(raw.format)) {\n return bad(`${at} has an unsupported format`)\n }\n field.format = raw.format as McpElicitationFieldSchema['format']\n }\n }\n } else if (type === 'number' || type === 'integer') {\n for (const key of ['minimum', 'maximum'] as const) {\n const bound = raw[key]\n if (bound === undefined) {\n continue\n }\n if (typeof bound !== 'number' || !Number.isFinite(bound)) {\n return bad(`${at} has a bound that is not a number`)\n }\n field[key] = bound\n }\n } else if (type === 'array') {\n const items = raw.items\n if (!isPlainObject(items) || items.properties !== undefined) {\n return bad(`${at} is a list of something other than options; a form is flat`)\n }\n if (items.enum !== undefined && items.anyOf === undefined) {\n const options = plainOptions(items.enum)\n if (!options || (items.type !== undefined && items.type !== 'string')) {\n return bad(`${at} has options that cannot be shown`)\n }\n field.items = { type: 'string', enum: options }\n } else if (items.anyOf !== undefined && items.enum === undefined) {\n const options = titledOptions(items.anyOf)\n if (!options) {\n return bad(`${at} has options that cannot be shown`)\n }\n field.items = { anyOf: options }\n } else {\n return bad(`${at} is a list of something other than options; a form is flat`)\n }\n const min = count(raw.minItems)\n const max = count(raw.maxItems)\n if (min === null || max === null) {\n return bad(`${at} has a size limit that is not a whole number`)\n }\n if (min !== undefined) {\n field.minItems = min\n }\n if (max !== undefined) {\n field.maxItems = max\n }\n }\n // A default the field itself would refuse is left out, not shown.\n if (raw.default !== undefined && checkValue(name, field, raw.default) === undefined) {\n field.default = Array.isArray(raw.default)\n ? [...(raw.default as string[])]\n : (raw.default as string | number | boolean)\n }\n return { ok: true, value: field }\n}\n\n/**\n * The form a server asked for, reduced to what the specification allows a form to be: a flat\n * object of strings, numbers, booleans and selects. Anything else - a nested object, a list of\n * objects, a type union, an unknown format, too many fields or options, a name that could not\n * be sent back verbatim - is refused with a reason (the caller declines the request). Keywords\n * outside the subset are dropped; titles and descriptions are cleaned and capped.\n */\nexport const normalizeMcpElicitationSchema = (raw: unknown): Checked<McpElicitationSchema> => {\n if (!isPlainObject(raw) || raw.type !== 'object' || !isPlainObject(raw.properties)) {\n return bad('the form is not an object with properties')\n }\n const names = Object.keys(raw.properties)\n if (names.length > MCP_ELICITATION_MAX_FIELDS) {\n return bad(`the form has more than ${MCP_ELICITATION_MAX_FIELDS} fields`)\n }\n const properties: Record<string, McpElicitationFieldSchema> = {}\n for (const name of names) {\n if (!isVerbatim(name) || UNSAFE_NAMES.has(name)) {\n return bad(`the form has a field name that cannot be used (${fieldLabel(name)})`)\n }\n const field = normalizeField(name, raw.properties[name])\n if (!field.ok) {\n return field\n }\n properties[name] = field.value\n }\n const schema: McpElicitationSchema = { type: 'object', properties }\n if (raw.required !== undefined) {\n if (!Array.isArray(raw.required)) {\n return bad('the form\\'s \"required\" is not a list')\n }\n const required: string[] = []\n for (const name of raw.required) {\n if (typeof name !== 'string' || !Object.hasOwn(properties, name)) {\n return bad('the form requires a field it does not have')\n }\n if (!required.includes(name)) {\n required.push(name)\n }\n }\n if (required.length) {\n schema.required = required\n }\n }\n return { ok: true, value: schema }\n}\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]', '::1'])\n\n/**\n * A link a server wants the user to open, or why it is refused. Only https - or http on a\n * loopback host, the rule the OAuth code of these packages applies (`assertSecureOAuthUrl`) -\n * and no credentials in it. Parsed, not pattern-matched; the result is the parsed form (an\n * internationalised host shows as punycode). The link is never fetched or opened here.\n */\nexport const checkMcpElicitationUrl = (raw: unknown): Checked<string> => {\n if (typeof raw !== 'string' || !raw || raw.length > MCP_ELICITATION_URL_MAX_CHARS) {\n return bad('the link is missing or too long')\n }\n if (raw.replace(INVISIBLE, '') !== raw || /\\s/.test(raw)) {\n return bad('the link contains characters that cannot be shown')\n }\n let parsed: URL\n try {\n parsed = new URL(raw)\n } catch {\n return bad('the link is not a valid URL')\n }\n if (\n parsed.protocol !== 'https:' &&\n !(parsed.protocol === 'http:' && LOOPBACK_HOSTS.has(parsed.hostname))\n ) {\n return bad('only https links are accepted (http on a loopback host)')\n }\n if (parsed.username || parsed.password) {\n return bad('the link carries credentials')\n }\n return { ok: true, value: parsed.href }\n}\n\ntype ParsedRequest =\n | {\n ok: true\n mode: 'form'\n message: string\n requestedSchema: McpElicitationSchema\n }\n | { ok: true; mode: 'url'; message: string; url: string; elicitationId?: string }\n | { ok: false; reason: McpElicitationReason; detail: string }\n\n/**\n * The params of an `elicitation/create` request as a host may be shown them, or why the request\n * is declined before anybody is asked.\n */\nexport const parseMcpElicitationParams = (\n params: unknown,\n options: Pick<McpResolvedElicitationOptions, 'url'>,\n): ParsedRequest => {\n if (!isPlainObject(params)) {\n return { ok: false, reason: 'invalid-request', detail: 'the request has no parameters' }\n }\n const mode = params.mode ?? 'form'\n if (mode !== 'form' && mode !== 'url') {\n return { ok: false, reason: 'unsupported-mode', detail: 'the mode is neither form nor url' }\n }\n if (typeof params.message !== 'string') {\n return { ok: false, reason: 'invalid-request', detail: 'the request has no message' }\n }\n const message = cleanMcpElicitationText(params.message, MCP_ELICITATION_MESSAGE_MAX_CHARS)\n if (mode === 'url') {\n if (!options.url) {\n return {\n ok: false,\n reason: 'unsupported-mode',\n detail: 'URL mode was not offered (elicitation.url)',\n }\n }\n const url = checkMcpElicitationUrl(params.url)\n if (!url.ok) {\n return { ok: false, reason: 'insecure-url', detail: url.reason }\n }\n const elicitationId = label(params.elicitationId, MCP_ELICITATION_NAME_MAX_CHARS)\n return {\n ok: true,\n mode,\n message,\n url: url.value,\n ...(elicitationId ? { elicitationId } : {}),\n }\n }\n const schema = normalizeMcpElicitationSchema(params.requestedSchema)\n if (!schema.ok) {\n return { ok: false, reason: 'unsupported-schema', detail: schema.reason }\n }\n return { ok: true, mode, message, requestedSchema: schema.value }\n}\n\n// ── the answer, before a server sees it ──────────────────────────────────\n\nconst optionValues = (field: McpElicitationFieldSchema): string[] | undefined =>\n field.enum ?? field.oneOf?.map((o) => o.const)\n\nconst validFormat = (format: McpElicitationFieldSchema['format'], value: string): boolean => {\n switch (format) {\n case 'email':\n return /^[^@\\s]+@[^@\\s]+$/.test(value)\n case 'uri':\n try {\n return Boolean(new URL(value))\n } catch {\n return false\n }\n case 'date':\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(value) && !Number.isNaN(Date.parse(value))\n case 'date-time':\n return /^\\d{4}-\\d{2}-\\d{2}T/.test(value) && !Number.isNaN(Date.parse(value))\n default:\n return true\n }\n}\n\n// Why a value does not fit its field, or undefined when it does. Never quotes the value.\nconst checkValue = (\n name: string,\n field: McpElicitationFieldSchema,\n value: unknown,\n): string | undefined => {\n const at = `field ${fieldLabel(name)}`\n switch (field.type) {\n case 'string': {\n if (typeof value !== 'string') {\n return `${at} must be a text`\n }\n const options = optionValues(field)\n if (options) {\n return options.includes(value) ? undefined : `${at} is not one of the options`\n }\n if (value.length > (field.maxLength ?? MCP_ELICITATION_VALUE_MAX_CHARS)) {\n return `${at} is too long`\n }\n if (field.minLength !== undefined && value.length < field.minLength) {\n return `${at} is too short`\n }\n return validFormat(field.format, value)\n ? undefined\n : `${at} is not a valid ${field.format ?? 'text'}`\n }\n case 'number':\n case 'integer': {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n return `${at} must be a number`\n }\n if (field.type === 'integer' && !Number.isInteger(value)) {\n return `${at} must be a whole number`\n }\n if (field.minimum !== undefined && value < field.minimum) {\n return `${at} is below the minimum`\n }\n return field.maximum !== undefined && value > field.maximum\n ? `${at} is above the maximum`\n : undefined\n }\n case 'boolean':\n return typeof value === 'boolean' ? undefined : `${at} must be true or false`\n case 'array': {\n const options = field.items?.enum ?? field.items?.anyOf?.map((o) => o.const) ?? []\n if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) {\n return `${at} must be a list of options`\n }\n if (!value.every((item) => options.includes(item as string))) {\n return `${at} holds something that is not one of the options`\n }\n if (field.minItems !== undefined && value.length < field.minItems) {\n return `${at} has too few selected`\n }\n return (field.maxItems !== undefined && value.length > field.maxItems) ||\n value.length > MCP_ELICITATION_MAX_OPTIONS\n ? `${at} has too many selected`\n : undefined\n }\n }\n}\n\n/**\n * An accepted form, checked against the schema it answers: every value of the type and within\n * the limits its field states, every required field there, and NO field the form did not ask\n * for (what the server did not request is not sent to it). The result is a fresh object holding\n * only the form's own fields. A refusal names the field and the rule, never the value.\n */\nexport const validateMcpElicitationContent = (\n schema: McpElicitationSchema,\n content: unknown,\n): Checked<McpElicitationContent> => {\n if (content !== undefined && !isPlainObject(content)) {\n return bad('the answer is not an object of field values')\n }\n const given = content ?? {}\n for (const name of Object.keys(given)) {\n if (!Object.hasOwn(schema.properties, name)) {\n return bad(`${fieldLabel(name)} is not a field of the form`)\n }\n }\n const required = new Set(schema.required ?? [])\n const value: McpElicitationContent = {}\n for (const [name, field] of Object.entries(schema.properties)) {\n const answered = Object.hasOwn(given, name) ? given[name] : undefined\n if (answered === undefined || answered === null) {\n if (required.has(name)) {\n return bad(`field ${fieldLabel(name)} is required`)\n }\n continue\n }\n const problem = checkValue(name, field, answered)\n if (problem) {\n return bad(problem)\n }\n value[name] = Array.isArray(answered)\n ? [...(answered as string[])]\n : (answered as string | number | boolean)\n }\n return { ok: true, value }\n}\n\n// ── asking ───────────────────────────────────────────────────────────────\n\n/** One tool call, as far as its questions are concerned. Made per call, by the connector. */\nexport interface McpElicitationCall {\n server: string\n /** The tool's name as the model called it. */\n tool: string\n /** The run's abort signal (and the step's time limit), when the call has one. */\n signal?: AbortSignal\n /** Where the two events go; absent outside a run. */\n emit?: (event: McpElicitationEvent) => void\n runId?: string\n /** Set when the call is made by a helper (a subagent), not by the run itself. */\n subagent?: { id: string; depth: number }\n /** The questions asked in this run so far: one object per run, shared by its calls. */\n run: { count: number }\n /** The questions asked in this call so far. */\n asked: number\n /**\n * Set by the first answer nobody decided: the call then FAILS with this text, whatever the\n * server answers afterwards, and nothing is asked or sent again on its behalf.\n */\n failure?: string\n /** Called around the wait for the host (true: waiting), so a call's own clock can stop. */\n onWait?: (waiting: boolean) => void\n /**\n * Stops the time limits of the run the call belongs to (its step's, and those of the subagent\n * tools above it) for the length of the wait for the host; returns what starts them again.\n * The wait keeps its own bound, `timeoutMs`, and a stop of the run still ends it at once.\n */\n pause?: () => () => void\n}\n\nexport interface McpElicitationDeps {\n handler: McpElicitationHandler\n options: McpResolvedElicitationOptions\n log: (level: 'info' | 'warn' | 'error', message: string) => void\n}\n\nconst newId = (): string => {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto\n return typeof c?.randomUUID === 'function'\n ? c.randomUUID()\n : `e-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n}\n\nconst isTimeoutAbort = (signal: AbortSignal | undefined): boolean =>\n (signal?.reason as { name?: unknown } | undefined)?.name === 'TimeoutError'\n\nconst abortReason = (signal: AbortSignal | undefined): unknown => {\n if (signal?.reason !== undefined) {\n return signal.reason\n }\n const err = new Error('Aborted')\n err.name = 'AbortError'\n return err\n}\n\n/** What a tool call fails with when one of its questions was answered without the host deciding. */\nexport const mcpElicitationFailure = (\n tool: string,\n reason: McpElicitationReason,\n options: McpResolvedElicitationOptions,\n detail?: string,\n): string => {\n const why: Record<McpElicitationReason, string> = {\n 'unsupported-schema': `the form it sent cannot be shown (${detail ?? 'unsupported schema'})`,\n 'unsupported-mode': `it asked in a way this client does not offer (${detail ?? 'unsupported mode'})`,\n 'insecure-url': `the link it sent was refused (${detail ?? 'not https'})`,\n 'invalid-request': `its request was malformed (${detail ?? 'invalid'})`,\n subagent:\n 'a helper is not allowed to ask the user (elicitation.subagents); the question was not shown',\n 'cap-per-call': `it had already asked ${options.maxPerToolCall} time(s) in this call (elicitation.maxPerToolCall)`,\n 'cap-per-run': `${options.maxPerRun} question(s) were already asked in this run (elicitation.maxPerRun)`,\n 'handler-error': 'the host could not ask the user (its elicitation handler failed)',\n timeout: `nobody answered within ${options.timeoutMs} ms (elicitation.timeoutMs)`,\n 'invalid-answer': `the answer did not fit the form (${detail ?? 'invalid'}) and was not sent`,\n aborted: 'the run was stopped',\n 'step-timeout': \"the tool call's time limit ended before the question was answered\",\n 'after-failure': 'an earlier question of the same call had already failed',\n 'no-tool-call': 'no tool call was in progress',\n }\n return (\n `MCP tool \"${tool}\" did not finish: the server asked the user for input, and ${why[reason]}. ` +\n `The call was not repeated; do not call the tool again only because of this.`\n )\n}\n\ntype WireAnswer = { action: 'accept' | 'decline' | 'cancel'; content?: McpElicitationContent }\n\n/**\n * Answer one `elicitation/create` (its `params`, from either revision) on behalf of a tool call.\n *\n * The host's callback is called only when every guard passes: the request is well-formed and\n * within what a form may be, the call is not a helper's (unless allowed), the caps are not\n * reached, the call has not failed already. Its answer is checked against the form before it is\n * returned. In every other case the answer is made here (`decline` for a request that cannot be\n * shown, `cancel` otherwise), `call.failure` is set, and the caller fails the tool call with it.\n *\n * Throws only when the call's own signal aborted (the run was stopped, or its time was already\n * spent when the question came): the reason is rethrown, as for any aborted tool call. While\n * the host is asked, the limits of the run are stopped (`call.pause`): the wait is bounded by\n * `timeoutMs` and by a stop of the run, not by the step it belongs to.\n */\nexport const answerMcpElicitation = async (\n deps: McpElicitationDeps,\n call: McpElicitationCall,\n params: unknown,\n): Promise<WireAnswer> => {\n const { options, log } = deps\n const id = newId()\n const where = `[mcp] ${call.server}: elicitation during ${call.tool}`\n const answered = (\n action: WireAnswer['action'],\n automatic: boolean,\n reason?: McpElicitationReason,\n fields?: string[],\n ): void =>\n call.emit?.({\n type: 'mcp.elicitation-answered',\n id,\n server: call.server,\n tool: call.tool,\n action,\n automatic,\n ...(reason ? { reason } : {}),\n ...(fields ? { fields } : {}),\n })\n // Nobody decided: the answer is made here, and the tool call fails with the reason.\n const refuse = (reason: McpElicitationReason, detail?: string): WireAnswer => {\n const action = (\n ['unsupported-schema', 'unsupported-mode', 'insecure-url', 'invalid-request'] as string[]\n ).includes(reason)\n ? 'decline'\n : 'cancel'\n call.failure ??= mcpElicitationFailure(call.tool, reason, options, detail)\n log(\n 'warn',\n `${where} answered \"${action}\" automatically - ${reason}${detail ? `: ${detail}` : ''}`,\n )\n answered(action, true, reason)\n return { action }\n }\n\n if (call.failure) {\n return refuse('after-failure')\n }\n const parsed = parseMcpElicitationParams(params, options)\n if (!parsed.ok) {\n return refuse(parsed.reason, parsed.detail)\n }\n if (call.subagent && !options.subagents) {\n return refuse('subagent')\n }\n if (call.asked >= options.maxPerToolCall) {\n return refuse('cap-per-call')\n }\n if (call.run.count >= options.maxPerRun) {\n return refuse('cap-per-run')\n }\n if (call.signal?.aborted) {\n answered('cancel', true, isTimeoutAbort(call.signal) ? 'step-timeout' : 'aborted')\n throw abortReason(call.signal)\n }\n call.asked += 1\n call.run.count += 1\n\n const request: McpElicitationRequest = {\n id,\n server: call.server,\n tool: call.tool,\n mode: parsed.mode,\n message: parsed.message,\n ...(parsed.mode === 'form' ? { requestedSchema: parsed.requestedSchema } : { url: parsed.url }),\n ...(parsed.mode === 'url' && parsed.elicitationId\n ? { elicitationId: parsed.elicitationId }\n : {}),\n ...(call.runId ? { runId: call.runId } : {}),\n ...(call.subagent ? { subagent: call.subagent } : {}),\n }\n call.emit?.({\n type: 'mcp.elicitation-requested',\n id,\n server: call.server,\n tool: call.tool,\n mode: request.mode,\n message: request.message,\n ...(request.requestedSchema ? { requestedSchema: request.requestedSchema } : {}),\n ...(request.url ? { url: request.url } : {}),\n ...(call.subagent ? { subagent: call.subagent } : {}),\n })\n\n // The host's own signal: aborted when the wait ends for any reason, so a prompt left open\n // (a dialog, a terminal question) can be taken down.\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n let onAbort: (() => void) | undefined\n type Outcome =\n | { kind: 'answer'; value: unknown }\n | { kind: 'error'; error: unknown }\n | { kind: 'timeout' }\n | { kind: 'aborted' }\n call.onWait?.(true)\n // A person is being asked: the step's limit is about models and tools, and does not run\n // meanwhile. It goes on, with the time it had left, the moment the wait is over.\n const resume = call.pause?.()\n const outcome = await new Promise<Outcome>((resolve) => {\n if (options.timeoutMs > 0) {\n timer = setTimeout(() => resolve({ kind: 'timeout' }), options.timeoutMs)\n }\n onAbort = () => resolve({ kind: 'aborted' })\n call.signal?.addEventListener('abort', onAbort, { once: true })\n Promise.resolve()\n .then(() => deps.handler(request, { signal: controller.signal }))\n .then(\n (value) => resolve({ kind: 'answer', value }),\n (error: unknown) => resolve({ kind: 'error', error }),\n )\n })\n resume?.()\n call.onWait?.(false)\n if (timer) {\n clearTimeout(timer)\n }\n if (onAbort) {\n call.signal?.removeEventListener('abort', onAbort)\n }\n controller.abort()\n\n if (outcome.kind === 'aborted') {\n const reason: McpElicitationReason = isTimeoutAbort(call.signal) ? 'step-timeout' : 'aborted'\n call.failure ??= mcpElicitationFailure(call.tool, reason, options)\n if (reason === 'step-timeout') {\n // Not the step's own limit, which does not run while the host is asked (`call.pause`): a\n // time limit put on the call's signal from outside, the run's signal included.\n log(\n 'warn',\n `${where}: a time limit on the tool call's signal ended while the question was waiting for an answer; only the step's own limit stops while a person is asked, not a limit on the run's signal`,\n )\n }\n answered('cancel', true, reason)\n throw abortReason(call.signal)\n }\n if (outcome.kind === 'timeout') {\n return refuse('timeout')\n }\n if (outcome.kind === 'error') {\n // The handler's message is the host's own text and may quote what the user typed: only\n // the kind of error is said.\n const name = (outcome.error as { name?: unknown } | null)?.name\n return refuse('handler-error', typeof name === 'string' ? name.slice(0, 40) : 'error')\n }\n const result = outcome.value as { action?: unknown; content?: unknown } | null | undefined\n const action = result?.action\n if (action === 'decline' || action === 'cancel') {\n answered(action, false)\n return { action }\n }\n if (action !== 'accept') {\n return refuse('invalid-answer', 'the handler returned no accept, decline or cancel')\n }\n if (parsed.mode === 'url') {\n // Consent to open the link; a URL-mode answer carries no content.\n answered('accept', false)\n return { action: 'accept' }\n }\n const content = validateMcpElicitationContent(parsed.requestedSchema, result?.content)\n if (!content.ok) {\n return refuse('invalid-answer', content.reason)\n }\n answered('accept', false, undefined, Object.keys(content.value))\n return { action: 'accept', content: content.value }\n}\n\n// ── driving a tool call ──────────────────────────────────────────────────\n\n/** What a later leg of a 2026-07-28 tool call adds to its params. */\nexport interface McpInputRequiredRetry {\n inputResponses?: Record<string, unknown>\n requestState?: string\n}\n\n/** One request of a tool call, as the connector sends it. */\nexport interface McpToolCallLeg {\n /** The call's signal for this leg. */\n signal?: AbortSignal\n /** 2026-07-28, after an `input_required` answer: what to add to the original params. */\n retry?: McpInputRequiredRetry\n /** 2025 revisions: the request's own timeout is replaced by the session's pausable one. */\n ownTimeout?: boolean\n}\n\nconst sleep = (ms: number, signal: AbortSignal | undefined): Promise<void> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortReason(signal))\n return\n }\n const onAbort = (): void => {\n clearTimeout(timer)\n reject(abortReason(signal))\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n\nconst isInputRequired = (\n value: unknown,\n): value is { resultType: 'input_required'; inputRequests?: unknown; requestState?: unknown } =>\n isPlainObject(value) && value.resultType === 'input_required'\n\n/** What a tool call fails with when a 2026-07-28 server asks for something that is not a question to the user. */\nexport const mcpInputRequestUnsupportedMessage = (toolName: string, method: unknown): string =>\n `MCP tool \"${toolName}\" did not finish: the server asked for input this client does not provide ` +\n `(${cleanMcpElicitationText(typeof method === 'string' ? method : 'a malformed request', 60)}; only elicitation is answered). ` +\n `The call was not repeated.`\n\nexport const mcpInputRequiredRoundsMessage = (toolName: string): string =>\n `MCP tool \"${toolName}\" did not finish: the server still asked for input after ` +\n `${MCP_INPUT_REQUIRED_MAX_ROUNDS} rounds. The call was not repeated.`\n\n/** A tool call that ran past MCP_TOOL_CALL_TIMEOUT_MS of its own time (2025 revisions). */\nexport const mcpToolCallTimeoutMessage = (toolName: string): string =>\n `MCP tool \"${toolName}\" timed out after ${MCP_TOOL_CALL_TIMEOUT_MS} ms (not counting the time ` +\n `its questions waited for the user).`\n\nexport interface McpElicitationCallInfo {\n /** The tool's name as the model called it (events, the host's request). */\n tool: string\n /** The tool's own name on the server (error texts, as the other MCP errors use). */\n toolName: string\n signal?: AbortSignal\n emit?: (event: McpElicitationEvent) => void\n runId?: string\n subagent?: { id: string; depth: number }\n /** The run's counter; absent outside a run (the call then counts alone). */\n run?: { count: number }\n /** Stops the run's time limits while the host is asked; returns what starts them again. */\n pause?: () => () => void\n}\n\nexport interface McpElicitationSession {\n /** The `elicitation` capability to declare. */\n capability: { form: Record<string, never>; url?: Record<string, never> }\n /**\n * 2025 revisions: answer an `elicitation/create` request the server sent. It belongs to the\n * tool call in flight (there is exactly one: `call` runs them one at a time); with none in\n * flight it is cancelled.\n */\n onRequest: (params: unknown) => Promise<WireAnswer>\n /**\n * Make one tool call. `send` issues one `tools/call` request and resolves with its result -\n * on 2026-07-28 possibly an `input_required` one, which is answered here and followed by\n * another leg. Rejects with McpElicitationError when a question was answered automatically.\n */\n call: <T>(\n era: 'legacy' | 'modern',\n info: McpElicitationCallInfo,\n send: (leg: McpToolCallLeg) => Promise<T>,\n ) => Promise<T>\n}\n\n/**\n * The elicitation side of one connection to one server.\n *\n * 2025 revisions: the server's question is a request of its own that does not say which tool\n * call it belongs to, so calls made through a session run ONE AT A TIME - the call in flight is\n * the one that asks. The call's own clock (MCP_TOOL_CALL_TIMEOUT_MS) stops while a question\n * waits. After an automatic answer the server's result is discarded and the call fails; a\n * server that asks again after that has its call aborted.\n *\n * 2026-07-28: the question is the call's own `input_required` result. Each is answered and the\n * call is sent again with the answers and the server's `requestState`, byte for byte - the\n * server's way of continuing ONE call, not a second call. After an automatic answer nothing is\n * sent again.\n */\nexport const createMcpElicitationSession = (\n server: string,\n deps: McpElicitationDeps,\n): McpElicitationSession => {\n let current: (McpElicitationCall & { abort: (reason: unknown) => void }) | undefined\n let tail: Promise<void> = Promise.resolve()\n\n // One at a time; waiting for the turn ends when the caller's signal aborts.\n const acquire = async (signal: AbortSignal | undefined): Promise<() => void> => {\n const before = tail\n let release!: () => void\n tail = new Promise<void>((resolve) => {\n release = resolve\n })\n try {\n await new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortReason(signal))\n return\n }\n const onAbort = (): void => reject(abortReason(signal))\n signal?.addEventListener('abort', onAbort, { once: true })\n void before.then(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n })\n })\n } catch (err) {\n // Give the turn up without breaking the chain for those behind.\n void before.then(release)\n throw err\n }\n return release\n }\n\n const newCall = (info: McpElicitationCallInfo, signal?: AbortSignal): McpElicitationCall => ({\n server,\n tool: info.tool,\n ...(signal ? { signal } : {}),\n ...(info.emit ? { emit: info.emit } : {}),\n ...(info.runId ? { runId: info.runId } : {}),\n ...(info.subagent ? { subagent: info.subagent } : {}),\n ...(info.pause ? { pause: info.pause } : {}),\n run: info.run ?? { count: 0 },\n asked: 0,\n })\n\n const callLegacy = async <T>(\n info: McpElicitationCallInfo,\n send: (leg: McpToolCallLeg) => Promise<T>,\n ): Promise<T> => {\n const release = await acquire(info.signal)\n const controller = new AbortController()\n const onOuterAbort = (): void => controller.abort(abortReason(info.signal))\n info.signal?.addEventListener('abort', onOuterAbort, { once: true })\n // The call's own clock: it runs only while no question is waiting.\n let left = MCP_TOOL_CALL_TIMEOUT_MS\n let startedAt = Date.now()\n let timedOut = false\n let timer: ReturnType<typeof setTimeout> | undefined\n const start = (): void => {\n startedAt = Date.now()\n timer = setTimeout(\n () => {\n timedOut = true\n controller.abort(new McpElicitationError(mcpToolCallTimeoutMessage(info.toolName)))\n },\n Math.max(0, left),\n )\n }\n const stop = (): void => {\n if (timer) {\n clearTimeout(timer)\n timer = undefined\n left -= Date.now() - startedAt\n }\n }\n const call = Object.assign(newCall(info, controller.signal), {\n abort: (reason: unknown) => controller.abort(reason),\n onWait: (waiting: boolean) => (waiting ? stop() : start()),\n })\n current = call\n try {\n if (info.signal?.aborted) {\n throw abortReason(info.signal)\n }\n start()\n const result = await send({ signal: controller.signal, ownTimeout: true })\n if (call.failure) {\n throw new McpElicitationError(call.failure)\n }\n return result\n } catch (err) {\n // The caller's own abort stays what it was.\n if (info.signal?.aborted) {\n throw err\n }\n if (call.failure) {\n throw new McpElicitationError(call.failure)\n }\n if (timedOut) {\n throw new McpElicitationError(mcpToolCallTimeoutMessage(info.toolName))\n }\n throw err\n } finally {\n stop()\n info.signal?.removeEventListener('abort', onOuterAbort)\n if (current === call) {\n current = undefined\n }\n release()\n }\n }\n\n const callModern = async <T>(\n info: McpElicitationCallInfo,\n send: (leg: McpToolCallLeg) => Promise<T>,\n ): Promise<T> => {\n const call = newCall(info, info.signal)\n let retry: McpInputRequiredRetry | undefined\n for (let round = 0; ; round += 1) {\n const result = await send({\n ...(info.signal ? { signal: info.signal } : {}),\n ...(retry ? { retry } : {}),\n })\n if (!isInputRequired(result)) {\n return result\n }\n if (round >= MCP_INPUT_REQUIRED_MAX_ROUNDS) {\n throw new McpElicitationError(mcpInputRequiredRoundsMessage(info.toolName))\n }\n const requests = isPlainObject(result.inputRequests)\n ? Object.entries(result.inputRequests)\n : []\n const state = typeof result.requestState === 'string' ? result.requestState : undefined\n if (requests.length === 0 && state === undefined) {\n throw new McpElicitationError(\n mcpInputRequestUnsupportedMessage(info.toolName, 'an empty input_required result'),\n )\n }\n // Checked before anybody is asked: a round that also wants something this client does\n // not provide (sampling, roots) is not answered in part.\n for (const [, entry] of requests) {\n if (!isPlainObject(entry) || entry.method !== 'elicitation/create') {\n throw new McpElicitationError(\n mcpInputRequestUnsupportedMessage(\n info.toolName,\n isPlainObject(entry) ? entry.method : undefined,\n ),\n )\n }\n }\n // Keys are the server's: a prototype-less object, so none of them can be special.\n const responses = Object.create(null) as Record<string, unknown>\n for (const [key, entry] of requests) {\n const answer = await answerMcpElicitation(\n deps,\n call,\n (entry as Record<string, unknown>).params,\n )\n if (call.failure) {\n // Nobody decided: nothing is sent again.\n throw new McpElicitationError(call.failure)\n }\n responses[key] = answer\n }\n if (requests.length === 0) {\n // Only \"call me again\": do not spin.\n await sleep(MCP_INPUT_REQUIRED_PACING_MS, info.signal)\n }\n retry = {\n ...(requests.length ? { inputResponses: responses } : {}),\n ...(state !== undefined ? { requestState: state } : {}),\n }\n }\n }\n\n return {\n capability: mcpElicitationCapability(deps.options),\n onRequest: async (params) => {\n const call = current\n if (!call) {\n deps.log(\n 'warn',\n `[mcp] ${server}: the server asked the user for input while no tool call was in progress; cancelled`,\n )\n return { action: 'cancel' }\n }\n const failedBefore = call.failure !== undefined\n const answer = await answerMcpElicitation(deps, call, params)\n if (failedBefore) {\n // It was told the call is over and asks again: stop waiting for it.\n call.abort(new McpElicitationError(call.failure as string))\n }\n return answer\n },\n call: (era, info, send) => (era === 'modern' ? callModern(info, send) : callLegacy(info, send)),\n }\n}\n","// 2026-07-28: the `subscriptions/listen` stream that carries a server's tool list change notices,\n// kept open for the life of the connection.\n//\n// That revision has no stream a server may write to unasked: `notifications/tools/list_changed`\n// arrives only on a `subscriptions/listen` stream the client opened, and the SDK does not open it\n// again when it ends. This file does, with backoff, and once a stream is back it reports the tool\n// list as changed - a change made while no stream was open was announced to nobody - through the\n// same callback the notice itself calls, so whoever listens sees exactly what a notice causes.\n//\n// - Retried: a stream that DROPPED (no result: \"an unexpected disconnect, which the client MAY\n// treat as a trigger to reconnect\") and one the server CLOSED with its result (the server's own\n// initiative, \"for example, during shutdown\": on a stateless revision the process that ends a\n// subscription is not the service - the next request may reach another - and a server that no\n// longer takes listeners says so to the next attempt, which is final). A failed attempt is\n// retried too, unless its error is final.\n// - Final, never retried: 401 / 403 (authorization is the OAuth flow's job, not a loop's), 404 /\n// 405 / -32601 (the server does not offer the method), -32602 (it refuses the request as made),\n// a client that is not connected, and an acknowledgement that leaves `toolsListChanged` out.\n// - The delay before attempt n: MCP_LISTEN_RETRY_BASE_MS doubled n - 1 times, at most\n// MCP_LISTEN_RETRY_MAX_MS, less a random share of up to half (so many clients that lost one\n// server do not come back in step). The count goes back to zero only when a stream stayed up\n// MCP_LISTEN_STABLE_MS: a stream that is acknowledged and lost at once counts against it, so a\n// flapping server is tried MCP_LISTEN_MAX_ATTEMPTS times in a row and then given up on.\n// - Logs: one `warn` per end or failed attempt (the attempt and the delay; past the last attempt\n// the same line says it gave up), one `info` when a stream is back. Nothing after `stop()`.\n// - `stop()` takes down a pending retry and the stability timer and gives up an attempt in\n// flight. An acknowledged stream is ended by the connection's own close (no extra request).\n//\n// Pure, no imports: the listen call and the log are given; the timers are `setTimeout`'s, or a\n// test's through the seam below. This file is a COPY, byte for byte, of the sibling package's (Node: `@dudko.dev/agent` `src/mcp-listen.ts`, browser:\n// `@dudko.dev/agent-web` `src/mcp/listen.ts`). Change both; `tests/mcp-listen.test.ts` of the\n// Node package compares them.\n\n/** The first delay: attempt 1 waits at most this long. */\nexport const MCP_LISTEN_RETRY_BASE_MS = 1_000\n/** The longest delay between two attempts. */\nexport const MCP_LISTEN_RETRY_MAX_MS = 60_000\n/** A stream that stayed up this long resets the count: the next loss starts at the first delay. */\nexport const MCP_LISTEN_STABLE_MS = 60_000\n/** Attempts in a row (failed, or lost before they were stable) before this connection gives up. */\nexport const MCP_LISTEN_MAX_ATTEMPTS = 10\n\n/** The SDK's `McpSubscription`, as far as this file reads it. */\nexport interface McpListenSubscription {\n /** The filter the server agreed to (its acknowledgement). */\n readonly honoredFilter: { toolsListChanged?: boolean }\n /** How the stream ended: `local` (this side), `graceful` (the server's result), `remote`. */\n readonly closed: Promise<'local' | 'graceful' | 'remote'>\n}\n\nexport interface McpListenDeps {\n /** The server's name, for the log. */\n server: string\n /** Open one stream; resolves once the server acknowledged it. `signal` gives the attempt up. */\n listen: (signal: AbortSignal) => Promise<McpListenSubscription>\n /** Call `fire` after `ms`; the result takes the timer down. Default: `setTimeout` (or the seam). */\n timer?: (ms: number, fire: () => void) => { cancel: () => void }\n log: (level: 'info' | 'warn', message: string) => void\n /** A stream is open again after one ended or failed: report the tool list as changed. */\n onResubscribed: () => void\n /** The source of the jitter (default `Math.random`). */\n random?: () => number\n}\n\nexport interface McpListenSupervisor {\n /** Open the first stream. Resolves once it was acknowledged, or the attempt failed. */\n start: () => Promise<void>\n /** For good: no retry, no log, nothing pending. Safe to call twice. */\n stop: () => void\n}\n\n/** The delay before attempt `attempt` (1, 2, ...), `random` in [0, 1) taking up to half off. */\nexport const mcpListenRetryDelay = (\n attempt: number,\n random: () => number = Math.random,\n): number => {\n const exponent = Math.max(0, Math.floor(attempt) - 1)\n const full = Math.min(MCP_LISTEN_RETRY_MAX_MS, MCP_LISTEN_RETRY_BASE_MS * 2 ** exponent)\n const drawn = random()\n const share = Number.isFinite(drawn) ? Math.min(1, Math.max(0, drawn)) : 0\n return Math.round(full - (full / 2) * share)\n}\n\n/**\n * Why a failed attempt must not be made again, or `undefined` when it may be. Read structurally:\n * the SDK's `SdkHttpError.status`, `ProtocolError.code` (a number), `SdkError.code` (a string),\n * `UnauthorizedError`'s name - a second copy of the SDK is another class.\n */\nexport const mcpListenFinalReason = (err: unknown): string | undefined => {\n if (typeof err !== 'object' || err === null) return undefined\n const { name, status, code } = err as { name?: unknown; status?: unknown; code?: unknown }\n if (name === 'UnauthorizedError' || status === 401 || status === 403) {\n return 'the server refused the authorization'\n }\n if (\n status === 404 ||\n status === 405 ||\n code === -32601 ||\n code === 'METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION'\n ) {\n return 'the server does not offer subscriptions/listen'\n }\n if (code === -32602) return 'the server refused the request'\n if (code === 'NOT_CONNECTED') return 'the connection is closed'\n return undefined\n}\n\n/** Where the timers are set: the globals, looked up at each call (so mocked timers apply). */\ninterface McpListenTimeSource {\n set: (fire: () => void, ms: number) => unknown\n clear: (handle: unknown) => void\n}\n\nconst REAL_TIME: McpListenTimeSource = {\n set: (fire, ms) => setTimeout(fire, ms),\n clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),\n}\n\n/**\n * A TEST seam, not an API: a test that puts a time source under this key of `globalThis` before\n * a connection is made moves this file's timers itself - the retry and the stability timer - so\n * the whole schedule runs on virtual time against real servers. A key of its own, not the wait\n * clock's (`wait-clock.ts`): that one is for the deadlines of runs, and its tests ask whether any\n * deadline is running, which a listen timer is not. Nothing exports it; it gives no power the\n * globals it stands for do not.\n */\nconst TEST_TIME = Symbol.for('@dudko.dev/agent:mcp-listen-test-time')\n\nconst timeSource = (): McpListenTimeSource => {\n const test = (globalThis as unknown as Record<symbol, Partial<McpListenTimeSource> | undefined>)[\n TEST_TIME\n ]\n return typeof test?.set === 'function' && typeof test.clear === 'function'\n ? (test as McpListenTimeSource)\n : REAL_TIME\n}\n\nconst seconds = (ms: number): string => `${(ms / 1000).toFixed(1)} s`\n\nconst messageOf = (err: unknown): string => (err instanceof Error ? err.message : String(err))\n\nexport const createMcpListenSupervisor = (deps: McpListenDeps): McpListenSupervisor => {\n const { server, log } = deps\n const random = deps.random ?? Math.random\n // Read when the supervisor is made, as the wait clock reads its own seam.\n const time = timeSource()\n const timer =\n deps.timer ??\n ((ms: number, fire: () => void) => {\n const handle = time.set(fire, ms)\n return { cancel: () => time.clear(handle) }\n })\n let started = false\n let stopped = false\n // Attempts since the start, or since the last stream that stayed up MCP_LISTEN_STABLE_MS.\n let attempts = 0\n let retry: { cancel: () => void } | undefined\n let stable: { cancel: () => void } | undefined\n let inFlight: AbortController | undefined\n let current: McpListenSubscription | undefined\n\n // A stream ended or an attempt failed (`what` says which): the next attempt, or the end.\n const again = (what: string): void => {\n if (attempts >= MCP_LISTEN_MAX_ATTEMPTS) {\n log(\n 'warn',\n `[mcp] ${server}: ${what}; gave up after ${attempts} attempts in a row - tool list changes are not announced until the server is connected again (refreshServer still re-lists)`,\n )\n return\n }\n attempts += 1\n const delay = mcpListenRetryDelay(attempts, random)\n log(\n 'warn',\n `[mcp] ${server}: ${what}; listening again in ${seconds(delay)} (attempt ${attempts} of ${MCP_LISTEN_MAX_ATTEMPTS})`,\n )\n retry = timer(delay, () => {\n retry = undefined\n void open(true)\n })\n }\n\n const ended = (subscription: McpListenSubscription, cause: string): void => {\n if (stopped || current !== subscription) return\n current = undefined\n stable?.cancel()\n stable = undefined\n // Only this side closes a stream locally, and only when it is done with it.\n if (cause === 'local') return\n again(\n `the tool list change stream ended (${cause === 'graceful' ? 'closed by the server' : 'dropped'})`,\n )\n }\n\n const open = async (resubscribe: boolean): Promise<void> => {\n if (stopped) return\n const attempt = new AbortController()\n inFlight = attempt\n let subscription: McpListenSubscription\n try {\n subscription = await deps.listen(attempt.signal)\n } catch (err) {\n if (inFlight === attempt) inFlight = undefined\n if (stopped) return\n const final = mcpListenFinalReason(err)\n if (final) {\n log(\n 'warn',\n `[mcp] ${server}: could not subscribe to tool list changes - ${messageOf(err)}; not tried again: ${final}`,\n )\n return\n }\n again(`could not subscribe to tool list changes - ${messageOf(err)}`)\n return\n }\n if (inFlight === attempt) inFlight = undefined\n // Stopped while the acknowledgement was on its way: `stop()` already gave the attempt up.\n if (stopped) return\n if (subscription.honoredFilter?.toolsListChanged !== true) {\n log('info', `[mcp] ${server}: the server did not agree to announce tool list changes`)\n attempt.abort()\n return\n }\n current = subscription\n stable = timer(MCP_LISTEN_STABLE_MS, () => {\n stable = undefined\n attempts = 0\n })\n subscription.closed.then(\n (cause) => ended(subscription, cause),\n () => ended(subscription, 'remote'),\n )\n if (resubscribe) {\n log(\n 'info',\n `[mcp] ${server}: listening for tool list changes again (attempt ${attempts}); the tool list is read again`,\n )\n try {\n deps.onResubscribed()\n } catch (err) {\n log('warn', `[mcp] ${server}: the tool list change callback failed - ${messageOf(err)}`)\n }\n }\n }\n\n return {\n start: async () => {\n if (started || stopped) return\n started = true\n await open(false)\n },\n stop: () => {\n stopped = true\n retry?.cancel()\n retry = undefined\n stable?.cancel()\n stable = undefined\n inFlight?.abort()\n inFlight = undefined\n current = undefined\n },\n }\n}\n","import {\n auth,\n type FetchLike,\n type OAuthClientInformationMixed,\n type OAuthClientMetadata,\n type OAuthClientProvider,\n type OAuthDiscoveryState,\n type OAuthTokens,\n} from '@modelcontextprotocol/client'\nimport { IndexedDBVault, type VaultOptions } from '../secrets/vault.js'\n\n/**\n * Browser-side OAuth 2.1 for remote MCP servers: Dynamic Client Registration\n * (RFC 7591) or a client ID metadata document (CIMD) - automatically or one of\n * them only (`registration`) - PKCE authorization-code flow, refresh-token\n * rotation, and the `iss` check on the way back (RFC 9207).\n *\n * The heavy lifting lives in the MCP SDK — `auth()` discovers the protected\n * resource (RFC 9728), registers the client if we have no client_id yet,\n * exchanges the code, and refreshes expired tokens; `StreamableHTTPClient-\n * Transport` retries any 401 through it. This module supplies the missing\n * half: WHERE the tokens, the registration, and the PKCE verifier are kept,\n * and HOW the user is sent to the authorization server.\n *\n * ── WHY NO AUTOMATIC NAVIGATION ──\n * `redirectToAuthorization` deliberately does NOT navigate by default. The SDK\n * can call it from deep inside a tool call, and throwing the user out of a\n * running agent would discard in-flight state. Instead the URL is recorded on\n * `authorizationUrl`, `connectMcpHttp` reports `needsAuthorization: true`, and\n * the app decides when to send the user there (a button, a popup, a redirect).\n * Pass `onRedirect` to opt into eager navigation.\n */\n\n/** Where an OAuth provider keeps its tokens / registration / PKCE verifier. */\nexport interface McpOAuthStorage {\n get(key: string): Promise<string | undefined>\n set(key: string, value: string): Promise<void>\n delete(key: string): Promise<void>\n}\n\n/**\n * Default storage: the same encrypted IndexedDB vault that holds provider API\n * keys (AES-GCM, non-extractable key). Read the threat model in\n * `secrets/vault.ts` — this protects tokens at rest, not against active XSS.\n */\nexport class VaultOAuthStorage implements McpOAuthStorage {\n private readonly vault: IndexedDBVault\n\n constructor(opts: VaultOptions = {}) {\n this.vault = new IndexedDBVault(opts)\n }\n\n get(key: string): Promise<string | undefined> {\n return this.vault.getSecret(key)\n }\n set(key: string, value: string): Promise<void> {\n return this.vault.setSecret(key, value)\n }\n delete(key: string): Promise<void> {\n return this.vault.deleteSecret(key)\n }\n}\n\n/** Non-persistent storage for tests / SSR. Tokens die with the tab. */\nexport class MemoryOAuthStorage implements McpOAuthStorage {\n private readonly map = new Map<string, string>()\n\n async get(key: string): Promise<string | undefined> {\n return this.map.get(key)\n }\n async set(key: string, value: string): Promise<void> {\n this.map.set(key, value)\n }\n async delete(key: string): Promise<void> {\n this.map.delete(key)\n }\n}\n\n/**\n * How the OAuth client is registered with a server's authorization server\n * (`BrowserOAuthProviderOptions.registration`):\n *\n * - `'auto'` (the default): by the client ID metadata document (CIMD) when the\n * authorization server advertises `client_id_metadata_document_supported` and\n * a `clientMetadataUrl` is set, by dynamic client registration (DCR, RFC 7591)\n * otherwise. A client already in storage is used as it is.\n * - `'cimd'`: by the metadata document only. Needs `clientMetadataUrl`. An\n * authorization server that does not advertise support is refused before\n * anything is sent to its registration endpoint.\n * - `'dcr'`: by dynamic registration only, even with a `clientMetadataUrl` set:\n * the SDK is never shown the URL.\n *\n * The Node package has the same option, with the same names; change both.\n */\nexport type McpOAuthRegistration = 'auto' | 'cimd' | 'dcr'\n\n/** How a stored client was registered: see {@link BrowserOAuthProvider.registrationKind}. */\nexport type McpOAuthRegistrationKind = 'cimd' | 'dcr'\n\nexport interface BrowserOAuthProviderOptions {\n /** The MCP endpoint this provider authorizes against (the resource server). */\n serverUrl: string\n /**\n * Where the authorization server sends the user back. Must be a page of your\n * app that calls `readOAuthCallback()` + `finishMcpOAuth()`. Registered with\n * the AS via DCR, so it has to match byte-for-byte on the way back.\n */\n redirectUrl: string | URL\n /** `client_name` submitted during dynamic registration. */\n clientName?: string\n /** Fallback scope when the server's metadata advertises none. */\n scope?: string\n /** Merged over the defaults; use it for `software_id`, `contacts`, `application_type`, … */\n clientMetadata?: Partial<OAuthClientMetadata> & { application_type?: string }\n /**\n * URL of a client ID metadata document (CIMD) you host. When the\n * authorization server advertises `client_id_metadata_document_supported`,\n * this URL is used as the `client_id` and no dynamic registration is made;\n * otherwise registration runs as before. A registration already in storage\n * wins over both. Must be https with a non-root path, and the document served\n * there must list the same `redirect_uris` as `redirectUrl`. With\n * `registration: 'dcr'` it is never used as the `client_id`.\n */\n clientMetadataUrl?: string\n /**\n * How the client is registered: `'auto'` (default; as described for\n * `clientMetadataUrl`), `'cimd'` (the metadata document only: needs\n * `clientMetadataUrl`, and an authorization server without support is refused\n * before any registration request) or `'dcr'` (dynamic registration only).\n * A stored client of the other kind is not reused: it is forgotten, with the\n * tokens issued to it, and the user signs in again. See\n * {@link McpOAuthRegistration}.\n */\n registration?: McpOAuthRegistration\n /** Defaults to the encrypted IndexedDB vault. */\n storage?: McpOAuthStorage\n /** Treat an access token as expired this many seconds early. Default 30. */\n expirySkewSeconds?: number\n /** Called when the SDK wants the user at the authorization server. */\n onRedirect?: (url: URL) => void | Promise<void>\n}\n\ninterface StoredTokens {\n tokens: OAuthTokens\n /** Absolute ms timestamp derived from `expires_in` at save time. */\n expiresAt?: number\n}\n\nconst DEFAULT_SKEW_SECONDS = 30\n\n// Namespacing by origin+path+query keeps two MCP servers on the same host\n// (/mcp/docs vs /mcp/crm, or ?tenant=a vs ?tenant=b) from sharing a\n// registration or a token — one tenant's bearer must never be sent to another.\nconst namespaceFor = (serverUrl: string): string => {\n const u = new URL(serverUrl)\n return `mcp-oauth:${u.origin}${u.pathname.replace(/\\/+$/, '')}${u.search}`\n}\n\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1'])\n\n/**\n * OAuth over plaintext hands the bearer token to anyone on the path, so only\n * https — or a loopback host, where there is no network to sniff — is allowed.\n * Parsed rather than pattern-matched: `http://localhost.attacker.example/` is a\n * registrable host that a prefix match would wave through.\n */\nexport const assertSecureOAuthUrl = (url: string, label = 'MCP server'): void => {\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n throw new Error(`${label}: \"${url}\" is not a valid URL`)\n }\n if (parsed.protocol === 'https:' || LOOPBACK_HOSTS.has(parsed.hostname)) return\n throw new Error(\n `${label}: MCP OAuth requires https (or a loopback host) - refusing to send tokens to \"${url}\"`,\n )\n}\n\n/**\n * A client ID metadata document URL is used as the `client_id`, and the\n * authorization server fetches it: it has to be https with a path of its own\n * (a bare origin identifies a site, not a client). Checked when the provider is\n * built, so a bad value fails at start-up and not in the middle of a flow.\n */\nconst assertClientMetadataUrl = (url: string, label = 'MCP OAuth'): void => {\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n throw new Error(`${label}: clientMetadataUrl \"${url}\" is not a valid URL`)\n }\n if (parsed.protocol === 'https:' && parsed.pathname !== '/') return\n throw new Error(\n `${label}: clientMetadataUrl requires https and a non-root path - refusing \"${url}\"`,\n )\n}\n\nconst REGISTRATIONS: readonly McpOAuthRegistration[] = ['auto', 'cimd', 'dcr']\n\n/**\n * `registration` is checked when the provider is built: an unknown value would\n * otherwise read as \"auto\", and `'cimd'` without a document has nothing to sign\n * in with. The Node package carries the same function; change both.\n */\nconst resolveRegistration = (\n registration: unknown,\n clientMetadataUrl: string | undefined,\n label = 'MCP OAuth',\n): McpOAuthRegistration => {\n if (registration === undefined) return 'auto'\n if (!REGISTRATIONS.includes(registration as McpOAuthRegistration)) {\n throw new Error(\n `${label}: registration must be 'auto', 'cimd' or 'dcr' - refusing \"${String(registration)}\"`,\n )\n }\n if (registration === 'cimd' && clientMetadataUrl === undefined) {\n throw new Error(\n `${label}: registration 'cimd' needs a clientMetadataUrl - the client ID metadata document to sign in with`,\n )\n }\n return registration as McpOAuthRegistration\n}\n\n// How a client was registered is stamped on its stored record under this key,\n// when it is saved (the URL it was registered under is known then, and may be\n// configured differently later), and taken off again before the record reaches\n// the SDK: nothing of it is ever sent.\nconst KIND_KEY = 'x-agent-registration'\n\n/**\n * RFC 9207: is the `iss` parameter of an authorization response the\n * authorization server this flow was started with? Throws when it is not; the\n * caller must not exchange the code then (a mix-up attack hands the code of an\n * honest server to another one's token endpoint).\n *\n * - expected issuer: the `issuer` of the stored authorization server metadata,\n * else the authorization server URL discovery used;\n * - `iss` present: it must equal the expected issuer, compared as plain strings\n * (RFC 9207 section 2.4: no normalization);\n * - `iss` absent: refused when the metadata says\n * `authorization_response_iss_parameter_supported: true`;\n * - no stored discovery state (storage written by an older version): `iss` is\n * compared with the issuer stamped on the stored client information, and with\n * nothing to compare against the response is accepted. ({@link finishMcpOAuth}\n * does not exchange a code in that case: see there.)\n *\n * The Node package carries the same function; change both.\n */\nexport const checkAuthorizationResponseIssuer = (\n iss: string | undefined,\n discoveryState: OAuthDiscoveryState | undefined,\n clientIssuer?: string,\n): void => {\n // Read as it is stored, not through the SDK's type: only a literal `true` is\n // a promise (the SDK's schema keeps the flag for both metadata documents and\n // turns anything that is not a boolean into \"absent\").\n const metadata = discoveryState?.authorizationServerMetadata as\n { issuer?: string; authorization_response_iss_parameter_supported?: unknown } | undefined\n const expected = discoveryState\n ? (metadata?.issuer ?? String(discoveryState.authorizationServerUrl))\n : clientIssuer\n if (iss === undefined) {\n if (metadata?.authorization_response_iss_parameter_supported === true) {\n throw new Error(\n 'Authorization response carried no \"iss\", which this authorization server says it always sends; refusing to exchange the code (possible mix-up attack)',\n )\n }\n return\n }\n if (expected !== undefined && iss !== expected) {\n throw new Error(\n `Authorization response came from issuer \"${iss}\", expected \"${expected}\"; refusing to exchange the code (possible mix-up attack)`,\n )\n }\n}\n\nconst randomToken = (): string => {\n const bytes = new Uint8Array(32)\n globalThis.crypto.getRandomValues(bytes)\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * `application_type` for dynamic registration, read off the redirect URL: a\n * loopback address or a private-use scheme is how a native client is called\n * back, an https page is a web client. Said explicitly because a server that\n * tells the two apart assumes \"web\" when the field is absent, and then refuses\n * a loopback redirect - and one that is told \"native\" refuses an https one.\n * The browser and the Node package carry the same function; change both.\n */\nconst applicationTypeFor = (redirectUrl: string): 'native' | 'web' => {\n try {\n const u = new URL(redirectUrl)\n return u.protocol === 'https:' && !LOOPBACK_HOSTS.has(u.hostname) ? 'web' : 'native'\n } catch {\n return 'native'\n }\n}\n\n/**\n * An `OAuthClientProvider` (MCP SDK) that persists everything it is handed and\n * never navigates behind your back. One instance per MCP server.\n */\nexport class BrowserOAuthProvider implements OAuthClientProvider {\n /** Set when the SDK asks for an authorization redirect; read it in your UI. */\n authorizationUrl?: URL\n\n readonly serverUrl: string\n\n private readonly storage: McpOAuthStorage\n private readonly ns: string\n private readonly _redirectUrl: string\n private readonly _clientMetadata: OAuthClientMetadata\n private readonly _clientMetadataUrl?: string\n private readonly _registration: McpOAuthRegistration\n private readonly skewMs: number\n private readonly onRedirect?: (url: URL) => void | Promise<void>\n /** Once per provider: a stored client of the other kind is forgotten (see `settle`). */\n private settled?: Promise<void>\n\n constructor(opts: BrowserOAuthProviderOptions) {\n assertSecureOAuthUrl(opts.serverUrl)\n if (opts.clientMetadataUrl !== undefined) {\n assertClientMetadataUrl(opts.clientMetadataUrl)\n this._clientMetadataUrl = opts.clientMetadataUrl\n }\n this._registration = resolveRegistration(opts.registration, opts.clientMetadataUrl)\n this.serverUrl = opts.serverUrl\n this.storage = opts.storage ?? new VaultOAuthStorage()\n this.ns = namespaceFor(opts.serverUrl)\n this._redirectUrl = String(opts.redirectUrl)\n this.skewMs = (opts.expirySkewSeconds ?? DEFAULT_SKEW_SECONDS) * 1000\n this.onRedirect = opts.onRedirect\n this._clientMetadata = {\n client_name: opts.clientName ?? 'agent-web',\n redirect_uris: [this._redirectUrl],\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n // Public client: a browser cannot hold a client_secret. PKCE is what\n // actually protects the code exchange.\n token_endpoint_auth_method: 'none',\n // By the redirect: an https page is 'web', a loopback one (local dev) is 'native'.\n application_type: applicationTypeFor(this._redirectUrl),\n ...(opts.scope ? { scope: opts.scope } : {}),\n ...opts.clientMetadata,\n } as OAuthClientMetadata\n }\n\n get redirectUrl(): string {\n return this._redirectUrl\n }\n\n get clientMetadata(): OAuthClientMetadata {\n return this._clientMetadata\n }\n\n /**\n * The client ID metadata document URL (CIMD), when one was configured - and\n * not with `registration: 'dcr'`: the SDK uses this getter to decide, so a\n * URL it cannot see is a URL it never uses as the `client_id`.\n */\n get clientMetadataUrl(): string | undefined {\n return this._registration === 'dcr' ? undefined : this._clientMetadataUrl\n }\n\n /** How this provider registers its client: `'auto'`, `'cimd'` or `'dcr'`. */\n get registration(): McpOAuthRegistration {\n return this._registration\n }\n\n private key(suffix: string): string {\n return `${this.ns}:${suffix}`\n }\n\n private async readJSON<T>(suffix: string): Promise<T | undefined> {\n // The read itself is inside the guard on purpose: the default storage\n // decrypts, and an AES-GCM blob written under a key that no longer exists\n // (a partially cleared IndexedDB, a rotated vault key) throws. Treating\n // that as \"no value\" lets the flow re-authorize instead of every call\n // rejecting with an opaque OperationError forever.\n try {\n const raw = await this.storage.get(this.key(suffix))\n if (raw === undefined) return undefined\n return JSON.parse(raw) as T\n } catch {\n await this.storage.delete(this.key(suffix)).catch(() => {})\n return undefined\n }\n }\n\n async state(): Promise<string> {\n const value = randomToken()\n await this.storage.set(this.key('state'), value)\n return value\n }\n\n /**\n * CSRF check for the redirect back. Single-use: the stored value is dropped\n * whether or not it matched, so a replayed callback can't pass twice.\n */\n async verifyState(returned: string | undefined): Promise<boolean> {\n const expected = await this.storage.get(this.key('state'))\n await this.storage.delete(this.key('state'))\n return expected !== undefined && returned !== undefined && expected === returned\n }\n\n /** The stored client, without our stamp, and how it was registered. */\n private async readClient(): Promise<\n { info: OAuthClientInformationMixed; kind: McpOAuthRegistrationKind } | undefined\n > {\n const stored = await this.readJSON<Record<string, unknown>>('client')\n if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return undefined\n const info: Record<string, unknown> = { ...stored }\n const stamp = info[KIND_KEY]\n delete info[KIND_KEY]\n // A record saved before the stamp existed: CIMD when its client_id is the\n // document configured now.\n const kind = stamp === 'cimd' || stamp === 'dcr' ? stamp : this.kindOf(info.client_id)\n return { info: info as unknown as OAuthClientInformationMixed, kind }\n }\n\n private kindOf(clientId: unknown): McpOAuthRegistrationKind {\n return this._clientMetadataUrl !== undefined && clientId === this._clientMetadataUrl\n ? 'cimd'\n : 'dcr'\n }\n\n /**\n * May this provider use the stored client? Under `'auto'` any; under `'cimd'`\n * only the configured document itself; under `'dcr'` only one that was not\n * registered by a document.\n */\n private fits(client: { info: OAuthClientInformationMixed; kind: McpOAuthRegistrationKind }) {\n if (this._registration === 'cimd') {\n return client.kind === 'cimd' && client.info.client_id === this._clientMetadataUrl\n }\n if (this._registration === 'dcr') return client.kind === 'dcr'\n return true\n }\n\n /** The client and the tokens issued to it go together: a token belongs to a client. */\n private async forgetClient(): Promise<void> {\n await Promise.all(['client', 'tokens'].map((t) => this.storage.delete(this.key(t))))\n }\n\n /**\n * Under `'cimd'` / `'dcr'`, before the first read of the client or a token: a\n * stored client of the other kind (registered under another setting) is\n * forgotten with its tokens, so the setting is never served by the old\n * client - not even by its access token, which the transport would otherwise\n * keep sending until it expires. Once per provider (its setting is fixed); a\n * failure is not remembered.\n */\n private settle(): Promise<void> {\n if (this._registration === 'auto') return Promise.resolve()\n this.settled ??= (async () => {\n const client = await this.readClient()\n if (client && !this.fits(client)) await this.forgetClient()\n })().catch((err: unknown) => {\n this.settled = undefined\n throw err\n })\n return this.settled\n }\n\n /**\n * `'cimd'` with no usable client: the SDK is about to choose between the\n * document and a dynamic registration, by the authorization server metadata\n * it has just saved (`saveDiscoveryState` comes first). Without support it\n * would register - so it is stopped HERE, before any request is made, and\n * what discovery found is forgotten, so the next attempt reads the server's\n * metadata again (a server that starts supporting CIMD is noticed).\n */\n private async assertCimdSupported(): Promise<void> {\n const discovery = await this.discoveryState()\n const metadata = discovery?.authorizationServerMetadata as\n { issuer?: unknown; client_id_metadata_document_supported?: unknown } | undefined\n // Only a literal `true` is a promise, as the SDK reads it.\n if (metadata?.client_id_metadata_document_supported === true) return\n await this.storage.delete(this.key('discovery')).catch(() => {})\n const server =\n typeof metadata?.issuer === 'string' ? metadata.issuer : discovery?.authorizationServerUrl\n throw new Error(\n server\n ? `MCP OAuth: the authorization server ${server} of ${this.serverUrl} does not support client ID metadata documents (CIMD), which this connection requires (registration: 'cimd') - nothing was sent to its registration endpoint`\n : `MCP OAuth: no record of the authorization server of ${this.serverUrl}, so its support for client ID metadata documents (CIMD), which this connection requires (registration: 'cimd'), cannot be confirmed - nothing was registered`,\n )\n }\n\n async clientInformation(): Promise<OAuthClientInformationMixed | undefined> {\n await this.settle()\n const client = await this.readClient()\n if (client && this.fits(client)) return client.info\n // Written by a provider with another setting since this one settled.\n if (client) await this.forgetClient()\n if (this._registration === 'cimd') await this.assertCimdSupported()\n return undefined\n }\n\n async saveClientInformation(info: OAuthClientInformationMixed): Promise<void> {\n // Whatever arrived under our key (a registration response is the server's\n // text) is replaced by what this provider knows: a client whose ID is the\n // configured document is CIMD, any other was registered dynamically.\n const record: Record<string, unknown> = { ...info }\n record[KIND_KEY] = this.kindOf(info.client_id)\n await this.storage.set(this.key('client'), JSON.stringify(record))\n }\n\n /**\n * How the stored client was registered: `'cimd'` (its `client_id` is the\n * client ID metadata document), `'dcr'` (registered dynamically - or saved by\n * the host), or undefined when there is none this provider would use. Read it\n * after a sign-in to show the user which way was taken.\n */\n async registrationKind(): Promise<McpOAuthRegistrationKind | undefined> {\n await this.settle()\n const client = await this.readClient()\n return client && this.fits(client) ? client.kind : undefined\n }\n\n async tokens(): Promise<OAuthTokens | undefined> {\n await this.settle()\n return (await this.readJSON<StoredTokens>('tokens'))?.tokens\n }\n\n async saveTokens(tokens: OAuthTokens): Promise<void> {\n const stored: StoredTokens = {\n tokens,\n expiresAt:\n typeof tokens.expires_in === 'number' ? Date.now() + tokens.expires_in * 1000 : undefined,\n }\n await this.storage.set(this.key('tokens'), JSON.stringify(stored))\n }\n\n async saveCodeVerifier(verifier: string): Promise<void> {\n await this.storage.set(this.key('verifier'), verifier)\n }\n\n async codeVerifier(): Promise<string> {\n const v = await this.storage.get(this.key('verifier'))\n if (!v) {\n throw new Error(\n 'No PKCE code verifier stored: the authorization was started in a different browser profile, or storage was cleared mid-flow',\n )\n }\n return v\n }\n\n /**\n * What discovery found (the authorization server, its metadata, the resource\n * metadata). The SDK reuses it instead of discovering again - after the\n * redirect back too - and {@link finishMcpOAuth} reads the expected issuer\n * from it.\n */\n async saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {\n await this.storage.set(this.key('discovery'), JSON.stringify(state))\n }\n\n async discoveryState(): Promise<OAuthDiscoveryState | undefined> {\n const state = await this.readJSON<OAuthDiscoveryState>('discovery')\n if (!state || typeof state !== 'object' || typeof state.authorizationServerUrl !== 'string') {\n return undefined\n }\n return state\n }\n\n async redirectToAuthorization(url: URL): Promise<void> {\n this.authorizationUrl = url\n await this.onRedirect?.(url)\n }\n\n /**\n * Called by the SDK when the server rejects what we hold: `'tokens'` after an\n * `invalid_grant` (dead refresh token); `'client'` and then `'tokens'` after\n * an `invalid_client` (the AS forgot our dynamic registration) - what\n * discovery found is kept on purpose, the SDK checks the next callback\n * against it. `'verifier'` and `'discovery'` are in its type and handled the\n * same way: one key each. `'all'` is what {@link reset} asks for. Clearing\n * lets the SDK re-register and re-authorize without the user clearing site\n * data.\n */\n async invalidateCredentials(\n scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery',\n ): Promise<void> {\n const targets =\n scope === 'all' ? ['tokens', 'client', 'verifier', 'state', 'discovery'] : [scope]\n await Promise.all(targets.map((t) => this.storage.delete(this.key(t))))\n }\n\n /** True when there is no access token, or it expires within the skew window. */\n async isAccessTokenExpired(): Promise<boolean> {\n await this.settle()\n const stored = await this.readJSON<StoredTokens>('tokens')\n if (!stored?.tokens?.access_token) return true\n // No expires_in means the AS didn't say; assume it is still good and let a\n // 401 drive the refresh.\n if (stored.expiresAt === undefined) return false\n return Date.now() + this.skewMs >= stored.expiresAt\n }\n\n /** True once an authorization has completed for this server. */\n async isAuthorized(): Promise<boolean> {\n return (await this.tokens()) !== undefined\n }\n\n /** Forget tokens, registration, verifier, state and discovery for this server. */\n async reset(): Promise<void> {\n this.authorizationUrl = undefined\n await this.invalidateCredentials('all')\n }\n}\n\nexport interface McpOAuthRequestOptions {\n /**\n * Custom fetch for the discovery / registration / token requests. Pass the\n * same one you give the connector so a proxy or an instrumentation wrapper\n * covers the OAuth traffic too.\n */\n fetch?: FetchLike\n}\n\nexport interface McpOAuthCallback {\n code?: string\n state?: string\n /** The `iss` parameter of the response (RFC 9207), when the server sent one. */\n iss?: string\n error?: string\n errorDescription?: string\n}\n\n/**\n * Pull the authorization-code parameters out of a redirect URL. Reads the query\n * string and, for hash-routed apps, the fragment. Returns undefined when the\n * URL carries neither a `code` nor an `error`, so it is safe to call on every\n * page load.\n */\nexport const readOAuthCallback = (input?: string | URL): McpOAuthCallback | undefined => {\n const href = input\n ? String(input)\n : typeof globalThis.location !== 'undefined'\n ? globalThis.location.href\n : undefined\n if (!href) return undefined\n let url: URL\n try {\n url = new URL(href)\n } catch {\n return undefined\n }\n const params = new URLSearchParams(url.search)\n const hash = url.hash.startsWith('#') ? url.hash.slice(1) : url.hash\n // Hash-routed apps get \"#/callback?code=…\"; take whatever follows the \"?\".\n const q = hash.indexOf('?')\n if (q >= 0) {\n for (const [k, v] of new URLSearchParams(hash.slice(q + 1))) {\n if (!params.has(k)) params.set(k, v)\n }\n }\n const code = params.get('code') ?? undefined\n const error = params.get('error') ?? undefined\n if (!code && !error) return undefined\n return {\n code,\n state: params.get('state') ?? undefined,\n iss: params.get('iss') ?? undefined,\n error,\n errorDescription: params.get('error_description') ?? undefined,\n }\n}\n\n/**\n * Finish the flow after the authorization server redirected back: verify the\n * `state`, then the issuer (RFC 9207, {@link checkAuthorizationResponseIssuer}),\n * exchange the code (PKCE) and persist the tokens. Throws when the AS returned\n * an error, when `state` doesn't match what we issued, when `iss` names another\n * authorization server, or when the exchange fails — never resolves on a\n * half-finished authorization.\n *\n * A flow whose discovery state is not in storage any more (started by a\n * version that did not keep it, or cleared in between) is not completed: the\n * code is bound to the authorization server the user was sent to, and without\n * the record of which one that was the SDK refuses the exchange. Start again\n * with {@link beginMcpOAuth}; stored tokens are not touched.\n */\nexport const finishMcpOAuth = async (\n provider: BrowserOAuthProvider,\n callback: McpOAuthCallback,\n opts: McpOAuthRequestOptions = {},\n): Promise<void> => {\n if (callback.error) {\n throw new Error(\n `Authorization denied by the server: ${callback.error}${\n callback.errorDescription ? ` - ${callback.errorDescription}` : ''\n }`,\n )\n }\n if (!callback.code) {\n throw new Error('Authorization callback carried no code')\n }\n if (!(await provider.verifyState(callback.state))) {\n throw new Error('Authorization state mismatch; refusing to exchange the code (possible CSRF)')\n }\n // Before the exchange: a code that came from another authorization server\n // must never reach this one's token endpoint.\n const discovery = await provider.discoveryState()\n checkAuthorizationResponseIssuer(\n callback.iss,\n discovery,\n (await provider.clientInformation())?.issuer,\n )\n if (!discovery) {\n // The SDK's own gate, said in our words: it throws on this inside `auth()`.\n throw new Error(\n 'Authorization cannot be completed: the record of which authorization server it was started with is not in the store (started by an older version, or cleared in between); start the authorization again',\n )\n }\n const result = await auth(provider, {\n serverUrl: provider.serverUrl,\n authorizationCode: callback.code,\n // The SDK runs its own RFC 9207 check inside `auth()`, after ours: without\n // the value it would read a response that carried `iss` as one that did not.\n iss: callback.iss,\n fetchFn: opts.fetch,\n })\n if (result !== 'AUTHORIZED') {\n throw new Error(`Token exchange did not complete (SDK returned \"${result}\")`)\n }\n}\n\n/**\n * Kick off (or silently renew) an authorization. Returns `'AUTHORIZED'` when a\n * usable token is in hand — including the case where a refresh token was\n * silently exchanged — or `'REDIRECT'` when the user has to visit\n * `provider.authorizationUrl`.\n */\nexport const beginMcpOAuth = async (\n provider: BrowserOAuthProvider,\n opts: McpOAuthRequestOptions = {},\n): Promise<'AUTHORIZED' | 'REDIRECT'> => {\n provider.authorizationUrl = undefined\n return auth(provider, { serverUrl: provider.serverUrl, fetchFn: opts.fetch })\n}\n","export { connectMcpHttp, diagnoseMcpCors, flattenContent } from './http.js'\n// Re-exported so a host that only depends on this package can identify an\n// authorization failure: `err instanceof UnauthorizedError`. The 2.x SDK's\n// class is branded, so the check also holds for an error made by ANOTHER copy\n// of the SDK (two bundles, or the ESM and the CJS build on one page), and it\n// sets `name` to 'UnauthorizedError' (the 1.x class did neither).\nexport { UnauthorizedError } from '@modelcontextprotocol/client'\nexport {\n MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER,\n MCP_INSTRUCTIONS_MAX_CHARS_TOTAL,\n MCP_MODERN_PROTOCOL_VERSION,\n MCP_MODERN_REQUEST_HEADERS,\n renderMcpInstructions,\n} from './shared.js'\nexport type { McpProtocolMode, McpServerInstructions, McpServerProtocol } from './shared.js'\nexport {\n MCP_ELICITATION_MAX_PER_RUN,\n MCP_ELICITATION_MAX_PER_TOOL_CALL,\n MCP_ELICITATION_TIMEOUT_MS,\n normalizeMcpElicitationSchema,\n validateMcpElicitationContent,\n} from './elicitation.js'\nexport type {\n McpElicitationContent,\n McpElicitationContext,\n McpElicitationFieldSchema,\n McpElicitationHandler,\n McpElicitationOptions,\n McpElicitationReason,\n McpElicitationRequest,\n McpElicitationResult,\n McpElicitationSchema,\n} from './elicitation.js'\nexport type {\n McpHttpServerConfig,\n McpCatalogEntry,\n McpServerResult,\n ConnectedMcp,\n ConnectMcpOptions,\n McpAppsConnection,\n McpAppTool,\n} from './http.js'\nexport {\n MCP_APP_DEFAULT_VISIBILITY,\n MCP_APP_MAX_DOMAINS,\n MCP_APP_MAX_DOWNLOAD_BYTES,\n MCP_APP_MAX_HTML_CHARS,\n MCP_APP_MAX_RESULT_CHARS,\n MCP_APP_MIME_TYPE,\n MCP_APPS_EXTENSION,\n McpAppResourceError,\n isMcpAppMimeType,\n isMcpAppUri,\n mcpAppCspOf,\n mcpAppDownloadOf,\n mcpAppOrigin,\n mcpAppPermissionsOf,\n mcpAppResourceOf,\n mcpAppToolMeta,\n mcpAppToolResultOf,\n mcpAppsModeOf,\n} from './apps.js'\nexport type {\n McpAppCsp,\n McpAppDownloadResource,\n McpAppPermissions,\n McpAppResource,\n McpAppToolMeta,\n McpAppToolResult,\n McpAppVisibility,\n McpAppsMode,\n} from './apps.js'\nexport {\n BrowserOAuthProvider,\n MemoryOAuthStorage,\n VaultOAuthStorage,\n beginMcpOAuth,\n checkAuthorizationResponseIssuer,\n finishMcpOAuth,\n readOAuthCallback,\n} from './oauth.js'\nexport type {\n BrowserOAuthProviderOptions,\n McpOAuthCallback,\n McpOAuthRegistration,\n McpOAuthRegistrationKind,\n McpOAuthRequestOptions,\n McpOAuthStorage,\n} from './oauth.js'\nexport {\n BrowserEnterpriseOAuthProvider,\n createEnterpriseOAuthProvider,\n ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION,\n EnterpriseOAuthError,\n} from './enterprise-oauth.js'\nexport type {\n EnterpriseAssertionAlgorithm,\n EnterpriseAssertionAudience,\n EnterpriseAssertionType,\n EnterpriseIdpOptions,\n EnterpriseOAuthHop,\n EnterpriseOAuthLog,\n EnterpriseOAuthProviderOptions,\n EnterprisePrivateKey,\n} from './enterprise-oauth.js'\n","import {\n auth,\n OAuthError,\n type FetchLike,\n type OAuthClientInformationMixed,\n type OAuthClientMetadata,\n type OAuthClientProvider,\n type OAuthDiscoveryState,\n type OAuthTokens,\n} from '@modelcontextprotocol/client'\nimport { createLogger } from '../logger.js'\nimport { assertSecureOAuthUrl, VaultOAuthStorage, type McpOAuthStorage } from './oauth.js'\n\n/**\n * Enterprise-Managed Authorization for remote MCP servers (the MCP extension\n * `io.modelcontextprotocol/enterprise-managed-authorization`, also called Cross\n * App Access): the organization's identity provider decides which MCP servers\n * a user's client may reach, and no one is sent to a consent page.\n *\n * Two hops, both plain HTTP POSTs:\n *\n * 1. at the IdP - an RFC 8693 token exchange turns the user's ID token into an\n * Identity Assertion JWT Authorization Grant (ID-JAG) addressed to the MCP\n * server's authorization server;\n * 2. at the MCP authorization server - an RFC 7523 `jwt-bearer` grant turns the\n * ID-JAG into an ordinary access token.\n *\n * The MCP SDK owns discovery (RFC 9728 / RFC 8414), the second hop and the\n * retry on a 401; this module supplies the first hop and the checks around it.\n * Only the resulting access token is stored. The ID token, the ID-JAG and the\n * client assertions pass through memory and are never written, logged or put\n * in an error.\n *\n * The client authenticates on each hop with a secret or with a signed\n * assertion (`private_key_jwt`, RFC 7523 section 2.2). By default the audience\n * of that assertion is the issuer identifier of the server it is for and\n * nothing else, as draft-ietf-oauth-rfc7523bis requires: an assertion made for\n * the IdP is of no use at the authorization server, and the other way round.\n * For a server built to RFC 7523 as published, `assertionAudience:\n * 'token-endpoint'` and `assertionType: 'JWT'` produce the older form - see\n * `EnterpriseAssertionAudience` for what that gives up.\n *\n * Follows draft-ietf-oauth-identity-assertion-authz-grant and the extension's\n * 2026-07-28 revision. The Node package carries the same provider; change both.\n *\n * In a browser the IdP's token endpoint must allow this page's origin (CORS),\n * and a `clientSecret` in a page is readable by anyone who can open the page:\n * see docs/security.md before using one here.\n *\n * Pass the result to `connectMcpHttp`'s `servers[name].authProvider`.\n */\n\n/** The extension identifier a client declares in its capabilities. */\nexport const ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION =\n 'io.modelcontextprotocol/enterprise-managed-authorization'\n\nconst GRANT_TOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange'\nconst GRANT_JWT_BEARER = 'urn:ietf:params:oauth:grant-type:jwt-bearer'\nconst TOKEN_TYPE_ID_JAG = 'urn:ietf:params:oauth:token-type:id-jag'\nconst TOKEN_TYPE_ID_TOKEN = 'urn:ietf:params:oauth:token-type:id_token'\nconst CLIENT_ASSERTION_TYPE = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n/** Seconds a client assertion lives: long enough for one request, no more. */\nconst CLIENT_ASSERTION_LIFETIME_SECONDS = 60\n\n/** Which part of the flow refused. */\nexport type EnterpriseOAuthHop = 'discovery' | 'idp' | 'authorization-server'\n\n/**\n * A failure of the enterprise flow, with the hop that refused: `'discovery'`\n * (what the MCP server published cannot be trusted or used), `'idp'` (the token\n * exchange) or `'authorization-server'` (the `jwt-bearer` grant). The message\n * is short and safe to show: never a request body, a token, an assertion, a\n * secret or a key. What the authorization server said in full goes to the log\n * (`onLog`), redacted the same way.\n */\nexport class EnterpriseOAuthError extends Error {\n readonly hop: EnterpriseOAuthHop\n /** The OAuth `error` code the server answered with, when it sent one. */\n readonly code?: string\n\n constructor(hop: EnterpriseOAuthHop, message: string, code?: string) {\n super(message)\n this.name = 'EnterpriseOAuthError'\n this.hop = hop\n this.code = code\n }\n}\n\n/** Signature algorithms for a `private_key_jwt` client assertion. */\nexport type EnterpriseAssertionAlgorithm =\n 'ES256' | 'ES384' | 'ES512' | 'RS256' | 'RS384' | 'RS512' | 'PS256' | 'PS384' | 'PS512'\n\n/**\n * The private key that signs a client assertion: a `CryptoKey` (best: import\n * or generate it as non-extractable, so page script can use it but not read\n * it) or a JWK object. It must be a key for the chosen `algorithm` (an ECDSA\n * P-256 key for ES256, an RSASSA-PKCS1-v1_5 key for RS256, RSA-PSS for PS256...).\n */\nexport type EnterprisePrivateKey = JsonWebKey | CryptoKey\n\n/**\n * What a `private_key_jwt` client assertion names as its audience (`aud`).\n *\n * - `'issuer'` (the default): the issuer identifier of the server the\n * assertion is for, as draft-ietf-oauth-rfc7523bis requires.\n * - `'token-endpoint'`: the URL of that server's token endpoint, which is what\n * RFC 7523 as published describes and what many deployed identity providers\n * check for.\n *\n * The default is the issuer because an assertion addressed to a token endpoint\n * URL is exactly what the bis draft forbids. The token endpoint is one field of\n * a metadata document; a client that reads its audience from metadata can be\n * handed a document that names an honest server's endpoint (audience\n * injection), and then signs an assertion the party that served the document\n * can replay at that honest server. The issuer identifier is the one value a\n * client checks before it trusts the rest of the document. This provider never\n * takes either value from the MCP server alone - the IdP's endpoint is\n * configuration, and the authorization server's is used only after its\n * metadata matched `expectedIssuer` - so `'token-endpoint'` here costs the\n * defence in depth, not the check itself. Use it only for a server that\n * refuses the issuer form.\n */\nexport type EnterpriseAssertionAudience = 'issuer' | 'token-endpoint'\n\n/**\n * The `typ` header of a client assertion: `client-authentication+jwt` (the\n * default, from draft-ietf-oauth-rfc7523bis: a token typed this way cannot be\n * mistaken for another kind of JWT) or `JWT`, for a server that refuses a\n * `typ` it does not know.\n */\nexport type EnterpriseAssertionType = 'client-authentication+jwt' | 'JWT'\n\n/** Where the provider reports what it will not put in an error. */\nexport type EnterpriseOAuthLog = (level: 'info' | 'warn' | 'error', message: string) => void\n\nexport interface EnterpriseIdpOptions {\n /**\n * The IdP's token endpoint, where the token exchange is posted. Configured,\n * not discovered: it is where the user's ID token and the client's IdP\n * credentials go, so nothing fetched at run time may choose it.\n */\n tokenEndpoint: string\n /**\n * The IdP's issuer identifier. REQUIRED with `private_key_jwt`, where it is\n * the audience of the client assertion - unless `assertionAudience` is\n * `'token-endpoint'`, which addresses the assertion to `tokenEndpoint`.\n */\n issuer?: string\n /** This client's `client_id` at the IdP (the audience of the ID token). */\n clientId: string\n /**\n * This client's secret at the IdP. Omit for a client the IdP treats as\n * public. In a browser it is readable by anyone who can open the page: leave\n * it out and pass a `fetch` that sends this request through your backend.\n */\n clientSecret?: string\n /**\n * How the client authenticates at the IdP. With a secret: in an\n * `Authorization: Basic` header (the default, which every OAuth server must\n * accept) or in the form body. `'private_key_jwt'`: a signed assertion, which\n * needs `privateKey`, `algorithm` and `issuer` (or `assertionAudience:\n * 'token-endpoint'`).\n */\n clientAuthMethod?: 'client_secret_basic' | 'client_secret_post' | 'private_key_jwt'\n /** The key for `private_key_jwt`. Never stored, logged or put in an error. */\n privateKey?: EnterprisePrivateKey\n /** `kid` header of the assertion: the key's id in the JWKS the IdP holds. */\n keyId?: string\n /** Signature algorithm of the assertion. */\n algorithm?: EnterpriseAssertionAlgorithm\n /**\n * The audience of the assertion: `'issuer'` (the default: `issuer`) or\n * `'token-endpoint'` (`tokenEndpoint`, for an IdP built to RFC 7523 - the\n * weaker form, see `EnterpriseAssertionAudience`). Only with `private_key_jwt`.\n */\n assertionAudience?: EnterpriseAssertionAudience\n /**\n * The `typ` header of the assertion: `'client-authentication+jwt'` (the\n * default) or `'JWT'` for an IdP that refuses the new one. Only with\n * `private_key_jwt`.\n */\n assertionType?: EnterpriseAssertionType\n}\n\nexport interface EnterpriseOAuthProviderOptions {\n /** The MCP endpoint being authorized. */\n serverUrl: string\n /**\n * This client's `client_id` at the MCP server's authorization server: a\n * pre-registered identifier, or the https URL of a client ID metadata\n * document (CIMD) you host. A URL must be https with a path of its own, and\n * cannot be used with `clientSecret`: a document anyone can read establishes\n * no shared secret, so such a client is public or uses `private_key_jwt`\n * with the keys the document lists (`jwks` / `jwks_uri`).\n */\n clientId: string\n /**\n * Its secret there. The grant is meant for confidential clients. A secret\n * needs `expectedIssuer`: without it the MCP server's metadata would choose\n * who receives the secret, and the constructor throws.\n *\n * In a browser a secret is readable by anyone who can open the page. This\n * provider is for public clients there, or for a `fetch` that routes the IdP\n * call through your backend, which holds the secret.\n */\n clientSecret?: string\n /**\n * How the client authenticates at the authorization server. Left out, the\n * SDK decides: a secret is sent the way the server's metadata allows (Basic\n * first), no secret means `client_id` alone. `'private_key_jwt'` signs an\n * assertion and needs `privateKey`, `algorithm` and `expectedIssuer`.\n */\n clientAuthMethod?: 'client_secret_basic' | 'client_secret_post' | 'private_key_jwt' | 'none'\n /** The key for `private_key_jwt`. Never stored, logged or put in an error. */\n privateKey?: EnterprisePrivateKey\n /** `kid` header of the assertion: the key's id in the JWKS the server holds. */\n keyId?: string\n /** Signature algorithm of the assertion. */\n algorithm?: EnterpriseAssertionAlgorithm\n /**\n * The audience of the assertion for the authorization server: `'issuer'`\n * (the default: the issuer discovery found, once it matched\n * `expectedIssuer`) or `'token-endpoint'` (the token endpoint from that same\n * metadata, for a server built to RFC 7523 - the weaker form, see\n * `EnterpriseAssertionAudience`). The endpoint is read only from metadata\n * whose issuer is `expectedIssuer`, and must be https or loopback. Only with\n * `private_key_jwt`.\n */\n assertionAudience?: EnterpriseAssertionAudience\n /**\n * The `typ` header of the assertion: `'client-authentication+jwt'` (the\n * default) or `'JWT'` for a server that refuses the new one. Only with\n * `private_key_jwt`.\n */\n assertionType?: EnterpriseAssertionType\n /**\n * The issuer of the MCP server's authorization server. Anything else the MCP\n * server points at is refused before a credential leaves the process.\n * REQUIRED with `clientSecret` and with `private_key_jwt`: neither the\n * receiver of a secret nor the audience of a signed assertion may come from\n * the MCP server's metadata alone. A client with no credential at the\n * authorization server may omit it: then the only thing sent there is the\n * ID-JAG, which the IdP addressed to that one server and which is of no use\n * to any other.\n */\n expectedIssuer?: string\n /** The enterprise identity provider. */\n idp: EnterpriseIdpOptions\n /**\n * The user's OpenID Connect ID token from the IdP. How it was obtained (the\n * single sign-on of your application) is yours; it is called each time a new\n * ID-JAG is needed, so return a current one. The value is never stored.\n */\n getIdToken: () => string | Promise<string>\n /** Scopes to ask the IdP for (space-separated). */\n scope?: string\n /** Defaults to the encrypted IndexedDB vault. Holds the access token only. */\n storage?: McpOAuthStorage\n /** Treat the access token as expired this many seconds early. Default 30. */\n expirySkewSeconds?: number\n /** Custom fetch for the request to the IdP. */\n fetch?: FetchLike\n /**\n * Receives the detail a refusal's error leaves out (what the authorization\n * server answered), redacted. `connectMcpHttp` passes its `onLog`; this is\n * for a provider used without it. With neither, it goes to the package's\n * logger at `warn` (`[agent-web]` on the console).\n */\n onLog?: EnterpriseOAuthLog\n}\n\ninterface StoredTokens {\n tokens: OAuthTokens\n expiresAt?: number\n}\n\nconst DEFAULT_SKEW_SECONDS = 30\n\n// origin + path + query, as the interactive provider does, under a prefix of\n// its own: a token obtained for a user through the IdP is never mistaken for\n// one an operator authorized by hand.\nconst namespaceFor = (serverUrl: string): string => {\n const u = new URL(serverUrl)\n return `mcp-enterprise-oauth:${u.origin}${u.pathname.replace(/\\/+$/, '')}${u.search}`\n}\n\n/** Two issuer identifiers, equal as written or differing by one trailing slash. */\nconst sameIssuer = (a: string, b: string): boolean => a === b || a === `${b}/` || b === `${a}/`\n\nconst stripFragment = (url: string): string => {\n const u = new URL(url)\n u.hash = ''\n return u.href\n}\n\n/**\n * RFC 9728 section 3.3, as the MCP SDK applies it: the resource a server\n * publishes must be the URL we were configured with, or a parent path of it on\n * the same origin.\n */\nconst resourceCovers = (resource: string, serverUrl: string): boolean => {\n let published: URL\n try {\n published = new URL(resource)\n } catch {\n return false\n }\n const requested = new URL(serverUrl)\n if (published.origin !== requested.origin) {\n return false\n }\n const slashed = (p: string): string => (p.endsWith('/') ? p : `${p}/`)\n return slashed(requested.pathname).startsWith(slashed(published.pathname))\n}\n\n/**\n * The audience and the resource of the ID-JAG, read from what discovery found\n * for THIS server and from nothing else - and, once every check below has\n * passed, the token endpoint that metadata names (the audience of a client\n * assertion under `assertionAudience: 'token-endpoint'`). Throws (`hop:\n * 'discovery'`) when the published metadata cannot be trusted:\n *\n * - the authorization server and its token endpoint must be https or loopback;\n * - it must have published metadata with an `issuer`, and that issuer must be\n * the URL the metadata was fetched for (RFC 8414 section 3.3) - otherwise a\n * hostile server could name an honest authorization server as the audience\n * and collect the ID-JAG at its own token endpoint;\n * - with `expectedIssuer`, it must be that one;\n * - the published resource must cover the configured server URL.\n *\n * The Node package carries the same function; change both.\n */\nexport const enterpriseGrantTarget = (\n serverUrl: string,\n state: OAuthDiscoveryState | undefined,\n expectedIssuer?: string,\n): { audience: string; resource: string; tokenEndpoint?: string } => {\n const refuse = (message: string): never => {\n throw new EnterpriseOAuthError('discovery', `Enterprise MCP authorization: ${message}`)\n }\n if (!state) {\n return refuse('nothing is known about the authorization server of this MCP server yet')\n }\n const asUrl = String(state.authorizationServerUrl)\n const metadata = state.authorizationServerMetadata as\n { issuer?: unknown; token_endpoint?: unknown } | undefined\n const issuer = metadata?.issuer\n if (typeof issuer !== 'string' || !issuer) {\n return refuse(\n `the authorization server \"${asUrl}\" published no metadata with an issuer, so there is no audience to ask the identity provider for`,\n )\n }\n if (!sameIssuer(issuer, asUrl)) {\n return refuse(\n `the metadata fetched for \"${asUrl}\" names another issuer (\"${issuer}\"); refusing to request a grant for it`,\n )\n }\n if (expectedIssuer !== undefined && !sameIssuer(issuer, expectedIssuer)) {\n return refuse(\n `this MCP server points at the authorization server \"${issuer}\", expected \"${expectedIssuer}\"; refusing to send credentials there`,\n )\n }\n try {\n assertSecureOAuthUrl(asUrl, 'MCP authorization server')\n if (typeof metadata?.token_endpoint === 'string') {\n assertSecureOAuthUrl(metadata.token_endpoint, 'MCP authorization server token endpoint')\n }\n } catch (err) {\n return refuse((err as Error).message)\n }\n const published = state.resourceMetadata?.resource\n if (published !== undefined && !resourceCovers(published, serverUrl)) {\n return refuse(\n `the protected resource \"${published}\" this server published does not cover \"${serverUrl}\"`,\n )\n }\n return {\n audience: issuer,\n resource: published ?? stripFragment(serverUrl),\n // Handed out only here, after the issuer and the scheme checks above.\n ...(typeof metadata?.token_endpoint === 'string' && metadata.token_endpoint\n ? { tokenEndpoint: metadata.token_endpoint }\n : {}),\n }\n}\n\n/** Printable ASCII only, clipped: a server's words, safe to put in an error. */\nconst printable = (value: unknown, max = 300): string | undefined => {\n if (typeof value !== 'string') {\n return undefined\n }\n const clean = value.replace(/[^\\x20-\\x7e]+/g, ' ').trim()\n if (!clean) {\n return undefined\n }\n return clean.length > max ? `${clean.slice(0, max)}...` : clean\n}\n\nconst formEncode = (value: string): string => new URLSearchParams({ v: value }).toString().slice(2)\n\n/**\n * Whatever a failure message is built from, the secrets of this exchange never\n * leave in it - a server that echoes the request, or a fetch that quotes it,\n * included.\n */\nconst redact = (message: string, secrets: (string | undefined)[]): string => {\n let out = message\n for (const secret of secrets) {\n if (!secret) {\n continue\n }\n // As written, and as a form or a URL would spell it.\n const spellings = [secret, encodeURIComponent(secret), formEncode(secret)]\n for (const spelling of new Set(spellings)) {\n out = out.split(spelling).join('[redacted]')\n }\n }\n return out\n}\n\nconst ALGORITHMS: readonly EnterpriseAssertionAlgorithm[] = [\n 'ES256',\n 'ES384',\n 'ES512',\n 'RS256',\n 'RS384',\n 'RS512',\n 'PS256',\n 'PS384',\n 'PS512',\n]\n\nconst base64Url = (bytes: Uint8Array): string => {\n let binary = ''\n for (const byte of bytes) {\n binary += String.fromCharCode(byte)\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nconst base64UrlJson = (value: unknown): string =>\n base64Url(new TextEncoder().encode(JSON.stringify(value)))\n\n// ── signing: the one part the two packages do differently ──────────────────\n// The browser signs with WebCrypto; the Node package with node:crypto.\n\nconst isCryptoKey = (key: EnterprisePrivateKey): key is CryptoKey =>\n typeof (key as CryptoKey).extractable === 'boolean' &&\n typeof (key as CryptoKey).algorithm === 'object' &&\n Array.isArray((key as CryptoKey).usages)\n\n/** The signature (raw bytes, JWS form) of `input` under `algorithm`. Throws on a key that does not fit. */\nconst signAssertionInput = async (\n algorithm: EnterpriseAssertionAlgorithm,\n privateKey: EnterprisePrivateKey,\n input: string,\n): Promise<Uint8Array> => {\n const bits = algorithm.slice(2)\n const hash = `SHA-${bits}`\n const family = algorithm.slice(0, 2)\n const importAs =\n family === 'ES'\n ? { name: 'ECDSA', namedCurve: bits === '512' ? 'P-521' : `P-${bits}` }\n : { name: family === 'PS' ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5', hash }\n const signAs =\n family === 'ES'\n ? { name: 'ECDSA', hash }\n : family === 'PS'\n ? { name: 'RSA-PSS', saltLength: Number(bits) / 8 }\n : { name: 'RSASSA-PKCS1-v1_5' }\n const { subtle } = globalThis.crypto\n let key: CryptoKey\n if (isCryptoKey(privateKey)) {\n key = privateKey\n // A key made for another scheme, curve or hash must not sign under this name.\n const made = key.algorithm as { name?: string; namedCurve?: string; hash?: { name?: string } }\n const fits =\n key.type === 'private' &&\n made.name === importAs.name &&\n (family === 'ES'\n ? made.namedCurve === (importAs as { namedCurve: string }).namedCurve\n : made.hash?.name === hash)\n if (!fits) {\n throw new Error('key does not fit the algorithm')\n }\n } else {\n if (typeof (privateKey as { d?: unknown }).d !== 'string') {\n throw new Error('not a private key')\n }\n // Imported as non-extractable, for signing only. `alg`, `use` and `key_ops`\n // are left out: a JWK labelled for something else would refuse to import.\n const { alg: _alg, use: _use, key_ops: _ops, ...jwk } = privateKey as JsonWebKey\n key = await subtle.importKey('jwk', jwk, importAs, false, ['sign'])\n }\n return new Uint8Array(await subtle.sign(signAs, key, new TextEncoder().encode(input)))\n}\n\n// ── end of signing ─────────────────────────────────────────────────────────\n\n/** The strings of a key that must never be seen: a JWK's private members. A `CryptoKey` has none to read. */\nconst keySecrets = (key: EnterprisePrivateKey | undefined): string[] => {\n if (key === undefined) {\n return []\n }\n const jwk = key as Record<string, unknown>\n return ['d', 'p', 'q', 'dp', 'dq', 'qi', 'k']\n .map((member) => jwk[member])\n .filter((v): v is string => typeof v === 'string' && v.length > 0)\n}\n\nexport interface ClientAssertionRequest {\n /** The client: both `iss` and `sub`. */\n clientId: string\n /**\n * The sole `aud`: the issuer identifier of the server the assertion is for\n * or, for a server built to RFC 7523, the URL of its token endpoint.\n */\n audience: string\n privateKey: EnterprisePrivateKey\n algorithm: EnterpriseAssertionAlgorithm\n keyId?: string\n /** The `typ` header. Default `client-authentication+jwt`. */\n type?: EnterpriseAssertionType\n}\n\n/**\n * A `private_key_jwt` client assertion (RFC 7523 section 2.2, with the audience\n * rule of draft-ietf-oauth-rfc7523bis): `iss` = `sub` = the client, `aud` = the\n * one audience the caller chose (the provider passes the issuer identifier of\n * the server it is for, or its token endpoint URL when configured to), a\n * random `jti`, `iat`, and an `exp` one minute away; header `typ`\n * `client-authentication+jwt` unless `type` says `JWT`. A failure to sign says\n * so and nothing more: the underlying error may describe the key. The Node\n * package carries the same function; change both.\n */\nexport const createClientAssertion = async (req: ClientAssertionRequest): Promise<string> => {\n const now = Math.floor(Date.now() / 1000)\n const header = {\n alg: req.algorithm,\n typ: req.type === 'JWT' ? 'JWT' : 'client-authentication+jwt',\n ...(req.keyId ? { kid: req.keyId } : {}),\n }\n const payload = {\n iss: req.clientId,\n sub: req.clientId,\n aud: req.audience,\n jti: globalThis.crypto.randomUUID(),\n iat: now,\n exp: now + CLIENT_ASSERTION_LIFETIME_SECONDS,\n }\n const input = `${base64UrlJson(header)}.${base64UrlJson(payload)}`\n let signature: Uint8Array\n try {\n signature = await signAssertionInput(req.algorithm, req.privateKey, input)\n } catch {\n throw new Error(\n `Enterprise MCP authorization: could not sign the client assertion with ${req.algorithm}; check that privateKey is a private key for that algorithm`,\n )\n }\n return `${input}.${base64Url(signature)}`\n}\n\nexport interface IdJagRequest {\n idp: EnterpriseIdpOptions\n /** The ID token (the subject token). */\n idToken: string\n /** The issuer of the MCP server's authorization server. */\n audience: string\n /** The resource identifier of the MCP server. */\n resource: string\n scope?: string\n /** The signed client assertion, when the IdP client uses `private_key_jwt`. */\n clientAssertion?: string\n fetch?: FetchLike\n}\n\n/**\n * Hop 1: exchange the ID token for an ID-JAG at the IdP's token endpoint\n * (RFC 8693, as profiled by the ID-JAG draft, section 4.3). Returns the ID-JAG.\n *\n * Throws `EnterpriseOAuthError` (`hop: 'idp'`) unless the answer is a 200 whose\n * `issued_token_type` is the ID-JAG type and whose `access_token` is a\n * non-empty string. A redirect is refused, not followed: the body holds the ID\n * token and the client's credential. The browser package carries the same\n * function; change both.\n */\nexport const requestIdJag = async (req: IdJagRequest): Promise<string> => {\n const { idp } = req\n const secrets = [\n req.idToken,\n idp.clientSecret,\n req.clientAssertion,\n ...keySecrets(idp.privateKey),\n ]\n // Redacted BEFORE it is clipped: a clipped token no longer matches itself,\n // and the first half of a JWT is its claims.\n const said = (value: unknown, max?: number): string | undefined =>\n printable(typeof value === 'string' ? redact(value, secrets) : value, max)\n const fail = (message: string, code?: string): never => {\n throw new EnterpriseOAuthError(\n 'idp',\n redact(`Enterprise IdP token exchange failed: ${message}`, secrets),\n code,\n )\n }\n\n const params = new URLSearchParams({\n grant_type: GRANT_TOKEN_EXCHANGE,\n requested_token_type: TOKEN_TYPE_ID_JAG,\n audience: req.audience,\n resource: req.resource,\n subject_token: req.idToken,\n subject_token_type: TOKEN_TYPE_ID_TOKEN,\n })\n if (req.scope) {\n params.set('scope', req.scope)\n }\n const headers = new Headers({\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n })\n if (idp.clientAuthMethod === 'private_key_jwt') {\n if (!req.clientAssertion) {\n return fail('no client assertion was made for the identity provider')\n }\n params.set('client_assertion_type', CLIENT_ASSERTION_TYPE)\n params.set('client_assertion', req.clientAssertion)\n } else if (idp.clientSecret === undefined || idp.clientAuthMethod === 'client_secret_post') {\n params.set('client_id', idp.clientId)\n if (idp.clientSecret !== undefined) {\n params.set('client_secret', idp.clientSecret)\n }\n } else {\n // RFC 6749 section 2.3.1: both parts are form-encoded before the base64.\n headers.set(\n 'Authorization',\n `Basic ${btoa(`${formEncode(idp.clientId)}:${formEncode(idp.clientSecret)}`)}`,\n )\n }\n\n let response: Response\n try {\n response = await (req.fetch ?? fetch)(idp.tokenEndpoint, {\n method: 'POST',\n headers,\n body: params,\n redirect: 'error',\n })\n } catch (err) {\n return fail(\n `the request did not complete (${said((err as Error)?.message) ?? 'network error'})`,\n )\n }\n\n let body: Record<string, unknown> = {}\n try {\n const parsed: unknown = await response.json()\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n body = parsed as Record<string, unknown>\n }\n } catch {\n // Not JSON: reported by status below.\n }\n\n if (!response.ok) {\n const code = said(body.error, 80)\n const description = said(body.error_description)\n return fail(\n `the identity provider answered ${response.status}${code ? ` ${code}` : ''}${\n description ? ` - ${description}` : ''\n }`,\n code,\n )\n }\n if (body.issued_token_type !== TOKEN_TYPE_ID_JAG) {\n return fail(\n `the identity provider returned ${\n said(body.issued_token_type, 120) ?? 'no issued_token_type'\n } where an ID-JAG (${TOKEN_TYPE_ID_JAG}) was requested; nothing was sent to the MCP authorization server`,\n )\n }\n if (typeof body.access_token !== 'string' || !body.access_token) {\n return fail(\n 'the identity provider returned no ID-JAG; nothing was sent to the MCP authorization server',\n )\n }\n return body.access_token\n}\n\n/** An https URL with a path of its own: a client ID metadata document. */\nconst looksLikeUrl = (value: string): boolean => /^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)\n\nconst configError = (message: string): Error =>\n new Error(`Enterprise MCP authorization: ${message}`)\n\nconst ASSERTION_AUDIENCES: readonly unknown[] = ['issuer', 'token-endpoint']\nconst ASSERTION_TYPES: readonly unknown[] = ['client-authentication+jwt', 'JWT']\n\n/**\n * The two options that shape a client assertion, for one hop (`prefix` is ''\n * or 'idp.'): a value that is not one of the known ones is refused rather than\n * read as the default, and so is either option where no assertion is signed.\n */\nconst checkAssertionShape = (\n prefix: string,\n hop: { clientAuthMethod?: string; assertionAudience?: unknown; assertionType?: unknown },\n): void => {\n if (hop.assertionAudience !== undefined && !ASSERTION_AUDIENCES.includes(hop.assertionAudience)) {\n throw configError(`${prefix}assertionAudience must be 'issuer' or 'token-endpoint'`)\n }\n if (hop.assertionType !== undefined && !ASSERTION_TYPES.includes(hop.assertionType)) {\n throw configError(`${prefix}assertionType must be 'client-authentication+jwt' or 'JWT'`)\n }\n if (\n hop.clientAuthMethod !== 'private_key_jwt' &&\n (hop.assertionAudience !== undefined || hop.assertionType !== undefined)\n ) {\n throw configError(\n `${prefix}assertionAudience and ${prefix}assertionType are only used with ${prefix}clientAuthMethod 'private_key_jwt'`,\n )\n }\n}\n\n/**\n * What is wrong with the options, said when the provider is built and not in\n * the middle of a flow. Every rule here keeps a credential from going where\n * nobody chose to send it. The browser package carries the same function;\n * change both.\n */\nconst checkOptions = (opts: EnterpriseOAuthProviderOptions): void => {\n assertSecureOAuthUrl(opts.serverUrl)\n assertSecureOAuthUrl(opts.idp?.tokenEndpoint, 'Enterprise IdP token endpoint')\n if (opts.expectedIssuer !== undefined) {\n assertSecureOAuthUrl(opts.expectedIssuer, 'MCP authorization server')\n }\n const { idp } = opts\n if (!opts.clientId || !idp.clientId) {\n throw configError('clientId and idp.clientId are required')\n }\n if (typeof opts.getIdToken !== 'function') {\n throw configError('getIdToken is required')\n }\n\n // The client at the MCP authorization server.\n const method = opts.clientAuthMethod\n if (looksLikeUrl(opts.clientId)) {\n let url: URL | undefined\n try {\n url = new URL(opts.clientId)\n } catch {\n // Reported below.\n }\n if (!url || url.protocol !== 'https:' || url.pathname === '/') {\n throw configError(\n `a clientId that is a URL is a client ID metadata document: it requires https and a non-root path - refusing \"${opts.clientId}\"`,\n )\n }\n if (opts.clientSecret) {\n throw configError(\n 'a client ID metadata document cannot be used with clientSecret: use private_key_jwt, or no credential',\n )\n }\n }\n if (opts.clientSecret && (method === 'private_key_jwt' || method === 'none')) {\n throw configError(`clientSecret is not used with clientAuthMethod '${method}': remove one`)\n }\n if ((method === 'client_secret_basic' || method === 'client_secret_post') && !opts.clientSecret) {\n throw configError(`clientAuthMethod '${method}' needs clientSecret`)\n }\n if (opts.clientSecret && opts.expectedIssuer === undefined) {\n throw configError(\n 'clientSecret needs expectedIssuer: without the issuer of the authorization server, the MCP server decides who receives the secret',\n )\n }\n if (method === 'private_key_jwt') {\n if (opts.privateKey === undefined || !ALGORITHMS.includes(opts.algorithm as never)) {\n throw configError(\n `clientAuthMethod 'private_key_jwt' needs privateKey and an algorithm (${ALGORITHMS.join(', ')})`,\n )\n }\n if (opts.expectedIssuer === undefined) {\n throw configError(\n 'private_key_jwt needs expectedIssuer: the audience of the client assertion must not come from the MCP server alone',\n )\n }\n } else if (opts.privateKey !== undefined) {\n throw configError(\"privateKey is only used with clientAuthMethod 'private_key_jwt'\")\n }\n\n checkAssertionShape('', opts)\n\n // The client at the IdP.\n checkAssertionShape('idp.', idp)\n if (idp.clientAuthMethod === 'private_key_jwt') {\n if (idp.privateKey === undefined || !ALGORITHMS.includes(idp.algorithm as never)) {\n throw configError(\n `idp.clientAuthMethod 'private_key_jwt' needs idp.privateKey and an idp.algorithm (${ALGORITHMS.join(', ')})`,\n )\n }\n // The audience is configuration either way: the issuer, or the token\n // endpoint that is required above. Only the former needs `idp.issuer`.\n if (idp.assertionAudience !== 'token-endpoint' && !idp.issuer) {\n throw configError(\n \"idp.clientAuthMethod private_key_jwt needs idp.issuer: it is the audience of the client assertion (or set idp.assertionAudience to 'token-endpoint')\",\n )\n }\n if (idp.clientSecret) {\n throw configError(\"idp.clientSecret is not used with idp.clientAuthMethod 'private_key_jwt'\")\n }\n } else if (idp.privateKey !== undefined) {\n throw configError(\"idp.privateKey is only used with idp.clientAuthMethod 'private_key_jwt'\")\n }\n if (idp.issuer !== undefined) {\n assertSecureOAuthUrl(idp.issuer, 'Enterprise IdP issuer')\n }\n}\n\n/** One named parameter of a form body, however the caller spelled the body. */\nconst formParam = (body: unknown, name: string): string | undefined => {\n if (body instanceof URLSearchParams) {\n return body.get(name) ?? undefined\n }\n if (typeof body === 'string') {\n return new URLSearchParams(body).get(name) ?? undefined\n }\n return undefined\n}\n\n/** An OAuth `error` code as RFC 6749 spells one, or nothing. */\nconst oauthCode = (value: unknown): string | undefined =>\n typeof value === 'string' && /^[A-Za-z0-9_.-]{1,64}$/.test(value) ? value : undefined\n\n/**\n * A non-interactive `OAuthClientProvider`: no redirect, no browser, no human.\n * On first use, and whenever the access token is missing, expired or rejected,\n * the SDK asks it for a token request and it answers with a fresh ID-JAG.\n */\nexport class BrowserEnterpriseOAuthProvider implements OAuthClientProvider {\n readonly serverUrl: string\n /** The MCP extension this provider implements; the connector declares it. */\n readonly extension = ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION\n /**\n * Present only with an explicit `clientAuthMethod`: the SDK then leaves the\n * client authentication of the grant to it (a `private_key_jwt` assertion is\n * signed here, for the issuer discovery found and `expectedIssuer` confirmed).\n */\n addClientAuthentication?: OAuthClientProvider['addClientAuthentication']\n\n // True private fields: the options hold the secrets, the private keys and the\n // ID token callback, and nothing that prints or serializes the provider\n // (console.log, the devtools object view, JSON.stringify) can reach them.\n readonly #opts: EnterpriseOAuthProviderOptions\n readonly #storage: McpOAuthStorage\n readonly #ns: string\n readonly #skewMs: number\n readonly #clientMetadata: OAuthClientMetadata\n // Held (in memory only) between a granted ID-JAG and the access token it\n // buys: a failure in that window belongs to the MCP authorization server,\n // and nothing said about it may carry the grant or the client assertion.\n #pendingAssertion: string | undefined\n #pendingClientAssertion: string | undefined\n\n constructor(opts: EnterpriseOAuthProviderOptions) {\n checkOptions(opts)\n this.serverUrl = opts.serverUrl\n this.#opts = opts\n this.#storage = opts.storage ?? new VaultOAuthStorage()\n this.#ns = namespaceFor(opts.serverUrl)\n this.#skewMs = (opts.expirySkewSeconds ?? DEFAULT_SKEW_SECONDS) * 1000\n this.#clientMetadata = {\n client_name: 'agent-web',\n redirect_uris: [],\n grant_types: [GRANT_TOKEN_EXCHANGE, GRANT_JWT_BEARER],\n token_endpoint_auth_method:\n opts.clientAuthMethod ?? (opts.clientSecret ? 'client_secret_basic' : 'none'),\n ...(opts.scope ? { scope: opts.scope } : {}),\n }\n if (opts.clientAuthMethod !== undefined) {\n this.addClientAuthentication = (headers, params) => this.#authenticateClient(headers, params)\n }\n }\n\n /** Never set: this is what tells the SDK the flow has no human step. */\n get redirectUrl(): undefined {\n return undefined\n }\n\n get clientMetadata(): OAuthClientMetadata {\n return this.#clientMetadata\n }\n\n #key(suffix: string): string {\n return `${this.#ns}:${suffix}`\n }\n\n async #readJSON<T>(suffix: string): Promise<T | undefined> {\n // The read is inside the guard: the default storage decrypts, and a blob\n // written under a key that no longer exists throws. That is \"no value\".\n try {\n const raw = await this.#storage.get(this.#key(suffix))\n if (raw === undefined) {\n return undefined\n }\n return JSON.parse(raw) as T\n } catch {\n await this.#storage.delete(this.#key(suffix)).catch(() => {})\n return undefined\n }\n }\n\n /** Everything of this provider that must not appear in an error or a log line. */\n #secrets(): (string | undefined)[] {\n return [\n this.#pendingAssertion,\n this.#pendingClientAssertion,\n this.#opts.clientSecret,\n this.#opts.idp.clientSecret,\n ...keySecrets(this.#opts.privateKey),\n ...keySecrets(this.#opts.idp.privateKey),\n ]\n }\n\n /** The detail an error leaves out, to the log: redacted first, then clipped. */\n #report(log: EnterpriseOAuthLog | undefined, detail: string): void {\n // With no log given, the package's logger: the detail is not lost, and it\n // is as redacted there as anywhere.\n const sink: EnterpriseOAuthLog =\n log ?? this.#opts.onLog ?? ((_level, message) => createLogger().warn(message))\n const safe = printable(redact(detail, this.#secrets()), 600) ?? 'no detail'\n try {\n sink('warn', `[mcp] enterprise authorization for ${this.serverUrl}: ${safe}`)\n } catch {\n // A log sink that throws does not get to change the outcome.\n }\n }\n\n /**\n * The pre-registered client, from configuration and never from storage.\n * With `expectedIssuer` it carries that stamp, and the SDK then refuses to\n * present it to any other authorization server.\n */\n clientInformation(): OAuthClientInformationMixed {\n return {\n client_id: this.#opts.clientId,\n ...(this.#opts.clientSecret ? { client_secret: this.#opts.clientSecret } : {}),\n ...(this.#opts.expectedIssuer ? { issuer: this.#opts.expectedIssuer } : {}),\n }\n }\n\n async tokens(): Promise<OAuthTokens | undefined> {\n return (await this.#readJSON<StoredTokens>('tokens'))?.tokens\n }\n\n async saveTokens(tokens: OAuthTokens): Promise<void> {\n this.#pendingAssertion = undefined\n this.#pendingClientAssertion = undefined\n const stored: StoredTokens = {\n tokens,\n expiresAt:\n typeof tokens.expires_in === 'number' ? Date.now() + tokens.expires_in * 1000 : undefined,\n }\n await this.#storage.set(this.#key('tokens'), JSON.stringify(stored))\n }\n\n async saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {\n await this.#storage.set(this.#key('discovery'), JSON.stringify(state))\n }\n\n async discoveryState(): Promise<OAuthDiscoveryState | undefined> {\n const state = await this.#readJSON<OAuthDiscoveryState>('discovery')\n if (!state || typeof state !== 'object' || typeof state.authorizationServerUrl !== 'string') {\n return undefined\n }\n return state\n }\n\n /**\n * Called by the SDK inside `auth()`, after discovery and before the token\n * request to the MCP authorization server: get an ID token from the host,\n * exchange it at the IdP for an ID-JAG addressed to exactly the authorization\n * server and resource discovery found for this server, and hand the SDK the\n * `jwt-bearer` request. Throws before anything reaches the authorization\n * server when discovery cannot be trusted or the IdP's answer is not an ID-JAG.\n */\n async prepareTokenRequest(scope?: string): Promise<URLSearchParams> {\n this.#pendingAssertion = undefined\n this.#pendingClientAssertion = undefined\n let target: { audience: string; resource: string }\n try {\n target = enterpriseGrantTarget(\n this.serverUrl,\n await this.discoveryState(),\n this.#opts.expectedIssuer,\n )\n } catch (err) {\n // Never keep a discovery result that was refused: the next attempt\n // (after the server's 401 says where its metadata lives) starts clean.\n await this.#storage.delete(this.#key('discovery'))\n throw err\n }\n\n let idToken: string\n try {\n idToken = await this.#opts.getIdToken()\n } catch {\n // The host's error is not repeated: it may quote the token it failed on.\n throw new EnterpriseOAuthError(\n 'idp',\n 'Enterprise IdP token exchange failed: getIdToken() threw, so there is no ID token to exchange',\n )\n }\n if (typeof idToken !== 'string' || !idToken) {\n throw new EnterpriseOAuthError(\n 'idp',\n 'Enterprise IdP token exchange failed: getIdToken() returned no ID token',\n )\n }\n\n const { idp } = this.#opts\n // Signed for the IdP and for nothing else - its issuer or, when configured\n // so, its token endpoint, both from configuration: it is no use at the\n // authorization server, whose assertion is made separately.\n const clientAssertion =\n idp.clientAuthMethod === 'private_key_jwt'\n ? await createClientAssertion({\n clientId: idp.clientId,\n audience:\n idp.assertionAudience === 'token-endpoint'\n ? idp.tokenEndpoint\n : (idp.issuer as string),\n privateKey: idp.privateKey as EnterprisePrivateKey,\n algorithm: idp.algorithm as EnterpriseAssertionAlgorithm,\n keyId: idp.keyId,\n type: idp.assertionType,\n }).catch((err: Error) => {\n throw new EnterpriseOAuthError('idp', err.message)\n })\n : undefined\n const assertion = await requestIdJag({\n idp,\n idToken,\n audience: target.audience,\n resource: target.resource,\n scope: scope ?? this.#opts.scope,\n clientAssertion,\n fetch: this.#opts.fetch,\n })\n this.#pendingAssertion = assertion\n return new URLSearchParams({ grant_type: GRANT_JWT_BEARER, assertion })\n }\n\n /** The client authentication of the grant, when `clientAuthMethod` says how. */\n async #authenticateClient(headers: Headers, params: URLSearchParams): Promise<void> {\n const { clientId, clientSecret, clientAuthMethod } = this.#opts\n if (clientAuthMethod === 'private_key_jwt') {\n // The audience is the issuer discovery found, or the token endpoint of\n // that same metadata - either one only after the metadata was checked\n // against `expectedIssuer`, which this method requires.\n const target = enterpriseGrantTarget(\n this.serverUrl,\n await this.discoveryState(),\n this.#opts.expectedIssuer,\n )\n const audience =\n this.#opts.assertionAudience === 'token-endpoint' ? target.tokenEndpoint : target.audience\n if (audience === undefined) {\n this.#pendingAssertion = undefined\n throw new EnterpriseOAuthError(\n 'discovery',\n `Enterprise MCP authorization: the authorization server \"${target.audience}\" published no token endpoint, so there is no audience for the client assertion (assertionAudience 'token-endpoint')`,\n )\n }\n const assertion = await createClientAssertion({\n clientId,\n audience,\n privateKey: this.#opts.privateKey as EnterprisePrivateKey,\n algorithm: this.#opts.algorithm as EnterpriseAssertionAlgorithm,\n keyId: this.#opts.keyId,\n type: this.#opts.assertionType,\n }).catch((err: Error) => {\n this.#pendingAssertion = undefined\n throw new EnterpriseOAuthError('authorization-server', err.message)\n })\n this.#pendingClientAssertion = assertion\n params.set('client_assertion_type', CLIENT_ASSERTION_TYPE)\n params.set('client_assertion', assertion)\n return\n }\n if (clientAuthMethod === 'client_secret_basic') {\n headers.set(\n 'Authorization',\n `Basic ${btoa(`${formEncode(clientId)}:${formEncode(clientSecret as string)}`)}`,\n )\n return\n }\n params.set('client_id', clientId)\n if (clientAuthMethod === 'client_secret_post') {\n params.set('client_secret', clientSecret as string)\n }\n }\n\n /** The codes of the interactive flow: this provider has none. */\n redirectToAuthorization(): never {\n throw new Error('Enterprise MCP authorization has no interactive step')\n }\n saveCodeVerifier(): never {\n throw new Error('Enterprise MCP authorization has no interactive step')\n }\n codeVerifier(): never {\n throw new Error('Enterprise MCP authorization has no interactive step')\n }\n\n /**\n * Called by the SDK when the authorization server rejects what it was sent.\n * The client is configuration, so there is nothing of it to forget; tokens\n * and discovery are dropped as asked.\n */\n async invalidateCredentials(\n scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery',\n ): Promise<void> {\n const targets =\n scope === 'all'\n ? ['tokens', 'discovery']\n : scope === 'tokens' || scope === 'discovery'\n ? [scope]\n : []\n await Promise.all(targets.map((t) => this.#storage.delete(this.#key(t))))\n }\n\n /** True when there is no access token, or it expires within the skew window. */\n async isAccessTokenExpired(): Promise<boolean> {\n const stored = await this.#readJSON<StoredTokens>('tokens')\n if (!stored?.tokens?.access_token) {\n return true\n }\n if (stored.expiresAt === undefined) {\n return false\n }\n return Date.now() + this.#skewMs >= stored.expiresAt\n }\n\n async isAuthorized(): Promise<boolean> {\n return (await this.tokens()) !== undefined\n }\n\n /**\n * The fetch to give the transport that carries this provider (the connector\n * does). It changes one thing: when the request that carries the ID-JAG is\n * refused, the caller gets an `EnterpriseOAuthError` (`hop:\n * 'authorization-server'`) with a short message - the OAuth error code and\n * the status - and what the server said in full goes to `log`, redacted.\n * That holds whenever the SDK asks for a token, at connect or in the middle\n * of a session, so an application never has the server's raw words to show.\n * A refusal is final: every grant is already a fresh one, so the SDK's\n * \"drop the token and try again\" would only repeat the IdP exchange.\n */\n transportFetch(base?: FetchLike, log?: EnterpriseOAuthLog): FetchLike {\n const inner: FetchLike = base ?? ((url, init) => fetch(url, init))\n return async (url, init) => {\n const grant = this.#pendingAssertion\n if (grant === undefined || formParam(init?.body, 'assertion') !== grant) {\n return inner(url, init)\n }\n let response: Response\n try {\n response = await inner(url, init)\n } catch (err) {\n this.#report(log, `the grant request did not complete: ${(err as Error)?.message ?? err}`)\n this.#pendingAssertion = undefined\n this.#pendingClientAssertion = undefined\n throw new EnterpriseOAuthError(\n 'authorization-server',\n 'MCP authorization server could not be reached for the ID-JAG grant',\n )\n }\n if (response.status < 400) {\n return response\n }\n const text = await response.text().catch(() => '')\n let body: Record<string, unknown> = {}\n try {\n const parsed: unknown = JSON.parse(text)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n body = parsed as Record<string, unknown>\n }\n } catch {\n // Not JSON: the status is all there is.\n }\n const code = oauthCode(body.error)\n const description = typeof body.error_description === 'string' ? body.error_description : text\n this.#report(\n log,\n `the authorization server refused the ID-JAG grant with ${response.status}${\n code ? ` ${code}` : ''\n }${description ? `: ${description}` : ''}`,\n )\n this.#pendingAssertion = undefined\n this.#pendingClientAssertion = undefined\n throw new EnterpriseOAuthError(\n 'authorization-server',\n `MCP authorization server refused the ID-JAG grant: ${code ?? 'no error code'} (HTTP ${response.status})`,\n code,\n )\n }\n }\n\n /**\n * Run the whole flow now (discovery, IdP exchange, grant) and store the\n * access token. `connectMcpHttp` calls it before connecting when there is\n * no usable token; call it yourself to fail early. A refusal is an\n * `EnterpriseOAuthError` whose `hop` says who refused.\n */\n async authorize(opts: { fetch?: FetchLike; onLog?: EnterpriseOAuthLog } = {}): Promise<void> {\n try {\n await auth(this, {\n serverUrl: this.serverUrl,\n fetchFn: this.transportFetch(opts.fetch, opts.onLog),\n })\n } catch (err) {\n if (err instanceof EnterpriseOAuthError) {\n throw err\n }\n const detail = (err as Error)?.message ?? String(err)\n if (this.#pendingAssertion !== undefined) {\n // The server answered the grant with something that is not a token.\n this.#report(opts.onLog, `the answer to the ID-JAG grant could not be used: ${detail}`)\n this.#pendingAssertion = undefined\n this.#pendingClientAssertion = undefined\n throw new EnterpriseOAuthError(\n 'authorization-server',\n 'MCP authorization server answered the ID-JAG grant with something that is not a token response',\n )\n }\n // What discovery found is not kept when the flow stopped on it.\n await this.#storage.delete(this.#key('discovery')).catch(() => {})\n const message = printable(redact(detail, this.#secrets()), 500) ?? 'no reason given'\n throw new EnterpriseOAuthError(\n 'discovery',\n `Enterprise MCP authorization: discovery failed (${message})`,\n err instanceof OAuthError ? oauthCode(err.code) : undefined,\n )\n }\n }\n\n /** Forget the access token and what discovery found for this server. */\n async reset(): Promise<void> {\n await this.invalidateCredentials('all')\n }\n}\n\n/** Convenience factory mirroring the rest of the package's `createX` style. */\nexport const createEnterpriseOAuthProvider = (\n opts: EnterpriseOAuthProviderOptions,\n): BrowserEnterpriseOAuthProvider => new BrowserEnterpriseOAuthProvider(opts)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE,QAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAQK;AACP,SAAS,mCAAmC;AAC5C,SAAS,aAAa,kBAAgC;;;ACM/C,IAAM,6BAA6B;AAKnC,IAAM,iCAAiC;AAEvC,IAAM,oCAAoC;AAE1C,IAAM,8BAA8B;AAEpC,IAAM,oCAAoC;AAE1C,IAAM,kCAAkC;AAExC,IAAM,wCAAwC;AAE9C,IAAM,6BAA6B;AAEnC,IAAM,8BAA8B;AAEpC,IAAM,iCAAiC;AAEvC,IAAM,gCAAgC;AAEtC,IAAM,kCAAkC;AAExC,IAAM,4BAA4B;AAElC,IAAM,gCAAgC;AAEtC,IAAM,+BAA+B;AAMrC,IAAM,2BAA2B;AA4JjC,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AAAA,EAEA,SAAiB;AACf,WAAO,KAAK;AAAA,EACd;AACF;AAIA,IAAM,aAAa,CAAC,UAClB,OAAO,UAAU,WAAW,OAAO,KAAK,IAAK,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;AAEpF,IAAM,YAAY,CAAC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AAAA,QACR;AAAA,QACA,mDAAmD,OAAO;AAAA,QAC1D,eAAe,aAAa,UAAU,IAAI,IAAI,IAAI;AAAA,MACpD;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,QAAuB;AAC3B,UAAM,KAAK,sBAAsB,KAAK;AAAA,EACxC;AACF;AAGO,IAAM,gCAAgC,CAC3C,SACmC,IAAI,+BAA+B,IAAI;","names":["auth","action","LOOPBACK_HOSTS","label","label","auth","flat","UnauthorizedError","auth","DEFAULT_SKEW_SECONDS","namespaceFor","auth"]}
|
|
1
|
+
{"version":3,"sources":["../src/mcp/http.ts","../src/mcp/elicitation.ts","../src/mcp/listen.ts","../src/mcp/oauth.ts","../src/mcp/index.ts","../src/mcp/enterprise-oauth.ts"],"sourcesContent":["import {\n auth,\n Client,\n SdkError,\n SdkErrorCode,\n StreamableHTTPClientTransport,\n UnauthorizedError,\n type CallToolResult,\n type ClientOptions,\n type FetchLike,\n type JsonSchemaType,\n type JsonSchemaValidator,\n type OAuthClientProvider,\n type StreamableHTTPReconnectionOptions,\n} from '@modelcontextprotocol/client'\nimport { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/client/validators/cf-worker'\nimport { dynamicTool, jsonSchema, type ToolSet } from 'ai'\nimport {\n describeMcpAppPolicy,\n MCP_APP_MAX_DOWNLOAD_BYTES,\n mcpAppDownloadOf,\n mcpAppsModeOf,\n type McpAppDownloadResource,\n type McpAppsMode,\n MCP_APP_MIME_TYPE,\n MCP_APPS_EXTENSION,\n mcpAppResourceOf,\n mcpAppToolMeta,\n mcpAppToolResultOf,\n type McpAppResource,\n type McpAppToolResult,\n type McpAppVisibility,\n} from './apps.js'\nimport {\n createMcpElicitationSession,\n resolveMcpElicitationOptions,\n type McpElicitationCallInfo,\n type McpElicitationDeps,\n type McpElicitationEvent,\n type McpElicitationHandler,\n type McpElicitationOptions,\n type McpElicitationSession,\n} from './elicitation.js'\nimport { createMcpListenSupervisor, type McpListenSupervisor } from './listen.js'\nimport {\n createMcpSkillCatalog,\n markMcpSkills,\n MCP_SKILLS_EXTENSION,\n mcpSkillsSettingOf,\n type McpSkillSource,\n type McpSkillsClientLike,\n type McpSkillsSetting,\n} from './skills.js'\nimport { assertSecureOAuthUrl } from './oauth.js'\nimport {\n cleanMcpInstructions,\n dropStructuredDuplicates,\n isStructuredContent,\n markMcpTool,\n MCP_MODERN_PROTOCOL_VERSION,\n MCP_MODERN_REFUSED_HINT,\n MCP_MODERN_REQUEST_HEADERS,\n mcpInputRequiredMessage,\n mcpProtocolMode,\n mcpVersionNegotiation,\n outputSchemaNote,\n withStructuredContent,\n type McpProtocolMode,\n type McpServerInstructions,\n type McpServerProtocol,\n} from './shared.js'\n\n/**\n * A remote MCP server reached over StreamableHTTP. Browsers can ONLY speak the\n * HTTP transport — stdio (child processes) is Node-only and intentionally\n * unsupported here. This connector lives behind the `@dudko.dev/agent-web/mcp`\n * subpath so `@modelcontextprotocol/client` never enters the core bundle.\n *\n * Three ways to authenticate, in ascending order of capability:\n * 1. `headers` — a static token you already hold.\n * 2. `getHeaders` — resolved once per connect, for tokens you mint yourself.\n * 3. `authProvider` — full OAuth 2.1: the SDK discovers the authorization\n * server, dynamically registers the client (DCR), runs PKCE, and — the\n * part 1 and 2 cannot do — transparently REFRESHES the access token when\n * the server answers 401 mid-run. See `./oauth`.\n */\nexport interface McpHttpServerConfig {\n url: string\n headers?: Record<string, string>\n /** Called at connect time to provide fresh headers (e.g. a rotating Bearer). */\n getHeaders?: () => Promise<Record<string, string>> | Record<string, string>\n /**\n * OAuth client provider (see `./oauth` for a browser implementation). The\n * transport sends its access token, refreshes on 401 and retries the request.\n * Do NOT also set an `Authorization` entry in `headers`: request headers are\n * merged last and would shadow the OAuth token.\n */\n authProvider?: OAuthClientProvider\n /** Custom fetch for every request: proxying, instrumentation, retries. */\n fetch?: FetchLike\n /** Overrides for the SSE reconnect backoff. Merged over the defaults below. */\n reconnection?: Partial<StreamableHTTPReconnectionOptions>\n /** Give up on this server after this many ms of connect + listing (overrides the option). */\n connectTimeoutMs?: number\n /**\n * Which revisions of the protocol this connection may use. Default `'legacy'`:\n * the 2025 revisions (the `initialize` handshake), exactly what was sent before\n * this option existed. `'auto'` asks the server first (`server/discover`) and\n * speaks 2026-07-28 to one that offers it, the 2025 handshake to any other;\n * `'modern'` is 2026-07-28 only, and a server that does not offer it fails the\n * connect. Decided once, at connect: a tool call is never retried in another\n * revision.\n *\n * CORS: 2026-07-28 adds the request headers `Mcp-Method` and `Mcp-Name` (and\n * sends `MCP-Protocol-Version` on every request, the first included). A server\n * whose `Access-Control-Allow-Headers` does not list them cannot be reached\n * that way from a page: `'modern'` then fails, and `'auto'` falls back to the\n * 2025 revisions with a warning that names the headers. See the README, \"CORS\".\n *\n * On 2026-07-28 there is no session; a tool-list change arrives over a\n * `subscriptions/listen` stream this connector opens - and opens again, with\n * backoff, when it ends while the connection is open (then `onToolsChanged`\n * fires once: a change in the gap was announced to nobody) - and an\n * `input_required` result fails the call unless the connection was given\n * `onElicitation` (see `ConnectMcpOptions`).\n */\n protocol?: McpProtocolMode\n /**\n * EXPERIMENTAL (the Skills extension is Beta): load the skills this server serves\n * (`io.modelcontextprotocol/skills`) into the agent's skills catalog, as `<server>/<skill>`.\n * Off by default: without it the extension is not declared and nothing of it is sent. Needs\n * the 2026-07-28 revision (`protocol: 'auto'` or `'modern'`): the extension is written against\n * it. The skills come with the server's tools (each mounted tool carries them, like the\n * server's instructions), so merging `tools` into the agent's config is all a host does. Their\n * text is third-party - knowledge only, never policy; see the README, \"MCP skills\".\n * `true`, or `{ consent, dynamic }`: `consent` is when a person is asked before one of its\n * skills enters the model's context - `'once-per-skill'` (default, or the agent's\n * `mcpSkills.consent`), `'ask'` (every run) or `'never'` (a server you vetted); `dynamic: true`\n * also takes its GENERATED skills (`\"resources\": \"dynamic\"`, no checksums - declined by\n * default), each read whole into a snapshot in memory before anyone is asked, approved and used\n * as that copy only (README, \"MCP skills\").\n */\n skills?: McpSkillsSetting\n /**\n * MCP Apps for THIS server, over the connection's `apps`: `false` keeps its apps off while\n * other servers' are shown - nothing is declared to it, no app of it is read, no `mcp.app`\n * event is told, and a tool it marks for its app only (`visibility` without `'model'`) is\n * not mounted; its other tools are the model's, as plain tools. `true` turns them on for this\n * server alone. Left out, the connection's `apps` decides.\n */\n apps?: boolean\n}\n\nexport interface McpCatalogEntry {\n name: string\n description: string\n server: string\n /** The server marked the tool read-only (`annotations.readOnlyHint`). */\n readOnly?: boolean\n /**\n * With `apps: true`: the MCP App (`ui://…`) the tool declares. Its results then come with an\n * `mcp.app` event, and the host can show the app (`ConnectedMcp.apps`).\n */\n app?: string\n}\n\nexport interface McpServerResult {\n name: string\n connected: boolean\n error?: string\n /**\n * The server demands OAuth and we have no usable token. When the config\n * carried a `BrowserOAuthProvider`, its `authorizationUrl` now holds the page\n * to send the user to; reconnect once they are back.\n */\n needsAuthorization?: boolean\n}\n\nexport interface ConnectedMcp {\n /** Discovered tools, keyed by \"server__tool\", ready to merge into config.tools. */\n tools: ToolSet\n catalog: McpCatalogEntry[]\n /** Per-server connect outcome. */\n results: McpServerResult[]\n /**\n * The `instructions` each connected server returned in its `initialize`\n * result, in declaration order; servers that sent none are absent. Read once\n * per connection. Third-party text: the agent shows it to the model under a\n * preamble that says so (`config.mcpInstructions`, on by default) — each\n * mounted tool carries its server's instructions, so merging `tools` into\n * the agent's config is all a host does.\n */\n instructions: McpServerInstructions[]\n /**\n * The protocol revision negotiated with each connected server, in declaration\n * order: `2025-…` after the `initialize` handshake (always, for a server\n * without `protocol`), `2026-07-28` when `protocol: 'auto'` or `'modern'`\n * found a server that offers it. Fixed for the life of the connection.\n */\n protocols: McpServerProtocol[]\n /**\n * Re-list one server's tools and rewrite its entries in `tools`/`catalog`.\n * Both are mutated in place, so anything holding a reference (including a\n * live agent config) sees the new set. Throws if the server isn't connected.\n * With `skills: true` it lists the server's skills again too (an agent built\n * after the refresh has the new ones; one built before keeps what it read).\n */\n refreshServer: (name: string) => Promise<void>\n close: () => Promise<void>\n /**\n * MCP Apps, present only on a connection made with `apps: true`: read an app's HTML and make\n * the tool calls an app asks for. See {@link McpAppsConnection}.\n */\n apps?: McpAppsConnection\n}\n\n/** A tool of a server as an app of that server sees it (see `McpAppsConnection.appTool`). */\nexport interface McpAppTool {\n /** The server's own name for the tool. */\n name: string\n /**\n * The name the agent's consent rules match: the key the tool is mounted under, or the key it\n * would have (`server__tool`) when it is for apps only and not mounted.\n */\n key: string\n description: string\n inputSchema: unknown\n /** `annotations.readOnlyHint`: the consent gate lets it through in 'ask-writes'. */\n readOnly: boolean\n visibility: McpAppVisibility[]\n /** The app it declares, if any. */\n resourceUri?: string\n}\n\n/**\n * The host's side of MCP Apps for one connection (`apps: true`). Every call names the server:\n * an app may read and call only what its own server declared.\n *\n * - `readUiResource` reads an app's document with `resources/read` - only a `ui://` URI that a\n * tool of THAT server declares in its current listing, from that server and nowhere else;\n * checked (MIME type, size, URI) and cached per connection.\n * - `appTool` is a server's tool an app may call: listed, with `visibility` including `'app'`.\n * - `callAppTool` sends that tool call and returns the raw result for the app. It does NOT ask\n * the user: a host calls it only after its consent, e.g. `Agent.approveAppToolCall`.\n */\nexport interface McpAppsConnection {\n readUiResource: (\n server: string,\n uri: string,\n options?: { signal?: AbortSignal },\n ) => Promise<McpAppResource>\n appTool: (server: string, name: string) => McpAppTool | undefined\n /**\n * A resource of that server for a file its app asks the host to save (`ui/download-file` with\n * a `resource_link`): `resources/read` on THAT server only - never a fetch of the URI - its\n * `text` or base64 `blob` as bytes, at most `maxBytes` (default `MCP_APP_MAX_DOWNLOAD_BYTES`),\n * not cached. Only a server whose apps are on. It does NOT ask the user, nor judge the type:\n * the host does both before it saves anything.\n */\n readResource: (\n server: string,\n uri: string,\n options?: { signal?: AbortSignal; maxBytes?: number },\n ) => Promise<McpAppDownloadResource>\n callAppTool: (\n server: string,\n name: string,\n args: Record<string, unknown>,\n options?: { signal?: AbortSignal },\n ) => Promise<McpAppToolResult>\n}\n\nexport interface ConnectMcpOptions {\n clientName?: string\n clientVersion?: string\n onLog?: (level: 'info' | 'warn' | 'error', message: string) => void\n /**\n * Fires when a server pushes `notifications/tools/list_changed`. Call\n * `refreshServer(name)` from a point where no run is reading `tools` — this\n * connector deliberately does not refresh behind a running agent's back.\n * On a 2026-07-28 connection (`protocol`) the notice arrives over a\n * `subscriptions/listen` stream, opened only when this callback is given and\n * opened again when it ends (backoff from 1 s to 60 s, at most 10 attempts in\n * a row; never after a 401 / 403 / 404 / 405). Once a stream is back this\n * callback fires as for a notice, since a change in the gap was not announced.\n * On a server with `skills: true` it also fires for a resource list change\n * (`notifications/resources/list_changed`): that is how a change of its\n * skills is announced, and `refreshServer` lists them again. It fires too,\n * once per loaded skill, when a directory read (`resources/directory/read`,\n * a server that declared `directoryRead`) shows that a skill changed on the\n * server since it was loaded.\n */\n onToolsChanged?: (server: string) => void\n /**\n * Per-server deadline for connect + tool listing (default 30 000 ms). A\n * server that misses it is reported failed and closed; the others still\n * mount — one hanging server no longer holds every other one hostage.\n */\n connectTimeoutMs?: number\n /**\n * MCP elicitation: a server may ask the user for input in the middle of a tool\n * call (a form, or - with `elicitation.url` - a link to open), and this\n * callback answers: accept with the form's values, decline, or cancel. The\n * HOST decides, never the model: the question is not shown to the model, and\n * the answer goes only to the server that asked - not into the model's\n * context, an event, a log or a run checkpoint.\n *\n * Without the callback the capability is not declared, a server cannot ask,\n * and nothing is sent that was not sent before. The server's message and form\n * are third-party text: cleaned, capped and restricted to a flat form before\n * the callback sees them; the answer is checked against the form before it is\n * sent. A link (URL mode) is only handed to the callback: this package never\n * fetches or opens it. A callback that throws or does not answer in time\n * cancels the question and fails the tool call; nothing is retried.\n *\n * Inside an agent run the two events `mcp.elicitation-requested` /\n * `mcp.elicitation-answered` are emitted (the answered one never carries a\n * value). On the 2025 revisions the calls to a server with this option run\n * one at a time: its question does not say which call it belongs to.\n */\n onElicitation?: McpElicitationHandler\n /**\n * Its settings: `timeoutMs` (default 300 000: a human is answering; the\n * step's `chatTimeoutMs` stops while a question waits),\n * `maxPerToolCall` (5), `maxPerRun` (20), `url` (also accept URL mode; default\n * false), `subagents` (let a call made by a helper - a subagent - ask too;\n * default false: its question is cancelled without the callback being called).\n */\n elicitation?: McpElicitationOptions\n /**\n * MCP Apps (the `io.modelcontextprotocol/ui` extension): declare the extension in the\n * handshake, read each tool's `_meta.ui` (its `ui://` app and its `visibility`), emit an\n * `mcp.app` event in a run when such a tool returns, and give the host `ConnectedMcp.apps` to\n * read the app and make the calls it asks for. A tool whose `visibility` leaves out `'model'`\n * is then not mounted (it is for its app only). The app's HTML never reaches the model.\n *\n * Off by default: nothing is declared, `_meta` is not read, every tool is mounted as before and\n * the wire is unchanged. A server's own `apps` (`McpHttpServerConfig.apps`) wins over this one.\n */\n apps?: boolean\n}\n\n/**\n * The longest delay a timer takes (2^31 - 1 ms): the SDK's own request timeout\n * is set to it for a 2025 tool call that may ask the user something, whose time\n * is kept by the elicitation session instead (it does not count the time a\n * question waits).\n */\nconst MAX_TIMER_MS = 2_147_483_647\n\n/**\n * What an MCP tool reads of the call that reached it, structurally (this entry\n * does not import the core): the run context the agent passes as\n * `options.agentRun`, and the mark a subagent tool puts on a host tool's call.\n */\ninterface ToolCallOptions {\n abortSignal?: AbortSignal\n agentRun?: {\n emit?: (event: never) => void\n step?: unknown\n signal?: AbortSignal\n runId?: string\n subagent?: { id: string; depth: number }\n elicitations?: { count: number }\n /** The run's clock: stopped while a question waits, so the step's limit does not run. */\n clock?: { pause: () => () => void }\n }\n subagentCall?: {\n id: string\n depth: number\n elicitations?: { count: number }\n /** Stops the clock of the run that delegated, for a call that reaches here without a run. */\n pause?: () => () => void\n }\n}\n\n/** Hard stop for a server whose pagination never ends (the Node sibling's cap and name). */\nexport const MAX_TOOL_LIST_PAGES = 100\n/**\n * 2026-07-28: how long the `subscriptions/listen` stream may take to be\n * acknowledged before the connect goes on without tool-list change notices\n * (the Node sibling's bound and name).\n */\nexport const MCP_LISTEN_ACK_TIMEOUT_MS = 10_000\n\n/** The SDK's typed error with this code (by name too: a second copy of the SDK is another class). */\nconst isSdkError = (err: unknown, code: SdkErrorCode): boolean =>\n (err instanceof SdkError || (err instanceof Error && err.name === 'SdkError')) &&\n (err as { code?: unknown }).code === code\n\n/**\n * Every tool of a server, following `nextCursor` (up to MAX_TOOL_LIST_PAGES\n * pages; a repeated cursor ends the walk). Servers with hundreds of tools\n * paginate; reading only the first page silently drops the rest.\n *\n * Page by page through `client.request`, not `client.listTools()`: called\n * without a cursor, the typed verb of the 2.x SDK walks every page itself,\n * throws past its own page cap, answers without asking when the server did not\n * advertise the tools capability, and fills the cache that switches on the\n * SDK's output-schema check in `callTool` (which this module does itself, see\n * `outputSchemaViolation`). The raw request does none of that.\n */\nexport const listAllTools = async (\n client: Pick<Client, 'request'>,\n onTruncated?: () => void,\n): Promise<McpToolDescriptor[]> => {\n const all: McpToolDescriptor[] = []\n let cursor: string | undefined\n const seen = new Set<string>()\n for (let page = 0; page < MAX_TOOL_LIST_PAGES; page += 1) {\n const res = await client.request({\n method: 'tools/list',\n params: cursor ? { cursor } : undefined,\n })\n all.push(...(res.tools as McpToolDescriptor[]))\n const next = typeof res.nextCursor === 'string' && res.nextCursor ? res.nextCursor : undefined\n if (!next || seen.has(next)) return all\n seen.add(next)\n cursor = next\n }\n onTruncated?.()\n return all\n}\n\nclass ConnectTimeoutError extends Error {}\n\nconst withTimeout = <T>(p: Promise<T>, ms: number, label: string): Promise<T> => {\n if (!(ms > 0)) return p\n let timer: ReturnType<typeof setTimeout> | undefined\n return Promise.race([\n p.finally(() => clearTimeout(timer)),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new ConnectTimeoutError(`${label} timed out after ${ms} ms`)),\n ms,\n )\n }),\n ])\n}\n\n// Providers cap tool names at 64 chars (^[a-zA-Z0-9_-]{1,64}$). We enforce the\n// same limit on the prefixed \"server__tool\" so one server can't poison a run.\nconst MAX_TOOL_NAME_LEN = 64\n\n// Browsers drop long-lived SSE streams on tab-throttling and flaky networks far\n// more often than a server does; the SDK's default (2 retries) gives up too\n// early for an agent that may idle between steps.\nconst DEFAULT_RECONNECTION: StreamableHTTPReconnectionOptions = {\n maxReconnectionDelay: 30_000,\n initialReconnectionDelay: 1_000,\n reconnectionDelayGrowFactor: 1.5,\n maxRetries: 5,\n}\n\n// MCP names may contain characters providers reject (dots, slashes, spaces);\n// map them into the allowed alphabet. callTool still uses the ORIGINAL name.\nconst sanitizeName = (s: string): string => s.replace(/[^a-zA-Z0-9_-]/g, '_')\n\n/**\n * Sanitizing can map two distinct MCP names onto one key (\"a.b\" and \"a-b\" both\n * become \"a_b\"). Suffix instead of dropping: a tool the model can't see is a\n * silent capability loss, and the disambiguated name still resolves back to the\n * original on dispatch.\n */\nconst uniqueKey = (base: string, taken: ToolSet): string => {\n // hasOwn, not truthiness: a tool named so that the key lands on \"__proto__\"\n // would otherwise read as already taken through the prototype chain.\n if (!Object.hasOwn(taken, base)) return base\n for (let n = 2; n < 100; n++) {\n const suffix = `_${n}`\n const candidate = base.slice(0, MAX_TOOL_NAME_LEN - suffix.length) + suffix\n if (!Object.hasOwn(taken, candidate)) return candidate\n }\n return ''\n}\n\n/**\n * Flatten an MCP tool result's content into something a model can read. Unlike\n * the Node sibling this NEVER spills to a filesystem (there isn't one in the\n * browser): all-text content is joined; mixed content passes through as an\n * array of text + raw parts for the host to handle.\n */\nexport const flattenContent = (content: unknown): unknown => {\n if (!Array.isArray(content)) return content\n const parts = content as Array<Record<string, unknown>>\n const allText =\n parts.length > 0 && parts.every((p) => p?.type === 'text' && typeof p.text === 'string')\n if (allText) return parts.map((p) => p.text as string).join('\\n')\n return parts.map((p) => (p?.type === 'text' && typeof p.text === 'string' ? p.text : p))\n}\n\ninterface McpToolDescriptor {\n name: string\n description?: string\n inputSchema: unknown\n outputSchema?: unknown\n annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean; title?: string }\n _meta?: unknown\n}\n\n/** The longest compile error repeated in a refusal (the SDK clips at the same length). */\nconst OUTPUT_SCHEMA_ERROR_MAX_CHARS = 200\n\n/**\n * Why a tool result does not follow the `outputSchema` its tool declared, or\n * `undefined` when it does. The rule and the wording are those of the SDK's\n * `Client.callTool`: a tool with an output schema must answer with\n * `structuredContent`, and that value must validate. An `isError` result is\n * not checked.\n *\n * The check is made here, on a result that was received, instead of inside\n * `callTool`, which throws on a violation and takes the result with it: the\n * call RAN on the server, so its result goes to the model with a note.\n *\n * The Node package carries the same function; change both.\n */\nexport const outputSchemaViolation = (\n toolName: string,\n result: Pick<CallToolResult, 'structuredContent' | 'isError'>,\n validate: JsonSchemaValidator<unknown>,\n): string | undefined => {\n if (result.isError === true) return undefined\n if (result.structuredContent === undefined) {\n return `Tool ${toolName} has an output schema but did not return structured content`\n }\n try {\n const checked = validate(result.structuredContent)\n return checked.valid\n ? undefined\n : `Structured content does not match the tool's output schema: ${checked.errorMessage}`\n } catch (err) {\n return `Failed to validate structured content: ${err instanceof Error ? err.message : String(err)}`\n }\n}\n\ninterface ServerConnect {\n name: string\n client?: Client\n /** What the server said in its initialize result ('' when nothing). */\n instructions?: string\n /** The revision the connection negotiated. */\n protocol?: Omit<McpServerProtocol, 'server'>\n listed?: McpToolDescriptor[]\n /** 2026-07-28 with `onToolsChanged`: what keeps the listen stream open. */\n listener?: McpListenSupervisor\n /** `skills: true` on a 2026-07-28 connection to a server that offers the extension. */\n skills?: { source: McpSkillSource; refresh: () => Promise<void> }\n error?: string\n needsAuthorization?: boolean\n}\n\n/**\n * The enterprise-managed provider (`enterprise-oauth.ts`), recognised by shape\n * so a host's own subclass, or one from another bundle of this package, counts.\n */\ntype EnterpriseLog = (level: 'info' | 'warn' | 'error', message: string) => void\n\ninterface EnterpriseProviderShape {\n extension: string\n authorize: (opts: { fetch?: FetchLike; onLog?: EnterpriseLog }) => Promise<void>\n transportFetch: (base?: FetchLike, log?: EnterpriseLog) => FetchLike\n}\n\nconst asEnterpriseProvider = (\n provider: OAuthClientProvider,\n): EnterpriseProviderShape | undefined => {\n const p = provider as Partial<Record<keyof EnterpriseProviderShape, unknown>>\n return typeof p.extension === 'string' &&\n typeof p.authorize === 'function' &&\n typeof p.transportFetch === 'function'\n ? (provider as unknown as EnterpriseProviderShape)\n : undefined\n}\n\n/** Thrown by the refresh-only view when the SDK reaches for a redirect. */\nclass RefreshOnlyAbort extends Error {}\n\n/**\n * A view of the provider that can renew a token but can never start an\n * interactive authorization.\n *\n * `auth()` does not have a refresh-only mode: when a refresh fails for a reason\n * it deems recoverable (a 5xx from the token endpoint, a network blip) it falls\n * through to a brand-new authorization — issuing a state and a PKCE verifier,\n * overwriting the stored pair, and calling `redirectToAuthorization`. The\n * transport then does its own `auth()` on the first 401, overwriting them\n * again, so the user comes back holding a code the second pair can't verify.\n * Blocking the three redirect-path methods aborts the escalation before\n * anything is overwritten; the transport's 401 handling stays the single owner\n * of interactive authorization.\n */\nconst refreshOnly = (p: OAuthClientProvider): OAuthClientProvider => ({\n // Must stay truthy: `auth()` reads a missing redirectUrl as \"non-interactive\n // grant\" and would try to fetch a token without one.\n get redirectUrl() {\n return p.redirectUrl\n },\n get clientMetadata() {\n return p.clientMetadata\n },\n get clientMetadataUrl() {\n return p.clientMetadataUrl\n },\n // The second argument is the authorization server the SDK resolved: a\n // provider that keeps credentials per issuer reads and writes by it.\n clientInformation: (ctx) => p.clientInformation(ctx),\n saveClientInformation: p.saveClientInformation?.bind(p),\n tokens: (ctx) => p.tokens(ctx),\n saveTokens: (t, ctx) => p.saveTokens(t, ctx),\n invalidateCredentials: p.invalidateCredentials?.bind(p),\n addClientAuthentication: p.addClientAuthentication?.bind(p),\n validateResourceURL: p.validateResourceURL?.bind(p),\n // What a refresh request is made of, when the provider says so.\n scopeForRefresh: p.scopeForRefresh?.bind(p),\n dpop: p.dpop?.bind(p),\n codeVerifier: () => p.codeVerifier(),\n state: () => {\n throw new RefreshOnlyAbort()\n },\n saveCodeVerifier: () => {\n throw new RefreshOnlyAbort()\n },\n redirectToAuthorization: () => {\n throw new RefreshOnlyAbort()\n },\n})\n\n/**\n * An access token that is already expired produces a guaranteed 401 on the\n * first request. When the provider tells us so AND we hold a refresh token,\n * renew before connecting: one round-trip saved, and a run that starts on a\n * stale token doesn't surface a spurious auth error to the model.\n *\n * Best-effort by design — anything that goes wrong here is left to the\n * transport's own 401 handling, which is the path that knows how to ask the\n * user for a new authorization.\n */\nconst refreshIfExpired = async (\n provider: OAuthClientProvider,\n serverUrl: string,\n fetchFn: FetchLike | undefined,\n log: NonNullable<ConnectMcpOptions['onLog']>,\n name: string,\n // The host's own `onLog`, when it gave one: left undefined otherwise, so the\n // enterprise provider falls back to the package's logger for its detail.\n detailLog?: EnterpriseLog,\n): Promise<void> => {\n const check = (provider as { isAccessTokenExpired?: () => boolean | Promise<boolean> })\n .isAccessTokenExpired\n if (typeof check !== 'function') return\n if (!(await check.call(provider))) return\n const enterprise = asEnterpriseProvider(provider)\n if (enterprise) {\n // No human step and no refresh token (the ID-JAG replaces it): get the\n // token now. A refusal by the IdP or the authorization server is final -\n // asking again through the 401 path would only repeat the exchange - so it\n // fails this server with the error that names who refused. Only a\n // discovery failure is left to the transport: the server's 401 may say\n // where its metadata lives, or it may need no authorization at all.\n try {\n await enterprise.authorize({ fetch: fetchFn, onLog: detailLog })\n } catch (err) {\n if ((err as { hop?: unknown })?.hop !== 'discovery') throw err\n log('info', `[mcp] ${name}: ${err instanceof Error ? err.message : String(err)}; continuing`)\n }\n return\n }\n const tokens = await provider.tokens()\n // Nothing to refresh with: let the 401 path ask for a new authorization.\n if (!tokens?.refresh_token) return\n try {\n await auth(refreshOnly(provider), { serverUrl, fetchFn })\n } catch (err) {\n log(\n 'info',\n err instanceof RefreshOnlyAbort\n ? `[mcp] ${name}: the stored token could not be refreshed; a new authorization is needed`\n : `[mcp] ${name}: proactive token refresh failed (${\n err instanceof Error ? err.message : String(err)\n }); continuing`,\n )\n }\n}\n\n/**\n * A fetch the browser refused for CORS reasons is indistinguishable, from\n * JavaScript, from a server that is simply down: both surface as a bare\n * `TypeError`. The reason is deliberately withheld, and the browser prints it\n * only to the devtools console — which is why this failure is usually read as a\n * client bug and debugged in the wrong place for a long time.\n */\nconst isNetworkLevelFailure = (err: unknown): boolean =>\n err instanceof TypeError || /failed to fetch|networkerror|load failed/i.test(String(err))\n\n/**\n * Work out WHY the browser blocked us, by asking a question it will answer.\n *\n * A request carrying only `content-type` needs the same preflight as the real\n * one but asks for nothing else. So if the plain request gets through while the\n * transport's did not, the origin is fine and a *header* is the problem — and\n * the header the transport adds is `MCP-Protocol-Version`, which the spec has\n * required on every post-initialize request since 2025-06-18 and which server\n * CORS lists written before that date do not include. That is the shape of the\n * bug that lets OAuth and `initialize` succeed and then kills the connection\n * moments later, looking for all the world like the consent step failed.\n *\n * With `protocol: 'auto'` or `'modern'` the transport also sends the request\n * headers of the 2026-07-28 revision, on the very first request. The browser\n * will not say which header a preflight refused either, so each one is tried on\n * its own: the ones that do not get through are the ones missing from the\n * server's `Access-Control-Allow-Headers`, and they are named.\n *\n * Exported because a UI wants to say this too, not just log it.\n */\nexport const diagnoseMcpCors = async (\n url: string,\n fetchFn: FetchLike = globalThis.fetch,\n opts: { protocol?: McpProtocolMode } = {},\n): Promise<string | undefined> => {\n const body = JSON.stringify({ jsonrpc: '2.0', id: 0, method: 'ping' })\n let plain: Response\n try {\n plain = await fetchFn(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body,\n })\n } catch {\n return (\n `the browser blocked every request to ${url}, including a plain one. ` +\n 'The server is unreachable, or it does not answer the CORS preflight for this ' +\n 'origin: it must return Access-Control-Allow-Origin (and handle OPTIONS) on the ' +\n 'MCP endpoint, the OAuth endpoints and the /.well-known documents.'\n )\n }\n const hints: string[] = []\n const modern = opts.protocol === 'auto' || opts.protocol === 'modern'\n if (modern) {\n // One request per header, each asking the preflight for that header alone.\n // Whatever the server answers is an answer: only a blocked request counts.\n const refused: string[] = []\n for (const [header, value] of [\n ['MCP-Protocol-Version', MCP_MODERN_PROTOCOL_VERSION],\n [MCP_MODERN_REQUEST_HEADERS[0], 'ping'],\n [MCP_MODERN_REQUEST_HEADERS[1], 'cors-check'],\n ] as const) {\n try {\n await fetchFn(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', [header]: value },\n body,\n })\n } catch {\n refused.push(header)\n }\n }\n if (refused.length > 0) {\n hints.push(\n `a plain request to ${url} succeeded (HTTP ${plain.status}), but one carrying ` +\n `${refused.join(' / ')} was blocked: the server's Access-Control-Allow-Headers ` +\n `does not list ${refused.length === 1 ? 'it' : 'them'}. The ${MCP_MODERN_PROTOCOL_VERSION} ` +\n `revision of the protocol (protocol: '${opts.protocol}') sends MCP-Protocol-Version, ` +\n `${MCP_MODERN_REQUEST_HEADERS.join(' and ')} on every request: add ` +\n `${refused.join(', ')} to Access-Control-Allow-Headers, alongside Content-Type and ` +\n `Authorization (and any Mcp-Param-* header the server's tools declare).`,\n )\n }\n }\n if (hints.length === 0) {\n hints.push(\n `a plain request to ${url} succeeded (HTTP ${plain.status}) but the transport's did not, ` +\n 'so the origin is allowed and a request HEADER is being refused. Add ' +\n 'MCP-Protocol-Version (required on every request after initialize) and Last-Event-ID ' +\n \"to the server's Access-Control-Allow-Headers, alongside Content-Type, Authorization \" +\n 'and mcp-session-id.' +\n (modern\n ? ` With protocol: '${opts.protocol}', ${MCP_MODERN_REQUEST_HEADERS.join(' and ')} too.`\n : ''),\n )\n }\n // A 401 whose challenge JS cannot read means OAuth discovery cannot start\n // from a browser at all, so say so while we are here.\n if (plain.status === 401 && !plain.headers.get('www-authenticate')) {\n hints.push(\n 'The server also answers 401 without exposing WWW-Authenticate: add it to ' +\n 'Access-Control-Expose-Headers, or a browser client cannot read the challenge ' +\n 'and OAuth discovery never starts.',\n )\n }\n return hints.join(' ')\n}\n\n/** Says that `diagnoseMcpCors` found request headers the server's CORS policy refuses. */\nconst NAMES_REFUSED_HEADERS = /was blocked: the server's Access-Control-Allow-Headers/\n\nconst warnTruncated = (log: NonNullable<ConnectMcpOptions['onLog']>, name: string): void =>\n log(\n 'warn',\n `[mcp] ${name}: tools/list still paginating after ${MAX_TOOL_LIST_PAGES} pages; the rest of the tools are not mounted`,\n )\n\nconst openConnection = async (\n name: string,\n cfg: McpHttpServerConfig,\n opts: ConnectMcpOptions,\n log: NonNullable<ConnectMcpOptions['onLog']>,\n elicitation: McpElicitationSession | undefined,\n): Promise<ServerConnect> => {\n let client: Client | undefined\n let listener: McpListenSupervisor | undefined\n let timedOut = false\n const timeoutMs = cfg.connectTimeoutMs ?? opts.connectTimeoutMs ?? 30_000\n // What the version probe (`protocol: 'auto' | 'modern'`) ran into.\n const probe: ProbeState = { blocked: false }\n const attempt = connectAndList(\n name,\n cfg,\n opts,\n log,\n probe,\n (c) => {\n client = c\n // Created after the deadline already passed: nobody will ever use it.\n if (timedOut) void c.close().catch(() => {})\n },\n (l) => {\n listener = l\n if (timedOut) l.stop()\n },\n elicitation,\n )\n // A handshake that completes after the deadline must not leave a live session behind.\n attempt.then(\n (r) => {\n if (!timedOut) return\n r.listener?.stop()\n void r.client?.close().catch(() => {})\n },\n () => {},\n )\n try {\n return await withTimeout(attempt, timeoutMs, 'connect')\n } catch (err) {\n if (err instanceof ConnectTimeoutError) timedOut = true\n // The client may be live even though we ended up here (listTools() failing\n // after a successful connect, or the deadline passing mid-listing). Close\n // it, or the SSE stream leaks for the lifetime of the tab - and its listen\n // stream first, or a retry outlives it.\n listener?.stop()\n if (client) await client.close().catch(() => {})\n const needsAuthorization = err instanceof UnauthorizedError\n let message = err instanceof Error ? err.message : String(err)\n // `protocol: 'modern'` against a server that did not offer the revision:\n // the SDK's sentence, plus which option to turn.\n if (cfg.protocol === 'modern' && isSdkError(err, SdkErrorCode.EraNegotiationFailed)) {\n message = `${message} - ${MCP_MODERN_REFUSED_HINT}`\n }\n // Turn \"TypeError: Failed to fetch\" into the sentence the reader needs.\n // Only on the failure path, so the extra request costs nothing in normal use.\n if (!needsAuthorization && !(err instanceof ConnectTimeoutError)) {\n if (isNetworkLevelFailure(err)) {\n const hint = await diagnoseMcpCors(cfg.url, cfg.fetch, {\n protocol: probe.mode,\n }).catch(() => undefined)\n if (hint) message = `${message} - ${hint}`\n } else if (probe.blocked) {\n // The version probe never reached the server, and what failed\n // afterwards is another error (a page's SDK reads a blocked probe as\n // \"a 2025 server\" and goes on). Said only when a header is the cause.\n const hint = await diagnoseMcpCors(cfg.url, cfg.fetch, {\n protocol: probe.mode,\n }).catch(() => undefined)\n if (hint && NAMES_REFUSED_HEADERS.test(hint)) message = `${message} - ${hint}`\n }\n }\n log(\n 'error',\n needsAuthorization\n ? `[mcp] ${name}: authorization required - send the user to the provider's authorizationUrl`\n : `[mcp] ${name}: failed to connect - ${message}`,\n )\n return { name, error: message, needsAuthorization }\n }\n}\n\n/** What the version probe of one connect ran into (see `openConnection`). */\ninterface ProbeState {\n /** The configured mode, once it was read. */\n mode?: McpProtocolMode\n /** A request of the probe was blocked before it reached the server (CORS, or no network). */\n blocked: boolean\n}\n\n/**\n * 2026-07-28: ask the server for tool-list change notices, and ask again while the\n * connection is open (`./listen`: backoff, final errors, the re-list once a stream\n * is back). Best effort - a server that does not announce them, or a stream that\n * cannot be opened, leaves a connection whose tools still work; `refreshServer`\n * still re-lists.\n */\nconst listenForToolChanges = async (\n name: string,\n client: Client,\n log: NonNullable<ConnectMcpOptions['onLog']>,\n announce: () => void,\n onListener: (listener: McpListenSupervisor) => void,\n skills: boolean,\n): Promise<void> => {\n if (!client.getServerCapabilities()?.tools?.listChanged) {\n log('info', `[mcp] ${name}: the server does not announce tool list changes`)\n return\n }\n // `skills: true`: a change of the server's skills comes as a resource list change (the\n // extension is built on resources), on the same stream.\n const resources = skills && client.getServerCapabilities()?.resources?.listChanged === true\n const listener = createMcpListenSupervisor({\n server: name,\n listen: (signal) =>\n client.listen(\n { toolsListChanged: true, ...(resources ? { resourcesListChanged: true } : {}) },\n { timeout: MCP_LISTEN_ACK_TIMEOUT_MS, signal },\n ),\n log,\n // Changes made while no stream was open: the path a notice takes, so the host\n // sees what a notice causes.\n onResubscribed: announce,\n })\n onListener(listener)\n await listener.start()\n}\n\nconst connectAndList = async (\n name: string,\n cfg: McpHttpServerConfig,\n opts: ConnectMcpOptions,\n log: NonNullable<ConnectMcpOptions['onLog']>,\n probe: ProbeState,\n onClient: (client: Client) => void,\n onListener: (listener: McpListenSupervisor) => void,\n elicitation: McpElicitationSession | undefined,\n): Promise<ServerConnect> => {\n // Read first: a `protocol` that is none of the three names is a\n // configuration error, said before anything is sent.\n const mode = mcpProtocolMode(cfg.protocol, name)\n probe.mode = mode\n if (cfg.headers && cfg.getHeaders) {\n throw new Error(`MCP server \"${name}\": specify either headers or getHeaders, not both`)\n }\n const headers = cfg.getHeaders ? await cfg.getHeaders() : cfg.headers\n if (cfg.authProvider) {\n if (headers && 'Authorization' in headers) {\n log(\n 'warn',\n `[mcp] ${name}: an explicit Authorization header shadows the OAuth token from authProvider`,\n )\n }\n assertSecureOAuthUrl(cfg.url, name)\n await refreshIfExpired(cfg.authProvider, cfg.url, cfg.fetch, log, name, opts.onLog)\n }\n const transport = new StreamableHTTPClientTransport(new URL(cfg.url), {\n requestInit: headers ? { headers } : undefined,\n authProvider: cfg.authProvider,\n // A 403 `insufficient_scope` in the middle of a session. A provider\n // without a human step (no `redirectUrl`: the enterprise one) may ask\n // again for the wider scope, once per request - the SDK's cap. One WITH a\n // human step - in a browser nearly all of them - never does: the SDK would\n // skip the refresh and start a new authorization from inside a tool call,\n // replacing the stored state and PKCE verifier each time the model tried\n // the tool again. The call fails with the scope the server asked for, and\n // the host decides. The Node sibling's rule.\n onInsufficientScope: cfg.authProvider?.redirectUrl ? 'throw' : 'reauthorize',\n // The enterprise provider reports a refused grant itself: a short typed\n // error for the caller, the server's words (redacted) to the log.\n fetch:\n (cfg.authProvider &&\n asEnterpriseProvider(cfg.authProvider)?.transportFetch(cfg.fetch, opts.onLog)) ||\n cfg.fetch,\n reconnectionOptions: { ...DEFAULT_RECONNECTION, ...cfg.reconnection },\n })\n // Without these, a dropped SSE stream or a transport-level protocol error\n // is swallowed and the agent just stops getting results.\n // The version probe asks a question a 2025 server answers with an HTTP\n // error: that answer is the expected \"no\", not a fault of the connection. A\n // probe that was BLOCKED is remembered: a page's SDK reads it as \"a 2025\n // server\" too, and only this callback saw the difference.\n let probing = mode !== 'legacy'\n transport.onerror = (err) => {\n if (!probing) {\n log('warn', `[mcp] ${name}: transport error - ${err.message}`)\n return\n }\n if (isNetworkLevelFailure(err)) probe.blocked = true\n log('info', `[mcp] ${name}: version probe (server/discover) - ${err.message}`)\n }\n // info, not warn: an ordinary close() ends here too, and a routine\n // teardown logged as a warning trains people to ignore warnings.\n transport.onclose = () => log('info', `[mcp] ${name}: transport closed`)\n\n const enterprise = cfg.authProvider ? asEnterpriseProvider(cfg.authProvider) : undefined\n // Without `protocol` (or with 'legacy') nothing is added here: the client is\n // built with exactly the options it always had.\n const negotiation = mcpVersionNegotiation(mode)\n // MCP Apps: declared only where they are on for this server (`apps` of the server, else of\n // the connection); a server whose apps are declined is not told of them.\n const apps = mcpAppsModeOf(cfg.apps, opts.apps) === 'on'\n // `skills: true` (experimental): the Skills extension is written against 2026-07-28, so it is\n // declared only where that revision may be spoken; never on a 'legacy' connection.\n const skillsSetting = mcpSkillsSettingOf(cfg.skills, name)\n const skillsWanted = skillsSetting.on && mode !== 'legacy'\n if (skillsSetting.on && mode === 'legacy') {\n log(\n 'warn',\n `[mcp] ${name}: skills: true needs protocol 'auto' or 'modern' (the Skills extension is written against 2026-07-28); no skills are requested`,\n )\n }\n const clientOptions: ClientOptions | undefined =\n enterprise || negotiation || elicitation || apps || skillsWanted\n ? {\n // An extension is opt-in: it is declared only by the client that uses\n // it. So is elicitation: without `onElicitation` no capability is\n // declared, and a server cannot ask. MCP Apps: only with `apps`.\n ...(enterprise || elicitation || apps || skillsWanted\n ? {\n capabilities: {\n ...(enterprise || apps || skillsWanted\n ? {\n extensions: {\n ...(enterprise ? { [enterprise.extension]: {} } : {}),\n ...(apps\n ? { [MCP_APPS_EXTENSION]: { mimeTypes: [MCP_APP_MIME_TYPE] } }\n : {}),\n ...(skillsWanted ? { [MCP_SKILLS_EXTENSION]: {} } : {}),\n },\n }\n : {}),\n ...(elicitation ? { elicitation: elicitation.capability } : {}),\n },\n }\n : {}),\n ...(negotiation\n ? {\n versionNegotiation: negotiation,\n // 2026-07-28: an `input_required` result is NOT answered and the\n // call is NOT sent again by the SDK (its default would try\n // both). Without `onElicitation` it fails the tool call; with\n // it, `execute` answers it through the session, which keeps\n // the caps the SDK's own loop does not have.\n inputRequired: { autoFulfill: false },\n }\n : {}),\n }\n : undefined\n const client = new Client(\n { name: opts.clientName ?? 'agent-web', version: opts.clientVersion ?? '0.0.0' },\n clientOptions,\n )\n if (elicitation) {\n // 2025 revisions: the server's question is a request of its own. (On\n // 2026-07-28 the SDK drops inbound requests; the question is then the tool\n // call's `input_required` result.)\n client.setRequestHandler('elicitation/create', (request) =>\n elicitation.onRequest(request.params),\n )\n }\n onClient(client)\n await client.connect(transport)\n probing = false\n const era = client.getProtocolEra() ?? 'legacy'\n const version = client.getNegotiatedProtocolVersion() ?? ''\n if (mode !== 'legacy') {\n log(\n 'info',\n `[mcp] ${name}: protocol ${version} (${\n era === 'modern' ? 'modern: stateless, no session' : 'legacy: the initialize handshake'\n }; configured '${mode}')`,\n )\n // 'auto' on the 2025 revisions although the probe never reached the\n // server: when a CORS header is why, the server may well speak 2026-07-28.\n if (era === 'legacy' && probe.blocked) {\n const hint = await diagnoseMcpCors(cfg.url, cfg.fetch, { protocol: mode }).catch(\n () => undefined,\n )\n log(\n 'warn',\n `[mcp] ${name}: the version probe (server/discover) was blocked before it reached the server, so the connection uses ${version}${\n hint && NAMES_REFUSED_HEADERS.test(hint) ? ` - ${hint}` : ''\n }`,\n )\n }\n }\n\n // `skills: true`: only on 2026-07-28 (the revision the extension is written against), and only\n // from a server that declares it. Listed here; nothing of a skill is read yet. The SDK's skills\n // client is loaded only then: a connection without skills does not carry it.\n let skills: ServerConnect['skills']\n if (skillsWanted) {\n if (era !== 'modern') {\n log(\n 'info',\n `[mcp] ${name}: skills: true, but the connection uses ${version} - the Skills extension needs 2026-07-28; no skills`,\n )\n } else if (!client.getServerCapabilities()?.extensions?.[MCP_SKILLS_EXTENSION]) {\n log('info', `[mcp] ${name}: the server does not offer skills (${MCP_SKILLS_EXTENSION})`)\n } else {\n const { SkillsClient } = await import('@modelcontextprotocol/client/ext/skills')\n // A directory read that shows a skill changed on the server (`directoryRead`) is announced\n // the way a resource list change is: `onToolsChanged`, for a refresh between runs.\n const notify = opts.onToolsChanged\n skills = createMcpSkillCatalog(\n name,\n new SkillsClient(client, { skipInvalid: true }) as unknown as McpSkillsClientLike,\n (level, message) => log(level, message),\n {\n ...(skillsSetting.consent ? { consent: skillsSetting.consent } : {}),\n ...(skillsSetting.dynamic ? { dynamic: true } : {}),\n ...(notify ? { onChanged: () => notify(name) } : {}),\n },\n )\n await skills.refresh()\n }\n }\n\n // Subscribe BEFORE the first list call: a server that mutates its tool set\n // during init would otherwise lose the notification in the window between\n // connect() and listTools().\n let listener: McpListenSupervisor | undefined\n if (opts.onToolsChanged) {\n const notify = opts.onToolsChanged\n const announce = (): void => notify(name)\n client.setNotificationHandler('notifications/tools/list_changed', announce)\n // A change of the server's skills is a resource list change: the refresh re-lists both.\n if (skills) client.setNotificationHandler('notifications/resources/list_changed', announce)\n // 2026-07-28 has no stream a server may write to unasked: the notice above\n // arrives only on a `subscriptions/listen` stream the client opens, and\n // opens again when it ends. (The 2025 revisions send it on the GET stream\n // the transport opens, and resumes, by itself.)\n if (era === 'modern') {\n await listenForToolChanges(\n name,\n client,\n log,\n announce,\n (l) => {\n listener = l\n onListener(l)\n },\n Boolean(skills),\n )\n }\n }\n\n const listed = await listAllTools(client, () => warnTruncated(log, name))\n // Read once, here: the text is fixed for the life of this connection.\n return {\n name,\n client,\n listed,\n ...(listener ? { listener } : {}),\n instructions: cleanMcpInstructions(client.getInstructions()),\n protocol: { version, era },\n ...(skills ? { skills } : {}),\n }\n}\n\n/**\n * Connect to one or more HTTP MCP servers and return their tools + catalogue.\n * Servers connect concurrently; tools, catalogue, and results merge in the\n * caller's declaration order, so the outcome is deterministic.\n */\nexport const connectMcpHttp = async (\n servers: Record<string, McpHttpServerConfig>,\n opts: ConnectMcpOptions = {},\n): Promise<ConnectedMcp> => {\n const log = opts.onLog ?? (() => {})\n // Read first: a setting that is not a usable number is a configuration error.\n const elicitationOptions = resolveMcpElicitationOptions(opts.elicitation)\n const elicitationDeps: McpElicitationDeps | undefined = opts.onElicitation\n ? { handler: opts.onElicitation, options: elicitationOptions, log }\n : undefined\n // One per server, made before its client: the capability it declares is part\n // of the handshake.\n const elicitationSessions = new Map<string, McpElicitationSession>()\n const elicitationSessionOf = (name: string): McpElicitationSession | undefined => {\n if (!elicitationDeps) return undefined\n let session = elicitationSessions.get(name)\n if (!session) {\n session = createMcpElicitationSession(name, elicitationDeps)\n elicitationSessions.set(name, session)\n }\n return session\n }\n const clients = new Map<string, Client>()\n const tools: ToolSet = {}\n const catalog: McpCatalogEntry[] = []\n const results: McpServerResult[] = []\n const instructions: McpServerInstructions[] = []\n const instructionsOf = new Map<string, string>()\n const protocols: McpServerProtocol[] = []\n // 2026-07-28, with `onToolsChanged`: per connected server, what keeps its\n // listen stream open (`./listen`). Stopped before the clients are closed.\n const listeners = new Map<string, McpListenSupervisor>()\n // server name → the tool keys it currently owns, so a refresh can remove\n // exactly its own entries.\n const mountedKeys = new Map<string, string[]>()\n // server name → its skills (`skills: true`, 2026-07-28, the server offers the extension).\n const skillCatalogs = new Map<string, NonNullable<ServerConnect['skills']>>()\n // MCP Apps (`apps: true`): per server, the tools as an app sees them (every listed tool, by\n // its own name) and the app documents read so far (by URI; a failed read is not kept). Each\n // server has a mode of its own (`McpHttpServerConfig.apps` over `ConnectMcpOptions.apps`).\n const appsModes = new Map<string, McpAppsMode>(\n Object.entries(servers).map(([name, cfg]) => [name, mcpAppsModeOf(cfg.apps, opts.apps)]),\n )\n const appsOn = [...appsModes.values()].includes('on')\n const appToolsOf = new Map<string, Map<string, McpAppTool>>()\n const appResources = new Map<string, Map<string, Promise<McpAppResource>>>()\n let appEventSeq = 0\n\n /**\n * One `tools/call` to a server, for the model or for an app: through the elicitation session\n * when the connection has one (on the 2025 revisions the session runs a server's calls one at\n * a time - an app's call too, or a question could be put to the wrong call), else the plain\n * request. A request that fails throws: there is no result.\n */\n const requestToolCall = async (\n name: string,\n client: Client,\n key: string,\n toolName: string,\n args: Record<string, unknown>,\n options: ToolCallOptions | undefined,\n ): Promise<CallToolResult> => {\n const elicitation = elicitationSessionOf(name)\n try {\n if (elicitation) {\n // The server may ask the user something during this call\n // (`onElicitation`). The session answers - on the 2025 revisions\n // a request of the server's own, on 2026-07-28 an\n // `input_required` result followed by the same call sent again\n // with the answers and the server's state - and keeps the caps;\n // see elicitation.ts.\n const call = options\n const run = call?.agentRun\n const signal = call?.abortSignal ?? run?.signal\n const emit = run?.emit as ((event: unknown) => void) | undefined\n const step = run?.step\n // A call made by a helper says so: the agent marks its own\n // helpers' calls, a subagent tool the calls of its host tools.\n const helper = run?.subagent ?? call?.subagentCall\n // One count per run the host started: a subagent tool's child counts on the\n // run that delegated to it.\n const counter = call?.subagentCall?.elicitations ?? run?.elicitations\n // While the user is asked, the step's time limit does not run: the clock of the run\n // the call belongs to (or of the run that delegated it, from a worker's host tool).\n // An app's call made outside a run has no clock, and nothing to pause.\n const pause = run?.clock?.pause ?? call?.subagentCall?.pause\n const era = client.getProtocolEra() ?? 'legacy'\n const info: McpElicitationCallInfo = {\n tool: key,\n toolName,\n ...(signal ? { signal } : {}),\n ...(emit\n ? {\n emit: (event: McpElicitationEvent) =>\n emit(\n event.type === 'mcp.elicitation-requested' && step ? { ...event, step } : event,\n ),\n }\n : {}),\n ...(run?.runId ? { runId: run.runId } : {}),\n ...(helper ? { subagent: { id: helper.id, depth: helper.depth } } : {}),\n ...(counter ? { run: counter } : {}),\n ...(pause ? { pause } : {}),\n }\n return await elicitation.call(\n era,\n info,\n (leg) =>\n client.request(\n {\n method: 'tools/call',\n params: { name: toolName, arguments: args, ...leg.retry },\n },\n {\n ...(leg.signal ? { signal: leg.signal } : {}),\n ...(leg.ownTimeout ? { timeout: MAX_TIMER_MS } : {}),\n // Hand an `input_required` result back instead of failing\n // on it: the session answers it.\n ...(era === 'modern' ? { allowInputRequired: true } : {}),\n },\n ) as Promise<CallToolResult>,\n )\n }\n return await client.request(\n { method: 'tools/call', params: { name: toolName, arguments: args } },\n options?.abortSignal ? { signal: options.abortSignal } : undefined,\n )\n } catch (err) {\n // 2026-07-28: the server answered `input_required` (it wants the\n // user asked something, or the call sent again with a state). Not\n // supported here, and the call is not repeated.\n if (isSdkError(err, SdkErrorCode.UnsupportedResultType)) {\n throw new Error(mcpInputRequiredMessage(toolName))\n }\n throw err\n }\n }\n\n const mountTools = (name: string, client: Client, listed: McpToolDescriptor[]): void => {\n const prefix = `${sanitizeName(name)}__`\n // Drop this server's existing entries first, mutating in place so external\n // references (an agent's live ToolSet) stay valid. We delete the keys this\n // server actually mounted rather than everything matching its prefix:\n // sanitizing can make two server names share a prefix (\"docs.v1\" and\n // \"docs/v1\"), and one server's prefix can nest inside another's (\"a\" and\n // \"a__b\") — either way a prefix sweep would silently unmount a DIFFERENT\n // server's tools.\n for (const k of mountedKeys.get(name) ?? []) {\n delete tools[k]\n }\n for (let i = catalog.length - 1; i >= 0; i--) {\n if (catalog[i].server === name) catalog.splice(i, 1)\n }\n const keys: string[] = []\n const appTools = new Map<string, McpAppTool>()\n // The SDK's own validator, the one its browser build uses by default\n // (@cfworker/json-schema: no code generation, so it runs under a CSP without\n // 'unsafe-eval'; dialect by `$schema`). One per mount, compiled lazily.\n let schemaValidator: CfWorkerJsonSchemaValidator | undefined\n\n let mounted = 0\n const appsMode = appsModes.get(name) ?? 'off'\n for (const t of listed) {\n const prefixed = prefix + sanitizeName(t.name)\n // MCP Apps: read only with apps on for this server - or declined, for `visibility` alone. A\n // tool for its app only is not the model's either way.\n const ui = appsMode !== 'off' ? mcpAppToolMeta(t) : undefined\n if (appsMode === 'on' && ui?.refusedUri !== undefined) {\n log(\n 'warn',\n `[mcp] ${name}: tool \"${t.name}\" declares an app that is not a ui:// URI (${ui.refusedUri}); ignored`,\n )\n }\n if (ui && !ui.visibility.includes('model')) {\n if (appsMode === 'declined') {\n log(\n 'info',\n `[mcp] ${name}: tool \"${t.name}\" is for its app only, and apps are off for this server; not mounted`,\n )\n continue\n }\n if (ui.visibility.includes('app')) {\n appTools.set(t.name, {\n name: t.name,\n key: prefixed,\n description: t.description ?? '',\n inputSchema: t.inputSchema,\n readOnly: t.annotations?.readOnlyHint === true,\n visibility: ui.visibility,\n ...(ui.resourceUri ? { resourceUri: ui.resourceUri } : {}),\n })\n }\n log('info', `[mcp] ${name}: tool \"${t.name}\" is for its app only; not mounted`)\n continue\n }\n if (prefixed.length > MAX_TOOL_NAME_LEN) {\n log(\n 'warn',\n `[mcp] ${name}: tool \"${t.name}\" exceeds the ${MAX_TOOL_NAME_LEN}-char name limit; skipping`,\n )\n continue\n }\n const key = uniqueKey(prefixed, tools)\n if (!key) {\n log('warn', `[mcp] ${name}: cannot find a free name for tool \"${t.name}\"; skipping`)\n continue\n }\n if (key !== prefixed) {\n log('warn', `[mcp] ${name}: tool name \"${prefixed}\" already taken; mounted as \"${key}\"`)\n }\n const description = t.description ?? ''\n const readOnly = t.annotations?.readOnlyHint === true\n const appUri = appsMode === 'on' ? ui?.resourceUri : undefined\n if (appsMode === 'on' && ui?.visibility.includes('app')) {\n appTools.set(t.name, {\n name: t.name,\n key,\n description,\n inputSchema: t.inputSchema,\n readOnly,\n visibility: ui.visibility,\n ...(appUri ? { resourceUri: appUri } : {}),\n })\n }\n // Compiled on the first call, as the SDK does, and once per mount.\n let outputValidator: JsonSchemaValidator<unknown> | undefined\n const outputValidatorOf = (): JsonSchemaValidator<unknown> | undefined => {\n if (!t.outputSchema || outputValidator) return outputValidator\n try {\n schemaValidator ??= new CfWorkerJsonSchemaValidator()\n outputValidator = schemaValidator.getValidator(t.outputSchema as JsonSchemaType)\n } catch (err) {\n // Before anything is sent, so nothing ran on the server: a schema\n // that cannot be compiled is refused as the SDK refuses it, and never\n // silently skipped.\n const reason = (err instanceof Error ? err.message : String(err)).slice(\n 0,\n OUTPUT_SCHEMA_ERROR_MAX_CHARS,\n )\n throw new Error(`Tool '${t.name}' has an invalid outputSchema: ${reason}`)\n }\n return outputValidator\n }\n tools[key] = dynamicTool({\n description,\n inputSchema: jsonSchema(t.inputSchema as Parameters<typeof jsonSchema>[0]),\n execute: async (args, options) => {\n // Throws before anything is sent when the schema cannot be compiled.\n const validate = outputValidatorOf()\n // `client.request`, not `client.callTool`: the typed verb also checks\n // the result against the tool's outputSchema and throws when it does\n // not fit - taking with it a result that DID arrive. The request is\n // the same on the wire, in both eras: on 2026-07-28 the transport\n // derives `Mcp-Method` and `Mcp-Name` from the message itself,\n // whoever built it. Only the `Mcp-Param-*` headers are the typed\n // verb's own - a mirror of arguments a tool marked with\n // `x-mcp-header`, for intermediaries; this client does not send them\n // (so a server's CORS list needs none of them for this client). A\n // request that fails (transport, protocol, abort) throws here: there\n // is no result, and the throw is recorded as a failed call.\n const res = await requestToolCall(\n name,\n client,\n key,\n t.name,\n (args ?? {}) as Record<string, unknown>,\n options as ToolCallOptions | undefined,\n )\n // MCP Apps: the app of this tool can show the result. Told to the run (a UI is\n // listening there), with the call's arguments and the result the app is given -\n // never the app itself, which the host reads with `apps.readUiResource`.\n if (appUri) {\n const run = (options as ToolCallOptions | undefined)?.agentRun\n const emit = run?.emit as ((event: unknown) => void) | undefined\n if (emit) {\n const result = mcpAppToolResultOf(res)\n emit({\n type: 'mcp.app',\n id: `mcp-app-${Date.now().toString(36)}-${(appEventSeq += 1)}`,\n server: name,\n tool: key,\n toolName: t.name,\n resourceUri: appUri,\n input: (args ?? {}) as Record<string, unknown>,\n ...(result ? { result } : {}),\n ...(run?.step ? { step: run.step } : {}),\n })\n }\n }\n // A result arrived. When it does not follow the tool's outputSchema\n // (no structuredContent, or one that does not match) it is passed on\n // with a note rather than reported as a failure — a tool the model is\n // told failed is a tool it calls again, and this one may write.\n let schemaNote: string | undefined\n const violation = validate && outputSchemaViolation(t.name, res, validate)\n if (violation) {\n schemaNote = outputSchemaNote(t.name, violation)\n log(\n 'warn',\n `[mcp] ${key}: result does not follow the declared outputSchema - ${violation}; passed on with a note`,\n )\n }\n // An MCP failure is a NORMAL response with isError set — surface it\n // as a thrown error so both tool paths record a failed call instead\n // of feeding the error text to the model as a success.\n if (res.isError) {\n const flat = flattenContent(res.content)\n throw new Error(typeof flat === 'string' ? flat : JSON.stringify(flat))\n }\n // A server that returns structured content also sends it serialized\n // as text (the specification's backwards-compatible form): the model\n // gets the value once, and whatever else the content holds beside it.\n const structured = isStructuredContent(res.structuredContent)\n ? res.structuredContent\n : undefined\n const flat = flattenContent(\n structured ? dropStructuredDuplicates(res.content, structured) : res.content,\n )\n return withStructuredContent(flat, structured, schemaNote)\n },\n })\n // The agent's consent gate lets read-only tools through in 'ask-writes'.\n if (readOnly) (tools[key] as { readOnly?: boolean }).readOnly = true\n // Which server the tool came from, and that server's instructions: the\n // agent shows the notes of the servers whose tools it actually mounts.\n markMcpTool(tools[key], name, instructionsOf.get(name))\n // And its skills (`skills: true`): they come with its tools, like its instructions.\n const skillSource = skillCatalogs.get(name)?.source\n if (skillSource) markMcpSkills(tools[key], skillSource)\n catalog.push({\n name: key,\n description,\n server: name,\n ...(readOnly ? { readOnly } : {}),\n ...(appUri ? { app: appUri } : {}),\n })\n keys.push(key)\n mounted += 1\n }\n mountedKeys.set(name, keys)\n if (appsMode === 'on') {\n appToolsOf.set(name, appTools)\n // A new listing may declare other apps: what was read for the old one is read again.\n appResources.delete(name)\n }\n log('info', `[mcp] ${name}: ${mounted} tools mounted`)\n }\n\n const connects = await Promise.all(\n Object.entries(servers).map(([name, cfg]) =>\n openConnection(name, cfg, opts, log, elicitationSessionOf(name)),\n ),\n )\n\n for (const server of connects) {\n if (!server.client || !server.listed) {\n results.push({\n name: server.name,\n connected: false,\n error: server.error,\n ...(server.needsAuthorization ? { needsAuthorization: true } : {}),\n })\n continue\n }\n clients.set(server.name, server.client)\n if (server.listener) listeners.set(server.name, server.listener)\n if (server.instructions) {\n log(\n 'info',\n `[mcp] ${server.name}: the server sent instructions (${server.instructions.length} chars)`,\n )\n instructions.push({ server: server.name, instructions: server.instructions })\n instructionsOf.set(server.name, server.instructions)\n }\n if (server.protocol) protocols.push({ server: server.name, ...server.protocol })\n if (server.skills) skillCatalogs.set(server.name, server.skills)\n mountTools(server.name, server.client, server.listed)\n results.push({ name: server.name, connected: true })\n }\n\n const connectedClient = (server: string): Client => {\n const client = clients.get(server)\n if (!client) throw new Error(`MCP server \"${server}\" is not connected`)\n return client\n }\n\n const apps: McpAppsConnection | undefined = appsOn\n ? {\n readUiResource: (server, uri, readOptions) => {\n let client: Client\n try {\n client = connectedClient(server)\n } catch (err) {\n return Promise.reject(err)\n }\n // Only an app a tool of THIS server declares: an app cannot be pointed at another\n // server's resources, nor at a resource its server did not tie to a tool.\n const declared = [...(appToolsOf.get(server)?.values() ?? [])].some(\n (t) => t.resourceUri === uri,\n )\n if (!declared) {\n return Promise.reject(\n new Error(`no tool of MCP server \"${server}\" declares the app ${uri}`),\n )\n }\n let cache = appResources.get(server)\n if (!cache) {\n cache = new Map()\n appResources.set(server, cache)\n }\n const cached = cache.get(uri)\n if (cached) return cached\n const reading = client\n .request(\n { method: 'resources/read', params: { uri } },\n readOptions?.signal ? { signal: readOptions.signal } : undefined,\n )\n .then((result) => {\n const resource = mcpAppResourceOf(server, uri, result)\n // The audit trail the specification asks a host for: what the app may reach.\n log('info', `[mcp] ${server}: app ${uri} - ${describeMcpAppPolicy(resource)}`)\n return resource\n })\n // A failed read is not kept: the next one asks again.\n reading.catch(() => {\n if (appResources.get(server)?.get(uri) === reading) cache.delete(uri)\n })\n cache.set(uri, reading)\n return reading\n },\n appTool: (server, toolName) => {\n const tool = appToolsOf.get(server)?.get(toolName)\n return tool ? { ...tool, visibility: [...tool.visibility] } : undefined\n },\n readResource: async (server, uri, readOptions) => {\n const client = connectedClient(server)\n // Only a server whose apps are on: a declined one's app never runs here.\n if (!appToolsOf.has(server)) {\n throw new Error(`MCP Apps are off for the MCP server \"${server}\"`)\n }\n if (\n typeof uri !== 'string' ||\n uri.length === 0 ||\n uri.length > 2048 ||\n // eslint-disable-next-line no-control-regex\n /[\\u0000-\\u001f\\u007f\\s]/.test(uri)\n ) {\n throw new Error('a resource URI is one line of at most 2048 characters')\n }\n log('info', `[mcp] ${server}: an app's download reads ${uri.slice(0, 200)}`)\n const result = await client.request(\n { method: 'resources/read', params: { uri } },\n readOptions?.signal ? { signal: readOptions.signal } : undefined,\n )\n return mcpAppDownloadOf(uri, result, readOptions?.maxBytes ?? MCP_APP_MAX_DOWNLOAD_BYTES)\n },\n callAppTool: async (server, toolName, args, callOptions) => {\n const client = connectedClient(server)\n const tool = appToolsOf.get(server)?.get(toolName)\n // The specification: a call from an app to a tool whose visibility leaves out\n // 'app' (or that its server does not list) is refused, and never reaches the server.\n if (!tool) {\n throw new Error(`MCP server \"${server}\" has no tool \"${toolName}\" that an app may call`)\n }\n if (typeof args !== 'object' || args === null || Array.isArray(args)) {\n throw new Error(`the arguments of \"${toolName}\" must be an object`)\n }\n log('info', `[mcp] ${server}: an app called ${toolName}`)\n const res = await requestToolCall(\n server,\n client,\n tool.key,\n toolName,\n args,\n callOptions?.signal ? { abortSignal: callOptions.signal } : undefined,\n )\n return (\n mcpAppToolResultOf(res) ?? {\n content: [{ type: 'text', text: 'The result was too large to hand to the app.' }],\n isError: true,\n }\n )\n },\n }\n : undefined\n\n return {\n tools,\n catalog,\n results,\n instructions,\n protocols,\n refreshServer: async (name: string) => {\n const client = clients.get(name)\n if (!client) throw new Error(`MCP server \"${name}\" is not connected`)\n // Its skills too (`skills: true`): a change of them reaches here the way a tool change does.\n await skillCatalogs.get(name)?.refresh()\n mountTools(name, client, await listAllTools(client, () => warnTruncated(log, name)))\n },\n close: async () => {\n // The listen streams first: a pending retry or an attempt in flight must not\n // outlive (or be logged against) a client that is going away.\n for (const listener of listeners.values()) listener.stop()\n listeners.clear()\n appResources.clear()\n await Promise.allSettled([...clients.values()].map((c) => c.close()))\n },\n ...(apps ? { apps } : {}),\n }\n}\n","/**\n * MCP elicitation, the part the two agent packages share: a server asks the user for input in\n * the middle of a tool call, the HOST answers through a callback, and the call goes on. Pure, no\n * imports: the limits, what a request must look like before a host sees it, what an answer must\n * look like before a server sees it, the one function that asks, and the two ways a tool call\n * with questions is driven (`elicitation/create` requests on the 2025 revisions, `input_required`\n * results on 2026-07-28).\n *\n * A consent boundary. The server's text is third-party data: cleaned and capped here, shown only\n * to the host's callback and in the `mcp.elicitation-requested` event, never put into a prompt.\n * The answer goes to the server that asked and nowhere else: nothing in this file logs, emits or\n * returns a value the user entered - events and errors carry field NAMES only.\n *\n * This file is a COPY, byte for byte, in `@dudko.dev/agent` (`src/mcp-elicitation.ts`) and\n * `@dudko.dev/agent-web` (`src/mcp/elicitation.ts`): change both. The Node package's\n * `tests/mcp-elicitation-shared.test.ts` compares the two files and tests every guard here; each\n * needs a mutation check.\n */\n\n// ── limits ───────────────────────────────────────────────────────────────\n\n/** How long one question waits for the host's answer, by default: a human is reading it. */\nexport const MCP_ELICITATION_TIMEOUT_MS = 300_000\n/**\n * The longest wait a timer holds (2^31 - 1 ms, about 24.8 days). `setTimeout` fires a longer one -\n * Infinity included - after about 1 ms, so a `timeoutMs` past it is taken as no limit at all.\n */\nexport const MCP_ELICITATION_TIMEOUT_MAX_MS = 2_147_483_647\n/** The most questions one tool call may ask, by default. */\nexport const MCP_ELICITATION_MAX_PER_TOOL_CALL = 5\n/** The most questions one run may be asked, by default (its helpers' calls included). */\nexport const MCP_ELICITATION_MAX_PER_RUN = 20\n/** The most of a server's message a host is shown, in characters. */\nexport const MCP_ELICITATION_MESSAGE_MAX_CHARS = 2000\n/** The most of a field's title or of an option's title. */\nexport const MCP_ELICITATION_LABEL_MAX_CHARS = 200\n/** The most of a field's description. */\nexport const MCP_ELICITATION_DESCRIPTION_MAX_CHARS = 500\n/** A form with more fields is refused. */\nexport const MCP_ELICITATION_MAX_FIELDS = 50\n/** A select with more options is refused. */\nexport const MCP_ELICITATION_MAX_OPTIONS = 100\n/** A field name, or an option's value, longer than this is refused (they go back verbatim). */\nexport const MCP_ELICITATION_NAME_MAX_CHARS = 200\n/** A link longer than this is refused. */\nexport const MCP_ELICITATION_URL_MAX_CHARS = 2048\n/** The longest text a field without its own `maxLength` may be answered with. */\nexport const MCP_ELICITATION_VALUE_MAX_CHARS = 10_000\n/** Ends a text that a cap cut. */\nexport const MCP_ELICITATION_TRUNCATED = '... [truncated]'\n/** 2026-07-28: the most `input_required` answers one tool call may take before it fails. */\nexport const MCP_INPUT_REQUIRED_MAX_ROUNDS = 10\n/** 2026-07-28: the pause before a round that only says \"call me again\" is answered. */\nexport const MCP_INPUT_REQUIRED_PACING_MS = 250\n/**\n * 2025 revisions: how long a tool call may take, NOT counting the time a question of its own\n * waits for the user. (The SDK's request timeout, a minute, would otherwise end a call whose\n * form is still being filled in.)\n */\nexport const MCP_TOOL_CALL_TIMEOUT_MS = 60_000\n\n// ── types ────────────────────────────────────────────────────────────────\n\n/** One field of a form: the flat subset of JSON Schema the specification allows, nothing else. */\nexport interface McpElicitationFieldSchema {\n type: 'string' | 'number' | 'integer' | 'boolean' | 'array'\n title?: string\n description?: string\n default?: string | number | boolean | string[]\n /** string */\n minLength?: number\n maxLength?: number\n format?: 'email' | 'uri' | 'date' | 'date-time'\n /** string: single-select, plain (`enumNames`: the older titled form). */\n enum?: string[]\n enumNames?: string[]\n /** string: single-select with titles. */\n oneOf?: { const: string; title: string }[]\n /** number / integer */\n minimum?: number\n maximum?: number\n /** array: multi-select. */\n minItems?: number\n maxItems?: number\n items?: { type?: 'string'; enum?: string[]; anyOf?: { const: string; title: string }[] }\n}\n\n/** The form a server asks for, as a host is shown it: checked, cleaned and capped. */\nexport interface McpElicitationSchema {\n type: 'object'\n properties: Record<string, McpElicitationFieldSchema>\n required?: string[]\n}\n\n/** What the host's callback is given. Every string in it is third-party text. */\nexport interface McpElicitationRequest {\n /** Unique per question; the same id is in the two events. */\n id: string\n /** The server that asks: its key in the host's configuration. */\n server: string\n /** The tool call during which it asks: the tool's name as the model called it. */\n tool: string\n mode: 'form' | 'url'\n /** The server's words, cleaned and capped (MCP_ELICITATION_MESSAGE_MAX_CHARS). */\n message: string\n /** Form mode: the fields to fill in. */\n requestedSchema?: McpElicitationSchema\n /**\n * URL mode: the link the server wants the user to open. It is only handed over: nothing in\n * these packages fetches or opens it. https, or http on a loopback host.\n */\n url?: string\n /** URL mode on the 2025 revisions: the server's id for this interaction. */\n elicitationId?: string\n runId?: string\n /** Set when a helper the model started is the one whose call asks (`elicitation.subagents`). */\n subagent?: { id: string; depth: number }\n}\n\nexport type McpElicitationContent = Record<string, string | number | boolean | string[]>\n\n/**\n * The host's answer. `accept` carries the form's values (form mode) or nothing (URL mode: it\n * says the user agreed to open the link); `decline` is a no; `cancel` is \"dismissed\".\n */\nexport type McpElicitationResult =\n | { action: 'accept'; content?: McpElicitationContent }\n | { action: 'decline' }\n | { action: 'cancel' }\n\nexport interface McpElicitationContext {\n /** Aborted when the answer is no longer wanted: the run stopped, or the time ran out. */\n signal: AbortSignal\n}\n\n/** `onElicitation`: the host decides, never the model. */\nexport type McpElicitationHandler = (\n request: McpElicitationRequest,\n ctx: McpElicitationContext,\n) => McpElicitationResult | Promise<McpElicitationResult>\n\n/** The `elicitation` settings beside `onElicitation`. */\nexport interface McpElicitationOptions {\n /**\n * How long one question waits for an answer. Default 300 000. `0` or `Infinity` = no limit of\n * its own (the question waits until the run is stopped), and so is a value above 2^31 - 1 (about\n * 24.8 days, the most a timer holds). Negative or NaN: a configuration error.\n */\n timeoutMs?: number\n /** Questions one tool call may ask. Default 5. */\n maxPerToolCall?: number\n /** Questions one run may be asked. Default 20. */\n maxPerRun?: number\n /** Also accept URL mode (a link to open). Default false: only forms are declared. */\n url?: boolean\n /**\n * Let a tool call made by a helper (a subagent) ask the user too. Default false: such a\n * question is cancelled without the callback being called.\n */\n subagents?: boolean\n}\n\nexport interface McpResolvedElicitationOptions {\n /** 0 = no limit of its own; otherwise at most {@link MCP_ELICITATION_TIMEOUT_MAX_MS}. */\n timeoutMs: number\n maxPerToolCall: number\n maxPerRun: number\n url: boolean\n subagents: boolean\n}\n\n/** Why a question was answered without the host deciding. */\nexport type McpElicitationReason =\n | 'unsupported-schema'\n | 'unsupported-mode'\n | 'insecure-url'\n | 'invalid-request'\n | 'subagent'\n | 'cap-per-call'\n | 'cap-per-run'\n | 'handler-error'\n | 'timeout'\n | 'invalid-answer'\n | 'aborted'\n | 'step-timeout'\n | 'after-failure'\n | 'no-tool-call'\n\n/** The two events of a question. Neither ever carries a value the user entered. */\nexport type McpElicitationEvent =\n | {\n type: 'mcp.elicitation-requested'\n id: string\n server: string\n tool: string\n mode: 'form' | 'url'\n message: string\n requestedSchema?: McpElicitationSchema\n url?: string\n subagent?: { id: string; depth: number }\n }\n | {\n type: 'mcp.elicitation-answered'\n id: string\n server: string\n tool: string\n action: 'accept' | 'decline' | 'cancel'\n /** true when nobody decided: a guard, a cap, a timeout, a failed handler. */\n automatic: boolean\n reason?: McpElicitationReason\n /** The names of the fields an accepted form was answered with. Names only. */\n fields?: string[]\n }\n\n/** A failure of this boundary; `toJSON` keeps the message when a trace is serialised. */\nexport class McpElicitationError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'McpElicitationError'\n }\n\n toJSON(): string {\n return this.message\n }\n}\n\n// ── settings ─────────────────────────────────────────────────────────────\n\nconst shownValue = (value: unknown): string =>\n typeof value === 'number' ? String(value) : (JSON.stringify(value) ?? String(value))\n\nconst settingOf = (value: unknown, name: string, fallback: number, min: number): number => {\n if (value === undefined || value === null) {\n return fallback\n }\n if (typeof value !== 'number' || !Number.isFinite(value) || value < min) {\n throw new Error(\n `elicitation.${name} must be a number of at least ${min} (got ${shownValue(value)})`,\n )\n }\n return Math.floor(value)\n}\n\n// `timeoutMs`: 0, Infinity and anything past what a timer holds are no limit (0); a positive\n// fraction waits at least 1 ms rather than becoming \"no limit\".\nconst timeoutOf = (value: unknown): number => {\n if (value === undefined || value === null) {\n return MCP_ELICITATION_TIMEOUT_MS\n }\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {\n throw new Error(\n `elicitation.timeoutMs must be a number of at least 0 (0 or Infinity: no limit) (got ${shownValue(value)})`,\n )\n }\n return value === 0 || value > MCP_ELICITATION_TIMEOUT_MAX_MS ? 0 : Math.max(1, Math.floor(value))\n}\n\n/** The settings with their defaults. A value that is not a usable number is a configuration error. */\nexport const resolveMcpElicitationOptions = (\n raw: McpElicitationOptions | undefined,\n): McpResolvedElicitationOptions => ({\n timeoutMs: timeoutOf(raw?.timeoutMs),\n maxPerToolCall: settingOf(\n raw?.maxPerToolCall,\n 'maxPerToolCall',\n MCP_ELICITATION_MAX_PER_TOOL_CALL,\n 1,\n ),\n maxPerRun: settingOf(raw?.maxPerRun, 'maxPerRun', MCP_ELICITATION_MAX_PER_RUN, 1),\n url: raw?.url === true,\n subagents: raw?.subagents === true,\n})\n\n/**\n * The `elicitation` capability a client with a handler declares: the form always, URL mode only\n * when the host asked for it. (No handler: no capability at all - the caller declares nothing.)\n */\nexport const mcpElicitationCapability = (\n options: Pick<McpResolvedElicitationOptions, 'url'>,\n): { form: Record<string, never>; url?: Record<string, never> } =>\n options.url ? { form: {}, url: {} } : { form: {} }\n\n// ── the request, before a host sees it ───────────────────────────────────\n\n// C0 / C1 controls (tab and newline stay), zero-width and bidirectional-override characters.\nconst INVISIBLE = /[\\u0000-\\u0008\\u000B-\\u001F\\u007F-\\u009F---]/g\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** Third-party text as a host may show it: a string, invisible characters removed, capped. */\nexport const cleanMcpElicitationText = (raw: unknown, max: number): string => {\n if (typeof raw !== 'string') {\n return ''\n }\n const text = raw.replace(/\\r\\n?/g, '\\n').replace(INVISIBLE, '').trim()\n return text.length > max ? `${text.slice(0, Math.max(0, max))}${MCP_ELICITATION_TRUNCATED}` : text\n}\n\n// A string that goes back to the server verbatim (a field name, an option's value): it is\n// never altered, so one that would have to be is not usable.\nconst isVerbatim = (value: unknown): value is string =>\n typeof value === 'string' &&\n value.length > 0 &&\n value.length <= MCP_ELICITATION_NAME_MAX_CHARS &&\n value.replace(INVISIBLE, '') === value &&\n !/[\\r\\n\\t]/.test(value)\n\nconst UNSAFE_NAMES: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])\n\n// A field's name in a sentence a model or a log may read.\nconst fieldLabel = (name: string): string =>\n JSON.stringify(cleanMcpElicitationText(name, 64).replace(/\\s+/g, ' '))\n\ntype Checked<T> = { ok: true; value: T } | { ok: false; reason: string }\n\nconst bad = (reason: string): { ok: false; reason: string } => ({ ok: false, reason })\n\nconst label = (raw: unknown, max: number): string | undefined => {\n const text = cleanMcpElicitationText(raw, max)\n return text ? text : undefined\n}\n\nconst count = (raw: unknown): number | undefined | null =>\n raw === undefined\n ? undefined\n : typeof raw === 'number' && Number.isInteger(raw) && raw >= 0\n ? raw\n : null\n\nconst plainOptions = (raw: unknown): string[] | undefined =>\n Array.isArray(raw) &&\n raw.length > 0 &&\n raw.length <= MCP_ELICITATION_MAX_OPTIONS &&\n raw.every(isVerbatim)\n ? [...(raw as string[])]\n : undefined\n\nconst titledOptions = (raw: unknown): { const: string; title: string }[] | undefined => {\n if (!Array.isArray(raw) || raw.length === 0 || raw.length > MCP_ELICITATION_MAX_OPTIONS) {\n return undefined\n }\n const out: { const: string; title: string }[] = []\n for (const option of raw) {\n if (!isPlainObject(option) || !isVerbatim(option.const)) {\n return undefined\n }\n out.push({\n const: option.const,\n title: label(option.title, MCP_ELICITATION_LABEL_MAX_CHARS) ?? option.const,\n })\n }\n return out\n}\n\nconst FORMATS: ReadonlySet<string> = new Set(['email', 'uri', 'date', 'date-time'])\n\nconst normalizeField = (name: string, raw: unknown): Checked<McpElicitationFieldSchema> => {\n const at = `field ${fieldLabel(name)}`\n if (!isPlainObject(raw)) {\n return bad(`${at} is not a schema`)\n }\n const type = raw.type\n if (\n type !== 'string' &&\n type !== 'number' &&\n type !== 'integer' &&\n type !== 'boolean' &&\n type !== 'array'\n ) {\n return bad(\n `${at} has an unsupported type (${cleanMcpElicitationText(typeof type === 'string' ? type : typeof type, 20)}); a form may hold only strings, numbers, booleans and selects`,\n )\n }\n // A nested form, whatever its `type` says.\n if (raw.properties !== undefined || raw.additionalProperties !== undefined) {\n return bad(`${at} is a nested object; a form is flat`)\n }\n const field: McpElicitationFieldSchema = { type }\n const title = label(raw.title, MCP_ELICITATION_LABEL_MAX_CHARS)\n if (title) {\n field.title = title\n }\n const description = label(raw.description, MCP_ELICITATION_DESCRIPTION_MAX_CHARS)\n if (description) {\n field.description = description\n }\n if (type === 'string') {\n if (raw.enum !== undefined && raw.oneOf !== undefined) {\n return bad(`${at} has both \"enum\" and \"oneOf\"`)\n }\n if (raw.enum !== undefined) {\n const options = plainOptions(raw.enum)\n if (!options) {\n return bad(`${at} has options that cannot be shown`)\n }\n field.enum = options\n if (Array.isArray(raw.enumNames) && raw.enumNames.length === options.length) {\n field.enumNames = raw.enumNames.map(\n (n, i) => label(n, MCP_ELICITATION_LABEL_MAX_CHARS) ?? options[i],\n )\n }\n } else if (raw.oneOf !== undefined) {\n const options = titledOptions(raw.oneOf)\n if (!options) {\n return bad(`${at} has options that cannot be shown`)\n }\n field.oneOf = options\n } else {\n const min = count(raw.minLength)\n const max = count(raw.maxLength)\n if (min === null || max === null) {\n return bad(`${at} has a length limit that is not a whole number`)\n }\n if (min !== undefined) {\n field.minLength = min\n }\n if (max !== undefined) {\n field.maxLength = max\n }\n if (raw.format !== undefined) {\n if (typeof raw.format !== 'string' || !FORMATS.has(raw.format)) {\n return bad(`${at} has an unsupported format`)\n }\n field.format = raw.format as McpElicitationFieldSchema['format']\n }\n }\n } else if (type === 'number' || type === 'integer') {\n for (const key of ['minimum', 'maximum'] as const) {\n const bound = raw[key]\n if (bound === undefined) {\n continue\n }\n if (typeof bound !== 'number' || !Number.isFinite(bound)) {\n return bad(`${at} has a bound that is not a number`)\n }\n field[key] = bound\n }\n } else if (type === 'array') {\n const items = raw.items\n if (!isPlainObject(items) || items.properties !== undefined) {\n return bad(`${at} is a list of something other than options; a form is flat`)\n }\n if (items.enum !== undefined && items.anyOf === undefined) {\n const options = plainOptions(items.enum)\n if (!options || (items.type !== undefined && items.type !== 'string')) {\n return bad(`${at} has options that cannot be shown`)\n }\n field.items = { type: 'string', enum: options }\n } else if (items.anyOf !== undefined && items.enum === undefined) {\n const options = titledOptions(items.anyOf)\n if (!options) {\n return bad(`${at} has options that cannot be shown`)\n }\n field.items = { anyOf: options }\n } else {\n return bad(`${at} is a list of something other than options; a form is flat`)\n }\n const min = count(raw.minItems)\n const max = count(raw.maxItems)\n if (min === null || max === null) {\n return bad(`${at} has a size limit that is not a whole number`)\n }\n if (min !== undefined) {\n field.minItems = min\n }\n if (max !== undefined) {\n field.maxItems = max\n }\n }\n // A default the field itself would refuse is left out, not shown.\n if (raw.default !== undefined && checkValue(name, field, raw.default) === undefined) {\n field.default = Array.isArray(raw.default)\n ? [...(raw.default as string[])]\n : (raw.default as string | number | boolean)\n }\n return { ok: true, value: field }\n}\n\n/**\n * The form a server asked for, reduced to what the specification allows a form to be: a flat\n * object of strings, numbers, booleans and selects. Anything else - a nested object, a list of\n * objects, a type union, an unknown format, too many fields or options, a name that could not\n * be sent back verbatim - is refused with a reason (the caller declines the request). Keywords\n * outside the subset are dropped; titles and descriptions are cleaned and capped.\n */\nexport const normalizeMcpElicitationSchema = (raw: unknown): Checked<McpElicitationSchema> => {\n if (!isPlainObject(raw) || raw.type !== 'object' || !isPlainObject(raw.properties)) {\n return bad('the form is not an object with properties')\n }\n const names = Object.keys(raw.properties)\n if (names.length > MCP_ELICITATION_MAX_FIELDS) {\n return bad(`the form has more than ${MCP_ELICITATION_MAX_FIELDS} fields`)\n }\n const properties: Record<string, McpElicitationFieldSchema> = {}\n for (const name of names) {\n if (!isVerbatim(name) || UNSAFE_NAMES.has(name)) {\n return bad(`the form has a field name that cannot be used (${fieldLabel(name)})`)\n }\n const field = normalizeField(name, raw.properties[name])\n if (!field.ok) {\n return field\n }\n properties[name] = field.value\n }\n const schema: McpElicitationSchema = { type: 'object', properties }\n if (raw.required !== undefined) {\n if (!Array.isArray(raw.required)) {\n return bad('the form\\'s \"required\" is not a list')\n }\n const required: string[] = []\n for (const name of raw.required) {\n if (typeof name !== 'string' || !Object.hasOwn(properties, name)) {\n return bad('the form requires a field it does not have')\n }\n if (!required.includes(name)) {\n required.push(name)\n }\n }\n if (required.length) {\n schema.required = required\n }\n }\n return { ok: true, value: schema }\n}\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]', '::1'])\n\n/**\n * A link a server wants the user to open, or why it is refused. Only https - or http on a\n * loopback host, the rule the OAuth code of these packages applies (`assertSecureOAuthUrl`) -\n * and no credentials in it. Parsed, not pattern-matched; the result is the parsed form (an\n * internationalised host shows as punycode). The link is never fetched or opened here.\n */\nexport const checkMcpElicitationUrl = (raw: unknown): Checked<string> => {\n if (typeof raw !== 'string' || !raw || raw.length > MCP_ELICITATION_URL_MAX_CHARS) {\n return bad('the link is missing or too long')\n }\n if (raw.replace(INVISIBLE, '') !== raw || /\\s/.test(raw)) {\n return bad('the link contains characters that cannot be shown')\n }\n let parsed: URL\n try {\n parsed = new URL(raw)\n } catch {\n return bad('the link is not a valid URL')\n }\n if (\n parsed.protocol !== 'https:' &&\n !(parsed.protocol === 'http:' && LOOPBACK_HOSTS.has(parsed.hostname))\n ) {\n return bad('only https links are accepted (http on a loopback host)')\n }\n if (parsed.username || parsed.password) {\n return bad('the link carries credentials')\n }\n return { ok: true, value: parsed.href }\n}\n\ntype ParsedRequest =\n | {\n ok: true\n mode: 'form'\n message: string\n requestedSchema: McpElicitationSchema\n }\n | { ok: true; mode: 'url'; message: string; url: string; elicitationId?: string }\n | { ok: false; reason: McpElicitationReason; detail: string }\n\n/**\n * The params of an `elicitation/create` request as a host may be shown them, or why the request\n * is declined before anybody is asked.\n */\nexport const parseMcpElicitationParams = (\n params: unknown,\n options: Pick<McpResolvedElicitationOptions, 'url'>,\n): ParsedRequest => {\n if (!isPlainObject(params)) {\n return { ok: false, reason: 'invalid-request', detail: 'the request has no parameters' }\n }\n const mode = params.mode ?? 'form'\n if (mode !== 'form' && mode !== 'url') {\n return { ok: false, reason: 'unsupported-mode', detail: 'the mode is neither form nor url' }\n }\n if (typeof params.message !== 'string') {\n return { ok: false, reason: 'invalid-request', detail: 'the request has no message' }\n }\n const message = cleanMcpElicitationText(params.message, MCP_ELICITATION_MESSAGE_MAX_CHARS)\n if (mode === 'url') {\n if (!options.url) {\n return {\n ok: false,\n reason: 'unsupported-mode',\n detail: 'URL mode was not offered (elicitation.url)',\n }\n }\n const url = checkMcpElicitationUrl(params.url)\n if (!url.ok) {\n return { ok: false, reason: 'insecure-url', detail: url.reason }\n }\n const elicitationId = label(params.elicitationId, MCP_ELICITATION_NAME_MAX_CHARS)\n return {\n ok: true,\n mode,\n message,\n url: url.value,\n ...(elicitationId ? { elicitationId } : {}),\n }\n }\n const schema = normalizeMcpElicitationSchema(params.requestedSchema)\n if (!schema.ok) {\n return { ok: false, reason: 'unsupported-schema', detail: schema.reason }\n }\n return { ok: true, mode, message, requestedSchema: schema.value }\n}\n\n// ── the answer, before a server sees it ──────────────────────────────────\n\nconst optionValues = (field: McpElicitationFieldSchema): string[] | undefined =>\n field.enum ?? field.oneOf?.map((o) => o.const)\n\nconst validFormat = (format: McpElicitationFieldSchema['format'], value: string): boolean => {\n switch (format) {\n case 'email':\n return /^[^@\\s]+@[^@\\s]+$/.test(value)\n case 'uri':\n try {\n return Boolean(new URL(value))\n } catch {\n return false\n }\n case 'date':\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(value) && !Number.isNaN(Date.parse(value))\n case 'date-time':\n return /^\\d{4}-\\d{2}-\\d{2}T/.test(value) && !Number.isNaN(Date.parse(value))\n default:\n return true\n }\n}\n\n// Why a value does not fit its field, or undefined when it does. Never quotes the value.\nconst checkValue = (\n name: string,\n field: McpElicitationFieldSchema,\n value: unknown,\n): string | undefined => {\n const at = `field ${fieldLabel(name)}`\n switch (field.type) {\n case 'string': {\n if (typeof value !== 'string') {\n return `${at} must be a text`\n }\n const options = optionValues(field)\n if (options) {\n return options.includes(value) ? undefined : `${at} is not one of the options`\n }\n if (value.length > (field.maxLength ?? MCP_ELICITATION_VALUE_MAX_CHARS)) {\n return `${at} is too long`\n }\n if (field.minLength !== undefined && value.length < field.minLength) {\n return `${at} is too short`\n }\n return validFormat(field.format, value)\n ? undefined\n : `${at} is not a valid ${field.format ?? 'text'}`\n }\n case 'number':\n case 'integer': {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n return `${at} must be a number`\n }\n if (field.type === 'integer' && !Number.isInteger(value)) {\n return `${at} must be a whole number`\n }\n if (field.minimum !== undefined && value < field.minimum) {\n return `${at} is below the minimum`\n }\n return field.maximum !== undefined && value > field.maximum\n ? `${at} is above the maximum`\n : undefined\n }\n case 'boolean':\n return typeof value === 'boolean' ? undefined : `${at} must be true or false`\n case 'array': {\n const options = field.items?.enum ?? field.items?.anyOf?.map((o) => o.const) ?? []\n if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) {\n return `${at} must be a list of options`\n }\n if (!value.every((item) => options.includes(item as string))) {\n return `${at} holds something that is not one of the options`\n }\n if (field.minItems !== undefined && value.length < field.minItems) {\n return `${at} has too few selected`\n }\n return (field.maxItems !== undefined && value.length > field.maxItems) ||\n value.length > MCP_ELICITATION_MAX_OPTIONS\n ? `${at} has too many selected`\n : undefined\n }\n }\n}\n\n/**\n * An accepted form, checked against the schema it answers: every value of the type and within\n * the limits its field states, every required field there, and NO field the form did not ask\n * for (what the server did not request is not sent to it). The result is a fresh object holding\n * only the form's own fields. A refusal names the field and the rule, never the value.\n */\nexport const validateMcpElicitationContent = (\n schema: McpElicitationSchema,\n content: unknown,\n): Checked<McpElicitationContent> => {\n if (content !== undefined && !isPlainObject(content)) {\n return bad('the answer is not an object of field values')\n }\n const given = content ?? {}\n for (const name of Object.keys(given)) {\n if (!Object.hasOwn(schema.properties, name)) {\n return bad(`${fieldLabel(name)} is not a field of the form`)\n }\n }\n const required = new Set(schema.required ?? [])\n const value: McpElicitationContent = {}\n for (const [name, field] of Object.entries(schema.properties)) {\n const answered = Object.hasOwn(given, name) ? given[name] : undefined\n if (answered === undefined || answered === null) {\n if (required.has(name)) {\n return bad(`field ${fieldLabel(name)} is required`)\n }\n continue\n }\n const problem = checkValue(name, field, answered)\n if (problem) {\n return bad(problem)\n }\n value[name] = Array.isArray(answered)\n ? [...(answered as string[])]\n : (answered as string | number | boolean)\n }\n return { ok: true, value }\n}\n\n// ── asking ───────────────────────────────────────────────────────────────\n\n/** One tool call, as far as its questions are concerned. Made per call, by the connector. */\nexport interface McpElicitationCall {\n server: string\n /** The tool's name as the model called it. */\n tool: string\n /** The run's abort signal (and the step's time limit), when the call has one. */\n signal?: AbortSignal\n /** Where the two events go; absent outside a run. */\n emit?: (event: McpElicitationEvent) => void\n runId?: string\n /** Set when the call is made by a helper (a subagent), not by the run itself. */\n subagent?: { id: string; depth: number }\n /** The questions asked in this run so far: one object per run, shared by its calls. */\n run: { count: number }\n /** The questions asked in this call so far. */\n asked: number\n /**\n * Set by the first answer nobody decided: the call then FAILS with this text, whatever the\n * server answers afterwards, and nothing is asked or sent again on its behalf.\n */\n failure?: string\n /** Called around the wait for the host (true: waiting), so a call's own clock can stop. */\n onWait?: (waiting: boolean) => void\n /**\n * Stops the time limits of the run the call belongs to (its step's, and those of the subagent\n * tools above it) for the length of the wait for the host; returns what starts them again.\n * The wait keeps its own bound, `timeoutMs`, and a stop of the run still ends it at once.\n */\n pause?: () => () => void\n}\n\nexport interface McpElicitationDeps {\n handler: McpElicitationHandler\n options: McpResolvedElicitationOptions\n log: (level: 'info' | 'warn' | 'error', message: string) => void\n}\n\nconst newId = (): string => {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto\n return typeof c?.randomUUID === 'function'\n ? c.randomUUID()\n : `e-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n}\n\nconst isTimeoutAbort = (signal: AbortSignal | undefined): boolean =>\n (signal?.reason as { name?: unknown } | undefined)?.name === 'TimeoutError'\n\nconst abortReason = (signal: AbortSignal | undefined): unknown => {\n if (signal?.reason !== undefined) {\n return signal.reason\n }\n const err = new Error('Aborted')\n err.name = 'AbortError'\n return err\n}\n\n/** What a tool call fails with when one of its questions was answered without the host deciding. */\nexport const mcpElicitationFailure = (\n tool: string,\n reason: McpElicitationReason,\n options: McpResolvedElicitationOptions,\n detail?: string,\n): string => {\n const why: Record<McpElicitationReason, string> = {\n 'unsupported-schema': `the form it sent cannot be shown (${detail ?? 'unsupported schema'})`,\n 'unsupported-mode': `it asked in a way this client does not offer (${detail ?? 'unsupported mode'})`,\n 'insecure-url': `the link it sent was refused (${detail ?? 'not https'})`,\n 'invalid-request': `its request was malformed (${detail ?? 'invalid'})`,\n subagent:\n 'a helper is not allowed to ask the user (elicitation.subagents); the question was not shown',\n 'cap-per-call': `it had already asked ${options.maxPerToolCall} time(s) in this call (elicitation.maxPerToolCall)`,\n 'cap-per-run': `${options.maxPerRun} question(s) were already asked in this run (elicitation.maxPerRun)`,\n 'handler-error': 'the host could not ask the user (its elicitation handler failed)',\n timeout: `nobody answered within ${options.timeoutMs} ms (elicitation.timeoutMs)`,\n 'invalid-answer': `the answer did not fit the form (${detail ?? 'invalid'}) and was not sent`,\n aborted: 'the run was stopped',\n 'step-timeout': \"the tool call's time limit ended before the question was answered\",\n 'after-failure': 'an earlier question of the same call had already failed',\n 'no-tool-call': 'no tool call was in progress',\n }\n return (\n `MCP tool \"${tool}\" did not finish: the server asked the user for input, and ${why[reason]}. ` +\n `The call was not repeated; do not call the tool again only because of this.`\n )\n}\n\ntype WireAnswer = { action: 'accept' | 'decline' | 'cancel'; content?: McpElicitationContent }\n\n/**\n * Answer one `elicitation/create` (its `params`, from either revision) on behalf of a tool call.\n *\n * The host's callback is called only when every guard passes: the request is well-formed and\n * within what a form may be, the call is not a helper's (unless allowed), the caps are not\n * reached, the call has not failed already. Its answer is checked against the form before it is\n * returned. In every other case the answer is made here (`decline` for a request that cannot be\n * shown, `cancel` otherwise), `call.failure` is set, and the caller fails the tool call with it.\n *\n * Throws only when the call's own signal aborted (the run was stopped, or its time was already\n * spent when the question came): the reason is rethrown, as for any aborted tool call. While\n * the host is asked, the limits of the run are stopped (`call.pause`): the wait is bounded by\n * `timeoutMs` and by a stop of the run, not by the step it belongs to.\n */\nexport const answerMcpElicitation = async (\n deps: McpElicitationDeps,\n call: McpElicitationCall,\n params: unknown,\n): Promise<WireAnswer> => {\n const { options, log } = deps\n const id = newId()\n const where = `[mcp] ${call.server}: elicitation during ${call.tool}`\n const answered = (\n action: WireAnswer['action'],\n automatic: boolean,\n reason?: McpElicitationReason,\n fields?: string[],\n ): void =>\n call.emit?.({\n type: 'mcp.elicitation-answered',\n id,\n server: call.server,\n tool: call.tool,\n action,\n automatic,\n ...(reason ? { reason } : {}),\n ...(fields ? { fields } : {}),\n })\n // Nobody decided: the answer is made here, and the tool call fails with the reason.\n const refuse = (reason: McpElicitationReason, detail?: string): WireAnswer => {\n const action = (\n ['unsupported-schema', 'unsupported-mode', 'insecure-url', 'invalid-request'] as string[]\n ).includes(reason)\n ? 'decline'\n : 'cancel'\n call.failure ??= mcpElicitationFailure(call.tool, reason, options, detail)\n log(\n 'warn',\n `${where} answered \"${action}\" automatically - ${reason}${detail ? `: ${detail}` : ''}`,\n )\n answered(action, true, reason)\n return { action }\n }\n\n if (call.failure) {\n return refuse('after-failure')\n }\n const parsed = parseMcpElicitationParams(params, options)\n if (!parsed.ok) {\n return refuse(parsed.reason, parsed.detail)\n }\n if (call.subagent && !options.subagents) {\n return refuse('subagent')\n }\n if (call.asked >= options.maxPerToolCall) {\n return refuse('cap-per-call')\n }\n if (call.run.count >= options.maxPerRun) {\n return refuse('cap-per-run')\n }\n if (call.signal?.aborted) {\n answered('cancel', true, isTimeoutAbort(call.signal) ? 'step-timeout' : 'aborted')\n throw abortReason(call.signal)\n }\n call.asked += 1\n call.run.count += 1\n\n const request: McpElicitationRequest = {\n id,\n server: call.server,\n tool: call.tool,\n mode: parsed.mode,\n message: parsed.message,\n ...(parsed.mode === 'form' ? { requestedSchema: parsed.requestedSchema } : { url: parsed.url }),\n ...(parsed.mode === 'url' && parsed.elicitationId\n ? { elicitationId: parsed.elicitationId }\n : {}),\n ...(call.runId ? { runId: call.runId } : {}),\n ...(call.subagent ? { subagent: call.subagent } : {}),\n }\n call.emit?.({\n type: 'mcp.elicitation-requested',\n id,\n server: call.server,\n tool: call.tool,\n mode: request.mode,\n message: request.message,\n ...(request.requestedSchema ? { requestedSchema: request.requestedSchema } : {}),\n ...(request.url ? { url: request.url } : {}),\n ...(call.subagent ? { subagent: call.subagent } : {}),\n })\n\n // The host's own signal: aborted when the wait ends for any reason, so a prompt left open\n // (a dialog, a terminal question) can be taken down.\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n let onAbort: (() => void) | undefined\n type Outcome =\n | { kind: 'answer'; value: unknown }\n | { kind: 'error'; error: unknown }\n | { kind: 'timeout' }\n | { kind: 'aborted' }\n call.onWait?.(true)\n // A person is being asked: the step's limit is about models and tools, and does not run\n // meanwhile. It goes on, with the time it had left, the moment the wait is over.\n const resume = call.pause?.()\n const outcome = await new Promise<Outcome>((resolve) => {\n if (options.timeoutMs > 0) {\n timer = setTimeout(() => resolve({ kind: 'timeout' }), options.timeoutMs)\n }\n onAbort = () => resolve({ kind: 'aborted' })\n call.signal?.addEventListener('abort', onAbort, { once: true })\n Promise.resolve()\n .then(() => deps.handler(request, { signal: controller.signal }))\n .then(\n (value) => resolve({ kind: 'answer', value }),\n (error: unknown) => resolve({ kind: 'error', error }),\n )\n })\n resume?.()\n call.onWait?.(false)\n if (timer) {\n clearTimeout(timer)\n }\n if (onAbort) {\n call.signal?.removeEventListener('abort', onAbort)\n }\n controller.abort()\n\n if (outcome.kind === 'aborted') {\n const reason: McpElicitationReason = isTimeoutAbort(call.signal) ? 'step-timeout' : 'aborted'\n call.failure ??= mcpElicitationFailure(call.tool, reason, options)\n if (reason === 'step-timeout') {\n // Not the step's own limit, which does not run while the host is asked (`call.pause`): a\n // time limit put on the call's signal from outside, the run's signal included.\n log(\n 'warn',\n `${where}: a time limit on the tool call's signal ended while the question was waiting for an answer; only the step's own limit stops while a person is asked, not a limit on the run's signal`,\n )\n }\n answered('cancel', true, reason)\n throw abortReason(call.signal)\n }\n if (outcome.kind === 'timeout') {\n return refuse('timeout')\n }\n if (outcome.kind === 'error') {\n // The handler's message is the host's own text and may quote what the user typed: only\n // the kind of error is said.\n const name = (outcome.error as { name?: unknown } | null)?.name\n return refuse('handler-error', typeof name === 'string' ? name.slice(0, 40) : 'error')\n }\n const result = outcome.value as { action?: unknown; content?: unknown } | null | undefined\n const action = result?.action\n if (action === 'decline' || action === 'cancel') {\n answered(action, false)\n return { action }\n }\n if (action !== 'accept') {\n return refuse('invalid-answer', 'the handler returned no accept, decline or cancel')\n }\n if (parsed.mode === 'url') {\n // Consent to open the link; a URL-mode answer carries no content.\n answered('accept', false)\n return { action: 'accept' }\n }\n const content = validateMcpElicitationContent(parsed.requestedSchema, result?.content)\n if (!content.ok) {\n return refuse('invalid-answer', content.reason)\n }\n answered('accept', false, undefined, Object.keys(content.value))\n return { action: 'accept', content: content.value }\n}\n\n// ── driving a tool call ──────────────────────────────────────────────────\n\n/** What a later leg of a 2026-07-28 tool call adds to its params. */\nexport interface McpInputRequiredRetry {\n inputResponses?: Record<string, unknown>\n requestState?: string\n}\n\n/** One request of a tool call, as the connector sends it. */\nexport interface McpToolCallLeg {\n /** The call's signal for this leg. */\n signal?: AbortSignal\n /** 2026-07-28, after an `input_required` answer: what to add to the original params. */\n retry?: McpInputRequiredRetry\n /** 2025 revisions: the request's own timeout is replaced by the session's pausable one. */\n ownTimeout?: boolean\n}\n\nconst sleep = (ms: number, signal: AbortSignal | undefined): Promise<void> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortReason(signal))\n return\n }\n const onAbort = (): void => {\n clearTimeout(timer)\n reject(abortReason(signal))\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n\nconst isInputRequired = (\n value: unknown,\n): value is { resultType: 'input_required'; inputRequests?: unknown; requestState?: unknown } =>\n isPlainObject(value) && value.resultType === 'input_required'\n\n/** What a tool call fails with when a 2026-07-28 server asks for something that is not a question to the user. */\nexport const mcpInputRequestUnsupportedMessage = (toolName: string, method: unknown): string =>\n `MCP tool \"${toolName}\" did not finish: the server asked for input this client does not provide ` +\n `(${cleanMcpElicitationText(typeof method === 'string' ? method : 'a malformed request', 60)}; only elicitation is answered). ` +\n `The call was not repeated.`\n\nexport const mcpInputRequiredRoundsMessage = (toolName: string): string =>\n `MCP tool \"${toolName}\" did not finish: the server still asked for input after ` +\n `${MCP_INPUT_REQUIRED_MAX_ROUNDS} rounds. The call was not repeated.`\n\n/** A tool call that ran past MCP_TOOL_CALL_TIMEOUT_MS of its own time (2025 revisions). */\nexport const mcpToolCallTimeoutMessage = (toolName: string): string =>\n `MCP tool \"${toolName}\" timed out after ${MCP_TOOL_CALL_TIMEOUT_MS} ms (not counting the time ` +\n `its questions waited for the user).`\n\nexport interface McpElicitationCallInfo {\n /** The tool's name as the model called it (events, the host's request). */\n tool: string\n /** The tool's own name on the server (error texts, as the other MCP errors use). */\n toolName: string\n signal?: AbortSignal\n emit?: (event: McpElicitationEvent) => void\n runId?: string\n subagent?: { id: string; depth: number }\n /** The run's counter; absent outside a run (the call then counts alone). */\n run?: { count: number }\n /** Stops the run's time limits while the host is asked; returns what starts them again. */\n pause?: () => () => void\n}\n\nexport interface McpElicitationSession {\n /** The `elicitation` capability to declare. */\n capability: { form: Record<string, never>; url?: Record<string, never> }\n /**\n * 2025 revisions: answer an `elicitation/create` request the server sent. It belongs to the\n * tool call in flight (there is exactly one: `call` runs them one at a time); with none in\n * flight it is cancelled.\n */\n onRequest: (params: unknown) => Promise<WireAnswer>\n /**\n * Make one tool call. `send` issues one `tools/call` request and resolves with its result -\n * on 2026-07-28 possibly an `input_required` one, which is answered here and followed by\n * another leg. Rejects with McpElicitationError when a question was answered automatically.\n */\n call: <T>(\n era: 'legacy' | 'modern',\n info: McpElicitationCallInfo,\n send: (leg: McpToolCallLeg) => Promise<T>,\n ) => Promise<T>\n}\n\n/**\n * The elicitation side of one connection to one server.\n *\n * 2025 revisions: the server's question is a request of its own that does not say which tool\n * call it belongs to, so calls made through a session run ONE AT A TIME - the call in flight is\n * the one that asks. The call's own clock (MCP_TOOL_CALL_TIMEOUT_MS) stops while a question\n * waits. After an automatic answer the server's result is discarded and the call fails; a\n * server that asks again after that has its call aborted.\n *\n * 2026-07-28: the question is the call's own `input_required` result. Each is answered and the\n * call is sent again with the answers and the server's `requestState`, byte for byte - the\n * server's way of continuing ONE call, not a second call. After an automatic answer nothing is\n * sent again.\n */\nexport const createMcpElicitationSession = (\n server: string,\n deps: McpElicitationDeps,\n): McpElicitationSession => {\n let current: (McpElicitationCall & { abort: (reason: unknown) => void }) | undefined\n let tail: Promise<void> = Promise.resolve()\n\n // One at a time; waiting for the turn ends when the caller's signal aborts.\n const acquire = async (signal: AbortSignal | undefined): Promise<() => void> => {\n const before = tail\n let release!: () => void\n tail = new Promise<void>((resolve) => {\n release = resolve\n })\n try {\n await new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortReason(signal))\n return\n }\n const onAbort = (): void => reject(abortReason(signal))\n signal?.addEventListener('abort', onAbort, { once: true })\n void before.then(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n })\n })\n } catch (err) {\n // Give the turn up without breaking the chain for those behind.\n void before.then(release)\n throw err\n }\n return release\n }\n\n const newCall = (info: McpElicitationCallInfo, signal?: AbortSignal): McpElicitationCall => ({\n server,\n tool: info.tool,\n ...(signal ? { signal } : {}),\n ...(info.emit ? { emit: info.emit } : {}),\n ...(info.runId ? { runId: info.runId } : {}),\n ...(info.subagent ? { subagent: info.subagent } : {}),\n ...(info.pause ? { pause: info.pause } : {}),\n run: info.run ?? { count: 0 },\n asked: 0,\n })\n\n const callLegacy = async <T>(\n info: McpElicitationCallInfo,\n send: (leg: McpToolCallLeg) => Promise<T>,\n ): Promise<T> => {\n const release = await acquire(info.signal)\n const controller = new AbortController()\n const onOuterAbort = (): void => controller.abort(abortReason(info.signal))\n info.signal?.addEventListener('abort', onOuterAbort, { once: true })\n // The call's own clock: it runs only while no question is waiting.\n let left = MCP_TOOL_CALL_TIMEOUT_MS\n let startedAt = Date.now()\n let timedOut = false\n let timer: ReturnType<typeof setTimeout> | undefined\n const start = (): void => {\n startedAt = Date.now()\n timer = setTimeout(\n () => {\n timedOut = true\n controller.abort(new McpElicitationError(mcpToolCallTimeoutMessage(info.toolName)))\n },\n Math.max(0, left),\n )\n }\n const stop = (): void => {\n if (timer) {\n clearTimeout(timer)\n timer = undefined\n left -= Date.now() - startedAt\n }\n }\n const call = Object.assign(newCall(info, controller.signal), {\n abort: (reason: unknown) => controller.abort(reason),\n onWait: (waiting: boolean) => (waiting ? stop() : start()),\n })\n current = call\n try {\n if (info.signal?.aborted) {\n throw abortReason(info.signal)\n }\n start()\n const result = await send({ signal: controller.signal, ownTimeout: true })\n if (call.failure) {\n throw new McpElicitationError(call.failure)\n }\n return result\n } catch (err) {\n // The caller's own abort stays what it was.\n if (info.signal?.aborted) {\n throw err\n }\n if (call.failure) {\n throw new McpElicitationError(call.failure)\n }\n if (timedOut) {\n throw new McpElicitationError(mcpToolCallTimeoutMessage(info.toolName))\n }\n throw err\n } finally {\n stop()\n info.signal?.removeEventListener('abort', onOuterAbort)\n if (current === call) {\n current = undefined\n }\n release()\n }\n }\n\n const callModern = async <T>(\n info: McpElicitationCallInfo,\n send: (leg: McpToolCallLeg) => Promise<T>,\n ): Promise<T> => {\n const call = newCall(info, info.signal)\n let retry: McpInputRequiredRetry | undefined\n for (let round = 0; ; round += 1) {\n const result = await send({\n ...(info.signal ? { signal: info.signal } : {}),\n ...(retry ? { retry } : {}),\n })\n if (!isInputRequired(result)) {\n return result\n }\n if (round >= MCP_INPUT_REQUIRED_MAX_ROUNDS) {\n throw new McpElicitationError(mcpInputRequiredRoundsMessage(info.toolName))\n }\n const requests = isPlainObject(result.inputRequests)\n ? Object.entries(result.inputRequests)\n : []\n const state = typeof result.requestState === 'string' ? result.requestState : undefined\n if (requests.length === 0 && state === undefined) {\n throw new McpElicitationError(\n mcpInputRequestUnsupportedMessage(info.toolName, 'an empty input_required result'),\n )\n }\n // Checked before anybody is asked: a round that also wants something this client does\n // not provide (sampling, roots) is not answered in part.\n for (const [, entry] of requests) {\n if (!isPlainObject(entry) || entry.method !== 'elicitation/create') {\n throw new McpElicitationError(\n mcpInputRequestUnsupportedMessage(\n info.toolName,\n isPlainObject(entry) ? entry.method : undefined,\n ),\n )\n }\n }\n // Keys are the server's: a prototype-less object, so none of them can be special.\n const responses = Object.create(null) as Record<string, unknown>\n for (const [key, entry] of requests) {\n const answer = await answerMcpElicitation(\n deps,\n call,\n (entry as Record<string, unknown>).params,\n )\n if (call.failure) {\n // Nobody decided: nothing is sent again.\n throw new McpElicitationError(call.failure)\n }\n responses[key] = answer\n }\n if (requests.length === 0) {\n // Only \"call me again\": do not spin.\n await sleep(MCP_INPUT_REQUIRED_PACING_MS, info.signal)\n }\n retry = {\n ...(requests.length ? { inputResponses: responses } : {}),\n ...(state !== undefined ? { requestState: state } : {}),\n }\n }\n }\n\n return {\n capability: mcpElicitationCapability(deps.options),\n onRequest: async (params) => {\n const call = current\n if (!call) {\n deps.log(\n 'warn',\n `[mcp] ${server}: the server asked the user for input while no tool call was in progress; cancelled`,\n )\n return { action: 'cancel' }\n }\n const failedBefore = call.failure !== undefined\n const answer = await answerMcpElicitation(deps, call, params)\n if (failedBefore) {\n // It was told the call is over and asks again: stop waiting for it.\n call.abort(new McpElicitationError(call.failure as string))\n }\n return answer\n },\n call: (era, info, send) => (era === 'modern' ? callModern(info, send) : callLegacy(info, send)),\n }\n}\n","// 2026-07-28: the `subscriptions/listen` stream that carries a server's tool list change notices,\n// kept open for the life of the connection.\n//\n// That revision has no stream a server may write to unasked: `notifications/tools/list_changed`\n// arrives only on a `subscriptions/listen` stream the client opened, and the SDK does not open it\n// again when it ends. This file does, with backoff, and once a stream is back it reports the tool\n// list as changed - a change made while no stream was open was announced to nobody - through the\n// same callback the notice itself calls, so whoever listens sees exactly what a notice causes.\n//\n// - Retried: a stream that DROPPED (no result: \"an unexpected disconnect, which the client MAY\n// treat as a trigger to reconnect\") and one the server CLOSED with its result (the server's own\n// initiative, \"for example, during shutdown\": on a stateless revision the process that ends a\n// subscription is not the service - the next request may reach another - and a server that no\n// longer takes listeners says so to the next attempt, which is final). A failed attempt is\n// retried too, unless its error is final.\n// - Final, never retried: 401 / 403 (authorization is the OAuth flow's job, not a loop's), 404 /\n// 405 / -32601 (the server does not offer the method), -32602 (it refuses the request as made),\n// a client that is not connected, and an acknowledgement that leaves `toolsListChanged` out.\n// - The delay before attempt n: MCP_LISTEN_RETRY_BASE_MS doubled n - 1 times, at most\n// MCP_LISTEN_RETRY_MAX_MS, less a random share of up to half (so many clients that lost one\n// server do not come back in step). The count goes back to zero only when a stream stayed up\n// MCP_LISTEN_STABLE_MS: a stream that is acknowledged and lost at once counts against it, so a\n// flapping server is tried MCP_LISTEN_MAX_ATTEMPTS times in a row and then given up on.\n// - Logs: one `warn` per end or failed attempt (the attempt and the delay; past the last attempt\n// the same line says it gave up), one `info` when a stream is back. Nothing after `stop()`.\n// - `stop()` takes down a pending retry and the stability timer and gives up an attempt in\n// flight. An acknowledged stream is ended by the connection's own close (no extra request).\n//\n// Pure, no imports: the listen call and the log are given; the timers are `setTimeout`'s, or a\n// test's through the seam below. This file is a COPY, byte for byte, of the sibling package's (Node: `@dudko.dev/agent` `src/mcp-listen.ts`, browser:\n// `@dudko.dev/agent-web` `src/mcp/listen.ts`). Change both; `tests/mcp-listen.test.ts` of the\n// Node package compares them.\n\n/** The first delay: attempt 1 waits at most this long. */\nexport const MCP_LISTEN_RETRY_BASE_MS = 1_000\n/** The longest delay between two attempts. */\nexport const MCP_LISTEN_RETRY_MAX_MS = 60_000\n/** A stream that stayed up this long resets the count: the next loss starts at the first delay. */\nexport const MCP_LISTEN_STABLE_MS = 60_000\n/** Attempts in a row (failed, or lost before they were stable) before this connection gives up. */\nexport const MCP_LISTEN_MAX_ATTEMPTS = 10\n\n/** The SDK's `McpSubscription`, as far as this file reads it. */\nexport interface McpListenSubscription {\n /** The filter the server agreed to (its acknowledgement). */\n readonly honoredFilter: { toolsListChanged?: boolean }\n /** How the stream ended: `local` (this side), `graceful` (the server's result), `remote`. */\n readonly closed: Promise<'local' | 'graceful' | 'remote'>\n}\n\nexport interface McpListenDeps {\n /** The server's name, for the log. */\n server: string\n /** Open one stream; resolves once the server acknowledged it. `signal` gives the attempt up. */\n listen: (signal: AbortSignal) => Promise<McpListenSubscription>\n /** Call `fire` after `ms`; the result takes the timer down. Default: `setTimeout` (or the seam). */\n timer?: (ms: number, fire: () => void) => { cancel: () => void }\n log: (level: 'info' | 'warn', message: string) => void\n /** A stream is open again after one ended or failed: report the tool list as changed. */\n onResubscribed: () => void\n /** The source of the jitter (default `Math.random`). */\n random?: () => number\n}\n\nexport interface McpListenSupervisor {\n /** Open the first stream. Resolves once it was acknowledged, or the attempt failed. */\n start: () => Promise<void>\n /** For good: no retry, no log, nothing pending. Safe to call twice. */\n stop: () => void\n}\n\n/** The delay before attempt `attempt` (1, 2, ...), `random` in [0, 1) taking up to half off. */\nexport const mcpListenRetryDelay = (\n attempt: number,\n random: () => number = Math.random,\n): number => {\n const exponent = Math.max(0, Math.floor(attempt) - 1)\n const full = Math.min(MCP_LISTEN_RETRY_MAX_MS, MCP_LISTEN_RETRY_BASE_MS * 2 ** exponent)\n const drawn = random()\n const share = Number.isFinite(drawn) ? Math.min(1, Math.max(0, drawn)) : 0\n return Math.round(full - (full / 2) * share)\n}\n\n/**\n * Why a failed attempt must not be made again, or `undefined` when it may be. Read structurally:\n * the SDK's `SdkHttpError.status`, `ProtocolError.code` (a number), `SdkError.code` (a string),\n * `UnauthorizedError`'s name - a second copy of the SDK is another class.\n */\nexport const mcpListenFinalReason = (err: unknown): string | undefined => {\n if (typeof err !== 'object' || err === null) return undefined\n const { name, status, code } = err as { name?: unknown; status?: unknown; code?: unknown }\n if (name === 'UnauthorizedError' || status === 401 || status === 403) {\n return 'the server refused the authorization'\n }\n if (\n status === 404 ||\n status === 405 ||\n code === -32601 ||\n code === 'METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION'\n ) {\n return 'the server does not offer subscriptions/listen'\n }\n if (code === -32602) return 'the server refused the request'\n if (code === 'NOT_CONNECTED') return 'the connection is closed'\n return undefined\n}\n\n/** Where the timers are set: the globals, looked up at each call (so mocked timers apply). */\ninterface McpListenTimeSource {\n set: (fire: () => void, ms: number) => unknown\n clear: (handle: unknown) => void\n}\n\nconst REAL_TIME: McpListenTimeSource = {\n set: (fire, ms) => setTimeout(fire, ms),\n clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),\n}\n\n/**\n * A TEST seam, not an API: a test that puts a time source under this key of `globalThis` before\n * a connection is made moves this file's timers itself - the retry and the stability timer - so\n * the whole schedule runs on virtual time against real servers. A key of its own, not the wait\n * clock's (`wait-clock.ts`): that one is for the deadlines of runs, and its tests ask whether any\n * deadline is running, which a listen timer is not. Nothing exports it; it gives no power the\n * globals it stands for do not.\n */\nconst TEST_TIME = Symbol.for('@dudko.dev/agent:mcp-listen-test-time')\n\nconst timeSource = (): McpListenTimeSource => {\n const test = (globalThis as unknown as Record<symbol, Partial<McpListenTimeSource> | undefined>)[\n TEST_TIME\n ]\n return typeof test?.set === 'function' && typeof test.clear === 'function'\n ? (test as McpListenTimeSource)\n : REAL_TIME\n}\n\nconst seconds = (ms: number): string => `${(ms / 1000).toFixed(1)} s`\n\nconst messageOf = (err: unknown): string => (err instanceof Error ? err.message : String(err))\n\nexport const createMcpListenSupervisor = (deps: McpListenDeps): McpListenSupervisor => {\n const { server, log } = deps\n const random = deps.random ?? Math.random\n // Read when the supervisor is made, as the wait clock reads its own seam.\n const time = timeSource()\n const timer =\n deps.timer ??\n ((ms: number, fire: () => void) => {\n const handle = time.set(fire, ms)\n return { cancel: () => time.clear(handle) }\n })\n let started = false\n let stopped = false\n // Attempts since the start, or since the last stream that stayed up MCP_LISTEN_STABLE_MS.\n let attempts = 0\n let retry: { cancel: () => void } | undefined\n let stable: { cancel: () => void } | undefined\n let inFlight: AbortController | undefined\n let current: McpListenSubscription | undefined\n\n // A stream ended or an attempt failed (`what` says which): the next attempt, or the end.\n const again = (what: string): void => {\n if (attempts >= MCP_LISTEN_MAX_ATTEMPTS) {\n log(\n 'warn',\n `[mcp] ${server}: ${what}; gave up after ${attempts} attempts in a row - tool list changes are not announced until the server is connected again (refreshServer still re-lists)`,\n )\n return\n }\n attempts += 1\n const delay = mcpListenRetryDelay(attempts, random)\n log(\n 'warn',\n `[mcp] ${server}: ${what}; listening again in ${seconds(delay)} (attempt ${attempts} of ${MCP_LISTEN_MAX_ATTEMPTS})`,\n )\n retry = timer(delay, () => {\n retry = undefined\n void open(true)\n })\n }\n\n const ended = (subscription: McpListenSubscription, cause: string): void => {\n if (stopped || current !== subscription) return\n current = undefined\n stable?.cancel()\n stable = undefined\n // Only this side closes a stream locally, and only when it is done with it.\n if (cause === 'local') return\n again(\n `the tool list change stream ended (${cause === 'graceful' ? 'closed by the server' : 'dropped'})`,\n )\n }\n\n const open = async (resubscribe: boolean): Promise<void> => {\n if (stopped) return\n const attempt = new AbortController()\n inFlight = attempt\n let subscription: McpListenSubscription\n try {\n subscription = await deps.listen(attempt.signal)\n } catch (err) {\n if (inFlight === attempt) inFlight = undefined\n if (stopped) return\n const final = mcpListenFinalReason(err)\n if (final) {\n log(\n 'warn',\n `[mcp] ${server}: could not subscribe to tool list changes - ${messageOf(err)}; not tried again: ${final}`,\n )\n return\n }\n again(`could not subscribe to tool list changes - ${messageOf(err)}`)\n return\n }\n if (inFlight === attempt) inFlight = undefined\n // Stopped while the acknowledgement was on its way: `stop()` already gave the attempt up.\n if (stopped) return\n if (subscription.honoredFilter?.toolsListChanged !== true) {\n log('info', `[mcp] ${server}: the server did not agree to announce tool list changes`)\n attempt.abort()\n return\n }\n current = subscription\n stable = timer(MCP_LISTEN_STABLE_MS, () => {\n stable = undefined\n attempts = 0\n })\n subscription.closed.then(\n (cause) => ended(subscription, cause),\n () => ended(subscription, 'remote'),\n )\n if (resubscribe) {\n log(\n 'info',\n `[mcp] ${server}: listening for tool list changes again (attempt ${attempts}); the tool list is read again`,\n )\n try {\n deps.onResubscribed()\n } catch (err) {\n log('warn', `[mcp] ${server}: the tool list change callback failed - ${messageOf(err)}`)\n }\n }\n }\n\n return {\n start: async () => {\n if (started || stopped) return\n started = true\n await open(false)\n },\n stop: () => {\n stopped = true\n retry?.cancel()\n retry = undefined\n stable?.cancel()\n stable = undefined\n inFlight?.abort()\n inFlight = undefined\n current = undefined\n },\n }\n}\n","import {\n auth,\n type FetchLike,\n type OAuthClientInformationMixed,\n type OAuthClientMetadata,\n type OAuthClientProvider,\n type OAuthDiscoveryState,\n type OAuthTokens,\n} from '@modelcontextprotocol/client'\nimport { IndexedDBVault, type VaultOptions } from '../secrets/vault.js'\nimport { postStorageChangeFrom } from '../sync/notices.js'\nimport { currentTab, type Tab } from '../sync/tab.js'\n\n/**\n * Browser-side OAuth 2.1 for remote MCP servers: Dynamic Client Registration\n * (RFC 7591) or a client ID metadata document (CIMD) - automatically or one of\n * them only (`registration`) - PKCE authorization-code flow, refresh-token\n * rotation, and the `iss` check on the way back (RFC 9207).\n *\n * The heavy lifting lives in the MCP SDK — `auth()` discovers the protected\n * resource (RFC 9728), registers the client if we have no client_id yet,\n * exchanges the code, and refreshes expired tokens; `StreamableHTTPClient-\n * Transport` retries any 401 through it. This module supplies the missing\n * half: WHERE the tokens, the registration, and the PKCE verifier are kept,\n * and HOW the user is sent to the authorization server.\n *\n * ── WHY NO AUTOMATIC NAVIGATION ──\n * `redirectToAuthorization` deliberately does NOT navigate by default. The SDK\n * can call it from deep inside a tool call, and throwing the user out of a\n * running agent would discard in-flight state. Instead the URL is recorded on\n * `authorizationUrl`, `connectMcpHttp` reports `needsAuthorization: true`, and\n * the app decides when to send the user there (a button, a popup, a redirect).\n * Pass `onRedirect` to opt into eager navigation.\n */\n\n/** Where an OAuth provider keeps its tokens / registration / PKCE verifier. */\nexport interface McpOAuthStorage {\n get(key: string): Promise<string | undefined>\n set(key: string, value: string): Promise<void>\n delete(key: string): Promise<void>\n}\n\n/**\n * Default storage: the same encrypted IndexedDB vault that holds provider API\n * keys (AES-GCM, non-extractable key). Read the threat model in\n * `secrets/vault.ts` — this protects tokens at rest, not against active XSS.\n */\nexport class VaultOAuthStorage implements McpOAuthStorage {\n /** The database the vault lives in, and the name its change notices go out under. */\n readonly dbName: string\n private readonly vault: IndexedDBVault\n private readonly tab: Tab\n\n constructor(opts: VaultOptions = {}) {\n this.dbName = opts.dbName ?? 'agent-web'\n this.vault = new IndexedDBVault({ ...opts, dbName: this.dbName })\n this.tab = currentTab()\n }\n\n get(key: string): Promise<string | undefined> {\n return this.vault.getSecret(key)\n }\n // An `oauth` notice to the other tabs once written: no key (a record's id holds the server's\n // URL), never a token.\n async set(key: string, value: string): Promise<void> {\n await this.vault.setSecret(key, value)\n postStorageChangeFrom(this.tab, this.dbName, { kind: 'oauth', op: 'put' })\n }\n async delete(key: string): Promise<void> {\n await this.vault.deleteSecret(key)\n postStorageChangeFrom(this.tab, this.dbName, { kind: 'oauth', op: 'delete' })\n }\n}\n\n/** Non-persistent storage for tests / SSR. Tokens die with the tab. */\nexport class MemoryOAuthStorage implements McpOAuthStorage {\n private readonly map = new Map<string, string>()\n\n async get(key: string): Promise<string | undefined> {\n return this.map.get(key)\n }\n async set(key: string, value: string): Promise<void> {\n this.map.set(key, value)\n }\n async delete(key: string): Promise<void> {\n this.map.delete(key)\n }\n}\n\n/**\n * How the OAuth client is registered with a server's authorization server\n * (`BrowserOAuthProviderOptions.registration`):\n *\n * - `'auto'` (the default): by the client ID metadata document (CIMD) when the\n * authorization server advertises `client_id_metadata_document_supported` and\n * a `clientMetadataUrl` is set, by dynamic client registration (DCR, RFC 7591)\n * otherwise. A client already in storage is used as it is.\n * - `'cimd'`: by the metadata document only. Needs `clientMetadataUrl`. An\n * authorization server that does not advertise support is refused before\n * anything is sent to its registration endpoint.\n * - `'dcr'`: by dynamic registration only, even with a `clientMetadataUrl` set:\n * the SDK is never shown the URL.\n *\n * The Node package has the same option, with the same names; change both.\n */\nexport type McpOAuthRegistration = 'auto' | 'cimd' | 'dcr'\n\n/** How a stored client was registered: see {@link BrowserOAuthProvider.registrationKind}. */\nexport type McpOAuthRegistrationKind = 'cimd' | 'dcr'\n\nexport interface BrowserOAuthProviderOptions {\n /** The MCP endpoint this provider authorizes against (the resource server). */\n serverUrl: string\n /**\n * Where the authorization server sends the user back. Must be a page of your\n * app that calls `readOAuthCallback()` + `finishMcpOAuth()`. Registered with\n * the AS via DCR, so it has to match byte-for-byte on the way back.\n */\n redirectUrl: string | URL\n /** `client_name` submitted during dynamic registration. */\n clientName?: string\n /** Fallback scope when the server's metadata advertises none. */\n scope?: string\n /** Merged over the defaults; use it for `software_id`, `contacts`, `application_type`, … */\n clientMetadata?: Partial<OAuthClientMetadata> & { application_type?: string }\n /**\n * URL of a client ID metadata document (CIMD) you host. When the\n * authorization server advertises `client_id_metadata_document_supported`,\n * this URL is used as the `client_id` and no dynamic registration is made;\n * otherwise registration runs as before. A registration already in storage\n * wins over both. Must be https with a non-root path, and the document served\n * there must list the same `redirect_uris` as `redirectUrl`. With\n * `registration: 'dcr'` it is never used as the `client_id`.\n */\n clientMetadataUrl?: string\n /**\n * How the client is registered: `'auto'` (default; as described for\n * `clientMetadataUrl`), `'cimd'` (the metadata document only: needs\n * `clientMetadataUrl`, and an authorization server without support is refused\n * before any registration request) or `'dcr'` (dynamic registration only).\n * A stored client of the other kind is not reused: it is forgotten, with the\n * tokens issued to it, and the user signs in again. See\n * {@link McpOAuthRegistration}.\n */\n registration?: McpOAuthRegistration\n /** Defaults to the encrypted IndexedDB vault. */\n storage?: McpOAuthStorage\n /** Treat an access token as expired this many seconds early. Default 30. */\n expirySkewSeconds?: number\n /** Called when the SDK wants the user at the authorization server. */\n onRedirect?: (url: URL) => void | Promise<void>\n}\n\ninterface StoredTokens {\n tokens: OAuthTokens\n /** Absolute ms timestamp derived from `expires_in` at save time. */\n expiresAt?: number\n}\n\nconst DEFAULT_SKEW_SECONDS = 30\n\n// Namespacing by origin+path+query keeps two MCP servers on the same host\n// (/mcp/docs vs /mcp/crm, or ?tenant=a vs ?tenant=b) from sharing a\n// registration or a token — one tenant's bearer must never be sent to another.\nconst namespaceFor = (serverUrl: string): string => {\n const u = new URL(serverUrl)\n return `mcp-oauth:${u.origin}${u.pathname.replace(/\\/+$/, '')}${u.search}`\n}\n\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1'])\n\n/**\n * OAuth over plaintext hands the bearer token to anyone on the path, so only\n * https — or a loopback host, where there is no network to sniff — is allowed.\n * Parsed rather than pattern-matched: `http://localhost.attacker.example/` is a\n * registrable host that a prefix match would wave through.\n */\nexport const assertSecureOAuthUrl = (url: string, label = 'MCP server'): void => {\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n throw new Error(`${label}: \"${url}\" is not a valid URL`)\n }\n if (parsed.protocol === 'https:' || LOOPBACK_HOSTS.has(parsed.hostname)) return\n throw new Error(\n `${label}: MCP OAuth requires https (or a loopback host) - refusing to send tokens to \"${url}\"`,\n )\n}\n\n/**\n * A client ID metadata document URL is used as the `client_id`, and the\n * authorization server fetches it: it has to be https with a path of its own\n * (a bare origin identifies a site, not a client). Checked when the provider is\n * built, so a bad value fails at start-up and not in the middle of a flow.\n */\nconst assertClientMetadataUrl = (url: string, label = 'MCP OAuth'): void => {\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n throw new Error(`${label}: clientMetadataUrl \"${url}\" is not a valid URL`)\n }\n if (parsed.protocol === 'https:' && parsed.pathname !== '/') return\n throw new Error(\n `${label}: clientMetadataUrl requires https and a non-root path - refusing \"${url}\"`,\n )\n}\n\nconst REGISTRATIONS: readonly McpOAuthRegistration[] = ['auto', 'cimd', 'dcr']\n\n/**\n * `registration` is checked when the provider is built: an unknown value would\n * otherwise read as \"auto\", and `'cimd'` without a document has nothing to sign\n * in with. The Node package carries the same function; change both.\n */\nconst resolveRegistration = (\n registration: unknown,\n clientMetadataUrl: string | undefined,\n label = 'MCP OAuth',\n): McpOAuthRegistration => {\n if (registration === undefined) return 'auto'\n if (!REGISTRATIONS.includes(registration as McpOAuthRegistration)) {\n throw new Error(\n `${label}: registration must be 'auto', 'cimd' or 'dcr' - refusing \"${String(registration)}\"`,\n )\n }\n if (registration === 'cimd' && clientMetadataUrl === undefined) {\n throw new Error(\n `${label}: registration 'cimd' needs a clientMetadataUrl - the client ID metadata document to sign in with`,\n )\n }\n return registration as McpOAuthRegistration\n}\n\n// How a client was registered is stamped on its stored record under this key,\n// when it is saved (the URL it was registered under is known then, and may be\n// configured differently later), and taken off again before the record reaches\n// the SDK: nothing of it is ever sent.\nconst KIND_KEY = 'x-agent-registration'\n\n/**\n * RFC 9207: is the `iss` parameter of an authorization response the\n * authorization server this flow was started with? Throws when it is not; the\n * caller must not exchange the code then (a mix-up attack hands the code of an\n * honest server to another one's token endpoint).\n *\n * - expected issuer: the `issuer` of the stored authorization server metadata,\n * else the authorization server URL discovery used;\n * - `iss` present: it must equal the expected issuer, compared as plain strings\n * (RFC 9207 section 2.4: no normalization);\n * - `iss` absent: refused when the metadata says\n * `authorization_response_iss_parameter_supported: true`;\n * - no stored discovery state (storage written by an older version): `iss` is\n * compared with the issuer stamped on the stored client information, and with\n * nothing to compare against the response is accepted. ({@link finishMcpOAuth}\n * does not exchange a code in that case: see there.)\n *\n * The Node package carries the same function; change both.\n */\nexport const checkAuthorizationResponseIssuer = (\n iss: string | undefined,\n discoveryState: OAuthDiscoveryState | undefined,\n clientIssuer?: string,\n): void => {\n // Read as it is stored, not through the SDK's type: only a literal `true` is\n // a promise (the SDK's schema keeps the flag for both metadata documents and\n // turns anything that is not a boolean into \"absent\").\n const metadata = discoveryState?.authorizationServerMetadata as\n { issuer?: string; authorization_response_iss_parameter_supported?: unknown } | undefined\n const expected = discoveryState\n ? (metadata?.issuer ?? String(discoveryState.authorizationServerUrl))\n : clientIssuer\n if (iss === undefined) {\n if (metadata?.authorization_response_iss_parameter_supported === true) {\n throw new Error(\n 'Authorization response carried no \"iss\", which this authorization server says it always sends; refusing to exchange the code (possible mix-up attack)',\n )\n }\n return\n }\n if (expected !== undefined && iss !== expected) {\n throw new Error(\n `Authorization response came from issuer \"${iss}\", expected \"${expected}\"; refusing to exchange the code (possible mix-up attack)`,\n )\n }\n}\n\nconst randomToken = (): string => {\n const bytes = new Uint8Array(32)\n globalThis.crypto.getRandomValues(bytes)\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * `application_type` for dynamic registration, read off the redirect URL: a\n * loopback address or a private-use scheme is how a native client is called\n * back, an https page is a web client. Said explicitly because a server that\n * tells the two apart assumes \"web\" when the field is absent, and then refuses\n * a loopback redirect - and one that is told \"native\" refuses an https one.\n * The browser and the Node package carry the same function; change both.\n */\nconst applicationTypeFor = (redirectUrl: string): 'native' | 'web' => {\n try {\n const u = new URL(redirectUrl)\n return u.protocol === 'https:' && !LOOPBACK_HOSTS.has(u.hostname) ? 'web' : 'native'\n } catch {\n return 'native'\n }\n}\n\n/**\n * An `OAuthClientProvider` (MCP SDK) that persists everything it is handed and\n * never navigates behind your back. One instance per MCP server.\n */\nexport class BrowserOAuthProvider implements OAuthClientProvider {\n /** Set when the SDK asks for an authorization redirect; read it in your UI. */\n authorizationUrl?: URL\n\n readonly serverUrl: string\n\n private readonly storage: McpOAuthStorage\n private readonly ns: string\n private readonly _redirectUrl: string\n private readonly _clientMetadata: OAuthClientMetadata\n private readonly _clientMetadataUrl?: string\n private readonly _registration: McpOAuthRegistration\n private readonly skewMs: number\n private readonly onRedirect?: (url: URL) => void | Promise<void>\n /** Once per provider: a stored client of the other kind is forgotten (see `settle`). */\n private settled?: Promise<void>\n\n constructor(opts: BrowserOAuthProviderOptions) {\n assertSecureOAuthUrl(opts.serverUrl)\n if (opts.clientMetadataUrl !== undefined) {\n assertClientMetadataUrl(opts.clientMetadataUrl)\n this._clientMetadataUrl = opts.clientMetadataUrl\n }\n this._registration = resolveRegistration(opts.registration, opts.clientMetadataUrl)\n this.serverUrl = opts.serverUrl\n this.storage = opts.storage ?? new VaultOAuthStorage()\n this.ns = namespaceFor(opts.serverUrl)\n this._redirectUrl = String(opts.redirectUrl)\n this.skewMs = (opts.expirySkewSeconds ?? DEFAULT_SKEW_SECONDS) * 1000\n this.onRedirect = opts.onRedirect\n this._clientMetadata = {\n client_name: opts.clientName ?? 'agent-web',\n redirect_uris: [this._redirectUrl],\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n // Public client: a browser cannot hold a client_secret. PKCE is what\n // actually protects the code exchange.\n token_endpoint_auth_method: 'none',\n // By the redirect: an https page is 'web', a loopback one (local dev) is 'native'.\n application_type: applicationTypeFor(this._redirectUrl),\n ...(opts.scope ? { scope: opts.scope } : {}),\n ...opts.clientMetadata,\n } as OAuthClientMetadata\n }\n\n get redirectUrl(): string {\n return this._redirectUrl\n }\n\n get clientMetadata(): OAuthClientMetadata {\n return this._clientMetadata\n }\n\n /**\n * The client ID metadata document URL (CIMD), when one was configured - and\n * not with `registration: 'dcr'`: the SDK uses this getter to decide, so a\n * URL it cannot see is a URL it never uses as the `client_id`.\n */\n get clientMetadataUrl(): string | undefined {\n return this._registration === 'dcr' ? undefined : this._clientMetadataUrl\n }\n\n /** How this provider registers its client: `'auto'`, `'cimd'` or `'dcr'`. */\n get registration(): McpOAuthRegistration {\n return this._registration\n }\n\n private key(suffix: string): string {\n return `${this.ns}:${suffix}`\n }\n\n private async readJSON<T>(suffix: string): Promise<T | undefined> {\n // The read itself is inside the guard on purpose: the default storage\n // decrypts, and an AES-GCM blob written under a key that no longer exists\n // (a partially cleared IndexedDB, a rotated vault key) throws. Treating\n // that as \"no value\" lets the flow re-authorize instead of every call\n // rejecting with an opaque OperationError forever.\n try {\n const raw = await this.storage.get(this.key(suffix))\n if (raw === undefined) return undefined\n return JSON.parse(raw) as T\n } catch {\n await this.storage.delete(this.key(suffix)).catch(() => {})\n return undefined\n }\n }\n\n async state(): Promise<string> {\n const value = randomToken()\n await this.storage.set(this.key('state'), value)\n return value\n }\n\n /**\n * CSRF check for the redirect back. Single-use: the stored value is dropped\n * whether or not it matched, so a replayed callback can't pass twice.\n */\n async verifyState(returned: string | undefined): Promise<boolean> {\n const expected = await this.storage.get(this.key('state'))\n await this.storage.delete(this.key('state'))\n return expected !== undefined && returned !== undefined && expected === returned\n }\n\n /** The stored client, without our stamp, and how it was registered. */\n private async readClient(): Promise<\n { info: OAuthClientInformationMixed; kind: McpOAuthRegistrationKind } | undefined\n > {\n const stored = await this.readJSON<Record<string, unknown>>('client')\n if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return undefined\n const info: Record<string, unknown> = { ...stored }\n const stamp = info[KIND_KEY]\n delete info[KIND_KEY]\n // A record saved before the stamp existed: CIMD when its client_id is the\n // document configured now.\n const kind = stamp === 'cimd' || stamp === 'dcr' ? stamp : this.kindOf(info.client_id)\n return { info: info as unknown as OAuthClientInformationMixed, kind }\n }\n\n private kindOf(clientId: unknown): McpOAuthRegistrationKind {\n return this._clientMetadataUrl !== undefined && clientId === this._clientMetadataUrl\n ? 'cimd'\n : 'dcr'\n }\n\n /**\n * May this provider use the stored client? Under `'auto'` any; under `'cimd'`\n * only the configured document itself; under `'dcr'` only one that was not\n * registered by a document.\n */\n private fits(client: { info: OAuthClientInformationMixed; kind: McpOAuthRegistrationKind }) {\n if (this._registration === 'cimd') {\n return client.kind === 'cimd' && client.info.client_id === this._clientMetadataUrl\n }\n if (this._registration === 'dcr') return client.kind === 'dcr'\n return true\n }\n\n /** The client and the tokens issued to it go together: a token belongs to a client. */\n private async forgetClient(): Promise<void> {\n await Promise.all(['client', 'tokens'].map((t) => this.storage.delete(this.key(t))))\n }\n\n /**\n * Under `'cimd'` / `'dcr'`, before the first read of the client or a token: a\n * stored client of the other kind (registered under another setting) is\n * forgotten with its tokens, so the setting is never served by the old\n * client - not even by its access token, which the transport would otherwise\n * keep sending until it expires. Once per provider (its setting is fixed); a\n * failure is not remembered.\n */\n private settle(): Promise<void> {\n if (this._registration === 'auto') return Promise.resolve()\n this.settled ??= (async () => {\n const client = await this.readClient()\n if (client && !this.fits(client)) await this.forgetClient()\n })().catch((err: unknown) => {\n this.settled = undefined\n throw err\n })\n return this.settled\n }\n\n /**\n * `'cimd'` with no usable client: the SDK is about to choose between the\n * document and a dynamic registration, by the authorization server metadata\n * it has just saved (`saveDiscoveryState` comes first). Without support it\n * would register - so it is stopped HERE, before any request is made, and\n * what discovery found is forgotten, so the next attempt reads the server's\n * metadata again (a server that starts supporting CIMD is noticed).\n */\n private async assertCimdSupported(): Promise<void> {\n const discovery = await this.discoveryState()\n const metadata = discovery?.authorizationServerMetadata as\n { issuer?: unknown; client_id_metadata_document_supported?: unknown } | undefined\n // Only a literal `true` is a promise, as the SDK reads it.\n if (metadata?.client_id_metadata_document_supported === true) return\n await this.storage.delete(this.key('discovery')).catch(() => {})\n const server =\n typeof metadata?.issuer === 'string' ? metadata.issuer : discovery?.authorizationServerUrl\n throw new Error(\n server\n ? `MCP OAuth: the authorization server ${server} of ${this.serverUrl} does not support client ID metadata documents (CIMD), which this connection requires (registration: 'cimd') - nothing was sent to its registration endpoint`\n : `MCP OAuth: no record of the authorization server of ${this.serverUrl}, so its support for client ID metadata documents (CIMD), which this connection requires (registration: 'cimd'), cannot be confirmed - nothing was registered`,\n )\n }\n\n async clientInformation(): Promise<OAuthClientInformationMixed | undefined> {\n await this.settle()\n const client = await this.readClient()\n if (client && this.fits(client)) return client.info\n // Written by a provider with another setting since this one settled.\n if (client) await this.forgetClient()\n if (this._registration === 'cimd') await this.assertCimdSupported()\n return undefined\n }\n\n async saveClientInformation(info: OAuthClientInformationMixed): Promise<void> {\n // Whatever arrived under our key (a registration response is the server's\n // text) is replaced by what this provider knows: a client whose ID is the\n // configured document is CIMD, any other was registered dynamically.\n const record: Record<string, unknown> = { ...info }\n record[KIND_KEY] = this.kindOf(info.client_id)\n await this.storage.set(this.key('client'), JSON.stringify(record))\n }\n\n /**\n * How the stored client was registered: `'cimd'` (its `client_id` is the\n * client ID metadata document), `'dcr'` (registered dynamically - or saved by\n * the host), or undefined when there is none this provider would use. Read it\n * after a sign-in to show the user which way was taken.\n */\n async registrationKind(): Promise<McpOAuthRegistrationKind | undefined> {\n await this.settle()\n const client = await this.readClient()\n return client && this.fits(client) ? client.kind : undefined\n }\n\n async tokens(): Promise<OAuthTokens | undefined> {\n await this.settle()\n return (await this.readJSON<StoredTokens>('tokens'))?.tokens\n }\n\n async saveTokens(tokens: OAuthTokens): Promise<void> {\n const stored: StoredTokens = {\n tokens,\n expiresAt:\n typeof tokens.expires_in === 'number' ? Date.now() + tokens.expires_in * 1000 : undefined,\n }\n await this.storage.set(this.key('tokens'), JSON.stringify(stored))\n }\n\n async saveCodeVerifier(verifier: string): Promise<void> {\n await this.storage.set(this.key('verifier'), verifier)\n }\n\n async codeVerifier(): Promise<string> {\n const v = await this.storage.get(this.key('verifier'))\n if (!v) {\n throw new Error(\n 'No PKCE code verifier stored: the authorization was started in a different browser profile, or storage was cleared mid-flow',\n )\n }\n return v\n }\n\n /**\n * What discovery found (the authorization server, its metadata, the resource\n * metadata). The SDK reuses it instead of discovering again - after the\n * redirect back too - and {@link finishMcpOAuth} reads the expected issuer\n * from it.\n */\n async saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {\n await this.storage.set(this.key('discovery'), JSON.stringify(state))\n }\n\n async discoveryState(): Promise<OAuthDiscoveryState | undefined> {\n const state = await this.readJSON<OAuthDiscoveryState>('discovery')\n if (!state || typeof state !== 'object' || typeof state.authorizationServerUrl !== 'string') {\n return undefined\n }\n return state\n }\n\n async redirectToAuthorization(url: URL): Promise<void> {\n this.authorizationUrl = url\n await this.onRedirect?.(url)\n }\n\n /**\n * Called by the SDK when the server rejects what we hold: `'tokens'` after an\n * `invalid_grant` (dead refresh token); `'client'` and then `'tokens'` after\n * an `invalid_client` (the AS forgot our dynamic registration) - what\n * discovery found is kept on purpose, the SDK checks the next callback\n * against it. `'verifier'` and `'discovery'` are in its type and handled the\n * same way: one key each. `'all'` is what {@link reset} asks for. Clearing\n * lets the SDK re-register and re-authorize without the user clearing site\n * data.\n */\n async invalidateCredentials(\n scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery',\n ): Promise<void> {\n const targets =\n scope === 'all' ? ['tokens', 'client', 'verifier', 'state', 'discovery'] : [scope]\n await Promise.all(targets.map((t) => this.storage.delete(this.key(t))))\n }\n\n /** True when there is no access token, or it expires within the skew window. */\n async isAccessTokenExpired(): Promise<boolean> {\n await this.settle()\n const stored = await this.readJSON<StoredTokens>('tokens')\n if (!stored?.tokens?.access_token) return true\n // No expires_in means the AS didn't say; assume it is still good and let a\n // 401 drive the refresh.\n if (stored.expiresAt === undefined) return false\n return Date.now() + this.skewMs >= stored.expiresAt\n }\n\n /** True once an authorization has completed for this server. */\n async isAuthorized(): Promise<boolean> {\n return (await this.tokens()) !== undefined\n }\n\n /** Forget tokens, registration, verifier, state and discovery for this server. */\n async reset(): Promise<void> {\n this.authorizationUrl = undefined\n await this.invalidateCredentials('all')\n }\n}\n\nexport interface McpOAuthRequestOptions {\n /**\n * Custom fetch for the discovery / registration / token requests. Pass the\n * same one you give the connector so a proxy or an instrumentation wrapper\n * covers the OAuth traffic too.\n */\n fetch?: FetchLike\n}\n\nexport interface McpOAuthCallback {\n code?: string\n state?: string\n /** The `iss` parameter of the response (RFC 9207), when the server sent one. */\n iss?: string\n error?: string\n errorDescription?: string\n}\n\n/**\n * Pull the authorization-code parameters out of a redirect URL. Reads the query\n * string and, for hash-routed apps, the fragment. Returns undefined when the\n * URL carries neither a `code` nor an `error`, so it is safe to call on every\n * page load.\n */\nexport const readOAuthCallback = (input?: string | URL): McpOAuthCallback | undefined => {\n const href = input\n ? String(input)\n : typeof globalThis.location !== 'undefined'\n ? globalThis.location.href\n : undefined\n if (!href) return undefined\n let url: URL\n try {\n url = new URL(href)\n } catch {\n return undefined\n }\n const params = new URLSearchParams(url.search)\n const hash = url.hash.startsWith('#') ? url.hash.slice(1) : url.hash\n // Hash-routed apps get \"#/callback?code=…\"; take whatever follows the \"?\".\n const q = hash.indexOf('?')\n if (q >= 0) {\n for (const [k, v] of new URLSearchParams(hash.slice(q + 1))) {\n if (!params.has(k)) params.set(k, v)\n }\n }\n const code = params.get('code') ?? undefined\n const error = params.get('error') ?? undefined\n if (!code && !error) return undefined\n return {\n code,\n state: params.get('state') ?? undefined,\n iss: params.get('iss') ?? undefined,\n error,\n errorDescription: params.get('error_description') ?? undefined,\n }\n}\n\n/**\n * Finish the flow after the authorization server redirected back: verify the\n * `state`, then the issuer (RFC 9207, {@link checkAuthorizationResponseIssuer}),\n * exchange the code (PKCE) and persist the tokens. Throws when the AS returned\n * an error, when `state` doesn't match what we issued, when `iss` names another\n * authorization server, or when the exchange fails — never resolves on a\n * half-finished authorization.\n *\n * A flow whose discovery state is not in storage any more (started by a\n * version that did not keep it, or cleared in between) is not completed: the\n * code is bound to the authorization server the user was sent to, and without\n * the record of which one that was the SDK refuses the exchange. Start again\n * with {@link beginMcpOAuth}; stored tokens are not touched.\n */\nexport const finishMcpOAuth = async (\n provider: BrowserOAuthProvider,\n callback: McpOAuthCallback,\n opts: McpOAuthRequestOptions = {},\n): Promise<void> => {\n if (callback.error) {\n throw new Error(\n `Authorization denied by the server: ${callback.error}${\n callback.errorDescription ? ` - ${callback.errorDescription}` : ''\n }`,\n )\n }\n if (!callback.code) {\n throw new Error('Authorization callback carried no code')\n }\n if (!(await provider.verifyState(callback.state))) {\n throw new Error('Authorization state mismatch; refusing to exchange the code (possible CSRF)')\n }\n // Before the exchange: a code that came from another authorization server\n // must never reach this one's token endpoint.\n const discovery = await provider.discoveryState()\n checkAuthorizationResponseIssuer(\n callback.iss,\n discovery,\n (await provider.clientInformation())?.issuer,\n )\n if (!discovery) {\n // The SDK's own gate, said in our words: it throws on this inside `auth()`.\n throw new Error(\n 'Authorization cannot be completed: the record of which authorization server it was started with is not in the store (started by an older version, or cleared in between); start the authorization again',\n )\n }\n const result = await auth(provider, {\n serverUrl: provider.serverUrl,\n authorizationCode: callback.code,\n // The SDK runs its own RFC 9207 check inside `auth()`, after ours: without\n // the value it would read a response that carried `iss` as one that did not.\n iss: callback.iss,\n fetchFn: opts.fetch,\n })\n if (result !== 'AUTHORIZED') {\n throw new Error(`Token exchange did not complete (SDK returned \"${result}\")`)\n }\n}\n\n/**\n * Kick off (or silently renew) an authorization. Returns `'AUTHORIZED'` when a\n * usable token is in hand — including the case where a refresh token was\n * silently exchanged — or `'REDIRECT'` when the user has to visit\n * `provider.authorizationUrl`.\n */\nexport const beginMcpOAuth = async (\n provider: BrowserOAuthProvider,\n opts: McpOAuthRequestOptions = {},\n): Promise<'AUTHORIZED' | 'REDIRECT'> => {\n provider.authorizationUrl = undefined\n return auth(provider, { serverUrl: provider.serverUrl, fetchFn: opts.fetch })\n}\n","export { connectMcpHttp, diagnoseMcpCors, flattenContent } from './http.js'\n// Re-exported so a host that only depends on this package can identify an\n// authorization failure: `err instanceof UnauthorizedError`. The 2.x SDK's\n// class is branded, so the check also holds for an error made by ANOTHER copy\n// of the SDK (two bundles, or the ESM and the CJS build on one page), and it\n// sets `name` to 'UnauthorizedError' (the 1.x class did neither).\nexport { UnauthorizedError } from '@modelcontextprotocol/client'\nexport {\n MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER,\n MCP_INSTRUCTIONS_MAX_CHARS_TOTAL,\n MCP_MODERN_PROTOCOL_VERSION,\n MCP_MODERN_REQUEST_HEADERS,\n renderMcpInstructions,\n} from './shared.js'\nexport type { McpProtocolMode, McpServerInstructions, McpServerProtocol } from './shared.js'\nexport {\n MCP_ELICITATION_MAX_PER_RUN,\n MCP_ELICITATION_MAX_PER_TOOL_CALL,\n MCP_ELICITATION_TIMEOUT_MS,\n normalizeMcpElicitationSchema,\n validateMcpElicitationContent,\n} from './elicitation.js'\nexport type {\n McpElicitationContent,\n McpElicitationContext,\n McpElicitationFieldSchema,\n McpElicitationHandler,\n McpElicitationOptions,\n McpElicitationReason,\n McpElicitationRequest,\n McpElicitationResult,\n McpElicitationSchema,\n} from './elicitation.js'\nexport type {\n McpHttpServerConfig,\n McpCatalogEntry,\n McpServerResult,\n ConnectedMcp,\n ConnectMcpOptions,\n McpAppsConnection,\n McpAppTool,\n} from './http.js'\nexport {\n MCP_APP_DEFAULT_VISIBILITY,\n MCP_APP_MAX_DOMAINS,\n MCP_APP_MAX_DOWNLOAD_BYTES,\n MCP_APP_MAX_HTML_CHARS,\n MCP_APP_MAX_RESULT_CHARS,\n MCP_APP_MIME_TYPE,\n MCP_APPS_EXTENSION,\n McpAppResourceError,\n isMcpAppMimeType,\n isMcpAppUri,\n mcpAppCspOf,\n mcpAppDownloadOf,\n mcpAppOrigin,\n mcpAppPermissionsOf,\n mcpAppResourceOf,\n mcpAppToolMeta,\n mcpAppToolResultOf,\n mcpAppsModeOf,\n} from './apps.js'\nexport type {\n McpAppCsp,\n McpAppDownloadResource,\n McpAppPermissions,\n McpAppResource,\n McpAppToolMeta,\n McpAppToolResult,\n McpAppVisibility,\n McpAppsMode,\n} from './apps.js'\nexport {\n BrowserOAuthProvider,\n MemoryOAuthStorage,\n VaultOAuthStorage,\n beginMcpOAuth,\n checkAuthorizationResponseIssuer,\n finishMcpOAuth,\n readOAuthCallback,\n} from './oauth.js'\nexport type {\n BrowserOAuthProviderOptions,\n McpOAuthCallback,\n McpOAuthRegistration,\n McpOAuthRegistrationKind,\n McpOAuthRequestOptions,\n McpOAuthStorage,\n} from './oauth.js'\nexport {\n BrowserEnterpriseOAuthProvider,\n createEnterpriseOAuthProvider,\n ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION,\n EnterpriseOAuthError,\n} from './enterprise-oauth.js'\nexport type {\n EnterpriseAssertionAlgorithm,\n EnterpriseAssertionAudience,\n EnterpriseAssertionType,\n EnterpriseIdpOptions,\n EnterpriseOAuthHop,\n EnterpriseOAuthLog,\n EnterpriseOAuthProviderOptions,\n EnterprisePrivateKey,\n} from './enterprise-oauth.js'\n","import {\n auth,\n OAuthError,\n type FetchLike,\n type OAuthClientInformationMixed,\n type OAuthClientMetadata,\n type OAuthClientProvider,\n type OAuthDiscoveryState,\n type OAuthTokens,\n} from '@modelcontextprotocol/client'\nimport { createLogger } from '../logger.js'\nimport { assertSecureOAuthUrl, VaultOAuthStorage, type McpOAuthStorage } from './oauth.js'\n\n/**\n * Enterprise-Managed Authorization for remote MCP servers (the MCP extension\n * `io.modelcontextprotocol/enterprise-managed-authorization`, also called Cross\n * App Access): the organization's identity provider decides which MCP servers\n * a user's client may reach, and no one is sent to a consent page.\n *\n * Two hops, both plain HTTP POSTs:\n *\n * 1. at the IdP - an RFC 8693 token exchange turns the user's ID token into an\n * Identity Assertion JWT Authorization Grant (ID-JAG) addressed to the MCP\n * server's authorization server;\n * 2. at the MCP authorization server - an RFC 7523 `jwt-bearer` grant turns the\n * ID-JAG into an ordinary access token.\n *\n * The MCP SDK owns discovery (RFC 9728 / RFC 8414), the second hop and the\n * retry on a 401; this module supplies the first hop and the checks around it.\n * Only the resulting access token is stored. The ID token, the ID-JAG and the\n * client assertions pass through memory and are never written, logged or put\n * in an error.\n *\n * The client authenticates on each hop with a secret or with a signed\n * assertion (`private_key_jwt`, RFC 7523 section 2.2). By default the audience\n * of that assertion is the issuer identifier of the server it is for and\n * nothing else, as draft-ietf-oauth-rfc7523bis requires: an assertion made for\n * the IdP is of no use at the authorization server, and the other way round.\n * For a server built to RFC 7523 as published, `assertionAudience:\n * 'token-endpoint'` and `assertionType: 'JWT'` produce the older form - see\n * `EnterpriseAssertionAudience` for what that gives up.\n *\n * Follows draft-ietf-oauth-identity-assertion-authz-grant and the extension's\n * 2026-07-28 revision. The Node package carries the same provider; change both.\n *\n * In a browser the IdP's token endpoint must allow this page's origin (CORS),\n * and a `clientSecret` in a page is readable by anyone who can open the page:\n * see docs/security.md before using one here.\n *\n * Pass the result to `connectMcpHttp`'s `servers[name].authProvider`.\n */\n\n/** The extension identifier a client declares in its capabilities. */\nexport const ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION =\n 'io.modelcontextprotocol/enterprise-managed-authorization'\n\nconst GRANT_TOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange'\nconst GRANT_JWT_BEARER = 'urn:ietf:params:oauth:grant-type:jwt-bearer'\nconst TOKEN_TYPE_ID_JAG = 'urn:ietf:params:oauth:token-type:id-jag'\nconst TOKEN_TYPE_ID_TOKEN = 'urn:ietf:params:oauth:token-type:id_token'\nconst CLIENT_ASSERTION_TYPE = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n/** Seconds a client assertion lives: long enough for one request, no more. */\nconst CLIENT_ASSERTION_LIFETIME_SECONDS = 60\n\n/** Which part of the flow refused. */\nexport type EnterpriseOAuthHop = 'discovery' | 'idp' | 'authorization-server'\n\n/**\n * A failure of the enterprise flow, with the hop that refused: `'discovery'`\n * (what the MCP server published cannot be trusted or used), `'idp'` (the token\n * exchange) or `'authorization-server'` (the `jwt-bearer` grant). The message\n * is short and safe to show: never a request body, a token, an assertion, a\n * secret or a key. What the authorization server said in full goes to the log\n * (`onLog`), redacted the same way.\n */\nexport class EnterpriseOAuthError extends Error {\n readonly hop: EnterpriseOAuthHop\n /** The OAuth `error` code the server answered with, when it sent one. */\n readonly code?: string\n\n constructor(hop: EnterpriseOAuthHop, message: string, code?: string) {\n super(message)\n this.name = 'EnterpriseOAuthError'\n this.hop = hop\n this.code = code\n }\n}\n\n/** Signature algorithms for a `private_key_jwt` client assertion. */\nexport type EnterpriseAssertionAlgorithm =\n 'ES256' | 'ES384' | 'ES512' | 'RS256' | 'RS384' | 'RS512' | 'PS256' | 'PS384' | 'PS512'\n\n/**\n * The private key that signs a client assertion: a `CryptoKey` (best: import\n * or generate it as non-extractable, so page script can use it but not read\n * it) or a JWK object. It must be a key for the chosen `algorithm` (an ECDSA\n * P-256 key for ES256, an RSASSA-PKCS1-v1_5 key for RS256, RSA-PSS for PS256...).\n */\nexport type EnterprisePrivateKey = JsonWebKey | CryptoKey\n\n/**\n * What a `private_key_jwt` client assertion names as its audience (`aud`).\n *\n * - `'issuer'` (the default): the issuer identifier of the server the\n * assertion is for, as draft-ietf-oauth-rfc7523bis requires.\n * - `'token-endpoint'`: the URL of that server's token endpoint, which is what\n * RFC 7523 as published describes and what many deployed identity providers\n * check for.\n *\n * The default is the issuer because an assertion addressed to a token endpoint\n * URL is exactly what the bis draft forbids. The token endpoint is one field of\n * a metadata document; a client that reads its audience from metadata can be\n * handed a document that names an honest server's endpoint (audience\n * injection), and then signs an assertion the party that served the document\n * can replay at that honest server. The issuer identifier is the one value a\n * client checks before it trusts the rest of the document. This provider never\n * takes either value from the MCP server alone - the IdP's endpoint is\n * configuration, and the authorization server's is used only after its\n * metadata matched `expectedIssuer` - so `'token-endpoint'` here costs the\n * defence in depth, not the check itself. Use it only for a server that\n * refuses the issuer form.\n */\nexport type EnterpriseAssertionAudience = 'issuer' | 'token-endpoint'\n\n/**\n * The `typ` header of a client assertion: `client-authentication+jwt` (the\n * default, from draft-ietf-oauth-rfc7523bis: a token typed this way cannot be\n * mistaken for another kind of JWT) or `JWT`, for a server that refuses a\n * `typ` it does not know.\n */\nexport type EnterpriseAssertionType = 'client-authentication+jwt' | 'JWT'\n\n/** Where the provider reports what it will not put in an error. */\nexport type EnterpriseOAuthLog = (level: 'info' | 'warn' | 'error', message: string) => void\n\nexport interface EnterpriseIdpOptions {\n /**\n * The IdP's token endpoint, where the token exchange is posted. Configured,\n * not discovered: it is where the user's ID token and the client's IdP\n * credentials go, so nothing fetched at run time may choose it.\n */\n tokenEndpoint: string\n /**\n * The IdP's issuer identifier. REQUIRED with `private_key_jwt`, where it is\n * the audience of the client assertion - unless `assertionAudience` is\n * `'token-endpoint'`, which addresses the assertion to `tokenEndpoint`.\n */\n issuer?: string\n /** This client's `client_id` at the IdP (the audience of the ID token). */\n clientId: string\n /**\n * This client's secret at the IdP. Omit for a client the IdP treats as\n * public. In a browser it is readable by anyone who can open the page: leave\n * it out and pass a `fetch` that sends this request through your backend.\n */\n clientSecret?: string\n /**\n * How the client authenticates at the IdP. With a secret: in an\n * `Authorization: Basic` header (the default, which every OAuth server must\n * accept) or in the form body. `'private_key_jwt'`: a signed assertion, which\n * needs `privateKey`, `algorithm` and `issuer` (or `assertionAudience:\n * 'token-endpoint'`).\n */\n clientAuthMethod?: 'client_secret_basic' | 'client_secret_post' | 'private_key_jwt'\n /** The key for `private_key_jwt`. Never stored, logged or put in an error. */\n privateKey?: EnterprisePrivateKey\n /** `kid` header of the assertion: the key's id in the JWKS the IdP holds. */\n keyId?: string\n /** Signature algorithm of the assertion. */\n algorithm?: EnterpriseAssertionAlgorithm\n /**\n * The audience of the assertion: `'issuer'` (the default: `issuer`) or\n * `'token-endpoint'` (`tokenEndpoint`, for an IdP built to RFC 7523 - the\n * weaker form, see `EnterpriseAssertionAudience`). Only with `private_key_jwt`.\n */\n assertionAudience?: EnterpriseAssertionAudience\n /**\n * The `typ` header of the assertion: `'client-authentication+jwt'` (the\n * default) or `'JWT'` for an IdP that refuses the new one. Only with\n * `private_key_jwt`.\n */\n assertionType?: EnterpriseAssertionType\n}\n\nexport interface EnterpriseOAuthProviderOptions {\n /** The MCP endpoint being authorized. */\n serverUrl: string\n /**\n * This client's `client_id` at the MCP server's authorization server: a\n * pre-registered identifier, or the https URL of a client ID metadata\n * document (CIMD) you host. A URL must be https with a path of its own, and\n * cannot be used with `clientSecret`: a document anyone can read establishes\n * no shared secret, so such a client is public or uses `private_key_jwt`\n * with the keys the document lists (`jwks` / `jwks_uri`).\n */\n clientId: string\n /**\n * Its secret there. The grant is meant for confidential clients. A secret\n * needs `expectedIssuer`: without it the MCP server's metadata would choose\n * who receives the secret, and the constructor throws.\n *\n * In a browser a secret is readable by anyone who can open the page. This\n * provider is for public clients there, or for a `fetch` that routes the IdP\n * call through your backend, which holds the secret.\n */\n clientSecret?: string\n /**\n * How the client authenticates at the authorization server. Left out, the\n * SDK decides: a secret is sent the way the server's metadata allows (Basic\n * first), no secret means `client_id` alone. `'private_key_jwt'` signs an\n * assertion and needs `privateKey`, `algorithm` and `expectedIssuer`.\n */\n clientAuthMethod?: 'client_secret_basic' | 'client_secret_post' | 'private_key_jwt' | 'none'\n /** The key for `private_key_jwt`. Never stored, logged or put in an error. */\n privateKey?: EnterprisePrivateKey\n /** `kid` header of the assertion: the key's id in the JWKS the server holds. */\n keyId?: string\n /** Signature algorithm of the assertion. */\n algorithm?: EnterpriseAssertionAlgorithm\n /**\n * The audience of the assertion for the authorization server: `'issuer'`\n * (the default: the issuer discovery found, once it matched\n * `expectedIssuer`) or `'token-endpoint'` (the token endpoint from that same\n * metadata, for a server built to RFC 7523 - the weaker form, see\n * `EnterpriseAssertionAudience`). The endpoint is read only from metadata\n * whose issuer is `expectedIssuer`, and must be https or loopback. Only with\n * `private_key_jwt`.\n */\n assertionAudience?: EnterpriseAssertionAudience\n /**\n * The `typ` header of the assertion: `'client-authentication+jwt'` (the\n * default) or `'JWT'` for a server that refuses the new one. Only with\n * `private_key_jwt`.\n */\n assertionType?: EnterpriseAssertionType\n /**\n * The issuer of the MCP server's authorization server. Anything else the MCP\n * server points at is refused before a credential leaves the process.\n * REQUIRED with `clientSecret` and with `private_key_jwt`: neither the\n * receiver of a secret nor the audience of a signed assertion may come from\n * the MCP server's metadata alone. A client with no credential at the\n * authorization server may omit it: then the only thing sent there is the\n * ID-JAG, which the IdP addressed to that one server and which is of no use\n * to any other.\n */\n expectedIssuer?: string\n /** The enterprise identity provider. */\n idp: EnterpriseIdpOptions\n /**\n * The user's OpenID Connect ID token from the IdP. How it was obtained (the\n * single sign-on of your application) is yours; it is called each time a new\n * ID-JAG is needed, so return a current one. The value is never stored.\n */\n getIdToken: () => string | Promise<string>\n /** Scopes to ask the IdP for (space-separated). */\n scope?: string\n /** Defaults to the encrypted IndexedDB vault. Holds the access token only. */\n storage?: McpOAuthStorage\n /** Treat the access token as expired this many seconds early. Default 30. */\n expirySkewSeconds?: number\n /** Custom fetch for the request to the IdP. */\n fetch?: FetchLike\n /**\n * Receives the detail a refusal's error leaves out (what the authorization\n * server answered), redacted. `connectMcpHttp` passes its `onLog`; this is\n * for a provider used without it. With neither, it goes to the package's\n * logger at `warn` (`[agent-web]` on the console).\n */\n onLog?: EnterpriseOAuthLog\n}\n\ninterface StoredTokens {\n tokens: OAuthTokens\n expiresAt?: number\n}\n\nconst DEFAULT_SKEW_SECONDS = 30\n\n// origin + path + query, as the interactive provider does, under a prefix of\n// its own: a token obtained for a user through the IdP is never mistaken for\n// one an operator authorized by hand.\nconst namespaceFor = (serverUrl: string): string => {\n const u = new URL(serverUrl)\n return `mcp-enterprise-oauth:${u.origin}${u.pathname.replace(/\\/+$/, '')}${u.search}`\n}\n\n/** Two issuer identifiers, equal as written or differing by one trailing slash. */\nconst sameIssuer = (a: string, b: string): boolean => a === b || a === `${b}/` || b === `${a}/`\n\nconst stripFragment = (url: string): string => {\n const u = new URL(url)\n u.hash = ''\n return u.href\n}\n\n/**\n * RFC 9728 section 3.3, as the MCP SDK applies it: the resource a server\n * publishes must be the URL we were configured with, or a parent path of it on\n * the same origin.\n */\nconst resourceCovers = (resource: string, serverUrl: string): boolean => {\n let published: URL\n try {\n published = new URL(resource)\n } catch {\n return false\n }\n const requested = new URL(serverUrl)\n if (published.origin !== requested.origin) {\n return false\n }\n const slashed = (p: string): string => (p.endsWith('/') ? p : `${p}/`)\n return slashed(requested.pathname).startsWith(slashed(published.pathname))\n}\n\n/**\n * The audience and the resource of the ID-JAG, read from what discovery found\n * for THIS server and from nothing else - and, once every check below has\n * passed, the token endpoint that metadata names (the audience of a client\n * assertion under `assertionAudience: 'token-endpoint'`). Throws (`hop:\n * 'discovery'`) when the published metadata cannot be trusted:\n *\n * - the authorization server and its token endpoint must be https or loopback;\n * - it must have published metadata with an `issuer`, and that issuer must be\n * the URL the metadata was fetched for (RFC 8414 section 3.3) - otherwise a\n * hostile server could name an honest authorization server as the audience\n * and collect the ID-JAG at its own token endpoint;\n * - with `expectedIssuer`, it must be that one;\n * - the published resource must cover the configured server URL.\n *\n * The Node package carries the same function; change both.\n */\nexport const enterpriseGrantTarget = (\n serverUrl: string,\n state: OAuthDiscoveryState | undefined,\n expectedIssuer?: string,\n): { audience: string; resource: string; tokenEndpoint?: string } => {\n const refuse = (message: string): never => {\n throw new EnterpriseOAuthError('discovery', `Enterprise MCP authorization: ${message}`)\n }\n if (!state) {\n return refuse('nothing is known about the authorization server of this MCP server yet')\n }\n const asUrl = String(state.authorizationServerUrl)\n const metadata = state.authorizationServerMetadata as\n { issuer?: unknown; token_endpoint?: unknown } | undefined\n const issuer = metadata?.issuer\n if (typeof issuer !== 'string' || !issuer) {\n return refuse(\n `the authorization server \"${asUrl}\" published no metadata with an issuer, so there is no audience to ask the identity provider for`,\n )\n }\n if (!sameIssuer(issuer, asUrl)) {\n return refuse(\n `the metadata fetched for \"${asUrl}\" names another issuer (\"${issuer}\"); refusing to request a grant for it`,\n )\n }\n if (expectedIssuer !== undefined && !sameIssuer(issuer, expectedIssuer)) {\n return refuse(\n `this MCP server points at the authorization server \"${issuer}\", expected \"${expectedIssuer}\"; refusing to send credentials there`,\n )\n }\n try {\n assertSecureOAuthUrl(asUrl, 'MCP authorization server')\n if (typeof metadata?.token_endpoint === 'string') {\n assertSecureOAuthUrl(metadata.token_endpoint, 'MCP authorization server token endpoint')\n }\n } catch (err) {\n return refuse((err as Error).message)\n }\n const published = state.resourceMetadata?.resource\n if (published !== undefined && !resourceCovers(published, serverUrl)) {\n return refuse(\n `the protected resource \"${published}\" this server published does not cover \"${serverUrl}\"`,\n )\n }\n return {\n audience: issuer,\n resource: published ?? stripFragment(serverUrl),\n // Handed out only here, after the issuer and the scheme checks above.\n ...(typeof metadata?.token_endpoint === 'string' && metadata.token_endpoint\n ? { tokenEndpoint: metadata.token_endpoint }\n : {}),\n }\n}\n\n/** Printable ASCII only, clipped: a server's words, safe to put in an error. */\nconst printable = (value: unknown, max = 300): string | undefined => {\n if (typeof value !== 'string') {\n return undefined\n }\n const clean = value.replace(/[^\\x20-\\x7e]+/g, ' ').trim()\n if (!clean) {\n return undefined\n }\n return clean.length > max ? `${clean.slice(0, max)}...` : clean\n}\n\nconst formEncode = (value: string): string => new URLSearchParams({ v: value }).toString().slice(2)\n\n/**\n * Whatever a failure message is built from, the secrets of this exchange never\n * leave in it - a server that echoes the request, or a fetch that quotes it,\n * included.\n */\nconst redact = (message: string, secrets: (string | undefined)[]): string => {\n let out = message\n for (const secret of secrets) {\n if (!secret) {\n continue\n }\n // As written, and as a form or a URL would spell it.\n const spellings = [secret, encodeURIComponent(secret), formEncode(secret)]\n for (const spelling of new Set(spellings)) {\n out = out.split(spelling).join('[redacted]')\n }\n }\n return out\n}\n\nconst ALGORITHMS: readonly EnterpriseAssertionAlgorithm[] = [\n 'ES256',\n 'ES384',\n 'ES512',\n 'RS256',\n 'RS384',\n 'RS512',\n 'PS256',\n 'PS384',\n 'PS512',\n]\n\nconst base64Url = (bytes: Uint8Array): string => {\n let binary = ''\n for (const byte of bytes) {\n binary += String.fromCharCode(byte)\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nconst base64UrlJson = (value: unknown): string =>\n base64Url(new TextEncoder().encode(JSON.stringify(value)))\n\n// ── signing: the one part the two packages do differently ──────────────────\n// The browser signs with WebCrypto; the Node package with node:crypto.\n\nconst isCryptoKey = (key: EnterprisePrivateKey): key is CryptoKey =>\n typeof (key as CryptoKey).extractable === 'boolean' &&\n typeof (key as CryptoKey).algorithm === 'object' &&\n Array.isArray((key as CryptoKey).usages)\n\n/** The signature (raw bytes, JWS form) of `input` under `algorithm`. Throws on a key that does not fit. */\nconst signAssertionInput = async (\n algorithm: EnterpriseAssertionAlgorithm,\n privateKey: EnterprisePrivateKey,\n input: string,\n): Promise<Uint8Array> => {\n const bits = algorithm.slice(2)\n const hash = `SHA-${bits}`\n const family = algorithm.slice(0, 2)\n const importAs =\n family === 'ES'\n ? { name: 'ECDSA', namedCurve: bits === '512' ? 'P-521' : `P-${bits}` }\n : { name: family === 'PS' ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5', hash }\n const signAs =\n family === 'ES'\n ? { name: 'ECDSA', hash }\n : family === 'PS'\n ? { name: 'RSA-PSS', saltLength: Number(bits) / 8 }\n : { name: 'RSASSA-PKCS1-v1_5' }\n const { subtle } = globalThis.crypto\n let key: CryptoKey\n if (isCryptoKey(privateKey)) {\n key = privateKey\n // A key made for another scheme, curve or hash must not sign under this name.\n const made = key.algorithm as { name?: string; namedCurve?: string; hash?: { name?: string } }\n const fits =\n key.type === 'private' &&\n made.name === importAs.name &&\n (family === 'ES'\n ? made.namedCurve === (importAs as { namedCurve: string }).namedCurve\n : made.hash?.name === hash)\n if (!fits) {\n throw new Error('key does not fit the algorithm')\n }\n } else {\n if (typeof (privateKey as { d?: unknown }).d !== 'string') {\n throw new Error('not a private key')\n }\n // Imported as non-extractable, for signing only. `alg`, `use` and `key_ops`\n // are left out: a JWK labelled for something else would refuse to import.\n const { alg: _alg, use: _use, key_ops: _ops, ...jwk } = privateKey as JsonWebKey\n key = await subtle.importKey('jwk', jwk, importAs, false, ['sign'])\n }\n return new Uint8Array(await subtle.sign(signAs, key, new TextEncoder().encode(input)))\n}\n\n// ── end of signing ─────────────────────────────────────────────────────────\n\n/** The strings of a key that must never be seen: a JWK's private members. A `CryptoKey` has none to read. */\nconst keySecrets = (key: EnterprisePrivateKey | undefined): string[] => {\n if (key === undefined) {\n return []\n }\n const jwk = key as Record<string, unknown>\n return ['d', 'p', 'q', 'dp', 'dq', 'qi', 'k']\n .map((member) => jwk[member])\n .filter((v): v is string => typeof v === 'string' && v.length > 0)\n}\n\nexport interface ClientAssertionRequest {\n /** The client: both `iss` and `sub`. */\n clientId: string\n /**\n * The sole `aud`: the issuer identifier of the server the assertion is for\n * or, for a server built to RFC 7523, the URL of its token endpoint.\n */\n audience: string\n privateKey: EnterprisePrivateKey\n algorithm: EnterpriseAssertionAlgorithm\n keyId?: string\n /** The `typ` header. Default `client-authentication+jwt`. */\n type?: EnterpriseAssertionType\n}\n\n/**\n * A `private_key_jwt` client assertion (RFC 7523 section 2.2, with the audience\n * rule of draft-ietf-oauth-rfc7523bis): `iss` = `sub` = the client, `aud` = the\n * one audience the caller chose (the provider passes the issuer identifier of\n * the server it is for, or its token endpoint URL when configured to), a\n * random `jti`, `iat`, and an `exp` one minute away; header `typ`\n * `client-authentication+jwt` unless `type` says `JWT`. A failure to sign says\n * so and nothing more: the underlying error may describe the key. The Node\n * package carries the same function; change both.\n */\nexport const createClientAssertion = async (req: ClientAssertionRequest): Promise<string> => {\n const now = Math.floor(Date.now() / 1000)\n const header = {\n alg: req.algorithm,\n typ: req.type === 'JWT' ? 'JWT' : 'client-authentication+jwt',\n ...(req.keyId ? { kid: req.keyId } : {}),\n }\n const payload = {\n iss: req.clientId,\n sub: req.clientId,\n aud: req.audience,\n jti: globalThis.crypto.randomUUID(),\n iat: now,\n exp: now + CLIENT_ASSERTION_LIFETIME_SECONDS,\n }\n const input = `${base64UrlJson(header)}.${base64UrlJson(payload)}`\n let signature: Uint8Array\n try {\n signature = await signAssertionInput(req.algorithm, req.privateKey, input)\n } catch {\n throw new Error(\n `Enterprise MCP authorization: could not sign the client assertion with ${req.algorithm}; check that privateKey is a private key for that algorithm`,\n )\n }\n return `${input}.${base64Url(signature)}`\n}\n\nexport interface IdJagRequest {\n idp: EnterpriseIdpOptions\n /** The ID token (the subject token). */\n idToken: string\n /** The issuer of the MCP server's authorization server. */\n audience: string\n /** The resource identifier of the MCP server. */\n resource: string\n scope?: string\n /** The signed client assertion, when the IdP client uses `private_key_jwt`. */\n clientAssertion?: string\n fetch?: FetchLike\n}\n\n/**\n * Hop 1: exchange the ID token for an ID-JAG at the IdP's token endpoint\n * (RFC 8693, as profiled by the ID-JAG draft, section 4.3). Returns the ID-JAG.\n *\n * Throws `EnterpriseOAuthError` (`hop: 'idp'`) unless the answer is a 200 whose\n * `issued_token_type` is the ID-JAG type and whose `access_token` is a\n * non-empty string. A redirect is refused, not followed: the body holds the ID\n * token and the client's credential. The browser package carries the same\n * function; change both.\n */\nexport const requestIdJag = async (req: IdJagRequest): Promise<string> => {\n const { idp } = req\n const secrets = [\n req.idToken,\n idp.clientSecret,\n req.clientAssertion,\n ...keySecrets(idp.privateKey),\n ]\n // Redacted BEFORE it is clipped: a clipped token no longer matches itself,\n // and the first half of a JWT is its claims.\n const said = (value: unknown, max?: number): string | undefined =>\n printable(typeof value === 'string' ? redact(value, secrets) : value, max)\n const fail = (message: string, code?: string): never => {\n throw new EnterpriseOAuthError(\n 'idp',\n redact(`Enterprise IdP token exchange failed: ${message}`, secrets),\n code,\n )\n }\n\n const params = new URLSearchParams({\n grant_type: GRANT_TOKEN_EXCHANGE,\n requested_token_type: TOKEN_TYPE_ID_JAG,\n audience: req.audience,\n resource: req.resource,\n subject_token: req.idToken,\n subject_token_type: TOKEN_TYPE_ID_TOKEN,\n })\n if (req.scope) {\n params.set('scope', req.scope)\n }\n const headers = new Headers({\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n })\n if (idp.clientAuthMethod === 'private_key_jwt') {\n if (!req.clientAssertion) {\n return fail('no client assertion was made for the identity provider')\n }\n params.set('client_assertion_type', CLIENT_ASSERTION_TYPE)\n params.set('client_assertion', req.clientAssertion)\n } else if (idp.clientSecret === undefined || idp.clientAuthMethod === 'client_secret_post') {\n params.set('client_id', idp.clientId)\n if (idp.clientSecret !== undefined) {\n params.set('client_secret', idp.clientSecret)\n }\n } else {\n // RFC 6749 section 2.3.1: both parts are form-encoded before the base64.\n headers.set(\n 'Authorization',\n `Basic ${btoa(`${formEncode(idp.clientId)}:${formEncode(idp.clientSecret)}`)}`,\n )\n }\n\n let response: Response\n try {\n response = await (req.fetch ?? fetch)(idp.tokenEndpoint, {\n method: 'POST',\n headers,\n body: params,\n redirect: 'error',\n })\n } catch (err) {\n return fail(\n `the request did not complete (${said((err as Error)?.message) ?? 'network error'})`,\n )\n }\n\n let body: Record<string, unknown> = {}\n try {\n const parsed: unknown = await response.json()\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n body = parsed as Record<string, unknown>\n }\n } catch {\n // Not JSON: reported by status below.\n }\n\n if (!response.ok) {\n const code = said(body.error, 80)\n const description = said(body.error_description)\n return fail(\n `the identity provider answered ${response.status}${code ? ` ${code}` : ''}${\n description ? ` - ${description}` : ''\n }`,\n code,\n )\n }\n if (body.issued_token_type !== TOKEN_TYPE_ID_JAG) {\n return fail(\n `the identity provider returned ${\n said(body.issued_token_type, 120) ?? 'no issued_token_type'\n } where an ID-JAG (${TOKEN_TYPE_ID_JAG}) was requested; nothing was sent to the MCP authorization server`,\n )\n }\n if (typeof body.access_token !== 'string' || !body.access_token) {\n return fail(\n 'the identity provider returned no ID-JAG; nothing was sent to the MCP authorization server',\n )\n }\n return body.access_token\n}\n\n/** An https URL with a path of its own: a client ID metadata document. */\nconst looksLikeUrl = (value: string): boolean => /^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)\n\nconst configError = (message: string): Error =>\n new Error(`Enterprise MCP authorization: ${message}`)\n\nconst ASSERTION_AUDIENCES: readonly unknown[] = ['issuer', 'token-endpoint']\nconst ASSERTION_TYPES: readonly unknown[] = ['client-authentication+jwt', 'JWT']\n\n/**\n * The two options that shape a client assertion, for one hop (`prefix` is ''\n * or 'idp.'): a value that is not one of the known ones is refused rather than\n * read as the default, and so is either option where no assertion is signed.\n */\nconst checkAssertionShape = (\n prefix: string,\n hop: { clientAuthMethod?: string; assertionAudience?: unknown; assertionType?: unknown },\n): void => {\n if (hop.assertionAudience !== undefined && !ASSERTION_AUDIENCES.includes(hop.assertionAudience)) {\n throw configError(`${prefix}assertionAudience must be 'issuer' or 'token-endpoint'`)\n }\n if (hop.assertionType !== undefined && !ASSERTION_TYPES.includes(hop.assertionType)) {\n throw configError(`${prefix}assertionType must be 'client-authentication+jwt' or 'JWT'`)\n }\n if (\n hop.clientAuthMethod !== 'private_key_jwt' &&\n (hop.assertionAudience !== undefined || hop.assertionType !== undefined)\n ) {\n throw configError(\n `${prefix}assertionAudience and ${prefix}assertionType are only used with ${prefix}clientAuthMethod 'private_key_jwt'`,\n )\n }\n}\n\n/**\n * What is wrong with the options, said when the provider is built and not in\n * the middle of a flow. Every rule here keeps a credential from going where\n * nobody chose to send it. The browser package carries the same function;\n * change both.\n */\nconst checkOptions = (opts: EnterpriseOAuthProviderOptions): void => {\n assertSecureOAuthUrl(opts.serverUrl)\n assertSecureOAuthUrl(opts.idp?.tokenEndpoint, 'Enterprise IdP token endpoint')\n if (opts.expectedIssuer !== undefined) {\n assertSecureOAuthUrl(opts.expectedIssuer, 'MCP authorization server')\n }\n const { idp } = opts\n if (!opts.clientId || !idp.clientId) {\n throw configError('clientId and idp.clientId are required')\n }\n if (typeof opts.getIdToken !== 'function') {\n throw configError('getIdToken is required')\n }\n\n // The client at the MCP authorization server.\n const method = opts.clientAuthMethod\n if (looksLikeUrl(opts.clientId)) {\n let url: URL | undefined\n try {\n url = new URL(opts.clientId)\n } catch {\n // Reported below.\n }\n if (!url || url.protocol !== 'https:' || url.pathname === '/') {\n throw configError(\n `a clientId that is a URL is a client ID metadata document: it requires https and a non-root path - refusing \"${opts.clientId}\"`,\n )\n }\n if (opts.clientSecret) {\n throw configError(\n 'a client ID metadata document cannot be used with clientSecret: use private_key_jwt, or no credential',\n )\n }\n }\n if (opts.clientSecret && (method === 'private_key_jwt' || method === 'none')) {\n throw configError(`clientSecret is not used with clientAuthMethod '${method}': remove one`)\n }\n if ((method === 'client_secret_basic' || method === 'client_secret_post') && !opts.clientSecret) {\n throw configError(`clientAuthMethod '${method}' needs clientSecret`)\n }\n if (opts.clientSecret && opts.expectedIssuer === undefined) {\n throw configError(\n 'clientSecret needs expectedIssuer: without the issuer of the authorization server, the MCP server decides who receives the secret',\n )\n }\n if (method === 'private_key_jwt') {\n if (opts.privateKey === undefined || !ALGORITHMS.includes(opts.algorithm as never)) {\n throw configError(\n `clientAuthMethod 'private_key_jwt' needs privateKey and an algorithm (${ALGORITHMS.join(', ')})`,\n )\n }\n if (opts.expectedIssuer === undefined) {\n throw configError(\n 'private_key_jwt needs expectedIssuer: the audience of the client assertion must not come from the MCP server alone',\n )\n }\n } else if (opts.privateKey !== undefined) {\n throw configError(\"privateKey is only used with clientAuthMethod 'private_key_jwt'\")\n }\n\n checkAssertionShape('', opts)\n\n // The client at the IdP.\n checkAssertionShape('idp.', idp)\n if (idp.clientAuthMethod === 'private_key_jwt') {\n if (idp.privateKey === undefined || !ALGORITHMS.includes(idp.algorithm as never)) {\n throw configError(\n `idp.clientAuthMethod 'private_key_jwt' needs idp.privateKey and an idp.algorithm (${ALGORITHMS.join(', ')})`,\n )\n }\n // The audience is configuration either way: the issuer, or the token\n // endpoint that is required above. Only the former needs `idp.issuer`.\n if (idp.assertionAudience !== 'token-endpoint' && !idp.issuer) {\n throw configError(\n \"idp.clientAuthMethod private_key_jwt needs idp.issuer: it is the audience of the client assertion (or set idp.assertionAudience to 'token-endpoint')\",\n )\n }\n if (idp.clientSecret) {\n throw configError(\"idp.clientSecret is not used with idp.clientAuthMethod 'private_key_jwt'\")\n }\n } else if (idp.privateKey !== undefined) {\n throw configError(\"idp.privateKey is only used with idp.clientAuthMethod 'private_key_jwt'\")\n }\n if (idp.issuer !== undefined) {\n assertSecureOAuthUrl(idp.issuer, 'Enterprise IdP issuer')\n }\n}\n\n/** One named parameter of a form body, however the caller spelled the body. */\nconst formParam = (body: unknown, name: string): string | undefined => {\n if (body instanceof URLSearchParams) {\n return body.get(name) ?? undefined\n }\n if (typeof body === 'string') {\n return new URLSearchParams(body).get(name) ?? undefined\n }\n return undefined\n}\n\n/** An OAuth `error` code as RFC 6749 spells one, or nothing. */\nconst oauthCode = (value: unknown): string | undefined =>\n typeof value === 'string' && /^[A-Za-z0-9_.-]{1,64}$/.test(value) ? value : undefined\n\n/**\n * A non-interactive `OAuthClientProvider`: no redirect, no browser, no human.\n * On first use, and whenever the access token is missing, expired or rejected,\n * the SDK asks it for a token request and it answers with a fresh ID-JAG.\n */\nexport class BrowserEnterpriseOAuthProvider implements OAuthClientProvider {\n readonly serverUrl: string\n /** The MCP extension this provider implements; the connector declares it. */\n readonly extension = ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION\n /**\n * Present only with an explicit `clientAuthMethod`: the SDK then leaves the\n * client authentication of the grant to it (a `private_key_jwt` assertion is\n * signed here, for the issuer discovery found and `expectedIssuer` confirmed).\n */\n addClientAuthentication?: OAuthClientProvider['addClientAuthentication']\n\n // True private fields: the options hold the secrets, the private keys and the\n // ID token callback, and nothing that prints or serializes the provider\n // (console.log, the devtools object view, JSON.stringify) can reach them.\n readonly #opts: EnterpriseOAuthProviderOptions\n readonly #storage: McpOAuthStorage\n readonly #ns: string\n readonly #skewMs: number\n readonly #clientMetadata: OAuthClientMetadata\n // Held (in memory only) between a granted ID-JAG and the access token it\n // buys: a failure in that window belongs to the MCP authorization server,\n // and nothing said about it may carry the grant or the client assertion.\n #pendingAssertion: string | undefined\n #pendingClientAssertion: string | undefined\n\n constructor(opts: EnterpriseOAuthProviderOptions) {\n checkOptions(opts)\n this.serverUrl = opts.serverUrl\n this.#opts = opts\n this.#storage = opts.storage ?? new VaultOAuthStorage()\n this.#ns = namespaceFor(opts.serverUrl)\n this.#skewMs = (opts.expirySkewSeconds ?? DEFAULT_SKEW_SECONDS) * 1000\n this.#clientMetadata = {\n client_name: 'agent-web',\n redirect_uris: [],\n grant_types: [GRANT_TOKEN_EXCHANGE, GRANT_JWT_BEARER],\n token_endpoint_auth_method:\n opts.clientAuthMethod ?? (opts.clientSecret ? 'client_secret_basic' : 'none'),\n ...(opts.scope ? { scope: opts.scope } : {}),\n }\n if (opts.clientAuthMethod !== undefined) {\n this.addClientAuthentication = (headers, params) => this.#authenticateClient(headers, params)\n }\n }\n\n /** Never set: this is what tells the SDK the flow has no human step. */\n get redirectUrl(): undefined {\n return undefined\n }\n\n get clientMetadata(): OAuthClientMetadata {\n return this.#clientMetadata\n }\n\n #key(suffix: string): string {\n return `${this.#ns}:${suffix}`\n }\n\n async #readJSON<T>(suffix: string): Promise<T | undefined> {\n // The read is inside the guard: the default storage decrypts, and a blob\n // written under a key that no longer exists throws. That is \"no value\".\n try {\n const raw = await this.#storage.get(this.#key(suffix))\n if (raw === undefined) {\n return undefined\n }\n return JSON.parse(raw) as T\n } catch {\n await this.#storage.delete(this.#key(suffix)).catch(() => {})\n return undefined\n }\n }\n\n /** Everything of this provider that must not appear in an error or a log line. */\n #secrets(): (string | undefined)[] {\n return [\n this.#pendingAssertion,\n this.#pendingClientAssertion,\n this.#opts.clientSecret,\n this.#opts.idp.clientSecret,\n ...keySecrets(this.#opts.privateKey),\n ...keySecrets(this.#opts.idp.privateKey),\n ]\n }\n\n /** The detail an error leaves out, to the log: redacted first, then clipped. */\n #report(log: EnterpriseOAuthLog | undefined, detail: string): void {\n // With no log given, the package's logger: the detail is not lost, and it\n // is as redacted there as anywhere.\n const sink: EnterpriseOAuthLog =\n log ?? this.#opts.onLog ?? ((_level, message) => createLogger().warn(message))\n const safe = printable(redact(detail, this.#secrets()), 600) ?? 'no detail'\n try {\n sink('warn', `[mcp] enterprise authorization for ${this.serverUrl}: ${safe}`)\n } catch {\n // A log sink that throws does not get to change the outcome.\n }\n }\n\n /**\n * The pre-registered client, from configuration and never from storage.\n * With `expectedIssuer` it carries that stamp, and the SDK then refuses to\n * present it to any other authorization server.\n */\n clientInformation(): OAuthClientInformationMixed {\n return {\n client_id: this.#opts.clientId,\n ...(this.#opts.clientSecret ? { client_secret: this.#opts.clientSecret } : {}),\n ...(this.#opts.expectedIssuer ? { issuer: this.#opts.expectedIssuer } : {}),\n }\n }\n\n async tokens(): Promise<OAuthTokens | undefined> {\n return (await this.#readJSON<StoredTokens>('tokens'))?.tokens\n }\n\n async saveTokens(tokens: OAuthTokens): Promise<void> {\n this.#pendingAssertion = undefined\n this.#pendingClientAssertion = undefined\n const stored: StoredTokens = {\n tokens,\n expiresAt:\n typeof tokens.expires_in === 'number' ? Date.now() + tokens.expires_in * 1000 : undefined,\n }\n await this.#storage.set(this.#key('tokens'), JSON.stringify(stored))\n }\n\n async saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {\n await this.#storage.set(this.#key('discovery'), JSON.stringify(state))\n }\n\n async discoveryState(): Promise<OAuthDiscoveryState | undefined> {\n const state = await this.#readJSON<OAuthDiscoveryState>('discovery')\n if (!state || typeof state !== 'object' || typeof state.authorizationServerUrl !== 'string') {\n return undefined\n }\n return state\n }\n\n /**\n * Called by the SDK inside `auth()`, after discovery and before the token\n * request to the MCP authorization server: get an ID token from the host,\n * exchange it at the IdP for an ID-JAG addressed to exactly the authorization\n * server and resource discovery found for this server, and hand the SDK the\n * `jwt-bearer` request. Throws before anything reaches the authorization\n * server when discovery cannot be trusted or the IdP's answer is not an ID-JAG.\n */\n async prepareTokenRequest(scope?: string): Promise<URLSearchParams> {\n this.#pendingAssertion = undefined\n this.#pendingClientAssertion = undefined\n let target: { audience: string; resource: string }\n try {\n target = enterpriseGrantTarget(\n this.serverUrl,\n await this.discoveryState(),\n this.#opts.expectedIssuer,\n )\n } catch (err) {\n // Never keep a discovery result that was refused: the next attempt\n // (after the server's 401 says where its metadata lives) starts clean.\n await this.#storage.delete(this.#key('discovery'))\n throw err\n }\n\n let idToken: string\n try {\n idToken = await this.#opts.getIdToken()\n } catch {\n // The host's error is not repeated: it may quote the token it failed on.\n throw new EnterpriseOAuthError(\n 'idp',\n 'Enterprise IdP token exchange failed: getIdToken() threw, so there is no ID token to exchange',\n )\n }\n if (typeof idToken !== 'string' || !idToken) {\n throw new EnterpriseOAuthError(\n 'idp',\n 'Enterprise IdP token exchange failed: getIdToken() returned no ID token',\n )\n }\n\n const { idp } = this.#opts\n // Signed for the IdP and for nothing else - its issuer or, when configured\n // so, its token endpoint, both from configuration: it is no use at the\n // authorization server, whose assertion is made separately.\n const clientAssertion =\n idp.clientAuthMethod === 'private_key_jwt'\n ? await createClientAssertion({\n clientId: idp.clientId,\n audience:\n idp.assertionAudience === 'token-endpoint'\n ? idp.tokenEndpoint\n : (idp.issuer as string),\n privateKey: idp.privateKey as EnterprisePrivateKey,\n algorithm: idp.algorithm as EnterpriseAssertionAlgorithm,\n keyId: idp.keyId,\n type: idp.assertionType,\n }).catch((err: Error) => {\n throw new EnterpriseOAuthError('idp', err.message)\n })\n : undefined\n const assertion = await requestIdJag({\n idp,\n idToken,\n audience: target.audience,\n resource: target.resource,\n scope: scope ?? this.#opts.scope,\n clientAssertion,\n fetch: this.#opts.fetch,\n })\n this.#pendingAssertion = assertion\n return new URLSearchParams({ grant_type: GRANT_JWT_BEARER, assertion })\n }\n\n /** The client authentication of the grant, when `clientAuthMethod` says how. */\n async #authenticateClient(headers: Headers, params: URLSearchParams): Promise<void> {\n const { clientId, clientSecret, clientAuthMethod } = this.#opts\n if (clientAuthMethod === 'private_key_jwt') {\n // The audience is the issuer discovery found, or the token endpoint of\n // that same metadata - either one only after the metadata was checked\n // against `expectedIssuer`, which this method requires.\n const target = enterpriseGrantTarget(\n this.serverUrl,\n await this.discoveryState(),\n this.#opts.expectedIssuer,\n )\n const audience =\n this.#opts.assertionAudience === 'token-endpoint' ? target.tokenEndpoint : target.audience\n if (audience === undefined) {\n this.#pendingAssertion = undefined\n throw new EnterpriseOAuthError(\n 'discovery',\n `Enterprise MCP authorization: the authorization server \"${target.audience}\" published no token endpoint, so there is no audience for the client assertion (assertionAudience 'token-endpoint')`,\n )\n }\n const assertion = await createClientAssertion({\n clientId,\n audience,\n privateKey: this.#opts.privateKey as EnterprisePrivateKey,\n algorithm: this.#opts.algorithm as EnterpriseAssertionAlgorithm,\n keyId: this.#opts.keyId,\n type: this.#opts.assertionType,\n }).catch((err: Error) => {\n this.#pendingAssertion = undefined\n throw new EnterpriseOAuthError('authorization-server', err.message)\n })\n this.#pendingClientAssertion = assertion\n params.set('client_assertion_type', CLIENT_ASSERTION_TYPE)\n params.set('client_assertion', assertion)\n return\n }\n if (clientAuthMethod === 'client_secret_basic') {\n headers.set(\n 'Authorization',\n `Basic ${btoa(`${formEncode(clientId)}:${formEncode(clientSecret as string)}`)}`,\n )\n return\n }\n params.set('client_id', clientId)\n if (clientAuthMethod === 'client_secret_post') {\n params.set('client_secret', clientSecret as string)\n }\n }\n\n /** The codes of the interactive flow: this provider has none. */\n redirectToAuthorization(): never {\n throw new Error('Enterprise MCP authorization has no interactive step')\n }\n saveCodeVerifier(): never {\n throw new Error('Enterprise MCP authorization has no interactive step')\n }\n codeVerifier(): never {\n throw new Error('Enterprise MCP authorization has no interactive step')\n }\n\n /**\n * Called by the SDK when the authorization server rejects what it was sent.\n * The client is configuration, so there is nothing of it to forget; tokens\n * and discovery are dropped as asked.\n */\n async invalidateCredentials(\n scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery',\n ): Promise<void> {\n const targets =\n scope === 'all'\n ? ['tokens', 'discovery']\n : scope === 'tokens' || scope === 'discovery'\n ? [scope]\n : []\n await Promise.all(targets.map((t) => this.#storage.delete(this.#key(t))))\n }\n\n /** True when there is no access token, or it expires within the skew window. */\n async isAccessTokenExpired(): Promise<boolean> {\n const stored = await this.#readJSON<StoredTokens>('tokens')\n if (!stored?.tokens?.access_token) {\n return true\n }\n if (stored.expiresAt === undefined) {\n return false\n }\n return Date.now() + this.#skewMs >= stored.expiresAt\n }\n\n async isAuthorized(): Promise<boolean> {\n return (await this.tokens()) !== undefined\n }\n\n /**\n * The fetch to give the transport that carries this provider (the connector\n * does). It changes one thing: when the request that carries the ID-JAG is\n * refused, the caller gets an `EnterpriseOAuthError` (`hop:\n * 'authorization-server'`) with a short message - the OAuth error code and\n * the status - and what the server said in full goes to `log`, redacted.\n * That holds whenever the SDK asks for a token, at connect or in the middle\n * of a session, so an application never has the server's raw words to show.\n * A refusal is final: every grant is already a fresh one, so the SDK's\n * \"drop the token and try again\" would only repeat the IdP exchange.\n */\n transportFetch(base?: FetchLike, log?: EnterpriseOAuthLog): FetchLike {\n const inner: FetchLike = base ?? ((url, init) => fetch(url, init))\n return async (url, init) => {\n const grant = this.#pendingAssertion\n if (grant === undefined || formParam(init?.body, 'assertion') !== grant) {\n return inner(url, init)\n }\n let response: Response\n try {\n response = await inner(url, init)\n } catch (err) {\n this.#report(log, `the grant request did not complete: ${(err as Error)?.message ?? err}`)\n this.#pendingAssertion = undefined\n this.#pendingClientAssertion = undefined\n throw new EnterpriseOAuthError(\n 'authorization-server',\n 'MCP authorization server could not be reached for the ID-JAG grant',\n )\n }\n if (response.status < 400) {\n return response\n }\n const text = await response.text().catch(() => '')\n let body: Record<string, unknown> = {}\n try {\n const parsed: unknown = JSON.parse(text)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n body = parsed as Record<string, unknown>\n }\n } catch {\n // Not JSON: the status is all there is.\n }\n const code = oauthCode(body.error)\n const description = typeof body.error_description === 'string' ? body.error_description : text\n this.#report(\n log,\n `the authorization server refused the ID-JAG grant with ${response.status}${\n code ? ` ${code}` : ''\n }${description ? `: ${description}` : ''}`,\n )\n this.#pendingAssertion = undefined\n this.#pendingClientAssertion = undefined\n throw new EnterpriseOAuthError(\n 'authorization-server',\n `MCP authorization server refused the ID-JAG grant: ${code ?? 'no error code'} (HTTP ${response.status})`,\n code,\n )\n }\n }\n\n /**\n * Run the whole flow now (discovery, IdP exchange, grant) and store the\n * access token. `connectMcpHttp` calls it before connecting when there is\n * no usable token; call it yourself to fail early. A refusal is an\n * `EnterpriseOAuthError` whose `hop` says who refused.\n */\n async authorize(opts: { fetch?: FetchLike; onLog?: EnterpriseOAuthLog } = {}): Promise<void> {\n try {\n await auth(this, {\n serverUrl: this.serverUrl,\n fetchFn: this.transportFetch(opts.fetch, opts.onLog),\n })\n } catch (err) {\n if (err instanceof EnterpriseOAuthError) {\n throw err\n }\n const detail = (err as Error)?.message ?? String(err)\n if (this.#pendingAssertion !== undefined) {\n // The server answered the grant with something that is not a token.\n this.#report(opts.onLog, `the answer to the ID-JAG grant could not be used: ${detail}`)\n this.#pendingAssertion = undefined\n this.#pendingClientAssertion = undefined\n throw new EnterpriseOAuthError(\n 'authorization-server',\n 'MCP authorization server answered the ID-JAG grant with something that is not a token response',\n )\n }\n // What discovery found is not kept when the flow stopped on it.\n await this.#storage.delete(this.#key('discovery')).catch(() => {})\n const message = printable(redact(detail, this.#secrets()), 500) ?? 'no reason given'\n throw new EnterpriseOAuthError(\n 'discovery',\n `Enterprise MCP authorization: discovery failed (${message})`,\n err instanceof OAuthError ? oauthCode(err.code) : undefined,\n )\n }\n }\n\n /** Forget the access token and what discovery found for this server. */\n async reset(): Promise<void> {\n await this.invalidateCredentials('all')\n }\n}\n\n/** Convenience factory mirroring the rest of the package's `createX` style. */\nexport const createEnterpriseOAuthProvider = (\n opts: EnterpriseOAuthProviderOptions,\n): BrowserEnterpriseOAuthProvider => new BrowserEnterpriseOAuthProvider(opts)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE,QAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAQK;AACP,SAAS,mCAAmC;AAC5C,SAAS,aAAa,kBAAgC;;;ACM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auth","DEFAULT_SKEW_SECONDS","namespaceFor","auth"]}
|