agents 0.2.2 → 0.2.3

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/client.ts","../src/core/events.ts","../src/mcp/client-connection.ts","../src/mcp/errors.ts","../src/mcp/sse-edge.ts","../src/mcp/streamable-http-edge.ts"],"sourcesContent":["import type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n CallToolRequest,\n CallToolResultSchema,\n CompatibilityCallToolResultSchema,\n GetPromptRequest,\n Prompt,\n ReadResourceRequest,\n Resource,\n ResourceTemplate,\n Tool\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { type ToolSet, jsonSchema } from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport { Emitter, type Event, DisposableStore } from \"../core/events\";\nimport type { MCPObservabilityEvent } from \"../observability/mcp\";\nimport {\n MCPClientConnection,\n type MCPTransportOptions\n} from \"./client-connection\";\nimport { toErrorMessage } from \"./errors\";\nimport type { TransportType } from \"./types\";\n\nexport type MCPClientOAuthCallbackConfig = {\n successRedirect?: string;\n errorRedirect?: string;\n customHandler?: (result: MCPClientOAuthResult) => Response;\n};\n\nexport type MCPClientOAuthResult = {\n serverId: string;\n authSuccess: boolean;\n authError?: string;\n};\n\n/**\n * Utility class that aggregates multiple MCP clients into one\n */\nexport class MCPClientManager {\n public mcpConnections: Record<string, MCPClientConnection> = {};\n private _callbackUrls: string[] = [];\n private _didWarnAboutUnstableGetAITools = false;\n private _oauthCallbackConfig?: MCPClientOAuthCallbackConfig;\n private _connectionDisposables = new Map<string, DisposableStore>();\n\n private readonly _onObservabilityEvent = new Emitter<MCPObservabilityEvent>();\n public readonly onObservabilityEvent: Event<MCPObservabilityEvent> =\n this._onObservabilityEvent.event;\n\n private readonly _onConnected = new Emitter<string>();\n public readonly onConnected: Event<string> = this._onConnected.event;\n\n /**\n * @param _name Name of the MCP client\n * @param _version Version of the MCP Client\n * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider\n */\n constructor(\n private _name: string,\n private _version: string\n ) {}\n\n /**\n * Connect to and register an MCP server\n *\n * @param transportConfig Transport config\n * @param clientConfig Client config\n * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)\n */\n async connect(\n url: string,\n options: {\n // Allows you to reconnect to a server (in the case of an auth reconnect)\n reconnect?: {\n // server id\n id: string;\n oauthClientId?: string;\n oauthCode?: string;\n };\n // we're overriding authProvider here because we want to be able to access the auth URL\n transport?: MCPTransportOptions;\n client?: ConstructorParameters<typeof Client>[1];\n } = {}\n ): Promise<{\n id: string;\n authUrl?: string;\n clientId?: string;\n }> {\n const id = options.reconnect?.id ?? nanoid(8);\n\n if (options.transport?.authProvider) {\n options.transport.authProvider.serverId = id;\n // reconnect with auth\n if (options.reconnect?.oauthClientId) {\n options.transport.authProvider.clientId =\n options.reconnect?.oauthClientId;\n }\n }\n\n // During OAuth reconnect, reuse existing connection to preserve state\n if (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {\n const normalizedTransport = {\n ...options.transport,\n type: options.transport?.type ?? (\"auto\" as TransportType)\n };\n\n this.mcpConnections[id] = new MCPClientConnection(\n new URL(url),\n {\n name: this._name,\n version: this._version\n },\n {\n client: options.client ?? {},\n transport: normalizedTransport\n }\n );\n\n // Pipe connection-level observability events to the manager-level emitter\n // and track the subscription for cleanup.\n const store = new DisposableStore();\n // If we somehow already had disposables for this id, clear them first\n const existing = this._connectionDisposables.get(id);\n if (existing) existing.dispose();\n this._connectionDisposables.set(id, store);\n store.add(\n this.mcpConnections[id].onObservabilityEvent((event) => {\n this._onObservabilityEvent.fire(event);\n })\n );\n }\n\n // Initialize connection first\n await this.mcpConnections[id].init();\n\n // Handle OAuth completion if we have a reconnect code\n if (options.reconnect?.oauthCode) {\n try {\n await this.mcpConnections[id].completeAuthorization(\n options.reconnect.oauthCode\n );\n await this.mcpConnections[id].establishConnection();\n } catch (error) {\n this._onObservabilityEvent.fire({\n type: \"mcp:client:connect\",\n displayMessage: `Failed to complete OAuth reconnection for ${id} for ${url}`,\n payload: {\n url: url,\n transport: options.transport?.type ?? \"auto\",\n state: this.mcpConnections[id].connectionState,\n error: toErrorMessage(error)\n },\n timestamp: Date.now(),\n id\n });\n // Re-throw to signal failure to the caller\n throw error;\n }\n }\n\n // If connection is in authenticating state, return auth URL for OAuth flow\n const authUrl = options.transport?.authProvider?.authUrl;\n if (\n this.mcpConnections[id].connectionState === \"authenticating\" &&\n authUrl &&\n options.transport?.authProvider?.redirectUrl\n ) {\n this._callbackUrls.push(\n options.transport.authProvider.redirectUrl.toString()\n );\n return {\n authUrl,\n clientId: options.transport?.authProvider?.clientId,\n id\n };\n }\n\n return {\n id\n };\n }\n\n isCallbackRequest(req: Request): boolean {\n return (\n req.method === \"GET\" &&\n !!this._callbackUrls.find((url) => {\n return req.url.startsWith(url);\n })\n );\n }\n\n async handleCallbackRequest(req: Request) {\n const url = new URL(req.url);\n const urlMatch = this._callbackUrls.find((url) => {\n return req.url.startsWith(url);\n });\n if (!urlMatch) {\n throw new Error(\n `No callback URI match found for the request url: ${req.url}. Was the request matched with \\`isCallbackRequest()\\`?`\n );\n }\n const code = url.searchParams.get(\"code\");\n const clientId = url.searchParams.get(\"state\");\n const urlParams = urlMatch.split(\"/\");\n const serverId = urlParams[urlParams.length - 1];\n if (!code) {\n throw new Error(\"Unauthorized: no code provided\");\n }\n if (!clientId) {\n throw new Error(\"Unauthorized: no state provided\");\n }\n\n if (this.mcpConnections[serverId] === undefined) {\n throw new Error(`Could not find serverId: ${serverId}`);\n }\n\n if (this.mcpConnections[serverId].connectionState !== \"authenticating\") {\n throw new Error(\n \"Failed to authenticate: the client isn't in the `authenticating` state\"\n );\n }\n\n const conn = this.mcpConnections[serverId];\n if (!conn.options.transport.authProvider) {\n throw new Error(\n \"Trying to finalize authentication for a server connection without an authProvider\"\n );\n }\n\n // Set the OAuth credentials\n conn.options.transport.authProvider.clientId = clientId;\n conn.options.transport.authProvider.serverId = serverId;\n\n try {\n await conn.completeAuthorization(code);\n return {\n serverId,\n authSuccess: true\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n\n return {\n serverId,\n authSuccess: false,\n authError: errorMessage\n };\n }\n }\n\n /**\n * Establish connection in the background after OAuth completion\n * This method is called asynchronously and doesn't block the OAuth callback response\n * @param serverId The server ID to establish connection for\n */\n async establishConnection(serverId: string): Promise<void> {\n const conn = this.mcpConnections[serverId];\n if (!conn) {\n this._onObservabilityEvent.fire({\n type: \"mcp:client:preconnect\",\n displayMessage: `Connection not found for serverId: ${serverId}`,\n payload: { serverId },\n timestamp: Date.now(),\n id: nanoid()\n });\n return;\n }\n\n try {\n await conn.establishConnection();\n this._onConnected.fire(serverId);\n } catch (error) {\n const url = conn.url.toString();\n this._onObservabilityEvent.fire({\n type: \"mcp:client:connect\",\n displayMessage: `Failed to establish connection to server ${serverId} with url ${url}`,\n payload: {\n url,\n transport: conn.options.transport.type ?? \"auto\",\n state: conn.connectionState,\n error: toErrorMessage(error)\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n }\n }\n\n /**\n * Register a callback URL for OAuth handling\n * @param url The callback URL to register\n */\n registerCallbackUrl(url: string): void {\n if (!this._callbackUrls.includes(url)) {\n this._callbackUrls.push(url);\n }\n }\n\n /**\n * Unregister a callback URL\n * @param serverId The server ID whose callback URL should be removed\n */\n unregisterCallbackUrl(serverId: string): void {\n // Remove callback URLs that end with this serverId\n this._callbackUrls = this._callbackUrls.filter(\n (url) => !url.endsWith(`/${serverId}`)\n );\n }\n\n /**\n * Configure OAuth callback handling\n * @param config OAuth callback configuration\n */\n configureOAuthCallback(config: MCPClientOAuthCallbackConfig): void {\n this._oauthCallbackConfig = 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._oauthCallbackConfig;\n }\n\n /**\n * @returns namespaced list of tools\n */\n listTools(): NamespacedData[\"tools\"] {\n return getNamespacedData(this.mcpConnections, \"tools\");\n }\n\n /**\n * @returns a set of tools that you can use with the AI SDK\n */\n getAITools(): ToolSet {\n return Object.fromEntries(\n getNamespacedData(this.mcpConnections, \"tools\").map((tool) => {\n return [\n `tool_${tool.serverId}_${tool.name}`,\n {\n description: tool.description,\n execute: async (args) => {\n const result = await this.callTool({\n arguments: args,\n name: tool.name,\n serverId: tool.serverId\n });\n if (result.isError) {\n // @ts-expect-error TODO we should fix this\n throw new Error(result.content[0].text);\n }\n return result;\n },\n // @ts-expect-error drift between ai and mcp types\n inputSchema: jsonSchema(tool.inputSchema),\n\n outputSchema: tool.outputSchema\n ? // @ts-expect-error drift between ai and mcp types\n jsonSchema(tool.outputSchema)\n : undefined\n }\n ];\n })\n );\n }\n\n /**\n * @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version\n * @returns a set of tools that you can use with the AI SDK\n */\n unstable_getAITools(): ToolSet {\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();\n }\n\n /**\n * Closes all connections to MCP servers\n */\n async closeAllConnections() {\n const ids = Object.keys(this.mcpConnections);\n await Promise.all(\n ids.map(async (id) => {\n await this.mcpConnections[id].client.close();\n })\n );\n // Dispose all per-connection subscriptions\n for (const id of ids) {\n const store = this._connectionDisposables.get(id);\n if (store) store.dispose();\n this._connectionDisposables.delete(id);\n delete this.mcpConnections[id];\n }\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) {\n if (!this.mcpConnections[id]) {\n throw new Error(`Connection with id \"${id}\" does not exist.`);\n }\n await this.mcpConnections[id].client.close();\n delete this.mcpConnections[id];\n\n const store = this._connectionDisposables.get(id);\n if (store) store.dispose();\n this._connectionDisposables.delete(id);\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 // Dispose manager-level emitters\n this._onConnected.dispose();\n this._onObservabilityEvent.dispose();\n }\n }\n\n /**\n * @returns namespaced list of prompts\n */\n listPrompts(): NamespacedData[\"prompts\"] {\n return getNamespacedData(this.mcpConnections, \"prompts\");\n }\n\n /**\n * @returns namespaced list of tools\n */\n listResources(): NamespacedData[\"resources\"] {\n return getNamespacedData(this.mcpConnections, \"resources\");\n }\n\n /**\n * @returns namespaced list of resource templates\n */\n listResourceTemplates(): NamespacedData[\"resourceTemplates\"] {\n return getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n }\n\n /**\n * Namespaced version of callTool\n */\n async callTool(\n params: CallToolRequest[\"params\"] & { serverId: string },\n resultSchema?:\n | typeof CallToolResultSchema\n | typeof CompatibilityCallToolResultSchema,\n options?: RequestOptions\n ) {\n const unqualifiedName = params.name.replace(`${params.serverId}.`, \"\");\n return this.mcpConnections[params.serverId].client.callTool(\n {\n ...params,\n name: unqualifiedName\n },\n resultSchema,\n options\n );\n }\n\n /**\n * Namespaced version of readResource\n */\n readResource(\n params: ReadResourceRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.readResource(\n params,\n options\n );\n }\n\n /**\n * Namespaced version of getPrompt\n */\n getPrompt(\n params: GetPromptRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.getPrompt(\n params,\n options\n );\n }\n}\n\ntype NamespacedData = {\n tools: (Tool & { serverId: string })[];\n prompts: (Prompt & { serverId: string })[];\n resources: (Resource & { serverId: string })[];\n resourceTemplates: (ResourceTemplate & { serverId: string })[];\n};\n\nexport function getNamespacedData<T extends keyof NamespacedData>(\n mcpClients: Record<string, MCPClientConnection>,\n type: T\n): NamespacedData[T] {\n const sets = Object.entries(mcpClients).map(([name, conn]) => {\n return { data: conn[type], name };\n });\n\n const namespacedData = sets.flatMap(({ name: serverId, data }) => {\n return data.map((item) => {\n return {\n ...item,\n // we add a serverId so we can easily pull it out and send the tool call to the right server\n serverId\n };\n });\n });\n\n return namespacedData as NamespacedData[T]; // Type assertion needed due to TS limitations with conditional return types\n}\n","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","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { StreamableHTTPClientTransportOptions } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n// Import types directly from MCP SDK\nimport type {\n Prompt,\n Resource,\n Tool\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n type ClientCapabilities,\n type ElicitRequest,\n ElicitRequestSchema,\n type ElicitResult,\n type ListPromptsResult,\n type ListResourceTemplatesResult,\n type ListResourcesResult,\n type ListToolsResult,\n PromptListChangedNotificationSchema,\n ResourceListChangedNotificationSchema,\n type ResourceTemplate,\n type ServerCapabilities,\n ToolListChangedNotificationSchema\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { nanoid } from \"nanoid\";\nimport { Emitter, type Event } from \"../core/events\";\nimport type { MCPObservabilityEvent } from \"../observability/mcp\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\nimport {\n isTransportNotImplemented,\n isUnauthorized,\n toErrorMessage\n} from \"./errors\";\nimport { SSEEdgeClientTransport } from \"./sse-edge\";\nimport { StreamableHTTPEdgeClientTransport } from \"./streamable-http-edge\";\nimport type { BaseTransportType, TransportType } from \"./types\";\n\n/**\n * Connection state for MCP client connections\n */\nexport type MCPConnectionState =\n | \"authenticating\"\n | \"connecting\"\n | \"ready\"\n | \"discovering\"\n | \"failed\";\n\nexport type MCPTransportOptions = (\n | SSEClientTransportOptions\n | StreamableHTTPClientTransportOptions\n) & {\n authProvider?: AgentsOAuthProvider;\n type?: TransportType;\n};\n\nexport class MCPClientConnection {\n client: Client;\n connectionState: MCPConnectionState = \"connecting\";\n lastConnectedTransport: BaseTransportType | undefined;\n instructions?: string;\n tools: Tool[] = [];\n prompts: Prompt[] = [];\n resources: Resource[] = [];\n resourceTemplates: ResourceTemplate[] = [];\n serverCapabilities: ServerCapabilities | undefined;\n\n private readonly _onObservabilityEvent = new Emitter<MCPObservabilityEvent>();\n public readonly onObservabilityEvent: Event<MCPObservabilityEvent> =\n this._onObservabilityEvent.event;\n\n constructor(\n public url: URL,\n info: ConstructorParameters<typeof Client>[0],\n public options: {\n transport: MCPTransportOptions;\n client: ConstructorParameters<typeof Client>[1];\n } = { client: {}, transport: {} }\n ) {\n const clientOptions = {\n ...options.client,\n capabilities: {\n ...options.client?.capabilities,\n elicitation: {}\n } as ClientCapabilities\n };\n\n this.client = new Client(info, clientOptions);\n }\n\n /**\n * Initialize a client connection\n *\n * @returns\n */\n async init() {\n const transportType = this.options.transport.type;\n if (!transportType) {\n throw new Error(\"Transport type must be specified\");\n }\n\n try {\n await this.tryConnect(transportType);\n } catch (e) {\n if (isUnauthorized(e)) {\n // unauthorized, we should wait for the user to authenticate\n this.connectionState = \"authenticating\";\n return;\n }\n // For explicit transport mismatches or other errors, mark as failed\n // and do not throw to avoid bubbling errors to the client runtime.\n this._onObservabilityEvent.fire({\n type: \"mcp:client:connect\",\n displayMessage: `Connection initialization failed for ${this.url.toString()}`,\n payload: {\n url: this.url.toString(),\n transport: transportType,\n state: this.connectionState,\n error: toErrorMessage(e)\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n this.connectionState = \"failed\";\n return;\n }\n\n await this.discoverAndRegister();\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(code: string): 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: BaseTransportType) => {\n const transport = this.getTransport(base);\n await transport.finishAuth(code);\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(code: string): Promise<void> {\n if (this.connectionState !== \"authenticating\") {\n throw new Error(\n \"Connection must be in authenticating state to complete authorization\"\n );\n }\n\n try {\n // Finish OAuth by probing transports per configuration\n await this.finishAuthProbe(code);\n\n // Mark as connecting\n this.connectionState = \"connecting\";\n } catch (error) {\n this.connectionState = \"failed\";\n throw error;\n }\n }\n\n /**\n * Establish connection after successful authorization\n */\n async establishConnection(): Promise<void> {\n if (this.connectionState !== \"connecting\") {\n throw new Error(\n \"Connection must be in connecting state to establish connection\"\n );\n }\n\n try {\n const transportType = this.options.transport.type;\n if (!transportType) {\n throw new Error(\"Transport type must be specified\");\n }\n await this.tryConnect(transportType);\n\n await this.discoverAndRegister();\n } catch (error) {\n this.connectionState = \"failed\";\n throw error;\n }\n }\n\n /**\n * Discover server capabilities and register tools, resources, prompts, and templates\n */\n private async discoverAndRegister(): Promise<void> {\n this.connectionState = \"discovering\";\n\n this.serverCapabilities = this.client.getServerCapabilities();\n if (!this.serverCapabilities) {\n throw new Error(\"The MCP Server failed to return server capabilities\");\n }\n\n const [\n instructionsResult,\n toolsResult,\n resourcesResult,\n promptsResult,\n resourceTemplatesResult\n ] = await Promise.allSettled([\n this.client.getInstructions(),\n this.registerTools(),\n this.registerResources(),\n this.registerPrompts(),\n this.registerResourceTemplates()\n ]);\n\n const operations = [\n { name: \"instructions\", result: instructionsResult },\n { name: \"tools\", result: toolsResult },\n { name: \"resources\", result: resourcesResult },\n { name: \"prompts\", result: promptsResult },\n { name: \"resource templates\", result: resourceTemplatesResult }\n ];\n\n for (const { name, result } of operations) {\n if (result.status === \"rejected\") {\n const url = this.url.toString();\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n displayMessage: `Failed to discover ${name} for ${url}`,\n payload: {\n url,\n capability: name,\n error: result.reason\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n }\n }\n\n this.instructions =\n instructionsResult.status === \"fulfilled\"\n ? instructionsResult.value\n : undefined;\n this.tools = toolsResult.status === \"fulfilled\" ? toolsResult.value : [];\n this.resources =\n resourcesResult.status === \"fulfilled\" ? resourcesResult.value : [];\n this.prompts =\n promptsResult.status === \"fulfilled\" ? promptsResult.value : [];\n this.resourceTemplates =\n resourceTemplatesResult.status === \"fulfilled\"\n ? resourceTemplatesResult.value\n : [];\n\n this.connectionState = \"ready\";\n }\n\n /**\n * Notification handler registration\n */\n async registerTools(): Promise<Tool[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.tools) {\n return [];\n }\n\n if (this.serverCapabilities.tools.listChanged) {\n this.client.setNotificationHandler(\n ToolListChangedNotificationSchema,\n async (_notification) => {\n this.tools = await this.fetchTools();\n }\n );\n }\n\n return this.fetchTools();\n }\n\n async registerResources(): Promise<Resource[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n if (this.serverCapabilities.resources.listChanged) {\n this.client.setNotificationHandler(\n ResourceListChangedNotificationSchema,\n async (_notification) => {\n this.resources = await this.fetchResources();\n }\n );\n }\n\n return this.fetchResources();\n }\n\n async registerPrompts(): Promise<Prompt[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.prompts) {\n return [];\n }\n\n if (this.serverCapabilities.prompts.listChanged) {\n this.client.setNotificationHandler(\n PromptListChangedNotificationSchema,\n async (_notification) => {\n this.prompts = await this.fetchPrompts();\n }\n );\n }\n\n return this.fetchPrompts();\n }\n\n async registerResourceTemplates(): Promise<ResourceTemplate[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n return this.fetchResourceTemplates();\n }\n\n async fetchTools() {\n let toolsAgg: Tool[] = [];\n let toolsResult: ListToolsResult = { tools: [] };\n do {\n toolsResult = await this.client\n .listTools({\n cursor: toolsResult.nextCursor\n })\n .catch(this._capabilityErrorHandler({ tools: [] }, \"tools/list\"));\n toolsAgg = toolsAgg.concat(toolsResult.tools);\n } while (toolsResult.nextCursor);\n return toolsAgg;\n }\n\n async fetchResources() {\n let resourcesAgg: Resource[] = [];\n let resourcesResult: ListResourcesResult = { resources: [] };\n do {\n resourcesResult = await this.client\n .listResources({\n cursor: resourcesResult.nextCursor\n })\n .catch(\n this._capabilityErrorHandler({ resources: [] }, \"resources/list\")\n );\n resourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n } while (resourcesResult.nextCursor);\n return resourcesAgg;\n }\n\n async fetchPrompts() {\n let promptsAgg: Prompt[] = [];\n let promptsResult: ListPromptsResult = { prompts: [] };\n do {\n promptsResult = await this.client\n .listPrompts({\n cursor: promptsResult.nextCursor\n })\n .catch(this._capabilityErrorHandler({ prompts: [] }, \"prompts/list\"));\n promptsAgg = promptsAgg.concat(promptsResult.prompts);\n } while (promptsResult.nextCursor);\n return promptsAgg;\n }\n\n async fetchResourceTemplates() {\n let templatesAgg: ResourceTemplate[] = [];\n let templatesResult: ListResourceTemplatesResult = {\n resourceTemplates: []\n };\n do {\n templatesResult = await this.client\n .listResourceTemplates({\n cursor: templatesResult.nextCursor\n })\n .catch(\n this._capabilityErrorHandler(\n { resourceTemplates: [] },\n \"resources/templates/list\"\n )\n );\n templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n } while (templatesResult.nextCursor);\n return templatesAgg;\n }\n\n /**\n * Handle elicitation request from server\n * Automatically uses the Agent's built-in elicitation handling if available\n */\n async handleElicitationRequest(\n _request: ElicitRequest\n ): Promise<ElicitResult> {\n // Elicitation handling must be implemented by the platform\n // For MCP servers, this should be handled by McpAgent.elicitInput()\n throw new Error(\n \"Elicitation handler must be implemented for your platform. Override handleElicitationRequest method.\"\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 new StreamableHTTPEdgeClientTransport(\n this.url,\n this.options.transport as StreamableHTTPClientTransportOptions\n );\n case \"sse\":\n return new SSEEdgeClientTransport(\n this.url,\n this.options.transport as SSEClientTransportOptions\n );\n default:\n throw new Error(`Unsupported transport type: ${transportType}`);\n }\n }\n\n private async tryConnect(transportType: TransportType) {\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 await this.client.connect(transport);\n this.lastConnectedTransport = currentTransportType;\n const url = this.url.toString();\n this._onObservabilityEvent.fire({\n type: \"mcp:client:connect\",\n displayMessage: `Connected successfully using ${currentTransportType} transport for ${url}`,\n payload: {\n url,\n transport: currentTransportType,\n state: this.connectionState\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n break;\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e));\n\n // If unauthorized, bubble up for proper auth handling\n if (isUnauthorized(error)) {\n throw e;\n }\n\n if (hasFallback && isTransportNotImplemented(error)) {\n // Try the next transport silently\n const url = this.url.toString();\n this._onObservabilityEvent.fire({\n type: \"mcp:client:connect\",\n displayMessage: `${currentTransportType} transport not available, trying ${transports[transports.indexOf(currentTransportType) + 1]} for ${url}`,\n payload: {\n url,\n transport: currentTransportType,\n state: this.connectionState\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n continue;\n }\n\n throw e;\n }\n }\n\n // Set up elicitation request handler\n this.client.setRequestHandler(\n ElicitRequestSchema,\n async (request: ElicitRequest) => {\n return await this.handleElicitationRequest(request);\n }\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 displayMessage: `The server advertised support for the capability ${method.split(\"/\")[0]}, but returned \"Method not found\" for '${method}' for ${url}`,\n payload: {\n url,\n capability: method.split(\"/\")[0],\n error: toErrorMessage(e)\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n return empty;\n }\n throw e;\n };\n }\n}\n","export function toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function isUnauthorized(error: unknown): boolean {\n const msg = toErrorMessage(error);\n return msg.includes(\"Unauthorized\") || msg.includes(\"401\");\n}\n\nexport function isTransportNotImplemented(error: unknown): boolean {\n const msg = toErrorMessage(error);\n // Treat common \"not implemented\" surfaces as transport not supported\n return (\n msg.includes(\"404\") ||\n msg.includes(\"405\") ||\n msg.includes(\"Not Implemented\") ||\n msg.includes(\"not implemented\")\n );\n}\n","import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport {\n SSEClientTransport,\n type SSEClientTransportOptions\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nexport class SSEEdgeClientTransport extends SSEClientTransport {\n private authProvider: OAuthClientProvider | undefined;\n /**\n * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment\n */\n constructor(url: URL, options: SSEClientTransportOptions) {\n const fetchOverride: typeof fetch = async (\n fetchUrl: RequestInfo | URL,\n fetchInit: RequestInit = {}\n ) => {\n // add auth headers\n const headers = await this.authHeaders();\n const workerOptions = {\n ...fetchInit,\n headers: {\n ...options.requestInit?.headers,\n ...fetchInit?.headers,\n ...headers\n }\n };\n\n // Remove unsupported properties\n delete workerOptions.mode;\n\n // Call the original fetch with fixed options\n return (\n (options.eventSourceInit?.fetch?.(\n fetchUrl as URL | string,\n // @ts-expect-error Expects FetchLikeInit from EventSource but is compatible with RequestInit\n workerOptions\n ) as Promise<Response>) || fetch(fetchUrl, workerOptions)\n );\n };\n\n super(url, {\n ...options,\n eventSourceInit: {\n ...options.eventSourceInit,\n fetch: fetchOverride\n }\n });\n this.authProvider = options.authProvider;\n }\n\n async authHeaders() {\n if (this.authProvider) {\n const tokens = await this.authProvider.tokens();\n if (tokens) {\n return {\n Authorization: `Bearer ${tokens.access_token}`\n };\n }\n }\n }\n}\n","import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport {\n StreamableHTTPClientTransport,\n type StreamableHTTPClientTransportOptions\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\nexport class StreamableHTTPEdgeClientTransport extends StreamableHTTPClientTransport {\n private authProvider: OAuthClientProvider | undefined;\n\n /**\n * Creates a new StreamableHTTPEdgeClientTransport, which overrides fetch to be compatible with the CF workers environment\n */\n constructor(url: URL, options: StreamableHTTPClientTransportOptions) {\n const fetchOverride: typeof fetch = async (\n fetchUrl: RequestInfo | URL,\n fetchInit: RequestInit = {}\n ) => {\n // add auth headers\n const headers = await this.authHeaders();\n const workerOptions = {\n ...fetchInit,\n headers: {\n ...options.requestInit?.headers,\n ...fetchInit?.headers,\n ...headers\n }\n };\n\n // Remove unsupported properties\n delete workerOptions.mode;\n\n // Call the original fetch with fixed options\n return (\n // @ts-expect-error Custom fetch function for Cloudflare Workers compatibility\n (options.requestInit?.fetch?.(\n fetchUrl as URL | string,\n workerOptions\n ) as Promise<Response>) || fetch(fetchUrl, workerOptions)\n );\n };\n\n super(url, {\n ...options,\n requestInit: {\n ...options.requestInit,\n // @ts-expect-error Custom fetch override for Cloudflare Workers\n fetch: fetchOverride\n }\n });\n this.authProvider = options.authProvider;\n }\n\n async authHeaders() {\n if (this.authProvider) {\n const tokens = await this.authProvider.tokens();\n if (tokens) {\n return {\n Authorization: `Bearer ${tokens.access_token}`\n };\n }\n }\n }\n}\n"],"mappings":";AAaA,SAAuB,kBAAkB;AACzC,SAAS,UAAAA,eAAc;;;ACVhB,SAAS,aAAa,IAA4B;AACvD,SAAO,EAAE,SAAS,GAAG;AACvB;AAEO,IAAM,kBAAN,MAA4C;AAAA,EAA5C;AACL,SAAiB,SAAuB,CAAC;AAAA;AAAA,EAEzC,IAA0B,GAAS;AACjC,SAAK,OAAO,KAAK,CAAC;AAClB,WAAO;AAAA,EACT;AAAA,EAEA,UAAgB;AACd,WAAO,KAAK,OAAO,QAAQ;AACzB,UAAI;AACF,aAAK,OAAO,IAAI,EAAG,QAAQ;AAAA,MAC7B,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACF;AAIO,IAAM,UAAN,MAAuC;AAAA,EAAvC;AACL,SAAQ,aAAkC,oBAAI,IAAI;AAElD,SAAS,QAAkB,CAAC,aAAa;AACvC,WAAK,WAAW,IAAI,QAAQ;AAC5B,aAAO,aAAa,MAAM,KAAK,WAAW,OAAO,QAAQ,CAAC;AAAA,IAC5D;AAAA;AAAA,EAEA,KAAK,MAAe;AAClB,eAAW,YAAY,CAAC,GAAG,KAAK,UAAU,GAAG;AAC3C,UAAI;AACF,iBAAS,IAAI;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ACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,UACE,QACA,SACA;AACA,WAAO,KAAK,eAAe,OAAO,QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AASO,SAAS,kBACd,YACA,MACmB;AACnB,QAAM,OAAO,OAAO,QAAQ,UAAU,EAAE,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM;AAC5D,WAAO,EAAE,MAAM,KAAK,IAAI,GAAG,KAAK;AAAA,EAClC,CAAC;AAED,QAAM,iBAAiB,KAAK,QAAQ,CAAC,EAAE,MAAM,UAAU,KAAK,MAAM;AAChE,WAAO,KAAK,IAAI,CAAC,SAAS;AACxB,aAAO;AAAA,QACL,GAAG;AAAA;AAAA,QAEH;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AACT;","names":["nanoid","nanoid","url"]}
@@ -106,22 +106,9 @@ var DurableObjectOAuthClientProvider = class {
106
106
  }
