agents 0.33.0 → 0.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{agent-routing-vVMA7m8Y.d.ts → agent-routing-BSoZzNiP.d.ts} +537 -373
- package/dist/agent-routing.d.ts +1 -1
- package/dist/agent-tool-types.d.ts +1 -1
- package/dist/{agent-tools-gGXXkf1z.d.ts → agent-tools-Be-hpRpH.d.ts} +2 -2
- package/dist/agent-tools.d.ts +1 -1
- package/dist/{ai-sdk-Kon40i0q.js → ai-sdk-CRMlEBX7.js} +75 -44
- package/dist/ai-sdk-CRMlEBX7.js.map +1 -0
- package/dist/browser/ai.js +1 -1
- package/dist/browser/index.d.ts +7 -3
- package/dist/browser/index.js +2 -2
- package/dist/browser/tools/ai-sdk.d.ts +68 -3
- package/dist/browser/tools/pi.d.ts +2 -2
- package/dist/browser/tools/tanstack-ai.d.ts +2 -2
- package/dist/{browser-CI97khiJ.d.ts → browser-C9T74n4c.d.ts} +84 -5
- package/dist/{browser-tool-Cxtiwfua.d.ts → browser-tool-DxAYQY9T.d.ts} +2 -2
- package/dist/capability-DBAKc6UZ.js.map +1 -1
- package/dist/{capability-runner-BiVUtjqC.d.ts → capability-runner-uFOdSANC.d.ts} +3 -2
- package/dist/chat/index.d.ts +37 -6
- package/dist/chat/index.js +39 -3
- package/dist/chat/index.js.map +1 -1
- package/dist/chat-sdk/index.d.ts +3 -3
- package/dist/chat-sdk/index.js +1 -1
- package/dist/cli.js +64 -63
- package/dist/client-CkT8voRY.js +3740 -0
- package/dist/client-CkT8voRY.js.map +1 -0
- package/dist/{client-eSfgYvd3.d.ts → client-DqS6oequ.d.ts} +2 -2
- package/dist/client.d.ts +1 -1
- package/dist/{connector-Dl098To-.js → connector-Bphz6wIw.js} +16 -4
- package/dist/connector-Bphz6wIw.js.map +1 -0
- package/dist/{conversations-FjHDRZyD.d.ts → conversations-CoAYNW_q.d.ts} +4 -4
- package/dist/{current-agent-CKgT5d1O.d.ts → current-agent-DShbQHDO.d.ts} +24 -3
- package/dist/current-agent-DhoDkSnH.js.map +1 -1
- package/dist/{do-oauth-client-provider-DtNqv7oj.d.ts → do-oauth-client-provider-BsT8-vtd.d.ts} +22 -2
- package/dist/{durable-object-lifecycle-DOI_bzCH.d.ts → durable-object-lifecycle-CRCA6O0W.d.ts} +2 -2
- package/dist/experimental/channels/index.d.ts +2 -2
- package/dist/experimental/channels/web/index.d.ts +2 -2
- package/dist/experimental/channels/web/index.js +1 -1
- package/dist/experimental/webmcp.js +1 -1
- package/dist/{gateway-BFO6vRDn.d.ts → gateway-Dz8zyZBJ.d.ts} +2 -2
- package/dist/harness/ai-sdk/index.d.ts +2 -2
- package/dist/harness/container/index.d.ts +2 -2
- package/dist/harness/container/index.js +1 -1
- package/dist/harness/container/index.js.map +1 -1
- package/dist/harness/opencode/index.d.ts +1 -1
- package/dist/harness/pi/index.d.ts +128 -12
- package/dist/harness/pi/index.js +128 -20
- package/dist/harness/pi/index.js.map +1 -1
- package/dist/harness/think/index.d.ts +2 -2
- package/dist/{images-CfuRCjwq.js → images-D4gtE06D.js} +119 -27
- package/dist/images-D4gtE06D.js.map +1 -0
- package/dist/{index-8k4qsX1T.d.ts → index-BXVgv6tp.d.ts} +4 -4
- package/dist/{index-BEL3ZV-s.d.ts → index-Cs7Ed9la.d.ts} +2 -2
- package/dist/{index-CBt8oRJt.d.ts → index-XiZxauMU.d.ts} +3 -3
- package/dist/index.d.ts +21 -21
- package/dist/index.js +2 -2
- package/dist/{input-schema-0uUu392-.js → input-schema-D6GilRXI.js} +2 -2
- package/dist/{input-schema-0uUu392-.js.map → input-schema-D6GilRXI.js.map} +1 -1
- package/dist/{input-schema-waggtYrH.js → input-schema-y8W5bOdM.js} +2 -2
- package/dist/{input-schema-waggtYrH.js.map → input-schema-y8W5bOdM.js.map} +1 -1
- package/dist/internal_context.d.ts +1 -1
- package/dist/lifecycle/index.d.ts +3 -3
- package/dist/lifecycle/index.js +1 -1
- package/dist/{lifecycle-v1rKHV2C.js → lifecycle-CB5Dmtrt.js} +126 -38
- package/dist/lifecycle-CB5Dmtrt.js.map +1 -0
- package/dist/mcp/client/do-oauth-client-provider.d.ts +1 -1
- package/dist/mcp/client/do-oauth-client-provider.js +45 -2
- package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/client/index.d.ts +42 -36
- package/dist/mcp/client/index.js +2 -2
- package/dist/mcp/client/x402.d.ts +8 -8
- package/dist/mcp/index.d.ts +17 -17
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- package/dist/models/ai-sdk/index.d.ts +9 -5
- package/dist/models/ai-sdk/index.js +1 -1
- package/dist/models/opencode/index.d.ts +3 -3
- package/dist/models/opencode/index.js +2 -2
- package/dist/models/opencode/index.js.map +1 -1
- package/dist/models/pi-ai/index.d.ts +4 -4
- package/dist/models/pi-ai/index.js +53 -29
- package/dist/models/pi-ai/index.js.map +1 -1
- package/dist/{options-CiIsJHXR.d.ts → options-CiXaymmZ.d.ts} +2 -2
- package/dist/queue/index.d.ts +1 -1
- package/dist/queue/index.js +1 -1
- package/dist/{queue-CcIjVYTE.js → queue-B_wl6K0Z.js} +24 -5
- package/dist/queue-B_wl6K0Z.js.map +1 -0
- package/dist/react.d.ts +2 -2
- package/dist/routing/index.d.ts +2 -2
- package/dist/{scheduler-BCLESHSC.d.ts → scheduler-CTpR0Ct0.d.ts} +2 -2
- package/dist/{scheduler-FIHv2-kJ.js → scheduler-DGNEmxQR.js} +2 -1
- package/dist/scheduler-DGNEmxQR.js.map +1 -0
- package/dist/schedules/index.d.ts +1 -1
- package/dist/schedules/index.js +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/session-CRY0bGiI.js.map +1 -1
- package/dist/sessions/index.d.ts +1 -1
- package/dist/{settings-Dk2il2Hf.js → settings-D2F_qONv.js} +11 -2
- package/dist/settings-D2F_qONv.js.map +1 -0
- package/dist/{src-DoGNJ4Ud.js → src-BO1FdLK1.js} +145 -86
- package/dist/src-BO1FdLK1.js.map +1 -0
- package/dist/state/index.d.ts +1 -1
- package/dist/streams/index.d.ts +1 -1
- package/dist/{streams-vrCtbUIn.d.ts → streams-CAZxZBDg.d.ts} +2 -2
- package/dist/sub-routing.d.ts +12 -12
- package/dist/tasks/index.d.ts +1 -1
- package/dist/tasks/index.js +1 -1
- package/dist/{tasks-BN_5AWqI.js → tasks-Cf_UfEO4.js} +2 -1
- package/dist/{tasks-BN_5AWqI.js.map → tasks-Cf_UfEO4.js.map} +1 -1
- package/dist/{tasks-E89KdwkS.d.ts → tasks-Cs8ilctE.d.ts} +2 -2
- package/dist/{tool-DkT_DJBm.js → tool-CmAGY6Fo.js} +24 -3
- package/dist/tool-CmAGY6Fo.js.map +1 -0
- package/dist/{tool-CxKsvxjm.js → tool-Kxcj8_22.js} +24 -4
- package/dist/tool-Kxcj8_22.js.map +1 -0
- package/dist/{transport-5moD2pW5.d.ts → transport-hV8AW4Bv.d.ts} +45 -12
- package/dist/voice/index.d.ts +2 -2
- package/dist/web/fetch/index.js +1 -1
- package/dist/web/fetch/tools/ai-sdk.js +2 -2
- package/dist/web/fetch/tools/pi.d.ts +5 -0
- package/dist/web/fetch/tools/pi.js +25 -2
- package/dist/web/fetch/tools/pi.js.map +1 -1
- package/dist/web/fetch/tools/tanstack-ai.js +2 -2
- package/dist/web/search/index.js +1 -1
- package/dist/web/search/tools/ai-sdk.js +2 -2
- package/dist/web/search/tools/pi.d.ts +4 -0
- package/dist/web/search/tools/pi.js +23 -2
- package/dist/web/search/tools/pi.js.map +1 -1
- package/dist/web/search/tools/tanstack-ai.js +2 -2
- package/dist/websockets/index.d.ts +2 -2
- package/dist/websockets/index.js +1 -1
- package/dist/{websockets-C6SJtWCJ.js → websockets-W4uhRg4-.js} +68 -5
- package/dist/websockets-W4uhRg4-.js.map +1 -0
- package/dist/workflow-types.d.ts +1 -1
- package/dist/workflows.d.ts +1 -1
- package/docs/agent-class.md +30 -4
- package/docs/browse-the-web.md +14 -0
- package/docs/chat-agents.md +13 -10
- package/docs/client-tools-continuation.md +1 -1
- package/docs/codemode.md +1 -1
- package/docs/configuration.md +6 -3
- package/docs/cross-domain-authentication.md +1 -1
- package/docs/fetch-the-web.md +20 -0
- package/docs/harnesses/pi.md +211 -22
- package/docs/harnesses/think.md +1 -1
- package/docs/http-websockets.md +40 -32
- package/docs/human-in-the-loop.md +2 -2
- package/docs/lifecycle.md +56 -0
- package/docs/mcp-client.md +104 -7
- package/docs/models-pi-ai.md +24 -10
- package/docs/models.md +42 -17
- package/docs/resumable-streaming.md +1 -1
- package/docs/retries.md +3 -6
- package/docs/search-the-web.md +10 -0
- package/docs/voice.md +1 -1
- package/package.json +13 -12
- package/dist/ai-sdk-CpuRsjP5.d.ts +0 -72
- package/dist/ai-sdk-Kon40i0q.js.map +0 -1
- package/dist/client-DMWujQJ1.js +0 -2325
- package/dist/client-DMWujQJ1.js.map +0 -1
- package/dist/connector-Dl098To-.js.map +0 -1
- package/dist/images-CfuRCjwq.js.map +0 -1
- package/dist/lifecycle-v1rKHV2C.js.map +0 -1
- package/dist/queue-CcIjVYTE.js.map +0 -1
- package/dist/scheduler-FIHv2-kJ.js.map +0 -1
- package/dist/settings-Dk2il2Hf.js.map +0 -1
- package/dist/src-DoGNJ4Ud.js.map +0 -1
- package/dist/tool-CxKsvxjm.js.map +0 -1
- package/dist/tool-DkT_DJBm.js.map +0 -1
- package/dist/websockets-C6SJtWCJ.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-CkT8voRY.js","names":[],"sources":["../src/core/events.ts","../src/mcp/abort.ts","../src/mcp/rpc.ts","../src/mcp/client/catalog.ts","../src/mcp/client/authorization-turns.ts","../src/mcp/client/runtime.ts","../src/mcp/client/errors.ts","../src/mcp/client/connection.ts","../src/mcp/client/ai-tools.ts","../src/mcp/client/authorization-rounds.ts","../src/mcp/client/oauth-callback.ts","../src/mcp/client/server-lanes.ts","../src/mcp/client/authorization.ts","../src/mcp/client/elicitation.ts","../src/mcp/client/storage.ts","../src/mcp/client/rpc.ts","../src/mcp/client/url-policy.ts","../src/mcp/client/servers.ts","../src/mcp/client/legacy-connect.ts","../src/mcp/client/server-store.ts","../src/mcp/client/status.ts","../src/mcp/client/manager.ts"],"sourcesContent":["export interface Disposable {\n dispose(): void;\n}\n\nexport function toDisposable(fn: () => void): Disposable {\n return { dispose: fn };\n}\n\nexport class DisposableStore implements Disposable {\n private readonly _items: Disposable[] = [];\n\n add<T extends Disposable>(d: T): T {\n this._items.push(d);\n return d;\n }\n\n dispose(): void {\n while (this._items.length) {\n try {\n this._items.pop()!.dispose();\n } catch {\n // best-effort cleanup\n }\n }\n }\n}\n\nexport type Event<T> = (listener: (e: T) => void) => Disposable;\n\nexport class Emitter<T> implements Disposable {\n private _listeners: Set<(e: T) => void> = new Set();\n\n readonly event: Event<T> = (listener) => {\n this._listeners.add(listener);\n return toDisposable(() => this._listeners.delete(listener));\n };\n\n fire(data: T): void {\n for (const listener of [...this._listeners]) {\n try {\n listener(data);\n } catch (err) {\n // do not let one bad listener break others\n console.error(\"Emitter listener error:\", err);\n }\n }\n }\n\n dispose(): void {\n this._listeners.clear();\n }\n}\n","export function abortError(signal: AbortSignal): Error {\n return signal.reason instanceof Error\n ? signal.reason\n : new Error(String(signal.reason ?? \"Aborted\"));\n}\n\n/**\n * Stop awaiting an operation when its owner aborts. The underlying operation\n * remains responsible for observing the same signal and cancelling its work.\n */\nexport async function raceWithSignal<T>(\n promise: Promise<T>,\n signal?: AbortSignal\n): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) throw abortError(signal);\n\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError(signal));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", onAbort);\n });\n });\n}\n","import type {\n JSONRPCMessage as V2JSONRPCMessage,\n MessageExtraInfo as V2MessageExtraInfo,\n Transport as V2Transport,\n TransportSendOptions as V2TransportSendOptions\n} from \"@modelcontextprotocol/client\";\nimport type { Agent } from \"../index\";\nimport { getAgentByName } from \"../agent-routing\";\nimport { raceWithSignal } from \"./abort\";\n\n// This module is reachable from the root `agents` entry (via MCPClientManager),\n// so it must not depend on `@modelcontextprotocol/sdk` (an optional peer) or on\n// the legacy `McpAgent` class. The v1 server-side transport lives in\n// `./rpc-server`.\n\n/**\n * Structural shape of a Durable Object that serves MCP over RPC, such as\n * `McpAgent`. Declared structurally so the client side does not pull the\n * legacy server (and `@modelcontextprotocol/sdk`) into its types.\n */\nexport type McpRpcAgent = Agent<\n Cloudflare.Env,\n unknown,\n Record<string, unknown>\n> & {\n handleMcpMessage(\n message: V2JSONRPCMessage | V2JSONRPCMessage[]\n ): Promise<V2JSONRPCMessage | V2JSONRPCMessage[] | undefined>;\n};\n\nexport const RPC_DO_PREFIX = \"rpc:\";\n\n/** Narrow an unknown runtime binding to an MCP Durable Object namespace. */\nexport function isDurableObjectNamespace<\n T extends Rpc.DurableObjectBranded = McpRpcAgent\n>(namespace: unknown): namespace is DurableObjectNamespace<T> {\n return (\n typeof namespace === \"object\" &&\n namespace !== null &&\n \"newUniqueId\" in namespace &&\n typeof namespace.newUniqueId === \"function\" &&\n \"idFromName\" in namespace &&\n typeof namespace.idFromName === \"function\"\n );\n}\n\nexport interface RPCClientTransportOptions<\n T extends McpRpcAgent = McpRpcAgent\n> {\n namespace: DurableObjectNamespace<T>;\n name: string;\n props?: Record<string, unknown>;\n}\n\nexport class RPCClientTransport implements V2Transport {\n private _namespace: DurableObjectNamespace<McpRpcAgent>;\n private _name: string;\n private _props?: Record<string, unknown>;\n private _stub?: DurableObjectStub<McpRpcAgent>;\n private _started = false;\n private _protocolVersion?: string;\n\n sessionId?: string;\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: V2JSONRPCMessage, extra?: V2MessageExtraInfo) => void;\n\n constructor(options: RPCClientTransportOptions<McpRpcAgent>) {\n this._namespace = options.namespace;\n this._name = options.name;\n this._props = options.props;\n }\n\n setProtocolVersion(version: string): void {\n this._protocolVersion = version;\n }\n\n getProtocolVersion(): string | undefined {\n return this._protocolVersion;\n }\n\n async start(): Promise<void> {\n if (this._started) {\n throw new Error(\"Transport already started\");\n }\n\n const doName = `${RPC_DO_PREFIX}${this._name}`;\n this._stub = await getAgentByName<Cloudflare.Env, McpRpcAgent>(\n this._namespace,\n doName,\n { props: this._props }\n );\n\n this._started = true;\n }\n\n async close(): Promise<void> {\n this._started = false;\n this._stub = undefined;\n this.onclose?.();\n }\n\n async send(\n message: V2JSONRPCMessage | V2JSONRPCMessage[],\n options?: V2TransportSendOptions\n ): Promise<void> {\n if (!this._started || !this._stub) {\n throw new Error(\"Transport not started\");\n }\n\n try {\n const pending = this._stub.handleMcpMessage(message) as Promise<\n V2JSONRPCMessage | V2JSONRPCMessage[] | undefined\n >;\n const result = await raceWithSignal(pending, options?.requestSignal);\n\n if (!result || options?.requestSignal?.aborted) {\n return;\n }\n\n // The v2 client transport contract no longer uses the v1 requestInfo\n // placeholder. Correlation is carried by JSON-RPC ids in this adapter.\n const extra: V2MessageExtraInfo | undefined = undefined;\n\n const messages = Array.isArray(result) ? result : [result];\n for (const msg of messages) {\n this.onmessage?.(msg, extra);\n }\n } catch (error) {\n this.onerror?.(error as Error);\n throw error;\n }\n }\n}\n","import type {\n Client,\n ListPromptsResult,\n ListResourceTemplatesResult,\n ListResourcesResult,\n ListToolsResult,\n Prompt,\n Resource,\n ResourceTemplateType as ResourceTemplate,\n Tool\n} from \"@modelcontextprotocol/client\";\nimport type { MCPClientConnection } from \"./connection\";\nimport type { MCPServerRow } from \"./storage\";\nimport type { MCPServerFilter } from \"./types\";\n\ntype CapabilityErrorHandler = <T>(\n empty: T,\n method: string\n) => (error: { code: number }) => T;\n\ntype CatalogFetchOptions = {\n probing: boolean;\n onCapabilityError: CapabilityErrorHandler;\n};\n\nexport async function fetchMcpTools(\n client: Client,\n options: CatalogFetchOptions\n): Promise<Tool[]> {\n let aggregate: Tool[] = [];\n let page: ListToolsResult = { tools: [] };\n do {\n const params = { cursor: page.nextCursor };\n page = await (\n options.probing\n ? client.request({ method: \"tools/list\", params })\n : client.listTools(params)\n ).catch(options.onCapabilityError({ tools: [] }, \"tools/list\"));\n aggregate = aggregate.concat(page.tools);\n } while (page.nextCursor);\n return aggregate;\n}\n\nexport async function fetchMcpResources(\n client: Client,\n options: CatalogFetchOptions\n): Promise<Resource[]> {\n let aggregate: Resource[] = [];\n let page: ListResourcesResult = { resources: [] };\n do {\n const params = { cursor: page.nextCursor };\n page = await (\n options.probing\n ? client.request({ method: \"resources/list\", params })\n : client.listResources(params)\n ).catch(options.onCapabilityError({ resources: [] }, \"resources/list\"));\n aggregate = aggregate.concat(page.resources);\n } while (page.nextCursor);\n return aggregate;\n}\n\nexport async function fetchMcpPrompts(\n client: Client,\n options: CatalogFetchOptions\n): Promise<Prompt[]> {\n let aggregate: Prompt[] = [];\n let page: ListPromptsResult = { prompts: [] };\n do {\n const params = { cursor: page.nextCursor };\n page = await (\n options.probing\n ? client.request({ method: \"prompts/list\", params })\n : client.listPrompts(params)\n ).catch(options.onCapabilityError({ prompts: [] }, \"prompts/list\"));\n aggregate = aggregate.concat(page.prompts);\n } while (page.nextCursor);\n return aggregate;\n}\n\nexport async function fetchMcpResourceTemplates(\n client: Client,\n options: CatalogFetchOptions\n): Promise<ResourceTemplate[]> {\n let aggregate: ResourceTemplate[] = [];\n let page: ListResourceTemplatesResult = { resourceTemplates: [] };\n do {\n const params = { cursor: page.nextCursor };\n page = await (\n options.probing\n ? client.request({ method: \"resources/templates/list\", params })\n : client.listResourceTemplates(params)\n ).catch(\n options.onCapabilityError(\n { resourceTemplates: [] },\n \"resources/templates/list\"\n )\n );\n aggregate = aggregate.concat(page.resourceTemplates);\n } while (page.nextCursor);\n return aggregate;\n}\n\nexport type NamespacedData = {\n tools: (Tool & { serverId: string })[];\n prompts: (Prompt & { serverId: string })[];\n resources: (Resource & { serverId: string })[];\n resourceTemplates: (ResourceTemplate & { serverId: string })[];\n};\n\n/** One catalog of every given connection, each entry tagged with its server. */\nexport function getNamespacedData<T extends keyof NamespacedData>(\n mcpClients: Record<string, MCPClientConnection>,\n type: T\n): NamespacedData[T] {\n const namespaced = Object.entries(mcpClients).flatMap(([serverId, conn]) =>\n conn[type].map((item) => ({ ...item, serverId }))\n );\n // TypeScript cannot narrow the union of item types per key here.\n return namespaced as NamespacedData[T];\n}\n\n/** The connections a filter selects; every criterion must match. */\nexport function filterConnections(\n connections: Record<string, MCPClientConnection>,\n servers: () => MCPServerRow[],\n filter: MCPServerFilter | undefined\n): Record<string, MCPClientConnection> {\n if (!filter) return connections;\n const serverIds = asList(filter.serverId);\n const serverNames = asList(filter.serverName);\n const states = asList(filter.state);\n const namedIds = serverNames\n ? new Set(\n servers()\n .filter((server) => serverNames.includes(server.name))\n .map((server) => server.id)\n )\n : undefined;\n return Object.fromEntries(\n Object.entries(connections).filter(\n ([id, conn]) =>\n (!serverIds || serverIds.includes(id)) &&\n (!namedIds || namedIds.has(id)) &&\n (!states || states.includes(conn.connectionState))\n )\n );\n}\n\nfunction asList<T>(value: T | T[] | undefined): T[] | undefined {\n if (!value) return undefined;\n return Array.isArray(value) ? value : [value];\n}\n","import type { AgentMcpOAuthProvider } from \"./do-oauth-client-provider\";\n\n/** The `fetch` shape the SDK's HTTP transports accept. */\nexport type TransportFetch = (\n input: string | URL,\n init?: RequestInit\n) => Promise<Response>;\n\n/** The part of the SDK's adapted auth provider a transport calls on a 401. */\ntype UnauthorizedHandler = {\n onUnauthorized?: (context: unknown) => Promise<void>;\n};\n\n/**\n * One OAuth flow at a time per connection.\n *\n * The SDK transport answers every `401` by calling its auth provider's\n * `onUnauthorized`, which refreshes the token or registers a client and builds\n * an authorization URL with a fresh state and code verifier. When several\n * requests get a `401` together (catalog discovery lists tools, prompts and\n * resources in parallel, alongside the listen stream), those flows interleave\n * on one provider: each registers its own client, and the link the manager\n * saves can belong to a different client than the verifier stored for it, so\n * the link can never complete. Two refreshes racing on a rotating refresh\n * token lose the same way.\n *\n * Requests still go out together. Each `401`'s authorization waits until the\n * one before it has finished, whether it succeeded, built a link or failed,\n * so it reuses the client and tokens the previous flow saved. When that flow\n * already saved a newer access token, there is nothing left to authorize:\n * the SDK retries the request with the new token.\n */\nexport class AuthorizationTurns {\n /** Settles when every flow started so far has finished. */\n #tail: Promise<void> = Promise.resolve();\n /** The access token each 401 response's request was sent with. */\n readonly #sentTokens = new WeakMap<Response, string | undefined>();\n #warnedUnwrapped = false;\n\n /**\n * A `fetch` for the transport that remembers which access token a request\n * carried when it got a 401, so its authorization can tell whether a\n * newer token already exists.\n */\n wrapFetch(base: TransportFetch | undefined): TransportFetch {\n return async (input, init) => {\n const response = await (base ?? fetch)(input, init);\n if (response.status === 401) {\n this.#sentTokens.set(response, bearerToken(init?.headers));\n }\n return response;\n };\n }\n\n /**\n * Take a transport's 401 handling in turns. The SDK keeps the adapted\n * provider on the transport as `_authProvider`; when a later SDK moves it,\n * this does nothing, and the integration tests that send concurrent 401s\n * fail.\n */\n wrapTransport(transport: object, provider: AgentMcpOAuthProvider): void {\n const adapted = (transport as { _authProvider?: UnauthorizedHandler })\n ._authProvider;\n const onUnauthorized = adapted?.onUnauthorized?.bind(adapted);\n if (!adapted || !onUnauthorized) {\n if (!this.#warnedUnwrapped) {\n this.#warnedUnwrapped = true;\n console.warn(\n \"[MCPClientManager] The MCP SDK transport no longer exposes its auth provider; concurrent 401s will not share one OAuth flow.\"\n );\n }\n return;\n }\n\n adapted.onUnauthorized = async (context) => {\n // The token the failed request carried, else the one held now.\n const response = responseOf(context);\n const tokenSent =\n response && this.#sentTokens.has(response)\n ? this.#sentTokens.get(response)\n : await accessToken(provider);\n await this.run(async () => {\n const tokenNow = await accessToken(provider);\n if (tokenNow && tokenNow !== tokenSent) return;\n await onUnauthorized(context);\n });\n };\n }\n\n /**\n * Run `flow` once every flow started before it has finished, and hold\n * later flows until it has. A callback's code exchange runs here too, so\n * a refresh that started before it cannot save its older grant over the\n * one the exchange saves.\n */\n run<T>(flow: () => Promise<T>): Promise<T> {\n const result = this.#tail.then(flow);\n this.#tail = result.then(\n () => {},\n () => {}\n );\n return result;\n }\n}\n\nasync function accessToken(\n provider: AgentMcpOAuthProvider\n): Promise<string | undefined> {\n try {\n return (await provider.tokens())?.access_token;\n } catch {\n return undefined;\n }\n}\n\nfunction bearerToken(headers: HeadersInit | undefined): string | undefined {\n const value = new Headers(headers).get(\"authorization\");\n return value?.startsWith(\"Bearer \")\n ? value.slice(\"Bearer \".length)\n : undefined;\n}\n\nfunction responseOf(context: unknown): Response | undefined {\n if (typeof context !== \"object\" || context === null) return undefined;\n const { response } = context as { response?: unknown };\n return response instanceof Response ? response : undefined;\n}\n","import {\n Client,\n type ClientCapabilities,\n type JsonSchemaType,\n type jsonSchemaValidator,\n type ListChangedHandlers,\n type Prompt,\n type Resource,\n type Tool\n} from \"@modelcontextprotocol/client\";\nimport { CfWorkerJsonSchemaValidator } from \"@modelcontextprotocol/client/validators/cf-worker\";\nimport type { McpClientOptions } from \"../types\";\n\nclass CompatibleWorkerJsonSchemaValidator\n extends CfWorkerJsonSchemaValidator\n implements jsonSchemaValidator\n{\n private readonly legacy = new CfWorkerJsonSchemaValidator({ draft: \"7\" });\n\n override getValidator<T>(schema: JsonSchemaType) {\n const dialect = schema.$schema;\n return typeof dialect === \"string\" && /draft-0?7/i.test(dialect)\n ? this.legacy.getValidator<T>(schema)\n : super.getValidator<T>(schema);\n }\n}\n\nconst DEFAULT_CLIENT_OPTIONS: NonNullable<McpClientOptions> = {\n jsonSchemaValidator: new CompatibleWorkerJsonSchemaValidator(),\n versionNegotiation: { mode: \"auto\" },\n inputRequired: { autoFulfill: true }\n};\n\nexport function normalizeMcpClientOptions(\n options?: McpClientOptions\n): NonNullable<McpClientOptions> {\n return {\n ...DEFAULT_CLIENT_OPTIONS,\n ...options,\n versionNegotiation: {\n ...DEFAULT_CLIENT_OPTIONS.versionNegotiation,\n ...options?.versionNegotiation\n },\n inputRequired: {\n ...DEFAULT_CLIENT_OPTIONS.inputRequired,\n ...options?.inputRequired\n }\n };\n}\n\nexport function elicitationCapabilitiesFromHandlers(handlers?: {\n form?: unknown;\n url?: unknown;\n}): ClientCapabilities[\"elicitation\"] | undefined {\n if (!handlers) return undefined;\n const elicitation: NonNullable<ClientCapabilities[\"elicitation\"]> = {};\n if (handlers.form) elicitation.form = {};\n if (handlers.url) elicitation.url = {};\n return elicitation.form || elicitation.url ? elicitation : undefined;\n}\n\ntype CatalogCallbacks = {\n tools(error: Error | null, tools: Tool[] | null): void;\n prompts(error: Error | null, prompts: Prompt[] | null): void;\n resources(error: Error | null, resources: Resource[] | null): void;\n};\n\nfunction listChangedHandlers(\n configured: ListChangedHandlers | undefined,\n callbacks: CatalogCallbacks\n): ListChangedHandlers {\n return {\n tools: {\n ...configured?.tools,\n onChanged: (error, tools) => {\n callbacks.tools(error, tools);\n configured?.tools?.onChanged(error, tools);\n }\n },\n prompts: {\n ...configured?.prompts,\n onChanged: (error, prompts) => {\n callbacks.prompts(error, prompts);\n configured?.prompts?.onChanged(error, prompts);\n }\n },\n resources: {\n ...configured?.resources,\n onChanged: (error, resources) => {\n callbacks.resources(error, resources);\n configured?.resources?.onChanged(error, resources);\n }\n }\n };\n}\n\n/**\n * The elicitation capability a client built now would advertise: explicit\n * client capabilities, else the handlers' modes, else the restore seed.\n */\nexport function advertisedElicitation(\n options: NonNullable<McpClientOptions>,\n capabilitySeed: ClientCapabilities | undefined,\n handlerModes: { form?: unknown; url?: unknown } | undefined\n): ClientCapabilities[\"elicitation\"] | undefined {\n return (\n options.capabilities?.elicitation ??\n elicitationCapabilitiesFromHandlers(handlerModes) ??\n capabilitySeed?.elicitation\n );\n}\n\nexport function createMcpSdkClient(\n info: ConstructorParameters<typeof Client>[0],\n options: NonNullable<McpClientOptions>,\n capabilitySeed: ClientCapabilities | undefined,\n handlerModes: { form?: unknown; url?: unknown } | undefined,\n callbacks: CatalogCallbacks\n): { client: Client; elicitationEnabled: boolean } {\n const elicitation = advertisedElicitation(\n options,\n capabilitySeed,\n handlerModes\n );\n const client = new Client(info, {\n ...options,\n capabilities: {\n ...capabilitySeed,\n ...options.capabilities,\n ...(elicitation ? { elicitation } : {})\n },\n listChanged: listChangedHandlers(options.listChanged, callbacks)\n });\n return { client, elicitationEnabled: elicitation !== undefined };\n}\n","import {\n OAuthError,\n RegistrationRejectedError,\n UnauthorizedError\n} from \"@modelcontextprotocol/client\";\n\n/**\n * Thrown by `MCPClientManager.callTool()` (and `readResource()` /\n * `getPrompt()`) when a request on a ready connection needs the user to\n * authorize again: a `403 insufficient_scope` step-up, or a `401` whose token\n * refresh failed. The MCP SDK has already built a new authorization URL; the\n * manager has moved the connection to `authenticating` and persisted\n * `authUrl`, so sending the user to `authUrl` completes through the normal\n * OAuth callback. Retry the request once the connection is `ready` again.\n *\n * Extends the SDK's `UnauthorizedError`, which these calls threw before, and\n * keeps its `name`, so existing `instanceof UnauthorizedError` and\n * `name === \"UnauthorizedError\"` checks keep matching. Use\n * `instanceof MCPAuthorizationRequiredError` to read `authUrl`.\n */\nexport class MCPAuthorizationRequiredError extends UnauthorizedError {\n /** Stable discriminant for this error. */\n readonly _tag = \"MCPAuthorizationRequiredError\" as const;\n /** The MCP server that needs authorization. */\n readonly serverId: string;\n /** The authorization URL to send the user to; also persisted as `auth_url`. */\n readonly authUrl: string;\n /** The OAuth client id used for the authorization request, when known. */\n readonly clientId?: string;\n\n /**\n * @param serverId - The MCP server that needs authorization.\n * @param authUrl - The authorization URL the SDK built for the new flow.\n * @param options - The OAuth client id and the original unauthorized error.\n */\n constructor(\n serverId: string,\n authUrl: string,\n options: { clientId?: string; cause?: unknown } = {}\n ) {\n super(\n `MCP server \"${serverId}\" requires authorization: ${toErrorMessage(options.cause ?? \"Unauthorized\")}`\n );\n this.cause = options.cause;\n this.serverId = serverId;\n this.authUrl = authUrl;\n this.clientId = options.clientId;\n }\n}\n\n/**\n * Thrown by `MCPClientManager.callTool()`, `readResource()` and `getPrompt()`\n * when no connection exists for `serverId`: the id was never registered, the\n * server was removed, or a restore has not created the connection yet.\n */\nexport class MCPConnectionNotFoundError extends Error {\n /** Stable discriminant for this error. */\n readonly _tag = \"MCPConnectionNotFoundError\" as const;\n\n /**\n * @param serverId - The server id that has no connection.\n */\n constructor(readonly serverId: string) {\n super(\n `No MCP connection for server \"${serverId}\". It may not be registered yet, may have been removed, or may still be restoring.`\n );\n this.name = \"MCPConnectionNotFoundError\";\n }\n}\n\n/** Message of an unknown thrown value. */\nexport function toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction getErrorStatus(error: unknown): number | undefined {\n if (!error || typeof error !== \"object\") return undefined;\n const record = error as {\n code?: unknown;\n status?: unknown;\n data?: { status?: unknown; cause?: unknown };\n };\n if (typeof record.code === \"number\") return record.code;\n if (typeof record.status === \"number\") return record.status;\n if (typeof record.data?.status === \"number\") return record.data.status;\n return undefined;\n}\n\nfunction getErrorCause(error: unknown): unknown {\n if (!error || typeof error !== \"object\") return undefined;\n return (\n (error as { cause?: unknown; data?: { cause?: unknown } }).cause ??\n (error as { data?: { cause?: unknown } }).data?.cause\n );\n}\n\nexport function isUnauthorized(error: unknown): boolean {\n const status = getErrorStatus(error);\n if (status === 401) return true;\n const cause = getErrorCause(error);\n if (cause && cause !== error && isUnauthorized(cause)) return true;\n\n const msg = toErrorMessage(error);\n return msg.includes(\"Unauthorized\") || msg.includes(\"401\");\n}\n\n/**\n * OAuth error codes a retry can change: the authorization server's own\n * trouble. Every other code (`invalid_target`, `invalid_scope`,\n * `access_denied`, `unauthorized_client`, ...) refuses the request itself.\n * The SDK already recovers `invalid_grant` and `invalid_client` once by\n * starting a fresh authorization, so when they reach us that has failed too.\n */\nconst RETRYABLE_OAUTH_ERRORS = new Set([\n \"server_error\",\n \"temporarily_unavailable\"\n]);\n\n/**\n * Whether an error means authorization was refused in a way retrying cannot\n * change: the MCP server answered 403, the authorization server answered\n * with an OAuth error other than a temporary one, or it rejected dynamic\n * client registration with a 4xx other than 429.\n */\nexport function isAuthorizationRefused(error: unknown, depth = 0): boolean {\n if (depth > 5 || !error || typeof error !== \"object\") return false;\n if (OAuthError.isInstance(error)) {\n return !RETRYABLE_OAUTH_ERRORS.has(error.code);\n }\n if (RegistrationRejectedError.isInstance(error)) {\n return error.status >= 400 && error.status < 500 && error.status !== 429;\n }\n if (getErrorStatus(error) === 403) return true;\n const cause = getErrorCause(error);\n return cause !== error && isAuthorizationRefused(cause, depth + 1);\n}\n\n// MCP SDK change (v1.24.0, commit 6b90e1a):\n// - Old: Error POSTing to endpoint (HTTP 404): Not Found\n// - New: StreamableHTTPError with code: 404 and message Error POSTing to endpoint: Not Found\nexport function isTransportNotImplemented(error: unknown): boolean {\n const status = getErrorStatus(error);\n if (status === 404 || status === 405) return true;\n const cause = getErrorCause(error);\n if (cause && cause !== error && isTransportNotImplemented(cause)) return true;\n\n const msg = toErrorMessage(error);\n return (\n msg.includes(\"404\") ||\n msg.includes(\"405\") ||\n msg.includes(\"Error POSTing to endpoint: Not Found\") ||\n msg.includes(\"Not Implemented\") ||\n msg.includes(\"not implemented\")\n );\n}\n","import {\n Client,\n SSEClientTransport,\n StreamableHTTPClientTransport,\n SdkHttpError,\n type ClientCapabilities,\n type ClientContext,\n type DiscoverResult,\n type ElicitRequest,\n type ElicitResult,\n type McpSubscription,\n type Prompt,\n type Resource,\n type ResourceTemplateType as ResourceTemplate,\n type ServerCapabilities,\n type SSEClientTransportOptions,\n type StreamableHTTPClientTransportOptions,\n type Tool\n} from \"@modelcontextprotocol/client\";\nimport { Emitter, type Event } from \"../../core/events\";\nimport type { MCPObservabilityEvent } from \"../../observability/mcp\";\nimport { raceWithSignal } from \"../abort\";\nimport {\n fetchMcpPrompts,\n fetchMcpResources,\n fetchMcpResourceTemplates,\n fetchMcpTools\n} from \"./catalog\";\nimport type { AgentMcpOAuthProvider } from \"./do-oauth-client-provider\";\nimport { AuthorizationTurns } from \"./authorization-turns\";\nimport {\n advertisedElicitation,\n createMcpSdkClient,\n normalizeMcpClientOptions\n} from \"./runtime\";\nexport { elicitationCapabilitiesFromHandlers } from \"./runtime\";\nimport {\n isTransportNotImplemented,\n isAuthorizationRefused,\n isUnauthorized,\n toErrorMessage\n} from \"./errors\";\nimport { RPCClientTransport, type RPCClientTransportOptions } from \"../rpc\";\nimport type {\n BaseTransportType,\n HttpTransportType,\n TransportType,\n McpClientOptions\n} from \"../types\";\n\n/**\n * Connection state machine for MCP client connections.\n *\n * State transitions:\n * - Non-OAuth: init() → CONNECTING → DISCOVERING → READY\n * - OAuth: init() → AUTHENTICATING → (callback) → CONNECTING → DISCOVERING → READY\n * - Any state can transition to FAILED on error\n */\nexport const MCPConnectionState = {\n /** Waiting for OAuth authorization to complete */\n AUTHENTICATING: \"authenticating\",\n /** Establishing transport connection to MCP server */\n CONNECTING: \"connecting\",\n /** Transport connection established */\n CONNECTED: \"connected\",\n /** Discovering server capabilities (tools, resources, prompts) */\n DISCOVERING: \"discovering\",\n /** Fully connected and ready to use */\n READY: \"ready\",\n /** Connection failed at some point */\n FAILED: \"failed\"\n} as const;\n\n/**\n * Connection state type for MCP client connections.\n */\nexport type MCPConnectionState =\n (typeof MCPConnectionState)[keyof typeof MCPConnectionState];\n\n/**\n * Transport options for MCP client connections.\n * Combines transport-specific options with auth provider and type selection.\n */\nexport type MCPTransportOptions = (\n | SSEClientTransportOptions\n | StreamableHTTPClientTransportOptions\n | RPCClientTransportOptions\n) & {\n authProvider?: AgentMcpOAuthProvider;\n type?: TransportType;\n /**\n * Headers sent with every HTTP request, for servers that take a static\n * credential instead of OAuth. Stored with the server, so restored\n * connections send them too.\n */\n headers?: HeadersInit;\n};\n\n/**\n * Apply `headers` to an HTTP transport's options. The SDK transports only\n * read `requestInit`, and the SSE stream only `eventSourceInit.fetch`.\n * Headers already in `requestInit` win.\n */\nfunction withStaticHeaders<\n T extends StreamableHTTPClientTransportOptions | SSEClientTransportOptions\n>(options: T & { headers?: HeadersInit }): T {\n const { headers } = options;\n if (!headers) return options;\n const merge = (overrides: HeadersInit | undefined) => {\n const merged = new Headers(headers);\n new Headers(overrides).forEach((value, key) => merged.set(key, value));\n return merged;\n };\n const sse = options as SSEClientTransportOptions;\n const streamFetch = sse.eventSourceInit?.fetch ?? fetch;\n return {\n ...options,\n requestInit: {\n ...options.requestInit,\n headers: merge(options.requestInit?.headers)\n },\n eventSourceInit: {\n ...sse.eventSourceInit,\n fetch: (url, init) =>\n streamFetch(url, {\n ...init,\n // The SDK's headers win, whatever shape they arrive in.\n headers: Object.fromEntries(\n merge(init.headers)\n ) as typeof init.headers\n })\n }\n };\n}\n\nexport type MCPClientConnectionResult = {\n state: MCPConnectionState;\n error?: Error;\n transport?: BaseTransportType;\n};\n\n/** Result of discovering server capabilities. */\nexport type MCPDiscoveryResult =\n | { success: true }\n | { success: false; reason: \"error\" | \"stale-session\"; error: string };\n\n/**\n * Handler for server-initiated `elicitation/create` requests.\n * Held in memory only — never persisted — so it must be re-supplied when a\n * connection is recreated (e.g. after Durable Object hibernation).\n */\nexport type MCPElicitationHandler = (\n request: ElicitRequest,\n /** Aborts when the originating MCP call is cancelled or exhausts its total-time budget. */\n signal?: AbortSignal\n) => Promise<ElicitResult>;\n\nexport type MCPElicitationHandlers = {\n form?: MCPElicitationHandler;\n url?: MCPElicitationHandler;\n};\n\nexport class MCPClientConnection {\n client: Client;\n connectionState: MCPConnectionState = MCPConnectionState.CONNECTING;\n connectionError: string | null = null;\n lastConnectedTransport: BaseTransportType | undefined;\n instructions?: string;\n tools: Tool[] = [];\n private _transport?:\n | StreamableHTTPClientTransport\n | SSEClientTransport\n | RPCClientTransport;\n\n /**\n * Transport that received the 401 during the initial connect attempt.\n * Kept so finishAuth() runs on the transport that captured the resource\n * metadata URL from the WWW-Authenticate header — a fresh transport would\n * rediscover from defaults and exchange the code at the wrong token\n * endpoint when the authorization server is not at the default location.\n */\n private _pendingAuthTransport?:\n | StreamableHTTPClientTransport\n | SSEClientTransport\n | RPCClientTransport;\n private _restoredListSubscription?: McpSubscription;\n /**\n * Whether the last connect or discovery failed because authorization was\n * refused in a way retrying cannot change: a 403 from the server, or an\n * OAuth error such as `invalid_target` from the authorization server. The\n * manager stops reconnecting such a server instead of asking again.\n */\n accessRefused = false;\n /** Keeps concurrent `401`s from starting interleaved OAuth flows. */\n private readonly _authorizationTurns = new AuthorizationTurns();\n prompts: Prompt[] = [];\n resources: Resource[] = [];\n resourceTemplates: ResourceTemplate[] = [];\n serverCapabilities: ServerCapabilities | undefined;\n\n /** True when resuming a streamable-http session without cached capabilities */\n private _probingCapabilities = false;\n\n /** Whether init() is connecting: its client must not be replaced. */\n private _connecting = false;\n /** The elicitation capability `client` was built to advertise, as JSON. */\n private _advertisedElicitation = \"null\";\n\n /** Tracks in-flight discovery to allow cancellation */\n private _discoveryAbortController: AbortController | undefined;\n\n private readonly _onObservabilityEvent = new Emitter<MCPObservabilityEvent>();\n public readonly onObservabilityEvent: Event<MCPObservabilityEvent> =\n this._onObservabilityEvent.event;\n\n private readonly _onListChanged = new Emitter<void>();\n public readonly onListChanged: Event<void> = this._onListChanged.event;\n\n /**\n * Whether the connection advertised the elicitation capability. The SDK\n * client refuses to register an `elicitation/create` request handler when\n * the capability was not declared, so handler registration is gated on\n * this.\n */\n private _elicitationEnabled = false;\n\n constructor(\n public url: URL,\n private readonly _info: ConstructorParameters<typeof Client>[0],\n public options: {\n transport: MCPTransportOptions;\n client: NonNullable<McpClientOptions>;\n elicitationHandlers?: MCPElicitationHandlers;\n /**\n * Client capabilities persisted from a previous session, advertised\n * until handlers are reconfigured after a hibernation restore. Cleared\n * by {@link configureElicitationHandlers} — reconfigured handlers are\n * the source of truth. Explicit `client.capabilities` win per key.\n */\n capabilitySeed?: ClientCapabilities;\n /** SDK discovery result paired with a resumed Stateless HTTP session. */\n discoverResult?: DiscoverResult;\n } = { client: {}, transport: {} }\n ) {\n this.options = {\n ...options,\n client: normalizeMcpClientOptions(options.client)\n };\n\n this.client = this.createClient();\n }\n\n private createClient(): Client {\n const created = createMcpSdkClient(\n this._info,\n this.options.client,\n this.options.capabilitySeed,\n this.options.elicitationHandlers,\n {\n tools: (error, tools) => {\n if (!error && tools) this.tools = tools;\n this._onListChanged.fire();\n },\n prompts: (error, prompts) => {\n if (!error && prompts) this.prompts = prompts;\n this._onListChanged.fire();\n },\n resources: (error, resources) => {\n if (!error && resources) this.resources = resources;\n this._onListChanged.fire();\n }\n }\n );\n this._elicitationEnabled = created.elicitationEnabled;\n this._advertisedElicitation = this.elicitationToAdvertise();\n return created.client;\n }\n\n /**\n * Configure the handler used for server-initiated elicitation requests.\n *\n * If the connection has not been initialized yet, rebuild the SDK client so\n * handler-driven elicitation capabilities are reflected in the initial\n * handshake. A rebuild (rather than `Client.registerCapabilities`) is\n * required because SDK capability registration is merge-only — it cannot\n * un-advertise a mode when handlers are cleared before connecting. Active\n * connections keep their negotiated capabilities until they reconnect.\n */\n configureElicitationHandlers(handlers?: MCPElicitationHandlers): void {\n this.options.elicitationHandlers = handlers;\n // Handlers are now the source of truth — drop the restore seed so\n // clearing the handlers un-advertises the capability on rebuild.\n this.options.capabilitySeed = undefined;\n\n // A connect in flight runs on the current client: replacing it would\n // leave the connection on a client that never connected. init() connects\n // again when the handshake it made advertised something else.\n if (!this._transport && !this._connecting) {\n this.client = this.createClient();\n }\n }\n\n /** What a client built now would advertise for elicitation, as JSON. */\n private elicitationToAdvertise(): string {\n return JSON.stringify(\n advertisedElicitation(\n this.options.client,\n this.options.capabilitySeed,\n this.options.elicitationHandlers\n ) ?? null\n );\n }\n\n /**\n * Connect, and connect again when the elicitation handlers changed during\n * the handshake: apps configure them in `onStart`, while a restored\n * server is already connecting.\n */\n private async connectWithCurrentHandlers(\n transportType: TransportType\n ): Promise<MCPClientConnectionResult> {\n this._connecting = true;\n try {\n let res = await this.tryConnect(transportType);\n // Bounded, so handlers that keep changing cannot hold the connect.\n for (let again = 0; again < 3; again++) {\n if (this._advertisedElicitation === this.elicitationToAdvertise()) {\n break;\n }\n // A 401 keeps its transport for the callback, which builds a new\n // client once the user has authorized.\n if (res.state === MCPConnectionState.AUTHENTICATING) break;\n this._transport = undefined;\n await this.client.close().catch(() => {});\n this.client = this.createClient();\n if (res.state !== MCPConnectionState.CONNECTED) break;\n res = await this.tryConnect(transportType);\n }\n return res;\n } finally {\n this._connecting = false;\n }\n }\n\n /**\n * Initialize a client connection, if authentication is required, the connection will be in the AUTHENTICATING state\n * Sets connection state based on the result and emits observability events\n *\n * @returns Error message if connection failed, undefined otherwise\n */\n async init(): Promise<string | undefined> {\n const transportType = this.options.transport.type;\n if (!transportType) {\n throw new Error(\"Transport type must be specified\");\n }\n\n // init() can be re-entered after a mid-session 401 → OAuth → reconnect\n // cycle (e.g. scope step-up, token revocation). The SDK client refuses\n // to connect while a previous transport is still attached, so detach it\n // first. Rebuild the client so the new handshake advertises the current\n // handler-derived capabilities — reconnects are documented as the point\n // where handler changes on a live connection take effect.\n if (this._transport) {\n this._transport = undefined;\n try {\n await this.client.close();\n } catch {\n // Closing a transport that just failed auth is best-effort.\n }\n this.client = this.createClient();\n }\n\n const res = await this.connectWithCurrentHandlers(transportType);\n\n // Set the connection state\n this.connectionState = res.state;\n this.accessRefused =\n res.state === MCPConnectionState.FAILED &&\n isAuthorizationRefused(res.error);\n\n // Handle the result and emit appropriate events\n if (res.state === MCPConnectionState.CONNECTED && res.transport) {\n // Set up the elicitation request handler after a successful\n // connection. Only when the capability was advertised — the SDK\n // client throws on registering a handler for an undeclared capability.\n if (this._elicitationEnabled) {\n this.client.setRequestHandler(\n \"elicitation/create\",\n async (request: ElicitRequest, context: ClientContext) =>\n await this.handleElicitationRequest(request, context.mcpReq.signal)\n );\n }\n\n this.lastConnectedTransport = res.transport;\n\n this._onObservabilityEvent.fire({\n type: \"mcp:client:connect\",\n payload: {\n url: this.url.toString(),\n transport: res.transport,\n state: this.connectionState\n },\n timestamp: Date.now()\n });\n return undefined;\n } else if (res.state === MCPConnectionState.FAILED && res.error) {\n const errorMessage = toErrorMessage(res.error);\n this._onObservabilityEvent.fire({\n type: \"mcp:client:connect\",\n payload: {\n url: this.url.toString(),\n transport: transportType,\n state: this.connectionState,\n error: errorMessage\n },\n timestamp: Date.now()\n });\n return errorMessage;\n }\n return undefined;\n }\n\n /**\n * Finish OAuth by probing transports based on configured type.\n * - Explicit: finish on that transport\n * - Auto: try streamable-http, then sse on 404/405/Not Implemented\n */\n private async finishAuthProbe(\n callbackParams: URLSearchParams\n ): Promise<void> {\n if (!this.options.transport.authProvider) {\n throw new Error(\"No auth provider configured\");\n }\n\n const configuredType = this.options.transport.type;\n if (!configuredType) {\n throw new Error(\"Transport type must be specified\");\n }\n\n const finishAuth = async (base: HttpTransportType) => {\n const transport = this.getTransport(base);\n let completed = false;\n try {\n if (\n \"finishAuth\" in transport &&\n typeof transport.finishAuth === \"function\"\n ) {\n await transport.finishAuth(callbackParams);\n completed = true;\n }\n } finally {\n if (typeof transport.close === \"function\") {\n await transport.close().catch(() => {});\n }\n }\n if (completed) this.client = this.createClient();\n };\n\n if (configuredType === \"rpc\") {\n throw new Error(\"RPC transport does not support authentication\");\n }\n\n // Prefer the transport that triggered authentication (initial-connect\n // 401, or the active transport for a mid-session 401 such as a scope\n // step-up): it holds the resource metadata URL from the WWW-Authenticate\n // header that finishAuth() needs to locate the authorization server.\n const authTransport = this._pendingAuthTransport ?? this._transport;\n this._pendingAuthTransport = undefined;\n if (\n authTransport &&\n \"finishAuth\" in authTransport &&\n typeof authTransport.finishAuth === \"function\"\n ) {\n let completed = false;\n try {\n await authTransport.finishAuth(callbackParams);\n completed = true;\n } finally {\n if (typeof authTransport.close === \"function\") {\n await authTransport.close().catch(() => {});\n }\n if (this._transport === authTransport) this._transport = undefined;\n }\n if (completed) this.client = this.createClient();\n return;\n }\n\n if (configuredType === \"sse\" || configuredType === \"streamable-http\") {\n await finishAuth(configuredType);\n return;\n }\n\n // For \"auto\" mode, try streamable-http first, then fall back to SSE\n try {\n await finishAuth(\"streamable-http\");\n } catch (e) {\n if (isTransportNotImplemented(e)) {\n await finishAuth(\"sse\");\n return;\n }\n throw e;\n }\n }\n\n /**\n * Complete OAuth authorization\n */\n async completeAuthorization(\n callback: string | URLSearchParams,\n options: { alreadyAccepted?: boolean } = {}\n ): Promise<void> {\n const expectedState = options.alreadyAccepted\n ? MCPConnectionState.CONNECTING\n : MCPConnectionState.AUTHENTICATING;\n if (this.connectionState !== expectedState) {\n throw new Error(\n `Connection must be in ${expectedState} state to complete authorization`\n );\n }\n\n if (!options.alreadyAccepted) {\n this.connectionState = MCPConnectionState.CONNECTING;\n }\n\n try {\n // Finish OAuth by probing transports per configuration\n const callbackParams =\n typeof callback === \"string\"\n ? new URLSearchParams({ code: callback })\n : callback;\n // In a turn of its own: a 401's refresh that started before the\n // exchange finishes first, and one that starts after it finds the\n // newer token.\n await this._authorizationTurns.run(() =>\n this.finishAuthProbe(callbackParams)\n );\n } catch (error) {\n this.connectionState = MCPConnectionState.FAILED;\n throw error;\n }\n }\n\n /**\n * Discover server capabilities and register tools, resources, prompts, and templates.\n * This method does the work but does not manage connection state - that's handled by discover().\n */\n async discoverAndRegister(): Promise<void> {\n const discoveredCapabilities = this.client.getServerCapabilities();\n const shouldProbeCapabilities =\n !discoveredCapabilities && this.isResumedStreamableHttpSession();\n\n this.serverCapabilities = discoveredCapabilities;\n this._probingCapabilities = shouldProbeCapabilities;\n\n if (!discoveredCapabilities && !shouldProbeCapabilities) {\n throw new Error(\"The MCP Server failed to return server capabilities\");\n }\n\n // Build list of operations to perform based on server capabilities.\n // For resumed streamable-http sessions, the MCP SDK skips initialize()\n // when a sessionId already exists, so a fresh Client instance may not have\n // cached server capabilities yet. In that case, probe the list endpoints\n // directly and treat -32601 as capability absence.\n type DiscoveryResult =\n | string\n | undefined\n | Tool[]\n | Resource[]\n | Prompt[]\n | ResourceTemplate[];\n const operations: Promise<DiscoveryResult>[] = [];\n const operationNames: string[] = [];\n\n // Instructions (always try to fetch if available)\n operations.push(Promise.resolve(this.client.getInstructions()));\n operationNames.push(\"instructions\");\n\n if (discoveredCapabilities?.tools || shouldProbeCapabilities) {\n operations.push(this.registerTools());\n operationNames.push(\"tools\");\n }\n\n if (discoveredCapabilities?.resources || shouldProbeCapabilities) {\n operations.push(this.registerResources());\n operationNames.push(\"resources\");\n }\n\n if (discoveredCapabilities?.prompts || shouldProbeCapabilities) {\n operations.push(this.registerPrompts());\n operationNames.push(\"prompts\");\n }\n\n if (discoveredCapabilities?.resources || shouldProbeCapabilities) {\n operations.push(this.registerResourceTemplates());\n operationNames.push(\"resource templates\");\n }\n\n try {\n const results = await Promise.all(operations);\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n const name = operationNames[i];\n\n switch (name) {\n case \"instructions\":\n this.instructions = result as string | undefined;\n break;\n case \"tools\":\n this.tools = result as Tool[];\n break;\n case \"resources\":\n this.resources = result as Resource[];\n break;\n case \"prompts\":\n this.prompts = result as Prompt[];\n break;\n case \"resource templates\":\n this.resourceTemplates = result as ResourceTemplate[];\n break;\n }\n }\n } catch (error) {\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n payload: {\n url: this.url.toString(),\n error: toErrorMessage(error)\n },\n timestamp: Date.now()\n });\n\n throw error;\n }\n }\n\n /**\n * Discover server capabilities with timeout and cancellation support.\n * If called while a previous discovery is in-flight, the previous discovery will be aborted.\n *\n * @param options Optional configuration\n * @param options.timeoutMs Timeout in milliseconds (default: 15000)\n * @returns Result indicating success/failure with optional error message\n */\n async discover(\n options: { timeoutMs?: number } = {}\n ): Promise<MCPDiscoveryResult> {\n const { timeoutMs = 15000 } = options;\n\n // Check if state allows discovery\n if (\n this.connectionState !== MCPConnectionState.CONNECTED &&\n this.connectionState !== MCPConnectionState.READY\n ) {\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n payload: {\n url: this.url.toString(),\n state: this.connectionState\n },\n timestamp: Date.now()\n });\n return {\n success: false,\n reason: \"error\",\n error: `Discovery skipped - connection in ${this.connectionState} state`\n };\n }\n\n // Cancel any previous in-flight discovery\n if (this._discoveryAbortController) {\n this._discoveryAbortController.abort();\n this._discoveryAbortController = undefined;\n }\n\n // Create a new AbortController for this discovery\n const abortController = new AbortController();\n this._discoveryAbortController = abortController;\n\n this.connectionState = MCPConnectionState.DISCOVERING;\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n try {\n // Create timeout promise\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(\n () => reject(new Error(`Discovery timed out after ${timeoutMs}ms`)),\n timeoutMs\n );\n });\n\n // Check if aborted before starting\n if (abortController.signal.aborted) {\n throw new Error(\"Discovery was cancelled\");\n }\n\n // Create an abort promise that rejects when signal fires\n const abortPromise = new Promise<never>((_, reject) => {\n abortController.signal.addEventListener(\"abort\", () => {\n reject(new Error(\"Discovery was cancelled\"));\n });\n });\n\n await Promise.race([\n this.discoverAndRegister(),\n timeoutPromise,\n abortPromise\n ]);\n\n // Clear timeout on success\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n\n // Discovery succeeded - transition to ready\n this.connectionState = MCPConnectionState.READY;\n\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n payload: {\n url: this.url.toString()\n },\n timestamp: Date.now()\n });\n\n return { success: true };\n } catch (e) {\n // Always clear the timeout\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n\n // Ordinary discovery failures return to CONNECTED so callers can retry.\n // A 401 is different: the live transport has already produced an OAuth\n // authorization URL, so preserve AUTHENTICATING for the manager to\n // persist and expose that continuation.\n this.connectionState = isUnauthorized(e)\n ? MCPConnectionState.AUTHENTICATING\n : MCPConnectionState.CONNECTED;\n this.accessRefused = isAuthorizationRefused(e);\n\n const error = e instanceof Error ? e.message : String(e);\n // A restored streamable HTTP session rejected with 404 must be\n // initialized again without its persisted session id.\n const staleSession =\n this._probingCapabilities &&\n e instanceof SdkHttpError &&\n e.status === 404;\n return {\n success: false,\n reason: staleSession ? \"stale-session\" : \"error\",\n error\n };\n } finally {\n // Clean up the abort controller\n this._discoveryAbortController = undefined;\n }\n }\n\n /**\n * Cancel any in-flight discovery operation.\n * Called when closing the connection.\n */\n cancelDiscovery(): void {\n if (this._discoveryAbortController) {\n this._discoveryAbortController.abort();\n this._discoveryAbortController = undefined;\n }\n }\n\n /**\n * Notification handler registration for tools\n * Should only be called if serverCapabilities.tools exists\n */\n async registerTools(): Promise<Tool[]> {\n if (this._probingCapabilities) {\n this.client.setNotificationHandler(\n \"notifications/tools/list_changed\",\n async () => {\n this.tools = await this.fetchTools();\n this._onListChanged.fire();\n }\n );\n }\n return this.fetchTools();\n }\n\n /**\n * Notification handler registration for resources\n * Should only be called if serverCapabilities.resources exists\n */\n async registerResources(): Promise<Resource[]> {\n if (this._probingCapabilities) {\n this.client.setNotificationHandler(\n \"notifications/resources/list_changed\",\n async () => {\n this.resources = await this.fetchResources();\n this._onListChanged.fire();\n }\n );\n }\n return this.fetchResources();\n }\n\n /**\n * Notification handler registration for prompts\n * Should only be called if serverCapabilities.prompts exists\n */\n async registerPrompts(): Promise<Prompt[]> {\n if (this._probingCapabilities) {\n this.client.setNotificationHandler(\n \"notifications/prompts/list_changed\",\n async () => {\n this.prompts = await this.fetchPrompts();\n this._onListChanged.fire();\n }\n );\n }\n return this.fetchPrompts();\n }\n\n async registerResourceTemplates(): Promise<ResourceTemplate[]> {\n return this.fetchResourceTemplates();\n }\n\n private catalogFetchOptions() {\n return {\n probing: this._probingCapabilities,\n onCapabilityError: this._capabilityErrorHandler.bind(this)\n };\n }\n\n async fetchTools() {\n return fetchMcpTools(this.client, this.catalogFetchOptions());\n }\n\n async fetchResources() {\n return fetchMcpResources(this.client, this.catalogFetchOptions());\n }\n\n async fetchPrompts() {\n return fetchMcpPrompts(this.client, this.catalogFetchOptions());\n }\n\n async fetchResourceTemplates() {\n return fetchMcpResourceTemplates(this.client, this.catalogFetchOptions());\n }\n\n /**\n * Handle elicitation request from server.\n *\n * Delegates to the `elicitationHandlers` connection option when provided.\n *\n * @deprecated Overriding or instance-patching this method directly is\n * deprecated — pass the `elicitationHandlers` connection option instead.\n */\n async handleElicitationRequest(\n request: ElicitRequest,\n signal?: AbortSignal\n ): Promise<ElicitResult> {\n const mode = request.params.mode === \"url\" ? \"url\" : \"form\";\n const handler = this.options.elicitationHandlers?.[mode];\n if (handler) {\n const pending = signal ? handler(request, signal) : handler(request);\n return raceWithSignal(pending, signal);\n }\n if (this.options.elicitationHandlers) {\n throw new Error(\n `No MCP ${mode}-mode elicitation handler configured for this connection.`\n );\n }\n throw new Error(\n \"Elicitation handler must be implemented for your platform. Provide the MCPClientConnection elicitationHandlers option, or register handlers through the MCP client manager before connecting.\"\n );\n }\n\n private isResumedStreamableHttpSession(): boolean {\n return (\n this._transport instanceof StreamableHTTPClientTransport &&\n typeof this._transport.sessionId === \"string\"\n );\n }\n\n /**\n * @internal The transport of the open session, if any. Each connect opens\n * a new one, and init() drops it before reconnecting.\n */\n get session(): object | undefined {\n return this._transport;\n }\n\n get sessionId(): string | undefined {\n if (this._transport instanceof StreamableHTTPClientTransport) {\n return this._transport.sessionId;\n }\n\n return undefined;\n }\n\n /** @internal Clear a restored session before reconnecting. */\n clearResumedSession(): void {\n if (\"sessionId\" in this.options.transport) {\n delete this.options.transport.sessionId;\n }\n }\n\n get protocolVersion(): string | undefined {\n if (this._transport instanceof StreamableHTTPClientTransport) {\n return this._transport.protocolVersion;\n }\n\n return undefined;\n }\n\n get discoverResult(): DiscoverResult | undefined {\n return this.client.getDiscoverResult();\n }\n\n private async openRestoredListSubscription(): Promise<void> {\n const capabilities = this.client.getServerCapabilities();\n const filter = {\n ...(capabilities?.tools?.listChanged && { toolsListChanged: true }),\n ...(capabilities?.prompts?.listChanged && { promptsListChanged: true }),\n ...(capabilities?.resources?.listChanged && {\n resourcesListChanged: true\n })\n };\n if (Object.keys(filter).length === 0) return;\n\n try {\n this._restoredListSubscription = await this.client.listen(filter);\n } catch (error) {\n // A restored session is still usable when its optional listen stream\n // cannot be reopened. Surface the error without failing the connection.\n this.client.onerror?.(\n error instanceof Error ? error : new Error(String(error))\n );\n }\n }\n\n private getTransportName(\n transport?:\n | StreamableHTTPClientTransport\n | SSEClientTransport\n | RPCClientTransport\n ): string | undefined {\n if (transport instanceof StreamableHTTPClientTransport) {\n return \"streamable-http\";\n }\n\n if (transport instanceof SSEClientTransport) {\n return \"sse\";\n }\n\n if (transport instanceof RPCClientTransport) {\n return \"rpc\";\n }\n\n return this.lastConnectedTransport;\n }\n\n async close(): Promise<void> {\n const transport = this._transport;\n this._transport = undefined;\n await this._restoredListSubscription?.close().catch(() => {});\n this._restoredListSubscription = undefined;\n const url = this.url.toString();\n const transportName = this.getTransportName(transport);\n\n if (\n transport instanceof StreamableHTTPClientTransport &&\n transport.sessionId\n ) {\n try {\n await transport.terminateSession();\n } catch (error) {\n this._onObservabilityEvent.fire({\n type: \"mcp:client:close\",\n payload: {\n url,\n transport: transportName,\n state: \"error\",\n error: toErrorMessage(error),\n phase: \"terminate-session\"\n },\n timestamp: Date.now()\n });\n }\n }\n\n try {\n await this.client.close();\n } catch (error) {\n this._onObservabilityEvent.fire({\n type: \"mcp:client:close\",\n payload: {\n url,\n transport: transportName,\n state: \"error\",\n error: toErrorMessage(error),\n phase: \"client-close\"\n },\n timestamp: Date.now()\n });\n throw error;\n }\n\n this._onObservabilityEvent.fire({\n type: \"mcp:client:close\",\n payload: {\n url,\n transport: transportName,\n state: \"closed\"\n },\n timestamp: Date.now()\n });\n }\n\n /**\n * Get the transport for the client\n * @param transportType - The transport type to get\n * @returns The transport for the client\n */\n getTransport(transportType: BaseTransportType) {\n switch (transportType) {\n case \"streamable-http\":\n return this.withAuthorizationTurns(\n new StreamableHTTPClientTransport(\n this.url,\n this.authorizationTurnOptions(\n withStaticHeaders(\n this.options.transport as StreamableHTTPClientTransportOptions\n )\n )\n )\n );\n case \"sse\":\n return this.withAuthorizationTurns(\n new SSEClientTransport(\n this.url,\n this.authorizationTurnOptions(\n withStaticHeaders(\n this.options.transport as SSEClientTransportOptions\n )\n )\n )\n );\n case \"rpc\":\n return new RPCClientTransport(\n this.options.transport as RPCClientTransportOptions\n );\n default:\n throw new Error(`Unsupported transport type: ${transportType}`);\n }\n }\n\n /**\n * Take an HTTP transport's OAuth flows one at a time: a `401` waits for the\n * authorization an earlier one started, so concurrent requests share one\n * client registration and one pending link.\n */\n /** Transport options whose `fetch` records the token each 401 carried. */\n private authorizationTurnOptions<\n T extends StreamableHTTPClientTransportOptions | SSEClientTransportOptions\n >(options: T): T {\n if (!this.options.transport.authProvider) return options;\n return {\n ...options,\n fetch: this._authorizationTurns.wrapFetch(options.fetch)\n };\n }\n\n private withAuthorizationTurns<T extends object>(transport: T): T {\n const { authProvider } = this.options.transport;\n if (authProvider) {\n this._authorizationTurns.wrapTransport(transport, authProvider);\n }\n return transport;\n }\n\n private async tryConnect(\n transportType: TransportType\n ): Promise<MCPClientConnectionResult> {\n const transports: BaseTransportType[] =\n transportType === \"auto\" ? [\"streamable-http\", \"sse\"] : [transportType];\n\n for (const currentTransportType of transports) {\n const isLastTransport =\n currentTransportType === transports[transports.length - 1];\n const hasFallback =\n transportType === \"auto\" &&\n currentTransportType === \"streamable-http\" &&\n !isLastTransport;\n\n const transport = this.getTransport(currentTransportType);\n\n try {\n const prior =\n transport instanceof StreamableHTTPClientTransport &&\n transport.sessionId &&\n this.options.discoverResult\n ? { kind: \"modern\" as const, discover: this.options.discoverResult }\n : undefined;\n await this.client.connect(transport, prior ? { prior } : undefined);\n this._transport = transport;\n this._pendingAuthTransport = undefined;\n if (prior) await this.openRestoredListSubscription();\n\n return {\n state: MCPConnectionState.CONNECTED,\n transport: currentTransportType\n };\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e));\n\n if (isUnauthorized(error)) {\n this._pendingAuthTransport = transport;\n return {\n state: MCPConnectionState.AUTHENTICATING\n };\n }\n\n if (isTransportNotImplemented(error) && hasFallback) {\n // Try the next transport\n continue;\n }\n\n return {\n state: MCPConnectionState.FAILED,\n error\n };\n }\n }\n\n // Should never reach here\n return {\n state: MCPConnectionState.FAILED,\n error: new Error(\"No transports available\")\n };\n }\n\n private _capabilityErrorHandler<T>(empty: T, method: string) {\n return (e: { code: number }) => {\n // server is badly behaved and returning invalid capabilities. This commonly occurs for resource templates\n if (e.code === -32601) {\n const url = this.url.toString();\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n payload: {\n url,\n capability: method.split(\"/\")[0],\n error: toErrorMessage(e)\n },\n timestamp: Date.now()\n });\n return empty;\n }\n throw e;\n };\n }\n}\n","import type { CallToolResult, Tool } from \"@modelcontextprotocol/client\";\nimport { z } from \"zod\";\nimport { type MCPClientConnection, MCPConnectionState } from \"./connection\";\n\n/** One MCP tool converted for the AI SDK. */\nexport type MCPAITool = {\n description?: string;\n title?: string;\n execute: (\n args: Record<string, unknown>,\n options?: unknown\n ) => Promise<unknown>;\n inputSchema: z.ZodType;\n outputSchema?: z.ZodType;\n};\n\n/**\n * Structural tool set returned by {@link MCPClientManager.getAITools}.\n * Compatible with the AI SDK without importing its types into the core\n * `agents` declaration graph.\n */\nexport type MCPAIToolSet = Record<string, MCPAITool>;\n\ntype MCPAIConvertedSchemas = {\n inputSchema: z.ZodType;\n outputSchema?: z.ZodType;\n};\n\ntype MCPAISchemaSource = {\n tool: Tool;\n inputSchema: Tool[\"inputSchema\"] | undefined;\n outputSchema: Tool[\"outputSchema\"] | undefined;\n};\n\ntype MCPAISchemaCacheSlot = MCPAISchemaSource &\n (\n | { status: \"converted\"; converted: MCPAIConvertedSchemas }\n | { status: \"failed\"; error: string }\n );\n\ntype MCPAISchemaCacheEntry = {\n catalog: Tool[];\n converted: Array<MCPAISchemaCacheSlot | undefined>;\n};\n\n/** A namespaced tool call, as `MCPClientManager.callTool()` accepts it. */\ntype NamespacedToolCall = (params: {\n arguments: Record<string, unknown>;\n name: string;\n serverId: string;\n}) => Promise<CallToolResult>;\n\n/**\n * Converts MCP tool catalogs into AI SDK tool records. Converted schemas are\n * cached per connection while that connection keeps the same catalog array\n * and schema-source identities; tool records and `execute` closures are\n * rebuilt on every call.\n */\nexport class MCPAIToolConverter {\n /** Only the current catalog is cached, so old schema graphs are released. */\n readonly #schemas = new WeakMap<MCPClientConnection, MCPAISchemaCacheEntry>();\n\n /**\n * Convert the tools of the given connections.\n *\n * @param connections - Connections keyed by server id.\n * @param callTool - Runs a tool call for a tool's `execute`.\n * @returns AI SDK tools keyed `tool_<serverId>_<toolName>`.\n */\n convert(\n connections: Record<string, MCPClientConnection>,\n callTool: NamespacedToolCall\n ): MCPAIToolSet {\n const entries: [string, MCPAITool][] = [];\n\n for (const [serverId, conn] of Object.entries(connections)) {\n if (\n conn.connectionState !== MCPConnectionState.READY &&\n conn.connectionState !== MCPConnectionState.AUTHENTICATING\n ) {\n console.warn(\n `[getAITools] WARNING: Reading tools from connection ${serverId} in state \"${conn.connectionState}\". Tools may not be loaded yet.`\n );\n }\n\n const catalog = conn.tools;\n let cache = this.#schemas.get(conn);\n if (!cache || cache.catalog !== catalog) {\n cache = { catalog, converted: [] };\n this.#schemas.set(conn, cache);\n }\n\n for (const [index, tool] of catalog.entries()) {\n const toolName = tool.name;\n try {\n const sourceInputSchema = tool.inputSchema;\n const sourceOutputSchema = tool.outputSchema;\n let slot = cache.converted[index];\n if (\n !slot ||\n slot.tool !== tool ||\n slot.inputSchema !== sourceInputSchema ||\n slot.outputSchema !== sourceOutputSchema\n ) {\n try {\n slot = {\n status: \"converted\",\n tool,\n inputSchema: sourceInputSchema,\n outputSchema: sourceOutputSchema,\n converted: {\n inputSchema: sourceInputSchema\n ? z.fromJSONSchema(\n sourceInputSchema as Parameters<\n typeof z.fromJSONSchema\n >[0]\n )\n : z.fromJSONSchema({ type: \"object\" }),\n outputSchema: sourceOutputSchema\n ? z.fromJSONSchema(\n sourceOutputSchema as Parameters<\n typeof z.fromJSONSchema\n >[0]\n )\n : undefined\n }\n };\n } catch (error) {\n const errorText = String(error);\n cache.converted[index] = {\n status: \"failed\",\n tool,\n inputSchema: sourceInputSchema,\n outputSchema: sourceOutputSchema,\n error: errorText\n };\n console.warn(\n `[getAITools] Skipping tool \"${toolName}\" from \"${serverId}\": ${errorText}`\n );\n continue;\n }\n cache.converted[index] = slot;\n }\n\n if (slot.status === \"failed\") continue;\n\n const toolKey = `tool_${serverId.replace(/-/g, \"\")}_${toolName}`;\n const title = tool.title ?? tool.annotations?.title;\n const description = tool.description;\n entries.push([\n toolKey,\n {\n description,\n title,\n execute: async (args) => {\n const result = await callTool({\n arguments: args,\n name: toolName,\n serverId\n });\n if (result.isError) {\n const content = result.content as\n | Array<{ type: string; text?: string }>\n | undefined;\n const textContent = content?.[0];\n const message =\n textContent?.type === \"text\" && textContent.text\n ? textContent.text\n : \"Tool call failed\";\n throw new Error(message);\n }\n return result;\n },\n inputSchema: slot.converted.inputSchema,\n outputSchema: slot.converted.outputSchema\n }\n ]);\n } catch (error) {\n console.warn(\n `[getAITools] Skipping tool \"${toolName}\" from \"${serverId}\": ${error}`\n );\n }\n }\n\n // Release removed slots when a public catalog array is spliced in place.\n cache.converted.length = catalog.length;\n }\n\n return Object.fromEntries(entries);\n }\n}\n","/**\n * The authorization retry limit from the MCP authorization spec\n * (2026-07-28, \"Step-Up Authorization Flow\"): after a scope challenge the\n * client re-authorizes and retries \"no more than a few times\", then treats\n * the challenge as a permanent authorization failure, tracking attempts\n * so it does not loop on the same request.\n *\n * A round is one authorization URL the user is sent to. Rounds are counted\n * separately for each requested scope set, so challenges that alternate\n * between scope sets each use up their own budget. A new round for a scope\n * set only counts once its previous round completed (its callback exchanged\n * a code) and the server asked for the same scopes again. Several links\n * issued for one pending ask (for example two tool calls hitting the same\n * step-up at once) are one round.\n */\n\n/** Completed authorization rounds allowed for one scope set. */\nconst MAX_AUTHORIZATION_ROUNDS = 3;\n\n/** A scope set's rounds are forgotten this long after its latest round. */\nconst AUTHORIZATION_ROUNDS_WINDOW_MS = 60 * 60 * 1000;\n\n/** Rounds recorded for one requested scope set. */\ntype ScopeRounds = {\n /** Rounds started for this scope set within the window. */\n readonly rounds: number;\n /** Whether this scope set's latest round's callback exchanged a code. */\n readonly completed: boolean;\n /** When this scope set's latest round started, in epoch milliseconds. */\n readonly at: number;\n};\n\n/** Authorization rounds recorded for one server. */\ntype AuthorizationRounds = {\n /** The scope set of the round started most recently. */\n readonly latest: string;\n /** Rounds per normalized scope set; `\"\"` when no scope was requested. */\n readonly byScope: Readonly<Record<string, ScopeRounds>>;\n /**\n * The scope set of each link not yet exchanged, by its OAuth state, so a\n * callback completes the round of the link it belongs to. Absent on rounds\n * stored before this was recorded.\n */\n readonly byState?: Readonly<Record<string, string>>;\n};\n\n/**\n * Links remembered per server. A link older than these completes no round:\n * its scope set is unknown, and guessing could use up another's budget.\n */\nconst MAX_REMEMBERED_LINKS = 64;\n\n/** Whether the next authorization link may be shown. */\ntype RoundDecision =\n | { readonly _tag: \"start\"; readonly rounds: AuthorizationRounds }\n | {\n readonly _tag: \"exhausted\";\n readonly rounds: number;\n readonly scope: string;\n };\n\n/**\n * The requested scope set of an authorization URL: the `scope` parameter's\n * tokens, deduplicated and sorted, or an empty string when absent.\n */\nexport function requestedScope(authUrl: string): string {\n let scope: string | null;\n try {\n scope = new URL(authUrl).searchParams.get(\"scope\");\n } catch {\n return \"\";\n }\n if (!scope) return \"\";\n return [...new Set(scope.split(/\\s+/).filter(Boolean))].sort().join(\" \");\n}\n\n/**\n * Decide whether a new authorization link may be shown.\n *\n * @param previous - The server's recorded rounds, when any.\n * @param scope - The requested scope set of the new link.\n * @param now - The current time in epoch milliseconds.\n * @param state - The OAuth state of the new link, when it has one.\n * @returns The rounds to record, or that the limit is reached.\n */\nexport function startRound(\n previous: AuthorizationRounds | undefined,\n scope: string,\n now: number,\n state?: string | null\n): RoundDecision {\n const byScope = live(previous?.byScope ?? {}, now);\n const current = entryFor(byScope, scope);\n let next: ScopeRounds;\n if (!current) {\n next = { rounds: 1, completed: false, at: now };\n } else if (!current.completed) {\n // Another link for the round still waiting on the user.\n next = { ...current, at: now };\n } else if (current.rounds + 1 > MAX_AUTHORIZATION_ROUNDS) {\n return { _tag: \"exhausted\", rounds: current.rounds, scope };\n } else {\n next = { rounds: current.rounds + 1, completed: false, at: now };\n }\n const scopes = { ...byScope, [scope]: next };\n return {\n _tag: \"start\",\n rounds: {\n latest: scope,\n byScope: scopes,\n byState: rememberLink(previous?.byState ?? {}, scopes, state, scope)\n }\n };\n}\n\n/**\n * Record that a callback exchanged a code: the round of the link it belongs\n * to is complete. Links for other scope sets keep waiting. Rounds stored\n * before links were recorded count the callback for the latest round; with\n * links recorded, a link that is not among them completes nothing.\n *\n * @param previous - The server's recorded rounds, when any.\n * @param state - The OAuth state of the callback.\n */\nexport function completeRound(\n previous: AuthorizationRounds | undefined,\n state?: string | null\n): AuthorizationRounds | undefined {\n if (!previous) return undefined;\n const links = previous.byState;\n const scope = !links\n ? previous.latest\n : state && Object.hasOwn(links, state)\n ? links[state]\n : undefined;\n const byState = Object.fromEntries(\n Object.entries(links ?? {}).filter(([link]) => link !== state)\n );\n const current =\n scope === undefined ? undefined : entryFor(previous.byScope, scope);\n if (scope === undefined || !current) return { ...previous, byState };\n return {\n latest: previous.latest,\n byScope: { ...previous.byScope, [scope]: { ...current, completed: true } },\n byState\n };\n}\n\n/** Parse recorded rounds read back from storage. */\nexport function parseAuthorizationRounds(\n value: unknown\n): AuthorizationRounds | undefined {\n if (\n !isRecord(value) ||\n typeof value.latest !== \"string\" ||\n !isRecord(value.byScope)\n ) {\n return undefined;\n }\n // Object.fromEntries defines own properties, so scope names such as\n // `__proto__` or `constructor` are stored like any other.\n const byScope = Object.fromEntries(\n Object.entries(value.byScope).flatMap(([scope, entry]) =>\n isRecord(entry) &&\n typeof entry.rounds === \"number\" &&\n typeof entry.completed === \"boolean\" &&\n typeof entry.at === \"number\"\n ? [\n [\n scope,\n {\n rounds: entry.rounds,\n completed: entry.completed,\n at: entry.at\n }\n ] as const\n ]\n : []\n )\n );\n const byState = isRecord(value.byState)\n ? Object.fromEntries(\n Object.entries(value.byState).filter(\n (entry): entry is [string, string] => typeof entry[1] === \"string\"\n )\n )\n : undefined;\n return { latest: value.latest, byScope, ...(byState && { byState }) };\n}\n\n/** Message for a server that hit the limit. */\nexport function authorizationExhaustedMessage(\n rounds: number,\n scope: string\n): string {\n const scopes = scope ? ` for scope \"${scope}\"` : \"\";\n return `The server still requires authorization${scopes} after ${rounds} completed authorizations. Stopped to avoid an authorization loop; reconnect the server to try again.`;\n}\n\n/** Remember a new link's scope set, dropping links whose round is gone. */\nfunction rememberLink(\n links: Readonly<Record<string, string>>,\n byScope: Readonly<Record<string, ScopeRounds>>,\n state: string | null | undefined,\n scope: string\n): Record<string, string> {\n const kept = Object.entries(links).filter(\n ([link, linkScope]) => link !== state && Object.hasOwn(byScope, linkScope)\n );\n if (state) kept.push([state, scope]);\n return Object.fromEntries(kept.slice(-MAX_REMEMBERED_LINKS));\n}\n\n/** A scope set's own entry; never an inherited `Object` member. */\nfunction entryFor(\n byScope: Readonly<Record<string, ScopeRounds>>,\n scope: string\n): ScopeRounds | undefined {\n return Object.hasOwn(byScope, scope) ? byScope[scope] : undefined;\n}\n\n/** Scope sets whose latest round is still inside the window. */\nfunction live(\n byScope: Readonly<Record<string, ScopeRounds>>,\n now: number\n): Record<string, ScopeRounds> {\n return Object.fromEntries(\n Object.entries(byScope).filter(\n ([, entry]) => now - entry.at <= AUTHORIZATION_ROUNDS_WINDOW_MS\n )\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n","/**\n * The OAuth callback leg of the MCP client: recognizing a callback request,\n * parsing it, checking and consuming its `state` nonce, exchanging its code\n * inside the PKCE verifier scope of that state, and rendering the response.\n * Connection state transitions stay with the manager.\n */\n\nimport type { MCPClientConnection } from \"./connection\";\nimport type { AgentMcpOAuthProvider } from \"./do-oauth-client-provider\";\nimport type { MCPServerRow } from \"./storage\";\n\n/** Configures how the manager answers an OAuth callback request. */\nexport type MCPClientOAuthCallbackConfig = {\n /** Redirect target after a successful callback. */\n successRedirect?: string;\n /** Redirect target after a failed callback; `error` is appended. */\n errorRedirect?: string;\n /** Build the response yourself; takes precedence over the redirects. */\n customHandler?: (result: MCPClientOAuthResult) => Response;\n};\n\n/** Outcome of an OAuth callback request. */\nexport type MCPClientOAuthResult =\n | { serverId: string; authSuccess: true; authError?: undefined }\n | {\n serverId?: string;\n authSuccess: false;\n /** May contain untrusted content from external OAuth providers. Escape appropriately for your output context. */\n authError: string;\n };\n\n/** A callback request, parsed far enough to find its connection. */\ntype ParsedOAuthCallback =\n | {\n readonly _tag: \"callback\";\n readonly serverId: string;\n readonly state: string;\n readonly params: URLSearchParams;\n }\n | {\n readonly _tag: \"invalid\";\n readonly serverId?: string;\n readonly state?: string;\n readonly error: string;\n };\n\n/** Server id embedded in an OAuth `state` of the form `{nonce}.{serverId}`. */\nexport function serverIdFromState(state: string | null): string | null {\n if (!state) return null;\n const parts = state.split(\".\");\n return parts.length === 2 ? parts[1] : null;\n}\n\n/**\n * Whether a request is an OAuth callback for one of the stored servers: a\n * `GET` whose `state` names a server and whose origin and path match that\n * server's registered callback URL, so unrelated requests carrying a\n * `state` parameter are left alone.\n */\nexport function isOAuthCallbackFor(\n request: Request,\n servers: readonly MCPServerRow[]\n): boolean {\n if (request.method !== \"GET\") return false;\n const url = new URL(request.url);\n const serverId = serverIdFromState(url.searchParams.get(\"state\"));\n if (!serverId) return false;\n return servers.some((server) => {\n if (server.id !== serverId) return false;\n try {\n const storedUrl = new URL(server.callback_url);\n return (\n storedUrl.origin === url.origin && storedUrl.pathname === url.pathname\n );\n } catch {\n return false;\n }\n });\n}\n\n/** Parse a callback request and find the server and connection it targets. */\nexport function parseOAuthCallback(\n request: Request,\n lookup: {\n readonly hasServer: (id: string) => boolean;\n readonly hasConnection: (id: string) => boolean;\n }\n): ParsedOAuthCallback {\n const url = new URL(request.url);\n const code = url.searchParams.get(\"code\");\n const state = url.searchParams.get(\"state\");\n const error = url.searchParams.get(\"error\");\n\n if (!state) {\n return { _tag: \"invalid\", error: \"Unauthorized: no state provided\" };\n }\n const serverId = serverIdFromState(state);\n if (!serverId) {\n return {\n _tag: \"invalid\",\n error:\n \"No serverId found in state parameter. Expected format: {nonce}.{serverId}\"\n };\n }\n if (!code && !error) {\n return {\n _tag: \"invalid\",\n serverId,\n state,\n error: \"Unauthorized: no code provided\"\n };\n }\n if (!lookup.hasServer(serverId)) {\n return {\n _tag: \"invalid\",\n serverId,\n error: `No server found with id \"${serverId}\". Was the request matched with \\`isCallbackRequest()\\`?`\n };\n }\n if (!lookup.hasConnection(serverId)) {\n return {\n _tag: \"invalid\",\n serverId,\n error: `No connection found for serverId \"${serverId}\".`\n };\n }\n return { _tag: \"callback\", serverId, state, params: url.searchParams };\n}\n\n/** Whether the provider will still redeem `state` for this server. */\nexport async function isRedeemableState(\n serverId: string,\n authProvider: AgentMcpOAuthProvider,\n state: string\n): Promise<boolean> {\n authProvider.serverId = serverId;\n try {\n return (await authProvider.checkState(state)).valid;\n } catch {\n return false;\n }\n}\n\n/**\n * `authUrl` when it is an absolute http(s) URL, so a corrupted stored value\n * is never handed to a client. Whether the link still works is up to the\n * authorization server and the callback, not this check.\n */\nexport function usableAuthUrl(\n authUrl: string | null | undefined\n): string | undefined {\n if (!authUrl) return undefined;\n try {\n const { protocol } = new URL(authUrl);\n return protocol === \"http:\" || protocol === \"https:\" ? authUrl : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Consume the state of a callback that arrived after its flow was already\n * accepted (a duplicate or stale popup), so it cannot be replayed. Verifier\n * cleanup is left to the active completion path.\n */\nexport async function consumeStaleState(\n serverId: string,\n authProvider: AgentMcpOAuthProvider,\n state: string\n): Promise<void> {\n authProvider.serverId = serverId;\n try {\n const stateValidation = await authProvider.checkState(state);\n if (!stateValidation.valid) {\n console.warn(\n `[MCPClientManager] Ignoring stale OAuth callback with invalid state for server \"${serverId}\": ${\n stateValidation.error ?? \"Invalid state\"\n }`\n );\n return;\n }\n await authProvider.consumeState(state);\n } catch (cleanupError) {\n console.warn(\n `[MCPClientManager] Failed to clean up stale OAuth callback state for server \"${serverId}\":`,\n cleanupError\n );\n }\n}\n\n/**\n * Exchange a callback's authorization code on the connection, inside the\n * PKCE verifier scope of its state, then delete that verifier. A completion\n * error wins over a cleanup error.\n */\nexport async function exchangeAuthorizationCode(\n serverId: string,\n conn: MCPClientConnection,\n authProvider: AgentMcpOAuthProvider,\n state: string,\n params: URLSearchParams\n): Promise<void> {\n const exchange = async () => {\n let completeError: unknown;\n let cleanupError: unknown;\n\n try {\n await conn.completeAuthorization(params, { alreadyAccepted: true });\n } catch (error) {\n completeError = error;\n }\n\n try {\n await authProvider.deleteCodeVerifier();\n } catch (deleteError) {\n cleanupError = deleteError;\n }\n\n if (completeError) {\n if (cleanupError) {\n console.warn(\n `[MCPClientManager] Failed to clean up OAuth code verifier for server \"${serverId}\":`,\n cleanupError\n );\n }\n throw completeError;\n }\n if (cleanupError) throw cleanupError;\n };\n\n if (authProvider.runWithCodeVerifierState) {\n await authProvider.runWithCodeVerifierState(state, exchange);\n return;\n }\n await exchange();\n}\n\n/** The response for a handled callback, per the configured handler or redirects. */\nexport function oauthCallbackResponse(\n result: MCPClientOAuthResult,\n request: Request,\n config: MCPClientOAuthCallbackConfig | undefined\n): Response {\n if (config?.customHandler) return config.customHandler(result);\n\n const baseOrigin = new URL(request.url).origin;\n const redirect = result.authSuccess\n ? config?.successRedirect\n : config?.errorRedirect;\n if (!redirect) return Response.redirect(baseOrigin);\n\n try {\n const target = new URL(redirect, baseOrigin);\n if (!result.authSuccess) {\n target.searchParams.set(\"error\", result.authError);\n }\n return Response.redirect(target);\n } catch (error) {\n console.error(\"Invalid OAuth callback redirect URL:\", redirect, error);\n return Response.redirect(baseOrigin);\n }\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst noop = () => {};\nconst NO_LANES: ReadonlySet<string> = new Set();\n\n/** Call `fn`, turning a synchronous throw into a rejection. */\nfunction invoke<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return fn();\n } catch (error) {\n return Promise.reject(error);\n }\n}\n\n/**\n * Rejection for lane work that was still queued when its server's lane was\n * forgotten (the server was removed or its connections closed).\n */\nexport class ServerLaneCancelledError extends Error {\n /** Stable discriminant for this error. */\n readonly _tag = \"ServerLaneCancelledError\" as const;\n\n /**\n * @param serverId - The server whose queued work was cancelled.\n */\n constructor(readonly serverId: string) {\n super(\n `Connection work for MCP server \"${serverId}\" was cancelled because the server was removed or closed`\n );\n this.name = \"ServerLaneCancelledError\";\n }\n}\n\n/**\n * One queue of connection work per MCP server. Work for the same server runs\n * one item at a time in submission order, so connect, discovery, OAuth\n * callback completion and restore never interleave on one connection; work\n * for different servers runs independently.\n *\n * Work is re-entrant: work that is already running for a server may call\n * other lane-wrapped operations for the same server, and they run inline\n * instead of queueing behind their caller. Callbacks that should not inherit\n * that permission (event listeners) run through {@link ServerLanes.outside}.\n */\nexport class ServerLanes {\n readonly #tails = new Map<string, Promise<void>>();\n /** Bumped by `forget()`; queued work from an older generation is cancelled. */\n readonly #generations = new Map<string, number>();\n readonly #held = new AsyncLocalStorage<ReadonlySet<string>>();\n\n /**\n * Run `work` once every earlier item for `serverId` has settled.\n *\n * @param serverId - The server the work belongs to.\n * @param work - The work to run; its result or rejection is returned.\n */\n run<T>(serverId: string, work: () => Promise<T>): Promise<T> {\n const held = this.#held.getStore();\n if (held?.has(serverId)) return invoke(work);\n\n const lane = new Set(held);\n lane.add(serverId);\n const generation = this.#generation(serverId);\n const start = () =>\n this.#generation(serverId) === generation\n ? this.#held.run(lane, work)\n : Promise.reject(new ServerLaneCancelledError(serverId));\n const previous = this.#tails.get(serverId);\n // Claim the lane before starting, so work queued while this work runs\n // synchronously still waits for it.\n let release = noop;\n const tail = new Promise<void>((resolve) => {\n release = resolve;\n });\n this.#tails.set(serverId, tail);\n void tail.then(() => {\n if (this.#tails.get(serverId) === tail) this.#tails.delete(serverId);\n });\n // An idle lane starts the work synchronously, as a direct call would.\n const result = previous ? previous.then(start) : invoke(start);\n result.then(release, release);\n return result;\n }\n\n /**\n * Resolve once no work is queued or running for `serverId`, including work\n * queued while earlier work settles. Resolves immediately when called from\n * that server's own work.\n */\n async idle(serverId: string): Promise<void> {\n if (this.#held.getStore()?.has(serverId)) return;\n while (true) {\n const tail = this.#tails.get(serverId);\n if (!tail) return;\n await tail;\n }\n }\n\n /** Settle-promises for the work queued right now, one per busy server. */\n pending(): Promise<void>[] {\n return [...this.#tails.values()];\n }\n\n /**\n * Cancel a server's queue: work still waiting rejects with\n * {@link ServerLaneCancelledError}, and work already running keeps\n * running. Later work for the same id (a server added again) still waits\n * for that running work, so a late OAuth exchange cannot write over the\n * new server's flow.\n */\n forget(serverId: string): void {\n this.#generations.set(serverId, this.#generation(serverId) + 1);\n }\n\n /** Drop every server's queue, as {@link ServerLanes.forget} does for one. */\n forgetAll(): void {\n for (const serverId of [...this.#tails.keys()]) this.forget(serverId);\n }\n\n #generation(serverId: string): number {\n return this.#generations.get(serverId) ?? 0;\n }\n\n /** Run `fn` without the current work's re-entrant lane permission. */\n outside<T>(fn: () => T): T {\n return this.#held.run(NO_LANES, fn);\n }\n}\n","import {\n authorizationExhaustedMessage,\n completeRound,\n parseAuthorizationRounds,\n requestedScope,\n startRound\n} from \"./authorization-rounds\";\nimport { MCPConnectionState, type MCPClientConnection } from \"./connection\";\nimport type { McpClientContext } from \"./context\";\nimport {\n type AgentMcpOAuthProvider,\n DurableObjectOAuthClientProvider\n} from \"./do-oauth-client-provider\";\nimport {\n isUnauthorized,\n MCPAuthorizationRequiredError,\n MCPConnectionNotFoundError,\n toErrorMessage\n} from \"./errors\";\nimport {\n consumeStaleState,\n exchangeAuthorizationCode,\n isOAuthCallbackFor,\n isRedeemableState,\n type MCPClientOAuthCallbackConfig,\n parseOAuthCallback,\n serverIdFromState,\n usableAuthUrl\n} from \"./oauth-callback\";\nimport { ServerLaneCancelledError } from \"./server-lanes\";\nimport type { MCPServerRow } from \"./storage\";\nimport type { ServerStatus } from \"./status\";\nimport type { MCPOAuthCallbackResult } from \"./types\";\n\n/** What entering `authenticating` produced. */\ntype AuthContinuation =\n | {\n readonly _tag: \"authenticating\";\n readonly authUrl: string;\n readonly clientId?: string;\n }\n | { readonly _tag: \"unavailable\" }\n | { readonly _tag: \"exhausted\"; readonly error: string };\n\n/**\n * Everything about authorization links: building OAuth providers, putting a\n * server into `authenticating` with a link (within the step-up round\n * limit), completing OAuth callbacks, turning a request's 401 or step-up\n * into `MCPAuthorizationRequiredError`.\n *\n * A waiting server keeps the link it was given until someone reconnects it.\n * Whether that link still works is up to the authorization server; the\n * callback reports it when it does not. Only a link whose callback was\n * already redeemed is never shown again.\n */\nexport class AuthorizationController {\n /**\n * The OAuth state each server's callback last redeemed. The provider keeps\n * that link in memory afterwards; it must never be shown again.\n */\n private readonly spentStates = new Map<string, string>();\n /**\n * Step-ups started on a live session, by server: the connection and the\n * state it was in. The session keeps working on its current grant while\n * the user decides, and goes back to that state if they decline.\n */\n private readonly liveStepUps = new Map<\n string,\n {\n readonly conn: MCPClientConnection;\n readonly stateBefore: MCPConnectionState;\n }\n >();\n private callbackConfig: MCPClientOAuthCallbackConfig | undefined;\n\n constructor(\n private readonly ctx: McpClientContext,\n private readonly status: ServerStatus,\n /** Reconnect a server on the grant it holds, queued in its lane. */\n private readonly resume: (id: string) => void\n ) {}\n\n // Providers\n\n /** Build the OAuth provider for a server that has a callback URL. */\n createProvider(\n serverId: string,\n callbackUrl: string,\n clientName: string,\n clientId?: string\n ): AgentMcpOAuthProvider {\n const provider =\n this.ctx.createAuthProvider?.(callbackUrl) ??\n new DurableObjectOAuthClientProvider(\n this.ctx.storage,\n clientName,\n callbackUrl\n );\n provider.serverId = serverId;\n if (clientId) provider.clientId = clientId;\n return provider;\n }\n\n /** Rebuild a server's provider from its stored row, as restore does. */\n providerFromRow(\n row: MCPServerRow | undefined\n ): AgentMcpOAuthProvider | undefined {\n if (!row?.callback_url) return undefined;\n return this.createProvider(\n row.id,\n row.callback_url,\n this.ctx.name,\n row.client_id ?? undefined\n );\n }\n\n /**\n * Clear a server's saved OAuth state. This only deletes local state; it\n * does not revoke tokens at the OAuth provider.\n */\n async clearStorage(\n serverId: string,\n provider: AgentMcpOAuthProvider\n ): Promise<void> {\n try {\n if (provider instanceof DurableObjectOAuthClientProvider) {\n await provider.clearServerStorage();\n } else {\n await provider.invalidateCredentials?.(\"all\");\n }\n } catch (error) {\n console.warn(\n `[MCPClientManager] Failed to clear OAuth credentials for ${serverId}:`,\n error\n );\n }\n }\n\n /**\n * Stop a provider from storing anything more, for work still running on a\n * connection that was replaced. Only the default provider can be retired.\n */\n retire(provider: AgentMcpOAuthProvider): void {\n if (provider instanceof DurableObjectOAuthClientProvider) provider.retire();\n }\n\n /** Let a retired provider store again: a new connection uses it. */\n revive(provider: AgentMcpOAuthProvider): void {\n if (provider instanceof DurableObjectOAuthClientProvider) provider.revive();\n }\n\n // Links\n\n /**\n * Move a connection to `authenticating` on the link its provider holds.\n * Every path that ends up waiting for the user (connect, discovery, and a\n * request that hits a scope step-up or a failed refresh) goes through\n * here, so the saved `auth_url`, the connection state and the broadcast\n * always agree, and the OAuth callback finds the connection in the state\n * it completes from.\n *\n * Changes nothing when the provider holds no usable link. Records a\n * permanent failure instead of a link once the server has asked for the\n * same authorization past the round limit.\n */\n enterAuthenticating(\n id: string,\n conn: MCPClientConnection,\n { stepUp = false }: { readonly stepUp?: boolean } = {}\n ): AuthContinuation {\n if (this.ctx.connections[id] !== conn) return { _tag: \"unavailable\" };\n const provider = conn.options.transport.authProvider;\n const authUrl = provider?.authUrl;\n if (!provider || !authUrl || !provider.redirectUrl) {\n return { _tag: \"unavailable\" };\n }\n // The provider still holds the link whose callback was just redeemed:\n // the server rejected the tokens it produced, and no new flow started.\n if (this.isSpent(id, authUrl)) return { _tag: \"unavailable\" };\n\n const round = startRound(\n parseAuthorizationRounds(this.ctx.store.authorizationRounds(id)),\n requestedScope(authUrl),\n Date.now(),\n stateOf(authUrl)\n );\n if (round._tag === \"exhausted\") {\n const error = authorizationExhaustedMessage(round.rounds, round.scope);\n this.status.stop(id, \"authorization-exhausted\", error);\n return { _tag: \"exhausted\", error };\n }\n\n const clientId = provider.clientId;\n this.ctx.store.setAuthContinuation(id, authUrl, clientId, stepUp);\n this.ctx.store.setAuthorizationRounds(id, round.rounds);\n this.ctx.store.clearFailure(id);\n conn.connectionState = MCPConnectionState.AUTHENTICATING;\n this.ctx.observability.fire({\n type: \"mcp:client:authorize\",\n payload: { serverId: id, authUrl, clientId },\n timestamp: Date.now()\n });\n this.ctx.stateChanged();\n return { _tag: \"authenticating\", authUrl, clientId };\n }\n\n /** Why a 401 left no link to show, for the recorded failure. */\n noLinkReason(id: string, conn: MCPClientConnection): string {\n const provider = conn.options.transport.authProvider;\n if (provider?.authUrl && this.isSpent(id, provider.authUrl)) {\n return \"The server still answers 401 after a completed authorization\";\n }\n if (!provider) {\n return \"The server rejected the request (401 Unauthorized). Check the credentials sent with it, or, if the server uses OAuth, pass callbackHost to addMcpServer() (a callbackUrl to registerServer()) so the user can be asked.\";\n }\n if (!provider.redirectUrl) {\n return \"The server requires authorization, but the OAuth provider has no redirect URL to send the user back to.\";\n }\n return \"The server rejected the credentials, and no new authorization link was produced\";\n }\n\n /** The link a waiting server was given: the live one, else the stored one. */\n pendingLink(id: string, conn: MCPClientConnection): string | undefined {\n return (\n usableAuthUrl(conn.options.transport.authProvider?.authUrl) ??\n usableAuthUrl(this.ctx.store.get(id)?.auth_url)\n );\n }\n\n /** Forget a server's link and step-up budget, for an explicit reconnect. */\n forget(id: string): void {\n this.ctx.store.clearAuthUrl(id);\n this.ctx.store.setAuthorizationRounds(id, undefined);\n this.liveStepUps.delete(id);\n }\n\n /**\n * The server was renamed from `oldId` to `newId` (migrateServerId). Move\n * what is kept by id. A link it was waiting on names the old id in its\n * state, so that link's callback can never reach the server: abandon the\n * flow. A step-up goes back to the session's state, and anything else\n * connects again under the new id when it is settled.\n */\n renamed(\n oldId: string,\n newId: string,\n conn: MCPClientConnection | undefined\n ): void {\n const spent = this.spentStates.get(oldId);\n this.spentStates.delete(oldId);\n if (spent !== undefined) this.spentStates.set(newId, spent);\n const stepUp = this.liveStepUps.get(oldId);\n this.liveStepUps.delete(oldId);\n\n const waiting = conn?.connectionState === MCPConnectionState.AUTHENTICATING;\n if (!waiting && !this.ctx.store.get(newId)?.auth_url) return;\n this.ctx.store.clearAuthUrl(newId);\n if (conn && waiting) {\n conn.connectionState =\n stepUp?.conn === conn\n ? stepUp.stateBefore\n : MCPConnectionState.CONNECTING;\n }\n }\n\n private isLiveStepUp(id: string, conn: MCPClientConnection): boolean {\n return this.liveStepUps.get(id)?.conn === conn;\n }\n\n /**\n * The user declined a step-up: the session still holds its earlier grant,\n * so go back to where it was instead of failing the server. The next\n * request that needs the scope asks again.\n */\n private declineStepUp(\n serverId: string,\n conn: MCPClientConnection,\n error: string\n ): MCPOAuthCallbackResult {\n const stepUp = this.liveStepUps.get(serverId);\n this.liveStepUps.delete(serverId);\n this.ctx.store.clearAuthUrl(serverId);\n conn.connectionState = stepUp?.stateBefore ?? MCPConnectionState.READY;\n conn.connectionError = null;\n this.ctx.stateChanged();\n return { serverId, authSuccess: false, authError: error };\n }\n\n private isSpent(id: string, authUrl: string): boolean {\n const spent = this.spentStates.get(id);\n return spent !== undefined && stateOf(authUrl) === spent;\n }\n\n // Requests\n\n /**\n * Run a request on an established connection and surface mid-session\n * re-authorization.\n *\n * A request can fail after connect with `403 insufficient_scope` (scope\n * step-up) or a `401` whose refresh fails. The SDK then hands a new link\n * to the provider and throws `UnauthorizedError`. Left as is, nobody sees\n * that link, and its callback is ignored as stale because the connection\n * is still `ready`. Enter `authenticating` with it instead, as the connect\n * path does, and throw `MCPAuthorizationRequiredError`.\n */\n async recoverRequest<T>(\n serverId: string,\n request: (conn: MCPClientConnection) => Promise<T>\n ): Promise<T> {\n const conn = this.ctx.connections[serverId];\n if (!conn) throw new MCPConnectionNotFoundError(serverId);\n // Waiting for authorization with no session to fall back on: the\n // request cannot run, and the answer is the link the server waits on.\n if (\n conn.connectionState === MCPConnectionState.AUTHENTICATING &&\n !this.isLiveStepUp(serverId, conn)\n ) {\n const authUrl = this.pendingLink(serverId, conn);\n if (authUrl) {\n throw new MCPAuthorizationRequiredError(serverId, authUrl, {\n clientId: conn.options.transport.authProvider?.clientId\n });\n }\n }\n const authUrlBefore = conn.options.transport.authProvider?.authUrl;\n const sessionBefore = conn.session;\n try {\n return await request(conn);\n } catch (error) {\n throw (\n (await this.authorizationRequired(\n serverId,\n conn,\n error,\n authUrlBefore,\n sessionBefore\n )) ?? error\n );\n }\n }\n\n private async authorizationRequired(\n serverId: string,\n conn: MCPClientConnection,\n error: unknown,\n authUrlBefore: string | undefined,\n sessionBefore: object | undefined\n ): Promise<MCPAuthorizationRequiredError | undefined> {\n // Only take over an established connection, still on the session the\n // request ran on: a connect in the lane closes that session first and\n // leaves the state as it was until it settles. While a callback is being\n // processed (`connecting`, `discovering`) or after a failure, leave the\n // state machine alone and rethrow.\n const canTakeOver = () => {\n if (this.ctx.connections[serverId] !== conn) return false;\n if (conn.session !== sessionBefore) return false;\n const state = conn.connectionState;\n return (\n state === MCPConnectionState.READY ||\n state === MCPConnectionState.CONNECTED ||\n state === MCPConnectionState.AUTHENTICATING\n );\n };\n if (!canTakeOver() || !isUnauthorized(error)) return undefined;\n\n // Only a link set while this request ran counts; an unchanged one is\n // left over from an earlier flow. A changed one may still belong to a\n // flow another request started and the user already completed, so its\n // state must also be redeemable.\n const provider = conn.options.transport.authProvider;\n const authUrl = provider?.authUrl;\n if (!provider || !authUrl || authUrl === authUrlBefore) return undefined;\n const stateBefore = conn.connectionState;\n if (!(await isLive(serverId, authUrl, provider))) return undefined;\n // With a grant still stored, this asks for more than it holds (a scope\n // step-up), and the session keeps working while the user decides. With\n // none (the refresh was refused and the tokens dropped), nothing works\n // until the user signs in again: wait for that, as a connect does.\n const stepUp = await holdsGrant(provider);\n // Nothing may have moved while the check ran.\n if (\n !canTakeOver() ||\n conn.connectionState !== stateBefore ||\n provider.authUrl !== authUrl\n ) {\n return undefined;\n }\n\n const auth = this.enterAuthenticating(serverId, conn, { stepUp });\n // An exhausted server is now failed; the caller gets the original error.\n if (auth._tag !== \"authenticating\") return undefined;\n if (!stepUp) {\n this.liveStepUps.delete(serverId);\n } else if (stateBefore !== MCPConnectionState.AUTHENTICATING) {\n this.liveStepUps.set(serverId, { conn, stateBefore });\n }\n return new MCPAuthorizationRequiredError(serverId, auth.authUrl, {\n clientId: auth.clientId,\n cause: error\n });\n }\n\n // Callbacks\n\n configureCallback(config: MCPClientOAuthCallbackConfig): void {\n this.callbackConfig = config;\n }\n\n getCallbackConfig(): MCPClientOAuthCallbackConfig | undefined {\n return this.callbackConfig;\n }\n\n /** Whether a request is an OAuth callback for one of these servers. */\n isCallback(request: Request): boolean {\n return isOAuthCallbackFor(request, this.ctx.store.list());\n }\n\n /**\n * Complete the OAuth flow a callback belongs to: verify its state,\n * exchange its code, and leave the connection ready to reconnect. A\n * callback for a flow already accepted is consumed as a stale success;\n * one whose state cannot be verified changes nothing.\n */\n async handleCallback(request: Request): Promise<MCPOAuthCallbackResult> {\n const serverId = serverIdFromState(\n new URL(request.url).searchParams.get(\"state\")\n );\n if (!serverId) return this.completeCallback(request);\n return this.ctx.lanes\n .run(serverId, () => this.completeCallback(request))\n .catch((error) => {\n // Removed or closed while this callback waited for earlier work.\n if (error instanceof ServerLaneCancelledError) {\n return this.gone(serverId);\n }\n throw error;\n });\n }\n\n private async completeCallback(\n request: Request\n ): Promise<MCPOAuthCallbackResult> {\n const callback = parseOAuthCallback(request, {\n hasServer: (id) => this.ctx.store.get(id) !== undefined,\n hasConnection: (id) => this.ctx.connections[id] !== undefined\n });\n\n if (callback._tag === \"invalid\") {\n const conn = callback.serverId\n ? this.ctx.connections[callback.serverId]\n : undefined;\n if (!callback.serverId || !conn) {\n return {\n serverId: callback.serverId,\n authSuccess: false,\n authError: callback.error\n };\n }\n const provider = conn.options.transport.authProvider;\n if (isPastAuthorization(conn)) {\n if (callback.state && provider) {\n await consumeStaleState(callback.serverId, provider, callback.state);\n }\n return this.staleSuccess(callback.serverId, conn);\n }\n // Only a callback carrying a genuine state nonce may fail the\n // connection; a stray one must not alter the state machine.\n if (\n callback.state &&\n provider &&\n !(await isRedeemableState(callback.serverId, provider, callback.state))\n ) {\n return ignoreUnverified(callback.serverId, callback.error);\n }\n if (this.ctx.connections[callback.serverId] !== conn) {\n return this.gone(callback.serverId);\n }\n return this.fail(callback.serverId, callback.error);\n }\n\n const { serverId, state, params } = callback;\n const conn = this.ctx.connections[serverId];\n try {\n const provider = conn.options.transport.authProvider;\n if (!provider) {\n throw new Error(\n \"Trying to finalize authentication for a server connection without an authProvider\"\n );\n }\n provider.serverId = serverId;\n\n // Check first and consume later, so an attacker cannot burn a valid\n // state before the real callback arrives.\n const validation = await provider.checkState(state);\n if (!validation.valid) {\n if (isPastAuthorization(conn)) {\n await consumeStaleState(serverId, provider, state);\n return this.staleSuccess(serverId, conn);\n }\n return ignoreUnverified(\n serverId,\n params.get(\"error_description\") ??\n params.get(\"error\") ??\n validation.error ??\n \"Invalid state\"\n );\n }\n\n // A stale popup can complete after another callback already exchanged\n // tokens: succeed, but consume its state so it cannot be replayed.\n if (isPastAuthorization(conn)) {\n await consumeStaleState(serverId, provider, state);\n return this.staleSuccess(serverId, conn);\n }\n\n if (\n conn.connectionState !== MCPConnectionState.AUTHENTICATING &&\n conn.connectionState !== MCPConnectionState.FAILED\n ) {\n throw new Error(\n `Failed to authenticate from \"${conn.connectionState}\" state`\n );\n }\n\n // The user declined a step-up: the session keeps its current grant.\n // If the session is gone (the object woke since), reconnect on it.\n const declined = params.get(\"error\");\n if (declined && this.isLiveStepUp(serverId, conn)) {\n await consumeStaleState(serverId, provider, state);\n return this.declineStepUp(serverId, conn, declined);\n }\n if (declined && this.ctx.store.isPendingStepUp(serverId)) {\n await consumeStaleState(serverId, provider, state);\n this.ctx.store.clearAuthUrl(serverId);\n conn.connectionState = MCPConnectionState.CONNECTING;\n conn.connectionError = null;\n this.ctx.stateChanged();\n // Queued behind this callback, not run inside it.\n this.ctx.lanes.outside(() => this.resume(serverId));\n return { serverId, authSuccess: false, authError: declined };\n }\n\n // A genuine callback can recover a flow that previously failed.\n conn.connectionState = MCPConnectionState.CONNECTING;\n // Forget the link before redeeming it. If the isolate dies during the\n // exchange, a later wake reconnects instead of restoring a spent link.\n this.ctx.store.clearAuthUrl(serverId);\n this.liveStepUps.delete(serverId);\n this.spentStates.set(serverId, state);\n await provider.consumeState(state);\n await exchangeAuthorizationCode(serverId, conn, provider, state, params);\n if (this.ctx.connections[serverId] !== conn) {\n // A server added again under the same id keeps its own pending\n // flow; the tokens just saved were for the old connection.\n if (this.ctx.connections[serverId]) {\n await provider.invalidateCredentials?.(\"tokens\");\n return this.gone(serverId);\n }\n // Closed, still stored: the user's sign-in stands, and the server\n // uses it when it connects again.\n if (this.isClosed(serverId)) {\n this.ctx.store.setAuthorizationRounds(\n serverId,\n completeRound(\n parseAuthorizationRounds(\n this.ctx.store.authorizationRounds(serverId)\n ),\n state\n )\n );\n this.ctx.store.clearAuthUrl(serverId);\n return { serverId, authSuccess: true };\n }\n // Removed while the code was exchanged: the tokens just saved\n // outlived removeServer's cleanup, so clear them again.\n await this.clearStorage(serverId, provider);\n return removedDuringAuthorization(serverId);\n }\n this.status.saveSession(serverId, conn);\n this.ctx.store.setAuthorizationRounds(\n serverId,\n completeRound(\n parseAuthorizationRounds(\n this.ctx.store.authorizationRounds(serverId)\n ),\n state\n )\n );\n const result = this.success(serverId, conn);\n this.ctx.stateChanged();\n return result;\n } catch (error) {\n // A server removed (and maybe re-registered) meanwhile is not ours to\n // fail: the replacement keeps its own state and pending link.\n if (this.ctx.connections[serverId] !== conn) {\n return this.gone(serverId);\n }\n return this.fail(serverId, toErrorMessage(error));\n }\n }\n\n /**\n * The user denied the authorization or its code could not be exchanged.\n * Recorded, so a later wake does not start another flow nobody asked for.\n */\n private fail(serverId: string, error: string): MCPOAuthCallbackResult {\n this.liveStepUps.delete(serverId);\n if (this.ctx.store.get(serverId)) {\n this.status.stop(serverId, \"authorization-failed\", error);\n } else if (this.ctx.connections[serverId]) {\n this.ctx.connections[serverId].connectionState =\n MCPConnectionState.FAILED;\n this.ctx.connections[serverId].connectionError = error;\n this.ctx.stateChanged();\n }\n return { serverId, authSuccess: false, authError: error };\n }\n\n /**\n * Success for a callback whose flow was already accepted, unless the\n * server was removed while its state was cleaned up.\n */\n private staleSuccess(\n serverId: string,\n conn: MCPClientConnection\n ): MCPOAuthCallbackResult {\n if (this.ctx.connections[serverId] !== conn) {\n return this.gone(serverId);\n }\n return this.success(serverId, conn);\n }\n\n /**\n * Whether a server whose connection is gone is still stored and not being\n * removed: its connection was closed (closeConnection), or closed and\n * registered again.\n */\n private isClosed(serverId: string): boolean {\n return (\n this.ctx.store.get(serverId) !== undefined &&\n !this.ctx.removing.has(serverId)\n );\n }\n\n /**\n * Result for a callback whose connection went away while it was handled:\n * the server was registered again, closed, or removed.\n */\n private gone(serverId: string): MCPOAuthCallbackResult {\n const what = this.ctx.connections[serverId]\n ? \"replaced\"\n : this.isClosed(serverId)\n ? \"closed\"\n : undefined;\n if (!what) return removedDuringAuthorization(serverId);\n return {\n serverId,\n authSuccess: false,\n authError: `The connection to server ${serverId} was ${what} during authorization`\n };\n }\n\n private success(\n serverId: string,\n conn: MCPClientConnection\n ): MCPOAuthCallbackResult {\n this.ctx.store.clearAuthUrl(serverId);\n conn.connectionError = null;\n return { serverId, authSuccess: true };\n }\n}\n\n/** Whether a connection's flow was already accepted by a callback. */\nfunction isPastAuthorization(conn: MCPClientConnection): boolean {\n return (\n conn.connectionState === MCPConnectionState.READY ||\n conn.connectionState === MCPConnectionState.CONNECTED ||\n conn.connectionState === MCPConnectionState.CONNECTING ||\n conn.connectionState === MCPConnectionState.DISCOVERING\n );\n}\n\nfunction ignoreUnverified(\n serverId: string,\n error: string\n): MCPOAuthCallbackResult {\n console.warn(\n `[MCPClientManager] Ignoring OAuth callback with unverified state for server \"${serverId}\": ${error}`\n );\n return { serverId, authSuccess: false, authError: error };\n}\n\n/** Result for a callback whose server was removed while it was handled. */\nfunction removedDuringAuthorization(serverId: string): MCPOAuthCallbackResult {\n return {\n serverId,\n authSuccess: false,\n authError: `Server ${serverId} was removed during authorization`\n };\n}\n\n/** Whether a link's `state` can still be redeemed. */\nasync function isLive(\n serverId: string,\n authUrl: string,\n provider: AgentMcpOAuthProvider\n): Promise<boolean> {\n const state = stateOf(authUrl);\n return state ? isRedeemableState(serverId, provider, state) : false;\n}\n\n/** Whether the provider still has tokens stored. */\nasync function holdsGrant(provider: AgentMcpOAuthProvider): Promise<boolean> {\n try {\n return (await provider.tokens()) !== undefined;\n } catch {\n return false;\n }\n}\n\nfunction stateOf(authUrl: string): string | null {\n try {\n return new URL(authUrl).searchParams.get(\"state\");\n } catch {\n return null;\n }\n}\n","import type { ClientCapabilities } from \"@modelcontextprotocol/client\";\nimport {\n elicitationCapabilitiesFromHandlers,\n type MCPElicitationHandlers\n} from \"./connection\";\nimport type { McpClientContext } from \"./context\";\nimport type { MCPClientElicitationHandlers } from \"./types\";\n\n/**\n * The manager's elicitation handlers, held in memory only, and what they\n * make each connection advertise. Advertised modes are stamped on every\n * stored server so a restore re-advertises them before the handlers are\n * configured again.\n */\nexport class ElicitationHandlers {\n private handlers: MCPClientElicitationHandlers | undefined;\n\n constructor(private readonly ctx: McpClientContext) {}\n\n /** Whether any handler is configured. */\n get configured(): boolean {\n return this.handlers !== undefined;\n }\n\n /** Replace the handlers and apply them to every live connection. */\n configure(handlers: MCPClientElicitationHandlers | undefined): void {\n this.handlers =\n handlers && (handlers.form || handlers.url) ? handlers : undefined;\n this.ctx.store.stampCapabilities(this.capabilities());\n for (const [id, connection] of Object.entries(this.ctx.connections)) {\n connection.configureElicitationHandlers(this.scopedTo(id));\n }\n }\n\n /** Client capabilities advertised from the configured handlers. */\n capabilities(): ClientCapabilities | undefined {\n const elicitation = elicitationCapabilitiesFromHandlers(this.handlers);\n return elicitation ? { elicitation } : undefined;\n }\n\n /**\n * The handlers bound to one server id. Undefined when none are configured,\n * so the connection keeps its default throwing behaviour.\n */\n scopedTo(serverId: string): MCPElicitationHandlers | undefined {\n const handlers = this.handlers;\n if (!handlers) return undefined;\n const { form, url } = handlers;\n return {\n form: form\n ? (request, signal) =>\n signal ? form(request, serverId, signal) : form(request, serverId)\n : undefined,\n url: url\n ? (request, signal) =>\n signal ? url(request, serverId, signal) : url(request, serverId)\n : undefined\n };\n }\n}\n","import type {\n ClientCapabilities,\n DiscoverResult,\n StreamableHTTPReconnectionOptions\n} from \"@modelcontextprotocol/client\";\nimport type { RetryOptions } from \"../../retries\";\nimport type { McpClientOptions, TransportType } from \"../types\";\n\n/**\n * Represents a row in the cf_agents_mcp_servers table.\n */\nexport type MCPServerRow = {\n id: string;\n name: string;\n server_url: string;\n client_id: string | null;\n auth_url: string | null;\n callback_url: string;\n server_options: string | null;\n};\n\n/** Create the durable MCP server catalog table when it does not exist. */\nexport function ensureMcpServerTable(storage: DurableObjectStorage): void {\n storage.sql.exec(`\n CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (\n id TEXT PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n server_url TEXT NOT NULL,\n callback_url TEXT NOT NULL,\n client_id TEXT,\n auth_url TEXT,\n server_options TEXT\n )\n `);\n}\n\n/** Explicitly supported durable subset of MCP SDK client options. */\nexport type PersistedMcpClientOptions = Pick<\n McpClientOptions,\n | \"capabilities\"\n | \"supportedProtocolVersions\"\n | \"enforceStrictCapabilities\"\n | \"debouncedNotificationMethods\"\n | \"versionNegotiation\"\n | \"inputRequired\"\n | \"listMaxPages\"\n | \"cachePartition\"\n | \"defaultCacheTtlMs\"\n>;\n\nexport type PersistedMcpTransportOptions = {\n type?: TransportType;\n headers?: HeadersInit;\n requestInit?: RequestInit;\n reconnectionOptions?: StreamableHTTPReconnectionOptions;\n skipIssuerMetadataValidation?: boolean;\n onInsufficientScope?: \"reauthorize\" | \"throw\";\n maxStepUpRetries?: number;\n sessionId?: string;\n protocolVersion?: string;\n};\n\nexport type PersistedMcpServerOptions = {\n client?: PersistedMcpClientOptions;\n transport?: PersistedMcpTransportOptions;\n discoverResult?: DiscoverResult;\n retry?: RetryOptions;\n /** Durable Object binding used to restore an RPC MCP connection. */\n bindingName?: string;\n /** Application props passed back to a restored RPC MCP connection. */\n props?: Record<string, unknown>;\n /** One-wake capability seed; handler functions remain memory-only. */\n capabilities?: ClientCapabilities;\n};\n\ntype PersistableTransportOptions = PersistedMcpTransportOptions & {\n authProvider?: unknown;\n fetch?: unknown;\n reconnectionScheduler?: unknown;\n eventSourceInit?: unknown;\n};\n\ntype PersistableRegistration = {\n client?: McpClientOptions;\n transport?: PersistableTransportOptions;\n discoverResult?: DiscoverResult;\n retry?: RetryOptions;\n bindingName?: string;\n props?: Record<string, unknown>;\n capabilities?: ClientCapabilities;\n};\n\nfunction persistClientOptions(\n client?: McpClientOptions\n): PersistedMcpClientOptions | undefined {\n if (!client) return undefined;\n return {\n capabilities: client.capabilities,\n supportedProtocolVersions: client.supportedProtocolVersions,\n enforceStrictCapabilities: client.enforceStrictCapabilities,\n debouncedNotificationMethods: client.debouncedNotificationMethods,\n versionNegotiation: client.versionNegotiation,\n inputRequired: client.inputRequired,\n listMaxPages: client.listMaxPages,\n cachePartition: client.cachePartition,\n defaultCacheTtlMs: client.defaultCacheTtlMs\n };\n}\n\n/**\n * Headers as a plain record, so they survive JSON: a `Headers` instance\n * would be stored as `{}`.\n */\nfunction persistHeaders(\n headers: HeadersInit | undefined\n): Record<string, string> | undefined {\n return headers ? Object.fromEntries(new Headers(headers)) : undefined;\n}\n\nfunction persistTransportOptions(\n value?: PersistableTransportOptions\n): PersistedMcpTransportOptions | undefined {\n if (!value) return undefined;\n return {\n type: value.type,\n headers: persistHeaders(value.headers),\n requestInit: value.requestInit && {\n ...value.requestInit,\n headers: persistHeaders(value.requestInit.headers)\n },\n reconnectionOptions: value.reconnectionOptions,\n skipIssuerMetadataValidation: value.skipIssuerMetadataValidation,\n onInsufficientScope: value.onInsufficientScope,\n maxStepUpRetries: value.maxStepUpRetries,\n sessionId: value.sessionId,\n protocolVersion: value.protocolVersion\n };\n}\n\nexport function encodeMcpServerOptions(\n options: PersistableRegistration\n): string {\n return JSON.stringify({\n client: persistClientOptions(options.client),\n transport: persistTransportOptions(options.transport),\n discoverResult: options.discoverResult,\n retry: options.retry,\n bindingName: options.bindingName,\n props: options.props,\n capabilities: options.capabilities\n } satisfies PersistedMcpServerOptions);\n}\n\nexport function decodeMcpServerOptions(\n value: string | null\n): PersistedMcpServerOptions {\n if (!value) return {};\n const parsed = JSON.parse(value) as PersistedMcpServerOptions;\n const transport = persistTransportOptions(parsed.transport);\n const statelessWithoutPrior =\n transport?.protocolVersion === \"2026-07-28\" && !parsed.discoverResult;\n if (\n transport?.sessionId &&\n (!transport.protocolVersion || statelessWithoutPrior)\n ) {\n delete transport.sessionId;\n delete transport.protocolVersion;\n delete parsed.discoverResult;\n }\n return {\n client: persistClientOptions(parsed.client),\n transport,\n discoverResult: parsed.discoverResult,\n retry: parsed.retry,\n ...(parsed.bindingName !== undefined && {\n bindingName: parsed.bindingName\n }),\n ...(parsed.props !== undefined && { props: parsed.props }),\n capabilities: parsed.capabilities\n };\n}\n\nexport function withMcpSession(\n options: PersistedMcpServerOptions,\n session?: {\n id: string;\n protocolVersion: string;\n discoverResult?: DiscoverResult;\n }\n): PersistedMcpServerOptions {\n const transport = { ...(options.transport ?? {}) };\n if (!session) {\n delete transport.sessionId;\n delete transport.protocolVersion;\n const next = { ...options, transport };\n delete next.discoverResult;\n return next;\n }\n transport.sessionId = session.id;\n transport.protocolVersion = session.protocolVersion;\n return {\n ...options,\n transport,\n ...(session.discoverResult\n ? { discoverResult: session.discoverResult }\n : { discoverResult: undefined })\n };\n}\n","import type { RPCClientTransportOptions } from \"../rpc\";\nimport { decodeMcpServerOptions, type MCPServerRow } from \"./storage\";\nimport { isDurableObjectNamespace, RPC_DO_PREFIX } from \"../rpc\";\n\n/** The transport for a stored RPC server, or why it cannot be built. */\nexport type RpcTransportResolution =\n | {\n readonly _tag: \"resolved\";\n readonly transport: RPCClientTransportOptions & { type: \"rpc\" };\n }\n | { readonly _tag: \"unresolved\"; readonly reason: string };\n\n/**\n * Build the RPC transport for a stored server by resolving its Durable\n * Object binding from `env` by the binding name persisted with the server.\n */\nexport function resolveRpcTransport(\n env: Cloudflare.Env | undefined,\n server: MCPServerRow\n): RpcTransportResolution {\n if (!env) {\n return {\n _tag: \"unresolved\",\n reason:\n \"no env was provided; pass { env } when constructing MCPClientManager\"\n };\n }\n const options = decodeMcpServerOptions(server.server_options);\n const binding = options.bindingName\n ? Object.entries(env).find(([name]) => name === options.bindingName)?.[1]\n : undefined;\n if (!isDurableObjectNamespace(binding)) {\n return {\n _tag: \"unresolved\",\n reason: `binding \"${options.bindingName ?? \"<missing>\"}\" not found in env`\n };\n }\n return {\n _tag: \"resolved\",\n transport: {\n type: \"rpc\",\n namespace: binding,\n name: server.server_url.replace(RPC_DO_PREFIX, \"\"),\n props: options.props\n }\n };\n}\n","/**\n * Rules for the identifiers and URLs the MCP client manager accepts: stable\n * server ids, and the SSRF policy that keeps HTTP connections off private\n * and internal networks.\n */\n\n/** Maximum length of a normalized MCP server id. */\nexport const MCP_SERVER_ID_MAX_LENGTH = 64;\n\n/**\n * Normalize a caller-supplied MCP server id into a stable, storage- and\n * tool-name-safe form.\n *\n * The id is surfaced in several places where the character set matters:\n * - as the primary key in the `cf_agents_mcp_servers` SQLite table\n * - embedded in AI SDK tool names as `` `tool_${id.replace(/-/g, \"\")}_${tool}` ``\n * (tool names must match `/^[A-Za-z0-9_]+$/`)\n * - as a key on the `mcpConnections` map and OAuth provider storage\n *\n * Rules:\n * 1. Lowercase.\n * 2. Replace any run of disallowed characters with a single `-`.\n * 3. Collapse repeated `-` and trim leading/trailing `-`/`_`.\n * 4. Prefix with `id-` if the result is empty or doesn't start with a letter.\n * 5. Truncate to {@link MCP_SERVER_ID_MAX_LENGTH} characters.\n *\n * @example\n * normalizeServerId(\"my-supplied-id\"); // \"my-supplied-id\"\n * normalizeServerId(\"GitHub MCP!\"); // \"github-mcp\"\n * normalizeServerId(\"42-things\"); // \"id-42-things\"\n */\nexport function normalizeServerId(input: string): string {\n if (typeof input !== \"string\") {\n throw new TypeError(\n `normalizeServerId: expected string, got ${typeof input}`\n );\n }\n\n let id = input\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^[-_]+|[-_]+$/g, \"\");\n\n if (id.length === 0 || !/^[a-z]/.test(id)) {\n id = `id-${id}`.replace(/-+$/g, \"\");\n }\n\n if (id.length > MCP_SERVER_ID_MAX_LENGTH) {\n id = id.slice(0, MCP_SERVER_ID_MAX_LENGTH).replace(/-+$/g, \"\");\n }\n\n return id;\n}\n\n/**\n * Blocked hostname patterns for SSRF protection.\n * Prevents MCP client from connecting to internal/private network addresses\n * while allowing loopback hosts for local development.\n */\nconst BLOCKED_HOSTNAMES = new Set([\n \"0.0.0.0\",\n \"[::]\",\n \"metadata.google.internal\"\n]);\n\n/**\n * Check whether four IPv4 octets belong to a private/reserved range.\n * Blocks RFC 1918, link-local, cloud metadata, and unspecified addresses.\n */\nfunction isPrivateIPv4(octets: number[]): boolean {\n const [a, b] = octets;\n // 10.0.0.0/8\n if (a === 10) return true;\n // 172.16.0.0/12\n if (a === 172 && b >= 16 && b <= 31) return true;\n // 192.168.0.0/16\n if (a === 192 && b === 168) return true;\n // 169.254.0.0/16 (link-local / cloud metadata)\n if (a === 169 && b === 254) return true;\n // 0.0.0.0/8\n if (a === 0) return true;\n return false;\n}\n\n/**\n * fe80::/10 — IPv6 link-local (RFC 4291 §2.5.6).\n *\n * The /10 boundary fixes the first 10 bits (1111111010), which means valid\n * first hextets range from fe80 through febf. Only hex digits 8, 9, a, b\n * have high two bits \"10\" — anything else (e.g. fe7f, fec0) is out of range.\n * The fourth hex digit is unconstrained by the /10 boundary.\n *\n * Historical bug: `startsWith(\"fe80\")` only matched the narrower fe80::/16\n * prefix and let fe81::/feab::/febf:: slip through. See issue #1325.\n */\nconst IPV6_LINK_LOCAL = /^fe[89ab][0-9a-f]/;\n\n/**\n * Check whether a bracket-stripped, lowercased IPv6 address belongs to a\n * private/reserved range. Also unwraps IPv4-mapped IPv6 (::ffff:...) and\n * delegates to isPrivateIPv4 for those.\n *\n * Loopback (::1) and unspecified (::) are NOT blocked here:\n * - ::1 is intentionally allowed (parallel to 127.x.x.x for local dev)\n * - :: (== [::]) is blocked via BLOCKED_HOSTNAMES at the hostname level\n */\nfunction isPrivateIPv6(addr: string): boolean {\n // fc00::/7 — unique local addresses (fc00:: through fdff::).\n // /7 fixes first 7 bits \"1111110\", so the 8-bit prefix is either\n // fc (11111100) or fd (11111101). No other first hextets qualify.\n if (addr.startsWith(\"fc\") || addr.startsWith(\"fd\")) return true;\n\n // fe80::/10 — link-local addresses (fe80:: through febf:...).\n if (IPV6_LINK_LOCAL.test(addr)) return true;\n\n // IPv4-mapped IPv6 (::ffff:x.x.x.x or ::ffff:XXYY:ZZWW).\n // The WHATWG URL parser does NOT canonicalize hex-form tails to dotted\n // form — [::ffff:a00:1] stays as \"::ffff:a00:1\" and will only be caught\n // by the hex branch. Both forms must therefore be handled here.\n if (addr.startsWith(\"::ffff:\")) {\n const mapped = addr.slice(7);\n const dotParts = mapped.split(\".\");\n if (dotParts.length === 4 && dotParts.every((p) => /^\\d{1,3}$/.test(p))) {\n if (isPrivateIPv4(dotParts.map(Number))) return true;\n } else {\n const hexParts = mapped.split(\":\");\n if (hexParts.length === 2) {\n const hi = parseInt(hexParts[0], 16);\n const lo = parseInt(hexParts[1], 16);\n if (\n isPrivateIPv4([\n (hi >> 8) & 0xff,\n hi & 0xff,\n (lo >> 8) & 0xff,\n lo & 0xff\n ])\n )\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Check whether a hostname looks like a private/internal IP address.\n * Blocks RFC 1918, link-local, unique-local, unspecified,\n * and cloud metadata endpoints. Also detects IPv4-mapped IPv6 addresses.\n */\nexport function isBlockedUrl(url: string): boolean {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return true; // Malformed URLs are blocked\n }\n\n const hostname = parsed.hostname;\n\n if (BLOCKED_HOSTNAMES.has(hostname)) return true;\n\n // IPv4 checks\n const ipv4Parts = hostname.split(\".\");\n if (ipv4Parts.length === 4 && ipv4Parts.every((p) => /^\\d{1,3}$/.test(p))) {\n if (isPrivateIPv4(ipv4Parts.map(Number))) return true;\n }\n\n // IPv6 private range checks.\n // URL parser keeps brackets: hostname for [fc00::1] is \"[fc00::1]\".\n // The parser also lowercases/canonicalizes the address, but we\n // lowercase again defensively in case this helper is ever called with\n // a non-parser-produced hostname.\n if (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n if (isPrivateIPv6(hostname.slice(1, -1).toLowerCase())) return true;\n }\n\n return false;\n}\n","import type { DiscoverResult } from \"@modelcontextprotocol/client\";\nimport { DisposableStore } from \"../../core/events\";\nimport { tryN } from \"../../retries\";\nimport { RPC_DO_PREFIX } from \"../rpc\";\nimport type { McpClientOptions, TransportType } from \"../types\";\nimport type { AuthorizationController } from \"./authorization\";\nimport {\n MCPClientConnection,\n MCPConnectionState,\n type MCPDiscoveryResult,\n type MCPTransportOptions\n} from \"./connection\";\nimport type { McpClientContext } from \"./context\";\nimport type { AgentMcpOAuthProvider } from \"./do-oauth-client-provider\";\nimport type { ElicitationHandlers } from \"./elicitation\";\nimport { toErrorMessage } from \"./errors\";\nimport { resolveRpcTransport } from \"./rpc\";\nimport { ServerLaneCancelledError } from \"./server-lanes\";\nimport type { ServerStatus } from \"./status\";\nimport {\n decodeMcpServerOptions,\n encodeMcpServerOptions,\n type MCPServerRow\n} from \"./storage\";\nimport type {\n MCPConnectionResult,\n MCPDiscoverResult,\n MCPServerSettlement,\n RegisterServerOptions\n} from \"./types\";\nimport { isBlockedUrl } from \"./url-policy\";\n\n/**\n * The manager's public connection methods. Internal paths call through\n * them, so a subclass that overrides one (or a test that spies on it) sees\n * every connect and discovery, not only the ones callers start.\n */\nexport type ConnectionEntryPoints = {\n connectToServer(id: string): Promise<MCPConnectionResult>;\n discoverIfConnected(\n id: string,\n options?: { timeoutMs?: number }\n ): Promise<MCPDiscoverResult | undefined>;\n};\n\n/**\n * The life of each server: register, connect, discover, restore on wake,\n * settle for `addMcpServer()`, reconnect on request, close, remove, rename.\n *\n * All of it runs in the server's lane, one operation at a time. After every\n * failed connect or discovery (after its quick attempts),\n * {@link afterFailure} records why. A failed server stays failed, across\n * wakes too, until {@link reconnect} is called. Nothing retries on a timer.\n */\nexport class ServerController {\n private readonly disposables = new Map<string, DisposableStore>();\n /**\n * The provider of a server's closed connection. Work the connection\n * started may still be running with it (a token refresh, say). Once the\n * server has a new connection, or is removed, that work must not store\n * anything more: createConnection retires the provider, and removeServer\n * clears storage through it.\n */\n private readonly closedProviders = new Map<string, AgentMcpOAuthProvider>();\n /**\n * How many times each id was registered since this object woke.\n * removeServer deletes the row only if the id was not registered again\n * while it closed the connection and cleared the credentials.\n */\n private readonly registrations = new Map<string, number>();\n\n constructor(\n private readonly ctx: McpClientContext,\n private readonly status: ServerStatus,\n private readonly authorization: AuthorizationController,\n private readonly elicitation: ElicitationHandlers,\n private readonly entry: ConnectionEntryPoints\n ) {}\n\n // Registering\n\n /** Create the connection and save the server, without connecting. */\n register(id: string, options: RegisterServerOptions): void {\n assertAllowedUrl(options.url);\n const authProvider =\n options.transport?.authProvider ??\n (options.callbackUrl\n ? this.authorization.createProvider(\n id,\n options.callbackUrl,\n this.ctx.name,\n options.clientId\n )\n : undefined);\n if (authProvider) {\n authProvider.serverId = id;\n if (options.clientId) authProvider.clientId = options.clientId;\n }\n\n this.createConnection(id, options.url, {\n client: options.client,\n transport: {\n ...options.transport,\n authProvider,\n type: options.transport?.type ?? (\"auto\" as TransportType)\n }\n });\n\n this.ctx.store.save({\n id,\n name: options.name,\n server_url: options.url,\n callback_url: options.callbackUrl ?? \"\",\n client_id: options.clientId ?? null,\n auth_url: options.authUrl ?? null,\n server_options: encodeMcpServerOptions({\n client: options.client,\n transport: options.transport,\n retry: options.retry,\n capabilities: this.elicitation.capabilities()\n })\n });\n this.registrations.set(id, (this.registrations.get(id) ?? 0) + 1);\n // Registering again is a fresh start for the server.\n this.ctx.store.clearFailure(id);\n this.ctx.store.setAuthorizationRounds(id, undefined);\n this.ctx.stateChanged();\n }\n\n /**\n * Create the in-memory connection, or return the one that exists, and\n * pipe its events to the manager. Does not save anything.\n */\n createConnection(\n id: string,\n url: string,\n options: {\n client?: McpClientOptions;\n transport: MCPTransportOptions;\n discoverResult?: DiscoverResult;\n }\n ): MCPClientConnection {\n const existing = this.ctx.connections[id];\n if (existing) return existing;\n // The new connection owns the server's grant now. A caller may hand in\n // the provider it used before (transport.authProvider): that one is the\n // new connection's, so it is kept, and stores again if it was retired.\n const incoming = options.transport.authProvider;\n const closed = this.closedProviders.get(id);\n this.closedProviders.delete(id);\n if (closed && closed !== incoming) this.authorization.retire(closed);\n if (incoming) this.authorization.revive(incoming);\n\n // Stored servers re-advertise the capabilities saved on their row;\n // fresh registrations rely on the handlers. The stamp is read without\n // clearing, so a wake that never handshakes does not burn it.\n const capabilitySeed = this.ctx.store.options(id)?.capabilities;\n const conn = new MCPClientConnection(\n new URL(url),\n { name: this.ctx.name, version: this.ctx.version },\n {\n client: options.client ?? {},\n transport: {\n ...options.transport,\n type: options.transport?.type ?? (\"auto\" as TransportType)\n },\n elicitationHandlers: this.elicitation.scopedTo(id),\n capabilitySeed,\n discoverResult: options.discoverResult\n }\n );\n this.ctx.connections[id] = conn;\n\n const store = new DisposableStore();\n this.disposables.get(id)?.dispose();\n this.disposables.set(id, store);\n store.add(\n conn.onObservabilityEvent((event) => this.ctx.observability.fire(event))\n );\n store.add(conn.onListChanged(() => this.ctx.stateChanged()));\n\n if (capabilitySeed) {\n // The first successful handshake uses the seed up. Only deploys that\n // stopped configuring handlers clear the stamp; with handlers\n // configured, each configure call re-stamps it.\n const seedClear = conn.onObservabilityEvent((event) => {\n if (\n event.type !== \"mcp:client:connect\" ||\n event.payload.state !== MCPConnectionState.CONNECTED\n ) {\n return;\n }\n seedClear.dispose();\n if (this.elicitation.configured || !conn.options.capabilitySeed) {\n return;\n }\n // The row may have been renamed while the handshake was in flight.\n const currentId = this.idOf(conn);\n if (currentId) this.ctx.store.clearCapabilities(currentId);\n });\n store.add(seedClear);\n }\n return conn;\n }\n\n // Connecting\n\n /**\n * One connect attempt, in the server's lane. The manager's\n * `connectToServer()`.\n */\n connect(id: string): Promise<MCPConnectionResult> {\n return this.ctx.lanes.run(id, () => this.connectInLane(id));\n }\n\n private async connectInLane(id: string): Promise<MCPConnectionResult> {\n const conn = this.ctx.connections[id];\n if (!conn) {\n throw new Error(\n `Server ${id} is not registered. Call registerServer() first.`\n );\n }\n // Automatic paths never reach a server with a recorded failure, so this\n // is an explicit reconnect: forget why it stopped, including an\n // exhausted step-up budget.\n if (this.ctx.store.failure(id)) {\n this.ctx.store.clearFailure(id);\n this.ctx.store.setAuthorizationRounds(id, undefined);\n }\n\n const error = await conn.init();\n if (this.ctx.connections[id] !== conn) {\n // Removed or replaced while connecting: nothing from this attempt may\n // reach the catalog or a newer connection under the same id.\n await conn.close().catch(() => {});\n return {\n state: MCPConnectionState.FAILED,\n error: `Server ${id} was removed while connecting`\n };\n }\n this.status.saveSession(id, conn);\n this.ctx.stateChanged();\n\n switch (conn.connectionState) {\n case MCPConnectionState.FAILED:\n return {\n state: MCPConnectionState.FAILED,\n error: error ?? \"Unknown connection error\"\n };\n case MCPConnectionState.AUTHENTICATING: {\n const auth = this.authorization.enterAuthenticating(id, conn);\n switch (auth._tag) {\n case \"authenticating\":\n return {\n state: MCPConnectionState.AUTHENTICATING,\n authUrl: auth.authUrl,\n clientId: auth.clientId\n };\n case \"exhausted\":\n return { state: MCPConnectionState.FAILED, error: auth.error };\n case \"unavailable\":\n // A 401 nothing here can answer with a link: retrying gets the\n // same 401, so automatic reconnects stop.\n conn.accessRefused = true;\n return {\n state: MCPConnectionState.FAILED,\n error: this.authorization.noLinkReason(id, conn)\n };\n }\n }\n case MCPConnectionState.CONNECTED:\n return { state: MCPConnectionState.CONNECTED };\n default:\n return {\n state: MCPConnectionState.FAILED,\n error: `Unexpected connection state after init: ${conn.connectionState}`\n };\n }\n }\n\n /**\n * Discover a connected server, in its lane. The manager's\n * `discoverIfConnected()`.\n */\n discover(\n id: string,\n options: { timeoutMs?: number }\n ): Promise<MCPDiscoverResult | undefined> {\n return this.ctx.lanes.run(id, () => this.discoverInLane(id, options));\n }\n\n private async discoverInLane(\n id: string,\n options: { timeoutMs?: number }\n ): Promise<MCPDiscoverResult | undefined> {\n const conn = this.ctx.connections[id];\n if (!conn) {\n this.ctx.observability.fire({\n type: \"mcp:client:discover\",\n payload: {},\n timestamp: Date.now()\n });\n return undefined;\n }\n\n const result = await conn.discover(options);\n if (this.ctx.connections[id] !== conn) {\n // Removed or replaced while discovering; leave storage alone.\n return discoverResult(conn, result);\n }\n if (!result.success && result.reason === \"stale-session\") {\n return this.recoverStaleSession(conn, id, options);\n }\n return this.afterDiscovery(id, conn, result);\n }\n\n /** Record what discovery found: ready, or waiting for the user. */\n private afterDiscovery(\n id: string,\n conn: MCPClientConnection,\n result: Awaited<ReturnType<MCPClientConnection[\"discover\"]>>\n ): MCPDiscoverResult {\n if (result.success) this.status.ready(id);\n // A 401 during discovery (initialize open, catalogs protected) waits for\n // the user exactly like a 401 at connect.\n const auth =\n conn.connectionState === MCPConnectionState.AUTHENTICATING\n ? this.authorization.enterAuthenticating(id, conn)\n : undefined;\n this.ctx.stateChanged();\n return discoverResult(conn, result, auth);\n }\n\n /** A resumed session the server forgot: start a fresh one and discover. */\n private async recoverStaleSession(\n conn: MCPClientConnection,\n id: string,\n options: { timeoutMs?: number }\n ): Promise<MCPDiscoverResult> {\n conn.clearResumedSession();\n this.ctx.store.setSession(id);\n\n let connected: MCPConnectionResult;\n try {\n connected = await this.entry.connectToServer(id);\n } catch (error) {\n return {\n success: false,\n error: toErrorMessage(error),\n state: conn.connectionState\n };\n }\n if (connected.state === MCPConnectionState.AUTHENTICATING) {\n // The fresh session needs the user: keep the link it produced.\n return {\n success: false,\n error: \"The server requires authorization\",\n state: conn.connectionState,\n authUrl: connected.authUrl,\n clientId: connected.clientId\n };\n }\n if (connected.state !== MCPConnectionState.CONNECTED) {\n return {\n success: false,\n error: connected.error,\n state: conn.connectionState\n };\n }\n return this.afterDiscovery(id, conn, await conn.discover(options));\n }\n\n /**\n * Connect and discover as one unit of lane work, then act on the outcome\n * through {@link afterFailure}. Each attempt is a connect plus discovery;\n * a failed one is retried in place with the server's retry options (3\n * attempts by default) before the server counts as failed. A refusal gets\n * the same answer every time, so it is not retried.\n */\n private bringUp(id: string): Promise<MCPServerSettlement> {\n return this.ctx.lanes.run(id, async (): Promise<MCPServerSettlement> => {\n const retry = this.ctx.store.options(id)?.retry;\n // The connection this work brings up. A server removed and added again\n // meanwhile has a new one, which its own work brings up.\n const owner = this.ctx.connections[id];\n const replaced = () => this.ctx.connections[id] !== owner;\n let settlement: MCPServerSettlement;\n try {\n settlement = await tryN(\n retry?.maxAttempts ?? 3,\n async () => {\n if (replaced()) return { state: \"removed\" };\n const attempt = await this.attempt(id);\n if (\n attempt.state === MCPConnectionState.FAILED &&\n !attempt.refused &&\n // A failure the attempt recorded (the step-up limit, say) is\n // final; retrying would clear it.\n !this.ctx.store.failure(id) &&\n this.ctx.connections[id]\n ) {\n throw new AttemptFailedError(attempt);\n }\n return attempt;\n },\n {\n baseDelayMs: retry?.baseDelayMs ?? 500,\n maxDelayMs: retry?.maxDelayMs ?? 5000\n }\n );\n } catch (error) {\n if (!(error instanceof AttemptFailedError)) throw error;\n settlement = error.settlement;\n }\n if (replaced()) return { state: \"removed\" };\n if (settlement.state === MCPConnectionState.FAILED) {\n this.afterFailure(id, settlement);\n }\n return settlement;\n });\n }\n\n /** One connect plus discovery. */\n private async attempt(id: string): Promise<MCPServerSettlement> {\n let connected: MCPConnectionResult;\n try {\n connected = await this.entry.connectToServer(id);\n } catch (error) {\n connected = {\n state: MCPConnectionState.FAILED,\n error: toErrorMessage(error)\n };\n }\n if (connected.state === MCPConnectionState.CONNECTED) {\n return this.settleDiscovery(id);\n }\n if (connected.state === MCPConnectionState.AUTHENTICATING) {\n return {\n state: MCPConnectionState.AUTHENTICATING,\n authUrl: connected.authUrl\n };\n }\n return this.failed(id, \"connect\", connected.error);\n }\n\n private async settleDiscovery(id: string): Promise<MCPServerSettlement> {\n const discovered = await this.entry.discoverIfConnected(id);\n if (discovered?.state === MCPConnectionState.AUTHENTICATING) {\n // Initialize was open but the catalogs need OAuth.\n if (discovered.authUrl) {\n return {\n state: MCPConnectionState.AUTHENTICATING,\n authUrl: discovered.authUrl\n };\n }\n // A 401 no link can answer: asking again gets the same answer.\n return {\n state: MCPConnectionState.FAILED,\n phase: \"discover\",\n error: discovered.error ?? \"The server requires authorization\",\n refused: true\n };\n }\n if (!discovered?.success) {\n return this.failed(\n id,\n \"discover\",\n discovered?.error ?? \"connection not found\"\n );\n }\n return { state: MCPConnectionState.READY };\n }\n\n /** A failed settlement, marked refused when the connection was refused. */\n private failed(\n id: string,\n phase: \"connect\" | \"discover\",\n error: string\n ): MCPServerSettlement {\n return {\n state: MCPConnectionState.FAILED,\n phase,\n error,\n ...(this.ctx.connections[id]?.accessRefused && { refused: true as const })\n };\n }\n\n /**\n * After a failed connect or discovery, its quick attempts used up: record\n * why, so the server stays failed (across wakes too) until someone\n * reconnects it. Nothing retries it on a timer.\n */\n private afterFailure(\n id: string,\n settlement: { readonly error: string; readonly refused?: true }\n ): void {\n if (!this.ctx.connections[id] || !this.ctx.store.get(id)) return;\n // Already stopped for a recorded reason (the step-up limit, say).\n if (this.ctx.store.failure(id)) return;\n if (settlement.refused) {\n this.status.stop(\n id,\n \"authorization-failed\",\n `Authorization was refused: ${settlement.error}`\n );\n return;\n }\n this.status.stop(id, \"connect-failed\", settlement.error);\n }\n\n // What the manager and the Agent call\n\n /** Connect and discover a registered server. */\n connectAndDiscover(id: string): Promise<MCPServerSettlement> {\n return removedIfCancelled(this.bringUp(id));\n }\n\n /**\n * Bring a registered server to a settled state once the work queued for\n * it has run, for `addMcpServer()`: a ready server stays ready, a waiting\n * server returns its link, a connected server is discovered, one never\n * connected is connected. A failed server is reported as failed and never\n * retried here; that is reconnect()'s job.\n */\n settle(id: string): Promise<MCPServerSettlement> {\n return removedIfCancelled(\n this.ctx.lanes.run(id, async (): Promise<MCPServerSettlement> => {\n const conn = this.ctx.connections[id];\n if (!conn) return { state: \"removed\" };\n switch (conn.connectionState) {\n case MCPConnectionState.READY:\n return { state: MCPConnectionState.READY };\n case MCPConnectionState.FAILED:\n // A failure is reported, never retried here: apps call\n // addMcpServer() from onStart, onConnect and request handlers.\n return {\n state: MCPConnectionState.FAILED,\n phase: \"connect\",\n error: `${conn.connectionError ?? \"Connection failed\"} Call reconnectMcpServer(\"${id}\") to try again.`\n };\n case MCPConnectionState.CONNECTED: {\n const settlement = await this.settleDiscovery(id);\n if (settlement.state === MCPConnectionState.FAILED) {\n this.afterFailure(id, settlement);\n }\n return settlement;\n }\n case MCPConnectionState.AUTHENTICATING: {\n // The link it was given, until someone reconnects it.\n const authUrl = this.authorization.pendingLink(id, conn);\n if (authUrl) {\n return { state: MCPConnectionState.AUTHENTICATING, authUrl };\n }\n // No usable link is stored (corrupted storage): start a flow.\n return this.connectAndDiscover(id);\n }\n case MCPConnectionState.CONNECTING:\n case MCPConnectionState.DISCOVERING:\n // Nothing queued is driving it any more, so drive it.\n return this.connectAndDiscover(id);\n }\n })\n );\n }\n\n /**\n * Try a server again because someone asked: forget a recorded failure,\n * its link and step-up budget, and connect now. With the manager's own\n * `connectToServer()`, the only paths that retry a failed server; nothing\n * automatic does.\n */\n reconnect(id: string): Promise<MCPServerSettlement> {\n return removedIfCancelled(\n this.ctx.lanes.run(id, async () => {\n if (!this.ctx.connections[id]) return { state: \"removed\" as const };\n this.ctx.store.clearFailure(id);\n this.authorization.forget(id);\n return this.connectAndDiscover(id);\n })\n );\n }\n\n /** Connect and discover after an OAuth callback, in the background. */\n establish(id: string): Promise<void> {\n return this.ctx.lanes.run(id, async () => {\n const conn = this.ctx.connections[id];\n if (!conn) {\n this.ctx.observability.fire({\n type: \"mcp:client:preconnect\",\n payload: { serverId: id },\n timestamp: Date.now()\n });\n return;\n }\n // Already discovering or ready: nothing to do. Waiting for the user\n // again (a step-up started since the callback): leave it waiting.\n if (\n conn.connectionState !== MCPConnectionState.DISCOVERING &&\n conn.connectionState !== MCPConnectionState.READY &&\n conn.connectionState !== MCPConnectionState.AUTHENTICATING\n ) {\n await this.bringUp(id);\n this.ctx.stateChanged();\n }\n this.ctx.observability.fire({\n type: \"mcp:client:connect\",\n payload: {\n url: conn.url.toString(),\n transport: conn.options.transport.type || \"unknown\",\n state: conn.connectionState\n },\n timestamp: Date.now()\n });\n });\n }\n\n // Waking\n\n /**\n * Rebuild the connections of stored HTTP servers on wake. A server with a\n * recorded failure stays failed, a waiting flow keeps waiting while its\n * link works, and the rest connect in the background.\n *\n * @param clientName - Durable Object identity used to scope OAuth state.\n */\n async restore(clientName: string): Promise<void> {\n for (const server of this.ctx.store.list()) {\n if (server.server_url.startsWith(RPC_DO_PREFIX)) continue;\n if (!(await this.dropStaleConnection(server.id))) continue;\n\n const options = decodeMcpServerOptions(server.server_options);\n const authProvider: AgentMcpOAuthProvider | undefined =\n server.callback_url\n ? this.authorization.createProvider(\n server.id,\n server.callback_url,\n clientName,\n server.client_id ?? undefined\n )\n : undefined;\n const conn = this.createConnection(server.id, server.server_url, {\n client: options?.client ?? {},\n transport: {\n ...(options?.transport ?? {}),\n type: options?.transport?.type ?? (\"auto\" as TransportType),\n authProvider\n },\n discoverResult: options?.discoverResult\n });\n\n if (this.showRecordedFailure(server, conn)) continue;\n // A flow in progress keeps waiting for its callback.\n if (server.auth_url) {\n conn.connectionState = MCPConnectionState.AUTHENTICATING;\n continue;\n }\n this.connectInBackground(server.id);\n }\n }\n\n /**\n * Rebuild stored RPC servers. Like HTTP servers they connect in the\n * background: startup has a 30s budget a slow `McpAgent` must not hold.\n */\n restoreRpc(): void {\n for (const server of this.ctx.store.listRpc()) {\n if (this.ctx.connections[server.id]) continue;\n const resolved = resolveRpcTransport(this.ctx.env, server);\n if (resolved._tag === \"unresolved\") {\n console.warn(\n `[MCPClientManager] Cannot restore RPC MCP server \"${server.name}\": ${resolved.reason}`\n );\n continue;\n }\n const conn = this.createConnection(server.id, server.server_url, {\n transport: resolved.transport\n });\n if (this.showRecordedFailure(server, conn)) continue;\n this.connectInBackground(server.id);\n }\n }\n\n /**\n * Leave a live connection alone (ready, or a flow in progress), or close\n * a failed one so it can be rebuilt. Returns whether to rebuild.\n */\n private async dropStaleConnection(id: string): Promise<boolean> {\n const existing = this.ctx.connections[id];\n if (!existing) return true;\n switch (existing.connectionState) {\n case MCPConnectionState.READY:\n console.warn(\n `[MCPClientManager] Server ${id} already has a ready connection. Skipping recreation.`\n );\n return false;\n case MCPConnectionState.AUTHENTICATING:\n case MCPConnectionState.CONNECTING:\n case MCPConnectionState.DISCOVERING:\n return false;\n case MCPConnectionState.FAILED:\n try {\n await existing.close();\n } catch (error) {\n console.warn(\n `[MCPClientManager] Error closing failed connection ${id}:`,\n error\n );\n } finally {\n this.forgetConnection(existing);\n }\n return true;\n default:\n return true;\n }\n }\n\n /** Show a recorded failure on a rebuilt connection. */\n private showRecordedFailure(\n server: MCPServerRow,\n conn: MCPClientConnection\n ): boolean {\n const failure = this.ctx.store.failure(server.id);\n if (!failure) return false;\n conn.connectionState = MCPConnectionState.FAILED;\n conn.connectionError = failure.message;\n return true;\n }\n\n private connectInBackground(id: string): void {\n void this.bringUp(id).catch((error) => {\n if (error instanceof ServerLaneCancelledError) return;\n console.error(`[MCPClientManager] Error restoring ${id}:`, error);\n });\n }\n\n // Closing and removing\n\n /** Close a server's connection and cancel its queued work. */\n async close(id: string): Promise<void> {\n const conn = this.ctx.connections[id];\n if (!conn) throw new Error(`Connection with id \"${id}\" does not exist.`);\n conn.cancelDiscovery();\n // Queued work for a closed server would only reconnect it.\n this.ctx.lanes.forget(id);\n try {\n await conn.close();\n } finally {\n this.forgetConnection(conn);\n }\n }\n\n /** Close every connection, keeping the servers stored. */\n async closeAll(): Promise<void> {\n const ids = Object.keys(this.ctx.connections);\n this.ctx.lanes.forgetAll();\n for (const id of ids) this.ctx.connections[id].cancelDiscovery();\n const results = await Promise.allSettled(\n ids.map(async (id) => {\n const conn = this.ctx.connections[id];\n try {\n await conn.close();\n } finally {\n this.forgetConnection(conn);\n }\n })\n );\n const errors = results.flatMap((result) =>\n result.status === \"rejected\" ? [result.reason] : []\n );\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) {\n throw new AggregateError(\n errors,\n \"Failed to close one or more MCP connections\"\n );\n }\n }\n\n /** Close a server's connection and delete it with its OAuth state. */\n async remove(id: string): Promise<void> {\n this.ctx.removing.add(id);\n try {\n await this.removeServer(id);\n } finally {\n this.ctx.removing.delete(id);\n }\n }\n\n private async removeServer(id: string): Promise<void> {\n const registration = this.registrations.get(id);\n const conn = this.ctx.connections[id];\n let authProvider =\n conn?.options.transport.authProvider ?? this.closedProviders.get(id);\n if (!authProvider) {\n // A user-supplied provider factory can throw; that must not stop the\n // server from being removed.\n try {\n authProvider = this.authorization.providerFromRow(\n this.ctx.store.get(id)\n );\n } catch (error) {\n console.warn(\n `[MCPClientManager] Failed to create auth provider for ${id}:`,\n error\n );\n }\n }\n if (conn) await this.close(id).catch(() => {});\n // Registered again while the connection closed (an overlapping close let\n // it): the row and the OAuth storage under this id are the new server's.\n // The old provider only stops storing.\n const registeredAgain = () => this.registrations.get(id) !== registration;\n if (registeredAgain()) {\n const current = this.ctx.connections[id]?.options.transport.authProvider;\n // Unless the new registration was handed the same provider.\n if (authProvider && authProvider !== current) {\n this.authorization.retire(authProvider);\n }\n return;\n }\n if (authProvider) await this.authorization.clearStorage(id, authProvider);\n if (this.closedProviders.get(id) === authProvider) {\n this.closedProviders.delete(id);\n }\n // Registered again while the credentials were cleared: keep the new row.\n if (registeredAgain() || this.ctx.connections[id]) return;\n this.ctx.store.remove(id);\n this.ctx.stateChanged();\n }\n\n /**\n * Rename a server's id everywhere it is a key: its row, its connection,\n * its provider and its OAuth storage keys. A no-op when\n * the ids match; throws when `newId` is taken.\n */\n async migrate(\n oldId: string,\n newId: string,\n clientName: string\n ): Promise<void> {\n if (oldId === newId) return;\n // Restore work closes over oldId; drain it before renaming.\n await this.ctx.lanes.idle(oldId);\n\n // From here on nothing awaits. The row and the OAuth keys move in one\n // transaction, and the connection moves in the same step: nothing else\n // can write under the old id in between, and if a write fails or the\n // object dies, the server stays whole under the old id.\n const renamed = this.ctx.storage.transactionSync(() => {\n const result = this.ctx.store.rename(oldId, newId);\n if (result === \"renamed\") {\n this.moveOAuthKeys(\n `/${clientName}/${oldId}/`,\n `/${clientName}/${newId}/`\n );\n }\n return result;\n });\n if (renamed === \"missing\") {\n this.renameConnection(oldId, newId);\n return;\n }\n if (renamed === \"collision\") {\n throw new Error(\n `Cannot migrate MCP server id \"${oldId}\" → \"${newId}\": new id is already in use.`\n );\n }\n // A pending link names the old id in its state, so its callback can\n // never reach the renamed server: abandon it.\n this.authorization.renamed(oldId, newId, this.ctx.connections[oldId]);\n this.renameConnection(oldId, newId);\n this.ctx.stateChanged();\n }\n\n /** Move the provider's storage keys to the new id. Throws on failure. */\n private moveOAuthKeys(oldPrefix: string, newPrefix: string): void {\n const { kv } = this.ctx.storage;\n for (const [key, value] of [...kv.list({ prefix: oldPrefix })]) {\n kv.put(newPrefix + key.slice(oldPrefix.length), value);\n kv.delete(key);\n }\n }\n\n private renameConnection(oldId: string, newId: string): void {\n const conn = this.ctx.connections[oldId];\n if (conn) {\n this.ctx.connections[newId] = conn;\n delete this.ctx.connections[oldId];\n const authProvider = conn.options.transport.authProvider;\n if (authProvider) authProvider.serverId = newId;\n // The elicitation handler closes over the old id. With no handlers\n // there is nothing to rescope, and configuring would wipe the\n // connection's restored capability seed.\n const scoped = this.elicitation.scopedTo(newId);\n if (scoped) conn.configureElicitationHandlers(scoped);\n }\n const disposables = this.disposables.get(oldId);\n if (disposables) {\n this.disposables.set(newId, disposables);\n this.disposables.delete(oldId);\n }\n const registration = this.registrations.get(oldId);\n if (registration !== undefined) {\n this.registrations.set(newId, registration);\n this.registrations.delete(oldId);\n }\n const closed = this.closedProviders.get(oldId);\n if (closed) {\n closed.serverId = newId;\n this.closedProviders.set(newId, closed);\n this.closedProviders.delete(oldId);\n }\n }\n\n /**\n * Drop a closed connection and its session; the server stays stored. Only\n * this connection: while it was closing, an overlapping close may have\n * dropped it already and the server may have a new connection, or the\n * server may have been renamed.\n */\n private forgetConnection(conn: MCPClientConnection): void {\n const id = this.idOf(conn);\n if (id === undefined) return;\n const authProvider = conn.options.transport.authProvider;\n if (authProvider) this.closedProviders.set(id, authProvider);\n this.ctx.store.setSession(id);\n this.disposables.get(id)?.dispose();\n this.disposables.delete(id);\n delete this.ctx.connections[id];\n }\n\n private idOf(conn: MCPClientConnection): string | undefined {\n return Object.keys(this.ctx.connections).find(\n (key) => this.ctx.connections[key] === conn\n );\n }\n}\n\n/** Throw for a URL the SSRF policy blocks. */\nexport function assertAllowedUrl(url: string): void {\n if (isBlockedUrl(url)) {\n throw new Error(\n `Blocked URL: ${url} — MCP client connections to private/internal addresses are not allowed`\n );\n }\n}\n\n/** Report work cancelled by removal as a removed server. */\nasync function removedIfCancelled(\n work: Promise<MCPServerSettlement>\n): Promise<MCPServerSettlement> {\n try {\n return await work;\n } catch (error) {\n if (error instanceof ServerLaneCancelledError) return { state: \"removed\" };\n throw error;\n }\n}\n\nfunction discoverResult(\n conn: MCPClientConnection,\n result: MCPDiscoveryResult,\n auth?: ReturnType<AuthorizationController[\"enterAuthenticating\"]>\n): MCPDiscoverResult {\n if (result.success) return { success: true, state: conn.connectionState };\n return {\n success: false,\n error: auth?._tag === \"exhausted\" ? auth.error : result.error,\n state: conn.connectionState,\n ...(auth?._tag === \"authenticating\" && {\n authUrl: auth.authUrl,\n clientId: auth.clientId\n })\n };\n}\n\n/** Carries a failed attempt out of `tryN` so it is retried. */\nclass AttemptFailedError extends Error {\n constructor(readonly settlement: MCPServerSettlement) {\n super(\"MCP connection attempt failed\");\n }\n}\n","import { nanoid } from \"nanoid\";\nimport type { McpClientOptions } from \"../types\";\nimport {\n type MCPClientConnection,\n MCPConnectionState,\n type MCPTransportOptions\n} from \"./connection\";\nimport type { McpClientContext } from \"./context\";\nimport { toErrorMessage } from \"./errors\";\nimport type { ConnectionEntryPoints, ServerController } from \"./servers\";\nimport { assertAllowedUrl } from \"./servers\";\n\n/** Options for the deprecated `MCPClientManager.connect()`. */\nexport type LegacyConnectOptions = {\n /** Reconnect an existing server id, optionally completing OAuth with a code. */\n reconnect?: {\n id: string;\n oauthClientId?: string;\n oauthCode?: string;\n };\n /** Transport options, including the OAuth provider whose auth URL is read. */\n transport?: MCPTransportOptions;\n /** MCP SDK client options. */\n client?: McpClientOptions;\n};\n\n/**\n * The deprecated `MCPClientManager.connect()`: create (or, with an OAuth\n * code, reuse) a connection, connect it, and discover it. Kept apart from\n * the server controller because nothing else works this way: it neither\n * saves the server nor schedules reconnects.\n */\nexport function legacyConnect(\n ctx: McpClientContext,\n servers: ServerController,\n entry: ConnectionEntryPoints,\n url: string,\n options: LegacyConnectOptions\n): Promise<{ id: string; authUrl?: string; clientId?: string }> {\n const id = options.reconnect?.id ?? nanoid(8);\n return ctx.lanes.run(id, async () => {\n const provider = options.transport?.authProvider;\n if (provider) {\n provider.serverId = id;\n if (options.reconnect?.oauthClientId) {\n provider.clientId = options.reconnect.oauthClientId;\n }\n }\n assertAllowedUrl(url);\n\n // An OAuth reconnect keeps the connection to preserve its state;\n // otherwise drop any existing one and build it again.\n if (!options.reconnect?.oauthCode || !ctx.connections[id]) {\n const replaced = ctx.connections[id];\n if (replaced) {\n delete ctx.connections[id];\n // Out of the map, nothing else can close this transport.\n await replaced.close().catch(() => {});\n ctx.store.setSession(id);\n }\n servers.createConnection(id, url, {\n client: options.client,\n transport: options.transport ?? {}\n });\n }\n\n // The connection this call works on. removeServer and closeConnection\n // run outside the lane and can drop it at any `await`.\n const conn = ctx.connections[id];\n const stillRegistered = () => {\n if (ctx.connections[id] !== conn) {\n throw new Error(`MCP server ${id} was removed while connecting`);\n }\n };\n\n await conn.init();\n stillRegistered();\n\n if (options.reconnect?.oauthCode) {\n try {\n await completeAuthorization(conn, id, options.reconnect.oauthCode);\n stillRegistered();\n await conn.init();\n stillRegistered();\n } catch (error) {\n ctx.observability.fire({\n type: \"mcp:client:connect\",\n payload: {\n url,\n transport: options.transport?.type ?? \"auto\",\n state: conn.connectionState,\n error: toErrorMessage(error)\n },\n timestamp: Date.now()\n });\n throw error;\n }\n }\n\n const authUrl = provider?.authUrl;\n if (\n conn.connectionState === MCPConnectionState.AUTHENTICATING &&\n authUrl &&\n provider?.redirectUrl\n ) {\n return { authUrl, clientId: provider.clientId, id };\n }\n\n const discovered = await entry.discoverIfConnected(id);\n stillRegistered();\n if (discovered && !discovered.success) {\n throw new Error(\n `Failed to discover server capabilities: ${discovered.error}`\n );\n }\n return { id };\n });\n}\n\n/** Exchange the code, always cleaning up the code verifier afterwards. */\nasync function completeAuthorization(\n conn: MCPClientConnection,\n id: string,\n code: string\n): Promise<void> {\n let completeError: unknown;\n try {\n await conn.completeAuthorization(code);\n } catch (error) {\n completeError = error;\n }\n try {\n await conn.options.transport.authProvider?.deleteCodeVerifier();\n } catch (cleanupError) {\n console.warn(\n `[MCPClientManager] Failed to clean up OAuth code verifier for server \"${id}\":`,\n cleanupError\n );\n }\n if (completeError) throw completeError;\n}\n","import type {\n ClientCapabilities,\n DiscoverResult\n} from \"@modelcontextprotocol/client\";\nimport {\n decodeMcpServerOptions,\n encodeMcpServerOptions,\n withMcpSession,\n type MCPServerRow,\n type PersistedMcpServerOptions\n} from \"./storage\";\nimport { RPC_DO_PREFIX } from \"../rpc\";\n\nconst SERVER_COLUMNS =\n \"id, name, server_url, client_id, auth_url, callback_url, server_options\";\n\n/** Outcome of renaming a stored server. */\ntype ServerRenameResult = \"renamed\" | \"missing\" | \"collision\";\n\n/**\n * Why a server stopped trying to connect on its own. Stored with the server\n * so a later wake shows the same failure instead of trying again; only an\n * explicit reconnect clears it.\n */\nexport type StoredServerFailure = {\n /**\n * `connect-failed`: connecting failed after its quick attempts.\n * `authorization-failed`: authorization was refused or denied.\n * `authorization-exhausted`: the server kept asking for the same\n * authorization past the step-up limit.\n */\n readonly reason:\n | \"connect-failed\"\n | \"authorization-failed\"\n | \"authorization-exhausted\";\n /** Human-readable message, shown as the connection error. */\n readonly message: string;\n /** When the failure was recorded, in epoch milliseconds. */\n readonly at: number;\n};\n\n/** A resumable MCP session persisted with its server. */\ntype StoredMcpSession = {\n readonly id: string;\n readonly protocolVersion: string;\n readonly discoverResult?: DiscoverResult;\n};\n\n/**\n * The durable MCP server catalog: one `cf_agents_mcp_servers` row per\n * registered server. Every SQL statement the client manager runs lives here,\n * and `server_options` is read and written only through the storage codec.\n * The table itself is created by `ensureMcpServerTable` during startup.\n */\nexport class McpServerStore {\n /**\n * @param storage - The Durable Object storage holding the catalog table.\n */\n constructor(private readonly storage: DurableObjectStorage) {}\n\n #statusColumnsReady = false;\n\n #exec<T extends Record<string, SqlStorageValue>>(\n query: string,\n ...bindings: SqlStorageValue[]\n ): T[] {\n return [...this.storage.sql.exec<T>(query, ...bindings)];\n }\n\n /** Every stored server, in table order. */\n list(): MCPServerRow[] {\n return this.#exec<MCPServerRow>(\n `SELECT ${SERVER_COLUMNS} FROM cf_agents_mcp_servers`\n );\n }\n\n /** Stored servers reached over Durable Object RPC (`rpc://` URLs). */\n listRpc(): MCPServerRow[] {\n return this.list().filter((server) =>\n server.server_url.startsWith(RPC_DO_PREFIX)\n );\n }\n\n /** One stored server, or undefined when it is not registered. */\n get(id: string): MCPServerRow | undefined {\n return this.#exec<MCPServerRow>(\n `SELECT ${SERVER_COLUMNS} FROM cf_agents_mcp_servers WHERE id = ?`,\n id\n )[0];\n }\n\n /**\n * Insert one server row, or update every catalog column of an existing\n * one. A recorded failure is kept; registration clears it explicitly.\n */\n save(server: MCPServerRow): void {\n this.#exec(\n `INSERT INTO cf_agents_mcp_servers (${SERVER_COLUMNS})\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n name = excluded.name,\n server_url = excluded.server_url,\n client_id = excluded.client_id,\n auth_url = excluded.auth_url,\n callback_url = excluded.callback_url,\n server_options = excluded.server_options`,\n server.id,\n server.name,\n server.server_url,\n server.client_id ?? null,\n server.auth_url ?? null,\n server.callback_url,\n server.server_options ?? null\n );\n }\n\n /** Delete one server row. */\n remove(id: string): void {\n this.#exec(\"DELETE FROM cf_agents_mcp_servers WHERE id = ?\", id);\n }\n\n /** Move a row to a new primary key, refusing to overwrite another row. */\n rename(oldId: string, newId: string): ServerRenameResult {\n if (!this.get(oldId)) return \"missing\";\n if (this.get(newId)) return \"collision\";\n this.#exec(\n \"UPDATE cf_agents_mcp_servers SET id = ? WHERE id = ?\",\n newId,\n oldId\n );\n return \"renamed\";\n }\n\n /** The decoded `server_options` of one server. */\n options(id: string): PersistedMcpServerOptions | undefined {\n const row = this.get(id);\n if (!row?.server_options) return undefined;\n return decodeMcpServerOptions(row.server_options);\n }\n\n /**\n * Record the authorization URL and OAuth client id a flow is waiting on,\n * and whether it is a step-up on a grant the server already holds.\n */\n setAuthContinuation(\n id: string,\n authUrl: string,\n clientId: string | undefined,\n stepUp: boolean\n ): void {\n const row = this.get(id);\n if (!row) return;\n this.save({ ...row, auth_url: authUrl, client_id: clientId ?? null });\n this.#ensureStatusColumns();\n this.#exec(\n \"UPDATE cf_agents_mcp_servers SET pending_step_up = ? WHERE id = ?\",\n stepUp ? 1 : null,\n id\n );\n }\n\n /** Whether the flow a server waits on is a step-up on its current grant. */\n isPendingStepUp(id: string): boolean {\n this.#ensureStatusColumns();\n return (\n this.#exec<{ pending_step_up: number | null }>(\n \"SELECT pending_step_up FROM cf_agents_mcp_servers WHERE id = ?\",\n id\n )[0]?.pending_step_up === 1\n );\n }\n\n /** Forget the authorization URL of one server. */\n clearAuthUrl(id: string): void {\n this.#ensureStatusColumns();\n this.#exec(\n \"UPDATE cf_agents_mcp_servers SET auth_url = NULL, pending_step_up = NULL WHERE id = ?\",\n id\n );\n }\n\n /** Persist, or with no session clear, the resumable session of a server. */\n setSession(id: string, session?: StoredMcpSession): void {\n const row = this.get(id);\n if (!row) return;\n const options = decodeMcpServerOptions(row.server_options);\n this.save({\n ...row,\n server_options: encodeMcpServerOptions(withMcpSession(options, session))\n });\n }\n\n /**\n * Clear the capabilities persisted on one server. The stamp is valid for\n * one successful restore: sessions that configure elicitation handlers\n * re-stamp every row, so a deploy that stops configuring them stops\n * advertising stale modes after its first connected wake.\n */\n clearCapabilities(id: string): void {\n const row = this.get(id);\n if (!row?.server_options) return;\n const options = decodeMcpServerOptions(row.server_options);\n if (!options.capabilities) return;\n options.capabilities = undefined;\n this.save({ ...row, server_options: encodeMcpServerOptions(options) });\n }\n\n /** The failure recorded for one server, if it stopped trying. */\n failure(id: string): StoredServerFailure | undefined {\n this.#ensureStatusColumns();\n const value = this.#exec<{ failure: string | null }>(\n \"SELECT failure FROM cf_agents_mcp_servers WHERE id = ?\",\n id\n )[0]?.failure;\n if (!value) return undefined;\n try {\n return JSON.parse(value) as StoredServerFailure;\n } catch {\n return undefined;\n }\n }\n\n /** Record that one server stopped trying, and why. */\n setFailure(id: string, failure: StoredServerFailure): void {\n this.#ensureStatusColumns();\n this.#exec(\n \"UPDATE cf_agents_mcp_servers SET failure = ? WHERE id = ?\",\n JSON.stringify(failure),\n id\n );\n }\n\n /** Forget a recorded failure, so the server may connect again. */\n clearFailure(id: string): void {\n this.#ensureStatusColumns();\n this.#exec(\n \"UPDATE cf_agents_mcp_servers SET failure = NULL WHERE id = ? AND failure IS NOT NULL\",\n id\n );\n }\n\n /** Authorization rounds recorded for one server, as stored JSON. */\n authorizationRounds(id: string): unknown {\n this.#ensureStatusColumns();\n const value = this.#exec<{ authorization_rounds: string | null }>(\n \"SELECT authorization_rounds FROM cf_agents_mcp_servers WHERE id = ?\",\n id\n )[0]?.authorization_rounds;\n if (!value) return undefined;\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n }\n\n /** Record, or with no value forget, the authorization rounds of a server. */\n setAuthorizationRounds(id: string, rounds: object | undefined): void {\n this.#ensureStatusColumns();\n this.#exec(\n \"UPDATE cf_agents_mcp_servers SET authorization_rounds = ? WHERE id = ?\",\n rounds === undefined ? null : JSON.stringify(rounds),\n id\n );\n }\n\n /**\n * Add the status columns (`failure`, `authorization_rounds`,\n * `pending_step_up`) on first use.\n * They are owned here rather than in `ensureMcpServerTable`, so the\n * catalog's base DDL (and the Agent schema snapshot built from it) stays\n * unchanged and objects that never use them never alter the table.\n */\n #ensureStatusColumns(): void {\n if (this.#statusColumnsReady) return;\n const present = new Set(\n this.#exec<{ name: string }>(\n \"SELECT name FROM pragma_table_info('cf_agents_mcp_servers')\"\n ).map((column) => column.name)\n );\n for (const [column, type] of [\n [\"failure\", \"TEXT\"],\n [\"authorization_rounds\", \"TEXT\"],\n [\"pending_step_up\", \"INTEGER\"]\n ] as const) {\n if (!present.has(column)) {\n this.#exec(\n `ALTER TABLE cf_agents_mcp_servers ADD COLUMN ${column} ${type}`\n );\n }\n }\n this.#statusColumnsReady = true;\n }\n\n /** Stamp the handler-derived capabilities on every stored server. */\n stampCapabilities(capabilities: ClientCapabilities | undefined): void {\n for (const row of this.list()) {\n const options = decodeMcpServerOptions(row.server_options);\n if (\n JSON.stringify(options.capabilities) === JSON.stringify(capabilities)\n ) {\n continue;\n }\n options.capabilities = capabilities;\n this.save({ ...row, server_options: encodeMcpServerOptions(options) });\n }\n }\n}\n","import { MCPConnectionState, type MCPClientConnection } from \"./connection\";\nimport type { McpClientContext } from \"./context\";\nimport type { StoredServerFailure } from \"./server-store\";\n\n/**\n * The transitions every controller shares: a server stops with a recorded\n * reason, a server reaches ready, and a connection's resumable session is\n * saved with its row.\n */\nexport class ServerStatus {\n constructor(private readonly ctx: McpClientContext) {}\n\n /**\n * Mark a server failed and record why, so later wakes show the same\n * failure instead of trying again. Clears its pending link. Only an\n * explicit reconnect clears the failure.\n */\n stop(\n serverId: string,\n reason: StoredServerFailure[\"reason\"],\n message: string\n ): void {\n this.ctx.store.clearAuthUrl(serverId);\n this.ctx.store.setFailure(serverId, { reason, message, at: Date.now() });\n const conn = this.ctx.connections[serverId];\n if (conn) {\n conn.connectionState = MCPConnectionState.FAILED;\n conn.connectionError = message;\n }\n this.ctx.stateChanged();\n }\n\n /** A server reached ready: forget its failure. */\n ready(serverId: string): void {\n this.ctx.store.clearFailure(serverId);\n const conn = this.ctx.connections[serverId];\n if (conn) conn.connectionError = null;\n }\n\n /** Save the connection's resumable session with its row, or clear it. */\n saveSession(serverId: string, conn: MCPClientConnection): void {\n const { sessionId, protocolVersion, discoverResult } = conn;\n this.ctx.store.setSession(\n serverId,\n sessionId && protocolVersion\n ? { id: sessionId, protocolVersion, discoverResult }\n : undefined\n );\n }\n}\n","import type {\n CacheableRequestOptions,\n CallToolRequest,\n CallToolRequestOptions,\n Client,\n GetPromptRequest,\n ReadResourceRequest,\n RequestOptions\n} from \"@modelcontextprotocol/client\";\nimport { Emitter, type Event } from \"../../core/events\";\nimport { LifecycleCapability } from \"../../lifecycle/capability\";\nimport type { CapabilityRequestContext } from \"../../lifecycle/capability-runner\";\nimport type { MCPObservabilityEvent } from \"../../observability/mcp\";\nimport { RPC_DO_PREFIX } from \"../rpc\";\nimport { MCPAIToolConverter, type MCPAIToolSet } from \"./ai-tools\";\nimport { AuthorizationController } from \"./authorization\";\nimport {\n filterConnections,\n getNamespacedData,\n type NamespacedData\n} from \"./catalog\";\nimport type { MCPClientConnection } from \"./connection\";\nimport type { McpClientContext } from \"./context\";\nimport { ElicitationHandlers } from \"./elicitation\";\nimport {\n callV2Tool,\n type CallToolSchemaOrOptions,\n type LegacyCallToolResultSchema\n} from \"./invoker\";\nimport { legacyConnect, type LegacyConnectOptions } from \"./legacy-connect\";\nimport {\n type MCPClientOAuthCallbackConfig,\n oauthCallbackResponse\n} from \"./oauth-callback\";\nimport { McpServerStore } from \"./server-store\";\nimport { ServerLaneCancelledError, ServerLanes } from \"./server-lanes\";\nimport { ServerController } from \"./servers\";\nimport { ServerStatus } from \"./status\";\nimport {\n encodeMcpServerOptions,\n ensureMcpServerTable,\n type MCPServerRow\n} from \"./storage\";\nimport type {\n MCPClientElicitationHandlers,\n MCPClientManagerOptions,\n MCPConnectionResult,\n MCPDiscoverResult,\n MCPOAuthCallbackResult,\n MCPServerFilter,\n MCPServerSettlement,\n RegisterServerOptions\n} from \"./types\";\n\nconst MCP_SCHEMA_VERSION_KEY = \"cf_agents:mcp_schema_version\";\nconst CURRENT_MCP_SCHEMA_VERSION = 1;\n\n/**\n * A Durable Object capability that persists and aggregates MCP client\n * connections. Install it on any Lifecycle, or use `agent.mcp` on an Agent.\n *\n * The manager is the public API and the Lifecycle hooks. Behind it:\n * - {@link ServerController}: each server's connection life, and what\n * happens after a failure\n * - {@link AuthorizationController}: authorization links, OAuth callbacks\n * and re-authorization during requests\n */\nexport class MCPClientManager extends LifecycleCapability {\n public mcpConnections: Record<string, MCPClientConnection> = {};\n\n /** @internal Protected for testing purposes. */\n protected readonly _onObservabilityEvent =\n new Emitter<MCPObservabilityEvent>();\n public readonly onObservabilityEvent: Event<MCPObservabilityEvent> =\n this._onObservabilityEvent.event;\n\n private readonly _onServerStateChanged = new Emitter<void>();\n /**\n * Event that fires whenever any MCP server state changes (registered, connected, removed, etc.)\n * This is useful for broadcasting server state to clients.\n */\n public readonly onServerStateChanged: Event<void> =\n this._onServerStateChanged.event;\n\n private readonly _lanes = new ServerLanes();\n private _isRestored = false;\n #store: McpServerStore | undefined;\n private readonly aiTools = new MCPAIToolConverter();\n private didWarnAboutUnstableGetAITools = false;\n\n private readonly ctx: McpClientContext;\n private readonly status: ServerStatus;\n private readonly elicitation: ElicitationHandlers;\n private readonly authorization: AuthorizationController;\n private readonly servers: ServerController;\n\n /**\n * Construct a reusable Durable Object MCP client capability.\n *\n * @param name - MCP client implementation name sent during negotiation.\n * @param version - MCP client implementation version sent during negotiation.\n * @param options - Optional runtime bindings and OAuth configuration.\n */\n constructor(\n private readonly _name: string,\n version: string,\n options: MCPClientManagerOptions = {}\n ) {\n super(\"mcp\");\n const manager = this;\n const ctx: McpClientContext = {\n name: _name,\n version,\n get connections() {\n return manager.mcpConnections;\n },\n get store() {\n manager.#store ??= new McpServerStore(manager.lifecycle.storage);\n return manager.#store;\n },\n get storage() {\n return manager.lifecycle.storage;\n },\n lanes: this._lanes,\n removing: new Set(),\n env: options.env,\n createAuthProvider: options.createAuthProvider,\n observability: this._onObservabilityEvent,\n // Outside any lane, so a listener that starts connection work queues\n // it instead of running it inside the work that changed the state.\n stateChanged: () =>\n this._lanes.outside(() => this._onServerStateChanged.fire())\n };\n this.status = new ServerStatus(ctx);\n this.elicitation = new ElicitationHandlers(ctx);\n this.authorization = new AuthorizationController(ctx, this.status, (id) => {\n void this.establishConnection(id).catch((error) => {\n if (error instanceof ServerLaneCancelledError) return;\n console.error(\n \"[MCPClientManager] Reconnecting after a declined step-up failed:\",\n error\n );\n });\n });\n this.servers = new ServerController(\n ctx,\n this.status,\n this.authorization,\n this.elicitation,\n {\n connectToServer: (id) => this.connectToServer(id),\n discoverIfConnected: (...args) => this.discoverIfConnected(...args)\n }\n );\n this.ctx = ctx;\n }\n\n // Lifecycle hooks\n\n /** Restore persisted HTTP and RPC connections before the host handles work. */\n async onStart(): Promise<void> {\n const schemaVersion =\n (await this.lifecycle.storage.get<number>(MCP_SCHEMA_VERSION_KEY)) ?? 0;\n if (schemaVersion < CURRENT_MCP_SCHEMA_VERSION) {\n ensureMcpServerTable(this.lifecycle.storage);\n await this.lifecycle.storage.put(\n MCP_SCHEMA_VERSION_KEY,\n CURRENT_MCP_SCHEMA_VERSION\n );\n }\n await this.restoreConnectionsFromStorage(this._name);\n this.servers.restoreRpc();\n this.ctx.stateChanged();\n }\n\n /** Intercept a registered MCP OAuth callback request. */\n async onRequest(\n context: CapabilityRequestContext\n ): Promise<Response | undefined> {\n const { request } = context;\n if (!this.isCallbackRequest(request)) return undefined;\n\n const result = await this.handleCallbackRequest(request);\n if (result.authSuccess) {\n void this.establishConnection(result.serverId).catch((error) => {\n if (error instanceof ServerLaneCancelledError) return;\n console.error(\n \"[MCPClientManager] Connection establishment after OAuth failed:\",\n error\n );\n });\n }\n return oauthCallbackResponse(\n result,\n request,\n this.getOAuthCallbackConfig()\n );\n }\n\n // Servers\n\n /**\n * Register an MCP server connection without connecting\n * Creates the connection object, sets up observability, and saves to storage\n *\n * @param id Server ID\n * @param options Registration options including URL, name, callback URL, and connection config\n * @returns Server ID\n */\n async registerServer(\n id: string,\n options: RegisterServerOptions\n ): Promise<string> {\n this.servers.register(id, options);\n return id;\n }\n\n /**\n * Connect to an already registered MCP server and initialize the connection.\n *\n * For OAuth servers, returns `{ state: \"authenticating\", authUrl, clientId? }`.\n * The user must complete the OAuth flow via the authUrl, which triggers a\n * callback handled by `handleCallbackRequest()`.\n *\n * For non-OAuth servers, establishes the transport connection and returns\n * `{ state: \"connected\" }`. Call `discoverIfConnected()` afterwards to\n * discover capabilities and transition to \"ready\" state.\n *\n * @param id Server ID (must be registered first via registerServer())\n * @returns Connection result with current state and OAuth info (if applicable)\n */\n async connectToServer(id: string): Promise<MCPConnectionResult> {\n return this.servers.connect(id);\n }\n\n /**\n * Discover server capabilities if connection is in CONNECTED or READY state.\n * Transitions to DISCOVERING then READY (or CONNECTED on error).\n * Can be called to refresh server capabilities (e.g., from a UI refresh button).\n *\n * Runs after any connection work already queued for the same server, so a\n * call made during another discovery waits for it and then refreshes again.\n *\n * @param serverId The server ID to discover\n * @param options Optional configuration\n * @param options.timeoutMs Timeout in milliseconds (default: 30000)\n * @returns Result with current state and optional error, or undefined if connection not found\n */\n async discoverIfConnected(\n serverId: string,\n options: { timeoutMs?: number } = {}\n ): Promise<MCPDiscoverResult | undefined> {\n return this.servers.discover(serverId, options);\n }\n\n /**\n * Establish connection in the background after OAuth completion.\n * This method connects to the server and discovers its capabilities.\n * The connection is automatically tracked so that `waitForConnections()`\n * will include it.\n * @param serverId The server ID to establish connection for\n */\n async establishConnection(serverId: string): Promise<void> {\n return this.servers.establish(serverId);\n }\n\n /**\n * @internal Connect a registered server and discover its capabilities, as\n * one unit of lane work. A failure is recorded.\n */\n connectAndDiscover(id: string): Promise<MCPServerSettlement> {\n return this.servers.connectAndDiscover(id);\n }\n\n /**\n * @internal Bring an already-registered server to a settled state once the\n * work queued for it has run, for `addMcpServer()`. Never retries a failed\n * server.\n */\n settleServer(id: string): Promise<MCPServerSettlement> {\n return this.servers.settle(id);\n }\n\n /**\n * @internal Try a server again because someone asked: forget a recorded\n * failure, its link and the step-up budget, and connect now.\n */\n reconnectServer(id: string): Promise<MCPServerSettlement> {\n return this.servers.reconnect(id);\n }\n\n /**\n * Restore persisted HTTP MCP connections. Runs once per wake.\n *\n * @param clientName - Durable Object identity used to scope OAuth state.\n */\n async restoreConnectionsFromStorage(clientName: string): Promise<void> {\n if (this._isRestored) return;\n await this.servers.restore(clientName);\n this._isRestored = true;\n }\n\n /**\n * Wait for all in-flight connection and discovery operations to settle.\n * This is useful when you need MCP tools to be available before proceeding,\n * e.g. before calling getAITools() after the agent wakes from hibernation.\n *\n * Returns once every pending connection has either connected and discovered,\n * failed, or timed out. Never rejects.\n *\n * @param options.timeout - Maximum time in milliseconds to wait.\n * `0` returns immediately without waiting.\n * `undefined` (default) waits indefinitely.\n */\n async waitForConnections(options?: { timeout?: number }): Promise<void> {\n const pending = this._lanes.pending();\n if (pending.length === 0) return;\n if (options?.timeout != null && options.timeout <= 0) return;\n const settled = Promise.allSettled(pending);\n if (options?.timeout == null) {\n await settled;\n return;\n }\n let timerId: ReturnType<typeof setTimeout> | undefined;\n const timer = new Promise<void>((resolve) => {\n timerId = setTimeout(resolve, options.timeout);\n });\n await Promise.race([settled, timer]);\n clearTimeout(timerId);\n }\n\n /**\n * Rename a server's id, in-place, across every place the id is used as a\n * key: its row, its connection, its provider, its OAuth storage keys under\n * `/{clientName}/{oldId}/...`. Used to migrate a\n * server registered under an auto-generated id to a caller-supplied\n * stable id (see `Agent.addMcpServer`'s `{ id }` option).\n *\n * A no-op when `oldId === newId`. Throws when a row already exists under\n * `newId`; the caller is expected to have verified uniqueness.\n *\n * @internal Exposed for `Agent.addMcpServer` JIT-migration.\n */\n async migrateServerId(\n oldId: string,\n newId: string,\n clientName: string\n ): Promise<void> {\n return this.servers.migrate(oldId, newId, clientName);\n }\n\n /**\n * Closes a connection to an MCP server\n * @param id The id of the connection to close\n */\n async closeConnection(id: string): Promise<void> {\n return this.servers.close(id);\n }\n\n /**\n * Closes every in-memory connection. Servers stay stored, and their\n * callback URLs still match incoming OAuth requests; use removeServer()\n * to delete a server.\n */\n async closeAllConnections(): Promise<void> {\n return this.servers.closeAll();\n }\n\n /**\n * Remove an MCP server - closes connection if active and removes from storage.\n */\n async removeServer(serverId: string): Promise<void> {\n return this.servers.remove(serverId);\n }\n\n /**\n * List all MCP servers from storage\n */\n listServers(): MCPServerRow[] {\n return this.ctx.store.list();\n }\n\n /** Get saved RPC servers from storage (servers with `rpc://` URLs). */\n getRpcServersFromStorage(): MCPServerRow[] {\n return this.ctx.store.listRpc();\n }\n\n /**\n * Save an RPC server to storage for hibernation recovery.\n * The binding name is stored so this manager can resolve the namespace from\n * its runtime environment during restore.\n */\n saveRpcServerToStorage(\n id: string,\n name: string,\n normalizedName: string,\n bindingName: string,\n props?: Record<string, unknown>\n ): void {\n this.ctx.store.save({\n id,\n name,\n server_url: `${RPC_DO_PREFIX}${normalizedName}`,\n client_id: null,\n auth_url: null,\n callback_url: \"\",\n server_options: encodeMcpServerOptions({\n bindingName,\n props,\n capabilities: this.elicitation.capabilities()\n })\n });\n }\n\n /**\n * Connect to and register an MCP server\n *\n * @deprecated This method is maintained for backward compatibility.\n * For new code, use registerServer() and connectToServer() separately.\n *\n * @param url Server URL\n * @param options Connection options\n * @returns Object with server ID, auth URL (if OAuth), and client ID (if OAuth)\n */\n async connect(\n url: string,\n options: LegacyConnectOptions = {}\n ): Promise<{ id: string; authUrl?: string; clientId?: string }> {\n return legacyConnect(this.ctx, this.servers, this, url, options);\n }\n\n // OAuth\n\n /** Whether a request is an OAuth callback for one of this manager's servers. */\n isCallbackRequest(req: Request): boolean {\n return this.authorization.isCallback(req);\n }\n\n /**\n * Complete the OAuth flow a callback request belongs to: verify its state,\n * exchange its code, and leave the connection ready to reconnect. A\n * callback for a flow that was already accepted is consumed as a stale\n * success; one whose state cannot be verified changes nothing.\n */\n async handleCallbackRequest(req: Request): Promise<MCPOAuthCallbackResult> {\n return this.authorization.handleCallback(req);\n }\n\n /**\n * Configure OAuth callback handling\n * @param config OAuth callback configuration\n */\n configureOAuthCallback(config: MCPClientOAuthCallbackConfig): void {\n this.authorization.configureCallback(config);\n }\n\n /**\n * Get the current OAuth callback configuration\n * @returns The current OAuth callback configuration\n */\n getOAuthCallbackConfig(): MCPClientOAuthCallbackConfig | undefined {\n return this.authorization.getCallbackConfig();\n }\n\n /**\n * Configure handling for server-initiated `elicitation/create` requests.\n *\n * The handler is held in memory only and applied to every MCP connection\n * created or restored by this manager. Call this before registering\n * connections when you want the initial MCP handshake to advertise\n * handler-driven form- and url-mode elicitation. Existing active connections\n * keep their negotiated capabilities until they reconnect.\n *\n * The advertised modes are persisted with each stored server, so\n * connections restored after hibernation re-advertise them at the handshake\n * even when this is called later in the wake-up (e.g. from onStart) — the\n * handlers attach to the live connections as soon as this runs.\n *\n * Pass undefined to clear the handler.\n *\n * @param handlers Elicitation handlers keyed by mode, each scoped with the server id that sent the request\n */\n configureElicitationHandlers(handlers?: MCPClientElicitationHandlers): void {\n this.elicitation.configure(handlers);\n }\n\n // Catalog and requests\n\n /**\n * @param filter - Optional filter to scope results to specific servers\n * @returns namespaced list of tools\n */\n listTools(filter?: MCPServerFilter): NamespacedData[\"tools\"] {\n return getNamespacedData(this.connectionsFor(filter), \"tools\");\n }\n\n /**\n * @param filter - Optional filter to scope results to specific servers\n * @returns namespaced list of prompts\n */\n listPrompts(filter?: MCPServerFilter): NamespacedData[\"prompts\"] {\n return getNamespacedData(this.connectionsFor(filter), \"prompts\");\n }\n\n /**\n * @param filter - Optional filter to scope results to specific servers\n * @returns namespaced list of resources\n */\n listResources(filter?: MCPServerFilter): NamespacedData[\"resources\"] {\n return getNamespacedData(this.connectionsFor(filter), \"resources\");\n }\n\n /**\n * @param filter - Optional filter to scope results to specific servers\n * @returns namespaced list of resource templates\n */\n listResourceTemplates(\n filter?: MCPServerFilter\n ): NamespacedData[\"resourceTemplates\"] {\n return getNamespacedData(this.connectionsFor(filter), \"resourceTemplates\");\n }\n\n /**\n * Convert connected MCP tools for the AI SDK. Converted schemas are reused\n * while a live connection retains the same catalog array and schema-source\n * identities; tool records and execute closures are rebuilt on every call.\n *\n * @param filter - Optional filter to scope results to specific servers\n * @returns a set of tools that you can use with the AI SDK\n */\n getAITools(filter?: MCPServerFilter): MCPAIToolSet {\n return this.aiTools.convert(this.connectionsFor(filter), (params) =>\n this.callTool(params)\n );\n }\n\n /**\n * @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version\n * @param filter - Optional filter to scope results to specific servers\n * @returns a set of tools that you can use with the AI SDK\n */\n unstable_getAITools(filter?: MCPServerFilter): MCPAIToolSet {\n if (!this.didWarnAboutUnstableGetAITools) {\n this.didWarnAboutUnstableGetAITools = true;\n console.warn(\n \"unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version.\"\n );\n }\n return this.getAITools(filter);\n }\n\n /**\n * Namespaced version of callTool\n */\n async callTool(\n params: CallToolRequest[\"params\"] & { serverId: string },\n options?: CallToolRequestOptions\n ): ReturnType<Client[\"callTool\"]>;\n /**\n * @deprecated Prefer the v2 request-options overload. Explicit legacy result\n * schemas remain honored through the v2 SDK request funnel.\n */\n async callTool(\n params: CallToolRequest[\"params\"] & { serverId: string },\n resultSchema: LegacyCallToolResultSchema,\n options?: CallToolRequestOptions\n ): ReturnType<Client[\"callTool\"]>;\n async callTool(\n params: CallToolRequest[\"params\"] & { serverId: string },\n schemaOrOptions?: CallToolSchemaOrOptions,\n options?: CallToolRequestOptions\n ): ReturnType<Client[\"callTool\"]> {\n const { serverId, ...mcpParams } = params;\n const name = mcpParams.name.replace(`${serverId}.`, \"\");\n return this.authorization.recoverRequest(serverId, (conn) =>\n callV2Tool(conn.client, { ...mcpParams, name }, schemaOrOptions, options)\n );\n }\n\n /**\n * Namespaced version of readResource\n */\n readResource(\n params: ReadResourceRequest[\"params\"] & { serverId: string },\n options?: CacheableRequestOptions\n ) {\n const { serverId, ...mcpParams } = params;\n return this.authorization.recoverRequest(serverId, (conn) =>\n conn.client.readResource(mcpParams, options)\n );\n }\n\n /**\n * Namespaced version of getPrompt\n */\n getPrompt(\n params: GetPromptRequest[\"params\"] & { serverId: string },\n options?: RequestOptions\n ) {\n const { serverId, ...mcpParams } = params;\n return this.authorization.recoverRequest(serverId, (conn) =>\n conn.client.getPrompt(mcpParams, options)\n );\n }\n\n /**\n * Dispose the manager and all resources.\n */\n async dispose(): Promise<void> {\n try {\n await this.closeAllConnections();\n } finally {\n this._onServerStateChanged.dispose();\n this._onObservabilityEvent.dispose();\n }\n }\n\n private connectionsFor(\n filter: MCPServerFilter | undefined\n ): Record<string, MCPClientConnection> {\n return filterConnections(\n this.mcpConnections,\n () => this.ctx.store.list(),\n filter\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAIA,SAAgB,aAAa,IAA4B;CACvD,OAAO,EAAE,SAAS,GAAG;AACvB;AAEA,IAAa,kBAAb,MAAmD;;EACjD,KAAiB,SAAuB,CAAC;;CAEzC,IAA0B,GAAS;EACjC,KAAK,OAAO,KAAK,CAAC;EAClB,OAAO;CACT;CAEA,UAAgB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