hono-agents 2.0.6 → 2.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -138,7 +138,7 @@ var DurableObjectOAuthClientProvider = class {
138
138
  };
139
139
 
140
140
  //#endregion
141
- //#region ../agents/dist/client-BZq9qau2.js
141
+ //#region ../agents/dist/client-CFhjXCiO.js
142
142
  function toDisposable(fn) {
143
143
  return { dispose: fn };
144
144
  }
@@ -1133,7 +1133,7 @@ var MCPClientManager = class {
1133
1133
  async removeServer(serverId) {
1134
1134
  if (this.mcpConnections[serverId]) try {
1135
1135
  await this.closeConnection(serverId);
1136
- } catch (e) {}
1136
+ } catch (_e) {}
1137
1137
  this.removeServerFromStorage(serverId);
1138
1138
  this._onServerStateChanged.fire();
1139
1139
  }
@@ -1212,7 +1212,7 @@ function getNamespacedData(mcpClients, type) {
1212
1212
  }
1213
1213
 
1214
1214
  //#endregion
1215
- //#region ../agents/dist/src-D_KKH_4c.js
1215
+ //#region ../agents/dist/src-tXpYCgas.js
1216
1216
  /**
1217
1217
  * A generic observability implementation that logs events to the console.
1218
1218
  */
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Agent","env"],"sources":["../../agents/dist/ai-types-CrMqkwc_.js","../../agents/dist/client-B3SR12TQ.js","../../agents/dist/do-oauth-client-provider-CwqK5SXm.js","../../agents/dist/client-BZq9qau2.js","../../agents/dist/src-D_KKH_4c.js","../src/index.ts"],"sourcesContent":["//#region src/ai-types.ts\n/**\n* Enum for message types to improve type safety and maintainability\n*/\nlet MessageType = /* @__PURE__ */ function(MessageType$1) {\n\tMessageType$1[\"CF_AGENT_CHAT_MESSAGES\"] = \"cf_agent_chat_messages\";\n\tMessageType$1[\"CF_AGENT_USE_CHAT_REQUEST\"] = \"cf_agent_use_chat_request\";\n\tMessageType$1[\"CF_AGENT_USE_CHAT_RESPONSE\"] = \"cf_agent_use_chat_response\";\n\tMessageType$1[\"CF_AGENT_CHAT_CLEAR\"] = \"cf_agent_chat_clear\";\n\tMessageType$1[\"CF_AGENT_CHAT_REQUEST_CANCEL\"] = \"cf_agent_chat_request_cancel\";\n\t/** Sent by server when client connects and there's an active stream to resume */\n\tMessageType$1[\"CF_AGENT_STREAM_RESUMING\"] = \"cf_agent_stream_resuming\";\n\t/** Sent by client to acknowledge stream resuming notification and request chunks */\n\tMessageType$1[\"CF_AGENT_STREAM_RESUME_ACK\"] = \"cf_agent_stream_resume_ack\";\n\tMessageType$1[\"CF_AGENT_MCP_SERVERS\"] = \"cf_agent_mcp_servers\";\n\tMessageType$1[\"CF_MCP_AGENT_EVENT\"] = \"cf_mcp_agent_event\";\n\tMessageType$1[\"CF_AGENT_STATE\"] = \"cf_agent_state\";\n\tMessageType$1[\"RPC\"] = \"rpc\";\n\treturn MessageType$1;\n}({});\n\n//#endregion\nexport { MessageType as t };\n//# sourceMappingURL=ai-types-CrMqkwc_.js.map","import { t as MessageType } from \"./ai-types-CrMqkwc_.js\";\nimport { PartySocket } from \"partysocket\";\n\n//#region src/client.ts\n/**\n* Convert a camelCase string to a kebab-case string\n* @param str The string to convert\n* @returns The kebab-case string\n*/\nfunction camelCaseToKebabCase(str) {\n\tif (str === str.toUpperCase() && str !== str.toLowerCase()) return str.toLowerCase().replace(/_/g, \"-\");\n\tlet kebabified = str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n\tkebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n\treturn kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n/**\n* WebSocket client for connecting to an Agent\n*/\nvar AgentClient = class extends PartySocket {\n\t/**\n\t* @deprecated Use agentFetch instead\n\t*/\n\tstatic fetch(_opts) {\n\t\tthrow new Error(\"AgentClient.fetch is not implemented, use agentFetch instead\");\n\t}\n\tconstructor(options) {\n\t\tconst agentNamespace = camelCaseToKebabCase(options.agent);\n\t\tsuper({\n\t\t\tparty: agentNamespace,\n\t\t\tprefix: \"agents\",\n\t\t\troom: options.name || \"default\",\n\t\t\t...options\n\t\t});\n\t\tthis._pendingCalls = /* @__PURE__ */ new Map();\n\t\tthis.agent = agentNamespace;\n\t\tthis.name = options.name || \"default\";\n\t\tthis.options = options;\n\t\tthis.addEventListener(\"message\", (event) => {\n\t\t\tif (typeof event.data === \"string\") {\n\t\t\t\tlet parsedMessage;\n\t\t\t\ttry {\n\t\t\t\t\tparsedMessage = JSON.parse(event.data);\n\t\t\t\t} catch (_error) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (parsedMessage.type === MessageType.CF_AGENT_STATE) {\n\t\t\t\t\tthis.options.onStateUpdate?.(parsedMessage.state, \"server\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (parsedMessage.type === MessageType.RPC) {\n\t\t\t\t\tconst response = parsedMessage;\n\t\t\t\t\tconst pending = this._pendingCalls.get(response.id);\n\t\t\t\t\tif (!pending) return;\n\t\t\t\t\tif (!response.success) {\n\t\t\t\t\t\tpending.reject(new Error(response.error));\n\t\t\t\t\t\tthis._pendingCalls.delete(response.id);\n\t\t\t\t\t\tpending.stream?.onError?.(response.error);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"done\" in response) if (response.done) {\n\t\t\t\t\t\tpending.resolve(response.result);\n\t\t\t\t\t\tthis._pendingCalls.delete(response.id);\n\t\t\t\t\t\tpending.stream?.onDone?.(response.result);\n\t\t\t\t\t} else pending.stream?.onChunk?.(response.result);\n\t\t\t\t\telse {\n\t\t\t\t\t\tpending.resolve(response.result);\n\t\t\t\t\t\tthis._pendingCalls.delete(response.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\tsetState(state) {\n\t\tthis.send(JSON.stringify({\n\t\t\tstate,\n\t\t\ttype: MessageType.CF_AGENT_STATE\n\t\t}));\n\t\tthis.options.onStateUpdate?.(state, \"client\");\n\t}\n\tasync call(method, args = [], streamOptions) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst id = Math.random().toString(36).slice(2);\n\t\t\tthis._pendingCalls.set(id, {\n\t\t\t\treject,\n\t\t\t\tresolve: (value) => resolve(value),\n\t\t\t\tstream: streamOptions,\n\t\t\t\ttype: null\n\t\t\t});\n\t\t\tconst request = {\n\t\t\t\targs,\n\t\t\t\tid,\n\t\t\t\tmethod,\n\t\t\t\ttype: MessageType.RPC\n\t\t\t};\n\t\t\tthis.send(JSON.stringify(request));\n\t\t});\n\t}\n};\n/**\n* Make an HTTP request to an Agent\n* @param opts Connection options\n* @param init Request initialization options\n* @returns Promise resolving to a Response\n*/\nfunction agentFetch(opts, init) {\n\tconst agentNamespace = camelCaseToKebabCase(opts.agent);\n\treturn PartySocket.fetch({\n\t\tparty: agentNamespace,\n\t\tprefix: \"agents\",\n\t\troom: opts.name || \"default\",\n\t\t...opts\n\t}, init);\n}\n\n//#endregion\nexport { agentFetch as n, camelCaseToKebabCase as r, AgentClient as t };\n//# sourceMappingURL=client-B3SR12TQ.js.map","import { nanoid } from \"nanoid\";\n\n//#region src/mcp/do-oauth-client-provider.ts\nvar DurableObjectOAuthClientProvider = class {\n\tconstructor(storage, clientName, baseRedirectUrl) {\n\t\tthis.storage = storage;\n\t\tthis.clientName = clientName;\n\t\tthis.baseRedirectUrl = baseRedirectUrl;\n\t\tif (!storage) throw new Error(\"DurableObjectOAuthClientProvider requires a valid DurableObjectStorage instance\");\n\t}\n\tget clientMetadata() {\n\t\treturn {\n\t\t\tclient_name: this.clientName,\n\t\t\tclient_uri: this.clientUri,\n\t\t\tgrant_types: [\"authorization_code\", \"refresh_token\"],\n\t\t\tredirect_uris: [this.redirectUrl],\n\t\t\tresponse_types: [\"code\"],\n\t\t\ttoken_endpoint_auth_method: \"none\"\n\t\t};\n\t}\n\tget clientUri() {\n\t\treturn new URL(this.redirectUrl).origin;\n\t}\n\tget redirectUrl() {\n\t\treturn `${this.baseRedirectUrl}/${this.serverId}`;\n\t}\n\tget clientId() {\n\t\tif (!this._clientId_) throw new Error(\"Trying to access clientId before it was set\");\n\t\treturn this._clientId_;\n\t}\n\tset clientId(clientId_) {\n\t\tthis._clientId_ = clientId_;\n\t}\n\tget serverId() {\n\t\tif (!this._serverId_) throw new Error(\"Trying to access serverId before it was set\");\n\t\treturn this._serverId_;\n\t}\n\tset serverId(serverId_) {\n\t\tthis._serverId_ = serverId_;\n\t}\n\tkeyPrefix(clientId) {\n\t\treturn `/${this.clientName}/${this.serverId}/${clientId}`;\n\t}\n\tclientInfoKey(clientId) {\n\t\treturn `${this.keyPrefix(clientId)}/client_info/`;\n\t}\n\tasync clientInformation() {\n\t\tif (!this._clientId_) return;\n\t\treturn await this.storage.get(this.clientInfoKey(this.clientId)) ?? void 0;\n\t}\n\tasync saveClientInformation(clientInformation) {\n\t\tawait this.storage.put(this.clientInfoKey(clientInformation.client_id), clientInformation);\n\t\tthis.clientId = clientInformation.client_id;\n\t}\n\ttokenKey(clientId) {\n\t\treturn `${this.keyPrefix(clientId)}/token`;\n\t}\n\tasync tokens() {\n\t\tif (!this._clientId_) return;\n\t\treturn await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;\n\t}\n\tasync saveTokens(tokens) {\n\t\tawait this.storage.put(this.tokenKey(this.clientId), tokens);\n\t}\n\tget authUrl() {\n\t\treturn this._authUrl_;\n\t}\n\t/**\n\t* Because this operates on the server side (but we need browser auth), we send this url back to the user\n\t* and require user interact to initiate the redirect flow\n\t*/\n\tasync redirectToAuthorization(authUrl) {\n\t\tconst stateToken = nanoid();\n\t\tauthUrl.searchParams.set(\"state\", stateToken);\n\t\tthis._authUrl_ = authUrl.toString();\n\t}\n\tcodeVerifierKey(clientId) {\n\t\treturn `${this.keyPrefix(clientId)}/code_verifier`;\n\t}\n\tasync saveCodeVerifier(verifier) {\n\t\tconst key = this.codeVerifierKey(this.clientId);\n\t\tif (await this.storage.get(key)) return;\n\t\tawait this.storage.put(key, verifier);\n\t}\n\tasync codeVerifier() {\n\t\tconst codeVerifier = await this.storage.get(this.codeVerifierKey(this.clientId));\n\t\tif (!codeVerifier) throw new Error(\"No code verifier found\");\n\t\treturn codeVerifier;\n\t}\n};\n\n//#endregion\nexport { DurableObjectOAuthClientProvider as t };\n//# sourceMappingURL=do-oauth-client-provider-CwqK5SXm.js.map","import { t as DurableObjectOAuthClientProvider } from \"./do-oauth-client-provider-CwqK5SXm.js\";\nimport { nanoid } from \"nanoid\";\nimport { CfWorkerJsonSchemaValidator } from \"@modelcontextprotocol/sdk/validation/cfworker-provider.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { ElicitRequestSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from \"@modelcontextprotocol/sdk/types.js\";\n\n//#region src/core/events.ts\nfunction toDisposable(fn) {\n\treturn { dispose: fn };\n}\nvar DisposableStore = class {\n\tconstructor() {\n\t\tthis._items = [];\n\t}\n\tadd(d) {\n\t\tthis._items.push(d);\n\t\treturn d;\n\t}\n\tdispose() {\n\t\twhile (this._items.length) try {\n\t\t\tthis._items.pop().dispose();\n\t\t} catch {}\n\t}\n};\nvar Emitter = class {\n\tconstructor() {\n\t\tthis._listeners = /* @__PURE__ */ new Set();\n\t\tthis.event = (listener) => {\n\t\t\tthis._listeners.add(listener);\n\t\t\treturn toDisposable(() => this._listeners.delete(listener));\n\t\t};\n\t}\n\tfire(data) {\n\t\tfor (const listener of [...this._listeners]) try {\n\t\t\tlistener(data);\n\t\t} catch (err) {\n\t\t\tconsole.error(\"Emitter listener error:\", err);\n\t\t}\n\t}\n\tdispose() {\n\t\tthis._listeners.clear();\n\t}\n};\n\n//#endregion\n//#region src/mcp/errors.ts\nfunction toErrorMessage(error) {\n\treturn error instanceof Error ? error.message : String(error);\n}\nfunction isUnauthorized(error) {\n\tconst msg = toErrorMessage(error);\n\treturn msg.includes(\"Unauthorized\") || msg.includes(\"401\");\n}\nfunction isTransportNotImplemented(error) {\n\tconst msg = toErrorMessage(error);\n\treturn msg.includes(\"404\") || msg.includes(\"405\") || msg.includes(\"Not Implemented\") || msg.includes(\"not implemented\");\n}\n\n//#endregion\n//#region src/mcp/client-connection.ts\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*/\nconst MCPConnectionState = {\n\tAUTHENTICATING: \"authenticating\",\n\tCONNECTING: \"connecting\",\n\tCONNECTED: \"connected\",\n\tDISCOVERING: \"discovering\",\n\tREADY: \"ready\",\n\tFAILED: \"failed\"\n};\nvar MCPClientConnection = class {\n\tconstructor(url, info, options = {\n\t\tclient: {},\n\t\ttransport: {}\n\t}) {\n\t\tthis.url = url;\n\t\tthis.options = options;\n\t\tthis.connectionState = MCPConnectionState.CONNECTING;\n\t\tthis.tools = [];\n\t\tthis.prompts = [];\n\t\tthis.resources = [];\n\t\tthis.resourceTemplates = [];\n\t\tthis._onObservabilityEvent = new Emitter();\n\t\tthis.onObservabilityEvent = this._onObservabilityEvent.event;\n\t\tthis.client = new Client(info, {\n\t\t\t...options.client,\n\t\t\tcapabilities: {\n\t\t\t\t...options.client?.capabilities,\n\t\t\t\telicitation: {}\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* Initialize a client connection, if authentication is required, the connection will be in the AUTHENTICATING state\n\t* Sets connection state based on the result and emits observability events\n\t*\n\t* @returns Error message if connection failed, undefined otherwise\n\t*/\n\tasync init() {\n\t\tconst transportType = this.options.transport.type;\n\t\tif (!transportType) throw new Error(\"Transport type must be specified\");\n\t\tconst res = await this.tryConnect(transportType);\n\t\tthis.connectionState = res.state;\n\t\tif (res.state === MCPConnectionState.CONNECTED && res.transport) {\n\t\t\tthis.client.setRequestHandler(ElicitRequestSchema, async (request) => {\n\t\t\t\treturn await this.handleElicitationRequest(request);\n\t\t\t});\n\t\t\tthis.lastConnectedTransport = res.transport;\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `Connected successfully using ${res.transport} transport for ${this.url.toString()}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl: this.url.toString(),\n\t\t\t\t\ttransport: res.transport,\n\t\t\t\t\tstate: this.connectionState\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn;\n\t\t} else if (res.state === MCPConnectionState.FAILED && res.error) {\n\t\t\tconst errorMessage = toErrorMessage(res.error);\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `Failed to connect to ${this.url.toString()}: ${errorMessage}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl: this.url.toString(),\n\t\t\t\t\ttransport: transportType,\n\t\t\t\t\tstate: this.connectionState,\n\t\t\t\t\terror: errorMessage\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn errorMessage;\n\t\t}\n\t}\n\t/**\n\t* Finish OAuth by probing transports based on configured type.\n\t* - Explicit: finish on that transport\n\t* - Auto: try streamable-http, then sse on 404/405/Not Implemented\n\t*/\n\tasync finishAuthProbe(code) {\n\t\tif (!this.options.transport.authProvider) throw new Error(\"No auth provider configured\");\n\t\tconst configuredType = this.options.transport.type;\n\t\tif (!configuredType) throw new Error(\"Transport type must be specified\");\n\t\tconst finishAuth = async (base) => {\n\t\t\tawait this.getTransport(base).finishAuth(code);\n\t\t};\n\t\tif (configuredType === \"sse\" || configuredType === \"streamable-http\") {\n\t\t\tawait finishAuth(configuredType);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait finishAuth(\"streamable-http\");\n\t\t} catch (e) {\n\t\t\tif (isTransportNotImplemented(e)) {\n\t\t\t\tawait finishAuth(\"sse\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\t/**\n\t* Complete OAuth authorization\n\t*/\n\tasync completeAuthorization(code) {\n\t\tif (this.connectionState !== MCPConnectionState.AUTHENTICATING) throw new Error(\"Connection must be in authenticating state to complete authorization\");\n\t\ttry {\n\t\t\tawait this.finishAuthProbe(code);\n\t\t\tthis.connectionState = MCPConnectionState.CONNECTING;\n\t\t} catch (error) {\n\t\t\tthis.connectionState = MCPConnectionState.FAILED;\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t* Discover server capabilities and register tools, resources, prompts, and templates.\n\t* This method does the work but does not manage connection state - that's handled by discover().\n\t*/\n\tasync discoverAndRegister() {\n\t\tthis.serverCapabilities = this.client.getServerCapabilities();\n\t\tif (!this.serverCapabilities) throw new Error(\"The MCP Server failed to return server capabilities\");\n\t\tconst operations = [];\n\t\tconst operationNames = [];\n\t\toperations.push(Promise.resolve(this.client.getInstructions()));\n\t\toperationNames.push(\"instructions\");\n\t\tif (this.serverCapabilities.tools) {\n\t\t\toperations.push(this.registerTools());\n\t\t\toperationNames.push(\"tools\");\n\t\t}\n\t\tif (this.serverCapabilities.resources) {\n\t\t\toperations.push(this.registerResources());\n\t\t\toperationNames.push(\"resources\");\n\t\t}\n\t\tif (this.serverCapabilities.prompts) {\n\t\t\toperations.push(this.registerPrompts());\n\t\t\toperationNames.push(\"prompts\");\n\t\t}\n\t\tif (this.serverCapabilities.resources) {\n\t\t\toperations.push(this.registerResourceTemplates());\n\t\t\toperationNames.push(\"resource templates\");\n\t\t}\n\t\ttry {\n\t\t\tconst results = await Promise.all(operations);\n\t\t\tfor (let i = 0; i < results.length; i++) {\n\t\t\t\tconst result = results[i];\n\t\t\t\tswitch (operationNames[i]) {\n\t\t\t\t\tcase \"instructions\":\n\t\t\t\t\t\tthis.instructions = result;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tools\":\n\t\t\t\t\t\tthis.tools = result;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"resources\":\n\t\t\t\t\t\tthis.resources = result;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"prompts\":\n\t\t\t\t\t\tthis.prompts = result;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"resource templates\":\n\t\t\t\t\t\tthis.resourceTemplates = result;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\tdisplayMessage: `Failed to discover capabilities for ${this.url.toString()}: ${toErrorMessage(error)}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl: this.url.toString(),\n\t\t\t\t\terror: toErrorMessage(error)\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t* Discover server capabilities with timeout and cancellation support.\n\t* If called while a previous discovery is in-flight, the previous discovery will be aborted.\n\t*\n\t* @param options Optional configuration\n\t* @param options.timeoutMs Timeout in milliseconds (default: 15000)\n\t* @returns Result indicating success/failure with optional error message\n\t*/\n\tasync discover(options = {}) {\n\t\tconst { timeoutMs = 15e3 } = options;\n\t\tif (this.connectionState !== MCPConnectionState.CONNECTED && this.connectionState !== MCPConnectionState.READY) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\tdisplayMessage: `Discovery skipped for ${this.url.toString()}, state is ${this.connectionState}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl: this.url.toString(),\n\t\t\t\t\tstate: this.connectionState\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: `Discovery skipped - connection in ${this.connectionState} state`\n\t\t\t};\n\t\t}\n\t\tif (this._discoveryAbortController) {\n\t\t\tthis._discoveryAbortController.abort();\n\t\t\tthis._discoveryAbortController = void 0;\n\t\t}\n\t\tconst abortController = new AbortController();\n\t\tthis._discoveryAbortController = abortController;\n\t\tthis.connectionState = MCPConnectionState.DISCOVERING;\n\t\tlet timeoutId;\n\t\ttry {\n\t\t\tconst timeoutPromise = new Promise((_, reject) => {\n\t\t\t\ttimeoutId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Discovery timed out after ${timeoutMs}ms`)), timeoutMs);\n\t\t\t});\n\t\t\tif (abortController.signal.aborted) throw new Error(\"Discovery was cancelled\");\n\t\t\tconst abortPromise = new Promise((_, reject) => {\n\t\t\t\tabortController.signal.addEventListener(\"abort\", () => {\n\t\t\t\t\treject(/* @__PURE__ */ new Error(\"Discovery was cancelled\"));\n\t\t\t\t});\n\t\t\t});\n\t\t\tawait Promise.race([\n\t\t\t\tthis.discoverAndRegister(),\n\t\t\t\ttimeoutPromise,\n\t\t\t\tabortPromise\n\t\t\t]);\n\t\t\tif (timeoutId !== void 0) clearTimeout(timeoutId);\n\t\t\tthis.connectionState = MCPConnectionState.READY;\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\tdisplayMessage: `Discovery completed for ${this.url.toString()}`,\n\t\t\t\tpayload: { url: this.url.toString() },\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn { success: true };\n\t\t} catch (e) {\n\t\t\tif (timeoutId !== void 0) clearTimeout(timeoutId);\n\t\t\tthis.connectionState = MCPConnectionState.CONNECTED;\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: e instanceof Error ? e.message : String(e)\n\t\t\t};\n\t\t} finally {\n\t\t\tthis._discoveryAbortController = void 0;\n\t\t}\n\t}\n\t/**\n\t* Cancel any in-flight discovery operation.\n\t* Called when closing the connection.\n\t*/\n\tcancelDiscovery() {\n\t\tif (this._discoveryAbortController) {\n\t\t\tthis._discoveryAbortController.abort();\n\t\t\tthis._discoveryAbortController = void 0;\n\t\t}\n\t}\n\t/**\n\t* Notification handler registration for tools\n\t* Should only be called if serverCapabilities.tools exists\n\t*/\n\tasync registerTools() {\n\t\tif (this.serverCapabilities?.tools?.listChanged) this.client.setNotificationHandler(ToolListChangedNotificationSchema, async (_notification) => {\n\t\t\tthis.tools = await this.fetchTools();\n\t\t});\n\t\treturn this.fetchTools();\n\t}\n\t/**\n\t* Notification handler registration for resources\n\t* Should only be called if serverCapabilities.resources exists\n\t*/\n\tasync registerResources() {\n\t\tif (this.serverCapabilities?.resources?.listChanged) this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_notification) => {\n\t\t\tthis.resources = await this.fetchResources();\n\t\t});\n\t\treturn this.fetchResources();\n\t}\n\t/**\n\t* Notification handler registration for prompts\n\t* Should only be called if serverCapabilities.prompts exists\n\t*/\n\tasync registerPrompts() {\n\t\tif (this.serverCapabilities?.prompts?.listChanged) this.client.setNotificationHandler(PromptListChangedNotificationSchema, async (_notification) => {\n\t\t\tthis.prompts = await this.fetchPrompts();\n\t\t});\n\t\treturn this.fetchPrompts();\n\t}\n\tasync registerResourceTemplates() {\n\t\treturn this.fetchResourceTemplates();\n\t}\n\tasync fetchTools() {\n\t\tlet toolsAgg = [];\n\t\tlet toolsResult = { tools: [] };\n\t\tdo {\n\t\t\ttoolsResult = await this.client.listTools({ cursor: toolsResult.nextCursor }).catch(this._capabilityErrorHandler({ tools: [] }, \"tools/list\"));\n\t\t\ttoolsAgg = toolsAgg.concat(toolsResult.tools);\n\t\t} while (toolsResult.nextCursor);\n\t\treturn toolsAgg;\n\t}\n\tasync fetchResources() {\n\t\tlet resourcesAgg = [];\n\t\tlet resourcesResult = { resources: [] };\n\t\tdo {\n\t\t\tresourcesResult = await this.client.listResources({ cursor: resourcesResult.nextCursor }).catch(this._capabilityErrorHandler({ resources: [] }, \"resources/list\"));\n\t\t\tresourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n\t\t} while (resourcesResult.nextCursor);\n\t\treturn resourcesAgg;\n\t}\n\tasync fetchPrompts() {\n\t\tlet promptsAgg = [];\n\t\tlet promptsResult = { prompts: [] };\n\t\tdo {\n\t\t\tpromptsResult = await this.client.listPrompts({ cursor: promptsResult.nextCursor }).catch(this._capabilityErrorHandler({ prompts: [] }, \"prompts/list\"));\n\t\t\tpromptsAgg = promptsAgg.concat(promptsResult.prompts);\n\t\t} while (promptsResult.nextCursor);\n\t\treturn promptsAgg;\n\t}\n\tasync fetchResourceTemplates() {\n\t\tlet templatesAgg = [];\n\t\tlet templatesResult = { resourceTemplates: [] };\n\t\tdo {\n\t\t\ttemplatesResult = await this.client.listResourceTemplates({ cursor: templatesResult.nextCursor }).catch(this._capabilityErrorHandler({ resourceTemplates: [] }, \"resources/templates/list\"));\n\t\t\ttemplatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n\t\t} while (templatesResult.nextCursor);\n\t\treturn templatesAgg;\n\t}\n\t/**\n\t* Handle elicitation request from server\n\t* Automatically uses the Agent's built-in elicitation handling if available\n\t*/\n\tasync handleElicitationRequest(_request) {\n\t\tthrow new Error(\"Elicitation handler must be implemented for your platform. Override handleElicitationRequest method.\");\n\t}\n\t/**\n\t* Get the transport for the client\n\t* @param transportType - The transport type to get\n\t* @returns The transport for the client\n\t*/\n\tgetTransport(transportType) {\n\t\tswitch (transportType) {\n\t\t\tcase \"streamable-http\": return new StreamableHTTPClientTransport(this.url, this.options.transport);\n\t\t\tcase \"sse\": return new SSEClientTransport(this.url, this.options.transport);\n\t\t\tdefault: throw new Error(`Unsupported transport type: ${transportType}`);\n\t\t}\n\t}\n\tasync tryConnect(transportType) {\n\t\tconst transports = transportType === \"auto\" ? [\"streamable-http\", \"sse\"] : [transportType];\n\t\tfor (const currentTransportType of transports) {\n\t\t\tconst isLastTransport = currentTransportType === transports[transports.length - 1];\n\t\t\tconst hasFallback = transportType === \"auto\" && currentTransportType === \"streamable-http\" && !isLastTransport;\n\t\t\tconst transport = this.getTransport(currentTransportType);\n\t\t\ttry {\n\t\t\t\tawait this.client.connect(transport);\n\t\t\t\treturn {\n\t\t\t\t\tstate: MCPConnectionState.CONNECTED,\n\t\t\t\t\ttransport: currentTransportType\n\t\t\t\t};\n\t\t\t} catch (e) {\n\t\t\t\tconst error = e instanceof Error ? e : new Error(String(e));\n\t\t\t\tif (isUnauthorized(error)) return { state: MCPConnectionState.AUTHENTICATING };\n\t\t\t\tif (isTransportNotImplemented(error) && hasFallback) continue;\n\t\t\t\treturn {\n\t\t\t\t\tstate: MCPConnectionState.FAILED,\n\t\t\t\t\terror\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tstate: MCPConnectionState.FAILED,\n\t\t\terror: /* @__PURE__ */ new Error(\"No transports available\")\n\t\t};\n\t}\n\t_capabilityErrorHandler(empty, method) {\n\t\treturn (e) => {\n\t\t\tif (e.code === -32601) {\n\t\t\t\tconst url = this.url.toString();\n\t\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\t\tdisplayMessage: `The server advertised support for the capability ${method.split(\"/\")[0]}, but returned \"Method not found\" for '${method}' for ${url}`,\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\turl,\n\t\t\t\t\t\tcapability: method.split(\"/\")[0],\n\t\t\t\t\t\terror: toErrorMessage(e)\n\t\t\t\t\t},\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\tid: nanoid()\n\t\t\t\t});\n\t\t\t\treturn empty;\n\t\t\t}\n\t\t\tthrow e;\n\t\t};\n\t}\n};\n\n//#endregion\n//#region src/mcp/client.ts\nconst defaultClientOptions = { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() };\n/**\n* Utility class that aggregates multiple MCP clients into one\n*/\nvar MCPClientManager = class {\n\t/**\n\t* @param _name Name of the MCP client\n\t* @param _version Version of the MCP Client\n\t* @param options Storage adapter for persisting MCP server state\n\t*/\n\tconstructor(_name, _version, options) {\n\t\tthis._name = _name;\n\t\tthis._version = _version;\n\t\tthis.mcpConnections = {};\n\t\tthis._didWarnAboutUnstableGetAITools = false;\n\t\tthis._connectionDisposables = /* @__PURE__ */ new Map();\n\t\tthis._isRestored = false;\n\t\tthis._onObservabilityEvent = new Emitter();\n\t\tthis.onObservabilityEvent = this._onObservabilityEvent.event;\n\t\tthis._onServerStateChanged = new Emitter();\n\t\tthis.onServerStateChanged = this._onServerStateChanged.event;\n\t\tif (!options.storage) throw new Error(\"MCPClientManager requires a valid DurableObjectStorage instance\");\n\t\tthis._storage = options.storage;\n\t}\n\tsql(query, ...bindings) {\n\t\treturn [...this._storage.sql.exec(query, ...bindings)];\n\t}\n\tsaveServerToStorage(server) {\n\t\tthis.sql(`INSERT OR REPLACE INTO cf_agents_mcp_servers (\n id, name, server_url, client_id, auth_url, callback_url, server_options\n ) VALUES (?, ?, ?, ?, ?, ?, ?)`, server.id, server.name, server.server_url, server.client_id ?? null, server.auth_url ?? null, server.callback_url, server.server_options ?? null);\n\t}\n\tremoveServerFromStorage(serverId) {\n\t\tthis.sql(\"DELETE FROM cf_agents_mcp_servers WHERE id = ?\", serverId);\n\t}\n\tgetServersFromStorage() {\n\t\treturn this.sql(\"SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers\");\n\t}\n\tclearServerAuthUrl(serverId) {\n\t\tthis.sql(\"UPDATE cf_agents_mcp_servers SET auth_url = NULL WHERE id = ?\", serverId);\n\t}\n\t/**\n\t* Create an auth provider for a server\n\t* @internal\n\t*/\n\tcreateAuthProvider(serverId, callbackUrl, clientName, clientId) {\n\t\tif (!this._storage) throw new Error(\"Cannot create auth provider: storage is not initialized\");\n\t\tconst authProvider = new DurableObjectOAuthClientProvider(this._storage, clientName, callbackUrl);\n\t\tauthProvider.serverId = serverId;\n\t\tif (clientId) authProvider.clientId = clientId;\n\t\treturn authProvider;\n\t}\n\t/**\n\t* Restore MCP server connections from storage\n\t* This method is called on Agent initialization to restore previously connected servers\n\t*\n\t* @param clientName Name to use for OAuth client (typically the agent instance name)\n\t*/\n\tasync restoreConnectionsFromStorage(clientName) {\n\t\tif (this._isRestored) return;\n\t\tconst servers = this.getServersFromStorage();\n\t\tif (!servers || servers.length === 0) {\n\t\t\tthis._isRestored = true;\n\t\t\treturn;\n\t\t}\n\t\tfor (const server of servers) {\n\t\t\tconst existingConn = this.mcpConnections[server.id];\n\t\t\tif (existingConn) {\n\t\t\t\tif (existingConn.connectionState === MCPConnectionState.READY) {\n\t\t\t\t\tconsole.warn(`[MCPClientManager] Server ${server.id} already has a ready connection. Skipping recreation.`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (existingConn.connectionState === MCPConnectionState.AUTHENTICATING || existingConn.connectionState === MCPConnectionState.CONNECTING || existingConn.connectionState === MCPConnectionState.DISCOVERING) continue;\n\t\t\t\tif (existingConn.connectionState === MCPConnectionState.FAILED) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait existingConn.client.close();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconsole.warn(`[MCPClientManager] Error closing failed connection ${server.id}:`, error);\n\t\t\t\t\t}\n\t\t\t\t\tdelete this.mcpConnections[server.id];\n\t\t\t\t\tthis._connectionDisposables.get(server.id)?.dispose();\n\t\t\t\t\tthis._connectionDisposables.delete(server.id);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst parsedOptions = server.server_options ? JSON.parse(server.server_options) : null;\n\t\t\tconst authProvider = this.createAuthProvider(server.id, server.callback_url, clientName, server.client_id ?? void 0);\n\t\t\tconst conn = this.createConnection(server.id, server.server_url, {\n\t\t\t\tclient: parsedOptions?.client ?? {},\n\t\t\t\ttransport: {\n\t\t\t\t\t...parsedOptions?.transport ?? {},\n\t\t\t\t\ttype: parsedOptions?.transport?.type ?? \"auto\",\n\t\t\t\t\tauthProvider\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (server.auth_url) {\n\t\t\t\tconn.connectionState = MCPConnectionState.AUTHENTICATING;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis._restoreServer(server.id);\n\t\t}\n\t\tthis._isRestored = true;\n\t}\n\t/**\n\t* Internal method to restore a single server connection and discovery\n\t*/\n\tasync _restoreServer(serverId) {\n\t\tif ((await this.connectToServer(serverId).catch((error) => {\n\t\t\tconsole.error(`Error connecting to ${serverId}:`, error);\n\t\t\treturn null;\n\t\t}))?.state === MCPConnectionState.CONNECTED) {\n\t\t\tconst discoverResult = await this.discoverIfConnected(serverId);\n\t\t\tif (discoverResult && !discoverResult.success) console.error(`Error discovering ${serverId}:`, discoverResult.error);\n\t\t}\n\t}\n\t/**\n\t* Connect to and register an MCP server\n\t*\n\t* @deprecated This method is maintained for backward compatibility.\n\t* For new code, use registerServer() and connectToServer() separately.\n\t*\n\t* @param url Server URL\n\t* @param options Connection options\n\t* @returns Object with server ID, auth URL (if OAuth), and client ID (if OAuth)\n\t*/\n\tasync connect(url, options = {}) {\n\t\t/**\n\t\t* We need to delay loading ai sdk, because putting it in module scope is\n\t\t* causing issues with startup time.\n\t\t* The only place it's used is in getAITools, which only matters after\n\t\t* .connect() is called on at least one server.\n\t\t* So it's safe to delay loading it until .connect() is called.\n\t\t*/\n\t\tawait this.ensureJsonSchema();\n\t\tconst id = options.reconnect?.id ?? nanoid(8);\n\t\tif (options.transport?.authProvider) {\n\t\t\toptions.transport.authProvider.serverId = id;\n\t\t\tif (options.reconnect?.oauthClientId) options.transport.authProvider.clientId = options.reconnect?.oauthClientId;\n\t\t}\n\t\tif (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {\n\t\t\tconst normalizedTransport = {\n\t\t\t\t...options.transport,\n\t\t\t\ttype: options.transport?.type ?? \"auto\"\n\t\t\t};\n\t\t\tthis.mcpConnections[id] = new MCPClientConnection(new URL(url), {\n\t\t\t\tname: this._name,\n\t\t\t\tversion: this._version\n\t\t\t}, {\n\t\t\t\tclient: options.client ?? {},\n\t\t\t\ttransport: normalizedTransport\n\t\t\t});\n\t\t\tconst store = new DisposableStore();\n\t\t\tconst existing = this._connectionDisposables.get(id);\n\t\t\tif (existing) existing.dispose();\n\t\t\tthis._connectionDisposables.set(id, store);\n\t\t\tstore.add(this.mcpConnections[id].onObservabilityEvent((event) => {\n\t\t\t\tthis._onObservabilityEvent.fire(event);\n\t\t\t}));\n\t\t}\n\t\tawait this.mcpConnections[id].init();\n\t\tif (options.reconnect?.oauthCode) try {\n\t\t\tawait this.mcpConnections[id].completeAuthorization(options.reconnect.oauthCode);\n\t\t\tawait this.mcpConnections[id].init();\n\t\t} catch (error) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `Failed to complete OAuth reconnection for ${id} for ${url}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl,\n\t\t\t\t\ttransport: options.transport?.type ?? \"auto\",\n\t\t\t\t\tstate: this.mcpConnections[id].connectionState,\n\t\t\t\t\terror: toErrorMessage(error)\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid\n\t\t\t});\n\t\t\tthrow error;\n\t\t}\n\t\tconst authUrl = options.transport?.authProvider?.authUrl;\n\t\tif (this.mcpConnections[id].connectionState === MCPConnectionState.AUTHENTICATING && authUrl && options.transport?.authProvider?.redirectUrl) return {\n\t\t\tauthUrl,\n\t\t\tclientId: options.transport?.authProvider?.clientId,\n\t\t\tid\n\t\t};\n\t\tconst discoverResult = await this.discoverIfConnected(id);\n\t\tif (discoverResult && !discoverResult.success) throw new Error(`Failed to discover server capabilities: ${discoverResult.error}`);\n\t\treturn { id };\n\t}\n\t/**\n\t* Create an in-memory connection object and set up observability\n\t* Does NOT save to storage - use registerServer() for that\n\t* @returns The connection object (existing or newly created)\n\t*/\n\tcreateConnection(id, url, options) {\n\t\tif (this.mcpConnections[id]) return this.mcpConnections[id];\n\t\tconst normalizedTransport = {\n\t\t\t...options.transport,\n\t\t\ttype: options.transport?.type ?? \"auto\"\n\t\t};\n\t\tthis.mcpConnections[id] = new MCPClientConnection(new URL(url), {\n\t\t\tname: this._name,\n\t\t\tversion: this._version\n\t\t}, {\n\t\t\tclient: {\n\t\t\t\t...defaultClientOptions,\n\t\t\t\t...options.client\n\t\t\t},\n\t\t\ttransport: normalizedTransport\n\t\t});\n\t\tconst store = new DisposableStore();\n\t\tconst existing = this._connectionDisposables.get(id);\n\t\tif (existing) existing.dispose();\n\t\tthis._connectionDisposables.set(id, store);\n\t\tstore.add(this.mcpConnections[id].onObservabilityEvent((event) => {\n\t\t\tthis._onObservabilityEvent.fire(event);\n\t\t}));\n\t\treturn this.mcpConnections[id];\n\t}\n\t/**\n\t* Register an MCP server connection without connecting\n\t* Creates the connection object, sets up observability, and saves to storage\n\t*\n\t* @param id Server ID\n\t* @param options Registration options including URL, name, callback URL, and connection config\n\t* @returns Server ID\n\t*/\n\tasync registerServer(id, options) {\n\t\tthis.createConnection(id, options.url, {\n\t\t\tclient: options.client,\n\t\t\ttransport: {\n\t\t\t\t...options.transport,\n\t\t\t\ttype: options.transport?.type ?? \"auto\"\n\t\t\t}\n\t\t});\n\t\tconst { authProvider: _, ...transportWithoutAuth } = options.transport ?? {};\n\t\tthis.saveServerToStorage({\n\t\t\tid,\n\t\t\tname: options.name,\n\t\t\tserver_url: options.url,\n\t\t\tcallback_url: options.callbackUrl,\n\t\t\tclient_id: options.clientId ?? null,\n\t\t\tauth_url: options.authUrl ?? null,\n\t\t\tserver_options: JSON.stringify({\n\t\t\t\tclient: options.client,\n\t\t\t\ttransport: transportWithoutAuth\n\t\t\t})\n\t\t});\n\t\tthis._onServerStateChanged.fire();\n\t\treturn id;\n\t}\n\t/**\n\t* Connect to an already registered MCP server and initialize the connection.\n\t*\n\t* For OAuth servers, returns `{ state: \"authenticating\", authUrl, clientId? }`.\n\t* The user must complete the OAuth flow via the authUrl, which triggers a\n\t* callback handled by `handleCallbackRequest()`.\n\t*\n\t* For non-OAuth servers, establishes the transport connection and returns\n\t* `{ state: \"connected\" }`. Call `discoverIfConnected()` afterwards to\n\t* discover capabilities and transition to \"ready\" state.\n\t*\n\t* @param id Server ID (must be registered first via registerServer())\n\t* @returns Connection result with current state and OAuth info (if applicable)\n\t*/\n\tasync connectToServer(id) {\n\t\tconst conn = this.mcpConnections[id];\n\t\tif (!conn) throw new Error(`Server ${id} is not registered. Call registerServer() first.`);\n\t\tconst error = await conn.init();\n\t\tthis._onServerStateChanged.fire();\n\t\tswitch (conn.connectionState) {\n\t\t\tcase MCPConnectionState.FAILED: return {\n\t\t\t\tstate: conn.connectionState,\n\t\t\t\terror: error ?? \"Unknown connection error\"\n\t\t\t};\n\t\t\tcase MCPConnectionState.AUTHENTICATING: {\n\t\t\t\tconst authUrl = conn.options.transport.authProvider?.authUrl;\n\t\t\t\tconst redirectUrl = conn.options.transport.authProvider?.redirectUrl;\n\t\t\t\tif (!authUrl || !redirectUrl) return {\n\t\t\t\t\tstate: MCPConnectionState.FAILED,\n\t\t\t\t\terror: `OAuth configuration incomplete: missing ${!authUrl ? \"authUrl\" : \"redirectUrl\"}`\n\t\t\t\t};\n\t\t\t\tconst clientId = conn.options.transport.authProvider?.clientId;\n\t\t\t\tconst serverRow = this.getServersFromStorage().find((s) => s.id === id);\n\t\t\t\tif (serverRow) this.saveServerToStorage({\n\t\t\t\t\t...serverRow,\n\t\t\t\t\tauth_url: authUrl,\n\t\t\t\t\tclient_id: clientId ?? null\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tstate: conn.connectionState,\n\t\t\t\t\tauthUrl,\n\t\t\t\t\tclientId\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase MCPConnectionState.CONNECTED: return { state: conn.connectionState };\n\t\t\tdefault: return {\n\t\t\t\tstate: MCPConnectionState.FAILED,\n\t\t\t\terror: `Unexpected connection state after init: ${conn.connectionState}`\n\t\t\t};\n\t\t}\n\t}\n\tisCallbackRequest(req) {\n\t\tif (req.method !== \"GET\") return false;\n\t\tif (!req.url.includes(\"/callback\")) return false;\n\t\treturn this.getServersFromStorage().some((server) => server.callback_url && req.url.startsWith(server.callback_url));\n\t}\n\tasync handleCallbackRequest(req) {\n\t\tconst url = new URL(req.url);\n\t\tconst matchingServer = this.getServersFromStorage().find((server) => {\n\t\t\treturn server.callback_url && req.url.startsWith(server.callback_url);\n\t\t});\n\t\tif (!matchingServer) throw new Error(`No callback URI match found for the request url: ${req.url}. Was the request matched with \\`isCallbackRequest()\\`?`);\n\t\tconst serverId = matchingServer.id;\n\t\tconst code = url.searchParams.get(\"code\");\n\t\tconst state = url.searchParams.get(\"state\");\n\t\tconst error = url.searchParams.get(\"error\");\n\t\tconst errorDescription = url.searchParams.get(\"error_description\");\n\t\tif (error) return {\n\t\t\tserverId,\n\t\t\tauthSuccess: false,\n\t\t\tauthError: errorDescription || error\n\t\t};\n\t\tif (!code) throw new Error(\"Unauthorized: no code provided\");\n\t\tif (!state) throw new Error(\"Unauthorized: no state provided\");\n\t\tif (this.mcpConnections[serverId] === void 0) throw new Error(`Could not find serverId: ${serverId}`);\n\t\tif (this.mcpConnections[serverId].connectionState === MCPConnectionState.READY || this.mcpConnections[serverId].connectionState === MCPConnectionState.CONNECTED) {\n\t\t\tthis.clearServerAuthUrl(serverId);\n\t\t\treturn {\n\t\t\t\tserverId,\n\t\t\t\tauthSuccess: true\n\t\t\t};\n\t\t}\n\t\tif (this.mcpConnections[serverId].connectionState !== MCPConnectionState.AUTHENTICATING) throw new Error(`Failed to authenticate: the client is in \"${this.mcpConnections[serverId].connectionState}\" state, expected \"authenticating\"`);\n\t\tconst conn = this.mcpConnections[serverId];\n\t\tif (!conn.options.transport.authProvider) throw new Error(\"Trying to finalize authentication for a server connection without an authProvider\");\n\t\tconst clientId = conn.options.transport.authProvider.clientId || state;\n\t\tconn.options.transport.authProvider.clientId = clientId;\n\t\tconn.options.transport.authProvider.serverId = serverId;\n\t\ttry {\n\t\t\tawait conn.completeAuthorization(code);\n\t\t\tthis.clearServerAuthUrl(serverId);\n\t\t\tthis._onServerStateChanged.fire();\n\t\t\treturn {\n\t\t\t\tserverId,\n\t\t\t\tauthSuccess: true\n\t\t\t};\n\t\t} catch (error$1) {\n\t\t\tconst errorMessage = error$1 instanceof Error ? error$1.message : String(error$1);\n\t\t\tthis._onServerStateChanged.fire();\n\t\t\treturn {\n\t\t\t\tserverId,\n\t\t\t\tauthSuccess: false,\n\t\t\t\tauthError: errorMessage\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Discover server capabilities if connection is in CONNECTED or READY state.\n\t* Transitions to DISCOVERING then READY (or CONNECTED on error).\n\t* Can be called to refresh server capabilities (e.g., from a UI refresh button).\n\t*\n\t* If called while a previous discovery is in-flight for the same server,\n\t* the previous discovery will be aborted.\n\t*\n\t* @param serverId The server ID to discover\n\t* @param options Optional configuration\n\t* @param options.timeoutMs Timeout in milliseconds (default: 30000)\n\t* @returns Result with current state and optional error, or undefined if connection not found\n\t*/\n\tasync discoverIfConnected(serverId, options = {}) {\n\t\tconst conn = this.mcpConnections[serverId];\n\t\tif (!conn) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\tdisplayMessage: `Connection not found for ${serverId}`,\n\t\t\t\tpayload: {},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst result = await conn.discover(options);\n\t\tthis._onServerStateChanged.fire();\n\t\treturn {\n\t\t\t...result,\n\t\t\tstate: conn.connectionState\n\t\t};\n\t}\n\t/**\n\t* Establish connection in the background after OAuth completion\n\t* This method connects to the server and discovers its capabilities\n\t* @param serverId The server ID to establish connection for\n\t*/\n\tasync establishConnection(serverId) {\n\t\tconst conn = this.mcpConnections[serverId];\n\t\tif (!conn) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:preconnect\",\n\t\t\t\tdisplayMessage: `Connection not found for serverId: ${serverId}`,\n\t\t\t\tpayload: { serverId },\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (conn.connectionState === MCPConnectionState.DISCOVERING || conn.connectionState === MCPConnectionState.READY) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `establishConnection skipped for ${serverId}, already in ${conn.connectionState} state`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl: conn.url.toString(),\n\t\t\t\t\ttransport: conn.options.transport.type || \"unknown\",\n\t\t\t\t\tstate: conn.connectionState\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst connectResult = await this.connectToServer(serverId);\n\t\tthis._onServerStateChanged.fire();\n\t\tif (connectResult.state === MCPConnectionState.CONNECTED) await this.discoverIfConnected(serverId);\n\t\tthis._onObservabilityEvent.fire({\n\t\t\ttype: \"mcp:client:connect\",\n\t\t\tdisplayMessage: `establishConnection completed for ${serverId}, final state: ${conn.connectionState}`,\n\t\t\tpayload: {\n\t\t\t\turl: conn.url.toString(),\n\t\t\t\ttransport: conn.options.transport.type || \"unknown\",\n\t\t\t\tstate: conn.connectionState\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t\tid: nanoid()\n\t\t});\n\t}\n\t/**\n\t* Configure OAuth callback handling\n\t* @param config OAuth callback configuration\n\t*/\n\tconfigureOAuthCallback(config) {\n\t\tthis._oauthCallbackConfig = config;\n\t}\n\t/**\n\t* Get the current OAuth callback configuration\n\t* @returns The current OAuth callback configuration\n\t*/\n\tgetOAuthCallbackConfig() {\n\t\treturn this._oauthCallbackConfig;\n\t}\n\t/**\n\t* @returns namespaced list of tools\n\t*/\n\tlistTools() {\n\t\treturn getNamespacedData(this.mcpConnections, \"tools\");\n\t}\n\t/**\n\t* Lazy-loads the jsonSchema function from the AI SDK.\n\t*\n\t* This defers importing the \"ai\" package until it's actually needed, which helps reduce\n\t* initial bundle size and startup time. The jsonSchema function is required for converting\n\t* MCP tools into AI SDK tool definitions via getAITools().\n\t*\n\t* @internal This method is for internal use only. It's automatically called before operations\n\t* that need jsonSchema (like getAITools() or OAuth flows). External consumers should not need\n\t* to call this directly.\n\t*/\n\tasync ensureJsonSchema() {\n\t\tif (!this.jsonSchema) {\n\t\t\tconst { jsonSchema } = await import(\"ai\");\n\t\t\tthis.jsonSchema = jsonSchema;\n\t\t}\n\t}\n\t/**\n\t* @returns a set of tools that you can use with the AI SDK\n\t*/\n\tgetAITools() {\n\t\tif (!this.jsonSchema) throw new Error(\"jsonSchema not initialized.\");\n\t\tfor (const [id, conn] of Object.entries(this.mcpConnections)) if (conn.connectionState !== MCPConnectionState.READY && conn.connectionState !== MCPConnectionState.AUTHENTICATING) console.warn(`[getAITools] WARNING: Reading tools from connection ${id} in state \"${conn.connectionState}\". Tools may not be loaded yet.`);\n\t\treturn Object.fromEntries(getNamespacedData(this.mcpConnections, \"tools\").map((tool) => {\n\t\t\treturn [`tool_${tool.serverId.replace(/-/g, \"\")}_${tool.name}`, {\n\t\t\t\tdescription: tool.description,\n\t\t\t\texecute: async (args) => {\n\t\t\t\t\tconst result = await this.callTool({\n\t\t\t\t\t\targuments: args,\n\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\tserverId: tool.serverId\n\t\t\t\t\t});\n\t\t\t\t\tif (result.isError) throw new Error(result.content[0].text);\n\t\t\t\t\treturn result;\n\t\t\t\t},\n\t\t\t\tinputSchema: this.jsonSchema(tool.inputSchema),\n\t\t\t\toutputSchema: tool.outputSchema ? this.jsonSchema(tool.outputSchema) : void 0\n\t\t\t}];\n\t\t}));\n\t}\n\t/**\n\t* @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version\n\t* @returns a set of tools that you can use with the AI SDK\n\t*/\n\tunstable_getAITools() {\n\t\tif (!this._didWarnAboutUnstableGetAITools) {\n\t\t\tthis._didWarnAboutUnstableGetAITools = true;\n\t\t\tconsole.warn(\"unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version.\");\n\t\t}\n\t\treturn this.getAITools();\n\t}\n\t/**\n\t* Closes all active in-memory connections to MCP servers.\n\t*\n\t* Note: This only closes the transport connections - it does NOT remove\n\t* servers from storage. Servers will still be listed and their callback\n\t* URLs will still match incoming OAuth requests.\n\t*\n\t* Use removeServer() instead if you want to fully clean up a server\n\t* (closes connection AND removes from storage).\n\t*/\n\tasync closeAllConnections() {\n\t\tconst ids = Object.keys(this.mcpConnections);\n\t\tfor (const id of ids) this.mcpConnections[id].cancelDiscovery();\n\t\tawait Promise.all(ids.map(async (id) => {\n\t\t\tawait this.mcpConnections[id].client.close();\n\t\t}));\n\t\tfor (const id of ids) {\n\t\t\tconst store = this._connectionDisposables.get(id);\n\t\t\tif (store) store.dispose();\n\t\t\tthis._connectionDisposables.delete(id);\n\t\t\tdelete this.mcpConnections[id];\n\t\t}\n\t}\n\t/**\n\t* Closes a connection to an MCP server\n\t* @param id The id of the connection to close\n\t*/\n\tasync closeConnection(id) {\n\t\tif (!this.mcpConnections[id]) throw new Error(`Connection with id \"${id}\" does not exist.`);\n\t\tthis.mcpConnections[id].cancelDiscovery();\n\t\tawait this.mcpConnections[id].client.close();\n\t\tdelete this.mcpConnections[id];\n\t\tconst store = this._connectionDisposables.get(id);\n\t\tif (store) store.dispose();\n\t\tthis._connectionDisposables.delete(id);\n\t}\n\t/**\n\t* Remove an MCP server - closes connection if active and removes from storage.\n\t*/\n\tasync removeServer(serverId) {\n\t\tif (this.mcpConnections[serverId]) try {\n\t\t\tawait this.closeConnection(serverId);\n\t\t} catch (e) {}\n\t\tthis.removeServerFromStorage(serverId);\n\t\tthis._onServerStateChanged.fire();\n\t}\n\t/**\n\t* List all MCP servers from storage\n\t*/\n\tlistServers() {\n\t\treturn this.getServersFromStorage();\n\t}\n\t/**\n\t* Dispose the manager and all resources.\n\t*/\n\tasync dispose() {\n\t\ttry {\n\t\t\tawait this.closeAllConnections();\n\t\t} finally {\n\t\t\tthis._onServerStateChanged.dispose();\n\t\t\tthis._onObservabilityEvent.dispose();\n\t\t}\n\t}\n\t/**\n\t* @returns namespaced list of prompts\n\t*/\n\tlistPrompts() {\n\t\treturn getNamespacedData(this.mcpConnections, \"prompts\");\n\t}\n\t/**\n\t* @returns namespaced list of tools\n\t*/\n\tlistResources() {\n\t\treturn getNamespacedData(this.mcpConnections, \"resources\");\n\t}\n\t/**\n\t* @returns namespaced list of resource templates\n\t*/\n\tlistResourceTemplates() {\n\t\treturn getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n\t}\n\t/**\n\t* Namespaced version of callTool\n\t*/\n\tasync callTool(params, resultSchema, options) {\n\t\tconst unqualifiedName = params.name.replace(`${params.serverId}.`, \"\");\n\t\treturn this.mcpConnections[params.serverId].client.callTool({\n\t\t\t...params,\n\t\t\tname: unqualifiedName\n\t\t}, resultSchema, options);\n\t}\n\t/**\n\t* Namespaced version of readResource\n\t*/\n\treadResource(params, options) {\n\t\treturn this.mcpConnections[params.serverId].client.readResource(params, options);\n\t}\n\t/**\n\t* Namespaced version of getPrompt\n\t*/\n\tgetPrompt(params, options) {\n\t\treturn this.mcpConnections[params.serverId].client.getPrompt(params, options);\n\t}\n};\nfunction getNamespacedData(mcpClients, type) {\n\treturn Object.entries(mcpClients).map(([name, conn]) => {\n\t\treturn {\n\t\t\tdata: conn[type],\n\t\t\tname\n\t\t};\n\t}).flatMap(({ name: serverId, data }) => {\n\t\treturn data.map((item) => {\n\t\t\treturn {\n\t\t\t\t...item,\n\t\t\t\tserverId\n\t\t\t};\n\t\t});\n\t});\n}\n\n//#endregion\nexport { DisposableStore as i, getNamespacedData as n, MCPConnectionState as r, MCPClientManager as t };\n//# sourceMappingURL=client-BZq9qau2.js.map","import { t as MessageType } from \"./ai-types-CrMqkwc_.js\";\nimport { r as camelCaseToKebabCase } from \"./client-B3SR12TQ.js\";\nimport { i as DisposableStore, r as MCPConnectionState, t as MCPClientManager } from \"./client-BZq9qau2.js\";\nimport { t as DurableObjectOAuthClientProvider } from \"./do-oauth-client-provider-CwqK5SXm.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { parseCronExpression } from \"cron-schedule\";\nimport { nanoid } from \"nanoid\";\nimport { EmailMessage } from \"cloudflare:email\";\nimport { Server, getServerByName, routePartykitRequest } from \"partyserver\";\n\n//#region src/observability/index.ts\n/**\n* A generic observability implementation that logs events to the console.\n*/\nconst genericObservability = { emit(event) {\n\tif (isLocalMode()) {\n\t\tconsole.log(event.displayMessage);\n\t\treturn;\n\t}\n\tconsole.log(event);\n} };\nlet localMode = false;\nfunction isLocalMode() {\n\tif (localMode) return true;\n\tconst { request } = getCurrentAgent();\n\tif (!request) return false;\n\tlocalMode = new URL(request.url).hostname === \"localhost\";\n\treturn localMode;\n}\n\n//#endregion\n//#region src/index.ts\n/**\n* Type guard for RPC request messages\n*/\nfunction isRPCRequest(msg) {\n\treturn typeof msg === \"object\" && msg !== null && \"type\" in msg && msg.type === MessageType.RPC && \"id\" in msg && typeof msg.id === \"string\" && \"method\" in msg && typeof msg.method === \"string\" && \"args\" in msg && Array.isArray(msg.args);\n}\n/**\n* Type guard for state update messages\n*/\nfunction isStateUpdateMessage(msg) {\n\treturn typeof msg === \"object\" && msg !== null && \"type\" in msg && msg.type === MessageType.CF_AGENT_STATE && \"state\" in msg;\n}\nconst callableMetadata = /* @__PURE__ */ new Map();\n/**\n* Decorator that marks a method as callable by clients\n* @param metadata Optional metadata about the callable method\n*/\nfunction callable(metadata = {}) {\n\treturn function callableDecorator(target, context) {\n\t\tif (!callableMetadata.has(target)) callableMetadata.set(target, metadata);\n\t\treturn target;\n\t};\n}\nlet didWarnAboutUnstableCallable = false;\n/**\n* Decorator that marks a method as callable by clients\n* @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version\n* @param metadata Optional metadata about the callable method\n*/\nconst unstable_callable = (metadata = {}) => {\n\tif (!didWarnAboutUnstableCallable) {\n\t\tdidWarnAboutUnstableCallable = true;\n\t\tconsole.warn(\"unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version.\");\n\t}\n\tcallable(metadata);\n};\nfunction getNextCronTime(cron) {\n\treturn parseCronExpression(cron).getNextDate();\n}\nconst STATE_ROW_ID = \"cf_state_row_id\";\nconst STATE_WAS_CHANGED = \"cf_state_was_changed\";\nconst DEFAULT_STATE = {};\nconst agentContext = new AsyncLocalStorage();\nfunction getCurrentAgent() {\n\tconst store = agentContext.getStore();\n\tif (!store) return {\n\t\tagent: void 0,\n\t\tconnection: void 0,\n\t\trequest: void 0,\n\t\temail: void 0\n\t};\n\treturn store;\n}\n/**\n* Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly\n* @param agent The agent instance\n* @param method The method to wrap\n* @returns A wrapped method that runs within the agent context\n*/\nfunction withAgentContext(method) {\n\treturn function(...args) {\n\t\tconst { connection, request, email, agent } = getCurrentAgent();\n\t\tif (agent === this) return method.apply(this, args);\n\t\treturn agentContext.run({\n\t\t\tagent: this,\n\t\t\tconnection,\n\t\t\trequest,\n\t\t\temail\n\t\t}, () => {\n\t\t\treturn method.apply(this, args);\n\t\t});\n\t};\n}\n/**\n* Base class for creating Agent implementations\n* @template Env Environment type containing bindings\n* @template State State type to store within the Agent\n*/\nvar Agent = class Agent extends Server {\n\t/**\n\t* Current state of the Agent\n\t*/\n\tget state() {\n\t\tif (this._state !== DEFAULT_STATE) return this._state;\n\t\tconst wasChanged = this.sql`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}\n `;\n\t\tconst result = this.sql`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}\n `;\n\t\tif (wasChanged[0]?.state === \"true\" || result[0]?.state) {\n\t\t\tconst state = result[0]?.state;\n\t\t\tthis._state = JSON.parse(state);\n\t\t\treturn this._state;\n\t\t}\n\t\tif (this.initialState === DEFAULT_STATE) return;\n\t\tthis.setState(this.initialState);\n\t\treturn this.initialState;\n\t}\n\tstatic {\n\t\tthis.options = { hibernate: true };\n\t}\n\t/**\n\t* Execute SQL queries against the Agent's database\n\t* @template T Type of the returned rows\n\t* @param strings SQL query template strings\n\t* @param values Values to be inserted into the query\n\t* @returns Array of query results\n\t*/\n\tsql(strings, ...values) {\n\t\tlet query = \"\";\n\t\ttry {\n\t\t\tquery = strings.reduce((acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"), \"\");\n\t\t\treturn [...this.ctx.storage.sql.exec(query, ...values)];\n\t\t} catch (e) {\n\t\t\tconsole.error(`failed to execute sql query: ${query}`, e);\n\t\t\tthrow this.onError(e);\n\t\t}\n\t}\n\tconstructor(ctx, env) {\n\t\tsuper(ctx, env);\n\t\tthis._state = DEFAULT_STATE;\n\t\tthis._disposables = new DisposableStore();\n\t\tthis._destroyed = false;\n\t\tthis._ParentClass = Object.getPrototypeOf(this).constructor;\n\t\tthis.initialState = DEFAULT_STATE;\n\t\tthis.observability = genericObservability;\n\t\tthis._flushingQueue = false;\n\t\tthis.alarm = async () => {\n\t\t\tconst now = Math.floor(Date.now() / 1e3);\n\t\t\tconst result = this.sql`\n SELECT * FROM cf_agents_schedules WHERE time <= ${now}\n `;\n\t\t\tif (result && Array.isArray(result)) for (const row of result) {\n\t\t\t\tconst callback = this[row.callback];\n\t\t\t\tif (!callback) {\n\t\t\t\t\tconsole.error(`callback ${row.callback} not found`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tawait agentContext.run({\n\t\t\t\t\tagent: this,\n\t\t\t\t\tconnection: void 0,\n\t\t\t\t\trequest: void 0,\n\t\t\t\t\temail: void 0\n\t\t\t\t}, async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.observability?.emit({\n\t\t\t\t\t\t\tdisplayMessage: `Schedule ${row.id} executed`,\n\t\t\t\t\t\t\tid: nanoid(),\n\t\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\t\tcallback: row.callback,\n\t\t\t\t\t\t\t\tid: row.id\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\ttype: \"schedule:execute\"\n\t\t\t\t\t\t}, this.ctx);\n\t\t\t\t\t\tawait callback.bind(this)(JSON.parse(row.payload), row);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tconsole.error(`error executing callback \"${row.callback}\"`, e);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (row.type === \"cron\") {\n\t\t\t\t\tif (this._destroyed) return;\n\t\t\t\t\tconst nextExecutionTime = getNextCronTime(row.cron);\n\t\t\t\t\tconst nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);\n\t\t\t\t\tthis.sql`\n UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}\n `;\n\t\t\t\t} else {\n\t\t\t\t\tif (this._destroyed) return;\n\t\t\t\t\tthis.sql`\n DELETE FROM cf_agents_schedules WHERE id = ${row.id}\n `;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this._destroyed) return;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t};\n\t\tif (!wrappedClasses.has(this.constructor)) {\n\t\t\tthis._autoWrapCustomMethods();\n\t\t\twrappedClasses.add(this.constructor);\n\t\t}\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (\n id TEXT PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n server_url TEXT NOT NULL,\n callback_url TEXT NOT NULL,\n client_id TEXT,\n auth_url TEXT,\n server_options TEXT\n )\n `;\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_state (\n id TEXT PRIMARY KEY NOT NULL,\n state TEXT\n )\n `;\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_queues (\n id TEXT PRIMARY KEY NOT NULL,\n payload TEXT,\n callback TEXT,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_schedules (\n id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),\n callback TEXT,\n payload TEXT,\n type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),\n time INTEGER,\n delayInSeconds INTEGER,\n cron TEXT,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\t\tthis.mcp = new MCPClientManager(this._ParentClass.name, \"0.0.1\", { storage: this.ctx.storage });\n\t\tthis._disposables.add(this.mcp.onServerStateChanged(async () => {\n\t\t\tthis.broadcastMcpServers();\n\t\t}));\n\t\tthis._disposables.add(this.mcp.onObservabilityEvent((event) => {\n\t\t\tthis.observability?.emit(event);\n\t\t}));\n\t\tconst _onRequest = this.onRequest.bind(this);\n\t\tthis.onRequest = (request) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection: void 0,\n\t\t\t\trequest,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tawait this.mcp.ensureJsonSchema();\n\t\t\t\tconst oauthResponse = await this.handleMcpOAuthCallback(request);\n\t\t\t\tif (oauthResponse) return oauthResponse;\n\t\t\t\treturn this._tryCatch(() => _onRequest(request));\n\t\t\t});\n\t\t};\n\t\tconst _onMessage = this.onMessage.bind(this);\n\t\tthis.onMessage = async (connection, message) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection,\n\t\t\t\trequest: void 0,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tawait this.mcp.ensureJsonSchema();\n\t\t\t\tif (typeof message !== \"string\") return this._tryCatch(() => _onMessage(connection, message));\n\t\t\t\tlet parsed;\n\t\t\t\ttry {\n\t\t\t\t\tparsed = JSON.parse(message);\n\t\t\t\t} catch (_e) {\n\t\t\t\t\treturn this._tryCatch(() => _onMessage(connection, message));\n\t\t\t\t}\n\t\t\t\tif (isStateUpdateMessage(parsed)) {\n\t\t\t\t\tthis._setStateInternal(parsed.state, connection);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (isRPCRequest(parsed)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst { id, method, args } = parsed;\n\t\t\t\t\t\tconst methodFn = this[method];\n\t\t\t\t\t\tif (typeof methodFn !== \"function\") throw new Error(`Method ${method} does not exist`);\n\t\t\t\t\t\tif (!this._isCallable(method)) throw new Error(`Method ${method} is not callable`);\n\t\t\t\t\t\tconst metadata = callableMetadata.get(methodFn);\n\t\t\t\t\t\tif (metadata?.streaming) {\n\t\t\t\t\t\t\tconst stream = new StreamingResponse(connection, id);\n\t\t\t\t\t\t\tawait methodFn.apply(this, [stream, ...args]);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst result = await methodFn.apply(this, args);\n\t\t\t\t\t\tthis.observability?.emit({\n\t\t\t\t\t\t\tdisplayMessage: `RPC call to ${method}`,\n\t\t\t\t\t\t\tid: nanoid(),\n\t\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\t\tmethod,\n\t\t\t\t\t\t\t\tstreaming: metadata?.streaming\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\ttype: \"rpc\"\n\t\t\t\t\t\t}, this.ctx);\n\t\t\t\t\t\tconst response = {\n\t\t\t\t\t\t\tdone: true,\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\ttype: MessageType.RPC\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconnection.send(JSON.stringify(response));\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tconst response = {\n\t\t\t\t\t\t\terror: e instanceof Error ? e.message : \"Unknown error occurred\",\n\t\t\t\t\t\t\tid: parsed.id,\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\ttype: MessageType.RPC\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconnection.send(JSON.stringify(response));\n\t\t\t\t\t\tconsole.error(\"RPC error:\", e);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this._tryCatch(() => _onMessage(connection, message));\n\t\t\t});\n\t\t};\n\t\tconst _onConnect = this.onConnect.bind(this);\n\t\tthis.onConnect = (connection, ctx$1) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection,\n\t\t\t\trequest: ctx$1.request,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tif (this.state) connection.send(JSON.stringify({\n\t\t\t\t\tstate: this.state,\n\t\t\t\t\ttype: MessageType.CF_AGENT_STATE\n\t\t\t\t}));\n\t\t\t\tconnection.send(JSON.stringify({\n\t\t\t\t\tmcp: this.getMcpServers(),\n\t\t\t\t\ttype: MessageType.CF_AGENT_MCP_SERVERS\n\t\t\t\t}));\n\t\t\t\tthis.observability?.emit({\n\t\t\t\t\tdisplayMessage: \"Connection established\",\n\t\t\t\t\tid: nanoid(),\n\t\t\t\t\tpayload: { connectionId: connection.id },\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\ttype: \"connect\"\n\t\t\t\t}, this.ctx);\n\t\t\t\treturn this._tryCatch(() => _onConnect(connection, ctx$1));\n\t\t\t});\n\t\t};\n\t\tconst _onStart = this.onStart.bind(this);\n\t\tthis.onStart = async (props) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection: void 0,\n\t\t\t\trequest: void 0,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tawait this._tryCatch(async () => {\n\t\t\t\t\tawait this.mcp.restoreConnectionsFromStorage(this.name);\n\t\t\t\t\tthis.broadcastMcpServers();\n\t\t\t\t\treturn _onStart(props);\n\t\t\t\t});\n\t\t\t});\n\t\t};\n\t}\n\t_setStateInternal(state, source = \"server\") {\n\t\tthis._state = state;\n\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})\n `;\n\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})\n `;\n\t\tthis.broadcast(JSON.stringify({\n\t\t\tstate,\n\t\t\ttype: MessageType.CF_AGENT_STATE\n\t\t}), source !== \"server\" ? [source.id] : []);\n\t\treturn this._tryCatch(() => {\n\t\t\tconst { connection, request, email } = agentContext.getStore() || {};\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection,\n\t\t\t\trequest,\n\t\t\t\temail\n\t\t\t}, async () => {\n\t\t\t\tthis.observability?.emit({\n\t\t\t\t\tdisplayMessage: \"State updated\",\n\t\t\t\t\tid: nanoid(),\n\t\t\t\t\tpayload: {},\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\ttype: \"state:update\"\n\t\t\t\t}, this.ctx);\n\t\t\t\treturn this.onStateUpdate(state, source);\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* Update the Agent's state\n\t* @param state New state to set\n\t*/\n\tsetState(state) {\n\t\tthis._setStateInternal(state, \"server\");\n\t}\n\t/**\n\t* Called when the Agent's state is updated\n\t* @param state Updated state\n\t* @param source Source of the state update (\"server\" or a client connection)\n\t*/\n\tonStateUpdate(state, source) {}\n\t/**\n\t* Called when the Agent receives an email via routeAgentEmail()\n\t* Override this method to handle incoming emails\n\t* @param email Email message to process\n\t*/\n\tasync _onEmail(email) {\n\t\treturn agentContext.run({\n\t\t\tagent: this,\n\t\t\tconnection: void 0,\n\t\t\trequest: void 0,\n\t\t\temail\n\t\t}, async () => {\n\t\t\tif (\"onEmail\" in this && typeof this.onEmail === \"function\") return this._tryCatch(() => this.onEmail(email));\n\t\t\telse {\n\t\t\t\tconsole.log(\"Received email from:\", email.from, \"to:\", email.to);\n\t\t\t\tconsole.log(\"Subject:\", email.headers.get(\"subject\"));\n\t\t\t\tconsole.log(\"Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails\");\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* Reply to an email\n\t* @param email The email to reply to\n\t* @param options Options for the reply\n\t* @returns void\n\t*/\n\tasync replyToEmail(email, options) {\n\t\treturn this._tryCatch(async () => {\n\t\t\tconst agentName = camelCaseToKebabCase(this._ParentClass.name);\n\t\t\tconst agentId = this.name;\n\t\t\tconst { createMimeMessage } = await import(\"mimetext\");\n\t\t\tconst msg = createMimeMessage();\n\t\t\tmsg.setSender({\n\t\t\t\taddr: email.to,\n\t\t\t\tname: options.fromName\n\t\t\t});\n\t\t\tmsg.setRecipient(email.from);\n\t\t\tmsg.setSubject(options.subject || `Re: ${email.headers.get(\"subject\")}` || \"No subject\");\n\t\t\tmsg.addMessage({\n\t\t\t\tcontentType: options.contentType || \"text/plain\",\n\t\t\t\tdata: options.body\n\t\t\t});\n\t\t\tconst messageId = `<${agentId}@${email.from.split(\"@\")[1]}>`;\n\t\t\tmsg.setHeader(\"In-Reply-To\", email.headers.get(\"Message-ID\"));\n\t\t\tmsg.setHeader(\"Message-ID\", messageId);\n\t\t\tmsg.setHeader(\"X-Agent-Name\", agentName);\n\t\t\tmsg.setHeader(\"X-Agent-ID\", agentId);\n\t\t\tif (options.headers) for (const [key, value] of Object.entries(options.headers)) msg.setHeader(key, value);\n\t\t\tawait email.reply({\n\t\t\t\tfrom: email.to,\n\t\t\t\traw: msg.asRaw(),\n\t\t\t\tto: email.from\n\t\t\t});\n\t\t});\n\t}\n\tasync _tryCatch(fn) {\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} catch (e) {\n\t\t\tthrow this.onError(e);\n\t\t}\n\t}\n\t/**\n\t* Automatically wrap custom methods with agent context\n\t* This ensures getCurrentAgent() works in all custom methods without decorators\n\t*/\n\t_autoWrapCustomMethods() {\n\t\tconst basePrototypes = [Agent.prototype, Server.prototype];\n\t\tconst baseMethods = /* @__PURE__ */ new Set();\n\t\tfor (const baseProto of basePrototypes) {\n\t\t\tlet proto$1 = baseProto;\n\t\t\twhile (proto$1 && proto$1 !== Object.prototype) {\n\t\t\t\tconst methodNames = Object.getOwnPropertyNames(proto$1);\n\t\t\t\tfor (const methodName of methodNames) baseMethods.add(methodName);\n\t\t\t\tproto$1 = Object.getPrototypeOf(proto$1);\n\t\t\t}\n\t\t}\n\t\tlet proto = Object.getPrototypeOf(this);\n\t\tlet depth = 0;\n\t\twhile (proto && proto !== Object.prototype && depth < 10) {\n\t\t\tconst methodNames = Object.getOwnPropertyNames(proto);\n\t\t\tfor (const methodName of methodNames) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(proto, methodName);\n\t\t\t\tif (baseMethods.has(methodName) || methodName.startsWith(\"_\") || !descriptor || !!descriptor.get || typeof descriptor.value !== \"function\") continue;\n\t\t\t\tconst wrappedFunction = withAgentContext(this[methodName]);\n\t\t\t\tif (this._isCallable(methodName)) callableMetadata.set(wrappedFunction, callableMetadata.get(this[methodName]));\n\t\t\t\tthis.constructor.prototype[methodName] = wrappedFunction;\n\t\t\t}\n\t\t\tproto = Object.getPrototypeOf(proto);\n\t\t\tdepth++;\n\t\t}\n\t}\n\tonError(connectionOrError, error) {\n\t\tlet theError;\n\t\tif (connectionOrError && error) {\n\t\t\ttheError = error;\n\t\t\tconsole.error(\"Error on websocket connection:\", connectionOrError.id, theError);\n\t\t\tconsole.error(\"Override onError(connection, error) to handle websocket connection errors\");\n\t\t} else {\n\t\t\ttheError = connectionOrError;\n\t\t\tconsole.error(\"Error on server:\", theError);\n\t\t\tconsole.error(\"Override onError(error) to handle server errors\");\n\t\t}\n\t\tthrow theError;\n\t}\n\t/**\n\t* Render content (not implemented in base class)\n\t*/\n\trender() {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n\t/**\n\t* Queue a task to be executed in the future\n\t* @param payload Payload to pass to the callback\n\t* @param callback Name of the method to call\n\t* @returns The ID of the queued task\n\t*/\n\tasync queue(callback, payload) {\n\t\tconst id = nanoid(9);\n\t\tif (typeof callback !== \"string\") throw new Error(\"Callback must be a string\");\n\t\tif (typeof this[callback] !== \"function\") throw new Error(`this.${callback} is not a function`);\n\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)\n VALUES (${id}, ${JSON.stringify(payload)}, ${callback})\n `;\n\t\tthis._flushQueue().catch((e) => {\n\t\t\tconsole.error(\"Error flushing queue:\", e);\n\t\t});\n\t\treturn id;\n\t}\n\tasync _flushQueue() {\n\t\tif (this._flushingQueue) return;\n\t\tthis._flushingQueue = true;\n\t\twhile (true) {\n\t\t\tconst result = this.sql`\n SELECT * FROM cf_agents_queues\n ORDER BY created_at ASC\n `;\n\t\t\tif (!result || result.length === 0) break;\n\t\t\tfor (const row of result || []) {\n\t\t\t\tconst callback = this[row.callback];\n\t\t\t\tif (!callback) {\n\t\t\t\t\tconsole.error(`callback ${row.callback} not found`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst { connection, request, email } = agentContext.getStore() || {};\n\t\t\t\tawait agentContext.run({\n\t\t\t\t\tagent: this,\n\t\t\t\t\tconnection,\n\t\t\t\t\trequest,\n\t\t\t\t\temail\n\t\t\t\t}, async () => {\n\t\t\t\t\tawait callback.bind(this)(JSON.parse(row.payload), row);\n\t\t\t\t\tawait this.dequeue(row.id);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis._flushingQueue = false;\n\t}\n\t/**\n\t* Dequeue a task by ID\n\t* @param id ID of the task to dequeue\n\t*/\n\tasync dequeue(id) {\n\t\tthis.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;\n\t}\n\t/**\n\t* Dequeue all tasks\n\t*/\n\tasync dequeueAll() {\n\t\tthis.sql`DELETE FROM cf_agents_queues`;\n\t}\n\t/**\n\t* Dequeue all tasks by callback\n\t* @param callback Name of the callback to dequeue\n\t*/\n\tasync dequeueAllByCallback(callback) {\n\t\tthis.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;\n\t}\n\t/**\n\t* Get a queued task by ID\n\t* @param id ID of the task to get\n\t* @returns The task or undefined if not found\n\t*/\n\tasync getQueue(id) {\n\t\tconst result = this.sql`\n SELECT * FROM cf_agents_queues WHERE id = ${id}\n `;\n\t\treturn result ? {\n\t\t\t...result[0],\n\t\t\tpayload: JSON.parse(result[0].payload)\n\t\t} : void 0;\n\t}\n\t/**\n\t* Get all queues by key and value\n\t* @param key Key to filter by\n\t* @param value Value to filter by\n\t* @returns Array of matching QueueItem objects\n\t*/\n\tasync getQueues(key, value) {\n\t\treturn this.sql`\n SELECT * FROM cf_agents_queues\n `.filter((row) => JSON.parse(row.payload)[key] === value);\n\t}\n\t/**\n\t* Schedule a task to be executed in the future\n\t* @template T Type of the payload data\n\t* @param when When to execute the task (Date, seconds delay, or cron expression)\n\t* @param callback Name of the method to call\n\t* @param payload Data to pass to the callback\n\t* @returns Schedule object representing the scheduled task\n\t*/\n\tasync schedule(when, callback, payload) {\n\t\tconst id = nanoid(9);\n\t\tconst emitScheduleCreate = (schedule) => this.observability?.emit({\n\t\t\tdisplayMessage: `Schedule ${schedule.id} created`,\n\t\t\tid: nanoid(),\n\t\t\tpayload: {\n\t\t\t\tcallback,\n\t\t\t\tid\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t\ttype: \"schedule:create\"\n\t\t}, this.ctx);\n\t\tif (typeof callback !== \"string\") throw new Error(\"Callback must be a string\");\n\t\tif (typeof this[callback] !== \"function\") throw new Error(`this.${callback} is not a function`);\n\t\tif (when instanceof Date) {\n\t\t\tconst timestamp = Math.floor(when.getTime() / 1e3);\n\t\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})\n `;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t\tconst schedule = {\n\t\t\t\tcallback,\n\t\t\t\tid,\n\t\t\t\tpayload,\n\t\t\t\ttime: timestamp,\n\t\t\t\ttype: \"scheduled\"\n\t\t\t};\n\t\t\temitScheduleCreate(schedule);\n\t\t\treturn schedule;\n\t\t}\n\t\tif (typeof when === \"number\") {\n\t\t\tconst time = new Date(Date.now() + when * 1e3);\n\t\t\tconst timestamp = Math.floor(time.getTime() / 1e3);\n\t\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${timestamp})\n `;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t\tconst schedule = {\n\t\t\t\tcallback,\n\t\t\t\tdelayInSeconds: when,\n\t\t\t\tid,\n\t\t\t\tpayload,\n\t\t\t\ttime: timestamp,\n\t\t\t\ttype: \"delayed\"\n\t\t\t};\n\t\t\temitScheduleCreate(schedule);\n\t\t\treturn schedule;\n\t\t}\n\t\tif (typeof when === \"string\") {\n\t\t\tconst nextExecutionTime = getNextCronTime(when);\n\t\t\tconst timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);\n\t\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'cron', ${when}, ${timestamp})\n `;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t\tconst schedule = {\n\t\t\t\tcallback,\n\t\t\t\tcron: when,\n\t\t\t\tid,\n\t\t\t\tpayload,\n\t\t\t\ttime: timestamp,\n\t\t\t\ttype: \"cron\"\n\t\t\t};\n\t\t\temitScheduleCreate(schedule);\n\t\t\treturn schedule;\n\t\t}\n\t\tthrow new Error(\"Invalid schedule type\");\n\t}\n\t/**\n\t* Get a scheduled task by ID\n\t* @template T Type of the payload data\n\t* @param id ID of the scheduled task\n\t* @returns The Schedule object or undefined if not found\n\t*/\n\tasync getSchedule(id) {\n\t\tconst result = this.sql`\n SELECT * FROM cf_agents_schedules WHERE id = ${id}\n `;\n\t\tif (!result) {\n\t\t\tconsole.error(`schedule ${id} not found`);\n\t\t\treturn;\n\t\t}\n\t\treturn {\n\t\t\t...result[0],\n\t\t\tpayload: JSON.parse(result[0].payload)\n\t\t};\n\t}\n\t/**\n\t* Get scheduled tasks matching the given criteria\n\t* @template T Type of the payload data\n\t* @param criteria Criteria to filter schedules\n\t* @returns Array of matching Schedule objects\n\t*/\n\tgetSchedules(criteria = {}) {\n\t\tlet query = \"SELECT * FROM cf_agents_schedules WHERE 1=1\";\n\t\tconst params = [];\n\t\tif (criteria.id) {\n\t\t\tquery += \" AND id = ?\";\n\t\t\tparams.push(criteria.id);\n\t\t}\n\t\tif (criteria.type) {\n\t\t\tquery += \" AND type = ?\";\n\t\t\tparams.push(criteria.type);\n\t\t}\n\t\tif (criteria.timeRange) {\n\t\t\tquery += \" AND time >= ? AND time <= ?\";\n\t\t\tconst start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);\n\t\t\tconst end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);\n\t\t\tparams.push(Math.floor(start.getTime() / 1e3), Math.floor(end.getTime() / 1e3));\n\t\t}\n\t\treturn this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({\n\t\t\t...row,\n\t\t\tpayload: JSON.parse(row.payload)\n\t\t}));\n\t}\n\t/**\n\t* Cancel a scheduled task\n\t* @param id ID of the task to cancel\n\t* @returns true if the task was cancelled, false otherwise\n\t*/\n\tasync cancelSchedule(id) {\n\t\tconst schedule = await this.getSchedule(id);\n\t\tif (schedule) this.observability?.emit({\n\t\t\tdisplayMessage: `Schedule ${id} cancelled`,\n\t\t\tid: nanoid(),\n\t\t\tpayload: {\n\t\t\t\tcallback: schedule.callback,\n\t\t\t\tid: schedule.id\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t\ttype: \"schedule:cancel\"\n\t\t}, this.ctx);\n\t\tthis.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;\n\t\tawait this._scheduleNextAlarm();\n\t\treturn true;\n\t}\n\tasync _scheduleNextAlarm() {\n\t\tconst result = this.sql`\n SELECT time FROM cf_agents_schedules\n WHERE time >= ${Math.floor(Date.now() / 1e3)}\n ORDER BY time ASC\n LIMIT 1\n `;\n\t\tif (!result) return;\n\t\tif (result.length > 0 && \"time\" in result[0]) {\n\t\t\tconst nextTime = result[0].time * 1e3;\n\t\t\tawait this.ctx.storage.setAlarm(nextTime);\n\t\t}\n\t}\n\t/**\n\t* Destroy the Agent, removing all state and scheduled tasks\n\t*/\n\tasync destroy() {\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_state`;\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_schedules`;\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_queues`;\n\t\tawait this.ctx.storage.deleteAlarm();\n\t\tawait this.ctx.storage.deleteAll();\n\t\tthis._disposables.dispose();\n\t\tawait this.mcp.dispose();\n\t\tthis._destroyed = true;\n\t\tsetTimeout(() => {\n\t\t\tthis.ctx.abort(\"destroyed\");\n\t\t}, 0);\n\t\tthis.observability?.emit({\n\t\t\tdisplayMessage: \"Agent destroyed\",\n\t\t\tid: nanoid(),\n\t\t\tpayload: {},\n\t\t\ttimestamp: Date.now(),\n\t\t\ttype: \"destroy\"\n\t\t}, this.ctx);\n\t}\n\t/**\n\t* Get all methods marked as callable on this Agent\n\t* @returns A map of method names to their metadata\n\t*/\n\t_isCallable(method) {\n\t\treturn callableMetadata.has(this[method]);\n\t}\n\t/**\n\t* Connect to a new MCP Server\n\t*\n\t* @param serverName Name of the MCP server\n\t* @param url MCP Server SSE URL\n\t* @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.\n\t* @param agentsPrefix agents routing prefix if not using `agents`\n\t* @param options MCP client and transport options\n\t* @returns Server id and state - either \"authenticating\" with authUrl, or \"ready\"\n\t* @throws If connection or discovery fails\n\t*/\n\tasync addMcpServer(serverName, url, callbackHost, agentsPrefix = \"agents\", options) {\n\t\tlet resolvedCallbackHost = callbackHost;\n\t\tif (!resolvedCallbackHost) {\n\t\t\tconst { request } = getCurrentAgent();\n\t\t\tif (!request) throw new Error(\"callbackHost is required when not called within a request context\");\n\t\t\tconst requestUrl = new URL(request.url);\n\t\t\tresolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;\n\t\t}\n\t\tconst callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;\n\t\tawait this.mcp.ensureJsonSchema();\n\t\tconst id = nanoid(8);\n\t\tconst authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);\n\t\tauthProvider.serverId = id;\n\t\tconst transportType = options?.transport?.type ?? \"auto\";\n\t\tlet headerTransportOpts = {};\n\t\tif (options?.transport?.headers) headerTransportOpts = {\n\t\t\teventSourceInit: { fetch: (url$1, init) => fetch(url$1, {\n\t\t\t\t...init,\n\t\t\t\theaders: options?.transport?.headers\n\t\t\t}) },\n\t\t\trequestInit: { headers: options?.transport?.headers }\n\t\t};\n\t\tawait this.mcp.registerServer(id, {\n\t\t\turl,\n\t\t\tname: serverName,\n\t\t\tcallbackUrl,\n\t\t\tclient: options?.client,\n\t\t\ttransport: {\n\t\t\t\t...headerTransportOpts,\n\t\t\t\tauthProvider,\n\t\t\t\ttype: transportType\n\t\t\t}\n\t\t});\n\t\tconst result = await this.mcp.connectToServer(id);\n\t\tif (result.state === MCPConnectionState.FAILED) throw new Error(`Failed to connect to MCP server at ${url}: ${result.error}`);\n\t\tif (result.state === MCPConnectionState.AUTHENTICATING) return {\n\t\t\tid,\n\t\t\tstate: result.state,\n\t\t\tauthUrl: result.authUrl\n\t\t};\n\t\tconst discoverResult = await this.mcp.discoverIfConnected(id);\n\t\tif (discoverResult && !discoverResult.success) throw new Error(`Failed to discover MCP server capabilities: ${discoverResult.error}`);\n\t\treturn {\n\t\t\tid,\n\t\t\tstate: MCPConnectionState.READY\n\t\t};\n\t}\n\tasync removeMcpServer(id) {\n\t\tawait this.mcp.removeServer(id);\n\t}\n\tgetMcpServers() {\n\t\tconst mcpState = {\n\t\t\tprompts: this.mcp.listPrompts(),\n\t\t\tresources: this.mcp.listResources(),\n\t\t\tservers: {},\n\t\t\ttools: this.mcp.listTools()\n\t\t};\n\t\tconst servers = this.mcp.listServers();\n\t\tif (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {\n\t\t\tconst serverConn = this.mcp.mcpConnections[server.id];\n\t\t\tlet defaultState = \"not-connected\";\n\t\t\tif (!serverConn && server.auth_url) defaultState = \"authenticating\";\n\t\t\tmcpState.servers[server.id] = {\n\t\t\t\tauth_url: server.auth_url,\n\t\t\t\tcapabilities: serverConn?.serverCapabilities ?? null,\n\t\t\t\tinstructions: serverConn?.instructions ?? null,\n\t\t\t\tname: server.name,\n\t\t\t\tserver_url: server.server_url,\n\t\t\t\tstate: serverConn?.connectionState ?? defaultState\n\t\t\t};\n\t\t}\n\t\treturn mcpState;\n\t}\n\tbroadcastMcpServers() {\n\t\tthis.broadcast(JSON.stringify({\n\t\t\tmcp: this.getMcpServers(),\n\t\t\ttype: MessageType.CF_AGENT_MCP_SERVERS\n\t\t}));\n\t}\n\t/**\n\t* Handle MCP OAuth callback request if it's an OAuth callback.\n\t*\n\t* This method encapsulates the entire OAuth callback flow:\n\t* 1. Checks if the request is an MCP OAuth callback\n\t* 2. Processes the OAuth code exchange\n\t* 3. Establishes the connection if successful\n\t* 4. Broadcasts MCP server state updates\n\t* 5. Returns the appropriate HTTP response\n\t*\n\t* @param request The incoming HTTP request\n\t* @returns Response if this was an OAuth callback, null otherwise\n\t*/\n\tasync handleMcpOAuthCallback(request) {\n\t\tif (!this.mcp.isCallbackRequest(request)) return null;\n\t\tconst result = await this.mcp.handleCallbackRequest(request);\n\t\tif (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {\n\t\t\tconsole.error(\"[Agent handleMcpOAuthCallback] Connection establishment failed:\", error);\n\t\t});\n\t\tthis.broadcastMcpServers();\n\t\treturn this.handleOAuthCallbackResponse(result, request);\n\t}\n\t/**\n\t* Handle OAuth callback response using MCPClientManager configuration\n\t* @param result OAuth callback result\n\t* @param request The original request (needed for base URL)\n\t* @returns Response for the OAuth callback\n\t*/\n\thandleOAuthCallbackResponse(result, request) {\n\t\tconst config = this.mcp.getOAuthCallbackConfig();\n\t\tif (config?.customHandler) return config.customHandler(result);\n\t\tconst baseOrigin = new URL(request.url).origin;\n\t\tif (config?.successRedirect && result.authSuccess) try {\n\t\t\treturn Response.redirect(new URL(config.successRedirect, baseOrigin).href);\n\t\t} catch (e) {\n\t\t\tconsole.error(\"Invalid successRedirect URL:\", config.successRedirect, e);\n\t\t\treturn Response.redirect(baseOrigin);\n\t\t}\n\t\tif (config?.errorRedirect && !result.authSuccess) try {\n\t\t\tconst errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(result.authError || \"Unknown error\")}`;\n\t\t\treturn Response.redirect(new URL(errorUrl, baseOrigin).href);\n\t\t} catch (e) {\n\t\t\tconsole.error(\"Invalid errorRedirect URL:\", config.errorRedirect, e);\n\t\t\treturn Response.redirect(baseOrigin);\n\t\t}\n\t\treturn Response.redirect(baseOrigin);\n\t}\n};\nconst wrappedClasses = /* @__PURE__ */ new Set();\n/**\n* Route a request to the appropriate Agent\n* @param request Request to route\n* @param env Environment containing Agent bindings\n* @param options Routing options\n* @returns Response from the Agent or undefined if no route matched\n*/\nasync function routeAgentRequest(request, env, options) {\n\tconst corsHeaders = options?.cors === true ? {\n\t\t\"Access-Control-Allow-Credentials\": \"true\",\n\t\t\"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n\t\t\"Access-Control-Allow-Origin\": \"*\",\n\t\t\"Access-Control-Max-Age\": \"86400\"\n\t} : options?.cors;\n\tif (request.method === \"OPTIONS\") {\n\t\tif (corsHeaders) return new Response(null, { headers: corsHeaders });\n\t\tconsole.warn(\"Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.\");\n\t}\n\tlet response = await routePartykitRequest(request, env, {\n\t\tprefix: \"agents\",\n\t\t...options\n\t});\n\tif (response && corsHeaders && request.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\" && request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\") {\n\t\tconst newHeaders = new Headers(response.headers);\n\t\tfor (const [key, value] of Object.entries(corsHeaders)) newHeaders.set(key, value);\n\t\tresponse = new Response(response.body, {\n\t\t\tstatus: response.status,\n\t\t\tstatusText: response.statusText,\n\t\t\theaders: newHeaders\n\t\t});\n\t}\n\treturn response;\n}\n/**\n* Create a resolver that uses the message-id header to determine the agent to route the email to\n* @returns A function that resolves the agent to route the email to\n*/\nfunction createHeaderBasedEmailResolver() {\n\treturn async (email, _env) => {\n\t\tconst messageId = email.headers.get(\"message-id\");\n\t\tif (messageId) {\n\t\t\tconst messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);\n\t\t\tif (messageIdMatch) {\n\t\t\t\tconst [, agentId$1, domain] = messageIdMatch;\n\t\t\t\treturn {\n\t\t\t\t\tagentName: domain.split(\".\")[0],\n\t\t\t\t\tagentId: agentId$1\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst references = email.headers.get(\"references\");\n\t\tif (references) {\n\t\t\tconst referencesMatch = references.match(/<([A-Za-z0-9+/]{43}=)@([^>]+)>/);\n\t\t\tif (referencesMatch) {\n\t\t\t\tconst [, base64Id, domain] = referencesMatch;\n\t\t\t\tconst agentId$1 = Buffer.from(base64Id, \"base64\").toString(\"hex\");\n\t\t\t\treturn {\n\t\t\t\t\tagentName: domain.split(\".\")[0],\n\t\t\t\t\tagentId: agentId$1\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst agentName = email.headers.get(\"x-agent-name\");\n\t\tconst agentId = email.headers.get(\"x-agent-id\");\n\t\tif (agentName && agentId) return {\n\t\t\tagentName,\n\t\t\tagentId\n\t\t};\n\t\treturn null;\n\t};\n}\n/**\n* Create a resolver that uses the email address to determine the agent to route the email to\n* @param defaultAgentName The default agent name to use if the email address does not contain a sub-address\n* @returns A function that resolves the agent to route the email to\n*/\nfunction createAddressBasedEmailResolver(defaultAgentName) {\n\treturn async (email, _env) => {\n\t\tconst emailMatch = email.to.match(/^([^+@]+)(?:\\+([^@]+))?@(.+)$/);\n\t\tif (!emailMatch) return null;\n\t\tconst [, localPart, subAddress] = emailMatch;\n\t\tif (subAddress) return {\n\t\t\tagentName: localPart,\n\t\t\tagentId: subAddress\n\t\t};\n\t\treturn {\n\t\t\tagentName: defaultAgentName,\n\t\t\tagentId: localPart\n\t\t};\n\t};\n}\n/**\n* Create a resolver that uses the agentName and agentId to determine the agent to route the email to\n* @param agentName The name of the agent to route the email to\n* @param agentId The id of the agent to route the email to\n* @returns A function that resolves the agent to route the email to\n*/\nfunction createCatchAllEmailResolver(agentName, agentId) {\n\treturn async () => ({\n\t\tagentName,\n\t\tagentId\n\t});\n}\nconst agentMapCache = /* @__PURE__ */ new WeakMap();\n/**\n* Route an email to the appropriate Agent\n* @param email The email to route\n* @param env The environment containing the Agent bindings\n* @param options The options for routing the email\n* @returns A promise that resolves when the email has been routed\n*/\nasync function routeAgentEmail(email, env, options) {\n\tconst routingInfo = await options.resolver(email, env);\n\tif (!routingInfo) {\n\t\tconsole.warn(\"No routing information found for email, dropping message\");\n\t\treturn;\n\t}\n\tif (!agentMapCache.has(env)) {\n\t\tconst map = {};\n\t\tfor (const [key, value] of Object.entries(env)) if (value && typeof value === \"object\" && \"idFromName\" in value && typeof value.idFromName === \"function\") {\n\t\t\tmap[key] = value;\n\t\t\tmap[camelCaseToKebabCase(key)] = value;\n\t\t}\n\t\tagentMapCache.set(env, map);\n\t}\n\tconst agentMap = agentMapCache.get(env);\n\tconst namespace = agentMap[routingInfo.agentName];\n\tif (!namespace) {\n\t\tconst availableAgents = Object.keys(agentMap).filter((key) => !key.includes(\"-\")).join(\", \");\n\t\tthrow new Error(`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`);\n\t}\n\tconst agent = await getAgentByName(namespace, routingInfo.agentId);\n\tconst serialisableEmail = {\n\t\tgetRaw: async () => {\n\t\t\tconst reader = email.raw.getReader();\n\t\t\tconst chunks = [];\n\t\t\tlet done = false;\n\t\t\twhile (!done) {\n\t\t\t\tconst { value, done: readerDone } = await reader.read();\n\t\t\t\tdone = readerDone;\n\t\t\t\tif (value) chunks.push(value);\n\t\t\t}\n\t\t\tconst totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n\t\t\tconst combined = new Uint8Array(totalLength);\n\t\t\tlet offset = 0;\n\t\t\tfor (const chunk of chunks) {\n\t\t\t\tcombined.set(chunk, offset);\n\t\t\t\toffset += chunk.length;\n\t\t\t}\n\t\t\treturn combined;\n\t\t},\n\t\theaders: email.headers,\n\t\trawSize: email.rawSize,\n\t\tsetReject: (reason) => {\n\t\t\temail.setReject(reason);\n\t\t},\n\t\tforward: (rcptTo, headers) => {\n\t\t\treturn email.forward(rcptTo, headers);\n\t\t},\n\t\treply: (options$1) => {\n\t\t\treturn email.reply(new EmailMessage(options$1.from, options$1.to, options$1.raw));\n\t\t},\n\t\tfrom: email.from,\n\t\tto: email.to\n\t};\n\tawait agent._onEmail(serialisableEmail);\n}\n/**\n* Get or create an Agent by name\n* @template Env Environment type containing bindings\n* @template T Type of the Agent class\n* @param namespace Agent namespace\n* @param name Name of the Agent instance\n* @param options Options for Agent creation\n* @returns Promise resolving to an Agent instance stub\n*/\nasync function getAgentByName(namespace, name, options) {\n\treturn getServerByName(namespace, name, options);\n}\n/**\n* A wrapper for streaming responses in callable methods\n*/\nvar StreamingResponse = class {\n\tconstructor(connection, id) {\n\t\tthis._closed = false;\n\t\tthis._connection = connection;\n\t\tthis._id = id;\n\t}\n\t/**\n\t* Send a chunk of data to the client\n\t* @param chunk The data to send\n\t*/\n\tsend(chunk) {\n\t\tif (this._closed) throw new Error(\"StreamingResponse is already closed\");\n\t\tconst response = {\n\t\t\tdone: false,\n\t\t\tid: this._id,\n\t\t\tresult: chunk,\n\t\t\tsuccess: true,\n\t\t\ttype: MessageType.RPC\n\t\t};\n\t\tthis._connection.send(JSON.stringify(response));\n\t}\n\t/**\n\t* End the stream and send the final chunk (if any)\n\t* @param finalChunk Optional final chunk of data to send\n\t*/\n\tend(finalChunk) {\n\t\tif (this._closed) throw new Error(\"StreamingResponse is already closed\");\n\t\tthis._closed = true;\n\t\tconst response = {\n\t\t\tdone: true,\n\t\t\tid: this._id,\n\t\t\tresult: finalChunk,\n\t\t\tsuccess: true,\n\t\t\ttype: MessageType.RPC\n\t\t};\n\t\tthis._connection.send(JSON.stringify(response));\n\t}\n};\n\n//#endregion\nexport { createCatchAllEmailResolver as a, getCurrentAgent as c, unstable_callable as d, genericObservability as f, createAddressBasedEmailResolver as i, routeAgentEmail as l, StreamingResponse as n, createHeaderBasedEmailResolver as o, callable as r, getAgentByName as s, Agent as t, routeAgentRequest as u };\n//# sourceMappingURL=src-D_KKH_4c.js.map","import type { AgentOptions } from \"agents\";\nimport { routeAgentRequest } from \"agents\";\nimport type { Context, Env } from \"hono\";\nimport { env } from \"hono/adapter\";\nimport { createMiddleware } from \"hono/factory\";\n\n/**\n * Configuration options for the Cloudflare Agents middleware\n */\ntype AgentMiddlewareContext<E extends Env> = {\n /** Cloudflare Agents-specific configuration options */\n options?: AgentOptions<E>;\n /** Optional error handler for caught errors */\n onError?: (error: Error) => void;\n};\n\n/**\n * Creates a middleware for handling Cloudflare Agents WebSocket and HTTP requests\n * Processes both WebSocket upgrades and standard HTTP requests, delegating them to Cloudflare Agents\n */\nexport function agentsMiddleware<E extends Env = Env>(\n ctx?: AgentMiddlewareContext<E>\n) {\n return createMiddleware<Env>(async (c, next) => {\n try {\n const handler = isWebSocketUpgrade(c)\n ? handleWebSocketUpgrade\n : handleHttpRequest;\n\n const response = await handler(c, ctx?.options);\n\n return response === null ? await next() : response;\n } catch (error) {\n if (ctx?.onError) {\n ctx.onError(error as Error);\n return next();\n }\n throw error;\n }\n });\n}\n\n/**\n * Checks if the incoming request is a WebSocket upgrade request\n * Looks for the 'upgrade' header with a value of 'websocket' (case-insensitive)\n */\nfunction isWebSocketUpgrade(c: Context): boolean {\n return c.req.header(\"upgrade\")?.toLowerCase() === \"websocket\";\n}\n\n/**\n * Handles WebSocket upgrade requests\n * Returns a WebSocket upgrade response if successful, null otherwise\n */\nasync function handleWebSocketUpgrade<E extends Env>(\n c: Context<E>,\n options?: AgentOptions<E>\n) {\n const response = await routeAgentRequest(\n c.req.raw,\n env(c) satisfies Env,\n options\n );\n\n if (!response?.webSocket) {\n return null;\n }\n\n return new Response(null, {\n status: 101,\n webSocket: response.webSocket\n });\n}\n\n/**\n * Handles standard HTTP requests\n * Forwards the request to Cloudflare Agents and returns the response\n */\nasync function handleHttpRequest<E extends Env>(\n c: Context<E>,\n options?: AgentOptions<E>\n) {\n return routeAgentRequest(c.req.raw, env(c) satisfies Env, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,IAAI,cAA8B,yBAAS,eAAe;AACzD,eAAc,4BAA4B;AAC1C,eAAc,+BAA+B;AAC7C,eAAc,gCAAgC;AAC9C,eAAc,yBAAyB;AACvC,eAAc,kCAAkC;;AAEhD,eAAc,8BAA8B;;AAE5C,eAAc,gCAAgC;AAC9C,eAAc,0BAA0B;AACxC,eAAc,wBAAwB;AACtC,eAAc,oBAAoB;AAClC,eAAc,SAAS;AACvB,QAAO;EACN,EAAE,CAAC;;;;;;;;;ACVL,SAAS,qBAAqB,KAAK;AAClC,KAAI,QAAQ,IAAI,aAAa,IAAI,QAAQ,IAAI,aAAa,CAAE,QAAO,IAAI,aAAa,CAAC,QAAQ,MAAM,IAAI;CACvG,IAAI,aAAa,IAAI,QAAQ,WAAW,WAAW,IAAI,OAAO,aAAa,GAAG;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ACN,QACD;AAED,KAAI,CAAC,UAAU,UACb,QAAO;AAGT,QAAO,IAAI,SAAS,MAAM;EACxB,QAAQ;EACR,WAAW,SAAS;EACrB,CAAC;;;;;;AAOJ,eAAe,kBACb,GACA,SACA;AACA,QAAO,kBAAkB,EAAE,IAAI,KAAK,IAAI,EAAE,EAAgB,QAAQ"}
1
+ {"version":3,"file":"index.js","names":["Agent","env"],"sources":["../../agents/dist/ai-types-CrMqkwc_.js","../../agents/dist/client-B3SR12TQ.js","../../agents/dist/do-oauth-client-provider-CwqK5SXm.js","../../agents/dist/client-CFhjXCiO.js","../../agents/dist/src-tXpYCgas.js","../src/index.ts"],"sourcesContent":["//#region src/ai-types.ts\n/**\n* Enum for message types to improve type safety and maintainability\n*/\nlet MessageType = /* @__PURE__ */ function(MessageType$1) {\n\tMessageType$1[\"CF_AGENT_CHAT_MESSAGES\"] = \"cf_agent_chat_messages\";\n\tMessageType$1[\"CF_AGENT_USE_CHAT_REQUEST\"] = \"cf_agent_use_chat_request\";\n\tMessageType$1[\"CF_AGENT_USE_CHAT_RESPONSE\"] = \"cf_agent_use_chat_response\";\n\tMessageType$1[\"CF_AGENT_CHAT_CLEAR\"] = \"cf_agent_chat_clear\";\n\tMessageType$1[\"CF_AGENT_CHAT_REQUEST_CANCEL\"] = \"cf_agent_chat_request_cancel\";\n\t/** Sent by server when client connects and there's an active stream to resume */\n\tMessageType$1[\"CF_AGENT_STREAM_RESUMING\"] = \"cf_agent_stream_resuming\";\n\t/** Sent by client to acknowledge stream resuming notification and request chunks */\n\tMessageType$1[\"CF_AGENT_STREAM_RESUME_ACK\"] = \"cf_agent_stream_resume_ack\";\n\tMessageType$1[\"CF_AGENT_MCP_SERVERS\"] = \"cf_agent_mcp_servers\";\n\tMessageType$1[\"CF_MCP_AGENT_EVENT\"] = \"cf_mcp_agent_event\";\n\tMessageType$1[\"CF_AGENT_STATE\"] = \"cf_agent_state\";\n\tMessageType$1[\"RPC\"] = \"rpc\";\n\treturn MessageType$1;\n}({});\n\n//#endregion\nexport { MessageType as t };\n//# sourceMappingURL=ai-types-CrMqkwc_.js.map","import { t as MessageType } from \"./ai-types-CrMqkwc_.js\";\nimport { PartySocket } from \"partysocket\";\n\n//#region src/client.ts\n/**\n* Convert a camelCase string to a kebab-case string\n* @param str The string to convert\n* @returns The kebab-case string\n*/\nfunction camelCaseToKebabCase(str) {\n\tif (str === str.toUpperCase() && str !== str.toLowerCase()) return str.toLowerCase().replace(/_/g, \"-\");\n\tlet kebabified = str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n\tkebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n\treturn kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n/**\n* WebSocket client for connecting to an Agent\n*/\nvar AgentClient = class extends PartySocket {\n\t/**\n\t* @deprecated Use agentFetch instead\n\t*/\n\tstatic fetch(_opts) {\n\t\tthrow new Error(\"AgentClient.fetch is not implemented, use agentFetch instead\");\n\t}\n\tconstructor(options) {\n\t\tconst agentNamespace = camelCaseToKebabCase(options.agent);\n\t\tsuper({\n\t\t\tparty: agentNamespace,\n\t\t\tprefix: \"agents\",\n\t\t\troom: options.name || \"default\",\n\t\t\t...options\n\t\t});\n\t\tthis._pendingCalls = /* @__PURE__ */ new Map();\n\t\tthis.agent = agentNamespace;\n\t\tthis.name = options.name || \"default\";\n\t\tthis.options = options;\n\t\tthis.addEventListener(\"message\", (event) => {\n\t\t\tif (typeof event.data === \"string\") {\n\t\t\t\tlet parsedMessage;\n\t\t\t\ttry {\n\t\t\t\t\tparsedMessage = JSON.parse(event.data);\n\t\t\t\t} catch (_error) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (parsedMessage.type === MessageType.CF_AGENT_STATE) {\n\t\t\t\t\tthis.options.onStateUpdate?.(parsedMessage.state, \"server\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (parsedMessage.type === MessageType.RPC) {\n\t\t\t\t\tconst response = parsedMessage;\n\t\t\t\t\tconst pending = this._pendingCalls.get(response.id);\n\t\t\t\t\tif (!pending) return;\n\t\t\t\t\tif (!response.success) {\n\t\t\t\t\t\tpending.reject(new Error(response.error));\n\t\t\t\t\t\tthis._pendingCalls.delete(response.id);\n\t\t\t\t\t\tpending.stream?.onError?.(response.error);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"done\" in response) if (response.done) {\n\t\t\t\t\t\tpending.resolve(response.result);\n\t\t\t\t\t\tthis._pendingCalls.delete(response.id);\n\t\t\t\t\t\tpending.stream?.onDone?.(response.result);\n\t\t\t\t\t} else pending.stream?.onChunk?.(response.result);\n\t\t\t\t\telse {\n\t\t\t\t\t\tpending.resolve(response.result);\n\t\t\t\t\t\tthis._pendingCalls.delete(response.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\tsetState(state) {\n\t\tthis.send(JSON.stringify({\n\t\t\tstate,\n\t\t\ttype: MessageType.CF_AGENT_STATE\n\t\t}));\n\t\tthis.options.onStateUpdate?.(state, \"client\");\n\t}\n\tasync call(method, args = [], streamOptions) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst id = Math.random().toString(36).slice(2);\n\t\t\tthis._pendingCalls.set(id, {\n\t\t\t\treject,\n\t\t\t\tresolve: (value) => resolve(value),\n\t\t\t\tstream: streamOptions,\n\t\t\t\ttype: null\n\t\t\t});\n\t\t\tconst request = {\n\t\t\t\targs,\n\t\t\t\tid,\n\t\t\t\tmethod,\n\t\t\t\ttype: MessageType.RPC\n\t\t\t};\n\t\t\tthis.send(JSON.stringify(request));\n\t\t});\n\t}\n};\n/**\n* Make an HTTP request to an Agent\n* @param opts Connection options\n* @param init Request initialization options\n* @returns Promise resolving to a Response\n*/\nfunction agentFetch(opts, init) {\n\tconst agentNamespace = camelCaseToKebabCase(opts.agent);\n\treturn PartySocket.fetch({\n\t\tparty: agentNamespace,\n\t\tprefix: \"agents\",\n\t\troom: opts.name || \"default\",\n\t\t...opts\n\t}, init);\n}\n\n//#endregion\nexport { agentFetch as n, camelCaseToKebabCase as r, AgentClient as t };\n//# sourceMappingURL=client-B3SR12TQ.js.map","import { nanoid } from \"nanoid\";\n\n//#region src/mcp/do-oauth-client-provider.ts\nvar DurableObjectOAuthClientProvider = class {\n\tconstructor(storage, clientName, baseRedirectUrl) {\n\t\tthis.storage = storage;\n\t\tthis.clientName = clientName;\n\t\tthis.baseRedirectUrl = baseRedirectUrl;\n\t\tif (!storage) throw new Error(\"DurableObjectOAuthClientProvider requires a valid DurableObjectStorage instance\");\n\t}\n\tget clientMetadata() {\n\t\treturn {\n\t\t\tclient_name: this.clientName,\n\t\t\tclient_uri: this.clientUri,\n\t\t\tgrant_types: [\"authorization_code\", \"refresh_token\"],\n\t\t\tredirect_uris: [this.redirectUrl],\n\t\t\tresponse_types: [\"code\"],\n\t\t\ttoken_endpoint_auth_method: \"none\"\n\t\t};\n\t}\n\tget clientUri() {\n\t\treturn new URL(this.redirectUrl).origin;\n\t}\n\tget redirectUrl() {\n\t\treturn `${this.baseRedirectUrl}/${this.serverId}`;\n\t}\n\tget clientId() {\n\t\tif (!this._clientId_) throw new Error(\"Trying to access clientId before it was set\");\n\t\treturn this._clientId_;\n\t}\n\tset clientId(clientId_) {\n\t\tthis._clientId_ = clientId_;\n\t}\n\tget serverId() {\n\t\tif (!this._serverId_) throw new Error(\"Trying to access serverId before it was set\");\n\t\treturn this._serverId_;\n\t}\n\tset serverId(serverId_) {\n\t\tthis._serverId_ = serverId_;\n\t}\n\tkeyPrefix(clientId) {\n\t\treturn `/${this.clientName}/${this.serverId}/${clientId}`;\n\t}\n\tclientInfoKey(clientId) {\n\t\treturn `${this.keyPrefix(clientId)}/client_info/`;\n\t}\n\tasync clientInformation() {\n\t\tif (!this._clientId_) return;\n\t\treturn await this.storage.get(this.clientInfoKey(this.clientId)) ?? void 0;\n\t}\n\tasync saveClientInformation(clientInformation) {\n\t\tawait this.storage.put(this.clientInfoKey(clientInformation.client_id), clientInformation);\n\t\tthis.clientId = clientInformation.client_id;\n\t}\n\ttokenKey(clientId) {\n\t\treturn `${this.keyPrefix(clientId)}/token`;\n\t}\n\tasync tokens() {\n\t\tif (!this._clientId_) return;\n\t\treturn await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;\n\t}\n\tasync saveTokens(tokens) {\n\t\tawait this.storage.put(this.tokenKey(this.clientId), tokens);\n\t}\n\tget authUrl() {\n\t\treturn this._authUrl_;\n\t}\n\t/**\n\t* Because this operates on the server side (but we need browser auth), we send this url back to the user\n\t* and require user interact to initiate the redirect flow\n\t*/\n\tasync redirectToAuthorization(authUrl) {\n\t\tconst stateToken = nanoid();\n\t\tauthUrl.searchParams.set(\"state\", stateToken);\n\t\tthis._authUrl_ = authUrl.toString();\n\t}\n\tcodeVerifierKey(clientId) {\n\t\treturn `${this.keyPrefix(clientId)}/code_verifier`;\n\t}\n\tasync saveCodeVerifier(verifier) {\n\t\tconst key = this.codeVerifierKey(this.clientId);\n\t\tif (await this.storage.get(key)) return;\n\t\tawait this.storage.put(key, verifier);\n\t}\n\tasync codeVerifier() {\n\t\tconst codeVerifier = await this.storage.get(this.codeVerifierKey(this.clientId));\n\t\tif (!codeVerifier) throw new Error(\"No code verifier found\");\n\t\treturn codeVerifier;\n\t}\n};\n\n//#endregion\nexport { DurableObjectOAuthClientProvider as t };\n//# sourceMappingURL=do-oauth-client-provider-CwqK5SXm.js.map","import { t as DurableObjectOAuthClientProvider } from \"./do-oauth-client-provider-CwqK5SXm.js\";\nimport { nanoid } from \"nanoid\";\nimport { CfWorkerJsonSchemaValidator } from \"@modelcontextprotocol/sdk/validation/cfworker-provider.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { ElicitRequestSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from \"@modelcontextprotocol/sdk/types.js\";\n\n//#region src/core/events.ts\nfunction toDisposable(fn) {\n\treturn { dispose: fn };\n}\nvar DisposableStore = class {\n\tconstructor() {\n\t\tthis._items = [];\n\t}\n\tadd(d) {\n\t\tthis._items.push(d);\n\t\treturn d;\n\t}\n\tdispose() {\n\t\twhile (this._items.length) try {\n\t\t\tthis._items.pop().dispose();\n\t\t} catch {}\n\t}\n};\nvar Emitter = class {\n\tconstructor() {\n\t\tthis._listeners = /* @__PURE__ */ new Set();\n\t\tthis.event = (listener) => {\n\t\t\tthis._listeners.add(listener);\n\t\t\treturn toDisposable(() => this._listeners.delete(listener));\n\t\t};\n\t}\n\tfire(data) {\n\t\tfor (const listener of [...this._listeners]) try {\n\t\t\tlistener(data);\n\t\t} catch (err) {\n\t\t\tconsole.error(\"Emitter listener error:\", err);\n\t\t}\n\t}\n\tdispose() {\n\t\tthis._listeners.clear();\n\t}\n};\n\n//#endregion\n//#region src/mcp/errors.ts\nfunction toErrorMessage(error) {\n\treturn error instanceof Error ? error.message : String(error);\n}\nfunction isUnauthorized(error) {\n\tconst msg = toErrorMessage(error);\n\treturn msg.includes(\"Unauthorized\") || msg.includes(\"401\");\n}\nfunction isTransportNotImplemented(error) {\n\tconst msg = toErrorMessage(error);\n\treturn msg.includes(\"404\") || msg.includes(\"405\") || msg.includes(\"Not Implemented\") || msg.includes(\"not implemented\");\n}\n\n//#endregion\n//#region src/mcp/client-connection.ts\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*/\nconst MCPConnectionState = {\n\tAUTHENTICATING: \"authenticating\",\n\tCONNECTING: \"connecting\",\n\tCONNECTED: \"connected\",\n\tDISCOVERING: \"discovering\",\n\tREADY: \"ready\",\n\tFAILED: \"failed\"\n};\nvar MCPClientConnection = class {\n\tconstructor(url, info, options = {\n\t\tclient: {},\n\t\ttransport: {}\n\t}) {\n\t\tthis.url = url;\n\t\tthis.options = options;\n\t\tthis.connectionState = MCPConnectionState.CONNECTING;\n\t\tthis.tools = [];\n\t\tthis.prompts = [];\n\t\tthis.resources = [];\n\t\tthis.resourceTemplates = [];\n\t\tthis._onObservabilityEvent = new Emitter();\n\t\tthis.onObservabilityEvent = this._onObservabilityEvent.event;\n\t\tthis.client = new Client(info, {\n\t\t\t...options.client,\n\t\t\tcapabilities: {\n\t\t\t\t...options.client?.capabilities,\n\t\t\t\telicitation: {}\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* Initialize a client connection, if authentication is required, the connection will be in the AUTHENTICATING state\n\t* Sets connection state based on the result and emits observability events\n\t*\n\t* @returns Error message if connection failed, undefined otherwise\n\t*/\n\tasync init() {\n\t\tconst transportType = this.options.transport.type;\n\t\tif (!transportType) throw new Error(\"Transport type must be specified\");\n\t\tconst res = await this.tryConnect(transportType);\n\t\tthis.connectionState = res.state;\n\t\tif (res.state === MCPConnectionState.CONNECTED && res.transport) {\n\t\t\tthis.client.setRequestHandler(ElicitRequestSchema, async (request) => {\n\t\t\t\treturn await this.handleElicitationRequest(request);\n\t\t\t});\n\t\t\tthis.lastConnectedTransport = res.transport;\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `Connected successfully using ${res.transport} transport for ${this.url.toString()}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl: this.url.toString(),\n\t\t\t\t\ttransport: res.transport,\n\t\t\t\t\tstate: this.connectionState\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn;\n\t\t} else if (res.state === MCPConnectionState.FAILED && res.error) {\n\t\t\tconst errorMessage = toErrorMessage(res.error);\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `Failed to connect to ${this.url.toString()}: ${errorMessage}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl: this.url.toString(),\n\t\t\t\t\ttransport: transportType,\n\t\t\t\t\tstate: this.connectionState,\n\t\t\t\t\terror: errorMessage\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn errorMessage;\n\t\t}\n\t}\n\t/**\n\t* Finish OAuth by probing transports based on configured type.\n\t* - Explicit: finish on that transport\n\t* - Auto: try streamable-http, then sse on 404/405/Not Implemented\n\t*/\n\tasync finishAuthProbe(code) {\n\t\tif (!this.options.transport.authProvider) throw new Error(\"No auth provider configured\");\n\t\tconst configuredType = this.options.transport.type;\n\t\tif (!configuredType) throw new Error(\"Transport type must be specified\");\n\t\tconst finishAuth = async (base) => {\n\t\t\tawait this.getTransport(base).finishAuth(code);\n\t\t};\n\t\tif (configuredType === \"sse\" || configuredType === \"streamable-http\") {\n\t\t\tawait finishAuth(configuredType);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait finishAuth(\"streamable-http\");\n\t\t} catch (e) {\n\t\t\tif (isTransportNotImplemented(e)) {\n\t\t\t\tawait finishAuth(\"sse\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\t/**\n\t* Complete OAuth authorization\n\t*/\n\tasync completeAuthorization(code) {\n\t\tif (this.connectionState !== MCPConnectionState.AUTHENTICATING) throw new Error(\"Connection must be in authenticating state to complete authorization\");\n\t\ttry {\n\t\t\tawait this.finishAuthProbe(code);\n\t\t\tthis.connectionState = MCPConnectionState.CONNECTING;\n\t\t} catch (error) {\n\t\t\tthis.connectionState = MCPConnectionState.FAILED;\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t* Discover server capabilities and register tools, resources, prompts, and templates.\n\t* This method does the work but does not manage connection state - that's handled by discover().\n\t*/\n\tasync discoverAndRegister() {\n\t\tthis.serverCapabilities = this.client.getServerCapabilities();\n\t\tif (!this.serverCapabilities) throw new Error(\"The MCP Server failed to return server capabilities\");\n\t\tconst operations = [];\n\t\tconst operationNames = [];\n\t\toperations.push(Promise.resolve(this.client.getInstructions()));\n\t\toperationNames.push(\"instructions\");\n\t\tif (this.serverCapabilities.tools) {\n\t\t\toperations.push(this.registerTools());\n\t\t\toperationNames.push(\"tools\");\n\t\t}\n\t\tif (this.serverCapabilities.resources) {\n\t\t\toperations.push(this.registerResources());\n\t\t\toperationNames.push(\"resources\");\n\t\t}\n\t\tif (this.serverCapabilities.prompts) {\n\t\t\toperations.push(this.registerPrompts());\n\t\t\toperationNames.push(\"prompts\");\n\t\t}\n\t\tif (this.serverCapabilities.resources) {\n\t\t\toperations.push(this.registerResourceTemplates());\n\t\t\toperationNames.push(\"resource templates\");\n\t\t}\n\t\ttry {\n\t\t\tconst results = await Promise.all(operations);\n\t\t\tfor (let i = 0; i < results.length; i++) {\n\t\t\t\tconst result = results[i];\n\t\t\t\tswitch (operationNames[i]) {\n\t\t\t\t\tcase \"instructions\":\n\t\t\t\t\t\tthis.instructions = result;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tools\":\n\t\t\t\t\t\tthis.tools = result;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"resources\":\n\t\t\t\t\t\tthis.resources = result;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"prompts\":\n\t\t\t\t\t\tthis.prompts = result;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"resource templates\":\n\t\t\t\t\t\tthis.resourceTemplates = result;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\tdisplayMessage: `Failed to discover capabilities for ${this.url.toString()}: ${toErrorMessage(error)}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl: this.url.toString(),\n\t\t\t\t\terror: toErrorMessage(error)\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t* Discover server capabilities with timeout and cancellation support.\n\t* If called while a previous discovery is in-flight, the previous discovery will be aborted.\n\t*\n\t* @param options Optional configuration\n\t* @param options.timeoutMs Timeout in milliseconds (default: 15000)\n\t* @returns Result indicating success/failure with optional error message\n\t*/\n\tasync discover(options = {}) {\n\t\tconst { timeoutMs = 15e3 } = options;\n\t\tif (this.connectionState !== MCPConnectionState.CONNECTED && this.connectionState !== MCPConnectionState.READY) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\tdisplayMessage: `Discovery skipped for ${this.url.toString()}, state is ${this.connectionState}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl: this.url.toString(),\n\t\t\t\t\tstate: this.connectionState\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: `Discovery skipped - connection in ${this.connectionState} state`\n\t\t\t};\n\t\t}\n\t\tif (this._discoveryAbortController) {\n\t\t\tthis._discoveryAbortController.abort();\n\t\t\tthis._discoveryAbortController = void 0;\n\t\t}\n\t\tconst abortController = new AbortController();\n\t\tthis._discoveryAbortController = abortController;\n\t\tthis.connectionState = MCPConnectionState.DISCOVERING;\n\t\tlet timeoutId;\n\t\ttry {\n\t\t\tconst timeoutPromise = new Promise((_, reject) => {\n\t\t\t\ttimeoutId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Discovery timed out after ${timeoutMs}ms`)), timeoutMs);\n\t\t\t});\n\t\t\tif (abortController.signal.aborted) throw new Error(\"Discovery was cancelled\");\n\t\t\tconst abortPromise = new Promise((_, reject) => {\n\t\t\t\tabortController.signal.addEventListener(\"abort\", () => {\n\t\t\t\t\treject(/* @__PURE__ */ new Error(\"Discovery was cancelled\"));\n\t\t\t\t});\n\t\t\t});\n\t\t\tawait Promise.race([\n\t\t\t\tthis.discoverAndRegister(),\n\t\t\t\ttimeoutPromise,\n\t\t\t\tabortPromise\n\t\t\t]);\n\t\t\tif (timeoutId !== void 0) clearTimeout(timeoutId);\n\t\t\tthis.connectionState = MCPConnectionState.READY;\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\tdisplayMessage: `Discovery completed for ${this.url.toString()}`,\n\t\t\t\tpayload: { url: this.url.toString() },\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn { success: true };\n\t\t} catch (e) {\n\t\t\tif (timeoutId !== void 0) clearTimeout(timeoutId);\n\t\t\tthis.connectionState = MCPConnectionState.CONNECTED;\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: e instanceof Error ? e.message : String(e)\n\t\t\t};\n\t\t} finally {\n\t\t\tthis._discoveryAbortController = void 0;\n\t\t}\n\t}\n\t/**\n\t* Cancel any in-flight discovery operation.\n\t* Called when closing the connection.\n\t*/\n\tcancelDiscovery() {\n\t\tif (this._discoveryAbortController) {\n\t\t\tthis._discoveryAbortController.abort();\n\t\t\tthis._discoveryAbortController = void 0;\n\t\t}\n\t}\n\t/**\n\t* Notification handler registration for tools\n\t* Should only be called if serverCapabilities.tools exists\n\t*/\n\tasync registerTools() {\n\t\tif (this.serverCapabilities?.tools?.listChanged) this.client.setNotificationHandler(ToolListChangedNotificationSchema, async (_notification) => {\n\t\t\tthis.tools = await this.fetchTools();\n\t\t});\n\t\treturn this.fetchTools();\n\t}\n\t/**\n\t* Notification handler registration for resources\n\t* Should only be called if serverCapabilities.resources exists\n\t*/\n\tasync registerResources() {\n\t\tif (this.serverCapabilities?.resources?.listChanged) this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_notification) => {\n\t\t\tthis.resources = await this.fetchResources();\n\t\t});\n\t\treturn this.fetchResources();\n\t}\n\t/**\n\t* Notification handler registration for prompts\n\t* Should only be called if serverCapabilities.prompts exists\n\t*/\n\tasync registerPrompts() {\n\t\tif (this.serverCapabilities?.prompts?.listChanged) this.client.setNotificationHandler(PromptListChangedNotificationSchema, async (_notification) => {\n\t\t\tthis.prompts = await this.fetchPrompts();\n\t\t});\n\t\treturn this.fetchPrompts();\n\t}\n\tasync registerResourceTemplates() {\n\t\treturn this.fetchResourceTemplates();\n\t}\n\tasync fetchTools() {\n\t\tlet toolsAgg = [];\n\t\tlet toolsResult = { tools: [] };\n\t\tdo {\n\t\t\ttoolsResult = await this.client.listTools({ cursor: toolsResult.nextCursor }).catch(this._capabilityErrorHandler({ tools: [] }, \"tools/list\"));\n\t\t\ttoolsAgg = toolsAgg.concat(toolsResult.tools);\n\t\t} while (toolsResult.nextCursor);\n\t\treturn toolsAgg;\n\t}\n\tasync fetchResources() {\n\t\tlet resourcesAgg = [];\n\t\tlet resourcesResult = { resources: [] };\n\t\tdo {\n\t\t\tresourcesResult = await this.client.listResources({ cursor: resourcesResult.nextCursor }).catch(this._capabilityErrorHandler({ resources: [] }, \"resources/list\"));\n\t\t\tresourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n\t\t} while (resourcesResult.nextCursor);\n\t\treturn resourcesAgg;\n\t}\n\tasync fetchPrompts() {\n\t\tlet promptsAgg = [];\n\t\tlet promptsResult = { prompts: [] };\n\t\tdo {\n\t\t\tpromptsResult = await this.client.listPrompts({ cursor: promptsResult.nextCursor }).catch(this._capabilityErrorHandler({ prompts: [] }, \"prompts/list\"));\n\t\t\tpromptsAgg = promptsAgg.concat(promptsResult.prompts);\n\t\t} while (promptsResult.nextCursor);\n\t\treturn promptsAgg;\n\t}\n\tasync fetchResourceTemplates() {\n\t\tlet templatesAgg = [];\n\t\tlet templatesResult = { resourceTemplates: [] };\n\t\tdo {\n\t\t\ttemplatesResult = await this.client.listResourceTemplates({ cursor: templatesResult.nextCursor }).catch(this._capabilityErrorHandler({ resourceTemplates: [] }, \"resources/templates/list\"));\n\t\t\ttemplatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n\t\t} while (templatesResult.nextCursor);\n\t\treturn templatesAgg;\n\t}\n\t/**\n\t* Handle elicitation request from server\n\t* Automatically uses the Agent's built-in elicitation handling if available\n\t*/\n\tasync handleElicitationRequest(_request) {\n\t\tthrow new Error(\"Elicitation handler must be implemented for your platform. Override handleElicitationRequest method.\");\n\t}\n\t/**\n\t* Get the transport for the client\n\t* @param transportType - The transport type to get\n\t* @returns The transport for the client\n\t*/\n\tgetTransport(transportType) {\n\t\tswitch (transportType) {\n\t\t\tcase \"streamable-http\": return new StreamableHTTPClientTransport(this.url, this.options.transport);\n\t\t\tcase \"sse\": return new SSEClientTransport(this.url, this.options.transport);\n\t\t\tdefault: throw new Error(`Unsupported transport type: ${transportType}`);\n\t\t}\n\t}\n\tasync tryConnect(transportType) {\n\t\tconst transports = transportType === \"auto\" ? [\"streamable-http\", \"sse\"] : [transportType];\n\t\tfor (const currentTransportType of transports) {\n\t\t\tconst isLastTransport = currentTransportType === transports[transports.length - 1];\n\t\t\tconst hasFallback = transportType === \"auto\" && currentTransportType === \"streamable-http\" && !isLastTransport;\n\t\t\tconst transport = this.getTransport(currentTransportType);\n\t\t\ttry {\n\t\t\t\tawait this.client.connect(transport);\n\t\t\t\treturn {\n\t\t\t\t\tstate: MCPConnectionState.CONNECTED,\n\t\t\t\t\ttransport: currentTransportType\n\t\t\t\t};\n\t\t\t} catch (e) {\n\t\t\t\tconst error = e instanceof Error ? e : new Error(String(e));\n\t\t\t\tif (isUnauthorized(error)) return { state: MCPConnectionState.AUTHENTICATING };\n\t\t\t\tif (isTransportNotImplemented(error) && hasFallback) continue;\n\t\t\t\treturn {\n\t\t\t\t\tstate: MCPConnectionState.FAILED,\n\t\t\t\t\terror\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tstate: MCPConnectionState.FAILED,\n\t\t\terror: /* @__PURE__ */ new Error(\"No transports available\")\n\t\t};\n\t}\n\t_capabilityErrorHandler(empty, method) {\n\t\treturn (e) => {\n\t\t\tif (e.code === -32601) {\n\t\t\t\tconst url = this.url.toString();\n\t\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\t\tdisplayMessage: `The server advertised support for the capability ${method.split(\"/\")[0]}, but returned \"Method not found\" for '${method}' for ${url}`,\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\turl,\n\t\t\t\t\t\tcapability: method.split(\"/\")[0],\n\t\t\t\t\t\terror: toErrorMessage(e)\n\t\t\t\t\t},\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\tid: nanoid()\n\t\t\t\t});\n\t\t\t\treturn empty;\n\t\t\t}\n\t\t\tthrow e;\n\t\t};\n\t}\n};\n\n//#endregion\n//#region src/mcp/client.ts\nconst defaultClientOptions = { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() };\n/**\n* Utility class that aggregates multiple MCP clients into one\n*/\nvar MCPClientManager = class {\n\t/**\n\t* @param _name Name of the MCP client\n\t* @param _version Version of the MCP Client\n\t* @param options Storage adapter for persisting MCP server state\n\t*/\n\tconstructor(_name, _version, options) {\n\t\tthis._name = _name;\n\t\tthis._version = _version;\n\t\tthis.mcpConnections = {};\n\t\tthis._didWarnAboutUnstableGetAITools = false;\n\t\tthis._connectionDisposables = /* @__PURE__ */ new Map();\n\t\tthis._isRestored = false;\n\t\tthis._onObservabilityEvent = new Emitter();\n\t\tthis.onObservabilityEvent = this._onObservabilityEvent.event;\n\t\tthis._onServerStateChanged = new Emitter();\n\t\tthis.onServerStateChanged = this._onServerStateChanged.event;\n\t\tif (!options.storage) throw new Error(\"MCPClientManager requires a valid DurableObjectStorage instance\");\n\t\tthis._storage = options.storage;\n\t}\n\tsql(query, ...bindings) {\n\t\treturn [...this._storage.sql.exec(query, ...bindings)];\n\t}\n\tsaveServerToStorage(server) {\n\t\tthis.sql(`INSERT OR REPLACE INTO cf_agents_mcp_servers (\n id, name, server_url, client_id, auth_url, callback_url, server_options\n ) VALUES (?, ?, ?, ?, ?, ?, ?)`, server.id, server.name, server.server_url, server.client_id ?? null, server.auth_url ?? null, server.callback_url, server.server_options ?? null);\n\t}\n\tremoveServerFromStorage(serverId) {\n\t\tthis.sql(\"DELETE FROM cf_agents_mcp_servers WHERE id = ?\", serverId);\n\t}\n\tgetServersFromStorage() {\n\t\treturn this.sql(\"SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers\");\n\t}\n\tclearServerAuthUrl(serverId) {\n\t\tthis.sql(\"UPDATE cf_agents_mcp_servers SET auth_url = NULL WHERE id = ?\", serverId);\n\t}\n\t/**\n\t* Create an auth provider for a server\n\t* @internal\n\t*/\n\tcreateAuthProvider(serverId, callbackUrl, clientName, clientId) {\n\t\tif (!this._storage) throw new Error(\"Cannot create auth provider: storage is not initialized\");\n\t\tconst authProvider = new DurableObjectOAuthClientProvider(this._storage, clientName, callbackUrl);\n\t\tauthProvider.serverId = serverId;\n\t\tif (clientId) authProvider.clientId = clientId;\n\t\treturn authProvider;\n\t}\n\t/**\n\t* Restore MCP server connections from storage\n\t* This method is called on Agent initialization to restore previously connected servers\n\t*\n\t* @param clientName Name to use for OAuth client (typically the agent instance name)\n\t*/\n\tasync restoreConnectionsFromStorage(clientName) {\n\t\tif (this._isRestored) return;\n\t\tconst servers = this.getServersFromStorage();\n\t\tif (!servers || servers.length === 0) {\n\t\t\tthis._isRestored = true;\n\t\t\treturn;\n\t\t}\n\t\tfor (const server of servers) {\n\t\t\tconst existingConn = this.mcpConnections[server.id];\n\t\t\tif (existingConn) {\n\t\t\t\tif (existingConn.connectionState === MCPConnectionState.READY) {\n\t\t\t\t\tconsole.warn(`[MCPClientManager] Server ${server.id} already has a ready connection. Skipping recreation.`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (existingConn.connectionState === MCPConnectionState.AUTHENTICATING || existingConn.connectionState === MCPConnectionState.CONNECTING || existingConn.connectionState === MCPConnectionState.DISCOVERING) continue;\n\t\t\t\tif (existingConn.connectionState === MCPConnectionState.FAILED) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait existingConn.client.close();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconsole.warn(`[MCPClientManager] Error closing failed connection ${server.id}:`, error);\n\t\t\t\t\t}\n\t\t\t\t\tdelete this.mcpConnections[server.id];\n\t\t\t\t\tthis._connectionDisposables.get(server.id)?.dispose();\n\t\t\t\t\tthis._connectionDisposables.delete(server.id);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst parsedOptions = server.server_options ? JSON.parse(server.server_options) : null;\n\t\t\tconst authProvider = this.createAuthProvider(server.id, server.callback_url, clientName, server.client_id ?? void 0);\n\t\t\tconst conn = this.createConnection(server.id, server.server_url, {\n\t\t\t\tclient: parsedOptions?.client ?? {},\n\t\t\t\ttransport: {\n\t\t\t\t\t...parsedOptions?.transport ?? {},\n\t\t\t\t\ttype: parsedOptions?.transport?.type ?? \"auto\",\n\t\t\t\t\tauthProvider\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (server.auth_url) {\n\t\t\t\tconn.connectionState = MCPConnectionState.AUTHENTICATING;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis._restoreServer(server.id);\n\t\t}\n\t\tthis._isRestored = true;\n\t}\n\t/**\n\t* Internal method to restore a single server connection and discovery\n\t*/\n\tasync _restoreServer(serverId) {\n\t\tif ((await this.connectToServer(serverId).catch((error) => {\n\t\t\tconsole.error(`Error connecting to ${serverId}:`, error);\n\t\t\treturn null;\n\t\t}))?.state === MCPConnectionState.CONNECTED) {\n\t\t\tconst discoverResult = await this.discoverIfConnected(serverId);\n\t\t\tif (discoverResult && !discoverResult.success) console.error(`Error discovering ${serverId}:`, discoverResult.error);\n\t\t}\n\t}\n\t/**\n\t* Connect to and register an MCP server\n\t*\n\t* @deprecated This method is maintained for backward compatibility.\n\t* For new code, use registerServer() and connectToServer() separately.\n\t*\n\t* @param url Server URL\n\t* @param options Connection options\n\t* @returns Object with server ID, auth URL (if OAuth), and client ID (if OAuth)\n\t*/\n\tasync connect(url, options = {}) {\n\t\t/**\n\t\t* We need to delay loading ai sdk, because putting it in module scope is\n\t\t* causing issues with startup time.\n\t\t* The only place it's used is in getAITools, which only matters after\n\t\t* .connect() is called on at least one server.\n\t\t* So it's safe to delay loading it until .connect() is called.\n\t\t*/\n\t\tawait this.ensureJsonSchema();\n\t\tconst id = options.reconnect?.id ?? nanoid(8);\n\t\tif (options.transport?.authProvider) {\n\t\t\toptions.transport.authProvider.serverId = id;\n\t\t\tif (options.reconnect?.oauthClientId) options.transport.authProvider.clientId = options.reconnect?.oauthClientId;\n\t\t}\n\t\tif (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {\n\t\t\tconst normalizedTransport = {\n\t\t\t\t...options.transport,\n\t\t\t\ttype: options.transport?.type ?? \"auto\"\n\t\t\t};\n\t\t\tthis.mcpConnections[id] = new MCPClientConnection(new URL(url), {\n\t\t\t\tname: this._name,\n\t\t\t\tversion: this._version\n\t\t\t}, {\n\t\t\t\tclient: options.client ?? {},\n\t\t\t\ttransport: normalizedTransport\n\t\t\t});\n\t\t\tconst store = new DisposableStore();\n\t\t\tconst existing = this._connectionDisposables.get(id);\n\t\t\tif (existing) existing.dispose();\n\t\t\tthis._connectionDisposables.set(id, store);\n\t\t\tstore.add(this.mcpConnections[id].onObservabilityEvent((event) => {\n\t\t\t\tthis._onObservabilityEvent.fire(event);\n\t\t\t}));\n\t\t}\n\t\tawait this.mcpConnections[id].init();\n\t\tif (options.reconnect?.oauthCode) try {\n\t\t\tawait this.mcpConnections[id].completeAuthorization(options.reconnect.oauthCode);\n\t\t\tawait this.mcpConnections[id].init();\n\t\t} catch (error) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `Failed to complete OAuth reconnection for ${id} for ${url}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl,\n\t\t\t\t\ttransport: options.transport?.type ?? \"auto\",\n\t\t\t\t\tstate: this.mcpConnections[id].connectionState,\n\t\t\t\t\terror: toErrorMessage(error)\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid\n\t\t\t});\n\t\t\tthrow error;\n\t\t}\n\t\tconst authUrl = options.transport?.authProvider?.authUrl;\n\t\tif (this.mcpConnections[id].connectionState === MCPConnectionState.AUTHENTICATING && authUrl && options.transport?.authProvider?.redirectUrl) return {\n\t\t\tauthUrl,\n\t\t\tclientId: options.transport?.authProvider?.clientId,\n\t\t\tid\n\t\t};\n\t\tconst discoverResult = await this.discoverIfConnected(id);\n\t\tif (discoverResult && !discoverResult.success) throw new Error(`Failed to discover server capabilities: ${discoverResult.error}`);\n\t\treturn { id };\n\t}\n\t/**\n\t* Create an in-memory connection object and set up observability\n\t* Does NOT save to storage - use registerServer() for that\n\t* @returns The connection object (existing or newly created)\n\t*/\n\tcreateConnection(id, url, options) {\n\t\tif (this.mcpConnections[id]) return this.mcpConnections[id];\n\t\tconst normalizedTransport = {\n\t\t\t...options.transport,\n\t\t\ttype: options.transport?.type ?? \"auto\"\n\t\t};\n\t\tthis.mcpConnections[id] = new MCPClientConnection(new URL(url), {\n\t\t\tname: this._name,\n\t\t\tversion: this._version\n\t\t}, {\n\t\t\tclient: {\n\t\t\t\t...defaultClientOptions,\n\t\t\t\t...options.client\n\t\t\t},\n\t\t\ttransport: normalizedTransport\n\t\t});\n\t\tconst store = new DisposableStore();\n\t\tconst existing = this._connectionDisposables.get(id);\n\t\tif (existing) existing.dispose();\n\t\tthis._connectionDisposables.set(id, store);\n\t\tstore.add(this.mcpConnections[id].onObservabilityEvent((event) => {\n\t\t\tthis._onObservabilityEvent.fire(event);\n\t\t}));\n\t\treturn this.mcpConnections[id];\n\t}\n\t/**\n\t* Register an MCP server connection without connecting\n\t* Creates the connection object, sets up observability, and saves to storage\n\t*\n\t* @param id Server ID\n\t* @param options Registration options including URL, name, callback URL, and connection config\n\t* @returns Server ID\n\t*/\n\tasync registerServer(id, options) {\n\t\tthis.createConnection(id, options.url, {\n\t\t\tclient: options.client,\n\t\t\ttransport: {\n\t\t\t\t...options.transport,\n\t\t\t\ttype: options.transport?.type ?? \"auto\"\n\t\t\t}\n\t\t});\n\t\tconst { authProvider: _, ...transportWithoutAuth } = options.transport ?? {};\n\t\tthis.saveServerToStorage({\n\t\t\tid,\n\t\t\tname: options.name,\n\t\t\tserver_url: options.url,\n\t\t\tcallback_url: options.callbackUrl,\n\t\t\tclient_id: options.clientId ?? null,\n\t\t\tauth_url: options.authUrl ?? null,\n\t\t\tserver_options: JSON.stringify({\n\t\t\t\tclient: options.client,\n\t\t\t\ttransport: transportWithoutAuth\n\t\t\t})\n\t\t});\n\t\tthis._onServerStateChanged.fire();\n\t\treturn id;\n\t}\n\t/**\n\t* Connect to an already registered MCP server and initialize the connection.\n\t*\n\t* For OAuth servers, returns `{ state: \"authenticating\", authUrl, clientId? }`.\n\t* The user must complete the OAuth flow via the authUrl, which triggers a\n\t* callback handled by `handleCallbackRequest()`.\n\t*\n\t* For non-OAuth servers, establishes the transport connection and returns\n\t* `{ state: \"connected\" }`. Call `discoverIfConnected()` afterwards to\n\t* discover capabilities and transition to \"ready\" state.\n\t*\n\t* @param id Server ID (must be registered first via registerServer())\n\t* @returns Connection result with current state and OAuth info (if applicable)\n\t*/\n\tasync connectToServer(id) {\n\t\tconst conn = this.mcpConnections[id];\n\t\tif (!conn) throw new Error(`Server ${id} is not registered. Call registerServer() first.`);\n\t\tconst error = await conn.init();\n\t\tthis._onServerStateChanged.fire();\n\t\tswitch (conn.connectionState) {\n\t\t\tcase MCPConnectionState.FAILED: return {\n\t\t\t\tstate: conn.connectionState,\n\t\t\t\terror: error ?? \"Unknown connection error\"\n\t\t\t};\n\t\t\tcase MCPConnectionState.AUTHENTICATING: {\n\t\t\t\tconst authUrl = conn.options.transport.authProvider?.authUrl;\n\t\t\t\tconst redirectUrl = conn.options.transport.authProvider?.redirectUrl;\n\t\t\t\tif (!authUrl || !redirectUrl) return {\n\t\t\t\t\tstate: MCPConnectionState.FAILED,\n\t\t\t\t\terror: `OAuth configuration incomplete: missing ${!authUrl ? \"authUrl\" : \"redirectUrl\"}`\n\t\t\t\t};\n\t\t\t\tconst clientId = conn.options.transport.authProvider?.clientId;\n\t\t\t\tconst serverRow = this.getServersFromStorage().find((s) => s.id === id);\n\t\t\t\tif (serverRow) this.saveServerToStorage({\n\t\t\t\t\t...serverRow,\n\t\t\t\t\tauth_url: authUrl,\n\t\t\t\t\tclient_id: clientId ?? null\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tstate: conn.connectionState,\n\t\t\t\t\tauthUrl,\n\t\t\t\t\tclientId\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase MCPConnectionState.CONNECTED: return { state: conn.connectionState };\n\t\t\tdefault: return {\n\t\t\t\tstate: MCPConnectionState.FAILED,\n\t\t\t\terror: `Unexpected connection state after init: ${conn.connectionState}`\n\t\t\t};\n\t\t}\n\t}\n\tisCallbackRequest(req) {\n\t\tif (req.method !== \"GET\") return false;\n\t\tif (!req.url.includes(\"/callback\")) return false;\n\t\treturn this.getServersFromStorage().some((server) => server.callback_url && req.url.startsWith(server.callback_url));\n\t}\n\tasync handleCallbackRequest(req) {\n\t\tconst url = new URL(req.url);\n\t\tconst matchingServer = this.getServersFromStorage().find((server) => {\n\t\t\treturn server.callback_url && req.url.startsWith(server.callback_url);\n\t\t});\n\t\tif (!matchingServer) throw new Error(`No callback URI match found for the request url: ${req.url}. Was the request matched with \\`isCallbackRequest()\\`?`);\n\t\tconst serverId = matchingServer.id;\n\t\tconst code = url.searchParams.get(\"code\");\n\t\tconst state = url.searchParams.get(\"state\");\n\t\tconst error = url.searchParams.get(\"error\");\n\t\tconst errorDescription = url.searchParams.get(\"error_description\");\n\t\tif (error) return {\n\t\t\tserverId,\n\t\t\tauthSuccess: false,\n\t\t\tauthError: errorDescription || error\n\t\t};\n\t\tif (!code) throw new Error(\"Unauthorized: no code provided\");\n\t\tif (!state) throw new Error(\"Unauthorized: no state provided\");\n\t\tif (this.mcpConnections[serverId] === void 0) throw new Error(`Could not find serverId: ${serverId}`);\n\t\tif (this.mcpConnections[serverId].connectionState === MCPConnectionState.READY || this.mcpConnections[serverId].connectionState === MCPConnectionState.CONNECTED) {\n\t\t\tthis.clearServerAuthUrl(serverId);\n\t\t\treturn {\n\t\t\t\tserverId,\n\t\t\t\tauthSuccess: true\n\t\t\t};\n\t\t}\n\t\tif (this.mcpConnections[serverId].connectionState !== MCPConnectionState.AUTHENTICATING) throw new Error(`Failed to authenticate: the client is in \"${this.mcpConnections[serverId].connectionState}\" state, expected \"authenticating\"`);\n\t\tconst conn = this.mcpConnections[serverId];\n\t\tif (!conn.options.transport.authProvider) throw new Error(\"Trying to finalize authentication for a server connection without an authProvider\");\n\t\tconst clientId = conn.options.transport.authProvider.clientId || state;\n\t\tconn.options.transport.authProvider.clientId = clientId;\n\t\tconn.options.transport.authProvider.serverId = serverId;\n\t\ttry {\n\t\t\tawait conn.completeAuthorization(code);\n\t\t\tthis.clearServerAuthUrl(serverId);\n\t\t\tthis._onServerStateChanged.fire();\n\t\t\treturn {\n\t\t\t\tserverId,\n\t\t\t\tauthSuccess: true\n\t\t\t};\n\t\t} catch (error$1) {\n\t\t\tconst errorMessage = error$1 instanceof Error ? error$1.message : String(error$1);\n\t\t\tthis._onServerStateChanged.fire();\n\t\t\treturn {\n\t\t\t\tserverId,\n\t\t\t\tauthSuccess: false,\n\t\t\t\tauthError: errorMessage\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Discover server capabilities if connection is in CONNECTED or READY state.\n\t* Transitions to DISCOVERING then READY (or CONNECTED on error).\n\t* Can be called to refresh server capabilities (e.g., from a UI refresh button).\n\t*\n\t* If called while a previous discovery is in-flight for the same server,\n\t* the previous discovery will be aborted.\n\t*\n\t* @param serverId The server ID to discover\n\t* @param options Optional configuration\n\t* @param options.timeoutMs Timeout in milliseconds (default: 30000)\n\t* @returns Result with current state and optional error, or undefined if connection not found\n\t*/\n\tasync discoverIfConnected(serverId, options = {}) {\n\t\tconst conn = this.mcpConnections[serverId];\n\t\tif (!conn) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\tdisplayMessage: `Connection not found for ${serverId}`,\n\t\t\t\tpayload: {},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst result = await conn.discover(options);\n\t\tthis._onServerStateChanged.fire();\n\t\treturn {\n\t\t\t...result,\n\t\t\tstate: conn.connectionState\n\t\t};\n\t}\n\t/**\n\t* Establish connection in the background after OAuth completion\n\t* This method connects to the server and discovers its capabilities\n\t* @param serverId The server ID to establish connection for\n\t*/\n\tasync establishConnection(serverId) {\n\t\tconst conn = this.mcpConnections[serverId];\n\t\tif (!conn) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:preconnect\",\n\t\t\t\tdisplayMessage: `Connection not found for serverId: ${serverId}`,\n\t\t\t\tpayload: { serverId },\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (conn.connectionState === MCPConnectionState.DISCOVERING || conn.connectionState === MCPConnectionState.READY) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `establishConnection skipped for ${serverId}, already in ${conn.connectionState} state`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl: conn.url.toString(),\n\t\t\t\t\ttransport: conn.options.transport.type || \"unknown\",\n\t\t\t\t\tstate: conn.connectionState\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst connectResult = await this.connectToServer(serverId);\n\t\tthis._onServerStateChanged.fire();\n\t\tif (connectResult.state === MCPConnectionState.CONNECTED) await this.discoverIfConnected(serverId);\n\t\tthis._onObservabilityEvent.fire({\n\t\t\ttype: \"mcp:client:connect\",\n\t\t\tdisplayMessage: `establishConnection completed for ${serverId}, final state: ${conn.connectionState}`,\n\t\t\tpayload: {\n\t\t\t\turl: conn.url.toString(),\n\t\t\t\ttransport: conn.options.transport.type || \"unknown\",\n\t\t\t\tstate: conn.connectionState\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t\tid: nanoid()\n\t\t});\n\t}\n\t/**\n\t* Configure OAuth callback handling\n\t* @param config OAuth callback configuration\n\t*/\n\tconfigureOAuthCallback(config) {\n\t\tthis._oauthCallbackConfig = config;\n\t}\n\t/**\n\t* Get the current OAuth callback configuration\n\t* @returns The current OAuth callback configuration\n\t*/\n\tgetOAuthCallbackConfig() {\n\t\treturn this._oauthCallbackConfig;\n\t}\n\t/**\n\t* @returns namespaced list of tools\n\t*/\n\tlistTools() {\n\t\treturn getNamespacedData(this.mcpConnections, \"tools\");\n\t}\n\t/**\n\t* Lazy-loads the jsonSchema function from the AI SDK.\n\t*\n\t* This defers importing the \"ai\" package until it's actually needed, which helps reduce\n\t* initial bundle size and startup time. The jsonSchema function is required for converting\n\t* MCP tools into AI SDK tool definitions via getAITools().\n\t*\n\t* @internal This method is for internal use only. It's automatically called before operations\n\t* that need jsonSchema (like getAITools() or OAuth flows). External consumers should not need\n\t* to call this directly.\n\t*/\n\tasync ensureJsonSchema() {\n\t\tif (!this.jsonSchema) {\n\t\t\tconst { jsonSchema } = await import(\"ai\");\n\t\t\tthis.jsonSchema = jsonSchema;\n\t\t}\n\t}\n\t/**\n\t* @returns a set of tools that you can use with the AI SDK\n\t*/\n\tgetAITools() {\n\t\tif (!this.jsonSchema) throw new Error(\"jsonSchema not initialized.\");\n\t\tfor (const [id, conn] of Object.entries(this.mcpConnections)) if (conn.connectionState !== MCPConnectionState.READY && conn.connectionState !== MCPConnectionState.AUTHENTICATING) console.warn(`[getAITools] WARNING: Reading tools from connection ${id} in state \"${conn.connectionState}\". Tools may not be loaded yet.`);\n\t\treturn Object.fromEntries(getNamespacedData(this.mcpConnections, \"tools\").map((tool) => {\n\t\t\treturn [`tool_${tool.serverId.replace(/-/g, \"\")}_${tool.name}`, {\n\t\t\t\tdescription: tool.description,\n\t\t\t\texecute: async (args) => {\n\t\t\t\t\tconst result = await this.callTool({\n\t\t\t\t\t\targuments: args,\n\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\tserverId: tool.serverId\n\t\t\t\t\t});\n\t\t\t\t\tif (result.isError) throw new Error(result.content[0].text);\n\t\t\t\t\treturn result;\n\t\t\t\t},\n\t\t\t\tinputSchema: this.jsonSchema(tool.inputSchema),\n\t\t\t\toutputSchema: tool.outputSchema ? this.jsonSchema(tool.outputSchema) : void 0\n\t\t\t}];\n\t\t}));\n\t}\n\t/**\n\t* @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version\n\t* @returns a set of tools that you can use with the AI SDK\n\t*/\n\tunstable_getAITools() {\n\t\tif (!this._didWarnAboutUnstableGetAITools) {\n\t\t\tthis._didWarnAboutUnstableGetAITools = true;\n\t\t\tconsole.warn(\"unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version.\");\n\t\t}\n\t\treturn this.getAITools();\n\t}\n\t/**\n\t* Closes all active in-memory connections to MCP servers.\n\t*\n\t* Note: This only closes the transport connections - it does NOT remove\n\t* servers from storage. Servers will still be listed and their callback\n\t* URLs will still match incoming OAuth requests.\n\t*\n\t* Use removeServer() instead if you want to fully clean up a server\n\t* (closes connection AND removes from storage).\n\t*/\n\tasync closeAllConnections() {\n\t\tconst ids = Object.keys(this.mcpConnections);\n\t\tfor (const id of ids) this.mcpConnections[id].cancelDiscovery();\n\t\tawait Promise.all(ids.map(async (id) => {\n\t\t\tawait this.mcpConnections[id].client.close();\n\t\t}));\n\t\tfor (const id of ids) {\n\t\t\tconst store = this._connectionDisposables.get(id);\n\t\t\tif (store) store.dispose();\n\t\t\tthis._connectionDisposables.delete(id);\n\t\t\tdelete this.mcpConnections[id];\n\t\t}\n\t}\n\t/**\n\t* Closes a connection to an MCP server\n\t* @param id The id of the connection to close\n\t*/\n\tasync closeConnection(id) {\n\t\tif (!this.mcpConnections[id]) throw new Error(`Connection with id \"${id}\" does not exist.`);\n\t\tthis.mcpConnections[id].cancelDiscovery();\n\t\tawait this.mcpConnections[id].client.close();\n\t\tdelete this.mcpConnections[id];\n\t\tconst store = this._connectionDisposables.get(id);\n\t\tif (store) store.dispose();\n\t\tthis._connectionDisposables.delete(id);\n\t}\n\t/**\n\t* Remove an MCP server - closes connection if active and removes from storage.\n\t*/\n\tasync removeServer(serverId) {\n\t\tif (this.mcpConnections[serverId]) try {\n\t\t\tawait this.closeConnection(serverId);\n\t\t} catch (_e) {}\n\t\tthis.removeServerFromStorage(serverId);\n\t\tthis._onServerStateChanged.fire();\n\t}\n\t/**\n\t* List all MCP servers from storage\n\t*/\n\tlistServers() {\n\t\treturn this.getServersFromStorage();\n\t}\n\t/**\n\t* Dispose the manager and all resources.\n\t*/\n\tasync dispose() {\n\t\ttry {\n\t\t\tawait this.closeAllConnections();\n\t\t} finally {\n\t\t\tthis._onServerStateChanged.dispose();\n\t\t\tthis._onObservabilityEvent.dispose();\n\t\t}\n\t}\n\t/**\n\t* @returns namespaced list of prompts\n\t*/\n\tlistPrompts() {\n\t\treturn getNamespacedData(this.mcpConnections, \"prompts\");\n\t}\n\t/**\n\t* @returns namespaced list of tools\n\t*/\n\tlistResources() {\n\t\treturn getNamespacedData(this.mcpConnections, \"resources\");\n\t}\n\t/**\n\t* @returns namespaced list of resource templates\n\t*/\n\tlistResourceTemplates() {\n\t\treturn getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n\t}\n\t/**\n\t* Namespaced version of callTool\n\t*/\n\tasync callTool(params, resultSchema, options) {\n\t\tconst unqualifiedName = params.name.replace(`${params.serverId}.`, \"\");\n\t\treturn this.mcpConnections[params.serverId].client.callTool({\n\t\t\t...params,\n\t\t\tname: unqualifiedName\n\t\t}, resultSchema, options);\n\t}\n\t/**\n\t* Namespaced version of readResource\n\t*/\n\treadResource(params, options) {\n\t\treturn this.mcpConnections[params.serverId].client.readResource(params, options);\n\t}\n\t/**\n\t* Namespaced version of getPrompt\n\t*/\n\tgetPrompt(params, options) {\n\t\treturn this.mcpConnections[params.serverId].client.getPrompt(params, options);\n\t}\n};\nfunction getNamespacedData(mcpClients, type) {\n\treturn Object.entries(mcpClients).map(([name, conn]) => {\n\t\treturn {\n\t\t\tdata: conn[type],\n\t\t\tname\n\t\t};\n\t}).flatMap(({ name: serverId, data }) => {\n\t\treturn data.map((item) => {\n\t\t\treturn {\n\t\t\t\t...item,\n\t\t\t\tserverId\n\t\t\t};\n\t\t});\n\t});\n}\n\n//#endregion\nexport { DisposableStore as i, getNamespacedData as n, MCPConnectionState as r, MCPClientManager as t };\n//# sourceMappingURL=client-CFhjXCiO.js.map","import { t as MessageType } from \"./ai-types-CrMqkwc_.js\";\nimport { r as camelCaseToKebabCase } from \"./client-B3SR12TQ.js\";\nimport { i as DisposableStore, r as MCPConnectionState, t as MCPClientManager } from \"./client-CFhjXCiO.js\";\nimport { t as DurableObjectOAuthClientProvider } from \"./do-oauth-client-provider-CwqK5SXm.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { parseCronExpression } from \"cron-schedule\";\nimport { nanoid } from \"nanoid\";\nimport { EmailMessage } from \"cloudflare:email\";\nimport { Server, getServerByName, routePartykitRequest } from \"partyserver\";\n\n//#region src/observability/index.ts\n/**\n* A generic observability implementation that logs events to the console.\n*/\nconst genericObservability = { emit(event) {\n\tif (isLocalMode()) {\n\t\tconsole.log(event.displayMessage);\n\t\treturn;\n\t}\n\tconsole.log(event);\n} };\nlet localMode = false;\nfunction isLocalMode() {\n\tif (localMode) return true;\n\tconst { request } = getCurrentAgent();\n\tif (!request) return false;\n\tlocalMode = new URL(request.url).hostname === \"localhost\";\n\treturn localMode;\n}\n\n//#endregion\n//#region src/index.ts\n/**\n* Type guard for RPC request messages\n*/\nfunction isRPCRequest(msg) {\n\treturn typeof msg === \"object\" && msg !== null && \"type\" in msg && msg.type === MessageType.RPC && \"id\" in msg && typeof msg.id === \"string\" && \"method\" in msg && typeof msg.method === \"string\" && \"args\" in msg && Array.isArray(msg.args);\n}\n/**\n* Type guard for state update messages\n*/\nfunction isStateUpdateMessage(msg) {\n\treturn typeof msg === \"object\" && msg !== null && \"type\" in msg && msg.type === MessageType.CF_AGENT_STATE && \"state\" in msg;\n}\nconst callableMetadata = /* @__PURE__ */ new Map();\n/**\n* Decorator that marks a method as callable by clients\n* @param metadata Optional metadata about the callable method\n*/\nfunction callable(metadata = {}) {\n\treturn function callableDecorator(target, context) {\n\t\tif (!callableMetadata.has(target)) callableMetadata.set(target, metadata);\n\t\treturn target;\n\t};\n}\nlet didWarnAboutUnstableCallable = false;\n/**\n* Decorator that marks a method as callable by clients\n* @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version\n* @param metadata Optional metadata about the callable method\n*/\nconst unstable_callable = (metadata = {}) => {\n\tif (!didWarnAboutUnstableCallable) {\n\t\tdidWarnAboutUnstableCallable = true;\n\t\tconsole.warn(\"unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version.\");\n\t}\n\tcallable(metadata);\n};\nfunction getNextCronTime(cron) {\n\treturn parseCronExpression(cron).getNextDate();\n}\nconst STATE_ROW_ID = \"cf_state_row_id\";\nconst STATE_WAS_CHANGED = \"cf_state_was_changed\";\nconst DEFAULT_STATE = {};\nconst agentContext = new AsyncLocalStorage();\nfunction getCurrentAgent() {\n\tconst store = agentContext.getStore();\n\tif (!store) return {\n\t\tagent: void 0,\n\t\tconnection: void 0,\n\t\trequest: void 0,\n\t\temail: void 0\n\t};\n\treturn store;\n}\n/**\n* Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly\n* @param agent The agent instance\n* @param method The method to wrap\n* @returns A wrapped method that runs within the agent context\n*/\nfunction withAgentContext(method) {\n\treturn function(...args) {\n\t\tconst { connection, request, email, agent } = getCurrentAgent();\n\t\tif (agent === this) return method.apply(this, args);\n\t\treturn agentContext.run({\n\t\t\tagent: this,\n\t\t\tconnection,\n\t\t\trequest,\n\t\t\temail\n\t\t}, () => {\n\t\t\treturn method.apply(this, args);\n\t\t});\n\t};\n}\n/**\n* Base class for creating Agent implementations\n* @template Env Environment type containing bindings\n* @template State State type to store within the Agent\n*/\nvar Agent = class Agent extends Server {\n\t/**\n\t* Current state of the Agent\n\t*/\n\tget state() {\n\t\tif (this._state !== DEFAULT_STATE) return this._state;\n\t\tconst wasChanged = this.sql`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}\n `;\n\t\tconst result = this.sql`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}\n `;\n\t\tif (wasChanged[0]?.state === \"true\" || result[0]?.state) {\n\t\t\tconst state = result[0]?.state;\n\t\t\tthis._state = JSON.parse(state);\n\t\t\treturn this._state;\n\t\t}\n\t\tif (this.initialState === DEFAULT_STATE) return;\n\t\tthis.setState(this.initialState);\n\t\treturn this.initialState;\n\t}\n\tstatic {\n\t\tthis.options = { hibernate: true };\n\t}\n\t/**\n\t* Execute SQL queries against the Agent's database\n\t* @template T Type of the returned rows\n\t* @param strings SQL query template strings\n\t* @param values Values to be inserted into the query\n\t* @returns Array of query results\n\t*/\n\tsql(strings, ...values) {\n\t\tlet query = \"\";\n\t\ttry {\n\t\t\tquery = strings.reduce((acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"), \"\");\n\t\t\treturn [...this.ctx.storage.sql.exec(query, ...values)];\n\t\t} catch (e) {\n\t\t\tconsole.error(`failed to execute sql query: ${query}`, e);\n\t\t\tthrow this.onError(e);\n\t\t}\n\t}\n\tconstructor(ctx, env) {\n\t\tsuper(ctx, env);\n\t\tthis._state = DEFAULT_STATE;\n\t\tthis._disposables = new DisposableStore();\n\t\tthis._destroyed = false;\n\t\tthis._ParentClass = Object.getPrototypeOf(this).constructor;\n\t\tthis.initialState = DEFAULT_STATE;\n\t\tthis.observability = genericObservability;\n\t\tthis._flushingQueue = false;\n\t\tthis.alarm = async () => {\n\t\t\tconst now = Math.floor(Date.now() / 1e3);\n\t\t\tconst result = this.sql`\n SELECT * FROM cf_agents_schedules WHERE time <= ${now}\n `;\n\t\t\tif (result && Array.isArray(result)) for (const row of result) {\n\t\t\t\tconst callback = this[row.callback];\n\t\t\t\tif (!callback) {\n\t\t\t\t\tconsole.error(`callback ${row.callback} not found`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tawait agentContext.run({\n\t\t\t\t\tagent: this,\n\t\t\t\t\tconnection: void 0,\n\t\t\t\t\trequest: void 0,\n\t\t\t\t\temail: void 0\n\t\t\t\t}, async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.observability?.emit({\n\t\t\t\t\t\t\tdisplayMessage: `Schedule ${row.id} executed`,\n\t\t\t\t\t\t\tid: nanoid(),\n\t\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\t\tcallback: row.callback,\n\t\t\t\t\t\t\t\tid: row.id\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\ttype: \"schedule:execute\"\n\t\t\t\t\t\t}, this.ctx);\n\t\t\t\t\t\tawait callback.bind(this)(JSON.parse(row.payload), row);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tconsole.error(`error executing callback \"${row.callback}\"`, e);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (row.type === \"cron\") {\n\t\t\t\t\tif (this._destroyed) return;\n\t\t\t\t\tconst nextExecutionTime = getNextCronTime(row.cron);\n\t\t\t\t\tconst nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);\n\t\t\t\t\tthis.sql`\n UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}\n `;\n\t\t\t\t} else {\n\t\t\t\t\tif (this._destroyed) return;\n\t\t\t\t\tthis.sql`\n DELETE FROM cf_agents_schedules WHERE id = ${row.id}\n `;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this._destroyed) return;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t};\n\t\tif (!wrappedClasses.has(this.constructor)) {\n\t\t\tthis._autoWrapCustomMethods();\n\t\t\twrappedClasses.add(this.constructor);\n\t\t}\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (\n id TEXT PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n server_url TEXT NOT NULL,\n callback_url TEXT NOT NULL,\n client_id TEXT,\n auth_url TEXT,\n server_options TEXT\n )\n `;\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_state (\n id TEXT PRIMARY KEY NOT NULL,\n state TEXT\n )\n `;\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_queues (\n id TEXT PRIMARY KEY NOT NULL,\n payload TEXT,\n callback TEXT,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_schedules (\n id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),\n callback TEXT,\n payload TEXT,\n type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),\n time INTEGER,\n delayInSeconds INTEGER,\n cron TEXT,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\t\tthis.mcp = new MCPClientManager(this._ParentClass.name, \"0.0.1\", { storage: this.ctx.storage });\n\t\tthis._disposables.add(this.mcp.onServerStateChanged(async () => {\n\t\t\tthis.broadcastMcpServers();\n\t\t}));\n\t\tthis._disposables.add(this.mcp.onObservabilityEvent((event) => {\n\t\t\tthis.observability?.emit(event);\n\t\t}));\n\t\tconst _onRequest = this.onRequest.bind(this);\n\t\tthis.onRequest = (request) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection: void 0,\n\t\t\t\trequest,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tawait this.mcp.ensureJsonSchema();\n\t\t\t\tconst oauthResponse = await this.handleMcpOAuthCallback(request);\n\t\t\t\tif (oauthResponse) return oauthResponse;\n\t\t\t\treturn this._tryCatch(() => _onRequest(request));\n\t\t\t});\n\t\t};\n\t\tconst _onMessage = this.onMessage.bind(this);\n\t\tthis.onMessage = async (connection, message) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection,\n\t\t\t\trequest: void 0,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tawait this.mcp.ensureJsonSchema();\n\t\t\t\tif (typeof message !== \"string\") return this._tryCatch(() => _onMessage(connection, message));\n\t\t\t\tlet parsed;\n\t\t\t\ttry {\n\t\t\t\t\tparsed = JSON.parse(message);\n\t\t\t\t} catch (_e) {\n\t\t\t\t\treturn this._tryCatch(() => _onMessage(connection, message));\n\t\t\t\t}\n\t\t\t\tif (isStateUpdateMessage(parsed)) {\n\t\t\t\t\tthis._setStateInternal(parsed.state, connection);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (isRPCRequest(parsed)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst { id, method, args } = parsed;\n\t\t\t\t\t\tconst methodFn = this[method];\n\t\t\t\t\t\tif (typeof methodFn !== \"function\") throw new Error(`Method ${method} does not exist`);\n\t\t\t\t\t\tif (!this._isCallable(method)) throw new Error(`Method ${method} is not callable`);\n\t\t\t\t\t\tconst metadata = callableMetadata.get(methodFn);\n\t\t\t\t\t\tif (metadata?.streaming) {\n\t\t\t\t\t\t\tconst stream = new StreamingResponse(connection, id);\n\t\t\t\t\t\t\tawait methodFn.apply(this, [stream, ...args]);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst result = await methodFn.apply(this, args);\n\t\t\t\t\t\tthis.observability?.emit({\n\t\t\t\t\t\t\tdisplayMessage: `RPC call to ${method}`,\n\t\t\t\t\t\t\tid: nanoid(),\n\t\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\t\tmethod,\n\t\t\t\t\t\t\t\tstreaming: metadata?.streaming\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\ttype: \"rpc\"\n\t\t\t\t\t\t}, this.ctx);\n\t\t\t\t\t\tconst response = {\n\t\t\t\t\t\t\tdone: true,\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\ttype: MessageType.RPC\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconnection.send(JSON.stringify(response));\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tconst response = {\n\t\t\t\t\t\t\terror: e instanceof Error ? e.message : \"Unknown error occurred\",\n\t\t\t\t\t\t\tid: parsed.id,\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\ttype: MessageType.RPC\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconnection.send(JSON.stringify(response));\n\t\t\t\t\t\tconsole.error(\"RPC error:\", e);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this._tryCatch(() => _onMessage(connection, message));\n\t\t\t});\n\t\t};\n\t\tconst _onConnect = this.onConnect.bind(this);\n\t\tthis.onConnect = (connection, ctx$1) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection,\n\t\t\t\trequest: ctx$1.request,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tif (this.state) connection.send(JSON.stringify({\n\t\t\t\t\tstate: this.state,\n\t\t\t\t\ttype: MessageType.CF_AGENT_STATE\n\t\t\t\t}));\n\t\t\t\tconnection.send(JSON.stringify({\n\t\t\t\t\tmcp: this.getMcpServers(),\n\t\t\t\t\ttype: MessageType.CF_AGENT_MCP_SERVERS\n\t\t\t\t}));\n\t\t\t\tthis.observability?.emit({\n\t\t\t\t\tdisplayMessage: \"Connection established\",\n\t\t\t\t\tid: nanoid(),\n\t\t\t\t\tpayload: { connectionId: connection.id },\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\ttype: \"connect\"\n\t\t\t\t}, this.ctx);\n\t\t\t\treturn this._tryCatch(() => _onConnect(connection, ctx$1));\n\t\t\t});\n\t\t};\n\t\tconst _onStart = this.onStart.bind(this);\n\t\tthis.onStart = async (props) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection: void 0,\n\t\t\t\trequest: void 0,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tawait this._tryCatch(async () => {\n\t\t\t\t\tawait this.mcp.restoreConnectionsFromStorage(this.name);\n\t\t\t\t\tthis.broadcastMcpServers();\n\t\t\t\t\treturn _onStart(props);\n\t\t\t\t});\n\t\t\t});\n\t\t};\n\t}\n\t_setStateInternal(state, source = \"server\") {\n\t\tthis._state = state;\n\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})\n `;\n\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})\n `;\n\t\tthis.broadcast(JSON.stringify({\n\t\t\tstate,\n\t\t\ttype: MessageType.CF_AGENT_STATE\n\t\t}), source !== \"server\" ? [source.id] : []);\n\t\treturn this._tryCatch(() => {\n\t\t\tconst { connection, request, email } = agentContext.getStore() || {};\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection,\n\t\t\t\trequest,\n\t\t\t\temail\n\t\t\t}, async () => {\n\t\t\t\tthis.observability?.emit({\n\t\t\t\t\tdisplayMessage: \"State updated\",\n\t\t\t\t\tid: nanoid(),\n\t\t\t\t\tpayload: {},\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\ttype: \"state:update\"\n\t\t\t\t}, this.ctx);\n\t\t\t\treturn this.onStateUpdate(state, source);\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* Update the Agent's state\n\t* @param state New state to set\n\t*/\n\tsetState(state) {\n\t\tthis._setStateInternal(state, \"server\");\n\t}\n\t/**\n\t* Called when the Agent's state is updated\n\t* @param state Updated state\n\t* @param source Source of the state update (\"server\" or a client connection)\n\t*/\n\tonStateUpdate(state, source) {}\n\t/**\n\t* Called when the Agent receives an email via routeAgentEmail()\n\t* Override this method to handle incoming emails\n\t* @param email Email message to process\n\t*/\n\tasync _onEmail(email) {\n\t\treturn agentContext.run({\n\t\t\tagent: this,\n\t\t\tconnection: void 0,\n\t\t\trequest: void 0,\n\t\t\temail\n\t\t}, async () => {\n\t\t\tif (\"onEmail\" in this && typeof this.onEmail === \"function\") return this._tryCatch(() => this.onEmail(email));\n\t\t\telse {\n\t\t\t\tconsole.log(\"Received email from:\", email.from, \"to:\", email.to);\n\t\t\t\tconsole.log(\"Subject:\", email.headers.get(\"subject\"));\n\t\t\t\tconsole.log(\"Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails\");\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* Reply to an email\n\t* @param email The email to reply to\n\t* @param options Options for the reply\n\t* @returns void\n\t*/\n\tasync replyToEmail(email, options) {\n\t\treturn this._tryCatch(async () => {\n\t\t\tconst agentName = camelCaseToKebabCase(this._ParentClass.name);\n\t\t\tconst agentId = this.name;\n\t\t\tconst { createMimeMessage } = await import(\"mimetext\");\n\t\t\tconst msg = createMimeMessage();\n\t\t\tmsg.setSender({\n\t\t\t\taddr: email.to,\n\t\t\t\tname: options.fromName\n\t\t\t});\n\t\t\tmsg.setRecipient(email.from);\n\t\t\tmsg.setSubject(options.subject || `Re: ${email.headers.get(\"subject\")}` || \"No subject\");\n\t\t\tmsg.addMessage({\n\t\t\t\tcontentType: options.contentType || \"text/plain\",\n\t\t\t\tdata: options.body\n\t\t\t});\n\t\t\tconst messageId = `<${agentId}@${email.from.split(\"@\")[1]}>`;\n\t\t\tmsg.setHeader(\"In-Reply-To\", email.headers.get(\"Message-ID\"));\n\t\t\tmsg.setHeader(\"Message-ID\", messageId);\n\t\t\tmsg.setHeader(\"X-Agent-Name\", agentName);\n\t\t\tmsg.setHeader(\"X-Agent-ID\", agentId);\n\t\t\tif (options.headers) for (const [key, value] of Object.entries(options.headers)) msg.setHeader(key, value);\n\t\t\tawait email.reply({\n\t\t\t\tfrom: email.to,\n\t\t\t\traw: msg.asRaw(),\n\t\t\t\tto: email.from\n\t\t\t});\n\t\t});\n\t}\n\tasync _tryCatch(fn) {\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} catch (e) {\n\t\t\tthrow this.onError(e);\n\t\t}\n\t}\n\t/**\n\t* Automatically wrap custom methods with agent context\n\t* This ensures getCurrentAgent() works in all custom methods without decorators\n\t*/\n\t_autoWrapCustomMethods() {\n\t\tconst basePrototypes = [Agent.prototype, Server.prototype];\n\t\tconst baseMethods = /* @__PURE__ */ new Set();\n\t\tfor (const baseProto of basePrototypes) {\n\t\t\tlet proto$1 = baseProto;\n\t\t\twhile (proto$1 && proto$1 !== Object.prototype) {\n\t\t\t\tconst methodNames = Object.getOwnPropertyNames(proto$1);\n\t\t\t\tfor (const methodName of methodNames) baseMethods.add(methodName);\n\t\t\t\tproto$1 = Object.getPrototypeOf(proto$1);\n\t\t\t}\n\t\t}\n\t\tlet proto = Object.getPrototypeOf(this);\n\t\tlet depth = 0;\n\t\twhile (proto && proto !== Object.prototype && depth < 10) {\n\t\t\tconst methodNames = Object.getOwnPropertyNames(proto);\n\t\t\tfor (const methodName of methodNames) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(proto, methodName);\n\t\t\t\tif (baseMethods.has(methodName) || methodName.startsWith(\"_\") || !descriptor || !!descriptor.get || typeof descriptor.value !== \"function\") continue;\n\t\t\t\tconst wrappedFunction = withAgentContext(this[methodName]);\n\t\t\t\tif (this._isCallable(methodName)) callableMetadata.set(wrappedFunction, callableMetadata.get(this[methodName]));\n\t\t\t\tthis.constructor.prototype[methodName] = wrappedFunction;\n\t\t\t}\n\t\t\tproto = Object.getPrototypeOf(proto);\n\t\t\tdepth++;\n\t\t}\n\t}\n\tonError(connectionOrError, error) {\n\t\tlet theError;\n\t\tif (connectionOrError && error) {\n\t\t\ttheError = error;\n\t\t\tconsole.error(\"Error on websocket connection:\", connectionOrError.id, theError);\n\t\t\tconsole.error(\"Override onError(connection, error) to handle websocket connection errors\");\n\t\t} else {\n\t\t\ttheError = connectionOrError;\n\t\t\tconsole.error(\"Error on server:\", theError);\n\t\t\tconsole.error(\"Override onError(error) to handle server errors\");\n\t\t}\n\t\tthrow theError;\n\t}\n\t/**\n\t* Render content (not implemented in base class)\n\t*/\n\trender() {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n\t/**\n\t* Queue a task to be executed in the future\n\t* @param payload Payload to pass to the callback\n\t* @param callback Name of the method to call\n\t* @returns The ID of the queued task\n\t*/\n\tasync queue(callback, payload) {\n\t\tconst id = nanoid(9);\n\t\tif (typeof callback !== \"string\") throw new Error(\"Callback must be a string\");\n\t\tif (typeof this[callback] !== \"function\") throw new Error(`this.${callback} is not a function`);\n\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)\n VALUES (${id}, ${JSON.stringify(payload)}, ${callback})\n `;\n\t\tthis._flushQueue().catch((e) => {\n\t\t\tconsole.error(\"Error flushing queue:\", e);\n\t\t});\n\t\treturn id;\n\t}\n\tasync _flushQueue() {\n\t\tif (this._flushingQueue) return;\n\t\tthis._flushingQueue = true;\n\t\twhile (true) {\n\t\t\tconst result = this.sql`\n SELECT * FROM cf_agents_queues\n ORDER BY created_at ASC\n `;\n\t\t\tif (!result || result.length === 0) break;\n\t\t\tfor (const row of result || []) {\n\t\t\t\tconst callback = this[row.callback];\n\t\t\t\tif (!callback) {\n\t\t\t\t\tconsole.error(`callback ${row.callback} not found`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst { connection, request, email } = agentContext.getStore() || {};\n\t\t\t\tawait agentContext.run({\n\t\t\t\t\tagent: this,\n\t\t\t\t\tconnection,\n\t\t\t\t\trequest,\n\t\t\t\t\temail\n\t\t\t\t}, async () => {\n\t\t\t\t\tawait callback.bind(this)(JSON.parse(row.payload), row);\n\t\t\t\t\tawait this.dequeue(row.id);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis._flushingQueue = false;\n\t}\n\t/**\n\t* Dequeue a task by ID\n\t* @param id ID of the task to dequeue\n\t*/\n\tasync dequeue(id) {\n\t\tthis.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;\n\t}\n\t/**\n\t* Dequeue all tasks\n\t*/\n\tasync dequeueAll() {\n\t\tthis.sql`DELETE FROM cf_agents_queues`;\n\t}\n\t/**\n\t* Dequeue all tasks by callback\n\t* @param callback Name of the callback to dequeue\n\t*/\n\tasync dequeueAllByCallback(callback) {\n\t\tthis.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;\n\t}\n\t/**\n\t* Get a queued task by ID\n\t* @param id ID of the task to get\n\t* @returns The task or undefined if not found\n\t*/\n\tasync getQueue(id) {\n\t\tconst result = this.sql`\n SELECT * FROM cf_agents_queues WHERE id = ${id}\n `;\n\t\treturn result ? {\n\t\t\t...result[0],\n\t\t\tpayload: JSON.parse(result[0].payload)\n\t\t} : void 0;\n\t}\n\t/**\n\t* Get all queues by key and value\n\t* @param key Key to filter by\n\t* @param value Value to filter by\n\t* @returns Array of matching QueueItem objects\n\t*/\n\tasync getQueues(key, value) {\n\t\treturn this.sql`\n SELECT * FROM cf_agents_queues\n `.filter((row) => JSON.parse(row.payload)[key] === value);\n\t}\n\t/**\n\t* Schedule a task to be executed in the future\n\t* @template T Type of the payload data\n\t* @param when When to execute the task (Date, seconds delay, or cron expression)\n\t* @param callback Name of the method to call\n\t* @param payload Data to pass to the callback\n\t* @returns Schedule object representing the scheduled task\n\t*/\n\tasync schedule(when, callback, payload) {\n\t\tconst id = nanoid(9);\n\t\tconst emitScheduleCreate = (schedule) => this.observability?.emit({\n\t\t\tdisplayMessage: `Schedule ${schedule.id} created`,\n\t\t\tid: nanoid(),\n\t\t\tpayload: {\n\t\t\t\tcallback,\n\t\t\t\tid\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t\ttype: \"schedule:create\"\n\t\t}, this.ctx);\n\t\tif (typeof callback !== \"string\") throw new Error(\"Callback must be a string\");\n\t\tif (typeof this[callback] !== \"function\") throw new Error(`this.${callback} is not a function`);\n\t\tif (when instanceof Date) {\n\t\t\tconst timestamp = Math.floor(when.getTime() / 1e3);\n\t\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})\n `;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t\tconst schedule = {\n\t\t\t\tcallback,\n\t\t\t\tid,\n\t\t\t\tpayload,\n\t\t\t\ttime: timestamp,\n\t\t\t\ttype: \"scheduled\"\n\t\t\t};\n\t\t\temitScheduleCreate(schedule);\n\t\t\treturn schedule;\n\t\t}\n\t\tif (typeof when === \"number\") {\n\t\t\tconst time = new Date(Date.now() + when * 1e3);\n\t\t\tconst timestamp = Math.floor(time.getTime() / 1e3);\n\t\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${timestamp})\n `;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t\tconst schedule = {\n\t\t\t\tcallback,\n\t\t\t\tdelayInSeconds: when,\n\t\t\t\tid,\n\t\t\t\tpayload,\n\t\t\t\ttime: timestamp,\n\t\t\t\ttype: \"delayed\"\n\t\t\t};\n\t\t\temitScheduleCreate(schedule);\n\t\t\treturn schedule;\n\t\t}\n\t\tif (typeof when === \"string\") {\n\t\t\tconst nextExecutionTime = getNextCronTime(when);\n\t\t\tconst timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);\n\t\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'cron', ${when}, ${timestamp})\n `;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t\tconst schedule = {\n\t\t\t\tcallback,\n\t\t\t\tcron: when,\n\t\t\t\tid,\n\t\t\t\tpayload,\n\t\t\t\ttime: timestamp,\n\t\t\t\ttype: \"cron\"\n\t\t\t};\n\t\t\temitScheduleCreate(schedule);\n\t\t\treturn schedule;\n\t\t}\n\t\tthrow new Error(\"Invalid schedule type\");\n\t}\n\t/**\n\t* Get a scheduled task by ID\n\t* @template T Type of the payload data\n\t* @param id ID of the scheduled task\n\t* @returns The Schedule object or undefined if not found\n\t*/\n\tasync getSchedule(id) {\n\t\tconst result = this.sql`\n SELECT * FROM cf_agents_schedules WHERE id = ${id}\n `;\n\t\tif (!result) {\n\t\t\tconsole.error(`schedule ${id} not found`);\n\t\t\treturn;\n\t\t}\n\t\treturn {\n\t\t\t...result[0],\n\t\t\tpayload: JSON.parse(result[0].payload)\n\t\t};\n\t}\n\t/**\n\t* Get scheduled tasks matching the given criteria\n\t* @template T Type of the payload data\n\t* @param criteria Criteria to filter schedules\n\t* @returns Array of matching Schedule objects\n\t*/\n\tgetSchedules(criteria = {}) {\n\t\tlet query = \"SELECT * FROM cf_agents_schedules WHERE 1=1\";\n\t\tconst params = [];\n\t\tif (criteria.id) {\n\t\t\tquery += \" AND id = ?\";\n\t\t\tparams.push(criteria.id);\n\t\t}\n\t\tif (criteria.type) {\n\t\t\tquery += \" AND type = ?\";\n\t\t\tparams.push(criteria.type);\n\t\t}\n\t\tif (criteria.timeRange) {\n\t\t\tquery += \" AND time >= ? AND time <= ?\";\n\t\t\tconst start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);\n\t\t\tconst end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);\n\t\t\tparams.push(Math.floor(start.getTime() / 1e3), Math.floor(end.getTime() / 1e3));\n\t\t}\n\t\treturn this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({\n\t\t\t...row,\n\t\t\tpayload: JSON.parse(row.payload)\n\t\t}));\n\t}\n\t/**\n\t* Cancel a scheduled task\n\t* @param id ID of the task to cancel\n\t* @returns true if the task was cancelled, false otherwise\n\t*/\n\tasync cancelSchedule(id) {\n\t\tconst schedule = await this.getSchedule(id);\n\t\tif (schedule) this.observability?.emit({\n\t\t\tdisplayMessage: `Schedule ${id} cancelled`,\n\t\t\tid: nanoid(),\n\t\t\tpayload: {\n\t\t\t\tcallback: schedule.callback,\n\t\t\t\tid: schedule.id\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t\ttype: \"schedule:cancel\"\n\t\t}, this.ctx);\n\t\tthis.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;\n\t\tawait this._scheduleNextAlarm();\n\t\treturn true;\n\t}\n\tasync _scheduleNextAlarm() {\n\t\tconst result = this.sql`\n SELECT time FROM cf_agents_schedules\n WHERE time >= ${Math.floor(Date.now() / 1e3)}\n ORDER BY time ASC\n LIMIT 1\n `;\n\t\tif (!result) return;\n\t\tif (result.length > 0 && \"time\" in result[0]) {\n\t\t\tconst nextTime = result[0].time * 1e3;\n\t\t\tawait this.ctx.storage.setAlarm(nextTime);\n\t\t}\n\t}\n\t/**\n\t* Destroy the Agent, removing all state and scheduled tasks\n\t*/\n\tasync destroy() {\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_state`;\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_schedules`;\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_queues`;\n\t\tawait this.ctx.storage.deleteAlarm();\n\t\tawait this.ctx.storage.deleteAll();\n\t\tthis._disposables.dispose();\n\t\tawait this.mcp.dispose();\n\t\tthis._destroyed = true;\n\t\tsetTimeout(() => {\n\t\t\tthis.ctx.abort(\"destroyed\");\n\t\t}, 0);\n\t\tthis.observability?.emit({\n\t\t\tdisplayMessage: \"Agent destroyed\",\n\t\t\tid: nanoid(),\n\t\t\tpayload: {},\n\t\t\ttimestamp: Date.now(),\n\t\t\ttype: \"destroy\"\n\t\t}, this.ctx);\n\t}\n\t/**\n\t* Get all methods marked as callable on this Agent\n\t* @returns A map of method names to their metadata\n\t*/\n\t_isCallable(method) {\n\t\treturn callableMetadata.has(this[method]);\n\t}\n\t/**\n\t* Connect to a new MCP Server\n\t*\n\t* @param serverName Name of the MCP server\n\t* @param url MCP Server SSE URL\n\t* @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.\n\t* @param agentsPrefix agents routing prefix if not using `agents`\n\t* @param options MCP client and transport options\n\t* @returns Server id and state - either \"authenticating\" with authUrl, or \"ready\"\n\t* @throws If connection or discovery fails\n\t*/\n\tasync addMcpServer(serverName, url, callbackHost, agentsPrefix = \"agents\", options) {\n\t\tlet resolvedCallbackHost = callbackHost;\n\t\tif (!resolvedCallbackHost) {\n\t\t\tconst { request } = getCurrentAgent();\n\t\t\tif (!request) throw new Error(\"callbackHost is required when not called within a request context\");\n\t\t\tconst requestUrl = new URL(request.url);\n\t\t\tresolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;\n\t\t}\n\t\tconst callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;\n\t\tawait this.mcp.ensureJsonSchema();\n\t\tconst id = nanoid(8);\n\t\tconst authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);\n\t\tauthProvider.serverId = id;\n\t\tconst transportType = options?.transport?.type ?? \"auto\";\n\t\tlet headerTransportOpts = {};\n\t\tif (options?.transport?.headers) headerTransportOpts = {\n\t\t\teventSourceInit: { fetch: (url$1, init) => fetch(url$1, {\n\t\t\t\t...init,\n\t\t\t\theaders: options?.transport?.headers\n\t\t\t}) },\n\t\t\trequestInit: { headers: options?.transport?.headers }\n\t\t};\n\t\tawait this.mcp.registerServer(id, {\n\t\t\turl,\n\t\t\tname: serverName,\n\t\t\tcallbackUrl,\n\t\t\tclient: options?.client,\n\t\t\ttransport: {\n\t\t\t\t...headerTransportOpts,\n\t\t\t\tauthProvider,\n\t\t\t\ttype: transportType\n\t\t\t}\n\t\t});\n\t\tconst result = await this.mcp.connectToServer(id);\n\t\tif (result.state === MCPConnectionState.FAILED) throw new Error(`Failed to connect to MCP server at ${url}: ${result.error}`);\n\t\tif (result.state === MCPConnectionState.AUTHENTICATING) return {\n\t\t\tid,\n\t\t\tstate: result.state,\n\t\t\tauthUrl: result.authUrl\n\t\t};\n\t\tconst discoverResult = await this.mcp.discoverIfConnected(id);\n\t\tif (discoverResult && !discoverResult.success) throw new Error(`Failed to discover MCP server capabilities: ${discoverResult.error}`);\n\t\treturn {\n\t\t\tid,\n\t\t\tstate: MCPConnectionState.READY\n\t\t};\n\t}\n\tasync removeMcpServer(id) {\n\t\tawait this.mcp.removeServer(id);\n\t}\n\tgetMcpServers() {\n\t\tconst mcpState = {\n\t\t\tprompts: this.mcp.listPrompts(),\n\t\t\tresources: this.mcp.listResources(),\n\t\t\tservers: {},\n\t\t\ttools: this.mcp.listTools()\n\t\t};\n\t\tconst servers = this.mcp.listServers();\n\t\tif (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {\n\t\t\tconst serverConn = this.mcp.mcpConnections[server.id];\n\t\t\tlet defaultState = \"not-connected\";\n\t\t\tif (!serverConn && server.auth_url) defaultState = \"authenticating\";\n\t\t\tmcpState.servers[server.id] = {\n\t\t\t\tauth_url: server.auth_url,\n\t\t\t\tcapabilities: serverConn?.serverCapabilities ?? null,\n\t\t\t\tinstructions: serverConn?.instructions ?? null,\n\t\t\t\tname: server.name,\n\t\t\t\tserver_url: server.server_url,\n\t\t\t\tstate: serverConn?.connectionState ?? defaultState\n\t\t\t};\n\t\t}\n\t\treturn mcpState;\n\t}\n\tbroadcastMcpServers() {\n\t\tthis.broadcast(JSON.stringify({\n\t\t\tmcp: this.getMcpServers(),\n\t\t\ttype: MessageType.CF_AGENT_MCP_SERVERS\n\t\t}));\n\t}\n\t/**\n\t* Handle MCP OAuth callback request if it's an OAuth callback.\n\t*\n\t* This method encapsulates the entire OAuth callback flow:\n\t* 1. Checks if the request is an MCP OAuth callback\n\t* 2. Processes the OAuth code exchange\n\t* 3. Establishes the connection if successful\n\t* 4. Broadcasts MCP server state updates\n\t* 5. Returns the appropriate HTTP response\n\t*\n\t* @param request The incoming HTTP request\n\t* @returns Response if this was an OAuth callback, null otherwise\n\t*/\n\tasync handleMcpOAuthCallback(request) {\n\t\tif (!this.mcp.isCallbackRequest(request)) return null;\n\t\tconst result = await this.mcp.handleCallbackRequest(request);\n\t\tif (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {\n\t\t\tconsole.error(\"[Agent handleMcpOAuthCallback] Connection establishment failed:\", error);\n\t\t});\n\t\tthis.broadcastMcpServers();\n\t\treturn this.handleOAuthCallbackResponse(result, request);\n\t}\n\t/**\n\t* Handle OAuth callback response using MCPClientManager configuration\n\t* @param result OAuth callback result\n\t* @param request The original request (needed for base URL)\n\t* @returns Response for the OAuth callback\n\t*/\n\thandleOAuthCallbackResponse(result, request) {\n\t\tconst config = this.mcp.getOAuthCallbackConfig();\n\t\tif (config?.customHandler) return config.customHandler(result);\n\t\tconst baseOrigin = new URL(request.url).origin;\n\t\tif (config?.successRedirect && result.authSuccess) try {\n\t\t\treturn Response.redirect(new URL(config.successRedirect, baseOrigin).href);\n\t\t} catch (e) {\n\t\t\tconsole.error(\"Invalid successRedirect URL:\", config.successRedirect, e);\n\t\t\treturn Response.redirect(baseOrigin);\n\t\t}\n\t\tif (config?.errorRedirect && !result.authSuccess) try {\n\t\t\tconst errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(result.authError || \"Unknown error\")}`;\n\t\t\treturn Response.redirect(new URL(errorUrl, baseOrigin).href);\n\t\t} catch (e) {\n\t\t\tconsole.error(\"Invalid errorRedirect URL:\", config.errorRedirect, e);\n\t\t\treturn Response.redirect(baseOrigin);\n\t\t}\n\t\treturn Response.redirect(baseOrigin);\n\t}\n};\nconst wrappedClasses = /* @__PURE__ */ new Set();\n/**\n* Route a request to the appropriate Agent\n* @param request Request to route\n* @param env Environment containing Agent bindings\n* @param options Routing options\n* @returns Response from the Agent or undefined if no route matched\n*/\nasync function routeAgentRequest(request, env, options) {\n\tconst corsHeaders = options?.cors === true ? {\n\t\t\"Access-Control-Allow-Credentials\": \"true\",\n\t\t\"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n\t\t\"Access-Control-Allow-Origin\": \"*\",\n\t\t\"Access-Control-Max-Age\": \"86400\"\n\t} : options?.cors;\n\tif (request.method === \"OPTIONS\") {\n\t\tif (corsHeaders) return new Response(null, { headers: corsHeaders });\n\t\tconsole.warn(\"Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.\");\n\t}\n\tlet response = await routePartykitRequest(request, env, {\n\t\tprefix: \"agents\",\n\t\t...options\n\t});\n\tif (response && corsHeaders && request.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\" && request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\") {\n\t\tconst newHeaders = new Headers(response.headers);\n\t\tfor (const [key, value] of Object.entries(corsHeaders)) newHeaders.set(key, value);\n\t\tresponse = new Response(response.body, {\n\t\t\tstatus: response.status,\n\t\t\tstatusText: response.statusText,\n\t\t\theaders: newHeaders\n\t\t});\n\t}\n\treturn response;\n}\n/**\n* Create a resolver that uses the message-id header to determine the agent to route the email to\n* @returns A function that resolves the agent to route the email to\n*/\nfunction createHeaderBasedEmailResolver() {\n\treturn async (email, _env) => {\n\t\tconst messageId = email.headers.get(\"message-id\");\n\t\tif (messageId) {\n\t\t\tconst messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);\n\t\t\tif (messageIdMatch) {\n\t\t\t\tconst [, agentId$1, domain] = messageIdMatch;\n\t\t\t\treturn {\n\t\t\t\t\tagentName: domain.split(\".\")[0],\n\t\t\t\t\tagentId: agentId$1\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst references = email.headers.get(\"references\");\n\t\tif (references) {\n\t\t\tconst referencesMatch = references.match(/<([A-Za-z0-9+/]{43}=)@([^>]+)>/);\n\t\t\tif (referencesMatch) {\n\t\t\t\tconst [, base64Id, domain] = referencesMatch;\n\t\t\t\tconst agentId$1 = Buffer.from(base64Id, \"base64\").toString(\"hex\");\n\t\t\t\treturn {\n\t\t\t\t\tagentName: domain.split(\".\")[0],\n\t\t\t\t\tagentId: agentId$1\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst agentName = email.headers.get(\"x-agent-name\");\n\t\tconst agentId = email.headers.get(\"x-agent-id\");\n\t\tif (agentName && agentId) return {\n\t\t\tagentName,\n\t\t\tagentId\n\t\t};\n\t\treturn null;\n\t};\n}\n/**\n* Create a resolver that uses the email address to determine the agent to route the email to\n* @param defaultAgentName The default agent name to use if the email address does not contain a sub-address\n* @returns A function that resolves the agent to route the email to\n*/\nfunction createAddressBasedEmailResolver(defaultAgentName) {\n\treturn async (email, _env) => {\n\t\tconst emailMatch = email.to.match(/^([^+@]+)(?:\\+([^@]+))?@(.+)$/);\n\t\tif (!emailMatch) return null;\n\t\tconst [, localPart, subAddress] = emailMatch;\n\t\tif (subAddress) return {\n\t\t\tagentName: localPart,\n\t\t\tagentId: subAddress\n\t\t};\n\t\treturn {\n\t\t\tagentName: defaultAgentName,\n\t\t\tagentId: localPart\n\t\t};\n\t};\n}\n/**\n* Create a resolver that uses the agentName and agentId to determine the agent to route the email to\n* @param agentName The name of the agent to route the email to\n* @param agentId The id of the agent to route the email to\n* @returns A function that resolves the agent to route the email to\n*/\nfunction createCatchAllEmailResolver(agentName, agentId) {\n\treturn async () => ({\n\t\tagentName,\n\t\tagentId\n\t});\n}\nconst agentMapCache = /* @__PURE__ */ new WeakMap();\n/**\n* Route an email to the appropriate Agent\n* @param email The email to route\n* @param env The environment containing the Agent bindings\n* @param options The options for routing the email\n* @returns A promise that resolves when the email has been routed\n*/\nasync function routeAgentEmail(email, env, options) {\n\tconst routingInfo = await options.resolver(email, env);\n\tif (!routingInfo) {\n\t\tconsole.warn(\"No routing information found for email, dropping message\");\n\t\treturn;\n\t}\n\tif (!agentMapCache.has(env)) {\n\t\tconst map = {};\n\t\tfor (const [key, value] of Object.entries(env)) if (value && typeof value === \"object\" && \"idFromName\" in value && typeof value.idFromName === \"function\") {\n\t\t\tmap[key] = value;\n\t\t\tmap[camelCaseToKebabCase(key)] = value;\n\t\t}\n\t\tagentMapCache.set(env, map);\n\t}\n\tconst agentMap = agentMapCache.get(env);\n\tconst namespace = agentMap[routingInfo.agentName];\n\tif (!namespace) {\n\t\tconst availableAgents = Object.keys(agentMap).filter((key) => !key.includes(\"-\")).join(\", \");\n\t\tthrow new Error(`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`);\n\t}\n\tconst agent = await getAgentByName(namespace, routingInfo.agentId);\n\tconst serialisableEmail = {\n\t\tgetRaw: async () => {\n\t\t\tconst reader = email.raw.getReader();\n\t\t\tconst chunks = [];\n\t\t\tlet done = false;\n\t\t\twhile (!done) {\n\t\t\t\tconst { value, done: readerDone } = await reader.read();\n\t\t\t\tdone = readerDone;\n\t\t\t\tif (value) chunks.push(value);\n\t\t\t}\n\t\t\tconst totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n\t\t\tconst combined = new Uint8Array(totalLength);\n\t\t\tlet offset = 0;\n\t\t\tfor (const chunk of chunks) {\n\t\t\t\tcombined.set(chunk, offset);\n\t\t\t\toffset += chunk.length;\n\t\t\t}\n\t\t\treturn combined;\n\t\t},\n\t\theaders: email.headers,\n\t\trawSize: email.rawSize,\n\t\tsetReject: (reason) => {\n\t\t\temail.setReject(reason);\n\t\t},\n\t\tforward: (rcptTo, headers) => {\n\t\t\treturn email.forward(rcptTo, headers);\n\t\t},\n\t\treply: (options$1) => {\n\t\t\treturn email.reply(new EmailMessage(options$1.from, options$1.to, options$1.raw));\n\t\t},\n\t\tfrom: email.from,\n\t\tto: email.to\n\t};\n\tawait agent._onEmail(serialisableEmail);\n}\n/**\n* Get or create an Agent by name\n* @template Env Environment type containing bindings\n* @template T Type of the Agent class\n* @param namespace Agent namespace\n* @param name Name of the Agent instance\n* @param options Options for Agent creation\n* @returns Promise resolving to an Agent instance stub\n*/\nasync function getAgentByName(namespace, name, options) {\n\treturn getServerByName(namespace, name, options);\n}\n/**\n* A wrapper for streaming responses in callable methods\n*/\nvar StreamingResponse = class {\n\tconstructor(connection, id) {\n\t\tthis._closed = false;\n\t\tthis._connection = connection;\n\t\tthis._id = id;\n\t}\n\t/**\n\t* Send a chunk of data to the client\n\t* @param chunk The data to send\n\t*/\n\tsend(chunk) {\n\t\tif (this._closed) throw new Error(\"StreamingResponse is already closed\");\n\t\tconst response = {\n\t\t\tdone: false,\n\t\t\tid: this._id,\n\t\t\tresult: chunk,\n\t\t\tsuccess: true,\n\t\t\ttype: MessageType.RPC\n\t\t};\n\t\tthis._connection.send(JSON.stringify(response));\n\t}\n\t/**\n\t* End the stream and send the final chunk (if any)\n\t* @param finalChunk Optional final chunk of data to send\n\t*/\n\tend(finalChunk) {\n\t\tif (this._closed) throw new Error(\"StreamingResponse is already closed\");\n\t\tthis._closed = true;\n\t\tconst response = {\n\t\t\tdone: true,\n\t\t\tid: this._id,\n\t\t\tresult: finalChunk,\n\t\t\tsuccess: true,\n\t\t\ttype: MessageType.RPC\n\t\t};\n\t\tthis._connection.send(JSON.stringify(response));\n\t}\n};\n\n//#endregion\nexport { createCatchAllEmailResolver as a, getCurrentAgent as c, unstable_callable as d, genericObservability as f, createAddressBasedEmailResolver as i, routeAgentEmail as l, StreamingResponse as n, createHeaderBasedEmailResolver as o, callable as r, getAgentByName as s, Agent as t, routeAgentRequest as u };\n//# sourceMappingURL=src-tXpYCgas.js.map","import type { AgentOptions } from \"agents\";\nimport { routeAgentRequest } from \"agents\";\nimport type { Context, Env } from \"hono\";\nimport { env } from \"hono/adapter\";\nimport { createMiddleware } from \"hono/factory\";\n\n/**\n * Configuration options for the Cloudflare Agents middleware\n */\ntype AgentMiddlewareContext<E extends Env> = {\n /** Cloudflare Agents-specific configuration options */\n options?: AgentOptions<E>;\n /** Optional error handler for caught errors */\n onError?: (error: Error) => void;\n};\n\n/**\n * Creates a middleware for handling Cloudflare Agents WebSocket and HTTP requests\n * Processes both WebSocket upgrades and standard HTTP requests, delegating them to Cloudflare Agents\n */\nexport function agentsMiddleware<E extends Env = Env>(\n ctx?: AgentMiddlewareContext<E>\n) {\n return createMiddleware<Env>(async (c, next) => {\n try {\n const handler = isWebSocketUpgrade(c)\n ? handleWebSocketUpgrade\n : handleHttpRequest;\n\n const response = await handler(c, ctx?.options);\n\n return response === null ? await next() : response;\n } catch (error) {\n if (ctx?.onError) {\n ctx.onError(error as Error);\n return next();\n }\n throw error;\n }\n });\n}\n\n/**\n * Checks if the incoming request is a WebSocket upgrade request\n * Looks for the 'upgrade' header with a value of 'websocket' (case-insensitive)\n */\nfunction isWebSocketUpgrade(c: Context): boolean {\n return c.req.header(\"upgrade\")?.toLowerCase() === \"websocket\";\n}\n\n/**\n * Handles WebSocket upgrade requests\n * Returns a WebSocket upgrade response if successful, null otherwise\n */\nasync function handleWebSocketUpgrade<E extends Env>(\n c: Context<E>,\n options?: AgentOptions<E>\n) {\n const response = await routeAgentRequest(\n c.req.raw,\n env(c) satisfies Env,\n options\n );\n\n if (!response?.webSocket) {\n return null;\n }\n\n return new Response(null, {\n status: 101,\n webSocket: response.webSocket\n });\n}\n\n/**\n * Handles standard HTTP requests\n * Forwards the request to Cloudflare Agents and returns the response\n */\nasync function handleHttpRequest<E extends Env>(\n c: Context<E>,\n options?: AgentOptions<E>\n) {\n return routeAgentRequest(c.req.raw, env(c) satisfies Env, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,IAAI,cAA8B,yBAAS,eAAe;AACzD,eAAc,4BAA4B;AAC1C,eAAc,+BAA+B;AAC7C,eAAc,gCAAgC;AAC9C,eAAc,yBAAyB;AACvC,eAAc,kCAAkC;;AAEhD,eAAc,8BAA8B;;AAE5C,eAAc,gCAAgC;AAC9C,eAAc,0BAA0B;AACxC,eAAc,wBAAwB;AACtC,eAAc,oBAAoB;AAClC,eAAc,SAAS;AACvB,QAAO;EACN,EAAE,CAAC;;;;;;;;;ACVL,SAAS,qBAAqB,KAAK;AAClC,KAAI,QAAQ,IAAI,aAAa,IAAI,QAAQ,IAAI,aAAa,CAAE,QAAO,IAAI,aAAa,CAAC,QAAQ,MAAM,IAAI;CACvG,IAAI,aAAa,IAAI,QAAQ,WAAW,WAAW,IAAI,OAAO,aAAa,GAAG;AAC9E,cAAa,WAAW,WAAW,IAAI,GAAG,WAAW,MAAM,EAAE,GAAG;AAChE,QAAO,WAAW,QAAQ,MAAM,IAAI,CAAC,QAAQ,MAAM,GAAG;;;;;ACVvD,IAAI,mCAAmC,MAAM;CAC5C,YAAY,SAAS,YAAY,iBAAiB;AACjD,OAAK,UAAU;AACf,OAAK,aAAa;AAClB,OAAK,kBAAkB;AACvB,MAAI,CAAC,QAAS,OAAM,IAAI,MAAM,kFAAkF;;CAEjH,IAAI,iBAAiB;AACpB,SAAO;GACN,aAAa,KAAK;GAClB,YAAY,KAAK;GACjB,aAAa,CAAC,sBAAsB,gBAAgB;GACpD,eAAe,CAAC,KAAK,YAAY;GACjC,gBAAgB,CAAC,OAAO;GACxB,4BAA4B;GAC5B;;CAEF,IAAI,YAAY;AACf,SAAO,IAAI,IAAI,KAAK,YAAY,CAAC;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AI,KAAK,QAAS,OAAM,IAAI,MAAM,sCAAsC;AACxE,OAAK,UAAU;EACf,MAAM,WAAW;GAChB,MAAM;GACN,IAAI,KAAK;GACT,QAAQ;GACR,SAAS;GACT,MAAM,YAAY;GAClB;AACD,OAAK,YAAY,KAAK,KAAK,UAAU,SAAS,CAAC;;;;;;;;;;ACroCjD,SAAgB,iBACd,KACA;AACA,QAAO,iBAAsB,OAAO,GAAG,SAAS;AAC9C,MAAI;GAKF,MAAM,WAAW,OAJD,mBAAmB,EAAE,GACjC,yBACA,mBAE2B,GAAG,KAAK,QAAQ;AAE/C,UAAO,aAAa,OAAO,MAAM,MAAM,GAAG;WACnC,OAAO;AACd,OAAI,KAAK,SAAS;AAChB,QAAI,QAAQ,MAAe;AAC3B,WAAO,MAAM;;AAEf,SAAM;;GAER;;;;;;AAOJ,SAAS,mBAAmB,GAAqB;AAC/C,QAAO,EAAE,IAAI,OAAO,UAAU,EAAE,aAAa,KAAK;;;;;;AAOpD,eAAe,uBACb,GACA,SACA;CACA,MAAM,WAAW,MAAM,kBACrB,EAAE,IAAI,KACN,IAAI,EAAE,EACN,QACD;AAED,KAAI,CAAC,UAAU,UACb,QAAO;AAGT,QAAO,IAAI,SAAS,MAAM;EACxB,QAAQ;EACR,WAAW,SAAS;EACrB,CAAC;;;;;;AAOJ,eAAe,kBACb,GACA,SACA;AACA,QAAO,kBAAkB,EAAE,IAAI,KAAK,IAAI,EAAE,EAAgB,QAAQ"}
package/package.json CHANGED
@@ -5,8 +5,8 @@
5
5
  },
6
6
  "description": "Add Cloudflare Agents to your Hono app",
7
7
  "devDependencies": {
8
- "agents": "^0.2.24",
9
- "hono": "^4.10.6"
8
+ "agents": "^0.2.26",
9
+ "hono": "^4.10.7"
10
10
  },
11
11
  "publishConfig": {
12
12
  "access": "public"
@@ -31,7 +31,7 @@
31
31
  "main": "src/index.ts",
32
32
  "name": "hono-agents",
33
33
  "peerDependencies": {
34
- "agents": "^0.2.24",
34
+ "agents": "^0.2.26",
35
35
  "hono": "^4.6.17"
36
36
  },
37
37
  "repository": {
@@ -45,5 +45,5 @@
45
45
  },
46
46
  "type": "module",
47
47
  "types": "dist/index.d.ts",
48
- "version": "2.0.6"
48
+ "version": "2.0.7"
49
49
  }