107
107
  return codeVerifier;
108
108
  }
109
- /** Transport tracking for OAuth flow */
110
- oauthTransportKey() {
111
- return `/${this.clientName}/${this.serverId}/oauth_transport`;
112
- }
113
- async saveOAuthTransport(transportType) {
114
- await this.storage.put(this.oauthTransportKey(), transportType);
115
- }
116
- async getOAuthTransport() {
117
- return await this.storage.get(this.oauthTransportKey());
118
- }
119
- async clearOAuthTransport() {
120
- await this.storage.delete(this.oauthTransportKey());
121
- }
122
109
  };
123
110
 
124
111
  export {
125
112
  DurableObjectOAuthClientProvider
126
113
  };
127
- //# sourceMappingURL=chunk-XFS5ERG3.js.map
114
+ //# sourceMappingURL=chunk-Z44WASMA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/do-oauth-client-provider.ts"],"sourcesContent":["import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport type {\n OAuthClientInformation,\n OAuthClientInformationFull,\n OAuthClientMetadata,\n OAuthTokens\n} from \"@modelcontextprotocol/sdk/shared/auth.js\";\n\n// A slight extension to the standard OAuthClientProvider interface because `redirectToAuthorization` doesn't give us the interface we need\n// This allows us to track authentication for a specific server and associated dynamic client registration\nexport interface AgentsOAuthProvider extends OAuthClientProvider {\n authUrl: string | undefined;\n clientId: string | undefined;\n serverId: string | undefined;\n}\n\nexport class DurableObjectOAuthClientProvider implements AgentsOAuthProvider {\n private _authUrl_: string | undefined;\n private _serverId_: string | undefined;\n private _clientId_: string | undefined;\n\n constructor(\n public storage: DurableObjectStorage,\n public clientName: string,\n public baseRedirectUrl: string\n ) {}\n\n get clientMetadata(): OAuthClientMetadata {\n return {\n client_name: this.clientName,\n client_uri: this.clientUri,\n grant_types: [\"authorization_code\", \"refresh_token\"],\n redirect_uris: [this.redirectUrl],\n response_types: [\"code\"],\n token_endpoint_auth_method: \"none\"\n };\n }\n\n get clientUri() {\n return new URL(this.redirectUrl).origin;\n }\n\n get redirectUrl() {\n return `${this.baseRedirectUrl}/${this.serverId}`;\n }\n\n get clientId() {\n if (!this._clientId_) {\n throw new Error(\"Trying to access clientId before it was set\");\n }\n return this._clientId_;\n }\n\n set clientId(clientId_: string) {\n this._clientId_ = clientId_;\n }\n\n get serverId() {\n if (!this._serverId_) {\n throw new Error(\"Trying to access serverId before it was set\");\n }\n return this._serverId_;\n }\n\n set serverId(serverId_: string) {\n this._serverId_ = serverId_;\n }\n\n keyPrefix(clientId: string) {\n return `/${this.clientName}/${this.serverId}/${clientId}`;\n }\n\n clientInfoKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/client_info/`;\n }\n\n async clientInformation(): Promise<OAuthClientInformation | undefined> {\n if (!this._clientId_) {\n return undefined;\n }\n return (\n (await this.storage.get<OAuthClientInformation>(\n this.clientInfoKey(this.clientId)\n )) ?? undefined\n );\n }\n\n async saveClientInformation(\n clientInformation: OAuthClientInformationFull\n ): Promise<void> {\n await this.storage.put(\n this.clientInfoKey(clientInformation.client_id),\n clientInformation\n );\n this.clientId = clientInformation.client_id;\n }\n\n tokenKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/token`;\n }\n\n async tokens(): Promise<OAuthTokens | undefined> {\n if (!this._clientId_) {\n return undefined;\n }\n return (\n (await this.storage.get<OAuthTokens>(this.tokenKey(this.clientId))) ??\n undefined\n );\n }\n\n async saveTokens(tokens: OAuthTokens): Promise<void> {\n await this.storage.put(this.tokenKey(this.clientId), tokens);\n }\n\n get authUrl() {\n return this._authUrl_;\n }\n\n /**\n * Because this operates on the server side (but we need browser auth), we send this url back to the user\n * and require user interact to initiate the redirect flow\n */\n async redirectToAuthorization(authUrl: URL): Promise<void> {\n // We want to track the client ID in state here because the typescript SSE client sometimes does\n // a dynamic client registration AFTER generating this redirect URL.\n const client_id = authUrl.searchParams.get(\"client_id\");\n if (client_id) {\n authUrl.searchParams.append(\"state\", client_id);\n }\n this._authUrl_ = authUrl.toString();\n }\n\n codeVerifierKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/code_verifier`;\n }\n\n async saveCodeVerifier(verifier: string): Promise<void> {\n const key = this.codeVerifierKey(this.clientId);\n\n // Don't overwrite existing verifier to preserve first PKCE verifier\n const existing = await this.storage.get<string>(key);\n if (existing) {\n return;\n }\n\n await this.storage.put(key, verifier);\n }\n\n async codeVerifier(): Promise<string> {\n const codeVerifier = await this.storage.get<string>(\n this.codeVerifierKey(this.clientId)\n );\n if (!codeVerifier) {\n throw new Error(\"No code verifier found\");\n }\n return codeVerifier;\n }\n}\n"],"mappings":";AAgBO,IAAM,mCAAN,MAAsE;AAAA,EAK3E,YACS,SACA,YACA,iBACP;AAHO;AACA;AACA;AAAA,EACN;AAAA,EAEH,IAAI,iBAAsC;AACxC,WAAO;AAAA,MACL,aAAa,KAAK;AAAA,MAClB,YAAY,KAAK;AAAA,MACjB,aAAa,CAAC,sBAAsB,eAAe;AAAA,MACnD,eAAe,CAAC,KAAK,WAAW;AAAA,MAChC,gBAAgB,CAAC,MAAM;AAAA,MACvB,4BAA4B;AAAA,IAC9B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ACG,MAAM,KAAK,QAAQ,IAAiB,KAAK,SAAS,KAAK,QAAQ,CAAC,KACjE;AAAA,EAEJ;AAAA,EAEA,MAAM,WAAW,QAAoC;AACnD,UAAM,KAAK,QAAQ,IAAI,KAAK,SAAS,KAAK,QAAQ,GAAG,MAAM;AAAA,EAC7D;AAAA,EAEA,IAAI,UAAU;AACZ,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,wBAAwB,SAA6B;AAGzD,UAAM,YAAY,QAAQ,aAAa,IAAI,WAAW;AACtD,QAAI,WAAW;AACb,cAAQ,aAAa,OAAO,SAAS,SAAS;AAAA,IAChD;AACA,SAAK,YAAY,QAAQ,SAAS;AAAA,EACpC;AAAA,EAEA,gBAAgB,UAAkB;AAChC,WAAO,GAAG,KAAK,UAAU,QAAQ,CAAC;AAAA,EACpC;AAAA,EAEA,MAAM,iBAAiB,UAAiC;AACtD,UAAM,MAAM,KAAK,gBAAgB,KAAK,QAAQ;AAG9C,UAAM,WAAW,MAAM,KAAK,QAAQ,IAAY,GAAG;AACnD,QAAI,UAAU;AACZ;AAAA,IACF;AAEA,UAAM,KAAK,QAAQ,IAAI,KAAK,QAAQ;AAAA,EACtC;AAAA,EAEA,MAAM,eAAgC;AACpC,UAAM,eAAe,MAAM,KAAK,QAAQ;AAAA,MACtC,KAAK,gBAAgB,KAAK,QAAQ;AAAA,IACpC;AACA,QAAI,CAAC,cAAc;AACjB,YAAM,IAAI,MAAM,wBAAwB;AAAA,IAC1C;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -16,6 +16,7 @@ import {
16
16
  GetPromptRequest
