agents 0.3.6 → 0.3.8

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 (69) hide show
  1. package/README.md +303 -314
  2. package/dist/ai-types.js +1 -1
  3. package/dist/{client-0lfEZpSQ.js → client-BA8NJB6l.js} +17 -4
  4. package/dist/client-BA8NJB6l.js.map +1 -0
  5. package/dist/{client-Cxno-5sH.d.ts → client-DGpERepg.d.ts} +8 -14
  6. package/dist/client.d.ts +93 -24
  7. package/dist/client.js +202 -2
  8. package/dist/client.js.map +1 -0
  9. package/dist/{do-oauth-client-provider-BH9zFtSy.d.ts → do-oauth-client-provider-BqnOQzjy.d.ts} +1 -1
  10. package/dist/{do-oauth-client-provider-BfPFgQU0.js → do-oauth-client-provider-DDg8QrEA.js} +1 -1
  11. package/dist/{do-oauth-client-provider-BfPFgQU0.js.map → do-oauth-client-provider-DDg8QrEA.js.map} +1 -1
  12. package/dist/email-8ljcpvwV.d.ts +157 -0
  13. package/dist/email-XHsSYsTO.js +223 -0
  14. package/dist/email-XHsSYsTO.js.map +1 -0
  15. package/dist/email.d.ts +30 -0
  16. package/dist/email.js +3 -0
  17. package/dist/{index-B7Ny-XfU.d.ts → index-N6791tVt.d.ts} +18 -3
  18. package/dist/index.d.ts +543 -87
  19. package/dist/index.js +6 -6
  20. package/dist/{internal_context-neg89p5n.d.ts → internal_context-CEu5ji80.d.ts} +8 -3
  21. package/dist/{internal_context-oN047Id3.js → internal_context-D9eKFth1.js} +1 -1
  22. package/dist/internal_context-D9eKFth1.js.map +1 -0
  23. package/dist/internal_context.d.ts +1 -1
  24. package/dist/internal_context.js +1 -1
  25. package/dist/mcp/client.d.ts +1 -1
  26. package/dist/mcp/client.js +2 -2
  27. package/dist/mcp/do-oauth-client-provider.d.ts +1 -1
  28. package/dist/mcp/do-oauth-client-provider.js +1 -1
  29. package/dist/mcp/index.d.ts +4 -2
  30. package/dist/mcp/index.js +35 -35
  31. package/dist/mcp/index.js.map +1 -1
  32. package/dist/mcp/x402.d.ts +0 -1
  33. package/dist/mcp/x402.js.map +1 -1
  34. package/dist/{mcp-AK39tq6H.d.ts → mcp-BwPscEiF.d.ts} +1 -1
  35. package/dist/observability/index.d.ts +1 -1
  36. package/dist/observability/index.js +5 -5
  37. package/dist/react.d.ts +70 -26
  38. package/dist/react.js +83 -21
  39. package/dist/react.js.map +1 -1
  40. package/dist/schedule.d.ts +23 -2
  41. package/dist/schedule.js +23 -1
  42. package/dist/schedule.js.map +1 -1
  43. package/dist/serializable.d.ts +68 -3
  44. package/dist/src-CqnVUbg1.js +2146 -0
  45. package/dist/src-CqnVUbg1.js.map +1 -0
  46. package/dist/types-BITaDFf-.js +16 -0
  47. package/dist/{types-4b5tlB0u.js.map → types-BITaDFf-.js.map} +1 -1
  48. package/dist/{types-C5vR2Gzv.d.ts → types-DSSHBW6w.d.ts} +2 -1
  49. package/dist/types.d.ts +1 -1
  50. package/dist/types.js +1 -1
  51. package/dist/utils-B49TmLCI.js +16 -0
  52. package/dist/utils-B49TmLCI.js.map +1 -0
  53. package/dist/utils.d.ts +10 -0
  54. package/dist/utils.js +3 -0
  55. package/dist/workflow-types-Z_Oem1FJ.d.ts +260 -0
  56. package/dist/workflow-types.d.ts +48 -0
  57. package/dist/workflow-types.js +16 -0
  58. package/dist/workflow-types.js.map +1 -0
  59. package/dist/workflows.d.ts +163 -0
  60. package/dist/workflows.js +240 -0
  61. package/dist/workflows.js.map +1 -0
  62. package/package.json +22 -12
  63. package/dist/client-0lfEZpSQ.js.map +0 -1
  64. package/dist/client-CEO0P7vN.js +0 -117
  65. package/dist/client-CEO0P7vN.js.map +0 -1
  66. package/dist/internal_context-oN047Id3.js.map +0 -1
  67. package/dist/src-C_iKczoR.js +0 -1191
  68. package/dist/src-C_iKczoR.js.map +0 -1
  69. package/dist/types-4b5tlB0u.js +0 -15
package/dist/ai-types.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as MessageType$2 } from "./types-4b5tlB0u.js";
1
+ import { t as MessageType$2 } from "./types-BITaDFf-.js";
2
2
  import { MessageType as MessageType$1 } from "@cloudflare/ai-chat/types";
3
3
 
4
4
  //#region src/ai-types.ts
@@ -1,4 +1,4 @@
1
- import { t as DurableObjectOAuthClientProvider } from "./do-oauth-client-provider-BfPFgQU0.js";
1
+ import { t as DurableObjectOAuthClientProvider } from "./do-oauth-client-provider-DDg8QrEA.js";
2
2
  import { nanoid } from "nanoid";
3
3
  import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/cfworker-provider.js";
