agents 0.0.0-d6a4eda → 0.0.0-d6d6d60

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.
Files changed (77) hide show
  1. package/README.md +255 -27
  2. package/dist/ai-chat-agent.d.ts +20 -17
  3. package/dist/ai-chat-agent.js +532 -222
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-DBHGW4Hv.js +155 -0
  6. package/dist/ai-chat-v5-migration-DBHGW4Hv.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +73 -84
  10. package/dist/ai-react.js +266 -199
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-B3aQaFv3.js +20 -0
  13. package/dist/ai-types-B3aQaFv3.js.map +1 -0
  14. package/dist/ai-types-D5YoPrBZ.d.ts +95 -0
  15. package/dist/ai-types.d.ts +6 -74
  16. package/dist/ai-types.js +3 -1
  17. package/dist/cli.d.ts +8 -0
  18. package/dist/cli.js +27 -0
  19. package/dist/cli.js.map +1 -0
  20. package/dist/client-BfiZ3HQd.js +117 -0
  21. package/dist/client-BfiZ3HQd.js.map +1 -0
  22. package/dist/client-Bws9q38u.d.ts +5427 -0
  23. package/dist/client-CbWe9FBd.d.ts +104 -0
  24. package/dist/client-DvK0u9vD.js +898 -0
  25. package/dist/client-DvK0u9vD.js.map +1 -0
  26. package/dist/client.d.ts +12 -87
  27. package/dist/client.js +4 -11
  28. package/dist/codemode/ai.d.ts +27 -0
  29. package/dist/codemode/ai.js +151 -0
  30. package/dist/codemode/ai.js.map +1 -0
  31. package/dist/do-oauth-client-provider-CcTno-25.d.ts +142 -0
  32. package/dist/do-oauth-client-provider-D2P1lSft.js +93 -0
  33. package/dist/do-oauth-client-provider-D2P1lSft.js.map +1 -0
  34. package/dist/index-Bdzb2feZ.d.ts +572 -0
  35. package/dist/index-DhJCaDWd.d.ts +58 -0
  36. package/dist/index.d.ts +62 -392
  37. package/dist/index.js +7 -22
  38. package/dist/mcp/client.d.ts +4 -783
  39. package/dist/mcp/client.js +4 -9
  40. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  41. package/dist/mcp/do-oauth-client-provider.js +3 -7
  42. package/dist/mcp/index.d.ts +190 -81
  43. package/dist/mcp/index.js +1428 -767
  44. package/dist/mcp/index.js.map +1 -1
  45. package/dist/mcp/x402.d.ts +34 -0
  46. package/dist/mcp/x402.js +194 -0
  47. package/dist/mcp/x402.js.map +1 -0
  48. package/dist/mcp-Dw5vDrY8.d.ts +61 -0
  49. package/dist/observability/index.d.ts +3 -0
  50. package/dist/observability/index.js +7 -0
  51. package/dist/react-DFNXTQzy.d.ts +113 -0
  52. package/dist/react.d.ts +10 -53
  53. package/dist/react.js +183 -100
  54. package/dist/react.js.map +1 -1
  55. package/dist/schedule.d.ts +89 -12
  56. package/dist/schedule.js +46 -21
  57. package/dist/schedule.js.map +1 -1
  58. package/dist/serializable-CymX8ovI.d.ts +39 -0
  59. package/dist/serializable.d.ts +7 -0
  60. package/dist/serializable.js +1 -0
  61. package/dist/src-C1WWpbRo.js +1247 -0
  62. package/dist/src-C1WWpbRo.js.map +1 -0
  63. package/package.json +125 -71
  64. package/dist/ai-types.js.map +0 -1
  65. package/dist/chunk-BZXOAZUX.js +0 -106
  66. package/dist/chunk-BZXOAZUX.js.map +0 -1
  67. package/dist/chunk-QSGN3REV.js +0 -123
  68. package/dist/chunk-QSGN3REV.js.map +0 -1
  69. package/dist/chunk-RIYR6FR6.js +0 -777
  70. package/dist/chunk-RIYR6FR6.js.map +0 -1
  71. package/dist/chunk-Y67CHZBI.js +0 -464
  72. package/dist/chunk-Y67CHZBI.js.map +0 -1
  73. package/dist/client.js.map +0 -1
  74. package/dist/index.js.map +0 -1
  75. package/dist/mcp/client.js.map +0 -1
  76. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  77. package/src/index.ts +0 -1243
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-DvK0u9vD.js","names":["url: URL","options: {\n transport: MCPTransportOptions;\n client: ConstructorParameters<typeof Client>[1];\n }","toolsAgg: Tool[]","toolsResult: ListToolsResult","resourcesAgg: Resource[]","resourcesResult: ListResourcesResult","promptsAgg: Prompt[]","promptsResult: ListPromptsResult","templatesAgg: ResourceTemplate[]","templatesResult: ListResourceTemplatesResult","transports: BaseTransportType[]","_name: string","_version: string","parsedOptions: MCPServerOptions | null","error"],"sources":["../src/core/events.ts","../src/mcp/errors.ts","../src/mcp/client-connection.ts","../src/mcp/client.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 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 { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n SSEClientTransport,\n type SSEClientTransportOptions\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport {\n StreamableHTTPClientTransport,\n type StreamableHTTPClientTransportOptions\n} 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 type { BaseTransportType, TransportType } 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 type MCPConnectionState =\n /**\n * Waiting for OAuth authorization to complete.\n * Server requires OAuth and user must complete the authorization flow.\n * Next state: \"connecting\" (after handleCallbackRequest + establishConnection)\n */\n | \"authenticating\"\n /**\n * Establishing transport connection to MCP server.\n * OAuth (if required) is complete, now connecting to the actual MCP endpoint.\n * Next state: \"discovering\" (after transport connected)\n */\n | \"connecting\"\n /**\n * Fully connected and ready to use.\n * Tools, resources, and prompts have been discovered and registered.\n * This is the terminal success state.\n */\n | \"ready\"\n /**\n * Discovering server capabilities (tools, resources, prompts).\n * Transport is connected, now fetching available capabilities via MCP protocol.\n * Next state: \"ready\" (after capabilities fetched)\n */\n | \"discovering\"\n /**\n * Connection failed at some point.\n * Check observability events for error details.\n * This is a terminal error state.\n */\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 StreamableHTTPClientTransport(\n this.url,\n this.options.transport as StreamableHTTPClientTransportOptions\n );\n case \"sse\":\n return new SSEClientTransport(\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","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 } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\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\";\nimport type { MCPClientStorage, MCPServerRow } from \"./client-storage\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\nimport { DurableObjectOAuthClientProvider } from \"./do-oauth-client-provider\";\n\n/**\n * Options that can be stored in the server_options column\n * This is what gets JSON.stringify'd and stored in the database\n */\nexport type MCPServerOptions = {\n client?: ConstructorParameters<typeof Client>[1];\n transport?: {\n headers?: HeadersInit;\n type?: TransportType;\n };\n};\n\n/**\n * Options for registering an MCP server\n */\nexport type RegisterServerOptions = {\n url: string;\n name: string;\n callbackUrl: string;\n client?: ConstructorParameters<typeof Client>[1];\n transport?: MCPTransportOptions;\n authUrl?: string;\n clientId?: string;\n};\n\n/**\n * Result of attempting to connect to an MCP server.\n * Returns the current connection state after the operation.\n *\n * - \"ready\": Connection established and ready to use (non-OAuth)\n * - \"authenticating\": OAuth required, user must visit authUrl to authorize\n */\nexport type MCPConnectionResult =\n | { state: \"ready\" }\n | { state: \"authenticating\"; authUrl: string; clientId?: string };\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\nexport type MCPClientManagerOptions = {\n storage: MCPClientStorage;\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 _didWarnAboutUnstableGetAITools = false;\n private _oauthCallbackConfig?: MCPClientOAuthCallbackConfig;\n private _connectionDisposables = new Map<string, DisposableStore>();\n private _storage: MCPClientStorage;\n private _isRestored = false;\n\n private readonly _onObservabilityEvent = 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 /**\n * @param _name Name of the MCP client\n * @param _version Version of the MCP Client\n * @param options Storage adapter for persisting MCP server state\n */\n constructor(\n private _name: string,\n private _version: string,\n options: MCPClientManagerOptions\n ) {\n this._storage = options.storage;\n }\n\n jsonSchema: typeof import(\"ai\").jsonSchema | undefined;\n\n /**\n * Create an auth provider for a server\n * @internal\n */\n private createAuthProvider(\n serverId: string,\n callbackUrl: string,\n clientName: string,\n clientId?: string\n ): AgentsOAuthProvider {\n const authProvider = new DurableObjectOAuthClientProvider(\n this._storage,\n clientName,\n callbackUrl\n );\n authProvider.serverId = serverId;\n if (clientId) {\n authProvider.clientId = clientId;\n }\n return authProvider;\n }\n\n /**\n * Restore MCP server connections from storage\n * This method is called on Agent initialization to restore previously connected servers\n *\n * @param clientName Name to use for OAuth client (typically the agent instance name)\n */\n async restoreConnectionsFromStorage(clientName: string): Promise<void> {\n if (this._isRestored) {\n return;\n }\n\n await this._storage.create();\n const servers = await this._storage.listServers();\n\n if (!servers || servers.length === 0) {\n this._isRestored = true;\n return;\n }\n\n for (const server of servers) {\n const existingConn = this.mcpConnections[server.id];\n\n // Skip if connection already exists and is in a good state\n if (existingConn) {\n if (existingConn.connectionState === \"ready\") {\n console.warn(\n `[MCPClientManager] Server ${server.id} already has a ready connection. Skipping recreation.`\n );\n continue;\n }\n\n // Don't interrupt in-flight OAuth or connections\n if (\n existingConn.connectionState === \"authenticating\" ||\n existingConn.connectionState === \"connecting\" ||\n existingConn.connectionState === \"discovering\"\n ) {\n // Let the existing flow complete\n continue;\n }\n\n // If failed, clean up the old connection before recreating\n if (existingConn.connectionState === \"failed\") {\n try {\n await existingConn.client.close();\n } catch (error) {\n console.warn(\n `[MCPClientManager] Error closing failed connection ${server.id}:`,\n error\n );\n }\n delete this.mcpConnections[server.id];\n this._connectionDisposables.get(server.id)?.dispose();\n this._connectionDisposables.delete(server.id);\n }\n }\n\n const parsedOptions: MCPServerOptions | null = server.server_options\n ? JSON.parse(server.server_options)\n : null;\n\n const authProvider = this.createAuthProvider(\n server.id,\n server.callback_url,\n clientName,\n server.client_id ?? undefined\n );\n\n // Create the in-memory connection object (no need to save to storage - we just read from it!)\n this.createConnection(server.id, server.server_url, {\n client: parsedOptions?.client ?? {},\n transport: {\n ...(parsedOptions?.transport ?? {}),\n type: parsedOptions?.transport?.type ?? (\"auto\" as TransportType),\n authProvider\n }\n });\n\n // Always try to connect - the connection logic will determine if OAuth is needed\n // If stored OAuth tokens are valid, connection will succeed automatically\n // If tokens are missing/invalid, connection will fail with Unauthorized\n // and state will be set to \"authenticating\"\n await this.connectToServer(server.id).catch((error) => {\n console.error(`Error restoring ${server.id}:`, error);\n });\n }\n\n this._isRestored = true;\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: {\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 /* Late initialization of jsonSchemaFn */\n /**\n * We need to delay loading ai sdk, because putting it in module scope is\n * causing issues with startup time.\n * The only place it's used is in getAITools, which only matters after\n * .connect() is called on at least one server.\n * So it's safe to delay loading it until .connect() is called.\n */\n await this.ensureJsonSchema();\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 return {\n authUrl,\n clientId: options.transport?.authProvider?.clientId,\n id\n };\n }\n\n return {\n id\n };\n }\n\n /**\n * Create an in-memory connection object and set up observability\n * Does NOT save to storage - use registerServer() for that\n */\n private createConnection(\n id: string,\n url: string,\n options: {\n client?: ConstructorParameters<typeof Client>[1];\n transport: MCPTransportOptions;\n }\n ): void {\n // Skip if connection already exists\n if (this.mcpConnections[id]) {\n return;\n }\n\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 const store = new DisposableStore();\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 /**\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 // Create the in-memory connection\n this.createConnection(id, options.url, {\n client: options.client,\n transport: {\n ...options.transport,\n type: options.transport?.type ?? (\"auto\" as TransportType)\n }\n });\n\n // Save to storage\n await this._storage.saveServer({\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: JSON.stringify({\n client: options.client,\n transport: options.transport\n })\n });\n\n this._onServerStateChanged.fire();\n\n return id;\n }\n\n /**\n * Connect to an already registered MCP server and initialize the connection.\n *\n * For OAuth servers, this returns `{ state: \"authenticating\", authUrl, clientId? }`\n * without establishing the connection. The user must complete the OAuth flow via\n * the authUrl, which will trigger a callback handled by `handleCallbackRequest()`.\n *\n * For non-OAuth servers, this establishes the connection immediately and returns\n * `{ state: \"ready\" }`.\n *\n * Updates storage with auth URL and client ID after connection.\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 const conn = this.mcpConnections[id];\n if (!conn) {\n throw new Error(\n `Server ${id} is not registered. Call registerServer() first.`\n );\n }\n\n // Initialize connection\n await conn.init();\n\n // If connection is in authenticating state, return auth URL for OAuth flow\n const authUrl = conn.options.transport.authProvider?.authUrl;\n\n if (\n conn.connectionState === \"authenticating\" &&\n authUrl &&\n conn.options.transport.authProvider?.redirectUrl\n ) {\n const clientId = conn.options.transport.authProvider?.clientId;\n\n // Update storage with auth URL and client ID\n const servers = await this._storage.listServers();\n const serverRow = servers.find((s) => s.id === id);\n if (serverRow) {\n await this._storage.saveServer({\n ...serverRow,\n auth_url: authUrl,\n client_id: clientId ?? null\n });\n }\n\n this._onServerStateChanged.fire();\n\n return {\n state: \"authenticating\",\n authUrl,\n clientId\n };\n }\n\n // Fire state changed event for non-OAuth connections that reached ready state\n if (conn.connectionState === \"ready\") {\n this._onServerStateChanged.fire();\n }\n\n return { state: \"ready\" };\n }\n\n async isCallbackRequest(req: Request): Promise<boolean> {\n if (req.method !== \"GET\") {\n return false;\n }\n\n // Quick heuristic check: most callback URLs contain \"/callback\"\n // This avoids DB queries for obviously non-callback requests\n if (!req.url.includes(\"/callback\")) {\n return false;\n }\n\n // Check database for matching callback URL\n const servers = await this._storage.listServers();\n return servers.some(\n (server) => server.callback_url && req.url.startsWith(server.callback_url)\n );\n }\n\n async handleCallbackRequest(req: Request) {\n const url = new URL(req.url);\n\n // Find the matching server from database\n const servers = await this._storage.listServers();\n const matchingServer = servers.find((server: MCPServerRow) => {\n return server.callback_url && req.url.startsWith(server.callback_url);\n });\n\n if (!matchingServer) {\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\n const serverId = matchingServer.id;\n const code = url.searchParams.get(\"code\");\n const state = url.searchParams.get(\"state\");\n const error = url.searchParams.get(\"error\");\n const errorDescription = url.searchParams.get(\"error_description\");\n\n // Handle OAuth error responses from the provider\n if (error) {\n return {\n serverId,\n authSuccess: false,\n authError: errorDescription || error\n };\n }\n\n if (!code) {\n throw new Error(\"Unauthorized: no code provided\");\n }\n if (!state) {\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 connection is already ready, this is likely a duplicate callback\n if (this.mcpConnections[serverId].connectionState === \"ready\") {\n // Already authenticated and ready, treat as success\n return {\n serverId,\n authSuccess: true\n };\n }\n\n if (this.mcpConnections[serverId].connectionState !== \"authenticating\") {\n throw new Error(\n `Failed to authenticate: the client is in \"${this.mcpConnections[serverId].connectionState}\" state, expected \"authenticating\"`\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 // Get clientId from auth provider (stored during redirectToAuthorization) or fallback to state for backward compatibility\n const clientId = conn.options.transport.authProvider.clientId || state;\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 await this._storage.clearAuthUrl(serverId);\n this._onServerStateChanged.fire();\n\n return {\n serverId,\n authSuccess: true\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n\n this._onServerStateChanged.fire();\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._onServerStateChanged.fire();\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 this._onServerStateChanged.fire();\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 * Lazy-loads the jsonSchema function from the AI SDK.\n *\n * This defers importing the \"ai\" package until it's actually needed, which helps reduce\n * initial bundle size and startup time. The jsonSchema function is required for converting\n * MCP tools into AI SDK tool definitions via getAITools().\n *\n * @internal This method is for internal use only. It's automatically called before operations\n * that need jsonSchema (like getAITools() or OAuth flows). External consumers should not need\n * to call this directly.\n */\n async ensureJsonSchema() {\n if (!this.jsonSchema) {\n const { jsonSchema } = await import(\"ai\");\n this.jsonSchema = jsonSchema;\n }\n }\n\n /**\n * @returns a set of tools that you can use with the AI SDK\n */\n getAITools(): ToolSet {\n if (!this.jsonSchema) {\n throw new Error(\"jsonSchema not initialized.\");\n }\n\n // Warn if tools are being read from non-ready connections\n for (const [id, conn] of Object.entries(this.mcpConnections)) {\n if (\n conn.connectionState !== \"ready\" &&\n conn.connectionState !== \"authenticating\"\n ) {\n console.warn(\n `[getAITools] WARNING: Reading tools from connection ${id} in state \"${conn.connectionState}\". Tools may not be loaded yet.`\n );\n }\n }\n\n return Object.fromEntries(\n getNamespacedData(this.mcpConnections, \"tools\").map((tool) => {\n return [\n `tool_${tool.serverId.replace(/-/g, \"\")}_${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 inputSchema: this.jsonSchema!(tool.inputSchema as JSONSchema7),\n outputSchema: tool.outputSchema\n ? this.jsonSchema!(tool.outputSchema as JSONSchema7)\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 * Remove an MCP server from storage\n */\n async removeServer(serverId: string): Promise<void> {\n await this._storage.removeServer(serverId);\n this._onServerStateChanged.fire();\n }\n\n /**\n * List all MCP servers from storage\n */\n async listServers(): Promise<MCPServerRow[]> {\n return await this._storage.listServers();\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._onServerStateChanged.dispose();\n this._onObservabilityEvent.dispose();\n\n // Drop the storage table\n await this._storage.destroy();\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"],"mappings":";;;;;;;;AAIA,SAAgB,aAAa,IAA4B;AACvD,QAAO,EAAE,SAAS,IAAI;;AAGxB,IAAa,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,WAAW,CAAC,KAAK,CAAC,MAAM,UAAU;AAC5D,SAAO;GAAE,MAAM,KAAK;GAAO;GAAM;GACjC,CAE0B,SAAS,EAAE,MAAM,UAAU,WAAW;AAChE,SAAO,KAAK,KAAK,SAAS;AACxB,UAAO;IACL,GAAG;IAEH;IACD;IACD;GACF"}
package/dist/client.d.ts CHANGED
@@ -1,92 +1,17 @@
1
+ import "./serializable-CymX8ovI.js";
1
2
  import {
2
- PartySocketOptions,
3
- PartyFetchOptions,
4
- PartySocket,
5
- } from "partysocket";
6
-
7
- /**
8
- * Options for creating an AgentClient
9
- */
10
- type AgentClientOptions<State = unknown> = Omit<
11
- PartySocketOptions,
12
- "party" | "room"
13
- > & {
14
- /** Name of the agent to connect to */
15
- agent: string;
16
- /** Name of the specific Agent instance */
17
- name?: string;
18
- /** Called when the Agent's state is updated */
19
- onStateUpdate?: (state: State, source: "server" | "client") => void;
20
- };
21
- /**
22
- * Options for streaming RPC calls
23
- */
24
- type StreamOptions = {
25
- /** Called when a chunk of data is received */
26
- onChunk?: (chunk: unknown) => void;
27
- /** Called when the stream ends */
28
- onDone?: (finalChunk: unknown) => void;
29
- /** Called when an error occurs */
30
- onError?: (error: string) => void;
31
- };
32
- /**
33
- * Options for the agentFetch function
34
- */
35
- type AgentClientFetchOptions = Omit<PartyFetchOptions, "party" | "room"> & {
36
- /** Name of the agent to connect to */
37
- agent: string;
38
- /** Name of the specific Agent instance */
39
- name?: string;
40
- };
41
- /**
42
- * Convert a camelCase string to a kebab-case string
43
- * @param str The string to convert
44
- * @returns The kebab-case string
45
- */
46
- declare function camelCaseToKebabCase(str: string): string;
47
- /**
48
- * WebSocket client for connecting to an Agent
49
- */
50
- declare class AgentClient<State = unknown> extends PartySocket {
51
- /**
52
- * @deprecated Use agentFetch instead
53
- */
54
- static fetch(_opts: PartyFetchOptions): Promise<Response>;
55
- agent: string;
56
- name: string;
57
- private options;
58
- private _pendingCalls;
59
- constructor(options: AgentClientOptions<State>);
60
- setState(state: State): void;
61
- /**
62
- * Call a method on the Agent
63
- * @param method Name of the method to call
64
- * @param args Arguments to pass to the method
65
- * @param streamOptions Options for handling streaming responses
66
- * @returns Promise that resolves with the method's return value
67
- */
68
- call<T = unknown>(
69
- method: string,
70
- args?: unknown[],
71
- streamOptions?: StreamOptions
72
- ): Promise<T>;
73
- }
74
- /**
75
- * Make an HTTP request to an Agent
76
- * @param opts Connection options
77
- * @param init Request initialization options
78
- * @returns Promise resolving to a Response
79
- */
80
- declare function agentFetch(
81
- opts: AgentClientFetchOptions,
82
- init?: RequestInit
83
- ): Promise<Response>;
84
-
3
+ a as agentFetch,
4
+ i as StreamOptions,
5
+ n as AgentClientFetchOptions,
6
+ o as camelCaseToKebabCase,
7
+ r as AgentClientOptions,
8
+ t as AgentClient
9
+ } from "./client-CbWe9FBd.js";
85
10
  export {
86
11
  AgentClient,
87
- type AgentClientFetchOptions,
88
- type AgentClientOptions,
89
- type StreamOptions,
12
+ AgentClientFetchOptions,
13
+ AgentClientOptions,
14
+ StreamOptions,
90
15
  agentFetch,
91
- camelCaseToKebabCase,
16
+ camelCaseToKebabCase
92
17
  };
