agents 0.0.107 → 0.0.109

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.
@@ -1,6 +1,7 @@
1
1
  import { Message, StreamTextOnFinishCallback, ToolSet } from "ai";
2
- import { A as Agent, a as AgentContext } from "./index-BIJvkfYt.js";
2
+ import { A as Agent, a as AgentContext } from "./index-CLW1aEBr.js";
3
3
  import { Connection, WSMessage } from "partyserver";
4
+ import "cloudflare:workers";
4
5
  import "@modelcontextprotocol/sdk/client/index.js";
5
6
  import "@modelcontextprotocol/sdk/types.js";
6
7
  import "./mcp/client.js";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  Agent
3
- } from "./chunk-Z2OUUKK4.js";
3
+ } from "./chunk-3IQQY2UH.js";
4
4
  import "./chunk-UNG3FXYX.js";
5
5
  import "./chunk-PVQZBKN7.js";
6
6
  import "./chunk-KUH345EY.js";
@@ -4,7 +4,8 @@ import { useChat } from "@ai-sdk/react";
4
4
  import { useAgent } from "./react.js";
5
5
  import "partysocket";
6
6
  import "partysocket/react";
7
- import "./index-BIJvkfYt.js";
7
+ import "./index-CLW1aEBr.js";
8
+ import "cloudflare:workers";
8
9
  import "@modelcontextprotocol/sdk/client/index.js";
9
10
  import "@modelcontextprotocol/sdk/types.js";
10
11
  import "partyserver";
@@ -1267,4 +1267,4 @@ export {
1267
1267
  getAgentByName,
1268
1268
  StreamingResponse
1269
1269
  };