4
4
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
@@ -802,7 +802,16 @@ var MCPClientManager = class {
802
802
  const authProvider = conn.options.transport.authProvider;
803
803
  authProvider.serverId = serverId;
804
804
  const stateValidation = await authProvider.checkState(state);
805
- if (!stateValidation.valid) throw new Error(`Invalid state: ${stateValidation.error}`);
805
+ if (!stateValidation.valid) {
806
+ this.clearServerAuthUrl(serverId);
807
+ if (this.mcpConnections[serverId]) this.mcpConnections[serverId].connectionState = MCPConnectionState.FAILED;
808
+ this._onServerStateChanged.fire();
809
+ return {
810
+ serverId,
811
+ authSuccess: false,
812
+ authError: stateValidation.error || "Invalid state"
813
+ };
814
+ }
806
815
  if (error) return {
807
816
  serverId,
808
817
  authSuccess: false,
@@ -967,7 +976,11 @@ var MCPClientManager = class {
967
976
  name: tool.name,
968
977
  serverId: tool.serverId
969
978
  });
970
- if (result.isError) throw new Error(result.content[0].text);
979
+ if (result.isError) {
980
+ const textContent = result.content?.[0];
981
+ const message = textContent?.type === "text" && textContent.text ? textContent.text : "Tool call failed";
982
+ throw new Error(message);
983
+ }
971
984
  return result;
972
985
  },
973
986
  inputSchema: this.jsonSchema(tool.inputSchema),