package/dist/client.js CHANGED
@@ -1,11 +1,4 @@
1
- import {
2
- AgentClient,
3
- agentFetch,
4
- camelCaseToKebabCase
5
- } from "./chunk-QSGN3REV.js";
6
- export {
7
- AgentClient,
8
- agentFetch,
9
- camelCaseToKebabCase
10
- };
11
- //# sourceMappingURL=client.js.map
1
+ import "./ai-types-B3aQaFv3.js";
2
+ import { n as agentFetch, r as camelCaseToKebabCase, t as AgentClient } from "./client-BfiZ3HQd.js";
3
+
4
+ export { AgentClient, agentFetch, camelCaseToKebabCase };
@@ -0,0 +1,27 @@
1
+ import { ToolSet } from "ai";
2
+ import { WorkerEntrypoint } from "cloudflare:workers";
3
+
4
+ //#region src/codemode/ai.d.ts
5
+ declare class CodeModeProxy extends WorkerEntrypoint<Cloudflare.Env, {
6
+ binding: string;
7
+ name: string;
8
+ callback: string;
9
+ }> {
10
+ callFunction(options: {
11
+ functionName: string;
12
+ args: unknown[];
13
+ }): Promise<any>;
14
+ }
15
+ declare function experimental_codemode(options: {
16
+ tools: ToolSet;
17
+ prompt: string;
18
+ globalOutbound: Fetcher;
19
+ loader: WorkerLoader;
20
+ proxy: Fetcher<CodeModeProxy>;
21
+ }): Promise<{
22
+ prompt: string;
23
+ tools: ToolSet;
24
+ }>;
25
+ //#endregion
26
+ export { CodeModeProxy, experimental_codemode };
27
+ //# sourceMappingURL=ai.d.ts.map
@@ -0,0 +1,151 @@
1
+ import "../ai-types-B3aQaFv3.js";
2
+ import "../client-BfiZ3HQd.js";
3
+ import "../client-DvK0u9vD.js";
4
+ import "../do-oauth-client-provider-D2P1lSft.js";
5
+ import { s as getAgentByName } from "../src-C1WWpbRo.js";
6
+ import { generateObject, tool } from "ai";
7
+ import { openai } from "@ai-sdk/openai";
8
+ import { z } from "zod/v3";
9
+ import { compile } from "json-schema-to-typescript";
10
+ import { createTypeAlias, printNode, zodToTs } from "zod-to-ts";
11
+ import { WorkerEntrypoint, env } from "cloudflare:workers";
12
+
13
+ //#region src/codemode/ai.ts
14
+ function toCamelCase(str) {
15
+ return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/^[a-z]/, (letter) => letter.toUpperCase());
16
+ }
17
+ var CodeModeProxy = class extends WorkerEntrypoint {
18
+ async callFunction(options) {
19
+ return (await getAgentByName(env[this.ctx.props.binding], this.ctx.props.name))[this.ctx.props.callback](options.functionName, options.args);
20
+ }
21
+ };
22
+ async function experimental_codemode(options) {
23
+ const generatedTypes = await generateTypes(options.tools);
24
+ return {
25
+ prompt: `You are a helpful assistant. You have access to the "codemode" tool that can do different things:
26
+
27
+ ${getToolDescriptions(options.tools)}
28
+
29
+ If the user asks to do anything that be achieveable by the codemode tool, then simply pass over control to it by giving it a simple function description. Don't be too verbose.
30
+
31
+ `,
32
+ tools: { codemode: tool({
33
+ description: "codemode: a tool that can generate code to achieve a goal",
34
+ inputSchema: z.object({ functionDescription: z.string() }),
35
+ outputSchema: z.object({
36
+ code: z.string(),
37
+ result: z.any()
38
+ }),
39
+ execute: async ({ functionDescription }) => {
40
+ try {
41
+ const response = await generateObject({
42
+ model: openai("gpt-4.1"),
43
+ schema: z.object({ code: z.string() }),
44
+ prompt: `You are a code generating machine.
45
+
46
+ In addition to regular javascript, you can also use the following functions:
47
+
48
+ ${generatedTypes}
49
+
50
+ Respond only with the code, nothing else. Output javascript code.
51
+
52
+ Generate an async function that achieves the goal. This async function doesn't accept any arguments.
53
+
54
+ Here is user input: ${functionDescription}`
55
+ });
56
+ const result = await createEvaluator(response.object.code, {
57
+ proxy: options.proxy,
58
+ loader: options.loader
59
+ })();
60
+ return {
61
+ code: response.object.code,
62
+ result
63
+ };
64
+ } catch (error) {
65
+ console.error("error", error);
66
+ throw error;
67
+ }
68
+ }
69
+ }) }
70
+ };
71
+ }
72
+ function createEvaluator(code, options) {
73
+ return async () => {
74
+ return await options.loader.get(`code-${Math.random()}`, () => {
75
+ return {
76
+ compatibilityDate: "2025-06-01",
77
+ compatibilityFlags: ["nodejs_compat"],
78
+ mainModule: "foo.js",
79
+ modules: { "foo.js": `
80
+ import { env, WorkerEntrypoint } from "cloudflare:workers";
81
+
82
+ export default class CodeModeWorker extends WorkerEntrypoint {
83
+ async evaluate() {
84
+ try {
85
+ const { CodeModeProxy } = env;
86
+ const codemode = new Proxy(
87
+ {},
88
+ {
89
+ get: (target, prop) => {
90
+ return (args) => {
91
+ return CodeModeProxy.callFunction({
92
+ functionName: prop,
93
+ args: args,
94
+ });
95
+ };
96
+ }
97
+ }
98
+ );
99
+
100
+ return await ${code}();
101
+ } catch (err) {
102
+ return {
103
+ err: err.message,
104
+ stack: err.stack
105
+ };
106
+ }
107
+ }
108
+ }
109
+
110
+ ` },
111
+ env: { CodeModeProxy: options.proxy },
112
+ globalOutbound: null
113
+ };
114
+ }).getEntrypoint().evaluate();
115
+ };
116
+ }
117
+ async function generateTypes(tools) {
118
+ let availableTools = "";
119
+ let availableTypes = "";
120
+ for (const [toolName, tool$1] of Object.entries(tools)) {
121
+ const inputJsonType = tool$1.inputSchema.jsonSchema ? await compile(tool$1.inputSchema.jsonSchema, `${toCamelCase(toolName)}Input`, {
122
+ format: false,
123
+ bannerComment: " "
124
+ }) : printNode(createTypeAlias(zodToTs(tool$1.inputSchema, `${toCamelCase(toolName)}Input`).node, `${toCamelCase(toolName)}Input`));
125
+ const outputJsonType = tool$1.outputSchema?.jsonSchema ? await compile(tool$1.outputSchema?.jsonSchema, `${toCamelCase(toolName)}Output`, {
126
+ format: false,
127
+ bannerComment: " "
128
+ }) : tool$1.outputSchema ? printNode(createTypeAlias(zodToTs(tool$1.outputSchema, `${toCamelCase(toolName)}Output`).node, `${toCamelCase(toolName)}Output`)) : `interface ${toCamelCase(toolName)}Output { [key: string]: any }`;
129
+ const InputType = inputJsonType.trim().replace("export interface", "interface");
130
+ const OutputType = outputJsonType.trim().replace("export interface", "interface");
131
+ availableTypes += `\n${InputType}`;
132
+ availableTypes += `\n${OutputType}`;
133
+ availableTools += `\n\t/*\n\t${tool$1.description?.trim()}\n\t*/`;
134
+ availableTools += `\n\t${toolName}: (input: ${toCamelCase(toolName)}Input) => Promise<${toCamelCase(toolName)}Output>;`;
135
+ availableTools += "\n";
136
+ }
137
+ availableTools = `\ndeclare const codemode: {${availableTools}}`;
138
+ return `
139
+ ${availableTypes}
140
+ ${availableTools}
141
+ `;
142
+ }
143
+ function getToolDescriptions(tools) {
144
+ return Object.entries(tools).map(([_toolName, tool$1]) => {
145
+ return `\n- ${tool$1.description?.trim()}`;
146
+ }).join("");
147
+ }
148
+
149
+ //#endregion
150
+ export { CodeModeProxy, experimental_codemode };
151
+ //# sourceMappingURL=ai.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai.js","names":["tool","compileJsonSchemaToTs","printNodeZodToTs"],"sources":["../../src/codemode/ai.ts"],"sourcesContent":["import { generateObject, tool, type ToolSet } from \"ai\";\nimport { openai } from \"@ai-sdk/openai\";\nimport { z } from \"zod/v3\";\nimport { compile as compileJsonSchemaToTs } from \"json-schema-to-typescript\";\nimport {\n zodToTs,\n printNode as printNodeZodToTs,\n createTypeAlias\n} from \"zod-to-ts\";\nimport { getAgentByName } from \"..\";\nimport { env, WorkerEntrypoint } from \"cloudflare:workers\";\n\nfunction toCamelCase(str: string) {\n return str\n .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n .replace(/^[a-z]/, (letter) => letter.toUpperCase());\n}\n\nexport class CodeModeProxy extends WorkerEntrypoint<\n Cloudflare.Env,\n {\n binding: string;\n name: string;\n callback: string;\n }\n> {\n async callFunction(options: { functionName: string; args: unknown[] }) {\n const stub = (await getAgentByName(\n // @ts-expect-error\n env[this.ctx.props.binding] as AgentNamespace<T>,\n this.ctx.props.name\n )) as DurableObjectStub;\n // @ts-expect-error\n return stub[this.ctx.props.callback](options.functionName, options.args);\n }\n}\n\nexport async function experimental_codemode(options: {\n tools: ToolSet;\n prompt: string;\n globalOutbound: Fetcher;\n loader: WorkerLoader;\n proxy: Fetcher<CodeModeProxy>;\n}): Promise<{\n prompt: string;\n tools: ToolSet;\n}> {\n const generatedTypes = await generateTypes(options.tools);\n const prompt = `You are a helpful assistant. You have access to the \"codemode\" tool that can do different things: \n \n ${getToolDescriptions(options.tools)} \n \n If the user asks to do anything that be achieveable by the codemode tool, then simply pass over control to it by giving it a simple function description. Don't be too verbose.\n \n `;\n\n const codemodeTool = tool({\n description: \"codemode: a tool that can generate code to achieve a goal\",\n inputSchema: z.object({\n functionDescription: z.string()\n }),\n outputSchema: z.object({\n code: z.string(),\n result: z.any()\n }),\n execute: async ({ functionDescription }) => {\n try {\n const response = await generateObject({\n model: openai(\"gpt-4.1\"),\n schema: z.object({\n code: z.string()\n }),\n prompt: `You are a code generating machine.\n\n In addition to regular javascript, you can also use the following functions:\n\n ${generatedTypes} \n\n Respond only with the code, nothing else. Output javascript code.\n\n Generate an async function that achieves the goal. This async function doesn't accept any arguments.\n\n Here is user input: ${functionDescription}` // insert ts types for the tools here\n });\n\n // console.log(\"args\", response.object.args);\n const evaluator = createEvaluator(response.object.code, {\n proxy: options.proxy,\n loader: options.loader\n });\n const result = await evaluator();\n return { code: response.object.code, result: result };\n } catch (error) {\n console.error(\"error\", error);\n throw error;\n // return { code: \"\", result: error };\n }\n }\n });\n\n return { prompt, tools: { codemode: codemodeTool } };\n}\n\nfunction createEvaluator(\n code: string,\n options: {\n loader: WorkerLoader;\n proxy: Fetcher<CodeModeProxy>;\n }\n) {\n return async () => {\n const worker = options.loader.get(`code-${Math.random()}`, () => {\n return {\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"foo.js\",\n modules: {\n \"foo.js\": `\nimport { env, WorkerEntrypoint } from \"cloudflare:workers\";\n\nexport default class CodeModeWorker extends WorkerEntrypoint {\n async evaluate() {\n try {\n const { CodeModeProxy } = env;\n const codemode = new Proxy(\n {},\n {\n get: (target, prop) => {\n return (args) => {\n return CodeModeProxy.callFunction({\n functionName: prop,\n args: args, \n });\n };\n }\n }\n );\n\n return await ${code}();\n } catch (err) {\n return {\n err: err.message,\n stack: err.stack\n };\n }\n }\n}\n \n `\n },\n env: {\n // insert keys and bindings to tools/ts functions here\n CodeModeProxy: options.proxy\n },\n globalOutbound: null\n };\n });\n\n // @ts-expect-error TODO: fix this\n return await worker.getEntrypoint().evaluate();\n };\n}\n\nasync function generateTypes(tools: ToolSet) {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n // @ts-expect-error TODO: fix this\n const inputJsonType = tool.inputSchema.jsonSchema\n ? await compileJsonSchemaToTs(\n // @ts-expect-error TODO: fix this\n tool.inputSchema.jsonSchema,\n `${toCamelCase(toolName)}Input`,\n {\n format: false,\n bannerComment: \" \"\n }\n )\n : printNodeZodToTs(\n createTypeAlias(\n zodToTs(\n // @ts-expect-error TODO: fix this\n tool.inputSchema,\n `${toCamelCase(toolName)}Input`\n ).node,\n `${toCamelCase(toolName)}Input`\n )\n );\n\n const outputJsonType =\n // @ts-expect-error TODO: fix this\n tool.outputSchema?.jsonSchema\n ? await compileJsonSchemaToTs(\n // @ts-expect-error TODO: fix this\n tool.outputSchema?.jsonSchema,\n `${toCamelCase(toolName)}Output`,\n {\n format: false,\n bannerComment: \" \"\n }\n )\n : tool.outputSchema\n ? printNodeZodToTs(\n createTypeAlias(\n zodToTs(\n // @ts-expect-error TODO: fix this\n tool.outputSchema,\n `${toCamelCase(toolName)}Output`\n ).node,\n `${toCamelCase(toolName)}Output`\n )\n )\n : `interface ${toCamelCase(toolName)}Output { [key: string]: any }`;\n\n const InputType = inputJsonType\n .trim()\n .replace(\"export interface\", \"interface\");\n\n const OutputType = outputJsonType\n .trim()\n .replace(\"export interface\", \"interface\");\n\n availableTypes += `\\n${InputType}`;\n availableTypes += `\\n${OutputType}`;\n availableTools += `\\n\\t/*\\n\\t${tool.description?.trim()}\\n\\t*/`;\n availableTools += `\\n\\t${toolName}: (input: ${toCamelCase(toolName)}Input) => Promise<${toCamelCase(toolName)}Output>;`;\n availableTools += \"\\n\";\n }\n\n availableTools = `\\ndeclare const codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `;\n}\n\nfunction getToolDescriptions(tools: ToolSet) {\n return Object.entries(tools)\n .map(([_toolName, tool]) => {\n return `\\n- ${tool.description?.trim()}`;\n })\n .join(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAS,YAAY,KAAa;AAChC,QAAO,IACJ,QAAQ,cAAc,GAAG,WAAW,OAAO,aAAa,CAAC,CACzD,QAAQ,WAAW,WAAW,OAAO,aAAa,CAAC;;AAGxD,IAAa,gBAAb,cAAmC,iBAOjC;CACA,MAAM,aAAa,SAAoD;AAOrE,UANc,MAAM,eAElB,IAAI,KAAK,IAAI,MAAM,UACnB,KAAK,IAAI,MAAM,KAChB,EAEW,KAAK,IAAI,MAAM,UAAU,QAAQ,cAAc,QAAQ,KAAK;;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UAAUA,WAAS,OAAO,QAAQ,MAAM,EAAE;EAEpD,MAAM,gBAAgBA,OAAK,YAAY,aACnC,MAAMC,QAEJD,OAAK,YAAY,YACjB,GAAG,YAAY,SAAS,CAAC,QACzB;GACE,QAAQ;GACR,eAAe;GAChB,CACF,GACDE,UACE,gBACE,QAEEF,OAAK,aACL,GAAG,YAAY,SAAS,CAAC,OAC1B,CAAC,MACF,GAAG,YAAY,SAAS,CAAC,OAC1B,CACF;EAEL,MAAM,iBAEJA,OAAK,cAAc,aACf,MAAMC,QAEJD,OAAK,cAAc,YACnB,GAAG,YAAY,SAAS,CAAC,SACzB;GACE,QAAQ;GACR,eAAe;GAChB,CACF,GACDA,OAAK,eACHE,UACE,gBACE,QAEEF,OAAK,cACL,GAAG,YAAY,SAAS,CAAC,QAC1B,CAAC,MACF,GAAG,YAAY,SAAS,CAAC,QAC1B,CACF,GACD,aAAa,YAAY,SAAS,CAAC;EAE3C,MAAM,YAAY,cACf,MAAM,CACN,QAAQ,oBAAoB,YAAY;EAE3C,MAAM,aAAa,eAChB,MAAM,CACN,QAAQ,oBAAoB,YAAY;AAE3C,oBAAkB,KAAK;AACvB,oBAAkB,KAAK;AACvB,oBAAkB,aAAaA,OAAK,aAAa,MAAM,CAAC;AACxD,oBAAkB,OAAO,SAAS,YAAY,YAAY,SAAS,CAAC,oBAAoB,YAAY,SAAS,CAAC;AAC9G,oBAAkB;;AAGpB,kBAAiB,8BAA8B,eAAe;AAE9D,QAAO;EACP,eAAe;EACf,eAAe;;;AAIjB,SAAS,oBAAoB,OAAgB;AAC3C,QAAO,OAAO,QAAQ,MAAM,CACzB,KAAK,CAAC,WAAWA,YAAU;AAC1B,SAAO,OAAOA,OAAK,aAAa,MAAM;GACtC,CACD,KAAK,GAAG"}
@@ -0,0 +1,142 @@
1
+ import { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js";
2
+ import {
3
+ OAuthClientInformationFull,
4
+ OAuthClientMetadata,
5
+ OAuthTokens
6
+ } from "@modelcontextprotocol/sdk/shared/auth.js";
7
+
8
+ //#region src/mcp/client-storage.d.ts
9
+ /**
10
+ * Represents a row in the cf_agents_mcp_servers table
11
+ */
12
+ type MCPServerRow = {
13
+ id: string;
14
+ name: string;
15
+ server_url: string;
16
+ client_id: string | null;
17
+ auth_url: string | null;
18
+ callback_url: string;
19
+ server_options: string | null;
20
+ };
21
+ /**
22
+ * KV storage interface for OAuth-related data
23
+ * Used by OAuth providers to store tokens, client info, etc.
24
+ */
25
+ interface OAuthClientStorage {
26
+ /**
27
+ * Get a value from key-value storage (for OAuth data like tokens, client info, etc.)
28
+ */
29
+ get<T>(key: string): Promise<T | undefined> | undefined;
30
+ /**
31
+ * Put a value into key-value storage (for OAuth data like tokens, client info, etc.)
32
+ */
33
+ put(key: string, value: unknown): Promise<void> | void;
34
+ }
35
+ /**
36
+ * Storage interface for MCP client manager
37
+ * Abstracts storage operations to decouple from specific storage implementations
38
+ */
39
+ interface MCPClientStorage extends OAuthClientStorage {
40
+ /**
41
+ * Create the cf_agents_mcp_servers table if it doesn't exist
42
+ */
43
+ create(): Promise<void>;
44
+ /**
45
+ * Drop the cf_agents_mcp_servers table
46
+ */
47
+ destroy(): Promise<void>;
48
+ /**
49
+ * Save or update an MCP server configuration
50
+ */
51
+ saveServer(server: MCPServerRow): Promise<void>;
52
+ /**
53
+ * Remove an MCP server from storage
54
+ */
55
+ removeServer(serverId: string): Promise<void>;
56
+ /**
57
+ * List all MCP servers from storage
58
+ */
59
+ listServers(): Promise<MCPServerRow[]>;
60
+ /**
61
+ * Get an MCP server by its callback URL
62
+ * Used during OAuth callback to identify which server is being authenticated
63
+ */
64
+ getServerByCallbackUrl(callbackUrl: string): Promise<MCPServerRow | null>;
65
+ /**
66
+ * Clear auth_url after successful OAuth authentication
67
+ * This prevents the agent from continuously asking for OAuth on reconnect
68
+ * when stored tokens are still valid.
69
+ */
70
+ clearAuthUrl(serverId: string): Promise<void>;
71
+ }
72
+ //#endregion
73
+ //#region src/mcp/do-oauth-client-provider.d.ts
74
+ interface AgentsOAuthProvider extends OAuthClientProvider {
75
+ authUrl: string | undefined;
76
+ clientId: string | undefined;
77
+ serverId: string | undefined;
78
+ }
79
+ declare class DurableObjectOAuthClientProvider implements AgentsOAuthProvider {
80
+ storage: OAuthClientStorage;
81
+ clientName: string;
82
+ baseRedirectUrl: string;
83
+ private _authUrl_;
84
+ private _serverId_;
85
+ private _clientId_;
86
+ constructor(
87
+ storage: OAuthClientStorage,
88
+ clientName: string,
89
+ baseRedirectUrl: string
90
+ );
91
+ get clientMetadata(): OAuthClientMetadata;
92
+ get clientUri(): string;
93
+ get redirectUrl(): string;
94
+ get clientId(): string;
95
+ set clientId(clientId_: string);
96
+ get serverId(): string;
97
+ set serverId(serverId_: string);
98
+ keyPrefix(clientId: string): string;
99
+ clientInfoKey(clientId: string): string;
100
+ clientInformation(): Promise<
101
+ | {
102
+ client_id: string;
103
+ client_secret?: string | undefined;
104
+ client_id_issued_at?: number | undefined;
105
+ client_secret_expires_at?: number | undefined;
106
+ }
107
+ | undefined
108
+ >;
109
+ saveClientInformation(
110
+ clientInformation: OAuthClientInformationFull
111
+ ): Promise<void>;
112
+ tokenKey(clientId: string): string;
113
+ tokens(): Promise<
114
+ | {
115
+ access_token: string;
116
+ token_type: string;
117
+ id_token?: string | undefined;
118
+ expires_in?: number | undefined;
119
+ scope?: string | undefined;
120
+ refresh_token?: string | undefined;
121
+ }
122
+ | undefined
123
+ >;
124
+ saveTokens(tokens: OAuthTokens): Promise<void>;
125
+ get authUrl(): string | undefined;
126
+ /**
127
+ * Because this operates on the server side (but we need browser auth), we send this url back to the user
128
+ * and require user interact to initiate the redirect flow
129
+ */
130
+ redirectToAuthorization(authUrl: URL): void;
131
+ codeVerifierKey(clientId: string): string;
132
+ saveCodeVerifier(verifier: string): Promise<void>;
133
+ codeVerifier(): Promise<string>;
134
+ }
135
+ //#endregion
136
+ export {
137
+ MCPServerRow as i,
138
+ DurableObjectOAuthClientProvider as n,
139
+ MCPClientStorage as r,
140
+ AgentsOAuthProvider as t
141
+ };
142
+ //# sourceMappingURL=do-oauth-client-provider-CcTno-25.d.ts.map