agents 0.0.83 → 0.0.85
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-chat-agent.js +1 -1
- package/dist/{chunk-RIYR6FR6.js → chunk-J6T74FUS.js} +14 -8
- package/dist/chunk-J6T74FUS.js.map +1 -0
- package/dist/index.d.ts +13 -2
- package/dist/index.js +1 -1
- package/dist/mcp/index.js +1 -1
- package/dist/react.d.ts +52 -1
- package/dist/react.js.map +1 -1
- package/package.json +3 -2
- package/src/index.ts +16 -9
- package/dist/chunk-RIYR6FR6.js.map +0 -1
package/dist/ai-chat-agent.js
CHANGED
|
@@ -149,7 +149,7 @@ var Agent = class extends Server {
|
|
|
149
149
|
this.broadcast(
|
|
150
150
|
JSON.stringify({
|
|
151
151
|
type: "cf_agent_mcp_servers",
|
|
152
|
-
mcp: this.
|
|
152
|
+
mcp: this.getMcpServers()
|
|
153
153
|
})
|
|
154
154
|
);
|
|
155
155
|
return new Response("<script>window.close();</script>", {
|
|
@@ -237,7 +237,7 @@ var Agent = class extends Server {
|
|
|
237
237
|
connection.send(
|
|
238
238
|
JSON.stringify({
|
|
239
239
|
type: "cf_agent_mcp_servers",
|
|
240
|
-
mcp: this.
|
|
240
|
+
mcp: this.getMcpServers()
|
|
241
241
|
})
|
|
242
242
|
);
|
|
243
243
|
return this._tryCatch(() => _onConnect(connection, ctx2));
|
|
@@ -270,7 +270,7 @@ var Agent = class extends Server {
|
|
|
270
270
|
this.broadcast(
|
|
271
271
|
JSON.stringify({
|
|
272
272
|
type: "cf_agent_mcp_servers",
|
|
273
|
-
mcp: this.
|
|
273
|
+
mcp: this.getMcpServers()
|
|
274
274
|
})
|
|
275
275
|
);
|
|
276
276
|
await this._tryCatch(() => _onStart());
|
|
@@ -562,6 +562,10 @@ var Agent = class extends Server {
|
|
|
562
562
|
await this.ctx.storage.deleteAlarm();
|
|
563
563
|
await this.ctx.storage.deleteAll();
|
|
564
564
|
}
|
|
565
|
+
/**
|
|
566
|
+
* Get all methods marked as callable on this Agent
|
|
567
|
+
* @returns A map of method names to their metadata
|
|
568
|
+
*/
|
|
565
569
|
_isCallable(method) {
|
|
566
570
|
return callableMetadata.has(this[method]);
|
|
567
571
|
}
|
|
@@ -585,7 +589,7 @@ var Agent = class extends Server {
|
|
|
585
589
|
this.broadcast(
|
|
586
590
|
JSON.stringify({
|
|
587
591
|
type: "cf_agent_mcp_servers",
|
|
588
|
-
mcp: this.
|
|
592
|
+
mcp: this.getMcpServers()
|
|
589
593
|
})
|
|
590
594
|
);
|
|
591
595
|
return result;
|
|
@@ -649,11 +653,11 @@ var Agent = class extends Server {
|
|
|
649
653
|
this.broadcast(
|
|
650
654
|
JSON.stringify({
|
|
651
655
|
type: "cf_agent_mcp_servers",
|
|
652
|
-
mcp: this.
|
|
656
|
+
mcp: this.getMcpServers()
|
|
653
657
|
})
|
|
654
658
|
);
|
|
655
659
|
}
|
|
656
|
-
|
|
660
|
+
getMcpServers() {
|
|
657
661
|
const mcpState = {
|
|
658
662
|
servers: {},
|
|
659
663
|
tools: this.mcp.listTools(),
|
|
@@ -668,7 +672,9 @@ var Agent = class extends Server {
|
|
|
668
672
|
name: server.name,
|
|
669
673
|
server_url: server.server_url,
|
|
670
674
|
auth_url: server.auth_url,
|
|
671
|
-
state: this.mcp.mcpConnections[server.id].connectionState
|
|
675
|
+
state: this.mcp.mcpConnections[server.id].connectionState,
|
|
676
|
+
instructions: this.mcp.mcpConnections[server.id].instructions ?? null,
|
|
677
|
+
capabilities: this.mcp.mcpConnections[server.id].serverCapabilities ?? null
|
|
672
678
|
};
|
|
673
679
|
}
|
|
674
680
|
return mcpState;
|
|
@@ -774,4 +780,4 @@ export {
|
|
|
774
780
|
getAgentByName,
|
|
775
781
|
StreamingResponse
|
|
776
782
|
};
|
|
777
|
-
//# sourceMappingURL=chunk-
|
|
783
|
+
//# sourceMappingURL=chunk-J6T74FUS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n Server,\n routePartykitRequest,\n type PartyServerOptions,\n getServerByName,\n type Connection,\n type ConnectionContext,\n type WSMessage,\n} from \"partyserver\";\n\nimport { parseCronExpression } from \"cron-schedule\";\nimport { nanoid } from \"nanoid\";\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { MCPClientManager } from \"./mcp/client\";\nimport {\n DurableObjectOAuthClientProvider,\n type AgentsOAuthProvider,\n} from \"./mcp/do-oauth-client-provider\";\nimport type {\n Tool,\n Resource,\n Prompt,\n ServerCapabilities,\n} from \"@modelcontextprotocol/sdk/types.js\";\n\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nimport { camelCaseToKebabCase } from \"./client\";\n\nexport type { Connection, WSMessage, ConnectionContext } 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 context: ClassMethodDecoratorContext\n ) {\n if (!callableMetadata.has(target)) {\n callableMetadata.set(target, metadata);\n }\n\n return target;\n };\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 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>;\n connection: Connection | undefined;\n request: Request | 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<unknown, CfProperties<unknown>> | undefined;\n} {\n const store = agentContext.getStore() as\n | {\n agent: T;\n connection: Connection | undefined;\n request: Request<unknown, CfProperties<unknown>> | undefined;\n }\n | undefined;\n if (!store) {\n return {\n agent: undefined,\n connection: undefined,\n request: undefined,\n };\n }\n return store;\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 * 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 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 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 },\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 type: \"cf_agent_mcp_servers\",\n mcp: this.getMcpServers(),\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 status: 200,\n headers: { \"content-type\": \"text/html\" },\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 },\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 const response: RPCResponse = {\n type: \"rpc\",\n id,\n success: true,\n result,\n done: true,\n };\n connection.send(JSON.stringify(response));\n } catch (e) {\n // Send error response\n const response: RPCResponse = {\n type: \"rpc\",\n id: parsed.id,\n success: false,\n error:\n e instanceof Error ? e.message : \"Unknown error occurred\",\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 },\n async () => {\n setTimeout(() => {\n if (this.state) {\n connection.send(\n JSON.stringify({\n type: \"cf_agent_state\",\n state: this.state,\n })\n );\n }\n\n connection.send(\n JSON.stringify({\n type: \"cf_agent_mcp_servers\",\n mcp: this.getMcpServers(),\n })\n );\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 { agent: this, connection: undefined, request: undefined },\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 using our saved auth information\n await 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 );\n\n this.broadcast(\n JSON.stringify({\n type: \"cf_agent_mcp_servers\",\n mcp: this.getMcpServers(),\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 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 type: \"cf_agent_state\",\n state: state,\n }),\n source !== \"server\" ? [source.id] : []\n );\n return this._tryCatch(() => {\n const { connection, request } = agentContext.getStore() || {};\n return agentContext.run(\n { agent: this, connection, request },\n async () => {\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 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\n * @param email Email message to process\n */\n onEmail(email: ForwardableEmailMessage) {\n return agentContext.run(\n { agent: this, connection: undefined, request: undefined },\n async () => {\n console.error(\"onEmail not implemented\");\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 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 * 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 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 return {\n id,\n callback: callback,\n payload: payload as T,\n time: timestamp,\n type: \"scheduled\",\n };\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 return {\n id,\n callback: callback,\n payload: payload as T,\n delayInSeconds: when,\n time: timestamp,\n type: \"delayed\",\n };\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 return {\n id,\n callback: callback,\n payload: payload as T,\n cron: when,\n time: timestamp,\n type: \"cron\",\n };\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 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 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 { agent: this, connection: undefined, request: undefined },\n async () => {\n try {\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 // 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\n // delete all alarms\n await this.ctx.storage.deleteAlarm();\n await this.ctx.storage.deleteAll();\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\n this.broadcast(\n JSON.stringify({\n type: \"cf_agent_mcp_servers\",\n mcp: this.getMcpServers(),\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<{ id: string; authUrl: string | undefined }> {\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 reconnect,\n transport: {\n ...headerTransportOpts,\n authProvider,\n },\n client: options?.client,\n });\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)\n VALUES (\n ${id},\n ${serverName},\n ${url},\n ${clientId ?? null},\n ${authUrl ?? null},\n ${callbackUrl},\n ${options ? JSON.stringify(options) : null}\n );\n `;\n\n return {\n id,\n authUrl,\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 type: \"cf_agent_mcp_servers\",\n mcp: this.getMcpServers(),\n })\n );\n }\n\n getMcpServers(): MCPServersState {\n const mcpState: MCPServersState = {\n servers: {},\n tools: this.mcp.listTools(),\n prompts: this.mcp.listPrompts(),\n resources: this.mcp.listResources(),\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 for (const server of servers) {\n mcpState.servers[server.id] = {\n name: server.name,\n server_url: server.server_url,\n auth_url: server.auth_url,\n state: this.mcp.mcpConnections[server.id].connectionState,\n instructions: this.mcp.mcpConnections[server.id].instructions ?? null,\n capabilities:\n this.mcp.mcpConnections[server.id].serverCapabilities ?? null,\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-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n \"Access-Control-Allow-Credentials\": \"true\",\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\n/**\n * Route an email to the appropriate Agent\n * @param email Email message to route\n * @param env Environment containing Agent bindings\n * @param options Routing options\n */\nexport async function routeAgentEmail<Env>(\n email: ForwardableEmailMessage,\n env: Env,\n options?: AgentOptions<Env>\n): Promise<void> {}\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 type: \"rpc\",\n id: this._id,\n success: true,\n result: chunk,\n done: false,\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 type: \"rpc\",\n id: this._id,\n success: true,\n result: finalChunk,\n done: true,\n };\n this._connection.send(JSON.stringify(response));\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,OAIK;AAEP,SAAS,2BAA2B;AACpC,SAAS,cAAc;AAEvB,SAAS,yBAAyB;AAgElC,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,oBACb,WAAW;AAEf;AAYA,IAAM,mBAAmB,oBAAI,IAAgC;AAMtD,SAAS,kBAAkB,WAA6B,CAAC,GAAG;AACjE,SAAO,SAAS,kBACd,QACA,SACA;AACA,QAAI,CAAC,iBAAiB,IAAI,MAAM,GAAG;AACjC,uBAAiB,IAAI,QAAQ,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C5B,MAAM;AAAA,MACN,IAAI,KAAK;AAAA,MACT,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,MAAM;AAAA,IACR;AACA,SAAK,YAAY,KAAK,KAAK,UAAU,QAAQ,CAAC;AAAA,EAChD;AACF;","names":["ctx","url"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { Server, Connection, PartyServerOptions } from "partyserver";
|
|
2
2
|
export { Connection, ConnectionContext, WSMessage } from "partyserver";
|
|
3
3
|
import { MCPClientManager } from "./mcp/client.js";
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
ServerCapabilities,
|
|
6
|
+
Tool,
|
|
7
|
+
Prompt,
|
|
8
|
+
Resource,
|
|
9
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
5
10
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
6
11
|
import "zod";
|
|
7
12
|
import "@modelcontextprotocol/sdk/client/sse.js";
|
|
@@ -123,6 +128,8 @@ type MCPServer = {
|
|
|
123
128
|
server_url: string;
|
|
124
129
|
auth_url: string | null;
|
|
125
130
|
state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
|
|
131
|
+
instructions: string | null;
|
|
132
|
+
capabilities: ServerCapabilities | null;
|
|
126
133
|
};
|
|
127
134
|
declare function getCurrentAgent<
|
|
128
135
|
T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
|
|
@@ -246,6 +253,10 @@ declare class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
246
253
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
247
254
|
*/
|
|
248
255
|
destroy(): Promise<void>;
|
|
256
|
+
/**
|
|
257
|
+
* Get all methods marked as callable on this Agent
|
|
258
|
+
* @returns A map of method names to their metadata
|
|
259
|
+
*/
|
|
249
260
|
private _isCallable;
|
|
250
261
|
/**
|
|
251
262
|
* Connect to a new MCP Server
|
|
@@ -297,7 +308,7 @@ declare class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
297
308
|
authUrl: string | undefined;
|
|
298
309
|
}>;
|
|
299
310
|
removeMcpServer(id: string): Promise<void>;
|
|
300
|
-
|
|
311
|
+
getMcpServers(): MCPServersState;
|
|
301
312
|
}
|
|
302
313
|
/**
|
|
303
314
|
* Namespace for creating Agent instances
|
package/dist/index.js
CHANGED
package/dist/mcp/index.js
CHANGED
package/dist/react.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { PartySocket } from "partysocket";
|
|
2
2
|
import { usePartySocket } from "partysocket/react";
|
|
3
|
-
import { MCPServersState } from "./index.js";
|
|
3
|
+
import { MCPServersState, Agent } from "./index.js";
|
|
4
4
|
import { StreamOptions } from "./client.js";
|
|
5
5
|
import "partyserver";
|
|
6
6
|
import "./mcp/client.js";
|
|
@@ -31,9 +31,38 @@ type UseAgentOptions<State = unknown> = Omit<
|
|
|
31
31
|
/** Called when MCP server state is updated */
|
|
32
32
|
onMcpUpdate?: (mcpServers: MCPServersState) => void;
|
|
33
33
|
};
|
|
34
|
+
type AllOptional<T> = T extends [infer A, ...infer R]
|
|
35
|
+
? undefined extends A
|
|
36
|
+
? AllOptional<R>
|
|
37
|
+
: false
|
|
38
|
+
: true;
|
|
39
|
+
type Method = (...args: any) => any;
|
|
40
|
+
type Methods<T> = {
|
|
41
|
+
[K in keyof T as T[K] extends Method ? K : never]: T[K];
|
|
42
|
+
};
|
|
43
|
+
type OptionalParametersMethod<T> = T extends Method
|
|
44
|
+
? AllOptional<Parameters<T>> extends true
|
|
45
|
+
? T
|
|
46
|
+
: never
|
|
47
|
+
: never;
|
|
48
|
+
type AgentMethods<T> = Omit<Methods<T>, keyof Agent<any, any>>;
|
|
49
|
+
type OptionalAgentMethods<T> = {
|
|
50
|
+
[K in keyof AgentMethods<T> as T[K] extends OptionalParametersMethod<T[K]>
|
|
51
|
+
? K
|
|
52
|
+
: never]: OptionalParametersMethod<T[K]>;
|
|
53
|
+
};
|
|
54
|
+
type RequiredAgentMethods<T> = Omit<
|
|
55
|
+
AgentMethods<T>,
|
|
56
|
+
keyof OptionalAgentMethods<T>
|
|
57
|
+
>;
|
|
58
|
+
type AgentPromiseReturnType<T extends AgentMethods<any>, K extends keyof T> =
|
|
59
|
+
ReturnType<T[K]> extends Promise<any>
|
|
60
|
+
? ReturnType<T[K]>
|
|
61
|
+
: Promise<ReturnType<T[K]>>;
|
|
34
62
|
/**
|
|
35
63
|
* React hook for connecting to an Agent
|
|
36
64
|
* @template State Type of the Agent's state
|
|
65
|
+
* @template Agent Type of the Agent
|
|
37
66
|
* @param options Connection options
|
|
38
67
|
* @returns WebSocket connection with setState and call methods
|
|
39
68
|
*/
|
|
@@ -49,5 +78,27 @@ declare function useAgent<State = unknown>(
|
|
|
49
78
|
streamOptions?: StreamOptions
|
|
50
79
|
) => Promise<T>;
|
|
51
80
|
};
|
|
81
|
+
declare function useAgent<
|
|
82
|
+
AgentT extends {
|
|
83
|
+
get state(): State;
|
|
84
|
+
},
|
|
85
|
+
State,
|
|
86
|
+
>(
|
|
87
|
+
options: UseAgentOptions<State>
|
|
88
|
+
): PartySocket & {
|
|
89
|
+
agent: string;
|
|
90
|
+
name: string;
|
|
91
|
+
setState: (state: State) => void;
|
|
92
|
+
call: (<T extends keyof OptionalAgentMethods<AgentT>>(
|
|
93
|
+
method: T,
|
|
94
|
+
args?: Parameters<OptionalAgentMethods<AgentT>[T]>,
|
|
95
|
+
streamOptions?: StreamOptions
|
|
96
|
+
) => AgentPromiseReturnType<AgentT, T>) &
|
|
97
|
+
(<T extends keyof RequiredAgentMethods<AgentT>>(
|
|
98
|
+
method: T,
|
|
99
|
+
args: Parameters<RequiredAgentMethods<AgentT>[T]>,
|
|
100
|
+
streamOptions?: StreamOptions
|
|
101
|
+
) => AgentPromiseReturnType<AgentT, T>);
|
|
102
|
+
};
|
|
52
103
|
|
|
53
104
|
export { type UseAgentOptions, useAgent };
|
package/dist/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react.tsx"],"sourcesContent":["import type { PartySocket } from \"partysocket\";\nimport { usePartySocket } from \"partysocket/react\";\nimport { useCallback, useRef } from \"react\";\nimport type { MCPServersState, RPCRequest, RPCResponse } from \"./\";\nimport type { StreamOptions } from \"./client\";\n\n/**\n * Convert a camelCase string to a kebab-case string\n * @param str The string to convert\n * @returns The kebab-case string\n */\nfunction camelCaseToKebabCase(str: string): string {\n // If string is all uppercase, convert to lowercase\n if (str === str.toUpperCase() && str !== str.toLowerCase()) {\n return str.toLowerCase().replace(/_/g, \"-\");\n }\n\n // Otherwise handle camelCase to kebab-case\n let kebabified = str.replace(\n /[A-Z]/g,\n (letter) => `-${letter.toLowerCase()}`\n );\n kebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n // Convert any remaining underscores to hyphens and remove trailing -'s\n return kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n\n/**\n * Options for the useAgent hook\n * @template State Type of the Agent's state\n */\nexport type UseAgentOptions<State = unknown> = Omit<\n Parameters<typeof usePartySocket>[0],\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n /** Called when the Agent's state is updated */\n onStateUpdate?: (state: State, source: \"server\" | \"client\") => void;\n /** Called when MCP server state is updated */\n onMcpUpdate?: (mcpServers: MCPServersState) => void;\n};\n\n/**\n * React hook for connecting to an Agent\n * @template State Type of the Agent's state\n * @param options Connection options\n * @returns WebSocket connection with setState and call methods\n */\nexport function useAgent<State = unknown>(\n options: UseAgentOptions<State>\n): PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: <T = unknown>(\n method: string,\n args?: unknown[],\n streamOptions?: StreamOptions\n ) => Promise<T>;\n} {\n const agentNamespace = camelCaseToKebabCase(options.agent);\n // Keep track of pending RPC calls\n const pendingCallsRef = useRef(\n new Map<\n string,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n stream?: StreamOptions;\n }\n >()\n );\n\n // TODO: if options.query is a function, then use\n // \"use()\" to get the value and pass it\n // as a query parameter to usePartySocket\n const agent = usePartySocket({\n prefix: \"agents\",\n party: agentNamespace,\n room: options.name || \"default\",\n ...options,\n onMessage: (message) => {\n if (typeof message.data === \"string\") {\n let parsedMessage: Record<string, unknown>;\n try {\n parsedMessage = JSON.parse(message.data);\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return options.onMessage?.(message);\n }\n if (parsedMessage.type === \"cf_agent_state\") {\n options.onStateUpdate?.(parsedMessage.state as State, \"server\");\n return;\n }\n if (parsedMessage.type === \"cf_agent_mcp_servers\") {\n options.onMcpUpdate?.(parsedMessage.mcp as MCPServersState);\n return;\n }\n if (parsedMessage.type === \"rpc\") {\n const response = parsedMessage as RPCResponse;\n const pending = pendingCallsRef.current.get(response.id);\n if (!pending) return;\n\n if (!response.success) {\n pending.reject(new Error(response.error));\n pendingCallsRef.current.delete(response.id);\n pending.stream?.onError?.(response.error);\n return;\n }\n\n // Handle streaming responses\n if (\"done\" in response) {\n if (response.done) {\n pending.resolve(response.result);\n pendingCallsRef.current.delete(response.id);\n pending.stream?.onDone?.(response.result);\n } else {\n pending.stream?.onChunk?.(response.result);\n }\n } else {\n // Non-streaming response\n pending.resolve(response.result);\n pendingCallsRef.current.delete(response.id);\n }\n return;\n }\n }\n options.onMessage?.(message);\n },\n }) as PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: <T = unknown>(\n method: string,\n args?: unknown[],\n streamOptions?: StreamOptions\n ) => Promise<T>;\n };\n // Create the call method\n const call = useCallback(\n <T = unknown,>(\n method: string,\n args: unknown[] = [],\n streamOptions?: StreamOptions\n ): Promise<T> => {\n return new Promise((resolve, reject) => {\n const id = Math.random().toString(36).slice(2);\n pendingCallsRef.current.set(id, {\n resolve: resolve as (value: unknown) => void,\n reject,\n stream: streamOptions,\n });\n\n const request: RPCRequest = {\n type: \"rpc\",\n id,\n method,\n args,\n };\n\n agent.send(JSON.stringify(request));\n });\n },\n [agent]\n );\n\n agent.setState = (state: State) => {\n agent.send(JSON.stringify({ type: \"cf_agent_state\", state }));\n options.onStateUpdate?.(state, \"client\");\n };\n\n agent.call = call;\n agent.agent = agentNamespace;\n agent.name = options.name || \"default\";\n\n // warn if agent isn't in lowercase\n if (agent.agent !== agent.agent.toLowerCase()) {\n console.warn(\n `Agent name: ${agent.agent} should probably be in lowercase. Received: ${agent.agent}`\n );\n }\n\n return agent;\n}\n"],"mappings":";AACA,SAAS,sBAAsB;AAC/B,SAAS,aAAa,cAAc;AASpC,SAAS,qBAAqB,KAAqB;AAEjD,MAAI,QAAQ,IAAI,YAAY,KAAK,QAAQ,IAAI,YAAY,GAAG;AAC1D,WAAO,IAAI,YAAY,EAAE,QAAQ,MAAM,GAAG;AAAA,EAC5C;AAGA,MAAI,aAAa,IAAI;AAAA,IACnB;AAAA,IACA,CAAC,WAAW,IAAI,OAAO,YAAY,CAAC;AAAA,EACtC;AACA,eAAa,WAAW,WAAW,GAAG,IAAI,WAAW,MAAM,CAAC,IAAI;AAEhE,SAAO,WAAW,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,EAAE;AACvD;AA0BO,SAAS,SACd,SAUA;AACA,QAAM,iBAAiB,qBAAqB,QAAQ,KAAK;AAEzD,QAAM,kBAAkB;AAAA,IACtB,oBAAI,IAOF;AAAA,EACJ;AAKA,QAAM,QAAQ,eAAe;AAAA,IAC3B,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,MAAM,QAAQ,QAAQ;AAAA,IACtB,GAAG;AAAA,IACH,WAAW,CAAC,YAAY;AACtB,UAAI,OAAO,QAAQ,SAAS,UAAU;AACpC,YAAI;AACJ,YAAI;AACF,0BAAgB,KAAK,MAAM,QAAQ,IAAI;AAAA,QACzC,SAAS,OAAO;AAGd,iBAAO,QAAQ,YAAY,OAAO;AAAA,QACpC;AACA,YAAI,cAAc,SAAS,kBAAkB;AAC3C,kBAAQ,gBAAgB,cAA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AAA,MACpC,CAAC;AAAA,IACH;AAAA,IACA,CAAC,KAAK;AAAA,EACR;AAEA,QAAM,WAAW,CAAC,UAAiB;AACjC,UAAM,KAAK,KAAK,UAAU,EAAE,MAAM,kBAAkB,MAAM,CAAC,CAAC;AAC5D,YAAQ,gBAAgB,OAAO,QAAQ;AAAA,EACzC;AAEA,QAAM,OAAO;AACb,QAAM,QAAQ;AACd,QAAM,OAAO,QAAQ,QAAQ;AAG7B,MAAI,MAAM,UAAU,MAAM,MAAM,YAAY,GAAG;AAC7C,YAAQ;AAAA,MACN,eAAe,MAAM,KAAK,+CAA+C,MAAM,KAAK;AAAA,IACtF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/react.tsx"],"sourcesContent":["import type { PartySocket } from \"partysocket\";\nimport { usePartySocket } from \"partysocket/react\";\nimport { useCallback, useRef } from \"react\";\nimport type { MCPServersState, RPCRequest, RPCResponse, Agent } from \"./\";\nimport type { StreamOptions } from \"./client\";\n\n/**\n * Convert a camelCase string to a kebab-case string\n * @param str The string to convert\n * @returns The kebab-case string\n */\nfunction camelCaseToKebabCase(str: string): string {\n // If string is all uppercase, convert to lowercase\n if (str === str.toUpperCase() && str !== str.toLowerCase()) {\n return str.toLowerCase().replace(/_/g, \"-\");\n }\n\n // Otherwise handle camelCase to kebab-case\n let kebabified = str.replace(\n /[A-Z]/g,\n (letter) => `-${letter.toLowerCase()}`\n );\n kebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n // Convert any remaining underscores to hyphens and remove trailing -'s\n return kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n\n/**\n * Options for the useAgent hook\n * @template State Type of the Agent's state\n */\nexport type UseAgentOptions<State = unknown> = Omit<\n Parameters<typeof usePartySocket>[0],\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n /** Called when the Agent's state is updated */\n onStateUpdate?: (state: State, source: \"server\" | \"client\") => void;\n /** Called when MCP server state is updated */\n onMcpUpdate?: (mcpServers: MCPServersState) => void;\n};\n\ntype AllOptional<T> = T extends [infer A, ...infer R]\n ? undefined extends A\n ? AllOptional<R>\n : false\n : true; // no params means optional by default\n\n// biome-ignore lint: suppressions/parse\ntype Method = (...args: any) => any;\n\ntype Methods<T> = {\n [K in keyof T as T[K] extends Method ? K : never]: T[K];\n};\n\ntype OptionalParametersMethod<T> = T extends Method\n ? AllOptional<Parameters<T>> extends true\n ? T\n : never\n : never;\n\n// all methods of the Agent, excluding the ones that are declared in the base Agent class\n// biome-ignore lint: suppressions/parse\ntype AgentMethods<T> = Omit<Methods<T>, keyof Agent<any, any>>;\n\ntype OptionalAgentMethods<T> = {\n [K in keyof AgentMethods<T> as T[K] extends OptionalParametersMethod<T[K]>\n ? K\n : never]: OptionalParametersMethod<T[K]>;\n};\n\ntype RequiredAgentMethods<T> = Omit<\n AgentMethods<T>,\n keyof OptionalAgentMethods<T>\n>;\n\n// biome-ignore lint: suppressions/parse\ntype AgentPromiseReturnType<T extends AgentMethods<any>, K extends keyof T> =\n // biome-ignore lint: suppressions/parse\n ReturnType<T[K]> extends Promise<any>\n ? ReturnType<T[K]>\n : Promise<ReturnType<T[K]>>;\n\n/**\n * React hook for connecting to an Agent\n * @template State Type of the Agent's state\n * @template Agent Type of the Agent\n * @param options Connection options\n * @returns WebSocket connection with setState and call methods\n */\nexport function useAgent<State = unknown>(\n options: UseAgentOptions<State>\n): PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: <T = unknown>(\n method: string,\n args?: unknown[],\n streamOptions?: StreamOptions\n ) => Promise<T>;\n};\nexport function useAgent<\n AgentT extends {\n get state(): State;\n },\n State,\n>(\n options: UseAgentOptions<State>\n): PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: (<T extends keyof OptionalAgentMethods<AgentT>>(\n method: T,\n args?: Parameters<OptionalAgentMethods<AgentT>[T]>,\n streamOptions?: StreamOptions\n ) => AgentPromiseReturnType<AgentT, T>) &\n (<T extends keyof RequiredAgentMethods<AgentT>>(\n method: T,\n args: Parameters<RequiredAgentMethods<AgentT>[T]>,\n streamOptions?: StreamOptions\n ) => AgentPromiseReturnType<AgentT, T>);\n};\nexport function useAgent<State>(\n options: UseAgentOptions<unknown>\n): PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: <T = unknown>(\n method: string,\n args?: unknown[],\n streamOptions?: StreamOptions\n ) => Promise<T>;\n} {\n const agentNamespace = camelCaseToKebabCase(options.agent);\n // Keep track of pending RPC calls\n const pendingCallsRef = useRef(\n new Map<\n string,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n stream?: StreamOptions;\n }\n >()\n );\n\n // TODO: if options.query is a function, then use\n // \"use()\" to get the value and pass it\n // as a query parameter to usePartySocket\n const agent = usePartySocket({\n prefix: \"agents\",\n party: agentNamespace,\n room: options.name || \"default\",\n ...options,\n onMessage: (message) => {\n if (typeof message.data === \"string\") {\n let parsedMessage: Record<string, unknown>;\n try {\n parsedMessage = JSON.parse(message.data);\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return options.onMessage?.(message);\n }\n if (parsedMessage.type === \"cf_agent_state\") {\n options.onStateUpdate?.(parsedMessage.state as State, \"server\");\n return;\n }\n if (parsedMessage.type === \"cf_agent_mcp_servers\") {\n options.onMcpUpdate?.(parsedMessage.mcp as MCPServersState);\n return;\n }\n if (parsedMessage.type === \"rpc\") {\n const response = parsedMessage as RPCResponse;\n const pending = pendingCallsRef.current.get(response.id);\n if (!pending) return;\n\n if (!response.success) {\n pending.reject(new Error(response.error));\n pendingCallsRef.current.delete(response.id);\n pending.stream?.onError?.(response.error);\n return;\n }\n\n // Handle streaming responses\n if (\"done\" in response) {\n if (response.done) {\n pending.resolve(response.result);\n pendingCallsRef.current.delete(response.id);\n pending.stream?.onDone?.(response.result);\n } else {\n pending.stream?.onChunk?.(response.result);\n }\n } else {\n // Non-streaming response\n pending.resolve(response.result);\n pendingCallsRef.current.delete(response.id);\n }\n return;\n }\n }\n options.onMessage?.(message);\n },\n }) as PartySocket & {\n agent: string;\n name: string;\n setState: (state: State) => void;\n call: <T = unknown>(\n method: string,\n args?: unknown[],\n streamOptions?: StreamOptions\n ) => Promise<T>;\n };\n // Create the call method\n const call = useCallback(\n <T = unknown,>(\n method: string,\n args: unknown[] = [],\n streamOptions?: StreamOptions\n ): Promise<T> => {\n return new Promise((resolve, reject) => {\n const id = Math.random().toString(36).slice(2);\n pendingCallsRef.current.set(id, {\n resolve: resolve as (value: unknown) => void,\n reject,\n stream: streamOptions,\n });\n\n const request: RPCRequest = {\n type: \"rpc\",\n id,\n method,\n args,\n };\n\n agent.send(JSON.stringify(request));\n });\n },\n [agent]\n );\n\n agent.setState = (state: State) => {\n agent.send(JSON.stringify({ type: \"cf_agent_state\", state }));\n options.onStateUpdate?.(state, \"client\");\n };\n\n agent.call = call;\n agent.agent = agentNamespace;\n agent.name = options.name || \"default\";\n\n // warn if agent isn't in lowercase\n if (agent.agent !== agent.agent.toLowerCase()) {\n console.warn(\n `Agent name: ${agent.agent} should probably be in lowercase. Received: ${agent.agent}`\n );\n }\n\n return agent;\n}\n"],"mappings":";AACA,SAAS,sBAAsB;AAC/B,SAAS,aAAa,cAAc;AASpC,SAAS,qBAAqB,KAAqB;AAEjD,MAAI,QAAQ,IAAI,YAAY,KAAK,QAAQ,IAAI,YAAY,GAAG;AAC1D,WAAO,IAAI,YAAY,EAAE,QAAQ,MAAM,GAAG;AAAA,EAC5C;AAGA,MAAI,aAAa,IAAI;AAAA,IACnB;AAAA,IACA,CAAC,WAAW,IAAI,OAAO,YAAY,CAAC;AAAA,EACtC;AACA,eAAa,WAAW,WAAW,GAAG,IAAI,WAAW,MAAM,CAAC,IAAI;AAEhE,SAAO,WAAW,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,EAAE;AACvD;AAsGO,SAAS,SACd,SAUA;AACA,QAAM,iB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AAAA,MACF;AACA,cAAQ,YAAY,OAAO;AAAA,IAC7B;AAAA,EACF,CAAC;AAWD,QAAM,OAAO;AAAA,IACX,CACE,QACA,OAAkB,CAAC,GACnB,kBACe;AACf,aAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,cAAM,KAAK,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC;AAC7C,wBAAgB,QAAQ,IAAI,IAAI;AAAA,UAC9B;AAAA,UACA;AAAA,UACA,QAAQ;AAAA,QACV,CAAC;AAED,cAAM,UAAsB;AAAA,UAC1B,MAAM;AAAA,UACN;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAEA,cAAM,KAAK,KAAK,UAAU,OAAO,CAAC;AAAA,MACpC,CAAC;AAAA,IACH;AAAA,IACA,CAAC,KAAK;AAAA,EACR;AAEA,QAAM,WAAW,CAAC,UAAiB;AACjC,UAAM,KAAK,KAAK,UAAU,EAAE,MAAM,kBAAkB,MAAM,CAAC,CAAC;AAC5D,YAAQ,gBAAgB,OAAO,QAAQ;AAAA,EACzC;AAEA,QAAM,OAAO;AACb,QAAM,QAAQ;AACd,QAAM,OAAO,QAAQ,QAAQ;AAG7B,MAAI,MAAM,UAAU,MAAM,MAAM,YAAY,GAAG;AAC7C,YAAQ;AAAA,MACN,eAAe,MAAM,KAAK,+CAA+C,MAAM,KAAK;AAAA,IACtF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agents",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.85",
|
|
4
4
|
"main": "src/index.ts",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"type": "module",
|
|
@@ -8,8 +8,9 @@
|
|
|
8
8
|
"check:test": "npm run check:test:workers && npm run check:test:react",
|
|
9
9
|
"check:test:workers": "vitest -r src/tests --watch false",
|
|
10
10
|
"check:test:react": "vitest -r src/react-tests --watch false",
|
|
11
|
-
"test": "vitest -r src/tests",
|
|
11
|
+
"test": "vitest -r src/tests && npm run test:types",
|
|
12
12
|
"test:react": "vitest -r src/react-tests",
|
|
13
|
+
"test:types": "tsc",
|
|
13
14
|
"evals": "(cd evals; evalite)",
|
|
14
15
|
"build": "tsx ./scripts/build.ts"
|
|
15
16
|
},
|
package/src/index.ts
CHANGED
|
@@ -21,6 +21,7 @@ import type {
|
|
|
21
21
|
Tool,
|
|
22
22
|
Resource,
|
|
23
23
|
Prompt,
|
|
24
|
+
ServerCapabilities,
|
|
24
25
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
25
26
|
|
|
26
27
|
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
@@ -112,7 +113,6 @@ export type CallableMetadata = {
|
|
|
112
113
|
streaming?: boolean;
|
|
113
114
|
};
|
|
114
115
|
|
|
115
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
116
116
|
const callableMetadata = new Map<Function, CallableMetadata>();
|
|
117
117
|
|
|
118
118
|
/**
|
|
@@ -195,6 +195,8 @@ export type MCPServer = {
|
|
|
195
195
|
server_url: string;
|
|
196
196
|
auth_url: string | null;
|
|
197
197
|
state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
|
|
198
|
+
instructions: string | null;
|
|
199
|
+
capabilities: ServerCapabilities | null;
|
|
198
200
|
};
|
|
199
201
|
|
|
200
202
|
/**
|
|
@@ -396,7 +398,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
396
398
|
this.broadcast(
|
|
397
399
|
JSON.stringify({
|
|
398
400
|
type: "cf_agent_mcp_servers",
|
|
399
|
-
mcp: this.
|
|
401
|
+
mcp: this.getMcpServers(),
|
|
400
402
|
})
|
|
401
403
|
);
|
|
402
404
|
|
|
@@ -448,7 +450,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
448
450
|
throw new Error(`Method ${method} is not callable`);
|
|
449
451
|
}
|
|
450
452
|
|
|
451
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
452
453
|
const metadata = callableMetadata.get(methodFn as Function);
|
|
453
454
|
|
|
454
455
|
// For streaming methods, pass a StreamingResponse object
|
|
@@ -508,7 +509,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
508
509
|
connection.send(
|
|
509
510
|
JSON.stringify({
|
|
510
511
|
type: "cf_agent_mcp_servers",
|
|
511
|
-
mcp: this.
|
|
512
|
+
mcp: this.getMcpServers(),
|
|
512
513
|
})
|
|
513
514
|
);
|
|
514
515
|
|
|
@@ -548,7 +549,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
548
549
|
this.broadcast(
|
|
549
550
|
JSON.stringify({
|
|
550
551
|
type: "cf_agent_mcp_servers",
|
|
551
|
-
mcp: this.
|
|
552
|
+
mcp: this.getMcpServers(),
|
|
552
553
|
})
|
|
553
554
|
);
|
|
554
555
|
|
|
@@ -914,8 +915,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
914
915
|
await this.ctx.storage.deleteAll();
|
|
915
916
|
}
|
|
916
917
|
|
|
918
|
+
/**
|
|
919
|
+
* Get all methods marked as callable on this Agent
|
|
920
|
+
* @returns A map of method names to their metadata
|
|
921
|
+
*/
|
|
917
922
|
private _isCallable(method: string): boolean {
|
|
918
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
919
923
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
920
924
|
}
|
|
921
925
|
|
|
@@ -952,7 +956,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
952
956
|
this.broadcast(
|
|
953
957
|
JSON.stringify({
|
|
954
958
|
type: "cf_agent_mcp_servers",
|
|
955
|
-
mcp: this.
|
|
959
|
+
mcp: this.getMcpServers(),
|
|
956
960
|
})
|
|
957
961
|
);
|
|
958
962
|
|
|
@@ -1049,12 +1053,12 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
1049
1053
|
this.broadcast(
|
|
1050
1054
|
JSON.stringify({
|
|
1051
1055
|
type: "cf_agent_mcp_servers",
|
|
1052
|
-
mcp: this.
|
|
1056
|
+
mcp: this.getMcpServers(),
|
|
1053
1057
|
})
|
|
1054
1058
|
);
|
|
1055
1059
|
}
|
|
1056
1060
|
|
|
1057
|
-
|
|
1061
|
+
getMcpServers(): MCPServersState {
|
|
1058
1062
|
const mcpState: MCPServersState = {
|
|
1059
1063
|
servers: {},
|
|
1060
1064
|
tools: this.mcp.listTools(),
|
|
@@ -1072,6 +1076,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
1072
1076
|
server_url: server.server_url,
|
|
1073
1077
|
auth_url: server.auth_url,
|
|
1074
1078
|
state: this.mcp.mcpConnections[server.id].connectionState,
|
|
1079
|
+
instructions: this.mcp.mcpConnections[server.id].instructions ?? null,
|
|
1080
|
+
capabilities:
|
|
1081
|
+
this.mcp.mcpConnections[server.id].serverCapabilities ?? null,
|
|
1075
1082
|
};
|
|
1076
1083
|
}
|
|
1077
1084
|
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n Server,\n routePartykitRequest,\n type PartyServerOptions,\n getServerByName,\n type Connection,\n type ConnectionContext,\n type WSMessage,\n} from \"partyserver\";\n\nimport { parseCronExpression } from \"cron-schedule\";\nimport { nanoid } from \"nanoid\";\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { MCPClientManager } from \"./mcp/client\";\nimport {\n DurableObjectOAuthClientProvider,\n type AgentsOAuthProvider,\n} from \"./mcp/do-oauth-client-provider\";\nimport type {\n Tool,\n Resource,\n Prompt,\n} from \"@modelcontextprotocol/sdk/types.js\";\n\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nimport { camelCaseToKebabCase } from \"./client\";\n\nexport type { Connection, WSMessage, ConnectionContext } 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\n// biome-ignore lint/complexity/noBannedTypes: <explanation>\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 context: ClassMethodDecoratorContext\n ) {\n if (!callableMetadata.has(target)) {\n callableMetadata.set(target, metadata);\n }\n\n return target;\n };\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 state: \"authenticating\" | \"connecting\" | \"ready\" | \"discovering\" | \"failed\";\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>;\n connection: Connection | undefined;\n request: Request | 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<unknown, CfProperties<unknown>> | undefined;\n} {\n const store = agentContext.getStore() as\n | {\n agent: T;\n connection: Connection | undefined;\n request: Request<unknown, CfProperties<unknown>> | undefined;\n }\n | undefined;\n if (!store) {\n return {\n agent: undefined,\n connection: undefined,\n request: undefined,\n };\n }\n return store;\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 * 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 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 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 },\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 type: \"cf_agent_mcp_servers\",\n mcp: this._getMcpServerStateInternal(),\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 status: 200,\n headers: { \"content-type\": \"text/html\" },\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 },\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 // biome-ignore lint/complexity/noBannedTypes: <explanation>\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 const response: RPCResponse = {\n type: \"rpc\",\n id,\n success: true,\n result,\n done: true,\n };\n connection.send(JSON.stringify(response));\n } catch (e) {\n // Send error response\n const response: RPCResponse = {\n type: \"rpc\",\n id: parsed.id,\n success: false,\n error:\n e instanceof Error ? e.message : \"Unknown error occurred\",\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 },\n async () => {\n setTimeout(() => {\n if (this.state) {\n connection.send(\n JSON.stringify({\n type: \"cf_agent_state\",\n state: this.state,\n })\n );\n }\n\n connection.send(\n JSON.stringify({\n type: \"cf_agent_mcp_servers\",\n mcp: this._getMcpServerStateInternal(),\n })\n );\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 { agent: this, connection: undefined, request: undefined },\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 using our saved auth information\n await 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 );\n\n this.broadcast(\n JSON.stringify({\n type: \"cf_agent_mcp_servers\",\n mcp: this._getMcpServerStateInternal(),\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 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 type: \"cf_agent_state\",\n state: state,\n }),\n source !== \"server\" ? [source.id] : []\n );\n return this._tryCatch(() => {\n const { connection, request } = agentContext.getStore() || {};\n return agentContext.run(\n { agent: this, connection, request },\n async () => {\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 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\n * @param email Email message to process\n */\n onEmail(email: ForwardableEmailMessage) {\n return agentContext.run(\n { agent: this, connection: undefined, request: undefined },\n async () => {\n console.error(\"onEmail not implemented\");\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 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 * 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 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 return {\n id,\n callback: callback,\n payload: payload as T,\n time: timestamp,\n type: \"scheduled\",\n };\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 return {\n id,\n callback: callback,\n payload: payload as T,\n delayInSeconds: when,\n time: timestamp,\n type: \"delayed\",\n };\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 return {\n id,\n callback: callback,\n payload: payload as T,\n cron: when,\n time: timestamp,\n type: \"cron\",\n };\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 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 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 { agent: this, connection: undefined, request: undefined },\n async () => {\n try {\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 // 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\n // delete all alarms\n await this.ctx.storage.deleteAlarm();\n await this.ctx.storage.deleteAll();\n }\n\n private _isCallable(method: string): boolean {\n // biome-ignore lint/complexity/noBannedTypes: <explanation>\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\n this.broadcast(\n JSON.stringify({\n type: \"cf_agent_mcp_servers\",\n mcp: this._getMcpServerStateInternal(),\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<{ id: string; authUrl: string | undefined }> {\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 reconnect,\n transport: {\n ...headerTransportOpts,\n authProvider,\n },\n client: options?.client,\n });\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)\n VALUES (\n ${id},\n ${serverName},\n ${url},\n ${clientId ?? null},\n ${authUrl ?? null},\n ${callbackUrl},\n ${options ? JSON.stringify(options) : null}\n );\n `;\n\n return {\n id,\n authUrl,\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 type: \"cf_agent_mcp_servers\",\n mcp: this._getMcpServerStateInternal(),\n })\n );\n }\n\n private _getMcpServerStateInternal(): MCPServersState {\n const mcpState: MCPServersState = {\n servers: {},\n tools: this.mcp.listTools(),\n prompts: this.mcp.listPrompts(),\n resources: this.mcp.listResources(),\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 for (const server of servers) {\n mcpState.servers[server.id] = {\n name: server.name,\n server_url: server.server_url,\n auth_url: server.auth_url,\n state: this.mcp.mcpConnections[server.id].connectionState,\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-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n \"Access-Control-Allow-Credentials\": \"true\",\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\n/**\n * Route an email to the appropriate Agent\n * @param email Email message to route\n * @param env Environment containing Agent bindings\n * @param options Routing options\n */\nexport async function routeAgentEmail<Env>(\n email: ForwardableEmailMessage,\n env: Env,\n options?: AgentOptions<Env>\n): Promise<void> {}\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 type: \"rpc\",\n id: this._id,\n success: true,\n result: chunk,\n done: false,\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 type: \"rpc\",\n id: this._id,\n success: true,\n result: finalChunk,\n done: true,\n };\n this._connection.send(JSON.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