@@ -1108,4 +1121,4 @@ function getNamespacedData(mcpClients, type) {
1108
1121
 
1109
1122
  //#endregion
1110
1123
  export { DisposableStore as i, getNamespacedData as n, MCPConnectionState as r, MCPClientManager as t };
1111
- //# sourceMappingURL=client-0lfEZpSQ.js.map
1124
+ //# sourceMappingURL=client-BA8NJB6l.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-BA8NJB6l.js","names":[],"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\nfunction getErrorCode(error: unknown): number | undefined {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n typeof (error as { code: unknown }).code === \"number\"\n ) {\n return (error as { code: number }).code;\n }\n return undefined;\n}\n\nexport function isUnauthorized(error: unknown): boolean {\n const code = getErrorCode(error);\n if (code === 401) return true;\n\n const msg = toErrorMessage(error);\n return msg.includes(\"Unauthorized\") || msg.includes(\"401\");\n}\n\n// MCP SDK change (v1.24.0, commit 6b90e1a):\n// - Old: Error POSTing to endpoint (HTTP 404): Not Found\n// - New: StreamableHTTPError with code: 404 and message Error POSTing to endpoint: Not Found\nexport function isTransportNotImplemented(error: unknown): boolean {\n const code = getErrorCode(error);\n if (code === 404 || code === 405) return true;\n\n const msg = toErrorMessage(error);\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 const MCPConnectionState = {\n /** Waiting for OAuth authorization to complete */\n AUTHENTICATING: \"authenticating\",\n /** Establishing transport connection to MCP server */\n CONNECTING: \"connecting\",\n /** Transport connection established */\n CONNECTED: \"connected\",\n /** Discovering server capabilities (tools, resources, prompts) */\n DISCOVERING: \"discovering\",\n /** Fully connected and ready to use */\n READY: \"ready\",\n /** Connection failed at some point */\n FAILED: \"failed\"\n} as const;\n\n/**\n * Connection state type for MCP client connections.\n */\nexport type MCPConnectionState =\n (typeof MCPConnectionState)[keyof typeof MCPConnectionState];\n\nexport type MCPTransportOptions = (\n | SSEClientTransportOptions\n | StreamableHTTPClientTransportOptions\n) & {\n authProvider?: AgentsOAuthProvider;\n type?: TransportType;\n};\n\nexport type MCPClientConnectionResult = {\n state: MCPConnectionState;\n error?: Error;\n transport?: BaseTransportType;\n};\n\n/**\n * Result of a discovery operation.\n * success indicates whether discovery completed successfully.\n * error is present when success is false.\n */\nexport type MCPDiscoveryResult = {\n success: boolean;\n error?: string;\n};\n\nexport class MCPClientConnection {\n client: Client;\n connectionState: MCPConnectionState = 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 /** Tracks in-flight discovery to allow cancellation */\n private _discoveryAbortController: AbortController | undefined;\n\n private readonly _onObservabilityEvent = new Emitter<MCPObservabilityEvent>();\n public readonly onObservabilityEvent: Event<MCPObservabilityEvent> =\n this._onObservabilityEvent.event;\n\n 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, if authentication is required, the connection will be in the AUTHENTICATING state\n * Sets connection state based on the result and emits observability events\n *\n * @returns Error message if connection failed, undefined otherwise\n */\n async init(): Promise<string | undefined> {\n const transportType = this.options.transport.type;\n if (!transportType) {\n throw new Error(\"Transport type must be specified\");\n }\n\n const res = await this.tryConnect(transportType);\n\n // Set the connection state\n this.connectionState = res.state;\n\n // Handle the result and emit appropriate events\n if (res.state === MCPConnectionState.CONNECTED && res.transport) {\n // Set up elicitation request handler after successful connection\n this.client.setRequestHandler(\n ElicitRequestSchema,\n async (request: ElicitRequest) => {\n return await this.handleElicitationRequest(request);\n }\n );\n\n this.lastConnectedTransport = res.transport;\n\n this._onObservabilityEvent.fire({\n type: \"mcp:client:connect\",\n displayMessage: `Connected successfully using ${res.transport} transport for ${this.url.toString()}`,\n payload: {\n url: this.url.toString(),\n transport: res.transport,\n state: this.connectionState\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n return undefined;\n } else if (res.state === MCPConnectionState.FAILED && res.error) {\n const errorMessage = toErrorMessage(res.error);\n this._onObservabilityEvent.fire({\n type: \"mcp:client:connect\",\n displayMessage: `Failed to connect to ${this.url.toString()}: ${errorMessage}`,\n payload: {\n url: this.url.toString(),\n transport: transportType,\n state: this.connectionState,\n error: errorMessage\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n return errorMessage;\n }\n return undefined;\n }\n\n /**\n * Finish OAuth by probing transports based on configured type.\n * - Explicit: finish on that transport\n * - Auto: try streamable-http, then sse on 404/405/Not Implemented\n */\n private async finishAuthProbe(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 !== MCPConnectionState.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 = MCPConnectionState.CONNECTING;\n } catch (error) {\n this.connectionState = MCPConnectionState.FAILED;\n throw error;\n }\n }\n\n /**\n * Discover server capabilities and register tools, resources, prompts, and templates.\n * This method does the work but does not manage connection state - that's handled by discover().\n */\n async discoverAndRegister(): Promise<void> {\n this.serverCapabilities = this.client.getServerCapabilities();\n if (!this.serverCapabilities) {\n throw new Error(\"The MCP Server failed to return server capabilities\");\n }\n\n // Build list of operations to perform based on server capabilities\n type DiscoveryResult =\n | string\n | undefined\n | Tool[]\n | Resource[]\n | Prompt[]\n | ResourceTemplate[];\n const operations: Promise<DiscoveryResult>[] = [];\n const operationNames: string[] = [];\n\n // Instructions (always try to fetch if available)\n operations.push(Promise.resolve(this.client.getInstructions()));\n operationNames.push(\"instructions\");\n\n // Only register capabilities that the server advertises\n if (this.serverCapabilities.tools) {\n operations.push(this.registerTools());\n operationNames.push(\"tools\");\n }\n\n if (this.serverCapabilities.resources) {\n operations.push(this.registerResources());\n operationNames.push(\"resources\");\n }\n\n if (this.serverCapabilities.prompts) {\n operations.push(this.registerPrompts());\n operationNames.push(\"prompts\");\n }\n\n if (this.serverCapabilities.resources) {\n operations.push(this.registerResourceTemplates());\n operationNames.push(\"resource templates\");\n }\n\n try {\n const results = await Promise.all(operations);\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n const name = operationNames[i];\n\n switch (name) {\n case \"instructions\":\n this.instructions = result as string | undefined;\n break;\n case \"tools\":\n this.tools = result as Tool[];\n break;\n case \"resources\":\n this.resources = result as Resource[];\n break;\n case \"prompts\":\n this.prompts = result as Prompt[];\n break;\n case \"resource templates\":\n this.resourceTemplates = result as ResourceTemplate[];\n break;\n }\n }\n } catch (error) {\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n displayMessage: `Failed to discover capabilities for ${this.url.toString()}: ${toErrorMessage(error)}`,\n payload: {\n url: this.url.toString(),\n error: toErrorMessage(error)\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n\n throw error;\n }\n }\n\n /**\n * Discover server capabilities with timeout and cancellation support.\n * If called while a previous discovery is in-flight, the previous discovery will be aborted.\n *\n * @param options Optional configuration\n * @param options.timeoutMs Timeout in milliseconds (default: 15000)\n * @returns Result indicating success/failure with optional error message\n */\n async discover(\n options: { timeoutMs?: number } = {}\n ): Promise<MCPDiscoveryResult> {\n const { timeoutMs = 15000 } = options;\n\n // Check if state allows discovery\n if (\n this.connectionState !== MCPConnectionState.CONNECTED &&\n this.connectionState !== MCPConnectionState.READY\n ) {\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n displayMessage: `Discovery skipped for ${this.url.toString()}, state is ${this.connectionState}`,\n payload: {\n url: this.url.toString(),\n state: this.connectionState\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n return {\n success: false,\n error: `Discovery skipped - connection in ${this.connectionState} state`\n };\n }\n\n // Cancel any previous in-flight discovery\n if (this._discoveryAbortController) {\n this._discoveryAbortController.abort();\n this._discoveryAbortController = undefined;\n }\n\n // Create a new AbortController for this discovery\n const abortController = new AbortController();\n this._discoveryAbortController = abortController;\n\n this.connectionState = MCPConnectionState.DISCOVERING;\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n try {\n // Create timeout promise\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(\n () => reject(new Error(`Discovery timed out after ${timeoutMs}ms`)),\n timeoutMs\n );\n });\n\n // Check if aborted before starting\n if (abortController.signal.aborted) {\n throw new Error(\"Discovery was cancelled\");\n }\n\n // Create an abort promise that rejects when signal fires\n const abortPromise = new Promise<never>((_, reject) => {\n abortController.signal.addEventListener(\"abort\", () => {\n reject(new Error(\"Discovery was cancelled\"));\n });\n });\n\n await Promise.race([\n this.discoverAndRegister(),\n timeoutPromise,\n abortPromise\n ]);\n\n // Clear timeout on success\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n\n // Discovery succeeded - transition to ready\n this.connectionState = MCPConnectionState.READY;\n\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n displayMessage: `Discovery completed for ${this.url.toString()}`,\n payload: {\n url: this.url.toString()\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n\n return { success: true };\n } catch (e) {\n // Always clear the timeout\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n\n // Return to CONNECTED state so user can retry discovery\n this.connectionState = MCPConnectionState.CONNECTED;\n\n const error = e instanceof Error ? e.message : String(e);\n return { success: false, error };\n } finally {\n // Clean up the abort controller\n this._discoveryAbortController = undefined;\n }\n }\n\n /**\n * Cancel any in-flight discovery operation.\n * Called when closing the connection.\n */\n cancelDiscovery(): void {\n if (this._discoveryAbortController) {\n this._discoveryAbortController.abort();\n this._discoveryAbortController = undefined;\n }\n }\n\n /**\n * Notification handler registration for tools\n * Should only be called if serverCapabilities.tools exists\n */\n async registerTools(): Promise<Tool[]> {\n if (this.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 /**\n * Notification handler registration for resources\n * Should only be called if serverCapabilities.resources exists\n */\n async registerResources(): Promise<Resource[]> {\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 /**\n * Notification handler registration for prompts\n * Should only be called if serverCapabilities.prompts exists\n */\n async registerPrompts(): Promise<Prompt[]> {\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 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(\n transportType: TransportType\n ): Promise<MCPClientConnectionResult> {\n const transports: BaseTransportType[] =\n transportType === \"auto\" ? [\"streamable-http\", \"sse\"] : [transportType];\n\n for (const currentTransportType of transports) {\n const isLastTransport =\n currentTransportType === transports[transports.length - 1];\n const hasFallback =\n transportType === \"auto\" &&\n currentTransportType === \"streamable-http\" &&\n !isLastTransport;\n\n const transport = this.getTransport(currentTransportType);\n\n try {\n await this.client.connect(transport);\n\n return {\n state: MCPConnectionState.CONNECTED,\n transport: currentTransportType\n };\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e));\n\n if (isUnauthorized(error)) {\n return {\n state: MCPConnectionState.AUTHENTICATING\n };\n }\n\n if (isTransportNotImplemented(error) && hasFallback) {\n // Try the next transport\n continue;\n }\n\n return {\n state: MCPConnectionState.FAILED,\n error\n };\n }\n }\n\n // Should never reach here\n return {\n state: MCPConnectionState.FAILED,\n error: new Error(\"No transports available\")\n };\n }\n\n private _capabilityErrorHandler<T>(empty: T, method: string) {\n return (e: { code: number }) => {\n // server is badly behaved and returning invalid capabilities. This commonly occurs for resource templates\n if (e.code === -32601) {\n const url = this.url.toString();\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n 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 { CfWorkerJsonSchemaValidator } from \"@modelcontextprotocol/sdk/validation/cfworker-provider.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 MCPConnectionState,\n type MCPTransportOptions\n} from \"./client-connection\";\nimport { toErrorMessage } from \"./errors\";\nimport type { TransportType } from \"./types\";\nimport type { MCPServerRow } from \"./client-storage\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\nimport { DurableObjectOAuthClientProvider } from \"./do-oauth-client-provider\";\n\nconst defaultClientOptions: ConstructorParameters<typeof Client>[1] = {\n jsonSchemaValidator: new CfWorkerJsonSchemaValidator()\n};\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 * Discriminated union ensures error is present only on failure.\n */\nexport type MCPConnectionResult =\n | {\n state: typeof MCPConnectionState.FAILED;\n error: string;\n }\n | {\n state: typeof MCPConnectionState.AUTHENTICATING;\n authUrl: string;\n clientId?: string;\n }\n | {\n state: typeof MCPConnectionState.CONNECTED;\n };\n\n/**\n * Result of discovering server capabilities.\n * success indicates whether discovery completed successfully.\n * state is the current connection state at time of return.\n * error is present when success is false.\n */\nexport type MCPDiscoverResult = {\n success: boolean;\n state: MCPConnectionState;\n error?: string;\n};\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: DurableObjectStorage;\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: DurableObjectStorage;\n private _isRestored = false;\n\n /** @internal Protected for testing purposes. */\n protected readonly _onObservabilityEvent =\n new Emitter<MCPObservabilityEvent>();\n public readonly onObservabilityEvent: Event<MCPObservabilityEvent> =\n this._onObservabilityEvent.event;\n\n private readonly _onServerStateChanged = new Emitter<void>();\n /**\n * Event that fires whenever any MCP server state changes (registered, connected, removed, etc.)\n * This is useful for broadcasting server state to clients.\n */\n public readonly onServerStateChanged: Event<void> =\n this._onServerStateChanged.event;\n\n /**\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 if (!options.storage) {\n throw new Error(\n \"MCPClientManager requires a valid DurableObjectStorage instance\"\n );\n }\n this._storage = options.storage;\n }\n\n // SQL helper - runs a query and returns results as array\n private sql<T extends Record<string, SqlStorageValue>>(\n query: string,\n ...bindings: SqlStorageValue[]\n ): T[] {\n return [...this._storage.sql.exec<T>(query, ...bindings)];\n }\n\n // Storage operations\n private saveServerToStorage(server: MCPServerRow): void {\n this.sql(\n `INSERT OR REPLACE INTO cf_agents_mcp_servers (\n id, name, server_url, client_id, auth_url, callback_url, server_options\n ) VALUES (?, ?, ?, ?, ?, ?, ?)`,\n server.id,\n server.name,\n server.server_url,\n server.client_id ?? null,\n server.auth_url ?? null,\n server.callback_url,\n server.server_options ?? null\n );\n }\n\n private removeServerFromStorage(serverId: string): void {\n this.sql(\"DELETE FROM cf_agents_mcp_servers WHERE id = ?\", serverId);\n }\n\n private getServersFromStorage(): MCPServerRow[] {\n return this.sql<MCPServerRow>(\n \"SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers\"\n );\n }\n\n private clearServerAuthUrl(serverId: string): void {\n this.sql(\n \"UPDATE cf_agents_mcp_servers SET auth_url = NULL WHERE id = ?\",\n serverId\n );\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 if (!this._storage) {\n throw new Error(\n \"Cannot create auth provider: storage is not initialized\"\n );\n }\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 const servers = this.getServersFromStorage();\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 === MCPConnectionState.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 === MCPConnectionState.AUTHENTICATING ||\n existingConn.connectionState === MCPConnectionState.CONNECTING ||\n existingConn.connectionState === MCPConnectionState.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 === MCPConnectionState.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 const conn = 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 // If auth_url exists, OAuth flow is in progress - set state and wait for callback\n if (server.auth_url) {\n conn.connectionState = MCPConnectionState.AUTHENTICATING;\n continue;\n }\n\n // Start connection in background (don't await) to avoid blocking the DO\n this._restoreServer(server.id);\n }\n\n this._isRestored = true;\n }\n\n /**\n * Internal method to restore a single server connection and discovery\n */\n private async _restoreServer(serverId: string): Promise<void> {\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 const connectResult = await this.connectToServer(serverId).catch(\n (error) => {\n console.error(`Error connecting to ${serverId}:`, error);\n return null;\n }\n );\n\n if (connectResult?.state === MCPConnectionState.CONNECTED) {\n const discoverResult = await this.discoverIfConnected(serverId);\n if (discoverResult && !discoverResult.success) {\n console.error(`Error discovering ${serverId}:`, discoverResult.error);\n }\n }\n }\n\n /**\n * Connect to and register an MCP server\n *\n * @deprecated This method is maintained for backward compatibility.\n * For new code, use registerServer() and connectToServer() separately.\n *\n * @param url Server URL\n * @param options Connection options\n * @returns Object with server ID, auth URL (if OAuth), and client ID (if OAuth)\n */\n async connect(\n url: string,\n options: {\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. this will try connect\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\n // Reinitialize connection\n await this.mcpConnections[id].init();\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 ===\n MCPConnectionState.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 // If connection is connected, discover capabilities\n const discoverResult = await this.discoverIfConnected(id);\n if (discoverResult && !discoverResult.success) {\n throw new Error(\n `Failed to discover server capabilities: ${discoverResult.error}`\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 * @returns The connection object (existing or newly created)\n */\n private createConnection(\n id: string,\n url: string,\n options: {\n client?: ConstructorParameters<typeof Client>[1];\n transport: MCPTransportOptions;\n }\n ): MCPClientConnection {\n // Return existing connection if already exists\n if (this.mcpConnections[id]) {\n return this.mcpConnections[id];\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: { ...defaultClientOptions, ...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 return this.mcpConnections[id];\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 (exclude authProvider since it's recreated during restore)\n const { authProvider: _, ...transportWithoutAuth } =\n options.transport ?? {};\n this.saveServerToStorage({\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: transportWithoutAuth\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, returns `{ state: \"authenticating\", authUrl, clientId? }`.\n * The user must complete the OAuth flow via the authUrl, which triggers a\n * callback handled by `handleCallbackRequest()`.\n *\n * For non-OAuth servers, establishes the transport connection and returns\n * `{ state: \"connected\" }`. Call `discoverIfConnected()` afterwards to\n * discover capabilities and transition to \"ready\" state.\n *\n * @param id Server ID (must be registered first via registerServer())\n * @returns Connection result with current state and OAuth info (if applicable)\n */\n async connectToServer(id: string): Promise<MCPConnectionResult> {\n 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 const error = await conn.init();\n this._onServerStateChanged.fire();\n\n switch (conn.connectionState) {\n case MCPConnectionState.FAILED:\n return {\n state: conn.connectionState,\n error: error ?? \"Unknown connection error\"\n };\n\n case MCPConnectionState.AUTHENTICATING: {\n const authUrl = conn.options.transport.authProvider?.authUrl;\n const redirectUrl = conn.options.transport.authProvider?.redirectUrl;\n\n if (!authUrl || !redirectUrl) {\n return {\n state: MCPConnectionState.FAILED,\n error: `OAuth configuration incomplete: missing ${!authUrl ? \"authUrl\" : \"redirectUrl\"}`\n };\n }\n\n const clientId = conn.options.transport.authProvider?.clientId;\n\n // Update storage with auth URL and client ID\n const servers = this.getServersFromStorage();\n const serverRow = servers.find((s) => s.id === id);\n if (serverRow) {\n this.saveServerToStorage({\n ...serverRow,\n auth_url: authUrl,\n client_id: clientId ?? null\n });\n // Broadcast again so clients receive the auth_url\n this._onServerStateChanged.fire();\n }\n\n return {\n state: conn.connectionState,\n authUrl,\n clientId\n };\n }\n\n case MCPConnectionState.CONNECTED:\n return { state: conn.connectionState };\n\n default:\n return {\n state: MCPConnectionState.FAILED,\n error: `Unexpected connection state after init: ${conn.connectionState}`\n };\n }\n }\n\n private extractServerIdFromState(state: string | null): string | null {\n if (!state) return null;\n const parts = state.split(\".\");\n return parts.length === 2 ? parts[1] : null;\n }\n\n isCallbackRequest(req: Request): boolean {\n if (req.method !== \"GET\") {\n return false;\n }\n\n if (!req.url.includes(\"/callback\")) {\n return false;\n }\n\n const url = new URL(req.url);\n const state = url.searchParams.get(\"state\");\n const serverId = this.extractServerIdFromState(state);\n if (!serverId) {\n return false;\n }\n\n const servers = this.getServersFromStorage();\n return servers.some((server) => server.id === serverId);\n }\n\n async handleCallbackRequest(req: Request) {\n const url = new URL(req.url);\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 if (!state) {\n throw new Error(\"Unauthorized: no state provided\");\n }\n\n const serverId = this.extractServerIdFromState(state);\n\n if (!serverId) {\n throw new Error(\n \"No serverId found in state parameter. Expected format: {nonce}.{serverId}\"\n );\n }\n\n const servers = this.getServersFromStorage();\n const serverExists = servers.some((server) => server.id === serverId);\n\n if (!serverExists) {\n throw new Error(\n `No server found with id \"${serverId}\". Was the request matched with \\`isCallbackRequest()\\`?`\n );\n }\n\n if (this.mcpConnections[serverId] === undefined) {\n throw new Error(`Could not find serverId: ${serverId}`);\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 const authProvider = conn.options.transport.authProvider;\n authProvider.serverId = serverId;\n\n // Two-phase state validation: check first (non-destructive), consume later\n // This prevents DoS attacks where attacker consumes valid state before legitimate callback\n const stateValidation = await authProvider.checkState(state);\n if (!stateValidation.valid) {\n this.clearServerAuthUrl(serverId);\n if (this.mcpConnections[serverId]) {\n this.mcpConnections[serverId].connectionState =\n MCPConnectionState.FAILED;\n }\n this._onServerStateChanged.fire();\n return {\n serverId,\n authSuccess: false,\n authError: stateValidation.error || \"Invalid state\"\n };\n }\n\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\n if (\n this.mcpConnections[serverId].connectionState ===\n MCPConnectionState.READY ||\n this.mcpConnections[serverId].connectionState ===\n MCPConnectionState.CONNECTED\n ) {\n this.clearServerAuthUrl(serverId);\n return {\n serverId,\n authSuccess: true\n };\n }\n\n if (\n this.mcpConnections[serverId].connectionState !==\n MCPConnectionState.AUTHENTICATING\n ) {\n throw new Error(\n `Failed to authenticate: the client is in \"${this.mcpConnections[serverId].connectionState}\" state, expected \"authenticating\"`\n );\n }\n\n try {\n await authProvider.consumeState(state);\n await conn.completeAuthorization(code);\n await authProvider.deleteCodeVerifier();\n this.clearServerAuthUrl(serverId);\n this._onServerStateChanged.fire();\n\n return {\n serverId,\n authSuccess: true\n };\n } catch (authError) {\n const errorMessage =\n authError instanceof Error ? authError.message : String(authError);\n\n this._onServerStateChanged.fire();\n\n return {\n serverId,\n authSuccess: false,\n authError: errorMessage\n };\n }\n }\n\n /**\n * Discover server capabilities if connection is in CONNECTED or READY state.\n * Transitions to DISCOVERING then READY (or CONNECTED on error).\n * Can be called to refresh server capabilities (e.g., from a UI refresh button).\n *\n * If called while a previous discovery is in-flight for the same server,\n * the previous discovery will be aborted.\n *\n * @param serverId The server ID to discover\n * @param options Optional configuration\n * @param options.timeoutMs Timeout in milliseconds (default: 30000)\n * @returns Result with current state and optional error, or undefined if connection not found\n */\n async discoverIfConnected(\n serverId: string,\n options: { timeoutMs?: number } = {}\n ): Promise<MCPDiscoverResult | undefined> {\n const conn = this.mcpConnections[serverId];\n if (!conn) {\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n displayMessage: `Connection not found for ${serverId}`,\n payload: {},\n timestamp: Date.now(),\n id: nanoid()\n });\n return undefined;\n }\n\n // Delegate to connection's discover method which handles cancellation and timeout\n const result = await conn.discover(options);\n this._onServerStateChanged.fire();\n\n return {\n ...result,\n state: conn.connectionState\n };\n }\n\n /**\n * Establish connection in the background after OAuth completion\n * This method connects to the server and discovers its capabilities\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 // Skip if already discovering or ready - prevents duplicate work\n if (\n conn.connectionState === MCPConnectionState.DISCOVERING ||\n conn.connectionState === MCPConnectionState.READY\n ) {\n this._onObservabilityEvent.fire({\n type: \"mcp:client:connect\",\n displayMessage: `establishConnection skipped for ${serverId}, already in ${conn.connectionState} state`,\n payload: {\n url: conn.url.toString(),\n transport: conn.options.transport.type || \"unknown\",\n state: conn.connectionState\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n return;\n }\n\n const connectResult = await this.connectToServer(serverId);\n this._onServerStateChanged.fire();\n\n if (connectResult.state === MCPConnectionState.CONNECTED) {\n await this.discoverIfConnected(serverId);\n }\n\n this._onObservabilityEvent.fire({\n type: \"mcp:client:connect\",\n displayMessage: `establishConnection completed for ${serverId}, final state: ${conn.connectionState}`,\n payload: {\n url: conn.url.toString(),\n transport: conn.options.transport.type || \"unknown\",\n state: conn.connectionState\n },\n timestamp: Date.now(),\n id: nanoid()\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 !== MCPConnectionState.READY &&\n conn.connectionState !== MCPConnectionState.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 const content = result.content as\n | Array<{ type: string; text?: string }>\n | undefined;\n const textContent = content?.[0];\n const message =\n textContent?.type === \"text\" && textContent.text\n ? textContent.text\n : \"Tool call failed\";\n throw new Error(message);\n }\n return result;\n },\n inputSchema: 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 active in-memory connections to MCP servers.\n *\n * Note: This only closes the transport connections - it does NOT remove\n * servers from storage. Servers will still be listed and their callback\n * URLs will still match incoming OAuth requests.\n *\n * Use removeServer() instead if you want to fully clean up a server\n * (closes connection AND removes from storage).\n */\n async closeAllConnections() {\n const ids = Object.keys(this.mcpConnections);\n\n // Cancel all in-flight discoveries\n for (const id of ids) {\n this.mcpConnections[id].cancelDiscovery();\n }\n\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\n // Cancel any in-flight discovery\n this.mcpConnections[id].cancelDiscovery();\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 - closes connection if active and removes from storage.\n */\n async removeServer(serverId: string): Promise<void> {\n if (this.mcpConnections[serverId]) {\n try {\n await this.closeConnection(serverId);\n } catch (_e) {\n // Ignore errors when closing\n }\n }\n this.removeServerFromStorage(serverId);\n this._onServerStateChanged.fire();\n }\n\n /**\n * List all MCP servers from storage\n */\n listServers(): MCPServerRow[] {\n return this.getServersFromStorage();\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 }\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,kBAAb,MAAmD;;gBACT,EAAE;;CAE1C,IAA0B,GAAS;AACjC,OAAK,OAAO,KAAK,EAAE;AACnB,SAAO;;CAGT,UAAgB;AACd,SAAO,KAAK,OAAO,OACjB,KAAI;AACF,QAAK,OAAO,KAAK,CAAE,SAAS;UACtB;;;AASd,IAAa,UAAb,MAA8C;;oCACF,IAAI,KAAK;gBAEvB,aAAa;AACvC,QAAK,WAAW,IAAI,SAAS;AAC7B,UAAO,mBAAmB,KAAK,WAAW,OAAO,SAAS,CAAC;;;CAG7D,KAAK,MAAe;AAClB,OAAK,MAAM,YAAY,CAAC,GAAG,KAAK,WAAW,CACzC,KAAI;AACF,YAAS,KAAK;WACP,KAAK;AAEZ,WAAQ,MAAM,2BAA2B,IAAI;;;CAKnD,UAAgB;AACd,OAAK,WAAW,OAAO;;;;;;ACjD3B,SAAgB,eAAe,OAAwB;AACrD,QAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;;AAG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ACD;;;AAWL,SAAgB,kBACd,YACA,MACmB;AAenB,QAda,OAAO,QAAQ,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"}
@@ -1,5 +1,5 @@
1
- import { t as MCPObservabilityEvent } from "./mcp-AK39tq6H.js";
2
- import { t as AgentsOAuthProvider } from "./do-oauth-client-provider-BH9zFtSy.js";
1
+ import { t as MCPObservabilityEvent } from "./mcp-BwPscEiF.js";
2
+ import { t as AgentsOAuthProvider } from "./do-oauth-client-provider-BqnOQzjy.js";
3
3
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
4
  import {
5
5
  SSEClientTransport,
@@ -67,17 +67,11 @@ interface ServeOptions {
67
67
  * - Any state can transition to FAILED on error
68
68
  */
69
69
  declare const MCPConnectionState: {
70
- /** Waiting for OAuth authorization to complete */
71
- readonly AUTHENTICATING: "authenticating";
72
- /** Establishing transport connection to MCP server */
73
- readonly CONNECTING: "connecting";
74
- /** Transport connection established */
75
- readonly CONNECTED: "connected";
76
- /** Discovering server capabilities (tools, resources, prompts) */
77
- readonly DISCOVERING: "discovering";
78
- /** Fully connected and ready to use */
79
- readonly READY: "ready";
80
- /** Connection failed at some point */
70
+ /** Waiting for OAuth authorization to complete */ readonly AUTHENTICATING: "authenticating"; /** Establishing transport connection to MCP server */
71
+ readonly CONNECTING: "connecting"; /** Transport connection established */
72
+ readonly CONNECTED: "connected"; /** Discovering server capabilities (tools, resources, prompts) */
73
+ readonly DISCOVERING: "discovering"; /** Fully connected and ready to use */
74
+ readonly READY: "ready"; /** Connection failed at some point */
81
75
  readonly FAILED: "failed";
82
76
  };
83
77
  /**
@@ -966,4 +960,4 @@ export {
966
960
  MCPClientManager as t,
967
961
  MCPConnectionState as u
968
962
  };
969
- //# sourceMappingURL=client-Cxno-5sH.d.ts.map
963
+ //# sourceMappingURL=client-DGpERepg.d.ts.map
package/dist/client.d.ts CHANGED
@@ -6,7 +6,6 @@ import {
6
6
  } from "partysocket";
7
7
 
8
8
  //#region src/client.d.ts
9
-
10
9
  /**
11
10
  * Options for creating an AgentClient
12
11
  */
@@ -14,39 +13,79 @@ type AgentClientOptions<State = unknown> = Omit<
14
13
  PartySocketOptions,
15
14
  "party" | "room"
16
15
  > & {
17
- /** Name of the agent to connect to */
18
- agent: string;
19
- /** Name of the specific Agent instance */
16
+ /** Name of the agent to connect to (ignored if basePath is set) */ agent: string; /** Name of the specific Agent instance (ignored if basePath is set) */
20
17
  name?: string;
21
- /** Called when the Agent's state is updated */
18
+ /**
19
+ * Full URL path - bypasses agent/name URL construction.
20
+ * When set, the client connects to this path directly.
21
+ * Server must handle routing manually (e.g., with getAgentByName + fetch).
22
+ * @example
23
+ * // Client connects to /user, server routes based on session
24
+ * useAgent({ agent: "UserAgent", basePath: "user" })
25
+ */
26
+ basePath?: string; /** Called when the Agent's state is updated */
22
27
  onStateUpdate?: (state: State, source: "server" | "client") => void;
28
+ /**
29
+ * Called when the server sends the agent's identity on connect.
30
+ * Useful when using basePath, as the actual instance name is determined server-side.
31
+ * @param name The actual agent instance name
32
+ * @param agent The agent class name (kebab-case)
33
+ */
34
+ onIdentity?: (name: string, agent: string) => void;
35
+ /**
36
+ * Called when identity changes on reconnect (different instance than before).
37
+ * If not provided and identity changes, a warning will be logged.
38
+ * @param oldName Previous instance name
39
+ * @param newName New instance name
40
+ * @param oldAgent Previous agent class name
41
+ * @param newAgent New agent class name
42
+ */
43
+ onIdentityChange?: (
44
+ oldName: string,
45
+ newName: string,
46
+ oldAgent: string,
47
+ newAgent: string
48
+ ) => void;
49
+ /**
50
+ * Additional path to append to the URL.
51
+ * Works with both standard routing and basePath.
52
+ * @example
53
+ * // With basePath: /user/settings
54
+ * { basePath: "user", path: "settings" }
55
+ * // Standard: /agents/my-agent/room/settings
56
+ * { agent: "MyAgent", name: "room", path: "settings" }
57
+ */
58
+ path?: string;
23
59
  };
24
60
  /**
25
61
  * Options for streaming RPC calls
26
62
  */
27
63
  type StreamOptions = {
28
- /** Called when a chunk of data is received */
29
- onChunk?: (chunk: unknown) => void;
30
- /** Called when the stream ends */
31
- onDone?: (finalChunk: unknown) => void;
32
- /** Called when an error occurs */
64
+ /** Called when a chunk of data is received */ onChunk?: (
65
+ chunk: unknown
66
+ ) => void; /** Called when the stream ends */
67
+ onDone?: (finalChunk: unknown) => void; /** Called when an error occurs */
33
68
  onError?: (error: string) => void;
34
69
  };
70
+ /**
71
+ * Options for RPC calls
72
+ */
73
+ type CallOptions = {
74
+ /** Timeout in milliseconds. If the call doesn't complete within this time, it will be rejected. */ timeout?: number; /** Streaming options for handling streaming responses */
75
+ stream?: StreamOptions;
76
+ };
35
77
  /**
36
78
  * Options for the agentFetch function
37
79
  */
38
80
  type AgentClientFetchOptions = Omit<PartyFetchOptions, "party" | "room"> & {
39
- /** Name of the agent to connect to */
40
- agent: string;
41
- /** Name of the specific Agent instance */
81
+ /** Name of the agent to connect to (ignored if basePath is set) */ agent: string; /** Name of the specific Agent instance (ignored if basePath is set) */
42
82
  name?: string;
83
+ /**
84
+ * Full URL path - bypasses agent/name URL construction.
85
+ * When set, the request is made to this path directly.
86
+ */
87
+ basePath?: string;
43
88
  };
44
- /**
45
- * Convert a camelCase string to a kebab-case string
46
- * @param str The string to convert
47
- * @returns The kebab-case string
48
- */
49
- declare function camelCaseToKebabCase(str: string): string;
50
89
  /**
51
90
  * WebSocket client for connecting to an Agent
52
91
  */
@@ -57,26 +96,56 @@ declare class AgentClient<State = unknown> extends PartySocket {
57
96
  static fetch(_opts: PartyFetchOptions): Promise<Response>;
58
97
  agent: string;
59
98
  name: string;
99
+ /**
100
+ * Whether the client has received identity from the server.
101
+ * Becomes true after the first identity message is received.
102
+ * Resets to false on connection close.
103
+ */
104
+ identified: boolean;
105
+ /**
106
+ * Promise that resolves when identity has been received from the server.
107
+ * Useful for waiting before making calls that depend on knowing the instance.
108
+ * Resets on connection close so it can be awaited again after reconnect.
109
+ */
110
+ get ready(): Promise<void>;
60
111
  private options;
61
112
  private _pendingCalls;
113
+ private _readyPromise;
114
+ private _resolveReady;
115
+ private _previousName;
116
+ private _previousAgent;
117
+ private _resetReady;
62
118
  constructor(options: AgentClientOptions<State>);
119
+ /**
120
+ * Reject all pending RPC calls with the given reason.
121
+ */
122
+ private _rejectPendingCalls;
63
123
  setState(state: State): void;
124
+ /**
125
+ * Close the connection and immediately reject all pending RPC calls.
126
+ * This provides immediate feedback on intentional close rather than
127
+ * waiting for the WebSocket close handshake to complete.
128
+ *
129
+ * Note: Any calls made after `close()` will be rejected when the
130
+ * underlying WebSocket close event fires.
131
+ */
132
+ close(code?: number, reason?: string): void;
64
133
  /**
65
134
  * Call a method on the Agent
66
135
  * @param method Name of the method to call
67
136
  * @param args Arguments to pass to the method
68
- * @param streamOptions Options for handling streaming responses
137
+ * @param options Options for the call (timeout, streaming) or legacy StreamOptions
69
138
  * @returns Promise that resolves with the method's return value
70
139
  */
71
140
  call<T extends SerializableReturnValue>(
72
141
  method: string,
73
142
  args?: SerializableValue[],
74
- streamOptions?: StreamOptions
143
+ options?: CallOptions | StreamOptions
75
144
  ): Promise<T>;
76
145
  call<T = unknown>(
77
146
  method: string,
78
147
  args?: unknown[],
79
- streamOptions?: StreamOptions
148
+ options?: CallOptions | StreamOptions
80
149
  ): Promise<T>;
81
150
  }
82
151
  /**
@@ -94,8 +163,8 @@ export {
94
163
  AgentClient,
95
164
  AgentClientFetchOptions,
96
165
  AgentClientOptions,
166
+ CallOptions,
97
167
  StreamOptions,
98
- agentFetch,
99
- camelCaseToKebabCase
168
+ agentFetch
100
169
  };
101
170
  //# sourceMappingURL=client.d.ts.map