1270
- //# sourceMappingURL=chunk-Z2OUUKK4.js.map
1270
+ //# sourceMappingURL=chunk-3IQQY2UH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/observability/index.ts"],"sourcesContent":["import type { env } from \"cloudflare:workers\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nimport type {\n Prompt,\n Resource,\n ServerCapabilities,\n Tool\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { parseCronExpression } from \"cron-schedule\";\nimport { nanoid } from \"nanoid\";\nimport { EmailMessage } from \"cloudflare:email\";\nimport {\n type Connection,\n type ConnectionContext,\n type PartyServerOptions,\n Server,\n type WSMessage,\n getServerByName,\n routePartykitRequest\n} from \"partyserver\";\nimport { camelCaseToKebabCase } from \"./client\";\nimport { MCPClientManager } from \"./mcp/client\";\n// import type { MCPClientConnection } from \"./mcp/client-connection\";\nimport { DurableObjectOAuthClientProvider } from \"./mcp/do-oauth-client-provider\";\nimport { genericObservability, type Observability } from \"./observability\";\n\nexport type { Connection, ConnectionContext, WSMessage } from \"partyserver\";\n\n/**\n * RPC request message from client\n */\nexport type RPCRequest = {\n type: \"rpc\";\n id: string;\n method: string;\n args: unknown[];\n};\n\n/**\n * State update message from client\n */\nexport type StateUpdateMessage = {\n type: \"cf_agent_state\";\n state: unknown;\n};\n\n/**\n * RPC response message to client\n */\nexport type RPCResponse = {\n type: \"rpc\";\n id: string;\n} & (\n | {\n success: true;\n result: unknown;\n done?: false;\n }\n | {\n success: true;\n result: unknown;\n done: true;\n }\n | {\n success: false;\n error: string;\n }\n);\n\n/**\n * Type guard for RPC request messages\n */\nfunction isRPCRequest(msg: unknown): msg is RPCRequest {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === \"rpc\" &&\n \"id\" in msg &&\n typeof msg.id === \"string\" &&\n \"method\" in msg &&\n typeof msg.method === \"string\" &&\n \"args\" in msg &&\n Array.isArray((msg as RPCRequest).args)\n );\n}\n\n/**\n * Type guard for state update messages\n */\nfunction isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === \"cf_agent_state\" &&\n \"state\" in msg\n );\n}\n\n/**\n * Metadata for a callable method\n */\nexport type CallableMetadata = {\n /** Optional description of what the method does */\n description?: string;\n /** Whether the method supports streaming responses */\n streaming?: boolean;\n};\n\nconst callableMetadata = new Map<Function, CallableMetadata>();\n\n/**\n * Decorator that marks a method as callable by clients\n * @param metadata Optional metadata about the callable method\n */\nexport function unstable_callable(metadata: CallableMetadata = {}) {\n return function callableDecorator<This, Args extends unknown[], Return>(\n target: (this: This, ...args: Args) => Return,\n // biome-ignore lint/correctness/noUnusedFunctionParameters: later\n context: ClassMethodDecoratorContext\n ) {\n if (!callableMetadata.has(target)) {\n callableMetadata.set(target, metadata);\n }\n\n return target;\n };\n}\n\nexport type QueueItem<T = string> = {\n id: string;\n payload: T;\n callback: keyof Agent<unknown>;\n created_at: number;\n};\n\n/**\n * Represents a scheduled task within an Agent\n * @template T Type of the payload data\n */\nexport type Schedule<T = string> = {\n /** Unique identifier for the schedule */\n id: string;\n /** Name of the method to be called */\n callback: string;\n /** Data to be passed to the callback */\n payload: T;\n} & (\n | {\n /** Type of schedule for one-time execution at a specific time */\n type: \"scheduled\";\n /** Timestamp when the task should execute */\n time: number;\n }\n | {\n /** Type of schedule for delayed execution */\n type: \"delayed\";\n /** Timestamp when the task should execute */\n time: number;\n /** Number of seconds to delay execution */\n delayInSeconds: number;\n }\n | {\n /** Type of schedule for recurring execution based on cron expression */\n type: \"cron\";\n /** Timestamp for the next execution */\n time: number;\n /** Cron expression defining the schedule */\n cron: string;\n }\n);\n\nfunction getNextCronTime(cron: string) {\n const interval = parseCronExpression(cron);\n return interval.getNextDate();\n}\n\n/**\n * MCP Server state update message from server -> Client\n */\nexport type MCPServerMessage = {\n type: \"cf_agent_mcp_servers\";\n mcp: MCPServersState;\n};\n\nexport type MCPServersState = {\n servers: {\n [id: string]: MCPServer;\n };\n tools: Tool[];\n prompts: Prompt[];\n resources: Resource[];\n};\n\nexport type MCPServer = {\n name: string;\n server_url: string;\n auth_url: string | null;\n // This state is specifically about the temporary process of getting a token (if needed).\n // Scope outside of that can't be relied upon because when the DO sleeps, there's no way\n // to communicate a change to a non-ready state.\n state: \"authenticating\" | \"connecting\" | \"ready\" | \"discovering\" | \"failed\";\n instructions: string | null;\n capabilities: ServerCapabilities | null;\n};\n\n/**\n * MCP Server data stored in DO SQL for resuming MCP Server connections\n */\ntype MCPServerRow = {\n id: string;\n name: string;\n server_url: string;\n client_id: string | null;\n auth_url: string | null;\n callback_url: string;\n server_options: string;\n};\n\nconst STATE_ROW_ID = \"cf_state_row_id\";\nconst STATE_WAS_CHANGED = \"cf_state_was_changed\";\n\nconst DEFAULT_STATE = {} as unknown;\n\nconst agentContext = new AsyncLocalStorage<{\n agent: Agent<unknown, unknown>;\n connection: Connection | undefined;\n request: Request | undefined;\n email: AgentEmail | undefined;\n}>();\n\nexport function getCurrentAgent<\n T extends Agent<unknown, unknown> = Agent<unknown, unknown>\n>(): {\n agent: T | undefined;\n connection: Connection | undefined;\n request: Request | undefined;\n email: AgentEmail | undefined;\n} {\n const store = agentContext.getStore() as\n | {\n agent: T;\n connection: Connection | undefined;\n request: Request | undefined;\n email: AgentEmail | undefined;\n }\n | undefined;\n if (!store) {\n return {\n agent: undefined,\n connection: undefined,\n request: undefined,\n email: undefined\n };\n }\n return store;\n}\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 */\n\n// biome-ignore lint/suspicious/noExplicitAny: I can't typescript\nfunction withAgentContext<T extends (...args: any[]) => any>(\n method: T\n): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {\n return function (...args: Parameters<T>): ReturnType<T> {\n const { connection, request, email } = getCurrentAgent();\n return agentContext.run({ agent: this, connection, request, email }, () => {\n return method.apply(this, args);\n });\n };\n}\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 */\nexport class Agent<Env = typeof env, State = unknown> extends Server<Env> {\n private _state = DEFAULT_STATE as State;\n\n private _ParentClass: typeof Agent<Env, State> =\n Object.getPrototypeOf(this).constructor;\n\n mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, \"0.0.1\");\n\n /**\n * Initial state for the Agent\n * Override to provide default state values\n */\n initialState: State = DEFAULT_STATE as State;\n\n /**\n * Current state of the Agent\n */\n get state(): State {\n if (this._state !== DEFAULT_STATE) {\n // state was previously set, and populated internal state\n return this._state;\n }\n // looks like this is the first time the state is being accessed\n // check if the state was set in a previous life\n const wasChanged = this.sql<{ state: \"true\" | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}\n `;\n\n // ok, let's pick up the actual state from the db\n const result = this.sql<{ state: State | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}\n `;\n\n if (\n wasChanged[0]?.state === \"true\" ||\n // we do this check for people who updated their code before we shipped wasChanged\n result[0]?.state\n ) {\n const state = result[0]?.state as string; // could be null?\n\n this._state = JSON.parse(state);\n return this._state;\n }\n\n // ok, this is the first time the state is being accessed\n // and the state was not set in a previous life\n // so we need to set the initial state (if provided)\n if (this.initialState === DEFAULT_STATE) {\n // no initial state provided, so we return undefined\n return undefined as State;\n }\n // initial state provided, so we set the state,\n // update db and return the initial state\n this.setState(this.initialState);\n return this.initialState;\n }\n\n /**\n * Agent configuration options\n */\n static options = {\n /** Whether the Agent should hibernate when inactive */\n hibernate: true // default to hibernate\n };\n\n /**\n * The observability implementation to use for the Agent\n */\n observability?: Observability = genericObservability;\n\n /**\n * Execute SQL queries against the Agent's database\n * @template T Type of the returned rows\n * @param strings SQL query template strings\n * @param values Values to be inserted into the query\n * @returns Array of query results\n */\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ) {\n let query = \"\";\n try {\n // Construct the SQL query with placeholders\n query = strings.reduce(\n (acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"),\n \"\"\n );\n\n // Execute the SQL query with the provided values\n return [...this.ctx.storage.sql.exec(query, ...values)] as T[];\n } catch (e) {\n console.error(`failed to execute sql query: ${query}`, e);\n throw this.onError(e);\n }\n }\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n\n // Auto-wrap custom methods with agent context\n this._autoWrapCustomMethods();\n\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_state (\n id TEXT PRIMARY KEY NOT NULL,\n state TEXT\n )\n `;\n\n this.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\n void this.ctx.blockConcurrencyWhile(async () => {\n return this._tryCatch(async () => {\n // Create alarms table if it doesn't exist\n this.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\n // execute any pending alarms and schedule the next alarm\n await this.alarm();\n });\n });\n\n this.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\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = (request: Request) => {\n return agentContext.run(\n { agent: this, connection: undefined, request, email: undefined },\n async () => {\n if (this.mcp.isCallbackRequest(request)) {\n await this.mcp.handleCallbackRequest(request);\n\n // after the MCP connection handshake, we can send updated mcp state\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: \"cf_agent_mcp_servers\"\n })\n );\n\n // We probably should let the user configure this response/redirect, but this is fine for now.\n return new Response(\"<script>window.close();</script>\", {\n headers: { \"content-type\": \"text/html\" },\n status: 200\n });\n }\n\n return this._tryCatch(() => _onRequest(request));\n }\n );\n };\n\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n return agentContext.run(\n { agent: this, connection, request: undefined, email: undefined },\n async () => {\n if (typeof message !== \"string\") {\n return this._tryCatch(() => _onMessage(connection, message));\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(message);\n } catch (_e) {\n // silently fail and let the onMessage handler handle it\n return this._tryCatch(() => _onMessage(connection, message));\n }\n\n if (isStateUpdateMessage(parsed)) {\n this._setStateInternal(parsed.state as State, connection);\n return;\n }\n\n if (isRPCRequest(parsed)) {\n try {\n const { id, method, args } = parsed;\n\n // Check if method exists and is callable\n const methodFn = this[method as keyof this];\n if (typeof methodFn !== \"function\") {\n throw new Error(`Method ${method} does not exist`);\n }\n\n if (!this._isCallable(method)) {\n throw new Error(`Method ${method} is not callable`);\n }\n\n const metadata = callableMetadata.get(methodFn as Function);\n\n // For streaming methods, pass a StreamingResponse object\n if (metadata?.streaming) {\n const stream = new StreamingResponse(connection, id);\n await methodFn.apply(this, [stream, ...args]);\n return;\n }\n\n // For regular methods, execute and send response\n const result = await methodFn.apply(this, args);\n\n this.observability?.emit(\n {\n displayMessage: `RPC call to ${method}`,\n id: nanoid(),\n payload: {\n args,\n method,\n streaming: metadata?.streaming,\n success: true\n },\n timestamp: Date.now(),\n type: \"rpc\"\n },\n this.ctx\n );\n\n const response: RPCResponse = {\n done: true,\n id,\n result,\n success: true,\n type: \"rpc\"\n };\n connection.send(JSON.stringify(response));\n } catch (e) {\n // Send error response\n const response: RPCResponse = {\n error:\n e instanceof Error ? e.message : \"Unknown error occurred\",\n id: parsed.id,\n success: false,\n type: \"rpc\"\n };\n connection.send(JSON.stringify(response));\n console.error(\"RPC error:\", e);\n }\n return;\n }\n\n return this._tryCatch(() => _onMessage(connection, message));\n }\n );\n };\n\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = (connection: Connection, ctx: ConnectionContext) => {\n // TODO: This is a hack to ensure the state is sent after the connection is established\n // must fix this\n return agentContext.run(\n { agent: this, connection, request: ctx.request, email: undefined },\n async () => {\n setTimeout(() => {\n if (this.state) {\n connection.send(\n JSON.stringify({\n state: this.state,\n type: \"cf_agent_state\"\n })\n );\n }\n\n connection.send(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: \"cf_agent_mcp_servers\"\n })\n );\n\n this.observability?.emit(\n {\n displayMessage: \"Connection established\",\n id: nanoid(),\n payload: {\n connectionId: connection.id\n },\n timestamp: Date.now(),\n type: \"connect\"\n },\n this.ctx\n );\n return this._tryCatch(() => _onConnect(connection, ctx));\n }, 20);\n }\n );\n };\n\n const _onStart = this.onStart.bind(this);\n this.onStart = async () => {\n return agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n const servers = this.sql<MCPServerRow>`\n SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;\n `;\n\n // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information\n if (servers && Array.isArray(servers) && servers.length > 0) {\n Promise.allSettled(\n servers.map((server) => {\n return this._connectToMcpServerInternal(\n server.name,\n server.server_url,\n server.callback_url,\n server.server_options\n ? JSON.parse(server.server_options)\n : undefined,\n {\n id: server.id,\n oauthClientId: server.client_id ?? undefined\n }\n );\n })\n ).then((_results) => {\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: \"cf_agent_mcp_servers\"\n })\n );\n });\n }\n await this._tryCatch(() => _onStart());\n }\n );\n };\n }\n\n private _setStateInternal(\n state: State,\n source: Connection | \"server\" = \"server\"\n ) {\n const previousState = this._state;\n this._state = state;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})\n `;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})\n `;\n this.broadcast(\n JSON.stringify({\n state: state,\n type: \"cf_agent_state\"\n }),\n source !== \"server\" ? [source.id] : []\n );\n return this._tryCatch(() => {\n const { connection, request, email } = agentContext.getStore() || {};\n return agentContext.run(\n { agent: this, connection, request, email },\n async () => {\n this.observability?.emit(\n {\n displayMessage: \"State updated\",\n id: nanoid(),\n payload: {\n previousState,\n state\n },\n timestamp: Date.now(),\n type: \"state:update\"\n },\n this.ctx\n );\n return this.onStateUpdate(state, source);\n }\n );\n });\n }\n\n /**\n * Update the Agent's state\n * @param state New state to set\n */\n setState(state: State) {\n this._setStateInternal(state, \"server\");\n }\n\n /**\n * Called when the Agent's state is updated\n * @param state Updated state\n * @param source Source of the state update (\"server\" or a client connection)\n */\n // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates\n }\n\n /**\n * Called when the Agent receives an email via routeAgentEmail()\n * Override this method to handle incoming emails\n * @param email Email message to process\n */\n async _onEmail(email: AgentEmail) {\n // nb: we use this roundabout way of getting to onEmail\n // because of https://github.com/cloudflare/workerd/issues/4499\n return agentContext.run(\n { agent: this, connection: undefined, request: undefined, email: email },\n async () => {\n if (\"onEmail\" in this && typeof this.onEmail === \"function\") {\n return this._tryCatch(() =>\n (this.onEmail as (email: AgentEmail) => Promise<void>)(email)\n );\n } else {\n console.log(\"Received email from:\", email.from, \"to:\", email.to);\n console.log(\"Subject:\", email.headers.get(\"subject\"));\n console.log(\n \"Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails\"\n );\n }\n }\n );\n }\n\n /**\n * Reply to an email\n * @param email The email to reply to\n * @param options Options for the reply\n * @returns void\n */\n async replyToEmail(\n email: AgentEmail,\n options: {\n fromName: string;\n subject?: string | undefined;\n body: string;\n contentType?: string;\n headers?: Record<string, string>;\n }\n ): Promise<void> {\n return this._tryCatch(async () => {\n const agentName = camelCaseToKebabCase(this._ParentClass.name);\n const agentId = this.name;\n\n const { createMimeMessage } = await import(\"mimetext\");\n const msg = createMimeMessage();\n msg.setSender({ addr: email.to, name: options.fromName });\n msg.setRecipient(email.from);\n msg.setSubject(\n options.subject || `Re: ${email.headers.get(\"subject\")}` || \"No subject\"\n );\n msg.addMessage({\n contentType: options.contentType || \"text/plain\",\n data: options.body\n });\n\n const domain = email.from.split(\"@\")[1];\n const messageId = `<${agentId}@${domain}>`;\n msg.setHeader(\"In-Reply-To\", email.headers.get(\"Message-ID\")!);\n msg.setHeader(\"Message-ID\", messageId);\n msg.setHeader(\"X-Agent-Name\", agentName);\n msg.setHeader(\"X-Agent-ID\", agentId);\n\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n msg.setHeader(key, value);\n }\n }\n await email.reply({\n from: email.to,\n raw: msg.asRaw(),\n to: email.from\n });\n });\n }\n\n private async _tryCatch<T>(fn: () => T | Promise<T>) {\n try {\n return await fn();\n } catch (e) {\n throw this.onError(e);\n }\n }\n\n /**\n * Automatically wrap custom methods with agent context\n * This ensures getCurrentAgent() works in all custom methods without decorators\n */\n private _autoWrapCustomMethods() {\n // Collect all methods from base prototypes (Agent and Server)\n const basePrototypes = [Agent.prototype, Server.prototype];\n const baseMethods = new Set<string>();\n for (const baseProto of basePrototypes) {\n let proto = baseProto;\n while (proto && proto !== Object.prototype) {\n const methodNames = Object.getOwnPropertyNames(proto);\n for (const methodName of methodNames) {\n baseMethods.add(methodName);\n }\n proto = Object.getPrototypeOf(proto);\n }\n }\n // Get all methods from the current instance's prototype chain\n let proto = Object.getPrototypeOf(this);\n let depth = 0;\n while (proto && proto !== Object.prototype && depth < 10) {\n const methodNames = Object.getOwnPropertyNames(proto);\n for (const methodName of methodNames) {\n // Skip if it's a private method or not a function\n if (\n baseMethods.has(methodName) ||\n methodName.startsWith(\"_\") ||\n typeof this[methodName as keyof this] !== \"function\"\n ) {\n continue;\n }\n // If the method doesn't exist in base prototypes, it's a custom method\n if (!baseMethods.has(methodName)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);\n if (descriptor && typeof descriptor.value === \"function\") {\n // Wrap the custom method with context\n\n const wrappedFunction = withAgentContext(\n // biome-ignore lint/suspicious/noExplicitAny: I can't typescript\n this[methodName as keyof this] as (...args: any[]) => any\n // biome-ignore lint/suspicious/noExplicitAny: I can't typescript\n ) as any;\n\n // if the method is callable, copy the metadata from the original method\n if (this._isCallable(methodName)) {\n callableMetadata.set(\n wrappedFunction,\n callableMetadata.get(\n this[methodName as keyof this] as Function\n )!\n );\n }\n\n // set the wrapped function on the prototype\n this.constructor.prototype[methodName as keyof this] =\n wrappedFunction;\n }\n }\n }\n\n proto = Object.getPrototypeOf(proto);\n depth++;\n }\n }\n\n override onError(\n connection: Connection,\n error: unknown\n ): void | Promise<void>;\n override onError(error: unknown): void | Promise<void>;\n override onError(connectionOrError: Connection | unknown, error?: unknown) {\n let theError: unknown;\n if (connectionOrError && error) {\n theError = error;\n // this is a websocket connection error\n console.error(\n \"Error on websocket connection:\",\n (connectionOrError as Connection).id,\n theError\n );\n console.error(\n \"Override onError(connection, error) to handle websocket connection errors\"\n );\n } else {\n theError = connectionOrError;\n // this is a server error\n console.error(\"Error on server:\", theError);\n console.error(\"Override onError(error) to handle server errors\");\n }\n throw theError;\n }\n\n /**\n * Render content (not implemented in base class)\n */\n render() {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Queue a task to be executed in the future\n * @param payload Payload to pass to the callback\n * @param callback Name of the method to call\n * @returns The ID of the queued task\n */\n async queue<T = unknown>(callback: keyof this, payload: T): Promise<string> {\n const id = nanoid(9);\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n\n if (typeof this[callback] !== \"function\") {\n throw new Error(`this.${callback} is not a function`);\n }\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)\n VALUES (${id}, ${JSON.stringify(payload)}, ${callback})\n `;\n\n void this._flushQueue().catch((e) => {\n console.error(\"Error flushing queue:\", e);\n });\n\n return id;\n }\n\n private _flushingQueue = false;\n\n private async _flushQueue() {\n if (this._flushingQueue) {\n return;\n }\n this._flushingQueue = true;\n while (true) {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues\n ORDER BY created_at ASC\n `;\n\n if (!result || result.length === 0) {\n break;\n }\n\n for (const row of result || []) {\n const callback = this[row.callback as keyof Agent<Env>];\n if (!callback) {\n console.error(`callback ${row.callback} not found`);\n continue;\n }\n const { connection, request, email } = agentContext.getStore() || {};\n await agentContext.run(\n {\n agent: this,\n connection,\n request,\n email\n },\n async () => {\n // TODO: add retries and backoff\n await (\n callback as (\n payload: unknown,\n queueItem: QueueItem<string>\n ) => Promise<void>\n ).bind(this)(JSON.parse(row.payload as string), row);\n await this.dequeue(row.id);\n }\n );\n }\n }\n this._flushingQueue = false;\n }\n\n /**\n * Dequeue a task by ID\n * @param id ID of the task to dequeue\n */\n async dequeue(id: string) {\n this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;\n }\n\n /**\n * Dequeue all tasks\n */\n async dequeueAll() {\n this.sql`DELETE FROM cf_agents_queues`;\n }\n\n /**\n * Dequeue all tasks by callback\n * @param callback Name of the callback to dequeue\n */\n async dequeueAllByCallback(callback: string) {\n this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;\n }\n\n /**\n * Get a queued task by ID\n * @param id ID of the task to get\n * @returns The task or undefined if not found\n */\n async getQueue(id: string): Promise<QueueItem<string> | undefined> {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues WHERE id = ${id}\n `;\n return result\n ? { ...result[0], payload: JSON.parse(result[0].payload) }\n : undefined;\n }\n\n /**\n * Get all queues by key and value\n * @param key Key to filter by\n * @param value Value to filter by\n * @returns Array of matching QueueItem objects\n */\n async getQueues(key: string, value: string): Promise<QueueItem<string>[]> {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues\n `;\n return result.filter((row) => JSON.parse(row.payload)[key] === value);\n }\n\n /**\n * Schedule a task to be executed in the future\n * @template T Type of the payload data\n * @param when When to execute the task (Date, seconds delay, or cron expression)\n * @param callback Name of the method to call\n * @param payload Data to pass to the callback\n * @returns Schedule object representing the scheduled task\n */\n async schedule<T = string>(\n when: Date | string | number,\n callback: keyof this,\n payload?: T\n ): Promise<Schedule<T>> {\n const id = nanoid(9);\n\n const emitScheduleCreate = (schedule: Schedule<T>) =>\n this.observability?.emit(\n {\n displayMessage: `Schedule ${schedule.id} created`,\n id: nanoid(),\n payload: schedule,\n timestamp: Date.now(),\n type: \"schedule:create\"\n },\n this.ctx\n );\n\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n\n if (typeof this[callback] !== \"function\") {\n throw new Error(`this.${callback} is not a function`);\n }\n\n if (when instanceof Date) {\n const timestamp = Math.floor(when.getTime() / 1000);\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'scheduled', ${timestamp})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n id,\n payload: payload as T,\n time: timestamp,\n type: \"scheduled\"\n };\n\n emitScheduleCreate(schedule);\n\n return schedule;\n }\n if (typeof when === \"number\") {\n const time = new Date(Date.now() + when * 1000);\n const timestamp = Math.floor(time.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'delayed', ${when}, ${timestamp})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n delayInSeconds: when,\n id,\n payload: payload as T,\n time: timestamp,\n type: \"delayed\"\n };\n\n emitScheduleCreate(schedule);\n\n return schedule;\n }\n if (typeof when === \"string\") {\n const nextExecutionTime = getNextCronTime(when);\n const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'cron', ${when}, ${timestamp})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n cron: when,\n id,\n payload: payload as T,\n time: timestamp,\n type: \"cron\"\n };\n\n emitScheduleCreate(schedule);\n\n return schedule;\n }\n throw new Error(\"Invalid schedule type\");\n }\n\n /**\n * Get a scheduled task by ID\n * @template T Type of the payload data\n * @param id ID of the scheduled task\n * @returns The Schedule object or undefined if not found\n */\n async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE id = ${id}\n `;\n if (!result) {\n console.error(`schedule ${id} not found`);\n return undefined;\n }\n\n return { ...result[0], payload: JSON.parse(result[0].payload) as T };\n }\n\n /**\n * Get scheduled tasks matching the given criteria\n * @template T Type of the payload data\n * @param criteria Criteria to filter schedules\n * @returns Array of matching Schedule objects\n */\n getSchedules<T = string>(\n criteria: {\n id?: string;\n type?: \"scheduled\" | \"delayed\" | \"cron\";\n timeRange?: { start?: Date; end?: Date };\n } = {}\n ): Schedule<T>[] {\n let query = \"SELECT * FROM cf_agents_schedules WHERE 1=1\";\n const params = [];\n\n if (criteria.id) {\n query += \" AND id = ?\";\n params.push(criteria.id);\n }\n\n if (criteria.type) {\n query += \" AND type = ?\";\n params.push(criteria.type);\n }\n\n if (criteria.timeRange) {\n query += \" AND time >= ? AND time <= ?\";\n const start = criteria.timeRange.start || new Date(0);\n const end = criteria.timeRange.end || new Date(999999999999999);\n params.push(\n Math.floor(start.getTime() / 1000),\n Math.floor(end.getTime() / 1000)\n );\n }\n\n const result = this.ctx.storage.sql\n .exec(query, ...params)\n .toArray()\n .map((row) => ({\n ...row,\n payload: JSON.parse(row.payload as string) as T\n })) as Schedule<T>[];\n\n return result;\n }\n\n /**\n * Cancel a scheduled task\n * @param id ID of the task to cancel\n * @returns true if the task was cancelled, false otherwise\n */\n async cancelSchedule(id: string): Promise<boolean> {\n const schedule = await this.getSchedule(id);\n if (schedule) {\n this.observability?.emit(\n {\n displayMessage: `Schedule ${id} cancelled`,\n id: nanoid(),\n payload: schedule,\n timestamp: Date.now(),\n type: \"schedule:cancel\"\n },\n this.ctx\n );\n }\n this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;\n\n await this._scheduleNextAlarm();\n return true;\n }\n\n private async _scheduleNextAlarm() {\n // Find the next schedule that needs to be executed\n const result = this.sql`\n SELECT time FROM cf_agents_schedules\n WHERE time > ${Math.floor(Date.now() / 1000)}\n ORDER BY time ASC\n LIMIT 1\n `;\n if (!result) return;\n\n if (result.length > 0 && \"time\" in result[0]) {\n const nextTime = (result[0].time as number) * 1000;\n await this.ctx.storage.setAlarm(nextTime);\n }\n }\n\n /**\n * Method called when an alarm fires.\n * Executes any scheduled tasks that are due.\n *\n * @remarks\n * To schedule a task, please use the `this.schedule` method instead.\n * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}\n */\n public readonly alarm = async () => {\n const now = Math.floor(Date.now() / 1000);\n\n // Get all schedules that should be executed now\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE time <= ${now}\n `;\n\n if (result && Array.isArray(result)) {\n for (const row of result) {\n const callback = this[row.callback as keyof Agent<Env>];\n if (!callback) {\n console.error(`callback ${row.callback} not found`);\n continue;\n }\n await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n try {\n this.observability?.emit(\n {\n displayMessage: `Schedule ${row.id} executed`,\n id: nanoid(),\n payload: row,\n timestamp: Date.now(),\n type: \"schedule:execute\"\n },\n this.ctx\n );\n\n await (\n callback as (\n payload: unknown,\n schedule: Schedule<unknown>\n ) => Promise<void>\n ).bind(this)(JSON.parse(row.payload as string), row);\n } catch (e) {\n console.error(`error executing callback \"${row.callback}\"`, e);\n }\n }\n );\n if (row.type === \"cron\") {\n // Update next execution time for cron schedules\n const nextExecutionTime = getNextCronTime(row.cron);\n const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}\n `;\n } else {\n // Delete one-time schedules after execution\n this.sql`\n DELETE FROM cf_agents_schedules WHERE id = ${row.id}\n `;\n }\n }\n }\n\n // Schedule the next alarm\n await this._scheduleNextAlarm();\n };\n\n /**\n * Destroy the Agent, removing all state and scheduled tasks\n */\n async destroy() {\n // drop all tables\n this.sql`DROP TABLE IF EXISTS cf_agents_state`;\n this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;\n this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;\n this.sql`DROP TABLE IF EXISTS cf_agents_queues`;\n\n // delete all alarms\n await this.ctx.storage.deleteAlarm();\n await this.ctx.storage.deleteAll();\n this.ctx.abort(\"destroyed\"); // enforce that the agent is evicted\n\n this.observability?.emit(\n {\n displayMessage: \"Agent destroyed\",\n id: nanoid(),\n payload: {},\n timestamp: Date.now(),\n type: \"destroy\"\n },\n this.ctx\n );\n }\n\n /**\n * Get all methods marked as callable on this Agent\n * @returns A map of method names to their metadata\n */\n private _isCallable(method: string): boolean {\n return callableMetadata.has(this[method as keyof this] as Function);\n }\n\n /**\n * Connect to a new MCP Server\n *\n * @param url MCP Server SSE URL\n * @param callbackHost Base host for the agent, used for the redirect URI.\n * @param agentsPrefix agents routing prefix if not using `agents`\n * @param options MCP client and transport (header) options\n * @returns authUrl\n */\n async addMcpServer(\n serverName: string,\n url: string,\n callbackHost: string,\n agentsPrefix = \"agents\",\n options?: {\n client?: ConstructorParameters<typeof Client>[1];\n transport?: {\n headers: HeadersInit;\n };\n }\n ): Promise<{ id: string; authUrl: string | undefined }> {\n const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;\n\n const result = await this._connectToMcpServerInternal(\n serverName,\n url,\n callbackUrl,\n options\n );\n this.sql`\n INSERT\n OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)\n VALUES (\n ${result.id},\n ${serverName},\n ${url},\n ${result.clientId ?? null},\n ${result.authUrl ?? null},\n ${callbackUrl},\n ${options ? JSON.stringify(options) : null}\n );\n `;\n\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: \"cf_agent_mcp_servers\"\n })\n );\n\n return result;\n }\n\n async _connectToMcpServerInternal(\n _serverName: string,\n url: string,\n callbackUrl: string,\n // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes\n options?: {\n client?: ConstructorParameters<typeof Client>[1];\n /**\n * We don't expose the normal set of transport options because:\n * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes\n * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)\n *\n * This has the limitation that you can't override fetch, but I think headers should handle nearly all cases needed (i.e. non-standard bearer auth).\n */\n transport?: {\n headers?: HeadersInit;\n };\n },\n reconnect?: {\n id: string;\n oauthClientId?: string;\n }\n ): Promise<{\n id: string;\n authUrl: string | undefined;\n clientId: string | undefined;\n }> {\n const authProvider = new DurableObjectOAuthClientProvider(\n this.ctx.storage,\n this.name,\n callbackUrl\n );\n\n if (reconnect) {\n authProvider.serverId = reconnect.id;\n if (reconnect.oauthClientId) {\n authProvider.clientId = reconnect.oauthClientId;\n }\n }\n\n // allows passing through transport headers if necessary\n // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)\n let headerTransportOpts: SSEClientTransportOptions = {};\n if (options?.transport?.headers) {\n headerTransportOpts = {\n eventSourceInit: {\n fetch: (url, init) =>\n fetch(url, {\n ...init,\n headers: options?.transport?.headers\n })\n },\n requestInit: {\n headers: options?.transport?.headers\n }\n };\n }\n\n const { id, authUrl, clientId } = await this.mcp.connect(url, {\n client: options?.client,\n reconnect,\n transport: {\n ...headerTransportOpts,\n authProvider\n }\n });\n\n return {\n authUrl,\n clientId,\n id\n };\n }\n\n async removeMcpServer(id: string) {\n this.mcp.closeConnection(id);\n this.sql`\n DELETE FROM cf_agents_mcp_servers WHERE id = ${id};\n `;\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: \"cf_agent_mcp_servers\"\n })\n );\n }\n\n getMcpServers(): MCPServersState {\n const mcpState: MCPServersState = {\n prompts: this.mcp.listPrompts(),\n resources: this.mcp.listResources(),\n servers: {},\n tools: this.mcp.listTools()\n };\n\n const servers = this.sql<MCPServerRow>`\n SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;\n `;\n\n if (servers && Array.isArray(servers) && servers.length > 0) {\n for (const server of servers) {\n const serverConn = this.mcp.mcpConnections[server.id];\n mcpState.servers[server.id] = {\n auth_url: server.auth_url,\n capabilities: serverConn?.serverCapabilities ?? null,\n instructions: serverConn?.instructions ?? null,\n name: server.name,\n server_url: server.server_url,\n // mark as \"authenticating\" because the server isn't automatically connected, so it's pending authenticating\n state: serverConn?.connectionState ?? \"authenticating\"\n };\n }\n }\n\n return mcpState;\n }\n}\n\n/**\n * Namespace for creating Agent instances\n * @template Agentic Type of the Agent class\n */\nexport type AgentNamespace<Agentic extends Agent<unknown>> =\n DurableObjectNamespace<Agentic>;\n\n/**\n * Agent's durable context\n */\nexport type AgentContext = DurableObjectState;\n\n/**\n * Configuration options for Agent routing\n */\nexport type AgentOptions<Env> = PartyServerOptions<Env> & {\n /**\n * Whether to enable CORS for the Agent\n */\n cors?: boolean | HeadersInit | undefined;\n};\n\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 */\nexport async function routeAgentRequest<Env>(\n request: Request,\n env: Env,\n options?: AgentOptions<Env>\n) {\n const corsHeaders =\n options?.cors === true\n ? {\n \"Access-Control-Allow-Credentials\": \"true\",\n \"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Max-Age\": \"86400\"\n }\n : options?.cors;\n\n if (request.method === \"OPTIONS\") {\n if (corsHeaders) {\n return new Response(null, {\n headers: corsHeaders\n });\n }\n console.warn(\n \"Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.\"\n );\n }\n\n let response = await routePartykitRequest(\n request,\n env as Record<string, unknown>,\n {\n prefix: \"agents\",\n ...(options as PartyServerOptions<Record<string, unknown>>)\n }\n );\n\n if (\n response &&\n corsHeaders &&\n request.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\" &&\n request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\"\n ) {\n response = new Response(response.body, {\n headers: {\n ...response.headers,\n ...corsHeaders\n }\n });\n }\n return response;\n}\n\nexport type EmailResolver<Env> = (\n email: ForwardableEmailMessage,\n env: Env\n) => Promise<{\n agentName: string;\n agentId: string;\n} | null>;\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 */\nexport function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {\n return async (email: ForwardableEmailMessage, _env: Env) => {\n const messageId = email.headers.get(\"message-id\");\n if (messageId) {\n const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);\n if (messageIdMatch) {\n const [, agentId, domain] = messageIdMatch;\n const agentName = domain.split(\".\")[0];\n return { agentName, agentId };\n }\n }\n\n const references = email.headers.get(\"references\");\n if (references) {\n const referencesMatch = references.match(\n /<([A-Za-z0-9+/]{43}=)@([^>]+)>/\n );\n if (referencesMatch) {\n const [, base64Id, domain] = referencesMatch;\n const agentId = Buffer.from(base64Id, \"base64\").toString(\"hex\");\n const agentName = domain.split(\".\")[0];\n return { agentName, agentId };\n }\n }\n\n const agentName = email.headers.get(\"x-agent-name\");\n const agentId = email.headers.get(\"x-agent-id\");\n if (agentName && agentId) {\n return { agentName, agentId };\n }\n\n return null;\n };\n}\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 */\nexport function createAddressBasedEmailResolver<Env>(\n defaultAgentName: string\n): EmailResolver<Env> {\n return async (email: ForwardableEmailMessage, _env: Env) => {\n const emailMatch = email.to.match(/^([^+@]+)(?:\\+([^@]+))?@(.+)$/);\n if (!emailMatch) {\n return null;\n }\n\n const [, localPart, subAddress] = emailMatch;\n\n if (subAddress) {\n return {\n agentName: localPart,\n agentId: subAddress\n };\n }\n\n // Option 2: Use defaultAgentName namespace, localPart as agentId\n // Common for catch-all email routing to a single EmailAgent namespace\n return {\n agentName: defaultAgentName,\n agentId: localPart\n };\n };\n}\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 */\nexport function createCatchAllEmailResolver<Env>(\n agentName: string,\n agentId: string\n): EmailResolver<Env> {\n return async () => ({ agentName, agentId });\n}\n\nexport type EmailRoutingOptions<Env> = AgentOptions<Env> & {\n resolver: EmailResolver<Env>;\n};\n\n// Cache the agent namespace map for email routing\n// This maps both kebab-case and original names to namespaces\nconst agentMapCache = new WeakMap<\n Record<string, unknown>,\n Record<string, unknown>\n>();\n\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 */\nexport async function routeAgentEmail<Env>(\n email: ForwardableEmailMessage,\n env: Env,\n options: EmailRoutingOptions<Env>\n): Promise<void> {\n const routingInfo = await options.resolver(email, env);\n\n if (!routingInfo) {\n console.warn(\"No routing information found for email, dropping message\");\n return;\n }\n\n // Build a map that includes both original names and kebab-case versions\n if (!agentMapCache.has(env as Record<string, unknown>)) {\n const map: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(env as Record<string, unknown>)) {\n if (\n value &&\n typeof value === \"object\" &&\n \"idFromName\" in value &&\n typeof value.idFromName === \"function\"\n ) {\n // Add both the original name and kebab-case version\n map[key] = value;\n map[camelCaseToKebabCase(key)] = value;\n }\n }\n agentMapCache.set(env as Record<string, unknown>, map);\n }\n\n const agentMap = agentMapCache.get(env as Record<string, unknown>)!;\n const namespace = agentMap[routingInfo.agentName];\n\n if (!namespace) {\n // Provide helpful error message listing available agents\n const availableAgents = Object.keys(agentMap)\n .filter((key) => !key.includes(\"-\")) // Show only original names, not kebab-case duplicates\n .join(\", \");\n throw new Error(\n `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`\n );\n }\n\n const agent = await getAgentByName(\n namespace as unknown as AgentNamespace<Agent<Env>>,\n routingInfo.agentId\n );\n\n // let's make a serialisable version of the email\n const serialisableEmail: AgentEmail = {\n getRaw: async () => {\n const reader = email.raw.getReader();\n const chunks: Uint8Array[] = [];\n\n let done = false;\n while (!done) {\n const { value, done: readerDone } = await reader.read();\n done = readerDone;\n if (value) {\n chunks.push(value);\n }\n }\n\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const combined = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n combined.set(chunk, offset);\n offset += chunk.length;\n }\n\n return combined;\n },\n headers: email.headers,\n rawSize: email.rawSize,\n setReject: (reason: string) => {\n email.setReject(reason);\n },\n forward: (rcptTo: string, headers?: Headers) => {\n return email.forward(rcptTo, headers);\n },\n reply: (options: { from: string; to: string; raw: string }) => {\n return email.reply(\n new EmailMessage(options.from, options.to, options.raw)\n );\n },\n from: email.from,\n to: email.to\n };\n\n await agent._onEmail(serialisableEmail);\n}\n\nexport type AgentEmail = {\n from: string;\n to: string;\n getRaw: () => Promise<Uint8Array>;\n headers: Headers;\n rawSize: number;\n setReject: (reason: string) => void;\n forward: (rcptTo: string, headers?: Headers) => Promise<void>;\n reply: (options: { from: string; to: string; raw: string }) => Promise<void>;\n};\n\nexport type EmailSendOptions = {\n to: string;\n subject: string;\n body: string;\n contentType?: string;\n headers?: Record<string, string>;\n includeRoutingHeaders?: boolean;\n agentName?: string;\n agentId?: string;\n domain?: string;\n};\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 */\nexport async function getAgentByName<Env, T extends Agent<Env>>(\n namespace: AgentNamespace<T>,\n name: string,\n options?: {\n jurisdiction?: DurableObjectJurisdiction;\n locationHint?: DurableObjectLocationHint;\n }\n) {\n return getServerByName<Env, T>(namespace, name, options);\n}\n\n/**\n * A wrapper for streaming responses in callable methods\n */\nexport class StreamingResponse {\n private _connection: Connection;\n private _id: string;\n private _closed = false;\n\n constructor(connection: Connection, id: string) {\n this._connection = connection;\n this._id = id;\n }\n\n /**\n * Send a chunk of data to the client\n * @param chunk The data to send\n */\n send(chunk: unknown) {\n if (this._closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n const response: RPCResponse = {\n done: false,\n id: this._id,\n result: chunk,\n success: true,\n type: \"rpc\"\n };\n this._connection.send(JSON.stringify(response));\n }\n\n /**\n * End the stream and send the final chunk (if any)\n * @param finalChunk Optional final chunk of data to send\n */\n end(finalChunk?: unknown) {\n if (this._closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n this._closed = true;\n const response: RPCResponse = {\n done: true,\n id: this._id,\n result: finalChunk,\n success: true,\n type: \"rpc\"\n };\n this._connection.send(JSON.stringify(response));\n }\n}\n","import type { Message } from \"ai\";\nimport type { Schedule } from \"../index\";\nimport { getCurrentAgent } from \"../index\";\n\ntype BaseEvent<\n T extends string,\n Payload extends Record<string, unknown> = {}\n> = {\n type: T;\n /**\n * The unique identifier for the event\n */\n id: string;\n /**\n * The message to display in the logs for this event, should the implementation choose to display\n * a human-readable message.\n */\n displayMessage: string;\n /**\n * The payload of the event\n */\n payload: Payload;\n /**\n * The timestamp of the event in milliseconds since epoch\n */\n timestamp: number;\n};\n\n/**\n * The type of events that can be emitted by an Agent\n */\nexport type ObservabilityEvent =\n | BaseEvent<\n \"state:update\",\n {\n state: unknown;\n previousState: unknown;\n }\n >\n | BaseEvent<\n \"rpc\",\n {\n method: string;\n args: unknown[];\n streaming?: boolean;\n success: boolean;\n }\n >\n | BaseEvent<\n \"message:request\" | \"message:response\",\n {\n message: Message[];\n }\n >\n | BaseEvent<\"message:clear\">\n | BaseEvent<\n \"schedule:create\" | \"schedule:execute\" | \"schedule:cancel\",\n Schedule<unknown>\n >\n | BaseEvent<\"destroy\">\n | BaseEvent<\n \"connect\",\n {\n connectionId: string;\n }\n >;\n\nexport interface Observability {\n /**\n * Emit an event for the Agent's observability implementation to handle.\n * @param event - The event to emit\n * @param ctx - The execution context of the invocation\n */\n emit(event: ObservabilityEvent, ctx: DurableObjectState): void;\n}\n\n/**\n * A generic observability implementation that logs events to the console.\n */\nexport const genericObservability: Observability = {\n emit(event) {\n // In local mode, we display a pretty-print version of the event for easier debugging.\n if (isLocalMode()) {\n console.log(event.displayMessage);\n return;\n }\n\n console.log(event);\n }\n};\n\nlet localMode = false;\n\nfunction isLocalMode() {\n if (localMode) {\n return true;\n }\n const { request } = getCurrentAgent();\n if (!request) {\n return false;\n }\n\n const url = new URL(request.url);\n localMode = url.hostname === \"localhost\";\n return localMode;\n}\n"],"mappings":";;;;;;;;;;;AACA,SAAS,yBAAyB;AAUlC,SAAS,2BAA2B;AACpC,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B;AAAA,EAIE;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AAqDP,SAAS,aAAa,KAAiC;AACrD,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,SAAS,SACb,QAAQ,OACR,OAAO,IAAI,OAAO,YAClB,YAAY,OACZ,OAAO,IAAI,WAAW,YACtB,UAAU,OACV,MAAM,QAAS,IAAmB,IAAI;AAE1C;AAKA,SAAS,qBAAqB,KAAyC;AACrE,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,SAAS,oB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AACnB,QAAI,KAAK,SAAS;AAChB,YAAM,IAAI,MAAM,qCAAqC;AAAA,IACvD;AACA,UAAM,WAAwB;AAAA,MAC5B,MAAM;AAAA,MACN,IAAI,KAAK;AAAA,MACT,QAAQ;AAAA,MACR,SAAS;AAAA,MACT,MAAM;AAAA,IACR;AACA,SAAK,YAAY,KAAK,KAAK,UAAU,QAAQ,CAAC;AAAA,EAChD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,YAAsB;AACxB,QAAI,KAAK,SAAS;AAChB,YAAM,IAAI,MAAM,qCAAqC;AAAA,IACvD;AACA,SAAK,UAAU;AACf,UAAM,WAAwB;AAAA,MAC5B,MAAM;AAAA,MACN,IAAI,KAAK;AAAA,MACT,QAAQ;AAAA,MACR,SAAS;AAAA,MACT,MAAM;AAAA,IACR;AACA,SAAK,YAAY,KAAK,KAAK,UAAU,QAAQ,CAAC;AAAA,EAChD;AACF;;;ACvxDO,IAAM,uBAAsC;AAAA,EACjD,KAAK,OAAO;AAEV,QAAI,YAAY,GAAG;AACjB,cAAQ,IAAI,MAAM,cAAc;AAChC;AAAA,IACF;AAEA,YAAQ,IAAI,KAAK;AAAA,EACnB;AACF;AAEA,IAAI,YAAY;AAEhB,SAAS,cAAc;AACrB,MAAI,WAAW;AACb,WAAO;AAAA,EACT;AACA,QAAM,EAAE,QAAQ,IAAI,gBAAgB;AACpC,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,QAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;AAC/B,cAAY,IAAI,aAAa;AAC7B,SAAO;AACT;","names":["ctx","proto","url","agentId","agentName","options"]}
@@ -1,3 +1,4 @@
1
+ import { env } from "cloudflare:workers";
1
2
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
3
  import {
3
4
  ServerCapabilities,
@@ -217,7 +218,7 @@ declare function getCurrentAgent<
217
218
  * @template Env Environment type containing bindings
218
219
  * @template State State type to store within the Agent
219
220
  */
220
- declare class Agent<Env, State = unknown> extends Server<Env> {
221
+ declare class Agent<Env = typeof env, State = unknown> extends Server<Env> {
221
222
  private _state;
222
223
  private _ParentClass;
223
224
  mcp: MCPClientManager;
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import "cloudflare:workers";
1
2
  import "@modelcontextprotocol/sdk/client/index.js";
2
3
  import "@modelcontextprotocol/sdk/types.js";
3
4
  export { Connection, ConnectionContext, WSMessage } from "partyserver";
@@ -29,7 +30,7 @@ export {
29
30
  o as routeAgentEmail,
30
31
  r as routeAgentRequest,
31
32
  u as unstable_callable
32
- } from "./index-BIJvkfYt.js";
33
+ } from "./index-CLW1aEBr.js";
33
34
  import "zod";
34
35
  import "@modelcontextprotocol/sdk/shared/protocol.js";
35
36
  import "ai";
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  routeAgentEmail,
10
10
  routeAgentRequest,
11
11
  unstable_callable
12
- } from "./chunk-Z2OUUKK4.js";
12
+ } from "./chunk-3IQQY2UH.js";
13
13
  import "./chunk-UNG3FXYX.js";
