agents 0.0.0-0cd2489 → 0.0.0-0dace6e

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