agents 0.0.0-fb4d0a6 → 0.0.0-fb62d22

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