14
14
  import "./chunk-PVQZBKN7.js";
15
15
  import "./chunk-KUH345EY.js";
package/dist/mcp/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  Agent
3
- } from "../chunk-Z2OUUKK4.js";
3
+ } from "../chunk-3IQQY2UH.js";
4
4
  import {
5
5
  SSEEdgeClientTransport,
6
6
  StreamableHTTPEdgeClientTransport
@@ -386,9 +386,14 @@ data: ${relativeUrlWithSession}
386
386
  await doStub._init(ctx.props);
387
387
  const upgradeUrl = new URL(request.url);
388
388
  upgradeUrl.pathname = "/sse";
389
+ const existingHeaders = {};
390
+ request.headers.forEach((value, key) => {
391
+ existingHeaders[key] = value;
392
+ });
389
393
  const response = await doStub.fetch(
390
394
  new Request(upgradeUrl, {
391
395
  headers: {
396
+ ...existingHeaders,
392
397
  Upgrade: "websocket",
393
398
  // Required by PartyServer
394
399
  "x-partykit-room": sessionId
@@ -667,9 +672,14 @@ data: ${JSON.stringify(result.data)}
667
672
  const encoder = new TextEncoder();
668
673
  const upgradeUrl = new URL(request.url);
669
674
  upgradeUrl.pathname = "/streamable-http";
675
+ const existingHeaders = {};
676
+ request.headers.forEach((value, key) => {
677
+ existingHeaders[key] = value;
678
+ });
670
679
  const response = await doStub.fetch(
671
680
  new Request(upgradeUrl, {
672
681
  headers: {
682
+ ...existingHeaders,
673
683
  Upgrade: "websocket",
674
684
  // Required by PartyServer
675
685
  "x-partykit-room": sessionId
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/index.ts"],"sourcesContent":["import { DurableObject } from \"cloudflare:workers\";\nimport type { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n InitializeRequestSchema,\n JSONRPCMessageSchema,\n isJSONRPCError,\n isJSONRPCNotification,\n isJSONRPCRequest,\n isJSONRPCResponse\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { Connection, WSMessage } from \"../\";\nimport { Agent } from \"../index\";\n\nconst MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024; // 4MB\n\n// CORS helper functions\nfunction corsHeaders(_request: Request, corsOptions: CORSOptions = {}) {\n const origin = \"*\";\n return {\n \"Access-Control-Allow-Headers\":\n corsOptions.headers ||\n \"Content-Type, mcp-session-id, mcp-protocol-version\",\n \"Access-Control-Allow-Methods\": corsOptions.methods || \"GET, POST, OPTIONS\",\n \"Access-Control-Allow-Origin\": corsOptions.origin || origin,\n \"Access-Control-Expose-Headers\":\n corsOptions.exposeHeaders || \"mcp-session-id\",\n \"Access-Control-Max-Age\": (corsOptions.maxAge || 86400).toString()\n };\n}\n\nfunction isDurableObjectNamespace(\n namespace: unknown\n): namespace is DurableObjectNamespace<McpAgent> {\n return (\n typeof namespace === \"object\" &&\n namespace !== null &&\n \"newUniqueId\" in namespace &&\n typeof namespace.newUniqueId === \"function\" &&\n \"idFromName\" in namespace &&\n typeof namespace.idFromName === \"function\"\n );\n}\n\nfunction handleCORS(\n request: Request,\n corsOptions?: CORSOptions\n): Response | null {\n if (request.method === \"OPTIONS\") {\n return new Response(null, { headers: corsHeaders(request, corsOptions) });\n }\n\n return null;\n}\n\ninterface CORSOptions {\n origin?: string;\n methods?: string;\n headers?: string;\n maxAge?: number;\n exposeHeaders?: string;\n}\n\nclass McpSSETransport implements Transport {\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage) => void;\n sessionId?: string;\n\n private _getWebSocket: () => WebSocket | null;\n private _started = false;\n constructor(getWebSocket: () => WebSocket | null) {\n this._getWebSocket = getWebSocket;\n }\n\n async start() {\n // The transport does not manage the WebSocket connection since it's terminated\n // by the Durable Object in order to allow hibernation. There's nothing to initialize.\n if (this._started) {\n throw new Error(\"Transport already started\");\n }\n this._started = true;\n }\n\n async send(message: JSONRPCMessage) {\n if (!this._started) {\n throw new Error(\"Transport not started\");\n }\n const websocket = this._getWebSocket();\n if (!websocket) {\n throw new Error(\"WebSocket not connected\");\n }\n try {\n websocket.send(JSON.stringify(message));\n } catch (error) {\n this.onerror?.(error as Error);\n throw error;\n }\n }\n\n async close() {\n // Similar to start, the only thing to do is to pass the event on to the server\n this.onclose?.();\n }\n}\n\ntype TransportType = \"sse\" | \"streamable-http\" | \"unset\";\n\nclass McpStreamableHttpTransport implements Transport {\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage) => void;\n sessionId?: string;\n\n // TODO: If there is an open connection to send server-initiated messages\n // back, we should use that connection\n private _getWebSocketForGetRequest: () => WebSocket | null;\n\n // Get the appropriate websocket connection for a given message id\n private _getWebSocketForMessageID: (id: string) => WebSocket | null;\n\n // Notify the server that a response has been sent for a given message id\n // so that it may clean up it's mapping of message ids to connections\n // once they are no longer needed\n private _notifyResponseIdSent: (id: string) => void;\n\n private _started = false;\n constructor(\n getWebSocketForMessageID: (id: string) => WebSocket | null,\n notifyResponseIdSent: (id: string | number) => void\n ) {\n this._getWebSocketForMessageID = getWebSocketForMessageID;\n this._notifyResponseIdSent = notifyResponseIdSent;\n // TODO\n this._getWebSocketForGetRequest = () => null;\n }\n\n async start() {\n // The transport does not manage the WebSocket connection since it's terminated\n // by the Durable Object in order to allow hibernation. There's nothing to initialize.\n if (this._started) {\n throw new Error(\"Transport already started\");\n }\n this._started = true;\n }\n\n async send(message: JSONRPCMessage) {\n if (!this._started) {\n throw new Error(\"Transport not started\");\n }\n\n let websocket: WebSocket | null = null;\n\n if (isJSONRPCResponse(message) || isJSONRPCError(message)) {\n websocket = this._getWebSocketForMessageID(message.id.toString());\n if (!websocket) {\n throw new Error(\n `Could not find WebSocket for message id: ${message.id}`\n );\n }\n } else if (isJSONRPCRequest(message)) {\n // requests originating from the server must be sent over the\n // the connection created by a GET request\n websocket = this._getWebSocketForGetRequest();\n } else if (isJSONRPCNotification(message)) {\n // notifications do not have an id\n // but do have a relatedRequestId field\n // so that they can be sent to the correct connection\n websocket = null;\n }\n\n try {\n websocket?.send(JSON.stringify(message));\n if (isJSONRPCResponse(message)) {\n this._notifyResponseIdSent(message.id.toString());\n }\n } catch (error) {\n this.onerror?.(error as Error);\n throw error;\n }\n }\n\n async close() {\n // Similar to start, the only thing to do is to pass the event on to the server\n this.onclose?.();\n }\n}\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport abstract class McpAgent<\n Env = unknown,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>\n> extends DurableObject<Env> {\n private _status: \"zero\" | \"starting\" | \"started\" = \"zero\";\n private _transport?: Transport;\n private _transportType: TransportType = \"unset\";\n private _requestIdToConnectionId: Map<string | number, string> = new Map();\n\n /**\n * Since McpAgent's _aren't_ yet real \"Agents\", let's only expose a couple of the methods\n * to the outer class: initialState/state/setState/onStateUpdate/sql\n */\n private _agent: Agent<Env, State>;\n\n get mcp() {\n return this._agent.mcp;\n }\n\n protected constructor(ctx: DurableObjectState, env: Env) {\n super(ctx, env);\n const self = this;\n\n this._agent = new (class extends Agent<Env, State> {\n static options = {\n hibernate: true\n };\n\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n return self.onStateUpdate(state, source);\n }\n\n async onMessage(\n connection: Connection,\n message: WSMessage\n ): Promise<void> {\n return self.onMessage(connection, message);\n }\n })(ctx, env);\n }\n\n /**\n * Agents API allowlist\n */\n initialState!: State;\n get state() {\n return this._agent.state;\n }\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ) {\n return this._agent.sql<T>(strings, ...values);\n }\n\n setState(state: State) {\n return this._agent.setState(state);\n }\n // biome-ignore lint/correctness/noUnusedFunctionParameters: overriden later\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates\n }\n async onStart() {\n const self = this;\n\n this._agent = new (class extends Agent<Env, State> {\n initialState: State = self.initialState;\n static options = {\n hibernate: true\n };\n\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n return self.onStateUpdate(state, source);\n }\n\n async onMessage(connection: Connection, event: WSMessage) {\n return self.onMessage(connection, event);\n }\n })(this.ctx, this.env);\n\n this.props = (await this.ctx.storage.get(\"props\")) as Props;\n this._transportType = (await this.ctx.storage.get(\n \"transportType\"\n )) as TransportType;\n await this._init(this.props);\n\n const server = await this.server;\n\n // Connect to the MCP server\n if (this._transportType === \"sse\") {\n this._transport = new McpSSETransport(() => this.getWebSocket());\n await server.connect(this._transport);\n } else if (this._transportType === \"streamable-http\") {\n this._transport = new McpStreamableHttpTransport(\n (id) => this.getWebSocketForResponseID(id),\n (id) => this._requestIdToConnectionId.delete(id)\n );\n await server.connect(this._transport);\n }\n }\n\n /**\n * McpAgent API\n */\n abstract server: MaybePromise<McpServer | Server>;\n props!: Props;\n initRun = false;\n\n abstract init(): Promise<void>;\n\n async _init(props: Props) {\n await this.ctx.storage.put(\"props\", props ?? {});\n if (!this.ctx.storage.get(\"transportType\")) {\n await this.ctx.storage.put(\"transportType\", \"unset\");\n }\n this.props = props;\n if (!this.initRun) {\n this.initRun = true;\n await this.init();\n }\n }\n\n async setInitialized() {\n await this.ctx.storage.put(\"initialized\", true);\n }\n\n async isInitialized() {\n return (await this.ctx.storage.get(\"initialized\")) === true;\n }\n\n private async _initialize(): Promise<void> {\n await this.ctx.blockConcurrencyWhile(async () => {\n this._status = \"starting\";\n await this.onStart();\n this._status = \"started\";\n });\n }\n\n // Allow the worker to fetch a websocket connection to the agent\n async fetch(request: Request): Promise<Response> {\n if (this._status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this._initialize();\n }\n\n // Only handle WebSocket upgrade requests\n if (request.headers.get(\"Upgrade\") !== \"websocket\") {\n return new Response(\"Expected WebSocket Upgrade request\", {\n status: 400\n });\n }\n\n // This request does not come from the user. The worker generates this\n // request to generate a websocket connection to the agent.\n const url = new URL(request.url);\n // This is not the path that the user requested, but the path that the worker\n // generated. We'll use this path to determine which transport to use.\n const path = url.pathname;\n const server = await this.server;\n\n switch (path) {\n case \"/sse\": {\n // For SSE connections, we can only have one open connection per session\n // If we get an upgrade while already connected, we should error\n const websockets = this.ctx.getWebSockets();\n if (websockets.length > 0) {\n return new Response(\"Websocket already connected\", { status: 400 });\n }\n\n // This session must always use the SSE transporo\n await this.ctx.storage.put(\"transportType\", \"sse\");\n this._transportType = \"sse\";\n\n if (!this._transport) {\n this._transport = new McpSSETransport(() => this.getWebSocket());\n await server.connect(this._transport);\n }\n\n // Defer to the Agent's fetch method to handle the WebSocket connection\n return this._agent.fetch(request);\n }\n case \"/streamable-http\": {\n if (!this._transport) {\n this._transport = new McpStreamableHttpTransport(\n (id) => this.getWebSocketForResponseID(id),\n (id) => this._requestIdToConnectionId.delete(id)\n );\n await server.connect(this._transport);\n }\n\n // This session must always use the streamable-http transport\n await this.ctx.storage.put(\"transportType\", \"streamable-http\");\n this._transportType = \"streamable-http\";\n\n return this._agent.fetch(request);\n }\n default:\n return new Response(\n \"Internal Server Error: Expected /sse or /streamable-http path\",\n {\n status: 500\n }\n );\n }\n }\n\n getWebSocket() {\n const websockets = this.ctx.getWebSockets();\n if (websockets.length === 0) {\n return null;\n }\n return websockets[0];\n }\n\n getWebSocketForResponseID(id: string): WebSocket | null {\n const connectionId = this._requestIdToConnectionId.get(id);\n if (connectionId === undefined) {\n return null;\n }\n return this._agent.getConnection(connectionId) ?? null;\n }\n\n // All messages received here. This is currently never called\n async onMessage(connection: Connection, event: WSMessage) {\n // Since we address the DO via both the protocol and the session id,\n // this should never happen, but let's enforce it just in case\n if (this._transportType !== \"streamable-http\") {\n const err = new Error(\n \"Internal Server Error: Expected streamable-http protocol\"\n );\n this._transport?.onerror?.(err);\n return;\n }\n\n let message: JSONRPCMessage;\n try {\n // Ensure event is a string\n const data =\n typeof event === \"string\" ? event : new TextDecoder().decode(event);\n message = JSONRPCMessageSchema.parse(JSON.parse(data));\n } catch (error) {\n this._transport?.onerror?.(error as Error);\n return;\n }\n\n // We need to map every incoming message to the connection that it came in on\n // so that we can send relevant responses and notifications back on the same connection\n if (isJSONRPCRequest(message)) {\n this._requestIdToConnectionId.set(message.id.toString(), connection.id);\n }\n\n this._transport?.onmessage?.(message);\n }\n\n // All messages received over SSE after the initial connection has been established\n // will be passed here\n async onSSEMcpMessage(\n _sessionId: string,\n request: Request\n ): Promise<Error | null> {\n if (this._status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this._initialize();\n }\n\n // Since we address the DO via both the protocol and the session id,\n // this should never happen, but let's enforce it just in case\n if (this._transportType !== \"sse\") {\n return new Error(\"Internal Server Error: Expected SSE protocol\");\n }\n\n try {\n const message = await request.json();\n let parsedMessage: JSONRPCMessage;\n try {\n parsedMessage = JSONRPCMessageSchema.parse(message);\n } catch (error) {\n this._transport?.onerror?.(error as Error);\n throw error;\n }\n\n this._transport?.onmessage?.(parsedMessage);\n return null;\n } catch (error) {\n console.error(\"Error forwarding message to SSE:\", error);\n this._transport?.onerror?.(error as Error);\n return error as Error;\n }\n }\n\n // Delegate all websocket events to the underlying agent\n async webSocketMessage(\n ws: WebSocket,\n event: ArrayBuffer | string\n ): Promise<void> {\n if (this._status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this._initialize();\n }\n return await this._agent.webSocketMessage(ws, event);\n }\n\n // WebSocket event handlers for hibernation support\n async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n if (this._status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this._initialize();\n }\n return await this._agent.webSocketError(ws, error);\n }\n\n async webSocketClose(\n ws: WebSocket,\n code: number,\n reason: string,\n wasClean: boolean\n ): Promise<void> {\n if (this._status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this._initialize();\n }\n return await this._agent.webSocketClose(ws, code, reason, wasClean);\n }\n\n static mount(\n path: string,\n {\n binding = \"MCP_OBJECT\",\n corsOptions\n }: {\n binding?: string;\n corsOptions?: CORSOptions;\n } = {}\n ) {\n return McpAgent.serveSSE(path, { binding, corsOptions });\n }\n\n static serveSSE(\n path: string,\n {\n binding = \"MCP_OBJECT\",\n corsOptions\n }: {\n binding?: string;\n corsOptions?: CORSOptions;\n } = {}\n ) {\n let pathname = path;\n if (path === \"/\") {\n pathname = \"/*\";\n }\n const basePattern = new URLPattern({ pathname });\n const messagePattern = new URLPattern({ pathname: `${pathname}/message` });\n\n return {\n async fetch<Env>(\n this: void,\n request: Request,\n env: Env,\n ctx: ExecutionContext\n ): Promise<Response> {\n // Handle CORS preflight\n const corsResponse = handleCORS(request, corsOptions);\n if (corsResponse) return corsResponse;\n\n const url = new URL(request.url);\n const bindingValue = env[binding as keyof typeof env] as unknown;\n\n // Ensure we have a binding of some sort\n if (bindingValue == null || typeof bindingValue !== \"object\") {\n console.error(\n `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`\n );\n return new Response(\"Invalid binding\", { status: 500 });\n }\n\n // Ensure that the binding is to a DurableObject\n if (!isDurableObjectNamespace(bindingValue)) {\n return new Response(\"Invalid binding\", { status: 500 });\n }\n\n const namespace =\n bindingValue satisfies DurableObjectNamespace<McpAgent>;\n\n // Handle initial SSE connection\n if (request.method === \"GET\" && basePattern.test(url)) {\n // Use a session ID if one is passed in, or create a unique\n // session ID for this connection\n const sessionId =\n url.searchParams.get(\"sessionId\") ||\n namespace.newUniqueId().toString();\n\n // Create a Transform Stream for SSE\n const { readable, writable } = new TransformStream();\n const writer = writable.getWriter();\n const encoder = new TextEncoder();\n\n // Send the endpoint event\n const endpointUrl = new URL(request.url);\n endpointUrl.pathname = encodeURI(`${pathname}/message`);\n endpointUrl.searchParams.set(\"sessionId\", sessionId);\n const relativeUrlWithSession =\n endpointUrl.pathname + endpointUrl.search + endpointUrl.hash;\n const endpointMessage = `event: endpoint\\ndata: ${relativeUrlWithSession}\\n\\n`;\n writer.write(encoder.encode(endpointMessage));\n\n // Get the Durable Object\n const id = namespace.idFromName(`sse:${sessionId}`);\n const doStub = namespace.get(id);\n\n // Initialize the object\n await doStub._init(ctx.props);\n\n // Connect to the Durable Object via WebSocket\n const upgradeUrl = new URL(request.url);\n // enforce that the path that the DO receives is always /sse\n upgradeUrl.pathname = \"/sse\";\n const response = await doStub.fetch(\n new Request(upgradeUrl, {\n headers: {\n Upgrade: \"websocket\",\n // Required by PartyServer\n \"x-partykit-room\": sessionId\n }\n })\n );\n\n // Get the WebSocket\n const ws = response.webSocket;\n if (!ws) {\n console.error(\"Failed to establish WebSocket connection\");\n await writer.close();\n return new Response(\"Failed to establish WebSocket connection\", {\n status: 500\n });\n }\n\n // Accept the WebSocket\n ws.accept();\n\n // Handle messages from the Durable Object\n ws.addEventListener(\"message\", (event) => {\n async function onMessage(event: MessageEvent) {\n try {\n const message = JSON.parse(event.data);\n\n // validate that the message is a valid JSONRPC message\n const result = JSONRPCMessageSchema.safeParse(message);\n if (!result.success) {\n // The message was not a valid JSONRPC message, so we will drop it\n // PartyKit will broadcast state change messages to all connected clients\n // and we need to filter those out so they are not passed to MCP clients\n return;\n }\n\n // Send the message as an SSE event\n const messageText = `event: message\\ndata: ${JSON.stringify(result.data)}\\n\\n`;\n await writer.write(encoder.encode(messageText));\n } catch (error) {\n console.error(\"Error forwarding message to SSE:\", error);\n }\n }\n onMessage(event).catch(console.error);\n });\n\n // Handle WebSocket errors\n ws.addEventListener(\"error\", (error) => {\n async function onError(_error: Event) {\n try {\n await writer.close();\n } catch (_e) {\n // Ignore errors when closing\n }\n }\n onError(error).catch(console.error);\n });\n\n // Handle WebSocket closure\n ws.addEventListener(\"close\", () => {\n async function onClose() {\n try {\n await writer.close();\n } catch (error) {\n console.error(\"Error closing SSE connection:\", error);\n }\n }\n onClose().catch(console.error);\n });\n\n // Return the SSE response\n return new Response(readable, {\n headers: {\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Content-Type\": \"text/event-stream\",\n ...corsHeaders(request, corsOptions)\n }\n });\n }\n\n // Handle incoming MCP messages. These will be passed to McpAgent\n // but the response will be sent back via the open SSE connection\n // so we only need to return a 202 Accepted response for success\n if (request.method === \"POST\" && messagePattern.test(url)) {\n const sessionId = url.searchParams.get(\"sessionId\");\n if (!sessionId) {\n return new Response(\n `Missing sessionId. Expected POST to ${pathname} to initiate new one`,\n { status: 400 }\n );\n }\n\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (!contentType.includes(\"application/json\")) {\n return new Response(`Unsupported content-type: ${contentType}`, {\n status: 400\n });\n }\n\n // check if the request body is too large\n const contentLength = Number.parseInt(\n request.headers.get(\"content-length\") || \"0\",\n 10\n );\n if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {\n return new Response(\n `Request body too large: ${contentLength} bytes`,\n {\n status: 400\n }\n );\n }\n\n // Get the Durable Object\n const id = namespace.idFromName(`sse:${sessionId}`);\n const doStub = namespace.get(id);\n\n // Forward the request to the Durable Object\n const error = await doStub.onSSEMcpMessage(sessionId, request);\n\n if (error) {\n return new Response(error.message, {\n headers: {\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Content-Type\": \"text/event-stream\",\n ...corsHeaders(request, corsOptions)\n },\n status: 400\n });\n }\n\n return new Response(\"Accepted\", {\n headers: {\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Content-Type\": \"text/event-stream\",\n ...corsHeaders(request, corsOptions)\n },\n status: 202\n });\n }\n\n return new Response(\"Not Found\", { status: 404 });\n }\n };\n }\n\n static serve(\n path: string,\n {\n binding = \"MCP_OBJECT\",\n corsOptions\n }: { binding?: string; corsOptions?: CORSOptions } = {}\n ) {\n let pathname = path;\n if (path === \"/\") {\n pathname = \"/*\";\n }\n const basePattern = new URLPattern({ pathname });\n\n return {\n async fetch<Env>(\n this: void,\n request: Request,\n env: Env,\n ctx: ExecutionContext\n ): Promise<Response> {\n // Handle CORS preflight\n const corsResponse = handleCORS(request, corsOptions);\n if (corsResponse) {\n return corsResponse;\n }\n\n const url = new URL(request.url);\n const bindingValue = env[binding as keyof typeof env] as unknown;\n\n // Ensure we have a binding of some sort\n if (bindingValue == null || typeof bindingValue !== \"object\") {\n console.error(\n `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`\n );\n return new Response(\"Invalid binding\", { status: 500 });\n }\n\n // Ensure that the binding is to a DurableObject\n if (!isDurableObjectNamespace(bindingValue)) {\n return new Response(\"Invalid binding\", { status: 500 });\n }\n\n const namespace =\n bindingValue satisfies DurableObjectNamespace<McpAgent>;\n\n if (request.method === \"POST\" && basePattern.test(url)) {\n // validate the Accept header\n const acceptHeader = request.headers.get(\"accept\");\n // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types.\n if (\n !acceptHeader?.includes(\"application/json\") ||\n !acceptHeader.includes(\"text/event-stream\")\n ) {\n const body = JSON.stringify({\n error: {\n code: -32000,\n message:\n \"Not Acceptable: Client must accept both application/json and text/event-stream\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 406 });\n }\n\n const ct = request.headers.get(\"content-type\");\n if (!ct || !ct.includes(\"application/json\")) {\n const body = JSON.stringify({\n error: {\n code: -32000,\n message:\n \"Unsupported Media Type: Content-Type must be application/json\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 415 });\n }\n\n // Check content length against maximum allowed size\n const contentLength = Number.parseInt(\n request.headers.get(\"content-length\") ?? \"0\",\n 10\n );\n if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {\n const body = JSON.stringify({\n error: {\n code: -32000,\n message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 413 });\n }\n\n let sessionId = request.headers.get(\"mcp-session-id\");\n let rawMessage: unknown;\n\n try {\n rawMessage = await request.json();\n } catch (_error) {\n const body = JSON.stringify({\n error: {\n code: -32700,\n message: \"Parse error: Invalid JSON\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 400 });\n }\n\n // Make sure the message is an array to simplify logic\n let arrayMessage: unknown[];\n if (Array.isArray(rawMessage)) {\n arrayMessage = rawMessage;\n } else {\n arrayMessage = [rawMessage];\n }\n\n let messages: JSONRPCMessage[] = [];\n\n // Try to parse each message as JSON RPC. Fail if any message is invalid\n for (const msg of arrayMessage) {\n if (!JSONRPCMessageSchema.safeParse(msg).success) {\n const body = JSON.stringify({\n error: {\n code: -32700,\n message: \"Parse error: Invalid JSON-RPC message\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 400 });\n }\n }\n\n messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));\n\n // Before we pass the messages to the agent, there's another error condition we need to enforce\n // Check if this is an initialization request\n // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/\n const isInitializationRequest = messages.some(\n (msg) => InitializeRequestSchema.safeParse(msg).success\n );\n\n if (isInitializationRequest && sessionId) {\n const body = JSON.stringify({\n error: {\n code: -32600,\n message:\n \"Invalid Request: Initialization requests must not include a sessionId\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 400 });\n }\n\n // The initialization request must be the only request in the batch\n if (isInitializationRequest && messages.length > 1) {\n const body = JSON.stringify({\n error: {\n code: -32600,\n message:\n \"Invalid Request: Only one initialization request is allowed\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 400 });\n }\n\n // If an Mcp-Session-Id is returned by the server during initialization,\n // clients using the Streamable HTTP transport MUST include it\n // in the Mcp-Session-Id header on all of their subsequent HTTP requests.\n if (!isInitializationRequest && !sessionId) {\n const body = JSON.stringify({\n error: {\n code: -32000,\n message: \"Bad Request: Mcp-Session-Id header is required\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 400 });\n }\n\n // If we don't have a sessionId, we are serving an initialization request\n // and need to generate a new sessionId\n sessionId = sessionId ?? namespace.newUniqueId().toString();\n\n // fetch the agent DO\n const id = namespace.idFromName(`streamable-http:${sessionId}`);\n const doStub = namespace.get(id);\n const isInitialized = await doStub.isInitialized();\n\n if (isInitializationRequest) {\n await doStub._init(ctx.props);\n await doStub.setInitialized();\n } else if (!isInitialized) {\n // if we have gotten here, then a session id that was never initialized\n // was provided\n const body = JSON.stringify({\n error: {\n code: -32001,\n message: \"Session not found\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 404 });\n }\n\n // We've evaluated all the error conditions! Now it's time to establish\n // all the streams\n\n // Create a Transform Stream for SSE\n const { readable, writable } = new TransformStream();\n const writer = writable.getWriter();\n const encoder = new TextEncoder();\n\n // Connect to the Durable Object via WebSocket\n const upgradeUrl = new URL(request.url);\n upgradeUrl.pathname = \"/streamable-http\";\n const response = await doStub.fetch(\n new Request(upgradeUrl, {\n headers: {\n Upgrade: \"websocket\",\n // Required by PartyServer\n \"x-partykit-room\": sessionId\n }\n })\n );\n\n // Get the WebSocket\n const ws = response.webSocket;\n if (!ws) {\n console.error(\"Failed to establish WebSocket connection\");\n\n await writer.close();\n const body = JSON.stringify({\n error: {\n code: -32001,\n message: \"Failed to establish WebSocket connection\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 500 });\n }\n\n // Keep track of the request ids that we have sent to the server\n // so that we can close the connection once we have received\n // all the responses\n const requestIds: Set<string | number> = new Set();\n\n // Accept the WebSocket\n ws.accept();\n\n // Handle messages from the Durable Object\n ws.addEventListener(\"message\", (event) => {\n async function onMessage(event: MessageEvent) {\n try {\n const data =\n typeof event.data === \"string\"\n ? event.data\n : new TextDecoder().decode(event.data);\n const message = JSON.parse(data);\n\n // validate that the message is a valid JSONRPC message\n const result = JSONRPCMessageSchema.safeParse(message);\n if (!result.success) {\n // The message was not a valid JSONRPC message, so we will drop it\n // PartyKit will broadcast state change messages to all connected clients\n // and we need to filter those out so they are not passed to MCP clients\n return;\n }\n\n // If the message is a response or an error, remove the id from the set of\n // request ids\n if (\n isJSONRPCResponse(result.data) ||\n isJSONRPCError(result.data)\n ) {\n requestIds.delete(result.data.id);\n }\n\n // Send the message as an SSE event\n const messageText = `event: message\\ndata: ${JSON.stringify(result.data)}\\n\\n`;\n await writer.write(encoder.encode(messageText));\n\n // If we have received all the responses, close the connection\n if (requestIds.size === 0) {\n ws!.close();\n }\n } catch (error) {\n console.error(\"Error forwarding message to SSE:\", error);\n }\n }\n onMessage(event).catch(console.error);\n });\n\n // Handle WebSocket errors\n ws.addEventListener(\"error\", (error) => {\n async function onError(_error: Event) {\n try {\n await writer.close();\n } catch (_e) {\n // Ignore errors when closing\n }\n }\n onError(error).catch(console.error);\n });\n\n // Handle WebSocket closure\n ws.addEventListener(\"close\", () => {\n async function onClose() {\n try {\n await writer.close();\n } catch (error) {\n console.error(\"Error closing SSE connection:\", error);\n }\n }\n onClose().catch(console.error);\n });\n\n // If there are no requests, we send the messages to the agent and acknowledge the request with a 202\n // since we don't expect any responses back through this connection\n const hasOnlyNotificationsOrResponses = messages.every(\n (msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)\n );\n if (hasOnlyNotificationsOrResponses) {\n for (const message of messages) {\n ws.send(JSON.stringify(message));\n }\n\n // closing the websocket will also close the SSE connection\n ws.close();\n\n return new Response(null, {\n headers: corsHeaders(request, corsOptions),\n status: 202\n });\n }\n\n for (const message of messages) {\n if (isJSONRPCRequest(message)) {\n // add each request id that we send off to a set\n // so that we can keep track of which requests we\n // still need a response for\n requestIds.add(message.id);\n }\n ws.send(JSON.stringify(message));\n }\n\n // Return the SSE response. We handle closing the stream in the ws \"message\"\n // handler\n return new Response(readable, {\n headers: {\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Content-Type\": \"text/event-stream\",\n \"mcp-session-id\": sessionId,\n ...corsHeaders(request, corsOptions)\n },\n status: 200\n });\n }\n\n // We don't yet support GET or DELETE requests\n const body = JSON.stringify({\n error: {\n code: -32000,\n message: \"Method not allowed\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 405 });\n }\n };\n }\n}\n\n// Export client transport classes\nexport { SSEEdgeClientTransport } from \"./sse-edge\";\nexport { StreamableHTTPEdgeClientTransport } from \"./streamable-http-edge\";\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,qBAAqB;AAK9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAIP,IAAM,6BAA6B,IAAI,OAAO;AAG9C,SAAS,YAAY,UAAmB,cAA2B,CAAC,GAAG;AACrE,QAAM,SAAS;AACf,SAAO;AAAA,IACL,gCACE,YAAY,WACZ;AAAA,IACF,gCAAgC,YAAY,WAAW;AAAA,IACvD,+BAA+B,YAAY,UAAU;AAAA,IACrD,iCACE,YAAY,iBAAiB;AAAA,IAC/B,2BAA2B,YAAY,UAAU,OAAO,SAA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U;AAAA,YAC5B,SAAS;AAAA,cACP,iBAAiB;AAAA,cACjB,YAAY;AAAA,cACZ,gBAAgB;AAAA,cAChB,kBAAkB;AAAA,cAClB,GAAG,YAAY,SAAS,WAAW;AAAA,YACrC;AAAA,YACA,QAAQ;AAAA,UACV,CAAC;AAAA,QACH;AAGA,cAAM,OAAO,KAAK,UAAU;AAAA,UAC1B,OAAO;AAAA,YACL,MAAM;AAAA,YACN,SAAS;AAAA,UACX;AAAA,UACA,IAAI;AAAA,UACJ,SAAS;AAAA,QACX,CAAC;AACD,eAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;AAAA,MAC3C;AAAA,IACF;AAAA,EACF;AACF;","names":["event","body"]}
1
+ {"version":3,"sources":["../../src/mcp/index.ts"],"sourcesContent":["import { DurableObject } from \"cloudflare:workers\";\nimport type { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n InitializeRequestSchema,\n JSONRPCMessageSchema,\n isJSONRPCError,\n isJSONRPCNotification,\n isJSONRPCRequest,\n isJSONRPCResponse\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { Connection, WSMessage } from \"../\";\nimport { Agent } from \"../index\";\n\nconst MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024; // 4MB\n\n// CORS helper functions\nfunction corsHeaders(_request: Request, corsOptions: CORSOptions = {}) {\n const origin = \"*\";\n return {\n \"Access-Control-Allow-Headers\":\n corsOptions.headers ||\n \"Content-Type, mcp-session-id, mcp-protocol-version\",\n \"Access-Control-Allow-Methods\": corsOptions.methods || \"GET, POST, OPTIONS\",\n \"Access-Control-Allow-Origin\": corsOptions.origin || origin,\n \"Access-Control-Expose-Headers\":\n corsOptions.exposeHeaders || \"mcp-session-id\",\n \"Access-Control-Max-Age\": (corsOptions.maxAge || 86400).toString()\n };\n}\n\nfunction isDurableObjectNamespace(\n namespace: unknown\n): namespace is DurableObjectNamespace<McpAgent> {\n return (\n typeof namespace === \"object\" &&\n namespace !== null &&\n \"newUniqueId\" in namespace &&\n typeof namespace.newUniqueId === \"function\" &&\n \"idFromName\" in namespace &&\n typeof namespace.idFromName === \"function\"\n );\n}\n\nfunction handleCORS(\n request: Request,\n corsOptions?: CORSOptions\n): Response | null {\n if (request.method === \"OPTIONS\") {\n return new Response(null, { headers: corsHeaders(request, corsOptions) });\n }\n\n return null;\n}\n\ninterface CORSOptions {\n origin?: string;\n methods?: string;\n headers?: string;\n maxAge?: number;\n exposeHeaders?: string;\n}\n\nclass McpSSETransport implements Transport {\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage) => void;\n sessionId?: string;\n\n private _getWebSocket: () => WebSocket | null;\n private _started = false;\n constructor(getWebSocket: () => WebSocket | null) {\n this._getWebSocket = getWebSocket;\n }\n\n async start() {\n // The transport does not manage the WebSocket connection since it's terminated\n // by the Durable Object in order to allow hibernation. There's nothing to initialize.\n if (this._started) {\n throw new Error(\"Transport already started\");\n }\n this._started = true;\n }\n\n async send(message: JSONRPCMessage) {\n if (!this._started) {\n throw new Error(\"Transport not started\");\n }\n const websocket = this._getWebSocket();\n if (!websocket) {\n throw new Error(\"WebSocket not connected\");\n }\n try {\n websocket.send(JSON.stringify(message));\n } catch (error) {\n this.onerror?.(error as Error);\n throw error;\n }\n }\n\n async close() {\n // Similar to start, the only thing to do is to pass the event on to the server\n this.onclose?.();\n }\n}\n\ntype TransportType = \"sse\" | \"streamable-http\" | \"unset\";\n\nclass McpStreamableHttpTransport implements Transport {\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage) => void;\n sessionId?: string;\n\n // TODO: If there is an open connection to send server-initiated messages\n // back, we should use that connection\n private _getWebSocketForGetRequest: () => WebSocket | null;\n\n // Get the appropriate websocket connection for a given message id\n private _getWebSocketForMessageID: (id: string) => WebSocket | null;\n\n // Notify the server that a response has been sent for a given message id\n // so that it may clean up it's mapping of message ids to connections\n // once they are no longer needed\n private _notifyResponseIdSent: (id: string) => void;\n\n private _started = false;\n constructor(\n getWebSocketForMessageID: (id: string) => WebSocket | null,\n notifyResponseIdSent: (id: string | number) => void\n ) {\n this._getWebSocketForMessageID = getWebSocketForMessageID;\n this._notifyResponseIdSent = notifyResponseIdSent;\n // TODO\n this._getWebSocketForGetRequest = () => null;\n }\n\n async start() {\n // The transport does not manage the WebSocket connection since it's terminated\n // by the Durable Object in order to allow hibernation. There's nothing to initialize.\n if (this._started) {\n throw new Error(\"Transport already started\");\n }\n this._started = true;\n }\n\n async send(message: JSONRPCMessage) {\n if (!this._started) {\n throw new Error(\"Transport not started\");\n }\n\n let websocket: WebSocket | null = null;\n\n if (isJSONRPCResponse(message) || isJSONRPCError(message)) {\n websocket = this._getWebSocketForMessageID(message.id.toString());\n if (!websocket) {\n throw new Error(\n `Could not find WebSocket for message id: ${message.id}`\n );\n }\n } else if (isJSONRPCRequest(message)) {\n // requests originating from the server must be sent over the\n // the connection created by a GET request\n websocket = this._getWebSocketForGetRequest();\n } else if (isJSONRPCNotification(message)) {\n // notifications do not have an id\n // but do have a relatedRequestId field\n // so that they can be sent to the correct connection\n websocket = null;\n }\n\n try {\n websocket?.send(JSON.stringify(message));\n if (isJSONRPCResponse(message)) {\n this._notifyResponseIdSent(message.id.toString());\n }\n } catch (error) {\n this.onerror?.(error as Error);\n throw error;\n }\n }\n\n async close() {\n // Similar to start, the only thing to do is to pass the event on to the server\n this.onclose?.();\n }\n}\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport abstract class McpAgent<\n Env = unknown,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>\n> extends DurableObject<Env> {\n private _status: \"zero\" | \"starting\" | \"started\" = \"zero\";\n private _transport?: Transport;\n private _transportType: TransportType = \"unset\";\n private _requestIdToConnectionId: Map<string | number, string> = new Map();\n\n /**\n * Since McpAgent's _aren't_ yet real \"Agents\", let's only expose a couple of the methods\n * to the outer class: initialState/state/setState/onStateUpdate/sql\n */\n private _agent: Agent<Env, State>;\n\n get mcp() {\n return this._agent.mcp;\n }\n\n protected constructor(ctx: DurableObjectState, env: Env) {\n super(ctx, env);\n const self = this;\n\n this._agent = new (class extends Agent<Env, State> {\n static options = {\n hibernate: true\n };\n\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n return self.onStateUpdate(state, source);\n }\n\n async onMessage(\n connection: Connection,\n message: WSMessage\n ): Promise<void> {\n return self.onMessage(connection, message);\n }\n })(ctx, env);\n }\n\n /**\n * Agents API allowlist\n */\n initialState!: State;\n get state() {\n return this._agent.state;\n }\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ) {\n return this._agent.sql<T>(strings, ...values);\n }\n\n setState(state: State) {\n return this._agent.setState(state);\n }\n // biome-ignore lint/correctness/noUnusedFunctionParameters: overriden later\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates\n }\n async onStart() {\n const self = this;\n\n this._agent = new (class extends Agent<Env, State> {\n initialState: State = self.initialState;\n static options = {\n hibernate: true\n };\n\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n return self.onStateUpdate(state, source);\n }\n\n async onMessage(connection: Connection, event: WSMessage) {\n return self.onMessage(connection, event);\n }\n })(this.ctx, this.env);\n\n this.props = (await this.ctx.storage.get(\"props\")) as Props;\n this._transportType = (await this.ctx.storage.get(\n \"transportType\"\n )) as TransportType;\n await this._init(this.props);\n\n const server = await this.server;\n\n // Connect to the MCP server\n if (this._transportType === \"sse\") {\n this._transport = new McpSSETransport(() => this.getWebSocket());\n await server.connect(this._transport);\n } else if (this._transportType === \"streamable-http\") {\n this._transport = new McpStreamableHttpTransport(\n (id) => this.getWebSocketForResponseID(id),\n (id) => this._requestIdToConnectionId.delete(id)\n );\n await server.connect(this._transport);\n }\n }\n\n /**\n * McpAgent API\n */\n abstract server: MaybePromise<McpServer | Server>;\n props!: Props;\n initRun = false;\n\n abstract init(): Promise<void>;\n\n async _init(props: Props) {\n await this.ctx.storage.put(\"props\", props ?? {});\n if (!this.ctx.storage.get(\"transportType\")) {\n await this.ctx.storage.put(\"transportType\", \"unset\");\n }\n this.props = props;\n if (!this.initRun) {\n this.initRun = true;\n await this.init();\n }\n }\n\n async setInitialized() {\n await this.ctx.storage.put(\"initialized\", true);\n }\n\n async isInitialized() {\n return (await this.ctx.storage.get(\"initialized\")) === true;\n }\n\n private async _initialize(): Promise<void> {\n await this.ctx.blockConcurrencyWhile(async () => {\n this._status = \"starting\";\n await this.onStart();\n this._status = \"started\";\n });\n }\n\n // Allow the worker to fetch a websocket connection to the agent\n async fetch(request: Request): Promise<Response> {\n if (this._status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this._initialize();\n }\n\n // Only handle WebSocket upgrade requests\n if (request.headers.get(\"Upgrade\") !== \"websocket\") {\n return new Response(\"Expected WebSocket Upgrade request\", {\n status: 400\n });\n }\n\n // This request does not come from the user. The worker generates this\n // request to generate a websocket connection to the agent.\n const url = new URL(request.url);\n // This is not the path that the user requested, but the path that the worker\n // generated. We'll use this path to determine which transport to use.\n const path = url.pathname;\n const server = await this.server;\n\n switch (path) {\n case \"/sse\": {\n // For SSE connections, we can only have one open connection per session\n // If we get an upgrade while already connected, we should error\n const websockets = this.ctx.getWebSockets();\n if (websockets.length > 0) {\n return new Response(\"Websocket already connected\", { status: 400 });\n }\n\n // This session must always use the SSE transporo\n await this.ctx.storage.put(\"transportType\", \"sse\");\n this._transportType = \"sse\";\n\n if (!this._transport) {\n this._transport = new McpSSETransport(() => this.getWebSocket());\n await server.connect(this._transport);\n }\n\n // Defer to the Agent's fetch method to handle the WebSocket connection\n return this._agent.fetch(request);\n }\n case \"/streamable-http\": {\n if (!this._transport) {\n this._transport = new McpStreamableHttpTransport(\n (id) => this.getWebSocketForResponseID(id),\n (id) => this._requestIdToConnectionId.delete(id)\n );\n await server.connect(this._transport);\n }\n\n // This session must always use the streamable-http transport\n await this.ctx.storage.put(\"transportType\", \"streamable-http\");\n this._transportType = \"streamable-http\";\n\n return this._agent.fetch(request);\n }\n default:\n return new Response(\n \"Internal Server Error: Expected /sse or /streamable-http path\",\n {\n status: 500\n }\n );\n }\n }\n\n getWebSocket() {\n const websockets = this.ctx.getWebSockets();\n if (websockets.length === 0) {\n return null;\n }\n return websockets[0];\n }\n\n getWebSocketForResponseID(id: string): WebSocket | null {\n const connectionId = this._requestIdToConnectionId.get(id);\n if (connectionId === undefined) {\n return null;\n }\n return this._agent.getConnection(connectionId) ?? null;\n }\n\n // All messages received here. This is currently never called\n async onMessage(connection: Connection, event: WSMessage) {\n // Since we address the DO via both the protocol and the session id,\n // this should never happen, but let's enforce it just in case\n if (this._transportType !== \"streamable-http\") {\n const err = new Error(\n \"Internal Server Error: Expected streamable-http protocol\"\n );\n this._transport?.onerror?.(err);\n return;\n }\n\n let message: JSONRPCMessage;\n try {\n // Ensure event is a string\n const data =\n typeof event === \"string\" ? event : new TextDecoder().decode(event);\n message = JSONRPCMessageSchema.parse(JSON.parse(data));\n } catch (error) {\n this._transport?.onerror?.(error as Error);\n return;\n }\n\n // We need to map every incoming message to the connection that it came in on\n // so that we can send relevant responses and notifications back on the same connection\n if (isJSONRPCRequest(message)) {\n this._requestIdToConnectionId.set(message.id.toString(), connection.id);\n }\n\n this._transport?.onmessage?.(message);\n }\n\n // All messages received over SSE after the initial connection has been established\n // will be passed here\n async onSSEMcpMessage(\n _sessionId: string,\n request: Request\n ): Promise<Error | null> {\n if (this._status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this._initialize();\n }\n\n // Since we address the DO via both the protocol and the session id,\n // this should never happen, but let's enforce it just in case\n if (this._transportType !== \"sse\") {\n return new Error(\"Internal Server Error: Expected SSE protocol\");\n }\n\n try {\n const message = await request.json();\n let parsedMessage: JSONRPCMessage;\n try {\n parsedMessage = JSONRPCMessageSchema.parse(message);\n } catch (error) {\n this._transport?.onerror?.(error as Error);\n throw error;\n }\n\n this._transport?.onmessage?.(parsedMessage);\n return null;\n } catch (error) {\n console.error(\"Error forwarding message to SSE:\", error);\n this._transport?.onerror?.(error as Error);\n return error as Error;\n }\n }\n\n // Delegate all websocket events to the underlying agent\n async webSocketMessage(\n ws: WebSocket,\n event: ArrayBuffer | string\n ): Promise<void> {\n if (this._status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this._initialize();\n }\n return await this._agent.webSocketMessage(ws, event);\n }\n\n // WebSocket event handlers for hibernation support\n async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n if (this._status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this._initialize();\n }\n return await this._agent.webSocketError(ws, error);\n }\n\n async webSocketClose(\n ws: WebSocket,\n code: number,\n reason: string,\n wasClean: boolean\n ): Promise<void> {\n if (this._status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this._initialize();\n }\n return await this._agent.webSocketClose(ws, code, reason, wasClean);\n }\n\n static mount(\n path: string,\n {\n binding = \"MCP_OBJECT\",\n corsOptions\n }: {\n binding?: string;\n corsOptions?: CORSOptions;\n } = {}\n ) {\n return McpAgent.serveSSE(path, { binding, corsOptions });\n }\n\n static serveSSE(\n path: string,\n {\n binding = \"MCP_OBJECT\",\n corsOptions\n }: {\n binding?: string;\n corsOptions?: CORSOptions;\n } = {}\n ) {\n let pathname = path;\n if (path === \"/\") {\n pathname = \"/*\";\n }\n const basePattern = new URLPattern({ pathname });\n const messagePattern = new URLPattern({ pathname: `${pathname}/message` });\n\n return {\n async fetch<Env>(\n this: void,\n request: Request,\n env: Env,\n ctx: ExecutionContext\n ): Promise<Response> {\n // Handle CORS preflight\n const corsResponse = handleCORS(request, corsOptions);\n if (corsResponse) return corsResponse;\n\n const url = new URL(request.url);\n const bindingValue = env[binding as keyof typeof env] as unknown;\n\n // Ensure we have a binding of some sort\n if (bindingValue == null || typeof bindingValue !== \"object\") {\n console.error(\n `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`\n );\n return new Response(\"Invalid binding\", { status: 500 });\n }\n\n // Ensure that the binding is to a DurableObject\n if (!isDurableObjectNamespace(bindingValue)) {\n return new Response(\"Invalid binding\", { status: 500 });\n }\n\n const namespace =\n bindingValue satisfies DurableObjectNamespace<McpAgent>;\n\n // Handle initial SSE connection\n if (request.method === \"GET\" && basePattern.test(url)) {\n // Use a session ID if one is passed in, or create a unique\n // session ID for this connection\n const sessionId =\n url.searchParams.get(\"sessionId\") ||\n namespace.newUniqueId().toString();\n\n // Create a Transform Stream for SSE\n const { readable, writable } = new TransformStream();\n const writer = writable.getWriter();\n const encoder = new TextEncoder();\n\n // Send the endpoint event\n const endpointUrl = new URL(request.url);\n endpointUrl.pathname = encodeURI(`${pathname}/message`);\n endpointUrl.searchParams.set(\"sessionId\", sessionId);\n const relativeUrlWithSession =\n endpointUrl.pathname + endpointUrl.search + endpointUrl.hash;\n const endpointMessage = `event: endpoint\\ndata: ${relativeUrlWithSession}\\n\\n`;\n writer.write(encoder.encode(endpointMessage));\n\n // Get the Durable Object\n const id = namespace.idFromName(`sse:${sessionId}`);\n const doStub = namespace.get(id);\n\n // Initialize the object\n await doStub._init(ctx.props);\n\n // Connect to the Durable Object via WebSocket\n const upgradeUrl = new URL(request.url);\n // enforce that the path that the DO receives is always /sse\n upgradeUrl.pathname = \"/sse\";\n const existingHeaders: Record<string, string> = {};\n request.headers.forEach((value, key) => {\n existingHeaders[key] = value;\n });\n const response = await doStub.fetch(\n new Request(upgradeUrl, {\n headers: {\n ...existingHeaders,\n Upgrade: \"websocket\",\n // Required by PartyServer\n \"x-partykit-room\": sessionId\n }\n })\n );\n\n // Get the WebSocket\n const ws = response.webSocket;\n if (!ws) {\n console.error(\"Failed to establish WebSocket connection\");\n await writer.close();\n return new Response(\"Failed to establish WebSocket connection\", {\n status: 500\n });\n }\n\n // Accept the WebSocket\n ws.accept();\n\n // Handle messages from the Durable Object\n ws.addEventListener(\"message\", (event) => {\n async function onMessage(event: MessageEvent) {\n try {\n const message = JSON.parse(event.data);\n\n // validate that the message is a valid JSONRPC message\n const result = JSONRPCMessageSchema.safeParse(message);\n if (!result.success) {\n // The message was not a valid JSONRPC message, so we will drop it\n // PartyKit will broadcast state change messages to all connected clients\n // and we need to filter those out so they are not passed to MCP clients\n return;\n }\n\n // Send the message as an SSE event\n const messageText = `event: message\\ndata: ${JSON.stringify(result.data)}\\n\\n`;\n await writer.write(encoder.encode(messageText));\n } catch (error) {\n console.error(\"Error forwarding message to SSE:\", error);\n }\n }\n onMessage(event).catch(console.error);\n });\n\n // Handle WebSocket errors\n ws.addEventListener(\"error\", (error) => {\n async function onError(_error: Event) {\n try {\n await writer.close();\n } catch (_e) {\n // Ignore errors when closing\n }\n }\n onError(error).catch(console.error);\n });\n\n // Handle WebSocket closure\n ws.addEventListener(\"close\", () => {\n async function onClose() {\n try {\n await writer.close();\n } catch (error) {\n console.error(\"Error closing SSE connection:\", error);\n }\n }\n onClose().catch(console.error);\n });\n\n // Return the SSE response\n return new Response(readable, {\n headers: {\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Content-Type\": \"text/event-stream\",\n ...corsHeaders(request, corsOptions)\n }\n });\n }\n\n // Handle incoming MCP messages. These will be passed to McpAgent\n // but the response will be sent back via the open SSE connection\n // so we only need to return a 202 Accepted response for success\n if (request.method === \"POST\" && messagePattern.test(url)) {\n const sessionId = url.searchParams.get(\"sessionId\");\n if (!sessionId) {\n return new Response(\n `Missing sessionId. Expected POST to ${pathname} to initiate new one`,\n { status: 400 }\n );\n }\n\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (!contentType.includes(\"application/json\")) {\n return new Response(`Unsupported content-type: ${contentType}`, {\n status: 400\n });\n }\n\n // check if the request body is too large\n const contentLength = Number.parseInt(\n request.headers.get(\"content-length\") || \"0\",\n 10\n );\n if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {\n return new Response(\n `Request body too large: ${contentLength} bytes`,\n {\n status: 400\n }\n );\n }\n\n // Get the Durable Object\n const id = namespace.idFromName(`sse:${sessionId}`);\n const doStub = namespace.get(id);\n\n // Forward the request to the Durable Object\n const error = await doStub.onSSEMcpMessage(sessionId, request);\n\n if (error) {\n return new Response(error.message, {\n headers: {\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Content-Type\": \"text/event-stream\",\n ...corsHeaders(request, corsOptions)\n },\n status: 400\n });\n }\n\n return new Response(\"Accepted\", {\n headers: {\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Content-Type\": \"text/event-stream\",\n ...corsHeaders(request, corsOptions)\n },\n status: 202\n });\n }\n\n return new Response(\"Not Found\", { status: 404 });\n }\n };\n }\n\n static serve(\n path: string,\n {\n binding = \"MCP_OBJECT\",\n corsOptions\n }: { binding?: string; corsOptions?: CORSOptions } = {}\n ) {\n let pathname = path;\n if (path === \"/\") {\n pathname = \"/*\";\n }\n const basePattern = new URLPattern({ pathname });\n\n return {\n async fetch<Env>(\n this: void,\n request: Request,\n env: Env,\n ctx: ExecutionContext\n ): Promise<Response> {\n // Handle CORS preflight\n const corsResponse = handleCORS(request, corsOptions);\n if (corsResponse) {\n return corsResponse;\n }\n\n const url = new URL(request.url);\n const bindingValue = env[binding as keyof typeof env] as unknown;\n\n // Ensure we have a binding of some sort\n if (bindingValue == null || typeof bindingValue !== \"object\") {\n console.error(\n `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`\n );\n return new Response(\"Invalid binding\", { status: 500 });\n }\n\n // Ensure that the binding is to a DurableObject\n if (!isDurableObjectNamespace(bindingValue)) {\n return new Response(\"Invalid binding\", { status: 500 });\n }\n\n const namespace =\n bindingValue satisfies DurableObjectNamespace<McpAgent>;\n\n if (request.method === \"POST\" && basePattern.test(url)) {\n // validate the Accept header\n const acceptHeader = request.headers.get(\"accept\");\n // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types.\n if (\n !acceptHeader?.includes(\"application/json\") ||\n !acceptHeader.includes(\"text/event-stream\")\n ) {\n const body = JSON.stringify({\n error: {\n code: -32000,\n message:\n \"Not Acceptable: Client must accept both application/json and text/event-stream\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 406 });\n }\n\n const ct = request.headers.get(\"content-type\");\n if (!ct || !ct.includes(\"application/json\")) {\n const body = JSON.stringify({\n error: {\n code: -32000,\n message:\n \"Unsupported Media Type: Content-Type must be application/json\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 415 });\n }\n\n // Check content length against maximum allowed size\n const contentLength = Number.parseInt(\n request.headers.get(\"content-length\") ?? \"0\",\n 10\n );\n if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {\n const body = JSON.stringify({\n error: {\n code: -32000,\n message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 413 });\n }\n\n let sessionId = request.headers.get(\"mcp-session-id\");\n let rawMessage: unknown;\n\n try {\n rawMessage = await request.json();\n } catch (_error) {\n const body = JSON.stringify({\n error: {\n code: -32700,\n message: \"Parse error: Invalid JSON\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 400 });\n }\n\n // Make sure the message is an array to simplify logic\n let arrayMessage: unknown[];\n if (Array.isArray(rawMessage)) {\n arrayMessage = rawMessage;\n } else {\n arrayMessage = [rawMessage];\n }\n\n let messages: JSONRPCMessage[] = [];\n\n // Try to parse each message as JSON RPC. Fail if any message is invalid\n for (const msg of arrayMessage) {\n if (!JSONRPCMessageSchema.safeParse(msg).success) {\n const body = JSON.stringify({\n error: {\n code: -32700,\n message: \"Parse error: Invalid JSON-RPC message\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 400 });\n }\n }\n\n messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));\n\n // Before we pass the messages to the agent, there's another error condition we need to enforce\n // Check if this is an initialization request\n // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/\n const isInitializationRequest = messages.some(\n (msg) => InitializeRequestSchema.safeParse(msg).success\n );\n\n if (isInitializationRequest && sessionId) {\n const body = JSON.stringify({\n error: {\n code: -32600,\n message:\n \"Invalid Request: Initialization requests must not include a sessionId\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 400 });\n }\n\n // The initialization request must be the only request in the batch\n if (isInitializationRequest && messages.length > 1) {\n const body = JSON.stringify({\n error: {\n code: -32600,\n message:\n \"Invalid Request: Only one initialization request is allowed\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 400 });\n }\n\n // If an Mcp-Session-Id is returned by the server during initialization,\n // clients using the Streamable HTTP transport MUST include it\n // in the Mcp-Session-Id header on all of their subsequent HTTP requests.\n if (!isInitializationRequest && !sessionId) {\n const body = JSON.stringify({\n error: {\n code: -32000,\n message: \"Bad Request: Mcp-Session-Id header is required\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 400 });\n }\n\n // If we don't have a sessionId, we are serving an initialization request\n // and need to generate a new sessionId\n sessionId = sessionId ?? namespace.newUniqueId().toString();\n\n // fetch the agent DO\n const id = namespace.idFromName(`streamable-http:${sessionId}`);\n const doStub = namespace.get(id);\n const isInitialized = await doStub.isInitialized();\n\n if (isInitializationRequest) {\n await doStub._init(ctx.props);\n await doStub.setInitialized();\n } else if (!isInitialized) {\n // if we have gotten here, then a session id that was never initialized\n // was provided\n const body = JSON.stringify({\n error: {\n code: -32001,\n message: \"Session not found\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 404 });\n }\n\n // We've evaluated all the error conditions! Now it's time to establish\n // all the streams\n\n // Create a Transform Stream for SSE\n const { readable, writable } = new TransformStream();\n const writer = writable.getWriter();\n const encoder = new TextEncoder();\n\n // Connect to the Durable Object via WebSocket\n const upgradeUrl = new URL(request.url);\n upgradeUrl.pathname = \"/streamable-http\";\n const existingHeaders: Record<string, string> = {};\n request.headers.forEach((value, key) => {\n existingHeaders[key] = value;\n });\n const response = await doStub.fetch(\n new Request(upgradeUrl, {\n headers: {\n ...existingHeaders,\n Upgrade: \"websocket\",\n // Required by PartyServer\n \"x-partykit-room\": sessionId\n }\n })\n );\n\n // Get the WebSocket\n const ws = response.webSocket;\n if (!ws) {\n console.error(\"Failed to establish WebSocket connection\");\n\n await writer.close();\n const body = JSON.stringify({\n error: {\n code: -32001,\n message: \"Failed to establish WebSocket connection\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 500 });\n }\n\n // Keep track of the request ids that we have sent to the server\n // so that we can close the connection once we have received\n // all the responses\n const requestIds: Set<string | number> = new Set();\n\n // Accept the WebSocket\n ws.accept();\n\n // Handle messages from the Durable Object\n ws.addEventListener(\"message\", (event) => {\n async function onMessage(event: MessageEvent) {\n try {\n const data =\n typeof event.data === \"string\"\n ? event.data\n : new TextDecoder().decode(event.data);\n const message = JSON.parse(data);\n\n // validate that the message is a valid JSONRPC message\n const result = JSONRPCMessageSchema.safeParse(message);\n if (!result.success) {\n // The message was not a valid JSONRPC message, so we will drop it\n // PartyKit will broadcast state change messages to all connected clients\n // and we need to filter those out so they are not passed to MCP clients\n return;\n }\n\n // If the message is a response or an error, remove the id from the set of\n // request ids\n if (\n isJSONRPCResponse(result.data) ||\n isJSONRPCError(result.data)\n ) {\n requestIds.delete(result.data.id);\n }\n\n // Send the message as an SSE event\n const messageText = `event: message\\ndata: ${JSON.stringify(result.data)}\\n\\n`;\n await writer.write(encoder.encode(messageText));\n\n // If we have received all the responses, close the connection\n if (requestIds.size === 0) {\n ws!.close();\n }\n } catch (error) {\n console.error(\"Error forwarding message to SSE:\", error);\n }\n }\n onMessage(event).catch(console.error);\n });\n\n // Handle WebSocket errors\n ws.addEventListener(\"error\", (error) => {\n async function onError(_error: Event) {\n try {\n await writer.close();\n } catch (_e) {\n // Ignore errors when closing\n }\n }\n onError(error).catch(console.error);\n });\n\n // Handle WebSocket closure\n ws.addEventListener(\"close\", () => {\n async function onClose() {\n try {\n await writer.close();\n } catch (error) {\n console.error(\"Error closing SSE connection:\", error);\n }\n }\n onClose().catch(console.error);\n });\n\n // If there are no requests, we send the messages to the agent and acknowledge the request with a 202\n // since we don't expect any responses back through this connection\n const hasOnlyNotificationsOrResponses = messages.every(\n (msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)\n );\n if (hasOnlyNotificationsOrResponses) {\n for (const message of messages) {\n ws.send(JSON.stringify(message));\n }\n\n // closing the websocket will also close the SSE connection\n ws.close();\n\n return new Response(null, {\n headers: corsHeaders(request, corsOptions),\n status: 202\n });\n }\n\n for (const message of messages) {\n if (isJSONRPCRequest(message)) {\n // add each request id that we send off to a set\n // so that we can keep track of which requests we\n // still need a response for\n requestIds.add(message.id);\n }\n ws.send(JSON.stringify(message));\n }\n\n // Return the SSE response. We handle closing the stream in the ws \"message\"\n // handler\n return new Response(readable, {\n headers: {\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Content-Type\": \"text/event-stream\",\n \"mcp-session-id\": sessionId,\n ...corsHeaders(request, corsOptions)\n },\n status: 200\n });\n }\n\n // We don't yet support GET or DELETE requests\n const body = JSON.stringify({\n error: {\n code: -32000,\n message: \"Method not allowed\"\n },\n id: null,\n jsonrpc: \"2.0\"\n });\n return new Response(body, { status: 405 });\n }\n };\n }\n}\n\n// Export client transport classes\nexport { SSEEdgeClientTransport } from \"./sse-edge\";\nexport { StreamableHTTPEdgeClientTransport } from \"./streamable-http-edge\";\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,qBAAqB;AAK9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAA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M,QAAQ,KAAK;AAAA,UAC/B,CAAC;AAID,gBAAM,kCAAkC,SAAS;AAAA,YAC/C,CAAC,QAAQ,sBAAsB,GAAG,KAAK,kBAAkB,GAAG;AAAA,UAC9D;AACA,cAAI,iCAAiC;AACnC,uBAAW,WAAW,UAAU;AAC9B,iBAAG,KAAK,KAAK,UAAU,OAAO,CAAC;AAAA,YACjC;AAGA,eAAG,MAAM;AAET,mBAAO,IAAI,SAAS,MAAM;AAAA,cACxB,SAAS,YAAY,SAAS,WAAW;AAAA,cACzC,QAAQ;AAAA,YACV,CAAC;AAAA,UACH;AAEA,qBAAW,WAAW,UAAU;AAC9B,gBAAI,iBAAiB,OAAO,GAAG;AAI7B,yBAAW,IAAI,QAAQ,EAAE;AAAA,YAC3B;AACA,eAAG,KAAK,KAAK,UAAU,OAAO,CAAC;AAAA,UACjC;AAIA,iBAAO,IAAI,SAAS,UAAU;AAAA,YAC5B,SAAS;AAAA,cACP,iBAAiB;AAAA,cACjB,YAAY;AAAA,cACZ,gBAAgB;AAAA,cAChB,kBAAkB;AAAA,cAClB,GAAG,YAAY,SAAS,WAAW;AAAA,YACrC;AAAA,YACA,QAAQ;AAAA,UACV,CAAC;AAAA,QACH;AAGA,cAAM,OAAO,KAAK,UAAU;AAAA,UAC1B,OAAO;AAAA,YACL,MAAM;AAAA,YACN,SAAS;AAAA,UACX;AAAA,UACA,IAAI;AAAA,UACJ,SAAS;AAAA,QACX,CAAC;AACD,eAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;AAAA,MAC3C;AAAA,IACF;AAAA,EACF;AACF;","names":["event","body"]}
@@ -1,5 +1,6 @@
1
1
  import 'ai';
2
- export { b as Observability, O as ObservabilityEvent, g as genericObservability } from '../index-BIJvkfYt.js';
2
+ export { b as Observability, O as ObservabilityEvent, g as genericObservability } from '../index-CLW1aEBr.js';
3
+ import 'cloudflare:workers';
3
4
  import '@modelcontextprotocol/sdk/client/index.js';
4
5
  import '@modelcontextprotocol/sdk/types.js';
5
6
  import 'partyserver';
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  genericObservability
3
- } from "../chunk-Z2OUUKK4.js";
3
+ } from "../chunk-3IQQY2UH.js";
4
4
  import "../chunk-UNG3FXYX.js";
5
5
  import "../chunk-PVQZBKN7.js";
6
6
  import "../chunk-KUH345EY.js";
package/dist/react.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { PartySocket } from "partysocket";
2
2
  import { usePartySocket } from "partysocket/react";
3
- import { M as MCPServersState, A as Agent } from "./index-BIJvkfYt.js";
3
+ import { M as MCPServersState, A as Agent } from "./index-CLW1aEBr.js";
4
4
  import { StreamOptions } from "./client.js";
5
5
  import { Method, RPCMethod } from "./serializable.js";
6
+ import "cloudflare:workers";
6
7
  import "@modelcontextprotocol/sdk/client/index.js";
7
8
  import "@modelcontextprotocol/sdk/types.js";
8
9
  import "partyserver";
package/package.json CHANGED
@@ -102,5 +102,5 @@
102
102
  },
103
103
  "type": "module",
104
104
  "types": "dist/index.d.ts",
105
- "version": "0.0.107"
105
+ "version": "0.0.109"
106
106
  }
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { env } from "cloudflare:workers";
1
2
  import { AsyncLocalStorage } from "node:async_hooks";
2
3
  import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
4
  import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
@@ -283,7 +284,7 @@ function withAgentContext<T extends (...args: any[]) => any>(
283
284
  * @template Env Environment type containing bindings
284
285
  * @template State State type to store within the Agent
285
286
  */
286
- export class Agent<Env, State = unknown> extends Server<Env> {
287
+ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
287
288
  private _state = DEFAULT_STATE as State;
288
289
 
289
290
  private _ParentClass: typeof Agent<Env, State> =
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts","../src/observability/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nimport type {\n Prompt,\n Resource,\n ServerCapabilities,\n Tool\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { parseCronExpression } from \"cron-schedule\";\nimport { nanoid } from \"nanoid\";\nimport { EmailMessage } from \"cloudflare:email\";\nimport {\n type Connection,\n type ConnectionContext,\n type PartyServerOptions,\n Server,\n type WSMessage,\n getServerByName,\n routePartykitRequest\n} from \"partyserver\";\nimport { camelCaseToKebabCase } from \"./client\";\nimport { MCPClientManager } from \"./mcp/client\";\n// import type { MCPClientConnection } from \"./mcp/client-connection\";\nimport { DurableObjectOAuthClientProvider } from \"./mcp/do-oauth-client-provider\";\nimport { genericObservability, type Observability } from \"./observability\";\n\nexport type { Connection, ConnectionContext, WSMessage } from \"partyserver\";\n\n/**\n * RPC request message from client\n */\nexport type RPCRequest = {\n type: \"rpc\";\n id: string;\n method: string;\n args: unknown[];\n};\n\n/**\n * State update message from client\n */\nexport type StateUpdateMessage = {\n type: \"cf_agent_state\";\n state: unknown;\n};\n\n/**\n * RPC response message to client\n */\nexport type RPCResponse = {\n type: \"rpc\";\n id: string;\n} & (\n | {\n success: true;\n result: unknown;\n done?: false;\n }\n | {\n success: true;\n result: unknown;\n done: true;\n }\n | {\n success: false;\n error: string;\n }\n);\n\n/**\n * Type guard for RPC request messages\n */\nfunction isRPCRequest(msg: unknown): msg is RPCRequest {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === \"rpc\" &&\n \"id\" in msg &&\n typeof msg.id === \"string\" &&\n \"method\" in msg &&\n typeof msg.method === \"string\" &&\n \"args\" in msg &&\n Array.isArray((msg as RPCRequest).args)\n );\n}\n\n/**\n * Type guard for state update messages\n */\nfunction isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === \"cf_agent_state\" &&\n \"state\" in msg\n );\n}\n\n/**\n * Metadata for a callable method\n */\nexport type CallableMetadata = {\n /** Optional description of what the method does */\n description?: string;\n /** Whether the method supports streaming responses */\n streaming?: boolean;\n};\n\nconst callableMetadata = new Map<Function, CallableMetadata>();\n\n/**\n * Decorator that marks a method as callable by clients\n * @param metadata Optional metadata about the callable method\n */\nexport function unstable_callable(metadata: CallableMetadata = {}) {\n return function callableDecorator<This, Args extends unknown[], Return>(\n target: (this: This, ...args: Args) => Return,\n // biome-ignore lint/correctness/noUnusedFunctionParameters: later\n context: ClassMethodDecoratorContext\n ) {\n if (!callableMetadata.has(target)) {\n callableMetadata.set(target, metadata);\n }\n\n return target;\n };\n}\n\nexport type QueueItem<T = string> = {\n id: string;\n payload: T;\n callback: keyof Agent<unknown>;\n created_at: number;\n};\n\n/**\n * Represents a scheduled task within an Agent\n * @template T Type of the payload data\n */\nexport type Schedule<T = string> = {\n /** Unique identifier for the schedule */\n id: string;\n /** Name of the method to be called */\n callback: string;\n /** Data to be passed to the callback */\n payload: T;\n} & (\n | {\n /** Type of schedule for one-time execution at a specific time */\n type: \"scheduled\";\n /** Timestamp when the task should execute */\n time: number;\n }\n | {\n /** Type of schedule for delayed execution */\n type: \"delayed\";\n /** Timestamp when the task should execute */\n time: number;\n /** Number of seconds to delay execution */\n delayInSeconds: number;\n }\n | {\n /** Type of schedule for recurring execution based on cron expression */\n type: \"cron\";\n /** Timestamp for the next execution */\n time: number;\n /** Cron expression defining the schedule */\n cron: string;\n }\n);\n\nfunction getNextCronTime(cron: string) {\n const interval = parseCronExpression(cron);\n return interval.getNextDate();\n}\n\n/**\n * MCP Server state update message from server -> Client\n */\nexport type MCPServerMessage = {\n type: \"cf_agent_mcp_servers\";\n mcp: MCPServersState;\n};\n\nexport type MCPServersState = {\n servers: {\n [id: string]: MCPServer;\n };\n tools: Tool[];\n prompts: Prompt[];\n resources: Resource[];\n};\n\nexport type MCPServer = {\n name: string;\n server_url: string;\n auth_url: string | null;\n // This state is specifically about the temporary process of getting a token (if needed).\n // Scope outside of that can't be relied upon because when the DO sleeps, there's no way\n // to communicate a change to a non-ready state.\n state: \"authenticating\" | \"connecting\" | \"ready\" | \"discovering\" | \"failed\";\n instructions: string | null;\n capabilities: ServerCapabilities | null;\n};\n\n/**\n * MCP Server data stored in DO SQL for resuming MCP Server connections\n */\ntype MCPServerRow = {\n id: string;\n name: string;\n server_url: string;\n client_id: string | null;\n auth_url: string | null;\n callback_url: string;\n server_options: string;\n};\n\nconst STATE_ROW_ID = \"cf_state_row_id\";\nconst STATE_WAS_CHANGED = \"cf_state_was_changed\";\n\nconst DEFAULT_STATE = {} as unknown;\n\nconst agentContext = new AsyncLocalStorage<{\n agent: Agent<unknown, unknown>;\n connection: Connection | undefined;\n request: Request | undefined;\n email: AgentEmail | undefined;\n}>();\n\nexport function getCurrentAgent<\n T extends Agent<unknown, unknown> = Agent<unknown, unknown>\n>(): {\n agent: T | undefined;\n connection: Connection | undefined;\n request: Request | undefined;\n email: AgentEmail | undefined;\n} {\n const store = agentContext.getStore() as\n | {\n agent: T;\n connection: Connection | undefined;\n request: Request | undefined;\n email: AgentEmail | undefined;\n }\n | undefined;\n if (!store) {\n return {\n agent: undefined,\n connection: undefined,\n request: undefined,\n email: undefined\n };\n }\n return store;\n}\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 */\n\n// biome-ignore lint/suspicious/noExplicitAny: I can't typescript\nfunction withAgentContext<T extends (...args: any[]) => any>(\n method: T\n): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {\n return function (...args: Parameters<T>): ReturnType<T> {\n const { connection, request, email } = getCurrentAgent();\n return agentContext.run({ agent: this, connection, request, email }, () => {\n return method.apply(this, args);\n });\n };\n}\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 */\nexport class Agent<Env, State = unknown> extends Server<Env> {\n private _state = DEFAULT_STATE as State;\n\n private _ParentClass: typeof Agent<Env, State> =\n Object.getPrototypeOf(this).constructor;\n\n mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, \"0.0.1\");\n\n /**\n * Initial state for the Agent\n * Override to provide default state values\n */\n initialState: State = DEFAULT_STATE as State;\n\n /**\n * Current state of the Agent\n */\n get state(): State {\n if (this._state !== DEFAULT_STATE) {\n // state was previously set, and populated internal state\n return this._state;\n }\n // looks like this is the first time the state is being accessed\n // check if the state was set in a previous life\n const wasChanged = this.sql<{ state: \"true\" | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}\n `;\n\n // ok, let's pick up the actual state from the db\n const result = this.sql<{ state: State | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}\n `;\n\n if (\n wasChanged[0]?.state === \"true\" ||\n // we do this check for people who updated their code before we shipped wasChanged\n result[0]?.state\n ) {\n const state = result[0]?.state as string; // could be null?\n\n this._state = JSON.parse(state);\n return this._state;\n }\n\n // ok, this is the first time the state is being accessed\n // and the state was not set in a previous life\n // so we need to set the initial state (if provided)\n if (this.initialState === DEFAULT_STATE) {\n // no initial state provided, so we return undefined\n return undefined as State;\n }\n // initial state provided, so we set the state,\n // update db and return the initial state\n this.setState(this.initialState);\n return this.initialState;\n }\n\n /**\n * Agent configuration options\n */\n static options = {\n /** Whether the Agent should hibernate when inactive */\n hibernate: true // default to hibernate\n };\n\n /**\n * The observability implementation to use for the Agent\n */\n observability?: Observability = genericObservability;\n\n /**\n * Execute SQL queries against the Agent's database\n * @template T Type of the returned rows\n * @param strings SQL query template strings\n * @param values Values to be inserted into the query\n * @returns Array of query results\n */\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ) {\n let query = \"\";\n try {\n // Construct the SQL query with placeholders\n query = strings.reduce(\n (acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"),\n \"\"\n );\n\n // Execute the SQL query with the provided values\n return [...this.ctx.storage.sql.exec(query, ...values)] as T[];\n } catch (e) {\n console.error(`failed to execute sql query: ${query}`, e);\n throw this.onError(e);\n }\n }\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n\n // Auto-wrap custom methods with agent context\n this._autoWrapCustomMethods();\n\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_state (\n id TEXT PRIMARY KEY NOT NULL,\n state TEXT\n )\n `;\n\n this.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\n void this.ctx.blockConcurrencyWhile(async () => {\n return this._tryCatch(async () => {\n // Create alarms table if it doesn't exist\n this.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\n // execute any pending alarms and schedule the next alarm\n await this.alarm();\n });\n });\n\n this.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\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = (request: Request) => {\n return agentContext.run(\n { agent: this, connection: undefined, request, email: undefined },\n async () => {\n if (this.mcp.isCallbackRequest(request)) {\n await this.mcp.handleCallbackRequest(request);\n\n // after the MCP connection handshake, we can send updated mcp state\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: \"cf_agent_mcp_servers\"\n })\n );\n\n // We probably should let the user configure this response/redirect, but this is fine for now.\n return new Response(\"<script>window.close();</script>\", {\n headers: { \"content-type\": \"text/html\" },\n status: 200\n });\n }\n\n return this._tryCatch(() => _onRequest(request));\n }\n );\n };\n\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n return agentContext.run(\n { agent: this, connection, request: undefined, email: undefined },\n async () => {\n if (typeof message !== \"string\") {\n return this._tryCatch(() => _onMessage(connection, message));\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(message);\n } catch (_e) {\n // silently fail and let the onMessage handler handle it\n return this._tryCatch(() => _onMessage(connection, message));\n }\n\n if (isStateUpdateMessage(parsed)) {\n this._setStateInternal(parsed.state as State, connection);\n return;\n }\n\n if (isRPCRequest(parsed)) {\n try {\n const { id, method, args } = parsed;\n\n // Check if method exists and is callable\n const methodFn = this[method as keyof this];\n if (typeof methodFn !== \"function\") {\n throw new Error(`Method ${method} does not exist`);\n }\n\n if (!this._isCallable(method)) {\n throw new Error(`Method ${method} is not callable`);\n }\n\n const metadata = callableMetadata.get(methodFn as Function);\n\n // For streaming methods, pass a StreamingResponse object\n if (metadata?.streaming) {\n const stream = new StreamingResponse(connection, id);\n await methodFn.apply(this, [stream, ...args]);\n return;\n }\n\n // For regular methods, execute and send response\n const result = await methodFn.apply(this, args);\n\n this.observability?.emit(\n {\n displayMessage: `RPC call to ${method}`,\n id: nanoid(),\n payload: {\n args,\n method,\n streaming: metadata?.streaming,\n success: true\n },\n timestamp: Date.now(),\n type: \"rpc\"\n },\n this.ctx\n );\n\n const response: RPCResponse = {\n done: true,\n id,\n result,\n success: true,\n type: \"rpc\"\n };\n connection.send(JSON.stringify(response));\n } catch (e) {\n // Send error response\n const response: RPCResponse = {\n error:\n e instanceof Error ? e.message : \"Unknown error occurred\",\n id: parsed.id,\n success: false,\n type: \"rpc\"\n };\n connection.send(JSON.stringify(response));\n console.error(\"RPC error:\", e);\n }\n return;\n }\n\n return this._tryCatch(() => _onMessage(connection, message));\n }\n );\n };\n\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = (connection: Connection, ctx: ConnectionContext) => {\n // TODO: This is a hack to ensure the state is sent after the connection is established\n // must fix this\n return agentContext.run(\n { agent: this, connection, request: ctx.request, email: undefined },\n async () => {\n setTimeout(() => {\n if (this.state) {\n connection.send(\n JSON.stringify({\n state: this.state,\n type: \"cf_agent_state\"\n })\n );\n }\n\n connection.send(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: \"cf_agent_mcp_servers\"\n })\n );\n\n this.observability?.emit(\n {\n displayMessage: \"Connection established\",\n id: nanoid(),\n payload: {\n connectionId: connection.id\n },\n timestamp: Date.now(),\n type: \"connect\"\n },\n this.ctx\n );\n return this._tryCatch(() => _onConnect(connection, ctx));\n }, 20);\n }\n );\n };\n\n const _onStart = this.onStart.bind(this);\n this.onStart = async () => {\n return agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n const servers = this.sql<MCPServerRow>`\n SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;\n `;\n\n // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information\n if (servers && Array.isArray(servers) && servers.length > 0) {\n Promise.allSettled(\n servers.map((server) => {\n return this._connectToMcpServerInternal(\n server.name,\n server.server_url,\n server.callback_url,\n server.server_options\n ? JSON.parse(server.server_options)\n : undefined,\n {\n id: server.id,\n oauthClientId: server.client_id ?? undefined\n }\n );\n })\n ).then((_results) => {\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: \"cf_agent_mcp_servers\"\n })\n );\n });\n }\n await this._tryCatch(() => _onStart());\n }\n );\n };\n }\n\n private _setStateInternal(\n state: State,\n source: Connection | \"server\" = \"server\"\n ) {\n const previousState = this._state;\n this._state = state;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})\n `;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})\n `;\n this.broadcast(\n JSON.stringify({\n state: state,\n type: \"cf_agent_state\"\n }),\n source !== \"server\" ? [source.id] : []\n );\n return this._tryCatch(() => {\n const { connection, request, email } = agentContext.getStore() || {};\n return agentContext.run(\n { agent: this, connection, request, email },\n async () => {\n this.observability?.emit(\n {\n displayMessage: \"State updated\",\n id: nanoid(),\n payload: {\n previousState,\n state\n },\n timestamp: Date.now(),\n type: \"state:update\"\n },\n this.ctx\n );\n return this.onStateUpdate(state, source);\n }\n );\n });\n }\n\n /**\n * Update the Agent's state\n * @param state New state to set\n */\n setState(state: State) {\n this._setStateInternal(state, \"server\");\n }\n\n /**\n * Called when the Agent's state is updated\n * @param state Updated state\n * @param source Source of the state update (\"server\" or a client connection)\n */\n // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates\n }\n\n /**\n * Called when the Agent receives an email via routeAgentEmail()\n * Override this method to handle incoming emails\n * @param email Email message to process\n */\n async _onEmail(email: AgentEmail) {\n // nb: we use this roundabout way of getting to onEmail\n // because of https://github.com/cloudflare/workerd/issues/4499\n return agentContext.run(\n { agent: this, connection: undefined, request: undefined, email: email },\n async () => {\n if (\"onEmail\" in this && typeof this.onEmail === \"function\") {\n return this._tryCatch(() =>\n (this.onEmail as (email: AgentEmail) => Promise<void>)(email)\n );\n } else {\n console.log(\"Received email from:\", email.from, \"to:\", email.to);\n console.log(\"Subject:\", email.headers.get(\"subject\"));\n console.log(\n \"Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails\"\n );\n }\n }\n );\n }\n\n /**\n * Reply to an email\n * @param email The email to reply to\n * @param options Options for the reply\n * @returns void\n */\n async replyToEmail(\n email: AgentEmail,\n options: {\n fromName: string;\n subject?: string | undefined;\n body: string;\n contentType?: string;\n headers?: Record<string, string>;\n }\n ): Promise<void> {\n return this._tryCatch(async () => {\n const agentName = camelCaseToKebabCase(this._ParentClass.name);\n const agentId = this.name;\n\n const { createMimeMessage } = await import(\"mimetext\");\n const msg = createMimeMessage();\n msg.setSender({ addr: email.to, name: options.fromName });\n msg.setRecipient(email.from);\n msg.setSubject(\n options.subject || `Re: ${email.headers.get(\"subject\")}` || \"No subject\"\n );\n msg.addMessage({\n contentType: options.contentType || \"text/plain\",\n data: options.body\n });\n\n const domain = email.from.split(\"@\")[1];\n const messageId = `<${agentId}@${domain}>`;\n msg.setHeader(\"In-Reply-To\", email.headers.get(\"Message-ID\")!);\n msg.setHeader(\"Message-ID\", messageId);\n msg.setHeader(\"X-Agent-Name\", agentName);\n msg.setHeader(\"X-Agent-ID\", agentId);\n\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n msg.setHeader(key, value);\n }\n }\n await email.reply({\n from: email.to,\n raw: msg.asRaw(),\n to: email.from\n });\n });\n }\n\n private async _tryCatch<T>(fn: () => T | Promise<T>) {\n try {\n return await fn();\n } catch (e) {\n throw this.onError(e);\n }\n }\n\n /**\n * Automatically wrap custom methods with agent context\n * This ensures getCurrentAgent() works in all custom methods without decorators\n */\n private _autoWrapCustomMethods() {\n // Collect all methods from base prototypes (Agent and Server)\n const basePrototypes = [Agent.prototype, Server.prototype];\n const baseMethods = new Set<string>();\n for (const baseProto of basePrototypes) {\n let proto = baseProto;\n while (proto && proto !== Object.prototype) {\n const methodNames = Object.getOwnPropertyNames(proto);\n for (const methodName of methodNames) {\n baseMethods.add(methodName);\n }\n proto = Object.getPrototypeOf(proto);\n }\n }\n // Get all methods from the current instance's prototype chain\n let proto = Object.getPrototypeOf(this);\n let depth = 0;\n while (proto && proto !== Object.prototype && depth < 10) {\n const methodNames = Object.getOwnPropertyNames(proto);\n for (const methodName of methodNames) {\n // Skip if it's a private method or not a function\n if (\n baseMethods.has(methodName) ||\n methodName.startsWith(\"_\") ||\n typeof this[methodName as keyof this] !== \"function\"\n ) {\n continue;\n }\n // If the method doesn't exist in base prototypes, it's a custom method\n if (!baseMethods.has(methodName)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);\n if (descriptor && typeof descriptor.value === \"function\") {\n // Wrap the custom method with context\n\n const wrappedFunction = withAgentContext(\n // biome-ignore lint/suspicious/noExplicitAny: I can't typescript\n this[methodName as keyof this] as (...args: any[]) => any\n // biome-ignore lint/suspicious/noExplicitAny: I can't typescript\n ) as any;\n\n // if the method is callable, copy the metadata from the original method\n if (this._isCallable(methodName)) {\n callableMetadata.set(\n wrappedFunction,\n callableMetadata.get(\n this[methodName as keyof this] as Function\n )!\n );\n }\n\n // set the wrapped function on the prototype\n this.constructor.prototype[methodName as keyof this] =\n wrappedFunction;\n }\n }\n }\n\n proto = Object.getPrototypeOf(proto);\n depth++;\n }\n }\n\n override onError(\n connection: Connection,\n error: unknown\n ): void | Promise<void>;\n override onError(error: unknown): void | Promise<void>;\n override onError(connectionOrError: Connection | unknown, error?: unknown) {\n let theError: unknown;\n if (connectionOrError && error) {\n theError = error;\n // this is a websocket connection error\n console.error(\n \"Error on websocket connection:\",\n (connectionOrError as Connection).id,\n theError\n );\n console.error(\n \"Override onError(connection, error) to handle websocket connection errors\"\n );\n } else {\n theError = connectionOrError;\n // this is a server error\n console.error(\"Error on server:\", theError);\n console.error(\"Override onError(error) to handle server errors\");\n }\n throw theError;\n }\n\n /**\n * Render content (not implemented in base class)\n */\n render() {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Queue a task to be executed in the future\n * @param payload Payload to pass to the callback\n * @param callback Name of the method to call\n * @returns The ID of the queued task\n */\n async queue<T = unknown>(callback: keyof this, payload: T): Promise<string> {\n const id = nanoid(9);\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n\n if (typeof this[callback] !== \"function\") {\n throw new Error(`this.${callback} is not a function`);\n }\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)\n VALUES (${id}, ${JSON.stringify(payload)}, ${callback})\n `;\n\n void this._flushQueue().catch((e) => {\n console.error(\"Error flushing queue:\", e);\n });\n\n return id;\n }\n\n private _flushingQueue = false;\n\n private async _flushQueue() {\n if (this._flushingQueue) {\n return;\n }\n this._flushingQueue = true;\n while (true) {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues\n ORDER BY created_at ASC\n `;\n\n if (!result || result.length === 0) {\n break;\n }\n\n for (const row of result || []) {\n const callback = this[row.callback as keyof Agent<Env>];\n if (!callback) {\n console.error(`callback ${row.callback} not found`);\n continue;\n }\n const { connection, request, email } = agentContext.getStore() || {};\n await agentContext.run(\n {\n agent: this,\n connection,\n request,\n email\n },\n async () => {\n // TODO: add retries and backoff\n await (\n callback as (\n payload: unknown,\n queueItem: QueueItem<string>\n ) => Promise<void>\n ).bind(this)(JSON.parse(row.payload as string), row);\n await this.dequeue(row.id);\n }\n );\n }\n }\n this._flushingQueue = false;\n }\n\n /**\n * Dequeue a task by ID\n * @param id ID of the task to dequeue\n */\n async dequeue(id: string) {\n this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;\n }\n\n /**\n * Dequeue all tasks\n */\n async dequeueAll() {\n this.sql`DELETE FROM cf_agents_queues`;\n }\n\n /**\n * Dequeue all tasks by callback\n * @param callback Name of the callback to dequeue\n */\n async dequeueAllByCallback(callback: string) {\n this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;\n }\n\n /**\n * Get a queued task by ID\n * @param id ID of the task to get\n * @returns The task or undefined if not found\n */\n async getQueue(id: string): Promise<QueueItem<string> | undefined> {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues WHERE id = ${id}\n `;\n return result\n ? { ...result[0], payload: JSON.parse(result[0].payload) }\n : undefined;\n }\n\n /**\n * Get all queues by key and value\n * @param key Key to filter by\n * @param value Value to filter by\n * @returns Array of matching QueueItem objects\n */\n async getQueues(key: string, value: string): Promise<QueueItem<string>[]> {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues\n `;\n return result.filter((row) => JSON.parse(row.payload)[key] === value);\n }\n\n /**\n * Schedule a task to be executed in the future\n * @template T Type of the payload data\n * @param when When to execute the task (Date, seconds delay, or cron expression)\n * @param callback Name of the method to call\n * @param payload Data to pass to the callback\n * @returns Schedule object representing the scheduled task\n */\n async schedule<T = string>(\n when: Date | string | number,\n callback: keyof this,\n payload?: T\n ): Promise<Schedule<T>> {\n const id = nanoid(9);\n\n const emitScheduleCreate = (schedule: Schedule<T>) =>\n this.observability?.emit(\n {\n displayMessage: `Schedule ${schedule.id} created`,\n id: nanoid(),\n payload: schedule,\n timestamp: Date.now(),\n type: \"schedule:create\"\n },\n this.ctx\n );\n\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n\n if (typeof this[callback] !== \"function\") {\n throw new Error(`this.${callback} is not a function`);\n }\n\n if (when instanceof Date) {\n const timestamp = Math.floor(when.getTime() / 1000);\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'scheduled', ${timestamp})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n id,\n payload: payload as T,\n time: timestamp,\n type: \"scheduled\"\n };\n\n emitScheduleCreate(schedule);\n\n return schedule;\n }\n if (typeof when === \"number\") {\n const time = new Date(Date.now() + when * 1000);\n const timestamp = Math.floor(time.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'delayed', ${when}, ${timestamp})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n delayInSeconds: when,\n id,\n payload: payload as T,\n time: timestamp,\n type: \"delayed\"\n };\n\n emitScheduleCreate(schedule);\n\n return schedule;\n }\n if (typeof when === \"string\") {\n const nextExecutionTime = getNextCronTime(when);\n const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'cron', ${when}, ${timestamp})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n cron: when,\n id,\n payload: payload as T,\n time: timestamp,\n type: \"cron\"\n };\n\n emitScheduleCreate(schedule);\n\n return schedule;\n }\n throw new Error(\"Invalid schedule type\");\n }\n\n /**\n * Get a scheduled task by ID\n * @template T Type of the payload data\n * @param id ID of the scheduled task\n * @returns The Schedule object or undefined if not found\n */\n async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE id = ${id}\n `;\n if (!result) {\n console.error(`schedule ${id} not found`);\n return undefined;\n }\n\n return { ...result[0], payload: JSON.parse(result[0].payload) as T };\n }\n\n /**\n * Get scheduled tasks matching the given criteria\n * @template T Type of the payload data\n * @param criteria Criteria to filter schedules\n * @returns Array of matching Schedule objects\n */\n getSchedules<T = string>(\n criteria: {\n id?: string;\n type?: \"scheduled\" | \"delayed\" | \"cron\";\n timeRange?: { start?: Date; end?: Date };\n } = {}\n ): Schedule<T>[] {\n let query = \"SELECT * FROM cf_agents_schedules WHERE 1=1\";\n const params = [];\n\n if (criteria.id) {\n query += \" AND id = ?\";\n params.push(criteria.id);\n }\n\n if (criteria.type) {\n query += \" AND type = ?\";\n params.push(criteria.type);\n }\n\n if (criteria.timeRange) {\n query += \" AND time >= ? AND time <= ?\";\n const start = criteria.timeRange.start || new Date(0);\n const end = criteria.timeRange.end || new Date(999999999999999);\n params.push(\n Math.floor(start.getTime() / 1000),\n Math.floor(end.getTime() / 1000)\n );\n }\n\n const result = this.ctx.storage.sql\n .exec(query, ...params)\n .toArray()\n .map((row) => ({\n ...row,\n payload: JSON.parse(row.payload as string) as T\n })) as Schedule<T>[];\n\n return result;\n }\n\n /**\n * Cancel a scheduled task\n * @param id ID of the task to cancel\n * @returns true if the task was cancelled, false otherwise\n */\n async cancelSchedule(id: string): Promise<boolean> {\n const schedule = await this.getSchedule(id);\n if (schedule) {\n this.observability?.emit(\n {\n displayMessage: `Schedule ${id} cancelled`,\n id: nanoid(),\n payload: schedule,\n timestamp: Date.now(),\n type: \"schedule:cancel\"\n },\n this.ctx\n );\n }\n this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;\n\n await this._scheduleNextAlarm();\n return true;\n }\n\n private async _scheduleNextAlarm() {\n // Find the next schedule that needs to be executed\n const result = this.sql`\n SELECT time FROM cf_agents_schedules\n WHERE time > ${Math.floor(Date.now() / 1000)}\n ORDER BY time ASC\n LIMIT 1\n `;\n if (!result) return;\n\n if (result.length > 0 && \"time\" in result[0]) {\n const nextTime = (result[0].time as number) * 1000;\n await this.ctx.storage.setAlarm(nextTime);\n }\n }\n\n /**\n * Method called when an alarm fires.\n * Executes any scheduled tasks that are due.\n *\n * @remarks\n * To schedule a task, please use the `this.schedule` method instead.\n * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}\n */\n public readonly alarm = async () => {\n const now = Math.floor(Date.now() / 1000);\n\n // Get all schedules that should be executed now\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE time <= ${now}\n `;\n\n if (result && Array.isArray(result)) {\n for (const row of result) {\n const callback = this[row.callback as keyof Agent<Env>];\n if (!callback) {\n console.error(`callback ${row.callback} not found`);\n continue;\n }\n await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n try {\n this.observability?.emit(\n {\n displayMessage: `Schedule ${row.id} executed`,\n id: nanoid(),\n payload: row,\n timestamp: Date.now(),\n type: \"schedule:execute\"\n },\n this.ctx\n );\n\n await (\n callback as (\n payload: unknown,\n schedule: Schedule<unknown>\n ) => Promise<void>\n ).bind(this)(JSON.parse(row.payload as string), row);\n } catch (e) {\n console.error(`error executing callback \"${row.callback}\"`, e);\n }\n }\n );\n if (row.type === \"cron\") {\n // Update next execution time for cron schedules\n const nextExecutionTime = getNextCronTime(row.cron);\n const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}\n `;\n } else {\n // Delete one-time schedules after execution\n this.sql`\n DELETE FROM cf_agents_schedules WHERE id = ${row.id}\n `;\n }\n }\n }\n\n // Schedule the next alarm\n await this._scheduleNextAlarm();\n };\n\n /**\n * Destroy the Agent, removing all state and scheduled tasks\n */\n async destroy() {\n // drop all tables\n this.sql`DROP TABLE IF EXISTS cf_agents_state`;\n this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;\n this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;\n this.sql`DROP TABLE IF EXISTS cf_agents_queues`;\n\n // delete all alarms\n await this.ctx.storage.deleteAlarm();\n await this.ctx.storage.deleteAll();\n this.ctx.abort(\"destroyed\"); // enforce that the agent is evicted\n\n this.observability?.emit(\n {\n displayMessage: \"Agent destroyed\",\n id: nanoid(),\n payload: {},\n timestamp: Date.now(),\n type: \"destroy\"\n },\n this.ctx\n );\n }\n\n /**\n * Get all methods marked as callable on this Agent\n * @returns A map of method names to their metadata\n */\n private _isCallable(method: string): boolean {\n return callableMetadata.has(this[method as keyof this] as Function);\n }\n\n /**\n * Connect to a new MCP Server\n *\n * @param url MCP Server SSE URL\n * @param callbackHost Base host for the agent, used for the redirect URI.\n * @param agentsPrefix agents routing prefix if not using `agents`\n * @param options MCP client and transport (header) options\n * @returns authUrl\n */\n async addMcpServer(\n serverName: string,\n url: string,\n callbackHost: string,\n agentsPrefix = \"agents\",\n options?: {\n client?: ConstructorParameters<typeof Client>[1];\n transport?: {\n headers: HeadersInit;\n };\n }\n ): Promise<{ id: string; authUrl: string | undefined }> {\n const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;\n\n const result = await this._connectToMcpServerInternal(\n serverName,\n url,\n callbackUrl,\n options\n );\n this.sql`\n INSERT\n OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)\n VALUES (\n ${result.id},\n ${serverName},\n ${url},\n ${result.clientId ?? null},\n ${result.authUrl ?? null},\n ${callbackUrl},\n ${options ? JSON.stringify(options) : null}\n );\n `;\n\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: \"cf_agent_mcp_servers\"\n })\n );\n\n return result;\n }\n\n async _connectToMcpServerInternal(\n _serverName: string,\n url: string,\n callbackUrl: string,\n // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes\n options?: {\n client?: ConstructorParameters<typeof Client>[1];\n /**\n * We don't expose the normal set of transport options because:\n * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes\n * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)\n *\n * This has the limitation that you can't override fetch, but I think headers should handle nearly all cases needed (i.e. non-standard bearer auth).\n */\n transport?: {\n headers?: HeadersInit;\n };\n },\n reconnect?: {\n id: string;\n oauthClientId?: string;\n }\n ): Promise<{\n id: string;\n authUrl: string | undefined;\n clientId: string | undefined;\n }> {\n const authProvider = new DurableObjectOAuthClientProvider(\n this.ctx.storage,\n this.name,\n callbackUrl\n );\n\n if (reconnect) {\n authProvider.serverId = reconnect.id;\n if (reconnect.oauthClientId) {\n authProvider.clientId = reconnect.oauthClientId;\n }\n }\n\n // allows passing through transport headers if necessary\n // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)\n let headerTransportOpts: SSEClientTransportOptions = {};\n if (options?.transport?.headers) {\n headerTransportOpts = {\n eventSourceInit: {\n fetch: (url, init) =>\n fetch(url, {\n ...init,\n headers: options?.transport?.headers\n })\n },\n requestInit: {\n headers: options?.transport?.headers\n }\n };\n }\n\n const { id, authUrl, clientId } = await this.mcp.connect(url, {\n client: options?.client,\n reconnect,\n transport: {\n ...headerTransportOpts,\n authProvider\n }\n });\n\n return {\n authUrl,\n clientId,\n id\n };\n }\n\n async removeMcpServer(id: string) {\n this.mcp.closeConnection(id);\n this.sql`\n DELETE FROM cf_agents_mcp_servers WHERE id = ${id};\n `;\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: \"cf_agent_mcp_servers\"\n })\n );\n }\n\n getMcpServers(): MCPServersState {\n const mcpState: MCPServersState = {\n prompts: this.mcp.listPrompts(),\n resources: this.mcp.listResources(),\n servers: {},\n tools: this.mcp.listTools()\n };\n\n const servers = this.sql<MCPServerRow>`\n SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;\n `;\n\n if (servers && Array.isArray(servers) && servers.length > 0) {\n for (const server of servers) {\n const serverConn = this.mcp.mcpConnections[server.id];\n mcpState.servers[server.id] = {\n auth_url: server.auth_url,\n capabilities: serverConn?.serverCapabilities ?? null,\n instructions: serverConn?.instructions ?? null,\n name: server.name,\n server_url: server.server_url,\n // mark as \"authenticating\" because the server isn't automatically connected, so it's pending authenticating\n state: serverConn?.connectionState ?? \"authenticating\"\n };\n }\n }\n\n return mcpState;\n }\n}\n\n/**\n * Namespace for creating Agent instances\n * @template Agentic Type of the Agent class\n */\nexport type AgentNamespace<Agentic extends Agent<unknown>> =\n DurableObjectNamespace<Agentic>;\n\n/**\n * Agent's durable context\n */\nexport type AgentContext = DurableObjectState;\n\n/**\n * Configuration options for Agent routing\n */\nexport type AgentOptions<Env> = PartyServerOptions<Env> & {\n /**\n * Whether to enable CORS for the Agent\n */\n cors?: boolean | HeadersInit | undefined;\n};\n\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 */\nexport async function routeAgentRequest<Env>(\n request: Request,\n env: Env,\n options?: AgentOptions<Env>\n) {\n const corsHeaders =\n options?.cors === true\n ? {\n \"Access-Control-Allow-Credentials\": \"true\",\n \"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Max-Age\": \"86400\"\n }\n : options?.cors;\n\n if (request.method === \"OPTIONS\") {\n if (corsHeaders) {\n return new Response(null, {\n headers: corsHeaders\n });\n }\n console.warn(\n \"Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.\"\n );\n }\n\n let response = await routePartykitRequest(\n request,\n env as Record<string, unknown>,\n {\n prefix: \"agents\",\n ...(options as PartyServerOptions<Record<string, unknown>>)\n }\n );\n\n if (\n response &&\n corsHeaders &&\n request.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\" &&\n request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\"\n ) {\n response = new Response(response.body, {\n headers: {\n ...response.headers,\n ...corsHeaders\n }\n });\n }\n return response;\n}\n\nexport type EmailResolver<Env> = (\n email: ForwardableEmailMessage,\n env: Env\n) => Promise<{\n agentName: string;\n agentId: string;\n} | null>;\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 */\nexport function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {\n return async (email: ForwardableEmailMessage, _env: Env) => {\n const messageId = email.headers.get(\"message-id\");\n if (messageId) {\n const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);\n if (messageIdMatch) {\n const [, agentId, domain] = messageIdMatch;\n const agentName = domain.split(\".\")[0];\n return { agentName, agentId };\n }\n }\n\n const references = email.headers.get(\"references\");\n if (references) {\n const referencesMatch = references.match(\n /<([A-Za-z0-9+/]{43}=)@([^>]+)>/\n );\n if (referencesMatch) {\n const [, base64Id, domain] = referencesMatch;\n const agentId = Buffer.from(base64Id, \"base64\").toString(\"hex\");\n const agentName = domain.split(\".\")[0];\n return { agentName, agentId };\n }\n }\n\n const agentName = email.headers.get(\"x-agent-name\");\n const agentId = email.headers.get(\"x-agent-id\");\n if (agentName && agentId) {\n return { agentName, agentId };\n }\n\n return null;\n };\n}\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 */\nexport function createAddressBasedEmailResolver<Env>(\n defaultAgentName: string\n): EmailResolver<Env> {\n return async (email: ForwardableEmailMessage, _env: Env) => {\n const emailMatch = email.to.match(/^([^+@]+)(?:\\+([^@]+))?@(.+)$/);\n if (!emailMatch) {\n return null;\n }\n\n const [, localPart, subAddress] = emailMatch;\n\n if (subAddress) {\n return {\n agentName: localPart,\n agentId: subAddress\n };\n }\n\n // Option 2: Use defaultAgentName namespace, localPart as agentId\n // Common for catch-all email routing to a single EmailAgent namespace\n return {\n agentName: defaultAgentName,\n agentId: localPart\n };\n };\n}\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 */\nexport function createCatchAllEmailResolver<Env>(\n agentName: string,\n agentId: string\n): EmailResolver<Env> {\n return async () => ({ agentName, agentId });\n}\n\nexport type EmailRoutingOptions<Env> = AgentOptions<Env> & {\n resolver: EmailResolver<Env>;\n};\n\n// Cache the agent namespace map for email routing\n// This maps both kebab-case and original names to namespaces\nconst agentMapCache = new WeakMap<\n Record<string, unknown>,\n Record<string, unknown>\n>();\n\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 */\nexport async function routeAgentEmail<Env>(\n email: ForwardableEmailMessage,\n env: Env,\n options: EmailRoutingOptions<Env>\n): Promise<void> {\n const routingInfo = await options.resolver(email, env);\n\n if (!routingInfo) {\n console.warn(\"No routing information found for email, dropping message\");\n return;\n }\n\n // Build a map that includes both original names and kebab-case versions\n if (!agentMapCache.has(env as Record<string, unknown>)) {\n const map: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(env as Record<string, unknown>)) {\n if (\n value &&\n typeof value === \"object\" &&\n \"idFromName\" in value &&\n typeof value.idFromName === \"function\"\n ) {\n // Add both the original name and kebab-case version\n map[key] = value;\n map[camelCaseToKebabCase(key)] = value;\n }\n }\n agentMapCache.set(env as Record<string, unknown>, map);\n }\n\n const agentMap = agentMapCache.get(env as Record<string, unknown>)!;\n const namespace = agentMap[routingInfo.agentName];\n\n if (!namespace) {\n // Provide helpful error message listing available agents\n const availableAgents = Object.keys(agentMap)\n .filter((key) => !key.includes(\"-\")) // Show only original names, not kebab-case duplicates\n .join(\", \");\n throw new Error(\n `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`\n );\n }\n\n const agent = await getAgentByName(\n namespace as unknown as AgentNamespace<Agent<Env>>,\n routingInfo.agentId\n );\n\n // let's make a serialisable version of the email\n const serialisableEmail: AgentEmail = {\n getRaw: async () => {\n const reader = email.raw.getReader();\n const chunks: Uint8Array[] = [];\n\n let done = false;\n while (!done) {\n const { value, done: readerDone } = await reader.read();\n done = readerDone;\n if (value) {\n chunks.push(value);\n }\n }\n\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const combined = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n combined.set(chunk, offset);\n offset += chunk.length;\n }\n\n return combined;\n },\n headers: email.headers,\n rawSize: email.rawSize,\n setReject: (reason: string) => {\n email.setReject(reason);\n },\n forward: (rcptTo: string, headers?: Headers) => {\n return email.forward(rcptTo, headers);\n },\n reply: (options: { from: string; to: string; raw: string }) => {\n return email.reply(\n new EmailMessage(options.from, options.to, options.raw)\n );\n },\n from: email.from,\n to: email.to\n };\n\n await agent._onEmail(serialisableEmail);\n}\n\nexport type AgentEmail = {\n from: string;\n to: string;\n getRaw: () => Promise<Uint8Array>;\n headers: Headers;\n rawSize: number;\n setReject: (reason: string) => void;\n forward: (rcptTo: string, headers?: Headers) => Promise<void>;\n reply: (options: { from: string; to: string; raw: string }) => Promise<void>;\n};\n\nexport type EmailSendOptions = {\n to: string;\n subject: string;\n body: string;\n contentType?: string;\n headers?: Record<string, string>;\n includeRoutingHeaders?: boolean;\n agentName?: string;\n agentId?: string;\n domain?: string;\n};\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 */\nexport async function getAgentByName<Env, T extends Agent<Env>>(\n namespace: AgentNamespace<T>,\n name: string,\n options?: {\n jurisdiction?: DurableObjectJurisdiction;\n locationHint?: DurableObjectLocationHint;\n }\n) {\n return getServerByName<Env, T>(namespace, name, options);\n}\n\n/**\n * A wrapper for streaming responses in callable methods\n */\nexport class StreamingResponse {\n private _connection: Connection;\n private _id: string;\n private _closed = false;\n\n constructor(connection: Connection, id: string) {\n this._connection = connection;\n this._id = id;\n }\n\n /**\n * Send a chunk of data to the client\n * @param chunk The data to send\n */\n send(chunk: unknown) {\n if (this._closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n const response: RPCResponse = {\n done: false,\n id: this._id,\n result: chunk,\n success: true,\n type: \"rpc\"\n };\n this._connection.send(JSON.stringify(response));\n }\n\n /**\n * End the stream and send the final chunk (if any)\n * @param finalChunk Optional final chunk of data to send\n */\n end(finalChunk?: unknown) {\n if (this._closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n this._closed = true;\n const response: RPCResponse = {\n done: true,\n id: this._id,\n result: finalChunk,\n success: true,\n type: \"rpc\"\n };\n this._connection.send(JSON.stringify(response));\n }\n}\n","import type { Message } from \"ai\";\nimport type { Schedule } from \"../index\";\nimport { getCurrentAgent } from \"../index\";\n\ntype BaseEvent<\n T extends string,\n Payload extends Record<string, unknown> = {}\n> = {\n type: T;\n /**\n * The unique identifier for the event\n */\n id: string;\n /**\n * The message to display in the logs for this event, should the implementation choose to display\n * a human-readable message.\n */\n displayMessage: string;\n /**\n * The payload of the event\n */\n payload: Payload;\n /**\n * The timestamp of the event in milliseconds since epoch\n */\n timestamp: number;\n};\n\n/**\n * The type of events that can be emitted by an Agent\n */\nexport type ObservabilityEvent =\n | BaseEvent<\n \"state:update\",\n {\n state: unknown;\n previousState: unknown;\n }\n >\n | BaseEvent<\n \"rpc\",\n {\n method: string;\n args: unknown[];\n streaming?: boolean;\n success: boolean;\n }\n >\n | BaseEvent<\n \"message:request\" | \"message:response\",\n {\n message: Message[];\n }\n >\n | BaseEvent<\"message:clear\">\n | BaseEvent<\n \"schedule:create\" | \"schedule:execute\" | \"schedule:cancel\",\n Schedule<unknown>\n >\n | BaseEvent<\"destroy\">\n | BaseEvent<\n \"connect\",\n {\n connectionId: string;\n }\n >;\n\nexport interface Observability {\n /**\n * Emit an event for the Agent's observability implementation to handle.\n * @param event - The event to emit\n * @param ctx - The execution context of the invocation\n */\n emit(event: ObservabilityEvent, ctx: DurableObjectState): void;\n}\n\n/**\n * A generic observability implementation that logs events to the console.\n */\nexport const genericObservability: Observability = {\n emit(event) {\n // In local mode, we display a pretty-print version of the event for easier debugging.\n if (isLocalMode()) {\n console.log(event.displayMessage);\n return;\n }\n\n console.log(event);\n }\n};\n\nlet localMode = false;\n\nfunction isLocalMode() {\n if (localMode) {\n return true;\n }\n const { request } = getCurrentAgent();\n if (!request) {\n return false;\n }\n\n const url = new URL(request.url);\n localMode = url.hostname === \"localhost\";\n return localMode;\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,yBAAyB;AAUlC,SAAS,2BAA2B;AACpC,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B;AAAA,EAIE;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AAqDP,SAAS,aAAa,KAAiC;AACrD,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,SAAS,SACb,QAAQ,OACR,OAAO,IAAI,OAAO,YAClB,YAAY,OACZ,OAAO,IAAI,WAAW,YACtB,UAAU,OACV,MAAM,QAAS,IAAm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