agents 0.0.0-eb6827a → 0.0.0-ecf8926

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +131 -25
  2. package/dist/ai-chat-agent.d.ts +56 -6
  3. package/dist/ai-chat-agent.js +264 -94
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration.d.ts +152 -0
  6. package/dist/ai-chat-v5-migration.js +19 -0
  7. package/dist/ai-react.d.ts +71 -67
  8. package/dist/ai-react.js +193 -72
  9. package/dist/ai-react.js.map +1 -1
  10. package/dist/ai-types.d.ts +40 -18
  11. package/dist/ai-types.js +6 -0
  12. package/dist/chunk-AVYJQSLW.js +17 -0
  13. package/dist/chunk-AVYJQSLW.js.map +1 -0
  14. package/dist/chunk-DS7BJNPH.js +598 -0
  15. package/dist/chunk-DS7BJNPH.js.map +1 -0
  16. package/dist/chunk-EGCWEPQL.js +1290 -0
  17. package/dist/chunk-EGCWEPQL.js.map +1 -0
  18. package/dist/chunk-PVQZBKN7.js +106 -0
  19. package/dist/chunk-PVQZBKN7.js.map +1 -0
  20. package/dist/chunk-QEVM4BVL.js +116 -0
  21. package/dist/chunk-QEVM4BVL.js.map +1 -0
  22. package/dist/chunk-UJVEAURM.js +150 -0
  23. package/dist/chunk-UJVEAURM.js.map +1 -0
  24. package/dist/client-BAqDHqAV.d.ts +4601 -0
  25. package/dist/client.d.ts +16 -2
  26. package/dist/client.js +7 -133
  27. package/dist/client.js.map +1 -1
  28. package/dist/index.d.ts +268 -22
  29. package/dist/index.js +13 -4
  30. package/dist/mcp/client.d.ts +11 -0
  31. package/dist/mcp/client.js +9 -0
  32. package/dist/mcp/client.js.map +1 -0
  33. package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
  34. package/dist/mcp/do-oauth-client-provider.js +7 -0
  35. package/dist/mcp/do-oauth-client-provider.js.map +1 -0
  36. package/dist/mcp/index.d.ts +112 -0
  37. package/dist/mcp/index.js +956 -0
  38. package/dist/mcp/index.js.map +1 -0
  39. package/dist/observability/index.d.ts +46 -0
  40. package/dist/observability/index.js +11 -0
  41. package/dist/observability/index.js.map +1 -0
  42. package/dist/react.d.ts +89 -5
  43. package/dist/react.js +53 -32
  44. package/dist/react.js.map +1 -1
  45. package/dist/schedule.d.ts +6 -6
  46. package/dist/schedule.js +4 -6
  47. package/dist/schedule.js.map +1 -1
  48. package/dist/serializable.d.ts +32 -0
  49. package/dist/serializable.js +1 -0
  50. package/dist/serializable.js.map +1 -0
  51. package/package.json +92 -51
  52. package/src/index.ts +1222 -189
  53. package/dist/chunk-HMLY7DHA.js +0 -16
  54. package/dist/chunk-X6BBKLSC.js +0 -568
  55. package/dist/chunk-X6BBKLSC.js.map +0 -1
  56. package/dist/mcp.d.ts +0 -58
  57. package/dist/mcp.js +0 -945
  58. package/dist/mcp.js.map +0 -1
  59. /package/dist/{chunk-HMLY7DHA.js.map → ai-chat-v5-migration.js.map} +0 -0
package/src/index.ts CHANGED
@@ -1,19 +1,34 @@
1
+ import type { env } from "cloudflare:workers";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
+ import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
5
+
6
+ import type {
7
+ Prompt,
8
+ Resource,
9
+ ServerCapabilities,
10
+ Tool
11
+ } from "@modelcontextprotocol/sdk/types.js";
12
+ import { parseCronExpression } from "cron-schedule";
13
+ import { nanoid } from "nanoid";
14
+ import { EmailMessage } from "cloudflare:email";
1
15
  import {
2
- Server,
3
- routePartykitRequest,
4
- type PartyServerOptions,
5
- getServerByName,
6
16
  type Connection,
7
17
  type ConnectionContext,
18
+ type PartyServerOptions,
19
+ Server,
8
20
  type WSMessage,
21
+ getServerByName,
22
+ routePartykitRequest
9
23
  } from "partyserver";
24
+ import { camelCaseToKebabCase } from "./client";
25
+ import { MCPClientManager } from "./mcp/client";
26
+ // import type { MCPClientConnection } from "./mcp/client-connection";
27
+ import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
28
+ import { genericObservability, type Observability } from "./observability";
29
+ import { MessageType } from "./ai-types";
10
30
 
11
- import { parseCronExpression } from "cron-schedule";
12
- import { nanoid } from "nanoid";
13
-
14
- export type { Connection, WSMessage, ConnectionContext } from "partyserver";
15
-
16
- import { WorkflowEntrypoint as CFWorkflowEntrypoint } from "cloudflare:workers";
31
+ export type { Connection, ConnectionContext, WSMessage } from "partyserver";
17
32
 
18
33
  /**
19
34
  * RPC request message from client
@@ -29,7 +44,7 @@ export type RPCRequest = {
29
44
  * State update message from client
30
45
  */
31
46
  export type StateUpdateMessage = {
32
- type: "cf_agent_state";
47
+ type: MessageType.CF_AGENT_STATE;
33
48
  state: unknown;
34
49
  };
35
50
 
