agents 0.0.0-eede2bd → 0.0.0-f31397c

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