17
17
  } from "@modelcontextprotocol/sdk/types.js";
18
18
  import { ToolSet } from "ai";
19
+ import { M as MCPObservabilityEvent } from "./mcp-BH1fJeiU.js";
19
20
  import {
20
21
  SSEClientTransport,
21
22
  SSEClientTransportOptions
@@ -26,6 +27,11 @@ import {
26
27
  } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
27
28
  import { AgentsOAuthProvider } from "./mcp/do-oauth-client-provider.js";
28
29
 
30
+ interface Disposable {
31
+ dispose(): void;
32
+ }
33
+ type Event<T> = (listener: (e: T) => void) => Disposable;
34
+
29
35
  declare class SSEEdgeClientTransport extends SSEClientTransport {
30
36
  private authProvider;
31
37
  /**
@@ -40,6 +46,20 @@ declare class SSEEdgeClientTransport extends SSEClientTransport {
40
46
  >;
41
47
  }
42
48
 
49
+ declare class StreamableHTTPEdgeClientTransport extends StreamableHTTPClientTransport {
50
+ private authProvider;
51
+ /**
52
+ * Creates a new StreamableHTTPEdgeClientTransport, which overrides fetch to be compatible with the CF workers environment
53
+ */
54
+ constructor(url: URL, options: StreamableHTTPClientTransportOptions);
55
+ authHeaders(): Promise<
56
+ | {
57
+ Authorization: string;
58
+ }
59
+ | undefined
60
+ >;
61
+ }
62
+
43
63
  type MaybePromise<T> = T | Promise<T>;
44
64
  type BaseTransportType = "sse" | "streamable-http";
45
65
  type TransportType = BaseTransportType | "auto";
@@ -56,20 +76,15 @@ interface ServeOptions {
56
76
  transport?: BaseTransportType;
57
77
  }
58
78
 
59
- declare class StreamableHTTPEdgeClientTransport extends StreamableHTTPClientTransport {
60
- private authProvider;
61
- /**
62
- * Creates a new StreamableHTTPEdgeClientTransport, which overrides fetch to be compatible with the CF workers environment
63
- */
64
- constructor(url: URL, options: StreamableHTTPClientTransportOptions);
65
- authHeaders(): Promise<
66
- | {
67
- Authorization: string;
68
- }
69
- | undefined
70
- >;
71
- }
72
-
79
+ /**
80
+ * Connection state for MCP client connections
81
+ */
82
+ type MCPConnectionState =
83
+ | "authenticating"
84
+ | "connecting"
85
+ | "ready"
86
+ | "discovering"
87
+ | "failed";
73
88
  type MCPTransportOptions = (
74
89
  | SSEClientTransportOptions
75
90
  | StreamableHTTPClientTransportOptions
@@ -84,18 +99,16 @@ declare class MCPClientConnection {
84
99
  client: ConstructorParameters<typeof Client>[1];
85
100
  };
86
101
  client: Client;
87
- connectionState:
88
- | "authenticating"
89
- | "connecting"
90
- | "ready"
91
- | "discovering"
92
- | "failed";
102
+ connectionState: MCPConnectionState;
103
+ lastConnectedTransport: BaseTransportType | undefined;
93
104
  instructions?: string;
94
105
  tools: Tool[];
95
106
  prompts: Prompt[];
96
107
  resources: Resource[];
97
108
  resourceTemplates: ResourceTemplate[];
98
109
  serverCapabilities: ServerCapabilities | undefined;
110
+ private readonly _onObservabilityEvent;
111
+ readonly onObservabilityEvent: Event<MCPObservabilityEvent>;
99
112
  constructor(
100
113
  url: URL,
101
114
  info: ConstructorParameters<typeof Client>[0],
@@ -107,10 +120,27 @@ declare class MCPClientConnection {
107
120
  /**
108
121
  * Initialize a client connection
109
122
  *
110
- * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized
111
123
  * @returns
112
124
  */
113
- init(code?: string): Promise<void>;
125
+ init(): Promise<void>;
126
+ /**
127
+ * Finish OAuth by probing transports based on configured type.
128
+ * - Explicit: finish on that transport
129
+ * - Auto: try streamable-http, then sse on 404/405/Not Implemented
130
+ */
131
+ private finishAuthProbe;
132
+ /**
133
+ * Complete OAuth authorization
134
+ */
135
+ completeAuthorization(code: string): Promise<void>;
136
+ /**
137
+ * Establish connection after successful authorization
138
+ */
139
+ establishConnection(): Promise<void>;
140
+ /**
141
+ * Discover server capabilities and register tools, resources, prompts, and templates
142
+ */
143
+ private discoverAndRegister;
114
144
  /**
115
145
  * Notification handler registration
116
146
  */
@@ -145,12 +175,12 @@ declare class MCPClientConnection {
145
175
  }
146
176
  | undefined;
147
177
  description?: string | undefined;
178
+ title?: string | undefined;
148
179
  _meta?:
149
180
  | {
150
181
  [x: string]: unknown;
151
182
  }
152
183
  | undefined;
153
- title?: string | undefined;
154
184
  annotations?:
155
185
  | {
156
186
  [x: string]: unknown;
@@ -177,12 +207,12 @@ declare class MCPClientConnection {
177
207
  name: string;
178
208
  uri: string;
179
209
  description?: string | undefined;
210
+ title?: string | undefined;
180
211
  _meta?:
181
212
  | {
182
213
  [x: string]: unknown;
183
214
  }
184
215
  | undefined;
185
- title?: string | undefined;
186
216
  icons?:
187
217
  | {
188
218
  [x: string]: unknown;
@@ -199,12 +229,12 @@ declare class MCPClientConnection {
199
229
  [x: string]: unknown;
200
230
  name: string;
201
231
  description?: string | undefined;
232
+ title?: string | undefined;
202
233
  _meta?:
203
234
  | {
204
235
  [x: string]: unknown;
205
236
  }
206
237
  | undefined;
207
- title?: string | undefined;
208
238
  icons?:
209
239
  | {
210
240
  [x: string]: unknown;
@@ -229,12 +259,12 @@ declare class MCPClientConnection {
229
259
  name: string;
230
260
  uriTemplate: string;
231
261
  description?: string | undefined;
262
+ title?: string | undefined;
232
263
  _meta?:
233
264
  | {
234
265
  [x: string]: unknown;
235
266
  }
236
267
  | undefined;
237
- title?: string | undefined;
238
268
  mimeType?: string | undefined;
239
269
  }[]
240
270
  >;
@@ -252,8 +282,19 @@ declare class MCPClientConnection {
252
282
  transportType: BaseTransportType
253
283
  ): SSEEdgeClientTransport | StreamableHTTPEdgeClientTransport;
254
284
  private tryConnect;
285
+ private _capabilityErrorHandler;
255
286
  }
256
287
 
288
+ type MCPClientOAuthCallbackConfig = {
289
+ successRedirect?: string;
290
+ errorRedirect?: string;
291
+ customHandler?: (result: MCPClientOAuthResult) => Response;
292
+ };
293
+ type MCPClientOAuthResult = {
294
+ serverId: string;
295
+ authSuccess: boolean;
296
+ authError?: string;
297
+ };
257
298
  /**
258
299
  * Utility class that aggregates multiple MCP clients into one
259
300
  */
@@ -263,6 +304,12 @@ declare class MCPClientManager {
263
304
  mcpConnections: Record<string, MCPClientConnection>;
264
305
  private _callbackUrls;
265
306
  private _didWarnAboutUnstableGetAITools;
307
+ private _oauthCallbackConfig?;
308
+ private _connectionDisposables;
309
+ private readonly _onObservabilityEvent;
310
+ readonly onObservabilityEvent: Event<MCPObservabilityEvent>;
311
+ private readonly _onConnected;
312
+ readonly onConnected: Event<string>;
266
313
  /**
267
314
  * @param _name Name of the MCP client
268
315
  * @param _version Version of the MCP Client
@@ -293,9 +340,24 @@ declare class MCPClientManager {
293
340
  clientId?: string;
294
341
  }>;
295
342
  isCallbackRequest(req: Request): boolean;
296
- handleCallbackRequest(req: Request): Promise<{
297
- serverId: string;
298
- }>;
343
+ handleCallbackRequest(req: Request): Promise<
344
+ | {
345
+ serverId: string;
346
+ authSuccess: boolean;
347
+ authError?: undefined;
348
+ }
349
+ | {
350
+ serverId: string;
351
+ authSuccess: boolean;
352
+ authError: string;
353
+ }
354
+ >;
355
+ /**
356
+ * Establish connection in the background after OAuth completion
357
+ * This method is called asynchronously and doesn't block the OAuth callback response
358
+ * @param serverId The server ID to establish connection for
359
+ */
360
+ establishConnection(serverId: string): Promise<void>;
299
361
  /**
300
362
  * Register a callback URL for OAuth handling
301
363
  * @param url The callback URL to register
@@ -306,6 +368,16 @@ declare class MCPClientManager {
306
368
  * @param serverId The server ID whose callback URL should be removed
307
369
  */
308
370
  unregisterCallbackUrl(serverId: string): void;
371
+ /**
372
+ * Configure OAuth callback handling
373
+ * @param config OAuth callback configuration
374
+ */
375
+ configureOAuthCallback(config: MCPClientOAuthCallbackConfig): void;
376
+ /**
377
+ * Get the current OAuth callback configuration
378
+ * @returns The current OAuth callback configuration
379
+ */
380
+ getOAuthCallbackConfig(): MCPClientOAuthCallbackConfig | undefined;
309
381
  /**
310
382
  * @returns namespaced list of tools
311
383
  */
@@ -322,12 +394,16 @@ declare class MCPClientManager {
322
394
  /**
323
395
  * Closes all connections to MCP servers
324
396
  */
325
- closeAllConnections(): Promise<void[]>;
397
+ closeAllConnections(): Promise<void>;
326
398
  /**
327
399
  * Closes a connection to an MCP server
328
400
  * @param id The id of the connection to close
329
401
  */
330
402
  closeConnection(id: string): Promise<void>;
403
+ /**
404
+ * Dispose the manager and all resources.
405
+ */
406
+ dispose(): Promise<void>;
331
407
  /**
332
408
  * @returns namespaced list of prompts
333
409
  */
@@ -5036,6 +5112,9 @@ export {
5036
5112
  type TransportType as T,
5037
5113
  SSEEdgeClientTransport as a,
5038
5114
  StreamableHTTPEdgeClientTransport as b,
5039
- MCPClientManager as c,
5115
+ type MCPClientOAuthResult as c,
5116
+ type MCPClientOAuthCallbackConfig as d,
5117
+ MCPClientManager as e,
5118
+ type MCPConnectionState as f,
5040
5119
  getNamespacedData as g
5041
5120
  };
@@ -0,0 +1,25 @@
1
+ import { ToolSet } from 'ai';
2
+ import { WorkerEntrypoint } from 'cloudflare:workers';
3
+
4
+ declare class CodeModeProxy extends WorkerEntrypoint<Cloudflare.Env, {
5
+ binding: string;
6
+ name: string;
7
+ callback: string;
8
+ }> {
9
+ callFunction(options: {
10
+ functionName: string;
11
+ args: unknown[];
12
+ }): Promise<any>;
13
+ }
14
+ declare function experimental_codemode(options: {
15
+ tools: ToolSet;
16
+ prompt: string;
17
+ globalOutbound: Fetcher;
18
+ loader: WorkerLoader;
19
+ proxy: Fetcher<CodeModeProxy>;
20
+ }): Promise<{
21
+ prompt: string;
22
+ tools: ToolSet;
23
+ }>;
24
+
25
+ export { CodeModeProxy, experimental_codemode };