@@ -37,7 +52,7 @@ export type StateUpdateMessage = {
37
52
  * RPC response message to client
38
53
  */
39
54
  export type RPCResponse = {
40
- type: "rpc";
55
+ type: MessageType.RPC;
41
56
  id: string;
42
57
  } & (
43
58
  | {
@@ -64,7 +79,7 @@ function isRPCRequest(msg: unknown): msg is RPCRequest {
64
79
  typeof msg === "object" &&
65
80
  msg !== null &&
66
81
  "type" in msg &&
67
- msg.type === "rpc" &&
82
+ msg.type === MessageType.RPC &&
68
83
  "id" in msg &&
69
84
  typeof msg.id === "string" &&
70
85
  "method" in msg &&
@@ -82,7 +97,7 @@ function isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {
82
97
  typeof msg === "object" &&
83
98
  msg !== null &&
84
99
  "type" in msg &&
85
- msg.type === "cf_agent_state" &&
100
+ msg.type === MessageType.CF_AGENT_STATE &&
86
101
  "state" in msg
87
102
  );
88
103
  }
@@ -97,7 +112,6 @@ export type CallableMetadata = {
97
112
  streaming?: boolean;
98
113
  };
99
114
 
100
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
101
115
  const callableMetadata = new Map<Function, CallableMetadata>();
102
116
 
103
117
  /**
@@ -107,6 +121,7 @@ const callableMetadata = new Map<Function, CallableMetadata>();
107
121
  export function unstable_callable(metadata: CallableMetadata = {}) {
108
122
  return function callableDecorator<This, Args extends unknown[], Return>(
109
123
  target: (this: This, ...args: Args) => Return,
124
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: later
110
125
  context: ClassMethodDecoratorContext
111
126
  ) {
112
127
  if (!callableMetadata.has(target)) {
@@ -117,10 +132,12 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
117
132
  };
118
133
  }
119
134
 
120
- /**
121
- * A class for creating workflow entry points that can be used with Cloudflare Workers
122
- */
123
- export class WorkflowEntrypoint extends CFWorkflowEntrypoint {}
135
+ export type QueueItem<T = string> = {
136
+ id: string;
137
+ payload: T;
138
+ callback: keyof Agent<unknown>;
139
+ created_at: number;
140
+ };
124
141
 
125
142
  /**
126
143
  * Represents a scheduled task within an Agent
@@ -163,18 +180,118 @@ function getNextCronTime(cron: string) {
163
180
  return interval.getNextDate();
164
181
  }
165
182
 
183
+ /**
184
+ * MCP Server state update message from server -> Client
185
+ */
186
+ export type MCPServerMessage = {
187
+ type: MessageType.CF_AGENT_MCP_SERVERS;
188
+ mcp: MCPServersState;
189
+ };
190
+
191
+ export type MCPServersState = {
192
+ servers: {
193
+ [id: string]: MCPServer;
194
+ };
195
+ tools: Tool[];
196
+ prompts: Prompt[];
197
+ resources: Resource[];
198
+ };
199
+
200
+ export type MCPServer = {
201
+ name: string;
202
+ server_url: string;
203
+ auth_url: string | null;
204
+ // This state is specifically about the temporary process of getting a token (if needed).
205
+ // Scope outside of that can't be relied upon because when the DO sleeps, there's no way
206
+ // to communicate a change to a non-ready state.
207
+ state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
208
+ instructions: string | null;
209
+ capabilities: ServerCapabilities | null;
210
+ };
211
+
212
+ /**
213
+ * MCP Server data stored in DO SQL for resuming MCP Server connections
214
+ */
215
+ type MCPServerRow = {
216
+ id: string;
217
+ name: string;
218
+ server_url: string;
219
+ client_id: string | null;
220
+ auth_url: string | null;
221
+ callback_url: string;
222
+ server_options: string;
223
+ };
224
+
166
225
  const STATE_ROW_ID = "cf_state_row_id";
167
226
  const STATE_WAS_CHANGED = "cf_state_was_changed";
168
227
 
169
228
  const DEFAULT_STATE = {} as unknown;
170
229
 
230
+ const agentContext = new AsyncLocalStorage<{
231
+ agent: Agent<unknown, unknown>;
232
+ connection: Connection | undefined;
233
+ request: Request | undefined;
234
+ email: AgentEmail | undefined;
235
+ }>();
236
+
237
+ export function getCurrentAgent<
238
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>
239
+ >(): {
240
+ agent: T | undefined;
241
+ connection: Connection | undefined;
242
+ request: Request | undefined;
243
+ email: AgentEmail | undefined;
244
+ } {
245
+ const store = agentContext.getStore() as
246
+ | {
247
+ agent: T;
248
+ connection: Connection | undefined;
249
+ request: Request | undefined;
250
+ email: AgentEmail | undefined;
251
+ }
252
+ | undefined;
253
+ if (!store) {
254
+ return {
255
+ agent: undefined,
256
+ connection: undefined,
257
+ request: undefined,
258
+ email: undefined
259
+ };
260
+ }
261
+ return store;
262
+ }
263
+
264
+ /**
265
+ * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
266
+ * @param agent The agent instance
267
+ * @param method The method to wrap
268
+ * @returns A wrapped method that runs within the agent context
269
+ */
270
+
271
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
272
+ function withAgentContext<T extends (...args: any[]) => any>(
273
+ method: T
274
+ ): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {
275
+ return function (...args: Parameters<T>): ReturnType<T> {
276
+ const { connection, request, email } = getCurrentAgent();
277
+ return agentContext.run({ agent: this, connection, request, email }, () => {
278
+ return method.apply(this, args);
279
+ });
280
+ };
281
+ }
282
+
171
283
  /**
172
284
  * Base class for creating Agent implementations
173
285
  * @template Env Environment type containing bindings
174
286
  * @template State State type to store within the Agent
175
287
  */
176
- export class Agent<Env, State = unknown> extends Server<Env> {
177
- #state = DEFAULT_STATE as State;
288
+ export class Agent<Env = typeof env, State = unknown> extends Server<Env> {
289
+ private _state = DEFAULT_STATE as State;
290
+
291
+ private _ParentClass: typeof Agent<Env, State> =
292
+ Object.getPrototypeOf(this).constructor;
293
+
294
+ mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
178
295
 
179
296
  /**
180
297
  * Initial state for the Agent
@@ -186,9 +303,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
186
303
  * Current state of the Agent
187
304
  */
188
305
  get state(): State {
189
- if (this.#state !== DEFAULT_STATE) {
306
+ if (this._state !== DEFAULT_STATE) {
190
307
  // state was previously set, and populated internal state
191
- return this.#state;
308
+ return this._state;
192
309
  }
193
310
  // looks like this is the first time the state is being accessed
194
311
  // check if the state was set in a previous life
@@ -208,8 +325,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
208
325
  ) {
209
326
  const state = result[0]?.state as string; // could be null?
210
327
 
211
- this.#state = JSON.parse(state);
212
- return this.#state;
328
+ this._state = JSON.parse(state);
329
+ return this._state;
213
330
  }
214
331
 
215
332
  // ok, this is the first time the state is being accessed
@@ -230,9 +347,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
230
347
  */
231
348
  static options = {
232
349
  /** Whether the Agent should hibernate when inactive */
233
- hibernate: true, // default to hibernate
350
+ hibernate: true // default to hibernate
234
351
  };
235
352
 
353
+ /**
354
+ * The observability implementation to use for the Agent
355
+ */
356
+ observability?: Observability = genericObservability;
357
+
236
358
  /**
237
359
  * Execute SQL queries against the Agent's database
238
360
  * @template T Type of the returned rows
@@ -262,6 +384,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
262
384
  constructor(ctx: AgentContext, env: Env) {
263
385
  super(ctx, env);
264
386
 
387
+ // Auto-wrap custom methods with agent context
388
+ this._autoWrapCustomMethods();
389
+
265
390
  this.sql`
266
391
  CREATE TABLE IF NOT EXISTS cf_agents_state (
267
392
  id TEXT PRIMARY KEY NOT NULL,
@@ -269,8 +394,17 @@ export class Agent<Env, State = unknown> extends Server<Env> {
269
394
  )
270
395
  `;
271
396
 
397
+ this.sql`
398
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
399
+ id TEXT PRIMARY KEY NOT NULL,
400
+ payload TEXT,
401
+ callback TEXT,
402
+ created_at INTEGER DEFAULT (unixepoch())
403
+ )
404
+ `;
405
+
272
406
  void this.ctx.blockConcurrencyWhile(async () => {
273
- return this.#tryCatch(async () => {
407
+ return this._tryCatch(async () => {
274
408
  // Create alarms table if it doesn't exist
275
409
  this.sql`
276
410
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
@@ -290,96 +424,251 @@ export class Agent<Env, State = unknown> extends Server<Env> {
290
424
  });
291
425
  });
292
426
 
293
- const _onMessage = this.onMessage.bind(this);
294
- this.onMessage = async (connection: Connection, message: WSMessage) => {
295
- if (typeof message !== "string") {
296
- return this.#tryCatch(() => _onMessage(connection, message));
297
- }
298
-
299
- let parsed: unknown;
300
- try {
301
- parsed = JSON.parse(message);
302
- } catch (e) {
303
- // silently fail and let the onMessage handler handle it
304
- return this.#tryCatch(() => _onMessage(connection, message));
305
- }
427
+ this.sql`
428
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
429
+ id TEXT PRIMARY KEY NOT NULL,
430
+ name TEXT NOT NULL,
431
+ server_url TEXT NOT NULL,
432
+ callback_url TEXT NOT NULL,
433
+ client_id TEXT,
434
+ auth_url TEXT,
435
+ server_options TEXT
436
+ )
437
+ `;
306
438
 
307
- if (isStateUpdateMessage(parsed)) {
308
- this.#setStateInternal(parsed.state as State, connection);
309
- return;
310
- }
439
+ const _onRequest = this.onRequest.bind(this);
440
+ this.onRequest = (request: Request) => {
441
+ return agentContext.run(
442
+ { agent: this, connection: undefined, request, email: undefined },
443
+ async () => {
444
+ if (this.mcp.isCallbackRequest(request)) {
445
+ await this.mcp.handleCallbackRequest(request);
446
+
447
+ // after the MCP connection handshake, we can send updated mcp state
448
+ this.broadcast(
449
+ JSON.stringify({
450
+ mcp: this.getMcpServers(),
451
+ type: MessageType.CF_AGENT_MCP_SERVERS
452
+ })
453
+ );
454
+
455
+ // We probably should let the user configure this response/redirect, but this is fine for now.
456
+ return new Response("<script>window.close();</script>", {
457
+ headers: { "content-type": "text/html" },
458
+ status: 200
459
+ });
460
+ }
311
461
 
312
- if (isRPCRequest(parsed)) {
313
- try {
314
- const { id, method, args } = parsed;
462
+ return this._tryCatch(() => _onRequest(request));
463
+ }
464
+ );
465
+ };
315
466
 
316
- // Check if method exists and is callable
317
- const methodFn = this[method as keyof this];
318
- if (typeof methodFn !== "function") {
319
- throw new Error(`Method ${method} does not exist`);
467
+ const _onMessage = this.onMessage.bind(this);
468
+ this.onMessage = async (connection: Connection, message: WSMessage) => {
469
+ return agentContext.run(
470
+ { agent: this, connection, request: undefined, email: undefined },
471
+ async () => {
472
+ if (typeof message !== "string") {
473
+ return this._tryCatch(() => _onMessage(connection, message));
320
474
  }
321
475
 
322
- if (!this.#isCallable(method)) {
323
- throw new Error(`Method ${method} is not callable`);
476
+ let parsed: unknown;
477
+ try {
478
+ parsed = JSON.parse(message);
479
+ } catch (_e) {
480
+ // silently fail and let the onMessage handler handle it
481
+ return this._tryCatch(() => _onMessage(connection, message));
324
482
  }
325
483
 
326
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
327
- const metadata = callableMetadata.get(methodFn as Function);
484
+ if (isStateUpdateMessage(parsed)) {
485
+ this._setStateInternal(parsed.state as State, connection);
486
+ return;
487
+ }
328
488
 
329
- // For streaming methods, pass a StreamingResponse object
330
- if (metadata?.streaming) {
331
- const stream = new StreamingResponse(connection, id);
332
- await methodFn.apply(this, [stream, ...args]);
489
+ if (isRPCRequest(parsed)) {
490
+ try {
491
+ const { id, method, args } = parsed;
492
+
493
+ // Check if method exists and is callable
494
+ const methodFn = this[method as keyof this];
495
+ if (typeof methodFn !== "function") {
496
+ throw new Error(`Method ${method} does not exist`);
497
+ }
498
+
499
+ if (!this._isCallable(method)) {
500
+ throw new Error(`Method ${method} is not callable`);
501
+ }
502
+
503
+ const metadata = callableMetadata.get(methodFn as Function);
504
+
505
+ // For streaming methods, pass a StreamingResponse object
506
+ if (metadata?.streaming) {
507
+ const stream = new StreamingResponse(connection, id);
508
+ await methodFn.apply(this, [stream, ...args]);
509
+ return;
510
+ }
511
+
512
+ // For regular methods, execute and send response
513
+ const result = await methodFn.apply(this, args);
514
+
515
+ this.observability?.emit(
516
+ {
517
+ displayMessage: `RPC call to ${method}`,
518
+ id: nanoid(),
519
+ payload: {
520
+ method,
521
+ streaming: metadata?.streaming
522
+ },
523
+ timestamp: Date.now(),
524
+ type: "rpc"
525
+ },
526
+ this.ctx
527
+ );
528
+
529
+ const response: RPCResponse = {
530
+ done: true,
531
+ id,
532
+ result,
533
+ success: true,
534
+ type: MessageType.RPC
535
+ };
536
+ connection.send(JSON.stringify(response));
537
+ } catch (e) {
538
+ // Send error response
539
+ const response: RPCResponse = {
540
+ error:
541
+ e instanceof Error ? e.message : "Unknown error occurred",
542
+ id: parsed.id,
543
+ success: false,
544
+ type: MessageType.RPC
545
+ };
546
+ connection.send(JSON.stringify(response));
547
+ console.error("RPC error:", e);
548
+ }
333
549
  return;
334
550
  }
335
551
 
336
- // For regular methods, execute and send response
337
- const result = await methodFn.apply(this, args);
338
- const response: RPCResponse = {
339
- type: "rpc",
340
- id,
341
- success: true,
342
- result,
343
- done: true,
344
- };
345
- connection.send(JSON.stringify(response));
346
- } catch (e) {
347
- // Send error response
348
- const response: RPCResponse = {
349
- type: "rpc",
350
- id: parsed.id,
351
- success: false,
352
- error: e instanceof Error ? e.message : "Unknown error occurred",
353
- };
354
- connection.send(JSON.stringify(response));
355
- console.error("RPC error:", e);
552
+ return this._tryCatch(() => _onMessage(connection, message));
356
553
  }
357
- return;
358
- }
359
-
360
- return this.#tryCatch(() => _onMessage(connection, message));
554
+ );
361
555
  };
362
556
 
363
557
  const _onConnect = this.onConnect.bind(this);
364
558
  this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
365
559
  // TODO: This is a hack to ensure the state is sent after the connection is established
366
560
  // must fix this
367
- setTimeout(() => {
368
- if (this.state) {
369
- connection.send(
370
- JSON.stringify({
371
- type: "cf_agent_state",
372
- state: this.state,
373
- })
374
- );
561
+ return agentContext.run(
562
+ { agent: this, connection, request: ctx.request, email: undefined },
563
+ async () => {
564
+ setTimeout(() => {
565
+ if (this.state) {
566
+ connection.send(
567
+ JSON.stringify({
568
+ state: this.state,
569
+ type: MessageType.CF_AGENT_STATE
570
+ })
571
+ );
572
+ }
573
+
574
+ connection.send(
575
+ JSON.stringify({
576
+ mcp: this.getMcpServers(),
577
+ type: MessageType.CF_AGENT_MCP_SERVERS
578
+ })
579
+ );
580
+
581
+ this.observability?.emit(
582
+ {
583
+ displayMessage: "Connection established",
584
+ id: nanoid(),
585
+ payload: {
586
+ connectionId: connection.id
587
+ },
588
+ timestamp: Date.now(),
589
+ type: "connect"
590
+ },
591
+ this.ctx
592
+ );
593
+ return this._tryCatch(() => _onConnect(connection, ctx));
594
+ }, 20);
595
+ }
596
+ );
597
+ };
598
+
599
+ const _onStart = this.onStart.bind(this);
600
+ this.onStart = async () => {
601
+ return agentContext.run(
602
+ {
603
+ agent: this,
604
+ connection: undefined,
605
+ request: undefined,
606
+ email: undefined
607
+ },
608
+ async () => {
609
+ await this._tryCatch(() => {
610
+ const servers = this.sql<MCPServerRow>`
611
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
612
+ `;
613
+
614
+ this.broadcast(
615
+ JSON.stringify({
616
+ mcp: this.getMcpServers(),
617
+ type: MessageType.CF_AGENT_MCP_SERVERS
618
+ })
619
+ );
620
+
621
+ // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
622
+ if (servers && Array.isArray(servers) && servers.length > 0) {
623
+ servers.forEach((server) => {
624
+ this._connectToMcpServerInternal(
625
+ server.name,
626
+ server.server_url,
627
+ server.callback_url,
628
+ server.server_options
629
+ ? JSON.parse(server.server_options)
630
+ : undefined,
631
+ {
632
+ id: server.id,
633
+ oauthClientId: server.client_id ?? undefined
634
+ }
635
+ )
636
+ .then(() => {
637
+ // Broadcast updated MCP servers state after each server connects
638
+ this.broadcast(
639
+ JSON.stringify({
640
+ mcp: this.getMcpServers(),
641
+ type: MessageType.CF_AGENT_MCP_SERVERS
642
+ })
643
+ );
644
+ })
645
+ .catch((error) => {
646
+ console.error(
647
+ `Error connecting to MCP server: ${server.name} (${server.server_url})`,
648
+ error
649
+ );
650
+ // Still broadcast even if connection fails, so clients know about the failure
651
+ this.broadcast(
652
+ JSON.stringify({
653
+ mcp: this.getMcpServers(),
654
+ type: MessageType.CF_AGENT_MCP_SERVERS
655
+ })
656
+ );
657
+ });
658
+ });
659
+ }
660
+ return _onStart();
661
+ });
375
662
  }
376
- return this.#tryCatch(() => _onConnect(connection, ctx));
377
- }, 20);
663
+ );
378
664
  };
379
665
  }
380
666
 
381
- #setStateInternal(state: State, source: Connection | "server" = "server") {
382
- this.#state = state;
667
+ private _setStateInternal(
668
+ state: State,
669
+ source: Connection | "server" = "server"
670
+ ) {
671
+ this._state = state;
383
672
  this.sql`
384
673
  INSERT OR REPLACE INTO cf_agents_state (id, state)
385
674
  VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
@@ -390,12 +679,30 @@ export class Agent<Env, State = unknown> extends Server<Env> {
390
679
  `;
391
680
  this.broadcast(
392
681
  JSON.stringify({
393
- type: "cf_agent_state",
394
682
  state: state,
683
+ type: MessageType.CF_AGENT_STATE
395
684
  }),
396
685
  source !== "server" ? [source.id] : []
397
686
  );
398
- return this.#tryCatch(() => this.onStateUpdate(state, source));
687
+ return this._tryCatch(() => {
688
+ const { connection, request, email } = agentContext.getStore() || {};
689
+ return agentContext.run(
690
+ { agent: this, connection, request, email },
691
+ async () => {
692
+ this.observability?.emit(
693
+ {
694
+ displayMessage: "State updated",
695
+ id: nanoid(),
696
+ payload: {},
697
+ timestamp: Date.now(),
698
+ type: "state:update"
699
+ },
700
+ this.ctx
701
+ );
702
+ return this.onStateUpdate(state, source);
703
+ }
704
+ );
705
+ });
399
706
  }
400
707
 
401
708
  /**
@@ -403,7 +710,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
403
710
  * @param state New state to set
404
711
  */
405
712
  setState(state: State) {
406
- this.#setStateInternal(state, "server");
713
+ this._setStateInternal(state, "server");
407
714
  }
408
715
 
409
716
  /**
@@ -411,19 +718,90 @@ export class Agent<Env, State = unknown> extends Server<Env> {
411
718
  * @param state Updated state
412
719
  * @param source Source of the state update ("server" or a client connection)
413
720
  */
721
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
414
722
  onStateUpdate(state: State | undefined, source: Connection | "server") {
415
723
  // override this to handle state updates
416
724
  }
417
725
 
418
726
  /**
419
- * Called when the Agent receives an email
727
+ * Called when the Agent receives an email via routeAgentEmail()
728
+ * Override this method to handle incoming emails
420
729
  * @param email Email message to process
421
730
  */
422
- onEmail(email: ForwardableEmailMessage) {
423
- throw new Error("Not implemented");
731
+ async _onEmail(email: AgentEmail) {
732
+ // nb: we use this roundabout way of getting to onEmail
733
+ // because of https://github.com/cloudflare/workerd/issues/4499
734
+ return agentContext.run(
735
+ { agent: this, connection: undefined, request: undefined, email: email },
736
+ async () => {
737
+ if ("onEmail" in this && typeof this.onEmail === "function") {
738
+ return this._tryCatch(() =>
739
+ (this.onEmail as (email: AgentEmail) => Promise<void>)(email)
740
+ );
741
+ } else {
742
+ console.log("Received email from:", email.from, "to:", email.to);
743
+ console.log("Subject:", email.headers.get("subject"));
744
+ console.log(
745
+ "Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
746
+ );
747
+ }
748
+ }
749
+ );
750
+ }
751
+
752
+ /**
753
+ * Reply to an email
754
+ * @param email The email to reply to
755
+ * @param options Options for the reply
756
+ * @returns void
757
+ */
758
+ async replyToEmail(
759
+ email: AgentEmail,
760
+ options: {
761
+ fromName: string;
762
+ subject?: string | undefined;
763
+ body: string;
764
+ contentType?: string;
765
+ headers?: Record<string, string>;
766
+ }
767
+ ): Promise<void> {
768
+ return this._tryCatch(async () => {
769
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
770
+ const agentId = this.name;
771
+
772
+ const { createMimeMessage } = await import("mimetext");
773
+ const msg = createMimeMessage();
774
+ msg.setSender({ addr: email.to, name: options.fromName });
775
+ msg.setRecipient(email.from);
776
+ msg.setSubject(
777
+ options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
778
+ );
779
+ msg.addMessage({
780
+ contentType: options.contentType || "text/plain",
781
+ data: options.body
782
+ });
783
+
784
+ const domain = email.from.split("@")[1];
785
+ const messageId = `<${agentId}@${domain}>`;
786
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID")!);
787
+ msg.setHeader("Message-ID", messageId);
788
+ msg.setHeader("X-Agent-Name", agentName);
789
+ msg.setHeader("X-Agent-ID", agentId);
790
+
791
+ if (options.headers) {
792
+ for (const [key, value] of Object.entries(options.headers)) {
793
+ msg.setHeader(key, value);
794
+ }
795
+ }
796
+ await email.reply({
797
+ from: email.to,
798
+ raw: msg.asRaw(),
799
+ to: email.from
800
+ });
801
+ });
424
802
  }
425
803
 
426
- async #tryCatch<T>(fn: () => T | Promise<T>) {
804
+ private async _tryCatch<T>(fn: () => T | Promise<T>) {
427
805
  try {
428
806
  return await fn();
429
807
  } catch (e) {
@@ -431,6 +809,72 @@ export class Agent<Env, State = unknown> extends Server<Env> {
431
809
  }
432
810
  }
433
811
 
812
+ /**
813
+ * Automatically wrap custom methods with agent context
814
+ * This ensures getCurrentAgent() works in all custom methods without decorators
815
+ */
816
+ private _autoWrapCustomMethods() {
817
+ // Collect all methods from base prototypes (Agent and Server)
818
+ const basePrototypes = [Agent.prototype, Server.prototype];
819
+ const baseMethods = new Set<string>();
820
+ for (const baseProto of basePrototypes) {
821
+ let proto = baseProto;
822
+ while (proto && proto !== Object.prototype) {
823
+ const methodNames = Object.getOwnPropertyNames(proto);
824
+ for (const methodName of methodNames) {
825
+ baseMethods.add(methodName);
826
+ }
827
+ proto = Object.getPrototypeOf(proto);
828
+ }
829
+ }
830
+ // Get all methods from the current instance's prototype chain
831
+ let proto = Object.getPrototypeOf(this);
832
+ let depth = 0;
833
+ while (proto && proto !== Object.prototype && depth < 10) {
834
+ const methodNames = Object.getOwnPropertyNames(proto);
835
+ for (const methodName of methodNames) {
836
+ // Skip if it's a private method or not a function
837
+ if (
838
+ baseMethods.has(methodName) ||
839
+ methodName.startsWith("_") ||
840
+ typeof this[methodName as keyof this] !== "function"
841
+ ) {
842
+ continue;
843
+ }
844
+ // If the method doesn't exist in base prototypes, it's a custom method
845
+ if (!baseMethods.has(methodName)) {
846
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
847
+ if (descriptor && typeof descriptor.value === "function") {
848
+ // Wrap the custom method with context
849
+
850
+ const wrappedFunction = withAgentContext(
851
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
852
+ this[methodName as keyof this] as (...args: any[]) => any
853
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
854
+ ) as any;
855
+
856
+ // if the method is callable, copy the metadata from the original method
857
+ if (this._isCallable(methodName)) {
858
+ callableMetadata.set(
859
+ wrappedFunction,
860
+ callableMetadata.get(
861
+ this[methodName as keyof this] as Function
862
+ )!
863
+ );
864
+ }
865
+
866
+ // set the wrapped function on the prototype
867
+ this.constructor.prototype[methodName as keyof this] =
868
+ wrappedFunction;
869
+ }
870
+ }
871
+ }
872
+
873
+ proto = Object.getPrototypeOf(proto);
874
+ depth++;
875
+ }
876
+ }
877
+
434
878
  override onError(
435
879
  connection: Connection,
436
880
  error: unknown
@@ -465,6 +909,131 @@ export class Agent<Env, State = unknown> extends Server<Env> {
465
909
  throw new Error("Not implemented");
466
910
  }
467
911
 
912
+ /**
913
+ * Queue a task to be executed in the future
914
+ * @param payload Payload to pass to the callback
915
+ * @param callback Name of the method to call
916
+ * @returns The ID of the queued task
917
+ */
918
+ async queue<T = unknown>(callback: keyof this, payload: T): Promise<string> {
919
+ const id = nanoid(9);
920
+ if (typeof callback !== "string") {
921
+ throw new Error("Callback must be a string");
922
+ }
923
+
924
+ if (typeof this[callback] !== "function") {
925
+ throw new Error(`this.${callback} is not a function`);
926
+ }
927
+
928
+ this.sql`
929
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
930
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
931
+ `;
932
+
933
+ void this._flushQueue().catch((e) => {
934
+ console.error("Error flushing queue:", e);
935
+ });
936
+
937
+ return id;
938
+ }
939
+
940
+ private _flushingQueue = false;
941
+
942
+ private async _flushQueue() {
943
+ if (this._flushingQueue) {
944
+ return;
945
+ }
946
+ this._flushingQueue = true;
947
+ while (true) {
948
+ const result = this.sql<QueueItem<string>>`
949
+ SELECT * FROM cf_agents_queues
950
+ ORDER BY created_at ASC
951
+ `;
952
+
953
+ if (!result || result.length === 0) {
954
+ break;
955
+ }
956
+
957
+ for (const row of result || []) {
958
+ const callback = this[row.callback as keyof Agent<Env>];
959
+ if (!callback) {
960
+ console.error(`callback ${row.callback} not found`);
961
+ continue;
962
+ }
963
+ const { connection, request, email } = agentContext.getStore() || {};
964
+ await agentContext.run(
965
+ {
966
+ agent: this,
967
+ connection,
968
+ request,
969
+ email
970
+ },
971
+ async () => {
972
+ // TODO: add retries and backoff
973
+ await (
974
+ callback as (
975
+ payload: unknown,
976
+ queueItem: QueueItem<string>
977
+ ) => Promise<void>
978
+ ).bind(this)(JSON.parse(row.payload as string), row);
979
+ await this.dequeue(row.id);
980
+ }
981
+ );
982
+ }
983
+ }
984
+ this._flushingQueue = false;
985
+ }
986
+
987
+ /**
988
+ * Dequeue a task by ID
989
+ * @param id ID of the task to dequeue
990
+ */
991
+ async dequeue(id: string) {
992
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
993
+ }
994
+
995
+ /**
996
+ * Dequeue all tasks
997
+ */
998
+ async dequeueAll() {
999
+ this.sql`DELETE FROM cf_agents_queues`;
1000
+ }
1001
+
1002
+ /**
1003
+ * Dequeue all tasks by callback
1004
+ * @param callback Name of the callback to dequeue
1005
+ */
1006
+ async dequeueAllByCallback(callback: string) {
1007
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
1008
+ }
1009
+
1010
+ /**
1011
+ * Get a queued task by ID
1012
+ * @param id ID of the task to get
1013
+ * @returns The task or undefined if not found
1014
+ */
1015
+ async getQueue(id: string): Promise<QueueItem<string> | undefined> {
1016
+ const result = this.sql<QueueItem<string>>`
1017
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
1018
+ `;
1019
+ return result
1020
+ ? { ...result[0], payload: JSON.parse(result[0].payload) }
1021
+ : undefined;
1022
+ }
1023
+
1024
+ /**
1025
+ * Get all queues by key and value
1026
+ * @param key Key to filter by
1027
+ * @param value Value to filter by
1028
+ * @returns Array of matching QueueItem objects
1029
+ */
1030
+ async getQueues(key: string, value: string): Promise<QueueItem<string>[]> {
1031
+ const result = this.sql<QueueItem<string>>`
1032
+ SELECT * FROM cf_agents_queues
1033
+ `;
1034
+ return result.filter((row) => JSON.parse(row.payload)[key] === value);
1035
+ }
1036
+
468
1037
  /**
469
1038
  * Schedule a task to be executed in the future
470
1039
  * @template T Type of the payload data
@@ -480,6 +1049,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
480
1049
  ): Promise<Schedule<T>> {
481
1050
  const id = nanoid(9);
482
1051
 
1052
+ const emitScheduleCreate = (schedule: Schedule<T>) =>
1053
+ this.observability?.emit(
1054
+ {
1055
+ displayMessage: `Schedule ${schedule.id} created`,
1056
+ id: nanoid(),
1057
+ payload: {
1058
+ callback: callback as string,
1059
+ id: id
1060
+ },
1061
+ timestamp: Date.now(),
1062
+ type: "schedule:create"
1063
+ },
1064
+ this.ctx
1065
+ );
1066
+
483
1067
  if (typeof callback !== "string") {
484
1068
  throw new Error("Callback must be a string");
485
1069
  }
@@ -497,15 +1081,19 @@ export class Agent<Env, State = unknown> extends Server<Env> {
497
1081
  )}, 'scheduled', ${timestamp})
498
1082
  `;
499
1083
 
500
- await this.#scheduleNextAlarm();
1084
+ await this._scheduleNextAlarm();
501
1085
 
502
- return {
503
- id,
1086
+ const schedule: Schedule<T> = {
504
1087
  callback: callback,
1088
+ id,
505
1089
  payload: payload as T,
506
1090
  time: timestamp,
507
- type: "scheduled",
1091
+ type: "scheduled"
508
1092
  };
1093
+
1094
+ emitScheduleCreate(schedule);
1095
+
1096
+ return schedule;
509
1097
  }
510
1098
  if (typeof when === "number") {
511
1099
  const time = new Date(Date.now() + when * 1000);
@@ -518,16 +1106,20 @@ export class Agent<Env, State = unknown> extends Server<Env> {
518
1106
  )}, 'delayed', ${when}, ${timestamp})
519
1107
  `;
520
1108
 
521
- await this.#scheduleNextAlarm();
1109
+ await this._scheduleNextAlarm();
522
1110
 
523
- return {
524
- id,
1111
+ const schedule: Schedule<T> = {
525
1112
  callback: callback,
526
- payload: payload as T,
527
1113
  delayInSeconds: when,
1114
+ id,
1115
+ payload: payload as T,
528
1116
  time: timestamp,
529
- type: "delayed",
1117
+ type: "delayed"
530
1118
  };
1119
+
1120
+ emitScheduleCreate(schedule);
1121
+
1122
+ return schedule;
531
1123
  }
532
1124
  if (typeof when === "string") {
533
1125
  const nextExecutionTime = getNextCronTime(when);
@@ -540,16 +1132,20 @@ export class Agent<Env, State = unknown> extends Server<Env> {
540
1132
  )}, 'cron', ${when}, ${timestamp})
541
1133
  `;
542
1134
 
543
- await this.#scheduleNextAlarm();
1135
+ await this._scheduleNextAlarm();
544
1136
 
545
- return {
546
- id,
1137
+ const schedule: Schedule<T> = {
547
1138
  callback: callback,
548
- payload: payload as T,
549
1139
  cron: when,
1140
+ id,
1141
+ payload: payload as T,
550
1142
  time: timestamp,
551
- type: "cron",
1143
+ type: "cron"
552
1144
  };
1145
+
1146
+ emitScheduleCreate(schedule);
1147
+
1148
+ return schedule;
553
1149
  }
554
1150
  throw new Error("Invalid schedule type");
555
1151
  }
@@ -580,7 +1176,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
580
1176
  */
581
1177
  getSchedules<T = string>(
582
1178
  criteria: {
583
- description?: string;
584
1179
  id?: string;
585
1180
  type?: "scheduled" | "delayed" | "cron";
586
1181
  timeRange?: { start?: Date; end?: Date };
@@ -594,11 +1189,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
594
1189
  params.push(criteria.id);
595
1190
  }
596
1191
 
597
- if (criteria.description) {
598
- query += " AND description = ?";
599
- params.push(criteria.description);
600
- }
601
-
602
1192
  if (criteria.type) {
603
1193
  query += " AND type = ?";
604
1194
  params.push(criteria.type);
@@ -619,7 +1209,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
619
1209
  .toArray()
620
1210
  .map((row) => ({
621
1211
  ...row,
622
- payload: JSON.parse(row.payload as string) as T,
1212
+ payload: JSON.parse(row.payload as string) as T
623
1213
  })) as Schedule<T>[];
624
1214
 
625
1215
  return result;
@@ -631,18 +1221,34 @@ export class Agent<Env, State = unknown> extends Server<Env> {
631
1221
  * @returns true if the task was cancelled, false otherwise
632
1222
  */
633
1223
  async cancelSchedule(id: string): Promise<boolean> {
1224
+ const schedule = await this.getSchedule(id);
1225
+ if (schedule) {
1226
+ this.observability?.emit(
1227
+ {
1228
+ displayMessage: `Schedule ${id} cancelled`,
1229
+ id: nanoid(),
1230
+ payload: {
1231
+ callback: schedule.callback,
1232
+ id: schedule.id
1233
+ },
1234
+ timestamp: Date.now(),
1235
+ type: "schedule:cancel"
1236
+ },
1237
+ this.ctx
1238
+ );
1239
+ }
634
1240
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
635
1241
 
636
- await this.#scheduleNextAlarm();
1242
+ await this._scheduleNextAlarm();
637
1243
  return true;
638
1244
  }
639
1245
 
640
- async #scheduleNextAlarm() {
1246
+ private async _scheduleNextAlarm() {
641
1247
  // Find the next schedule that needs to be executed
642
1248
  const result = this.sql`
643
- SELECT time FROM cf_agents_schedules
1249
+ SELECT time FROM cf_agents_schedules
644
1250
  WHERE time > ${Math.floor(Date.now() / 1000)}
645
- ORDER BY time ASC
1251
+ ORDER BY time ASC
646
1252
  LIMIT 1
647
1253
  `;
648
1254
  if (!result) return;
@@ -654,10 +1260,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
654
1260
  }
655
1261
 
656
1262
  /**
657
- * Method called when an alarm fires
658
- * Executes any scheduled tasks that are due
1263
+ * Method called when an alarm fires.
1264
+ * Executes any scheduled tasks that are due.
1265
+ *
1266
+ * @remarks
1267
+ * To schedule a task, please use the `this.schedule` method instead.
1268
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
659
1269
  */
660
- async alarm() {
1270
+ public readonly alarm = async () => {
661
1271
  const now = Math.floor(Date.now() / 1000);
662
1272
 
663
1273
  // Get all schedules that should be executed now
@@ -665,41 +1275,67 @@ export class Agent<Env, State = unknown> extends Server<Env> {
665
1275
  SELECT * FROM cf_agents_schedules WHERE time <= ${now}
666
1276
  `;
667
1277
 
668
- for (const row of result || []) {
669
- const callback = this[row.callback as keyof Agent<Env>];
670
- if (!callback) {
671
- console.error(`callback ${row.callback} not found`);
672
- continue;
673
- }
674
- try {
675
- await (
676
- callback as (
677
- payload: unknown,
678
- schedule: Schedule<unknown>
679
- ) => Promise<void>
680
- ).bind(this)(JSON.parse(row.payload as string), row);
681
- } catch (e) {
682
- console.error(`error executing callback "${row.callback}"`, e);
683
- }
684
- if (row.type === "cron") {
685
- // Update next execution time for cron schedules
686
- const nextExecutionTime = getNextCronTime(row.cron);
687
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1278
+ if (result && Array.isArray(result)) {
1279
+ for (const row of result) {
1280
+ const callback = this[row.callback as keyof Agent<Env>];
1281
+ if (!callback) {
1282
+ console.error(`callback ${row.callback} not found`);
1283
+ continue;
1284
+ }
1285
+ await agentContext.run(
1286
+ {
1287
+ agent: this,
1288
+ connection: undefined,
1289
+ request: undefined,
1290
+ email: undefined
1291
+ },
1292
+ async () => {
1293
+ try {
1294
+ this.observability?.emit(
1295
+ {
1296
+ displayMessage: `Schedule ${row.id} executed`,
1297
+ id: nanoid(),
1298
+ payload: {
1299
+ callback: row.callback,
1300
+ id: row.id
1301
+ },
1302
+ timestamp: Date.now(),
1303
+ type: "schedule:execute"
1304
+ },
1305
+ this.ctx
1306
+ );
1307
+
1308
+ await (
1309
+ callback as (
1310
+ payload: unknown,
1311
+ schedule: Schedule<unknown>
1312
+ ) => Promise<void>
1313
+ ).bind(this)(JSON.parse(row.payload as string), row);
1314
+ } catch (e) {
1315
+ console.error(`error executing callback "${row.callback}"`, e);
1316
+ }
1317
+ }
1318
+ );
1319
+ if (row.type === "cron") {
1320
+ // Update next execution time for cron schedules
1321
+ const nextExecutionTime = getNextCronTime(row.cron);
1322
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
688
1323
 
689
- this.sql`
1324
+ this.sql`
690
1325
  UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
691
1326
  `;
692
- } else {
693
- // Delete one-time schedules after execution
694
- this.sql`
1327
+ } else {
1328
+ // Delete one-time schedules after execution
1329
+ this.sql`
695
1330
  DELETE FROM cf_agents_schedules WHERE id = ${row.id}
696
1331
  `;
1332
+ }
697
1333
  }
698
1334
  }
699
1335
 
700
1336
  // Schedule the next alarm
701
- await this.#scheduleNextAlarm();
702
- }
1337
+ await this._scheduleNextAlarm();
1338
+ };
703
1339
 
704
1340
  /**
705
1341
  * Destroy the Agent, removing all state and scheduled tasks
@@ -708,20 +1344,203 @@ export class Agent<Env, State = unknown> extends Server<Env> {
708
1344
  // drop all tables
709
1345
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
710
1346
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
1347
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
1348
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
711
1349
 
712
1350
  // delete all alarms
713
1351
  await this.ctx.storage.deleteAlarm();
714
1352
  await this.ctx.storage.deleteAll();
1353
+ this.ctx.abort("destroyed"); // enforce that the agent is evicted
1354
+
1355
+ this.observability?.emit(
1356
+ {
1357
+ displayMessage: "Agent destroyed",
1358
+ id: nanoid(),
1359
+ payload: {},
1360
+ timestamp: Date.now(),
1361
+ type: "destroy"
1362
+ },
1363
+ this.ctx
1364
+ );
715
1365
  }
716
1366
 
717
1367
  /**
718
1368
  * Get all methods marked as callable on this Agent
719
1369
  * @returns A map of method names to their metadata
720
1370
  */
721
- #isCallable(method: string): boolean {
722
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
1371
+ private _isCallable(method: string): boolean {
723
1372
  return callableMetadata.has(this[method as keyof this] as Function);
724
1373
  }
1374
+
1375
+ /**
1376
+ * Connect to a new MCP Server
1377
+ *
1378
+ * @param url MCP Server SSE URL
1379
+ * @param callbackHost Base host for the agent, used for the redirect URI.
1380
+ * @param agentsPrefix agents routing prefix if not using `agents`
1381
+ * @param options MCP client and transport (header) options
1382
+ * @returns authUrl
1383
+ */
1384
+ async addMcpServer(
1385
+ serverName: string,
1386
+ url: string,
1387
+ callbackHost: string,
1388
+ agentsPrefix = "agents",
1389
+ options?: {
1390
+ client?: ConstructorParameters<typeof Client>[1];
1391
+ transport?: {
1392
+ headers: HeadersInit;
1393
+ };
1394
+ }
1395
+ ): Promise<{ id: string; authUrl: string | undefined }> {
1396
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
1397
+
1398
+ const result = await this._connectToMcpServerInternal(
1399
+ serverName,
1400
+ url,
1401
+ callbackUrl,
1402
+ options
1403
+ );
1404
+ this.sql`
1405
+ INSERT
1406
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1407
+ VALUES (
1408
+ ${result.id},
1409
+ ${serverName},
1410
+ ${url},
1411
+ ${result.clientId ?? null},
1412
+ ${result.authUrl ?? null},
1413
+ ${callbackUrl},
1414
+ ${options ? JSON.stringify(options) : null}
1415
+ );
1416
+ `;
1417
+
1418
+ this.broadcast(
1419
+ JSON.stringify({
1420
+ mcp: this.getMcpServers(),
1421
+ type: MessageType.CF_AGENT_MCP_SERVERS
1422
+ })
1423
+ );
1424
+
1425
+ return result;
1426
+ }
1427
+
1428
+ async _connectToMcpServerInternal(
1429
+ _serverName: string,
1430
+ url: string,
1431
+ callbackUrl: string,
1432
+ // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
1433
+ options?: {
1434
+ client?: ConstructorParameters<typeof Client>[1];
1435
+ /**
1436
+ * We don't expose the normal set of transport options because:
1437
+ * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
1438
+ * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
1439
+ *
1440
+ * 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).
1441
+ */
1442
+ transport?: {
1443
+ headers?: HeadersInit;
1444
+ };
1445
+ },
1446
+ reconnect?: {
1447
+ id: string;
1448
+ oauthClientId?: string;
1449
+ }
1450
+ ): Promise<{
1451
+ id: string;
1452
+ authUrl: string | undefined;
1453
+ clientId: string | undefined;
1454
+ }> {
1455
+ const authProvider = new DurableObjectOAuthClientProvider(
1456
+ this.ctx.storage,
1457
+ this.name,
1458
+ callbackUrl
1459
+ );
1460
+
1461
+ if (reconnect) {
1462
+ authProvider.serverId = reconnect.id;
1463
+ if (reconnect.oauthClientId) {
1464
+ authProvider.clientId = reconnect.oauthClientId;
1465
+ }
1466
+ }
1467
+
1468
+ // allows passing through transport headers if necessary
1469
+ // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
1470
+ let headerTransportOpts: SSEClientTransportOptions = {};
1471
+ if (options?.transport?.headers) {
1472
+ headerTransportOpts = {
1473
+ eventSourceInit: {
1474
+ fetch: (url, init) =>
1475
+ fetch(url, {
1476
+ ...init,
1477
+ headers: options?.transport?.headers
1478
+ })
1479
+ },
1480
+ requestInit: {
1481
+ headers: options?.transport?.headers
1482
+ }
1483
+ };
1484
+ }
1485
+
1486
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
1487
+ client: options?.client,
1488
+ reconnect,
1489
+ transport: {
1490
+ ...headerTransportOpts,
1491
+ authProvider
1492
+ }
1493
+ });
1494
+
1495
+ return {
1496
+ authUrl,
1497
+ clientId,
1498
+ id
1499
+ };
1500
+ }
1501
+
1502
+ async removeMcpServer(id: string) {
1503
+ this.mcp.closeConnection(id);
1504
+ this.sql`
1505
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1506
+ `;
1507
+ this.broadcast(
1508
+ JSON.stringify({
1509
+ mcp: this.getMcpServers(),
1510
+ type: MessageType.CF_AGENT_MCP_SERVERS
1511
+ })
1512
+ );
1513
+ }
1514
+
1515
+ getMcpServers(): MCPServersState {
1516
+ const mcpState: MCPServersState = {
1517
+ prompts: this.mcp.listPrompts(),
1518
+ resources: this.mcp.listResources(),
1519
+ servers: {},
1520
+ tools: this.mcp.listTools()
1521
+ };
1522
+
1523
+ const servers = this.sql<MCPServerRow>`
1524
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1525
+ `;
1526
+
1527
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1528
+ for (const server of servers) {
1529
+ const serverConn = this.mcp.mcpConnections[server.id];
1530
+ mcpState.servers[server.id] = {
1531
+ auth_url: server.auth_url,
1532
+ capabilities: serverConn?.serverCapabilities ?? null,
1533
+ instructions: serverConn?.instructions ?? null,
1534
+ name: server.name,
1535
+ server_url: server.server_url,
1536
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1537
+ state: serverConn?.connectionState ?? "authenticating"
1538
+ };
1539
+ }
1540
+ }
1541
+
1542
+ return mcpState;
1543
+ }
725
1544
  }
726
1545
 
727
1546
  /**
@@ -761,17 +1580,17 @@ export async function routeAgentRequest<Env>(
761
1580
  const corsHeaders =
762
1581
  options?.cors === true
763
1582
  ? {
764
- "Access-Control-Allow-Origin": "*",
765
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
766
1583
  "Access-Control-Allow-Credentials": "true",
767
- "Access-Control-Max-Age": "86400",
1584
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1585
+ "Access-Control-Allow-Origin": "*",
1586
+ "Access-Control-Max-Age": "86400"
768
1587
  }
769
1588
  : options?.cors;
770
1589
 
771
1590
  if (request.method === "OPTIONS") {
772
1591
  if (corsHeaders) {
773
1592
  return new Response(null, {
774
- headers: corsHeaders,
1593
+ headers: corsHeaders
775
1594
  });
776
1595
  }
777
1596
  console.warn(
@@ -784,7 +1603,7 @@ export async function routeAgentRequest<Env>(
784
1603
  env as Record<string, unknown>,
785
1604
  {
786
1605
  prefix: "agents",
787
- ...(options as PartyServerOptions<Record<string, unknown>>),
1606
+ ...(options as PartyServerOptions<Record<string, unknown>>)
788
1607
  }
789
1608
  );
790
1609
 
@@ -797,24 +1616,238 @@ export async function routeAgentRequest<Env>(
797
1616
  response = new Response(response.body, {
798
1617
  headers: {
799
1618
  ...response.headers,
800
- ...corsHeaders,
801
- },
1619
+ ...corsHeaders
1620
+ }
802
1621
  });
803
1622
  }
804
1623
  return response;
805
1624
  }
806
1625
 
1626
+ export type EmailResolver<Env> = (
1627
+ email: ForwardableEmailMessage,
1628
+ env: Env
1629
+ ) => Promise<{
1630
+ agentName: string;
1631
+ agentId: string;
1632
+ } | null>;
1633
+
1634
+ /**
1635
+ * Create a resolver that uses the message-id header to determine the agent to route the email to
1636
+ * @returns A function that resolves the agent to route the email to
1637
+ */
1638
+ export function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {
1639
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1640
+ const messageId = email.headers.get("message-id");
1641
+ if (messageId) {
1642
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1643
+ if (messageIdMatch) {
1644
+ const [, agentId, domain] = messageIdMatch;
1645
+ const agentName = domain.split(".")[0];
1646
+ return { agentName, agentId };
1647
+ }
1648
+ }
1649
+
1650
+ const references = email.headers.get("references");
1651
+ if (references) {
1652
+ const referencesMatch = references.match(
1653
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1654
+ );
1655
+ if (referencesMatch) {
1656
+ const [, base64Id, domain] = referencesMatch;
1657
+ const agentId = Buffer.from(base64Id, "base64").toString("hex");
1658
+ const agentName = domain.split(".")[0];
1659
+ return { agentName, agentId };
1660
+ }
1661
+ }
1662
+
1663
+ const agentName = email.headers.get("x-agent-name");
1664
+ const agentId = email.headers.get("x-agent-id");
1665
+ if (agentName && agentId) {
1666
+ return { agentName, agentId };
1667
+ }
1668
+
1669
+ return null;
1670
+ };
1671
+ }
1672
+
1673
+ /**
1674
+ * Create a resolver that uses the email address to determine the agent to route the email to
1675
+ * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
1676
+ * @returns A function that resolves the agent to route the email to
1677
+ */
1678
+ export function createAddressBasedEmailResolver<Env>(
1679
+ defaultAgentName: string
1680
+ ): EmailResolver<Env> {
1681
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1682
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1683
+ if (!emailMatch) {
1684
+ return null;
1685
+ }
1686
+
1687
+ const [, localPart, subAddress] = emailMatch;
1688
+
1689
+ if (subAddress) {
1690
+ return {
1691
+ agentName: localPart,
1692
+ agentId: subAddress
1693
+ };
1694
+ }
1695
+
1696
+ // Option 2: Use defaultAgentName namespace, localPart as agentId
1697
+ // Common for catch-all email routing to a single EmailAgent namespace
1698
+ return {
1699
+ agentName: defaultAgentName,
1700
+ agentId: localPart
1701
+ };
1702
+ };
1703
+ }
1704
+
1705
+ /**
1706
+ * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
1707
+ * @param agentName The name of the agent to route the email to
1708
+ * @param agentId The id of the agent to route the email to
1709
+ * @returns A function that resolves the agent to route the email to
1710
+ */
1711
+ export function createCatchAllEmailResolver<Env>(
1712
+ agentName: string,
1713
+ agentId: string
1714
+ ): EmailResolver<Env> {
1715
+ return async () => ({ agentName, agentId });
1716
+ }
1717
+
1718
+ export type EmailRoutingOptions<Env> = AgentOptions<Env> & {
1719
+ resolver: EmailResolver<Env>;
1720
+ };
1721
+
1722
+ // Cache the agent namespace map for email routing
1723
+ // This maps both kebab-case and original names to namespaces
1724
+ const agentMapCache = new WeakMap<
1725
+ Record<string, unknown>,
1726
+ Record<string, unknown>
1727
+ >();
1728
+
807
1729
  /**
808
1730
  * Route an email to the appropriate Agent
809
- * @param email Email message to route
810
- * @param env Environment containing Agent bindings
811
- * @param options Routing options
1731
+ * @param email The email to route
1732
+ * @param env The environment containing the Agent bindings
1733
+ * @param options The options for routing the email
1734
+ * @returns A promise that resolves when the email has been routed
812
1735
  */
813
1736
  export async function routeAgentEmail<Env>(
814
1737
  email: ForwardableEmailMessage,
815
1738
  env: Env,
816
- options?: AgentOptions<Env>
817
- ): Promise<void> {}
1739
+ options: EmailRoutingOptions<Env>
1740
+ ): Promise<void> {
1741
+ const routingInfo = await options.resolver(email, env);
1742
+
1743
+ if (!routingInfo) {
1744
+ console.warn("No routing information found for email, dropping message");
1745
+ return;
1746
+ }
1747
+
1748
+ // Build a map that includes both original names and kebab-case versions
1749
+ if (!agentMapCache.has(env as Record<string, unknown>)) {
1750
+ const map: Record<string, unknown> = {};
1751
+ for (const [key, value] of Object.entries(env as Record<string, unknown>)) {
1752
+ if (
1753
+ value &&
1754
+ typeof value === "object" &&
1755
+ "idFromName" in value &&
1756
+ typeof value.idFromName === "function"
1757
+ ) {
1758
+ // Add both the original name and kebab-case version
1759
+ map[key] = value;
1760
+ map[camelCaseToKebabCase(key)] = value;
1761
+ }
1762
+ }
1763
+ agentMapCache.set(env as Record<string, unknown>, map);
1764
+ }
1765
+
1766
+ const agentMap = agentMapCache.get(env as Record<string, unknown>)!;
1767
+ const namespace = agentMap[routingInfo.agentName];
1768
+
1769
+ if (!namespace) {
1770
+ // Provide helpful error message listing available agents
1771
+ const availableAgents = Object.keys(agentMap)
1772
+ .filter((key) => !key.includes("-")) // Show only original names, not kebab-case duplicates
1773
+ .join(", ");
1774
+ throw new Error(
1775
+ `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
1776
+ );
1777
+ }
1778
+
1779
+ const agent = await getAgentByName(
1780
+ namespace as unknown as AgentNamespace<Agent<Env>>,
1781
+ routingInfo.agentId
1782
+ );
1783
+
1784
+ // let's make a serialisable version of the email
1785
+ const serialisableEmail: AgentEmail = {
1786
+ getRaw: async () => {
1787
+ const reader = email.raw.getReader();
1788
+ const chunks: Uint8Array[] = [];
1789
+
1790
+ let done = false;
1791
+ while (!done) {
1792
+ const { value, done: readerDone } = await reader.read();
1793
+ done = readerDone;
1794
+ if (value) {
1795
+ chunks.push(value);
1796
+ }
1797
+ }
1798
+
1799
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1800
+ const combined = new Uint8Array(totalLength);
1801
+ let offset = 0;
1802
+ for (const chunk of chunks) {
1803
+ combined.set(chunk, offset);
1804
+ offset += chunk.length;
1805
+ }
1806
+
1807
+ return combined;
1808
+ },
1809
+ headers: email.headers,
1810
+ rawSize: email.rawSize,
1811
+ setReject: (reason: string) => {
1812
+ email.setReject(reason);
1813
+ },
1814
+ forward: (rcptTo: string, headers?: Headers) => {
1815
+ return email.forward(rcptTo, headers);
1816
+ },
1817
+ reply: (options: { from: string; to: string; raw: string }) => {
1818
+ return email.reply(
1819
+ new EmailMessage(options.from, options.to, options.raw)
1820
+ );
1821
+ },
1822
+ from: email.from,
1823
+ to: email.to
1824
+ };
1825
+
1826
+ await agent._onEmail(serialisableEmail);
1827
+ }
1828
+
1829
+ export type AgentEmail = {
1830
+ from: string;
1831
+ to: string;
1832
+ getRaw: () => Promise<Uint8Array>;
1833
+ headers: Headers;
1834
+ rawSize: number;
1835
+ setReject: (reason: string) => void;
1836
+ forward: (rcptTo: string, headers?: Headers) => Promise<void>;
1837
+ reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
1838
+ };
1839
+
1840
+ export type EmailSendOptions = {
1841
+ to: string;
1842
+ subject: string;
1843
+ body: string;
1844
+ contentType?: string;
1845
+ headers?: Record<string, string>;
1846
+ includeRoutingHeaders?: boolean;
1847
+ agentName?: string;
1848
+ agentId?: string;
1849
+ domain?: string;
1850
+ };
818
1851
 
819
1852
  /**
820
1853
  * Get or create an Agent by name
@@ -825,7 +1858,7 @@ export async function routeAgentEmail<Env>(
825
1858
  * @param options Options for Agent creation
826
1859
  * @returns Promise resolving to an Agent instance stub
827
1860
  */
828
- export function getAgentByName<Env, T extends Agent<Env>>(
1861
+ export async function getAgentByName<Env, T extends Agent<Env>>(
829
1862
  namespace: AgentNamespace<T>,
830
1863
  name: string,
831
1864
  options?: {
@@ -840,13 +1873,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
840
1873
  * A wrapper for streaming responses in callable methods
841
1874
  */
842
1875
  export class StreamingResponse {
843
- #connection: Connection;
844
- #id: string;
845
- #closed = false;
1876
+ private _connection: Connection;
1877
+ private _id: string;
1878
+ private _closed = false;
846
1879
 
847
1880
  constructor(connection: Connection, id: string) {
848
- this.#connection = connection;
849
- this.#id = id;
1881
+ this._connection = connection;
1882
+ this._id = id;
850
1883
  }
851
1884
 
852
1885
  /**
@@ -854,17 +1887,17 @@ export class StreamingResponse {
854
1887
  * @param chunk The data to send
855
1888
  */
856
1889
  send(chunk: unknown) {
857
- if (this.#closed) {
1890
+ if (this._closed) {
858
1891
  throw new Error("StreamingResponse is already closed");
859
1892
  }
860
1893
  const response: RPCResponse = {
861
- type: "rpc",
862
- id: this.#id,
863
- success: true,
864
- result: chunk,
865
1894
  done: false,
1895
+ id: this._id,
1896
+ result: chunk,
1897
+ success: true,
1898
+ type: MessageType.RPC
866
1899
  };
867
- this.#connection.send(JSON.stringify(response));
1900
+ this._connection.send(JSON.stringify(response));
868
1901
  }
869
1902
 
870
1903
  /**
@@ -872,17 +1905,17 @@ export class StreamingResponse {
872
1905
  * @param finalChunk Optional final chunk of data to send
873
1906
  */
874
1907
  end(finalChunk?: unknown) {
875
- if (this.#closed) {
1908
+ if (this._closed) {
876
1909
  throw new Error("StreamingResponse is already closed");
877
1910
  }
878
- this.#closed = true;
1911
+ this._closed = true;
879
1912
  const response: RPCResponse = {
880
- type: "rpc",
881
- id: this.#id,
882
- success: true,
883
- result: finalChunk,
884
1913
  done: true,
1914
+ id: this._id,
1915
+ result: finalChunk,
1916
+ success: true,
1917
+ type: MessageType.RPC
885
1918
  };
886
- this.#connection.send(JSON.stringify(response));
1919
+ this._connection.send(JSON.stringify(response));
887
1920
  }
888
1921
  }