agents 0.0.0-f5b5854 → 0.0.0-f64700e

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 (70) hide show
  1. package/README.md +255 -27
  2. package/dist/ai-chat-agent.d.ts +56 -11
  3. package/dist/ai-chat-agent.js +532 -160
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-gdyLiTd8.js +155 -0
  6. package/dist/ai-chat-v5-migration-gdyLiTd8.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +73 -72
  10. package/dist/ai-react.js +261 -188
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-BWW4umHY.d.ts +95 -0
  13. package/dist/ai-types-UZlfLOYP.js +20 -0
  14. package/dist/ai-types-UZlfLOYP.js.map +1 -0
  15. package/dist/ai-types.d.ts +6 -69
  16. package/dist/ai-types.js +3 -1
  17. package/dist/client-C-nwz-3N.d.ts +5313 -0
  18. package/dist/client-CZBVDDoO.js +786 -0
  19. package/dist/client-CZBVDDoO.js.map +1 -0
  20. package/dist/client-CmMi85Sj.d.ts +104 -0
  21. package/dist/client-DjR-lC16.js +117 -0
  22. package/dist/client-DjR-lC16.js.map +1 -0
  23. package/dist/client.d.ts +12 -79
  24. package/dist/client.js +3 -130
  25. package/dist/codemode/ai.d.ts +27 -0
  26. package/dist/codemode/ai.js +151 -0
  27. package/dist/codemode/ai.js.map +1 -0
  28. package/dist/do-oauth-client-provider-B2jr6UNq.js +93 -0
  29. package/dist/do-oauth-client-provider-B2jr6UNq.js.map +1 -0
  30. package/dist/do-oauth-client-provider-CCwGwnrA.d.ts +55 -0
  31. package/dist/index-CMEWpbHx.d.ts +568 -0
  32. package/dist/index-W4JUkafc.d.ts +54 -0
  33. package/dist/index.d.ts +63 -295
  34. package/dist/index.js +7 -20
  35. package/dist/mcp/client.d.ts +4 -763
  36. package/dist/mcp/client.js +2 -407
  37. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  38. package/dist/mcp/do-oauth-client-provider.js +2 -106
  39. package/dist/mcp/index.d.ts +73 -59
  40. package/dist/mcp/index.js +838 -769
  41. package/dist/mcp/index.js.map +1 -1
  42. package/dist/mcp/x402.d.ts +34 -0
  43. package/dist/mcp/x402.js +194 -0
  44. package/dist/mcp/x402.js.map +1 -0
  45. package/dist/mcp-BEwaCsxO.d.ts +61 -0
  46. package/dist/observability/index.d.ts +3 -0
  47. package/dist/observability/index.js +7 -0
  48. package/dist/react-jvtffQuA.d.ts +113 -0
  49. package/dist/react.d.ts +10 -39
  50. package/dist/react.js +183 -98
  51. package/dist/react.js.map +1 -1
  52. package/dist/schedule.d.ts +89 -12
  53. package/dist/schedule.js +46 -23
  54. package/dist/schedule.js.map +1 -1
  55. package/dist/serializable-gtr9YMhp.d.ts +34 -0
  56. package/dist/serializable.d.ts +7 -0
  57. package/dist/serializable.js +1 -0
  58. package/dist/src-L3cHuAag.js +1231 -0
  59. package/dist/src-L3cHuAag.js.map +1 -0
  60. package/package.json +110 -64
  61. package/src/index.ts +1407 -152
  62. package/dist/ai-types.js.map +0 -1
  63. package/dist/chunk-HMLY7DHA.js +0 -16
  64. package/dist/chunk-HMLY7DHA.js.map +0 -1
  65. package/dist/chunk-XG52S6YY.js +0 -591
  66. package/dist/chunk-XG52S6YY.js.map +0 -1
  67. package/dist/client.js.map +0 -1
  68. package/dist/index.js.map +0 -1
  69. package/dist/mcp/client.js.map +0 -1
  70. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
package/src/index.ts CHANGED
@@ -1,19 +1,36 @@
1
+ import type { env } from "cloudflare:workers";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
+ import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
5
+
6
+ import type {
7
+ Prompt,
8
+ Resource,
9
+ ServerCapabilities,
10
+ Tool
11
+ } from "@modelcontextprotocol/sdk/types.js";
12
+ import { parseCronExpression } from "cron-schedule";
13
+ import { nanoid } from "nanoid";
14
+ import { EmailMessage } from "cloudflare:email";
1
15
  import {
2
- Server,
3
- routePartykitRequest,
4
- type PartyServerOptions,
5
- getServerByName,
6
16
  type Connection,
7
17
  type ConnectionContext,
18
+ type PartyServerOptions,
19
+ Server,
8
20
  type WSMessage,
21
+ getServerByName,
22
+ routePartykitRequest
9
23
  } from "partyserver";
24
+ import { camelCaseToKebabCase } from "./client";
25
+ import { MCPClientManager, type MCPClientOAuthResult } from "./mcp/client";
26
+ import type { MCPConnectionState } from "./mcp/client-connection";
27
+ import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
28
+ import type { TransportType } from "./mcp/types";
29
+ import { genericObservability, type Observability } from "./observability";
30
+ import { DisposableStore } from "./core/events";
31
+ import { MessageType } from "./ai-types";
10
32
 
11
- import { parseCronExpression } from "cron-schedule";
12
- import { nanoid } from "nanoid";
13
-
14
- import { AsyncLocalStorage } from "node:async_hooks";
15
-
16
- export type { Connection, WSMessage, ConnectionContext } from "partyserver";
33
+ export type { Connection, ConnectionContext, WSMessage } from "partyserver";
17
34
 
18
35
  /**
19
36
  * RPC request message from client
@@ -29,7 +46,7 @@ export type RPCRequest = {
29
46
  * State update message from client
30
47
  */
31
48
  export type StateUpdateMessage = {
32
- type: "cf_agent_state";
49
+ type: MessageType.CF_AGENT_STATE;
33
50
  state: unknown;
34
51
  };
35
52
 
@@ -37,7 +54,7 @@ export type StateUpdateMessage = {
37
54
  * RPC response message to client
38
55
  */
39
56
  export type RPCResponse = {
40
- type: "rpc";
57
+ type: MessageType.RPC;
41
58
  id: string;
42
59
  } & (
43
60
  | {
@@ -64,7 +81,7 @@ function isRPCRequest(msg: unknown): msg is RPCRequest {
64
81
  typeof msg === "object" &&
65
82
  msg !== null &&
66
83
  "type" in msg &&
67
- msg.type === "rpc" &&
84
+ msg.type === MessageType.RPC &&
68
85
  "id" in msg &&
69
86
  typeof msg.id === "string" &&
70
87
  "method" in msg &&
@@ -82,7 +99,7 @@ function isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {
82
99
  typeof msg === "object" &&
83
100
  msg !== null &&
84
101
  "type" in msg &&
85
- msg.type === "cf_agent_state" &&
102
+ msg.type === MessageType.CF_AGENT_STATE &&
86
103
  "state" in msg
87
104
  );
88
105
  }
@@ -97,16 +114,16 @@ export type CallableMetadata = {
97
114
  streaming?: boolean;
98
115
  };
99
116
 
100
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
101
117
  const callableMetadata = new Map<Function, CallableMetadata>();
102
118
 
103
119
  /**
104
120
  * Decorator that marks a method as callable by clients
105
121
  * @param metadata Optional metadata about the callable method
106
122
  */
107
- export function unstable_callable(metadata: CallableMetadata = {}) {
123
+ export function callable(metadata: CallableMetadata = {}) {
108
124
  return function callableDecorator<This, Args extends unknown[], Return>(
109
125
  target: (this: This, ...args: Args) => Return,
126
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: later
110
127
  context: ClassMethodDecoratorContext
111
128
  ) {
112
129
  if (!callableMetadata.has(target)) {
@@ -117,6 +134,30 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
117
134
  };
118
135
  }
119
136
 
137
+ let didWarnAboutUnstableCallable = false;
138
+
139
+ /**
140
+ * Decorator that marks a method as callable by clients
141
+ * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
142
+ * @param metadata Optional metadata about the callable method
143
+ */
144
+ export const unstable_callable = (metadata: CallableMetadata = {}) => {
145
+ if (!didWarnAboutUnstableCallable) {
146
+ didWarnAboutUnstableCallable = true;
147
+ console.warn(
148
+ "unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version."
149
+ );
150
+ }
151
+ callable(metadata);
152
+ };
153
+
154
+ export type QueueItem<T = string> = {
155
+ id: string;
156
+ payload: T;
157
+ callback: keyof Agent<unknown>;
158
+ created_at: number;
159
+ };
160
+
120
161
  /**
121
162
  * Represents a scheduled task within an Agent
122
163
  * @template T Type of the payload data
@@ -158,24 +199,134 @@ function getNextCronTime(cron: string) {
158
199
  return interval.getNextDate();
159
200
  }
160
201
 
202
+ export type { TransportType } from "./mcp/types";
203
+
204
+ /**
205
+ * MCP Server state update message from server -> Client
206
+ */
207
+ export type MCPServerMessage = {
208
+ type: MessageType.CF_AGENT_MCP_SERVERS;
209
+ mcp: MCPServersState;
210
+ };
211
+
212
+ export type MCPServersState = {
213
+ servers: {
214
+ [id: string]: MCPServer;
215
+ };
216
+ tools: Tool[];
217
+ prompts: Prompt[];
218
+ resources: Resource[];
219
+ };
220
+
221
+ export type MCPServer = {
222
+ name: string;
223
+ server_url: string;
224
+ auth_url: string | null;
225
+ // This state is specifically about the temporary process of getting a token (if needed).
226
+ // Scope outside of that can't be relied upon because when the DO sleeps, there's no way
227
+ // to communicate a change to a non-ready state.
228
+ state: MCPConnectionState;
229
+ instructions: string | null;
230
+ capabilities: ServerCapabilities | null;
231
+ };
232
+
233
+ /**
234
+ * MCP Server data stored in DO SQL for resuming MCP Server connections
235
+ */
236
+ type MCPServerRow = {
237
+ id: string;
238
+ name: string;
239
+ server_url: string;
240
+ client_id: string | null;
241
+ auth_url: string | null;
242
+ callback_url: string;
243
+ server_options: string;
244
+ };
245
+
161
246
  const STATE_ROW_ID = "cf_state_row_id";
162
247
  const STATE_WAS_CHANGED = "cf_state_was_changed";
163
248
 
164
249
  const DEFAULT_STATE = {} as unknown;
165
250
 
166
- export const unstable_context = new AsyncLocalStorage<{
167
- agent: Agent<unknown>;
251
+ const agentContext = new AsyncLocalStorage<{
252
+ agent: Agent<unknown, unknown>;
168
253
  connection: Connection | undefined;
169
254
  request: Request | undefined;
255
+ email: AgentEmail | undefined;
170
256
  }>();
171
257
 
258
+ export function getCurrentAgent<
259
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>
260
+ >(): {
261
+ agent: T | undefined;
262
+ connection: Connection | undefined;
263
+ request: Request | undefined;
264
+ email: AgentEmail | undefined;
265
+ } {
266
+ const store = agentContext.getStore() as
267
+ | {
268
+ agent: T;
269
+ connection: Connection | undefined;
270
+ request: Request | undefined;
271
+ email: AgentEmail | undefined;
272
+ }
273
+ | undefined;
274
+ if (!store) {
275
+ return {
276
+ agent: undefined,
277
+ connection: undefined,
278
+ request: undefined,
279
+ email: undefined
280
+ };
281
+ }
282
+ return store;
283
+ }
284
+
285
+ /**
286
+ * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
287
+ * @param agent The agent instance
288
+ * @param method The method to wrap
289
+ * @returns A wrapped method that runs within the agent context
290
+ */
291
+
292
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
293
+ function withAgentContext<T extends (...args: any[]) => any>(
294
+ method: T
295
+ ): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {
296
+ return function (...args: Parameters<T>): ReturnType<T> {
297
+ const { connection, request, email, agent } = getCurrentAgent();
298
+
299
+ if (agent === this) {
300
+ // already wrapped, so we can just call the method
301
+ return method.apply(this, args);
302
+ }
303
+ // not wrapped, so we need to wrap it
304
+ return agentContext.run({ agent: this, connection, request, email }, () => {
305
+ return method.apply(this, args);
306
+ });
307
+ };
308
+ }
309
+
172
310
  /**
173
311
  * Base class for creating Agent implementations
174
312
  * @template Env Environment type containing bindings
175
313
  * @template State State type to store within the Agent
176
314
  */
177
- export class Agent<Env, State = unknown> extends Server<Env> {
178
- #state = DEFAULT_STATE as State;
315
+ export class Agent<
316
+ Env = typeof env,
317
+ State = unknown,
318
+ Props extends Record<string, unknown> = Record<string, unknown>
319
+ > extends Server<Env, Props> {
320
+ private _state = DEFAULT_STATE as State;
321
+ private _disposables = new DisposableStore();
322
+
323
+ private _ParentClass: typeof Agent<Env, State> =
324
+ Object.getPrototypeOf(this).constructor;
325
+
326
+ readonly mcp: MCPClientManager = new MCPClientManager(
327
+ this._ParentClass.name,
328
+ "0.0.1"
329
+ );
179
330
 
180
331
  /**
181
332
  * Initial state for the Agent
@@ -187,9 +338,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
187
338
  * Current state of the Agent
188
339
  */
189
340
  get state(): State {
190
- if (this.#state !== DEFAULT_STATE) {
341
+ if (this._state !== DEFAULT_STATE) {
191
342
  // state was previously set, and populated internal state
192
- return this.#state;
343
+ return this._state;
193
344
  }
194
345
  // looks like this is the first time the state is being accessed
195
346
  // check if the state was set in a previous life
@@ -209,8 +360,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
209
360
  ) {
210
361
  const state = result[0]?.state as string; // could be null?
211
362
 
212
- this.#state = JSON.parse(state);
213
- return this.#state;
363
+ this._state = JSON.parse(state);
364
+ return this._state;
214
365
  }
215
366
 
216
367
  // ok, this is the first time the state is being accessed
@@ -231,9 +382,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
231
382
  */
232
383
  static options = {
233
384
  /** Whether the Agent should hibernate when inactive */
234
- hibernate: true, // default to hibernate
385
+ hibernate: true // default to hibernate
235
386
  };
236
387
 
388
+ /**
389
+ * The observability implementation to use for the Agent
390
+ */
391
+ observability?: Observability = genericObservability;
392
+
237
393
  /**
238
394
  * Execute SQL queries against the Agent's database
239
395
  * @template T Type of the returned rows
@@ -263,6 +419,26 @@ export class Agent<Env, State = unknown> extends Server<Env> {
263
419
  constructor(ctx: AgentContext, env: Env) {
264
420
  super(ctx, env);
265
421
 
422
+ if (!wrappedClasses.has(this.constructor)) {
423
+ // Auto-wrap custom methods with agent context
424
+ this._autoWrapCustomMethods();
425
+ wrappedClasses.add(this.constructor);
426
+ }
427
+
428
+ // Broadcast server state after background connects (for OAuth servers)
429
+ this._disposables.add(
430
+ this.mcp.onConnected(async () => {
431
+ this.broadcastMcpServers();
432
+ })
433
+ );
434
+
435
+ // Emit MCP observability events
436
+ this._disposables.add(
437
+ this.mcp.onObservabilityEvent((event) => {
438
+ this.observability?.emit(event);
439
+ })
440
+ );
441
+
266
442
  this.sql`
267
443
  CREATE TABLE IF NOT EXISTS cf_agents_state (
268
444
  id TEXT PRIMARY KEY NOT NULL,
@@ -270,8 +446,17 @@ export class Agent<Env, State = unknown> extends Server<Env> {
270
446
  )
271
447
  `;
272
448
 
449
+ this.sql`
450
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
451
+ id TEXT PRIMARY KEY NOT NULL,
452
+ payload TEXT,
453
+ callback TEXT,
454
+ created_at INTEGER DEFAULT (unixepoch())
455
+ )
456
+ `;
457
+
273
458
  void this.ctx.blockConcurrencyWhile(async () => {
274
- return this.#tryCatch(async () => {
459
+ return this._tryCatch(async () => {
275
460
  // Create alarms table if it doesn't exist
276
461
  this.sql`
277
462
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
@@ -291,25 +476,54 @@ export class Agent<Env, State = unknown> extends Server<Env> {
291
476
  });
292
477
  });
293
478
 
479
+ this.sql`
480
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
481
+ id TEXT PRIMARY KEY NOT NULL,
482
+ name TEXT NOT NULL,
483
+ server_url TEXT NOT NULL,
484
+ callback_url TEXT NOT NULL,
485
+ client_id TEXT,
486
+ auth_url TEXT,
487
+ server_options TEXT
488
+ )
489
+ `;
490
+
491
+ const _onRequest = this.onRequest.bind(this);
492
+ this.onRequest = (request: Request) => {
493
+ return agentContext.run(
494
+ { agent: this, connection: undefined, request, email: undefined },
495
+ async () => {
496
+ // Check if this is an OAuth callback and restore state if needed
497
+ const callbackResult =
498
+ await this._handlePotentialOAuthCallback(request);
499
+ if (callbackResult) {
500
+ return callbackResult;
501
+ }
502
+
503
+ return this._tryCatch(() => _onRequest(request));
504
+ }
505
+ );
506
+ };
507
+
294
508
  const _onMessage = this.onMessage.bind(this);
295
509
  this.onMessage = async (connection: Connection, message: WSMessage) => {
296
- return unstable_context.run(
297
- { agent: this, connection, request: undefined },
510
+ return agentContext.run(
511
+ { agent: this, connection, request: undefined, email: undefined },
298
512
  async () => {
299
513
  if (typeof message !== "string") {
300
- return this.#tryCatch(() => _onMessage(connection, message));
514
+ return this._tryCatch(() => _onMessage(connection, message));
301
515
  }
302
516
 
303
517
  let parsed: unknown;
304
518
  try {
305
519
  parsed = JSON.parse(message);
306
- } catch (e) {
520
+ } catch (_e) {
307
521
  // silently fail and let the onMessage handler handle it
308
- return this.#tryCatch(() => _onMessage(connection, message));
522
+ return this._tryCatch(() => _onMessage(connection, message));
309
523
  }
310
524
 
311
525
  if (isStateUpdateMessage(parsed)) {
312
- this.#setStateInternal(parsed.state as State, connection);
526
+ this._setStateInternal(parsed.state as State, connection);
313
527
  return;
314
528
  }
315
529
 
@@ -323,11 +537,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
323
537
  throw new Error(`Method ${method} does not exist`);
324
538
  }
325
539
 
326
- if (!this.#isCallable(method)) {
540
+ if (!this._isCallable(method)) {
327
541
  throw new Error(`Method ${method} is not callable`);
328
542
  }
329
543
 
330
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
331
544
  const metadata = callableMetadata.get(methodFn as Function);
332
545
 
333
546
  // For streaming methods, pass a StreamingResponse object
@@ -339,22 +552,37 @@ export class Agent<Env, State = unknown> extends Server<Env> {
339
552
 
340
553
  // For regular methods, execute and send response
341
554
  const result = await methodFn.apply(this, args);
555
+
556
+ this.observability?.emit(
557
+ {
558
+ displayMessage: `RPC call to ${method}`,
559
+ id: nanoid(),
560
+ payload: {
561
+ method,
562
+ streaming: metadata?.streaming
563
+ },
564
+ timestamp: Date.now(),
565
+ type: "rpc"
566
+ },
567
+ this.ctx
568
+ );
569
+
342
570
  const response: RPCResponse = {
343
- type: "rpc",
571
+ done: true,
344
572
  id,
345
- success: true,
346
573
  result,
347
- done: true,
574
+ success: true,
575
+ type: MessageType.RPC
348
576
  };
349
577
  connection.send(JSON.stringify(response));
350
578
  } catch (e) {
351
579
  // Send error response
352
580
  const response: RPCResponse = {
353
- type: "rpc",
354
- id: parsed.id,
355
- success: false,
356
581
  error:
357
582
  e instanceof Error ? e.message : "Unknown error occurred",
583
+ id: parsed.id,
584
+ success: false,
585
+ type: MessageType.RPC
358
586
  };
359
587
  connection.send(JSON.stringify(response));
360
588
  console.error("RPC error:", e);
@@ -362,7 +590,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
362
590
  return;
363
591
  }
364
592
 
365
- return this.#tryCatch(() => _onMessage(connection, message));
593
+ return this._tryCatch(() => _onMessage(connection, message));
366
594
  }
367
595
  );
368
596
  };
@@ -371,27 +599,110 @@ export class Agent<Env, State = unknown> extends Server<Env> {
371
599
  this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
372
600
  // TODO: This is a hack to ensure the state is sent after the connection is established
373
601
  // must fix this
374
- return unstable_context.run(
375
- { agent: this, connection, request: ctx.request },
602
+ return agentContext.run(
603
+ { agent: this, connection, request: ctx.request, email: undefined },
604
+ () => {
605
+ if (this.state) {
606
+ connection.send(
607
+ JSON.stringify({
608
+ state: this.state,
609
+ type: MessageType.CF_AGENT_STATE
610
+ })
611
+ );
612
+ }
613
+
614
+ connection.send(
615
+ JSON.stringify({
616
+ mcp: this.getMcpServers(),
617
+ type: MessageType.CF_AGENT_MCP_SERVERS
618
+ })
619
+ );
620
+
621
+ this.observability?.emit(
622
+ {
623
+ displayMessage: "Connection established",
624
+ id: nanoid(),
625
+ payload: {
626
+ connectionId: connection.id
627
+ },
628
+ timestamp: Date.now(),
629
+ type: "connect"
630
+ },
631
+ this.ctx
632
+ );
633
+ return this._tryCatch(() => _onConnect(connection, ctx));
634
+ }
635
+ );
636
+ };
637
+
638
+ const _onStart = this.onStart.bind(this);
639
+ this.onStart = async (props?: Props) => {
640
+ return agentContext.run(
641
+ {
642
+ agent: this,
643
+ connection: undefined,
644
+ request: undefined,
645
+ email: undefined
646
+ },
376
647
  async () => {
377
- setTimeout(() => {
378
- if (this.state) {
379
- connection.send(
380
- JSON.stringify({
381
- type: "cf_agent_state",
382
- state: this.state,
383
- })
384
- );
648
+ await this._tryCatch(() => {
649
+ const servers = this.sql<MCPServerRow>`
650
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
651
+ `;
652
+
653
+ this.broadcastMcpServers();
654
+
655
+ // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
656
+ if (servers && Array.isArray(servers) && servers.length > 0) {
657
+ // Restore callback URLs for OAuth-enabled servers
658
+ servers.forEach((server) => {
659
+ if (server.callback_url) {
660
+ // Register the full redirect URL including serverId to avoid ambiguous matches
661
+ this.mcp.registerCallbackUrl(
662
+ `${server.callback_url}/${server.id}`
663
+ );
664
+ }
665
+ });
666
+
667
+ servers.forEach((server) => {
668
+ this._connectToMcpServerInternal(
669
+ server.name,
670
+ server.server_url,
671
+ server.callback_url,
672
+ server.server_options
673
+ ? JSON.parse(server.server_options)
674
+ : undefined,
675
+ {
676
+ id: server.id,
677
+ oauthClientId: server.client_id ?? undefined
678
+ }
679
+ )
680
+ .then(() => {
681
+ // Broadcast updated MCP servers state after each server connects
682
+ this.broadcastMcpServers();
683
+ })
684
+ .catch((error) => {
685
+ console.error(
686
+ `Error connecting to MCP server: ${server.name} (${server.server_url})`,
687
+ error
688
+ );
689
+ // Still broadcast even if connection fails, so clients know about the failure
690
+ this.broadcastMcpServers();
691
+ });
692
+ });
385
693
  }
386
- return this.#tryCatch(() => _onConnect(connection, ctx));
387
- }, 20);
694
+ return _onStart(props);
695
+ });
388
696
  }
389
697
  );
390
698
  };
391
699
  }
392
700
 
393
- #setStateInternal(state: State, source: Connection | "server" = "server") {
394
- this.#state = state;
701
+ private _setStateInternal(
702
+ state: State,
703
+ source: Connection | "server" = "server"
704
+ ) {
705
+ this._state = state;
395
706
  this.sql`
396
707
  INSERT OR REPLACE INTO cf_agents_state (id, state)
397
708
  VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
@@ -402,16 +713,26 @@ export class Agent<Env, State = unknown> extends Server<Env> {
402
713
  `;
403
714
  this.broadcast(
404
715
  JSON.stringify({
405
- type: "cf_agent_state",
406
716
  state: state,
717
+ type: MessageType.CF_AGENT_STATE
407
718
  }),
408
719
  source !== "server" ? [source.id] : []
409
720
  );
410
- return this.#tryCatch(() => {
411
- const { connection, request } = unstable_context.getStore() || {};
412
- return unstable_context.run(
413
- { agent: this, connection, request },
721
+ return this._tryCatch(() => {
722
+ const { connection, request, email } = agentContext.getStore() || {};
723
+ return agentContext.run(
724
+ { agent: this, connection, request, email },
414
725
  async () => {
726
+ this.observability?.emit(
727
+ {
728
+ displayMessage: "State updated",
729
+ id: nanoid(),
730
+ payload: {},
731
+ timestamp: Date.now(),
732
+ type: "state:update"
733
+ },
734
+ this.ctx
735
+ );
415
736
  return this.onStateUpdate(state, source);
416
737
  }
417
738
  );
@@ -423,7 +744,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
423
744
  * @param state New state to set
424
745
  */
425
746
  setState(state: State) {
426
- this.#setStateInternal(state, "server");
747
+ this._setStateInternal(state, "server");
427
748
  }
428
749
 
429
750
  /**
@@ -431,24 +752,90 @@ export class Agent<Env, State = unknown> extends Server<Env> {
431
752
  * @param state Updated state
432
753
  * @param source Source of the state update ("server" or a client connection)
433
754
  */
755
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
434
756
  onStateUpdate(state: State | undefined, source: Connection | "server") {
435
757
  // override this to handle state updates
436
758
  }
437
759
 
438
760
  /**
439
- * Called when the Agent receives an email
761
+ * Called when the Agent receives an email via routeAgentEmail()
762
+ * Override this method to handle incoming emails
440
763
  * @param email Email message to process
441
764
  */
442
- onEmail(email: ForwardableEmailMessage) {
443
- return unstable_context.run(
444
- { agent: this, connection: undefined, request: undefined },
765
+ async _onEmail(email: AgentEmail) {
766
+ // nb: we use this roundabout way of getting to onEmail
767
+ // because of https://github.com/cloudflare/workerd/issues/4499
768
+ return agentContext.run(
769
+ { agent: this, connection: undefined, request: undefined, email: email },
445
770
  async () => {
446
- console.error("onEmail not implemented");
771
+ if ("onEmail" in this && typeof this.onEmail === "function") {
772
+ return this._tryCatch(() =>
773
+ (this.onEmail as (email: AgentEmail) => Promise<void>)(email)
774
+ );
775
+ } else {
776
+ console.log("Received email from:", email.from, "to:", email.to);
777
+ console.log("Subject:", email.headers.get("subject"));
778
+ console.log(
779
+ "Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails"
780
+ );
781
+ }
447
782
  }
448
783
  );
449
784
  }
450
785
 
451
- async #tryCatch<T>(fn: () => T | Promise<T>) {
786
+ /**
787
+ * Reply to an email
788
+ * @param email The email to reply to
789
+ * @param options Options for the reply
790
+ * @returns void
791
+ */
792
+ async replyToEmail(
793
+ email: AgentEmail,
794
+ options: {
795
+ fromName: string;
796
+ subject?: string | undefined;
797
+ body: string;
798
+ contentType?: string;
799
+ headers?: Record<string, string>;
800
+ }
801
+ ): Promise<void> {
802
+ return this._tryCatch(async () => {
803
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
804
+ const agentId = this.name;
805
+
806
+ const { createMimeMessage } = await import("mimetext");
807
+ const msg = createMimeMessage();
808
+ msg.setSender({ addr: email.to, name: options.fromName });
809
+ msg.setRecipient(email.from);
810
+ msg.setSubject(
811
+ options.subject || `Re: ${email.headers.get("subject")}` || "No subject"
812
+ );
813
+ msg.addMessage({
814
+ contentType: options.contentType || "text/plain",
815
+ data: options.body
816
+ });
817
+
818
+ const domain = email.from.split("@")[1];
819
+ const messageId = `<${agentId}@${domain}>`;
820
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID")!);
821
+ msg.setHeader("Message-ID", messageId);
822
+ msg.setHeader("X-Agent-Name", agentName);
823
+ msg.setHeader("X-Agent-ID", agentId);
824
+
825
+ if (options.headers) {
826
+ for (const [key, value] of Object.entries(options.headers)) {
827
+ msg.setHeader(key, value);
828
+ }
829
+ }
830
+ await email.reply({
831
+ from: email.to,
832
+ raw: msg.asRaw(),
833
+ to: email.from
834
+ });
835
+ });
836
+ }
837
+
838
+ private async _tryCatch<T>(fn: () => T | Promise<T>) {
452
839
  try {
453
840
  return await fn();
454
841
  } catch (e) {
@@ -456,6 +843,68 @@ export class Agent<Env, State = unknown> extends Server<Env> {
456
843
  }
457
844
  }
458
845
 
846
+ /**
847
+ * Automatically wrap custom methods with agent context
848
+ * This ensures getCurrentAgent() works in all custom methods without decorators
849
+ */
850
+ private _autoWrapCustomMethods() {
851
+ // Collect all methods from base prototypes (Agent and Server)
852
+ const basePrototypes = [Agent.prototype, Server.prototype];
853
+ const baseMethods = new Set<string>();
854
+ for (const baseProto of basePrototypes) {
855
+ let proto = baseProto;
856
+ while (proto && proto !== Object.prototype) {
857
+ const methodNames = Object.getOwnPropertyNames(proto);
858
+ for (const methodName of methodNames) {
859
+ baseMethods.add(methodName);
860
+ }
861
+ proto = Object.getPrototypeOf(proto);
862
+ }
863
+ }
864
+ // Get all methods from the current instance's prototype chain
865
+ let proto = Object.getPrototypeOf(this);
866
+ let depth = 0;
867
+ while (proto && proto !== Object.prototype && depth < 10) {
868
+ const methodNames = Object.getOwnPropertyNames(proto);
869
+ for (const methodName of methodNames) {
870
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
871
+
872
+ // Skip if it's a private method, a base method, a getter, or not a function,
873
+ if (
874
+ baseMethods.has(methodName) ||
875
+ methodName.startsWith("_") ||
876
+ !descriptor ||
877
+ !!descriptor.get ||
878
+ typeof descriptor.value !== "function"
879
+ ) {
880
+ continue;
881
+ }
882
+
883
+ // Now, methodName is confirmed to be a custom method/function
884
+ // Wrap the custom method with context
885
+ const wrappedFunction = withAgentContext(
886
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
887
+ this[methodName as keyof this] as (...args: any[]) => any
888
+ // biome-ignore lint/suspicious/noExplicitAny: I can't typescript
889
+ ) as any;
890
+
891
+ // if the method is callable, copy the metadata from the original method
892
+ if (this._isCallable(methodName)) {
893
+ callableMetadata.set(
894
+ wrappedFunction,
895
+ callableMetadata.get(this[methodName as keyof this] as Function)!
896
+ );
897
+ }
898
+
899
+ // set the wrapped function on the prototype
900
+ this.constructor.prototype[methodName as keyof this] = wrappedFunction;
901
+ }
902
+
903
+ proto = Object.getPrototypeOf(proto);
904
+ depth++;
905
+ }
906
+ }
907
+
459
908
  override onError(
460
909
  connection: Connection,
461
910
  error: unknown
@@ -490,6 +939,131 @@ export class Agent<Env, State = unknown> extends Server<Env> {
490
939
  throw new Error("Not implemented");
491
940
  }
492
941
 
942
+ /**
943
+ * Queue a task to be executed in the future
944
+ * @param payload Payload to pass to the callback
945
+ * @param callback Name of the method to call
946
+ * @returns The ID of the queued task
947
+ */
948
+ async queue<T = unknown>(callback: keyof this, payload: T): Promise<string> {
949
+ const id = nanoid(9);
950
+ if (typeof callback !== "string") {
951
+ throw new Error("Callback must be a string");
952
+ }
953
+
954
+ if (typeof this[callback] !== "function") {
955
+ throw new Error(`this.${callback} is not a function`);
956
+ }
957
+
958
+ this.sql`
959
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
960
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
961
+ `;
962
+
963
+ void this._flushQueue().catch((e) => {
964
+ console.error("Error flushing queue:", e);
965
+ });
966
+
967
+ return id;
968
+ }
969
+
970
+ private _flushingQueue = false;
971
+
972
+ private async _flushQueue() {
973
+ if (this._flushingQueue) {
974
+ return;
975
+ }
976
+ this._flushingQueue = true;
977
+ while (true) {
978
+ const result = this.sql<QueueItem<string>>`
979
+ SELECT * FROM cf_agents_queues
980
+ ORDER BY created_at ASC
981
+ `;
982
+
983
+ if (!result || result.length === 0) {
984
+ break;
985
+ }
986
+
987
+ for (const row of result || []) {
988
+ const callback = this[row.callback as keyof Agent<Env>];
989
+ if (!callback) {
990
+ console.error(`callback ${row.callback} not found`);
991
+ continue;
992
+ }
993
+ const { connection, request, email } = agentContext.getStore() || {};
994
+ await agentContext.run(
995
+ {
996
+ agent: this,
997
+ connection,
998
+ request,
999
+ email
1000
+ },
1001
+ async () => {
1002
+ // TODO: add retries and backoff
1003
+ await (
1004
+ callback as (
1005
+ payload: unknown,
1006
+ queueItem: QueueItem<string>
1007
+ ) => Promise<void>
1008
+ ).bind(this)(JSON.parse(row.payload as string), row);
1009
+ await this.dequeue(row.id);
1010
+ }
1011
+ );
1012
+ }
1013
+ }
1014
+ this._flushingQueue = false;
1015
+ }
1016
+
1017
+ /**
1018
+ * Dequeue a task by ID
1019
+ * @param id ID of the task to dequeue
1020
+ */
1021
+ async dequeue(id: string) {
1022
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
1023
+ }
1024
+
1025
+ /**
1026
+ * Dequeue all tasks
1027
+ */
1028
+ async dequeueAll() {
1029
+ this.sql`DELETE FROM cf_agents_queues`;
1030
+ }
1031
+
1032
+ /**
1033
+ * Dequeue all tasks by callback
1034
+ * @param callback Name of the callback to dequeue
1035
+ */
1036
+ async dequeueAllByCallback(callback: string) {
1037
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
1038
+ }
1039
+
1040
+ /**
1041
+ * Get a queued task by ID
1042
+ * @param id ID of the task to get
1043
+ * @returns The task or undefined if not found
1044
+ */
1045
+ async getQueue(id: string): Promise<QueueItem<string> | undefined> {
1046
+ const result = this.sql<QueueItem<string>>`
1047
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
1048
+ `;
1049
+ return result
1050
+ ? { ...result[0], payload: JSON.parse(result[0].payload) }
1051
+ : undefined;
1052
+ }
1053
+
1054
+ /**
1055
+ * Get all queues by key and value
1056
+ * @param key Key to filter by
1057
+ * @param value Value to filter by
1058
+ * @returns Array of matching QueueItem objects
1059
+ */
1060
+ async getQueues(key: string, value: string): Promise<QueueItem<string>[]> {
1061
+ const result = this.sql<QueueItem<string>>`
1062
+ SELECT * FROM cf_agents_queues
1063
+ `;
1064
+ return result.filter((row) => JSON.parse(row.payload)[key] === value);
1065
+ }
1066
+
493
1067
  /**
494
1068
  * Schedule a task to be executed in the future
495
1069
  * @template T Type of the payload data
@@ -505,6 +1079,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
505
1079
  ): Promise<Schedule<T>> {
506
1080
  const id = nanoid(9);
507
1081
 
1082
+ const emitScheduleCreate = (schedule: Schedule<T>) =>
1083
+ this.observability?.emit(
1084
+ {
1085
+ displayMessage: `Schedule ${schedule.id} created`,
1086
+ id: nanoid(),
1087
+ payload: {
1088
+ callback: callback as string,
1089
+ id: id
1090
+ },
1091
+ timestamp: Date.now(),
1092
+ type: "schedule:create"
1093
+ },
1094
+ this.ctx
1095
+ );
1096
+
508
1097
  if (typeof callback !== "string") {
509
1098
  throw new Error("Callback must be a string");
510
1099
  }
@@ -522,15 +1111,19 @@ export class Agent<Env, State = unknown> extends Server<Env> {
522
1111
  )}, 'scheduled', ${timestamp})
523
1112
  `;
524
1113
 
525
- await this.#scheduleNextAlarm();
1114
+ await this._scheduleNextAlarm();
526
1115
 
527
- return {
528
- id,
1116
+ const schedule: Schedule<T> = {
529
1117
  callback: callback,
1118
+ id,
530
1119
  payload: payload as T,
531
1120
  time: timestamp,
532
- type: "scheduled",
1121
+ type: "scheduled"
533
1122
  };
1123
+
1124
+ emitScheduleCreate(schedule);
1125
+
1126
+ return schedule;
534
1127
  }
535
1128
  if (typeof when === "number") {
536
1129
  const time = new Date(Date.now() + when * 1000);
@@ -543,16 +1136,20 @@ export class Agent<Env, State = unknown> extends Server<Env> {
543
1136
  )}, 'delayed', ${when}, ${timestamp})
544
1137
  `;
545
1138
 
546
- await this.#scheduleNextAlarm();
1139
+ await this._scheduleNextAlarm();
547
1140
 
548
- return {
549
- id,
1141
+ const schedule: Schedule<T> = {
550
1142
  callback: callback,
551
- payload: payload as T,
552
1143
  delayInSeconds: when,
1144
+ id,
1145
+ payload: payload as T,
553
1146
  time: timestamp,
554
- type: "delayed",
1147
+ type: "delayed"
555
1148
  };
1149
+
1150
+ emitScheduleCreate(schedule);
1151
+
1152
+ return schedule;
556
1153
  }
557
1154
  if (typeof when === "string") {
558
1155
  const nextExecutionTime = getNextCronTime(when);
@@ -565,16 +1162,20 @@ export class Agent<Env, State = unknown> extends Server<Env> {
565
1162
  )}, 'cron', ${when}, ${timestamp})
566
1163
  `;
567
1164
 
568
- await this.#scheduleNextAlarm();
1165
+ await this._scheduleNextAlarm();
569
1166
 
570
- return {
571
- id,
1167
+ const schedule: Schedule<T> = {
572
1168
  callback: callback,
573
- payload: payload as T,
574
1169
  cron: when,
1170
+ id,
1171
+ payload: payload as T,
575
1172
  time: timestamp,
576
- type: "cron",
1173
+ type: "cron"
577
1174
  };
1175
+
1176
+ emitScheduleCreate(schedule);
1177
+
1178
+ return schedule;
578
1179
  }
579
1180
  throw new Error("Invalid schedule type");
580
1181
  }
@@ -638,7 +1239,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
638
1239
  .toArray()
639
1240
  .map((row) => ({
640
1241
  ...row,
641
- payload: JSON.parse(row.payload as string) as T,
1242
+ payload: JSON.parse(row.payload as string) as T
642
1243
  })) as Schedule<T>[];
643
1244
 
644
1245
  return result;
@@ -650,18 +1251,34 @@ export class Agent<Env, State = unknown> extends Server<Env> {
650
1251
  * @returns true if the task was cancelled, false otherwise
651
1252
  */
652
1253
  async cancelSchedule(id: string): Promise<boolean> {
1254
+ const schedule = await this.getSchedule(id);
1255
+ if (schedule) {
1256
+ this.observability?.emit(
1257
+ {
1258
+ displayMessage: `Schedule ${id} cancelled`,
1259
+ id: nanoid(),
1260
+ payload: {
1261
+ callback: schedule.callback,
1262
+ id: schedule.id
1263
+ },
1264
+ timestamp: Date.now(),
1265
+ type: "schedule:cancel"
1266
+ },
1267
+ this.ctx
1268
+ );
1269
+ }
653
1270
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
654
1271
 
655
- await this.#scheduleNextAlarm();
1272
+ await this._scheduleNextAlarm();
656
1273
  return true;
657
1274
  }
658
1275
 
659
- async #scheduleNextAlarm() {
1276
+ private async _scheduleNextAlarm() {
660
1277
  // Find the next schedule that needs to be executed
661
1278
  const result = this.sql`
662
- SELECT time FROM cf_agents_schedules
1279
+ SELECT time FROM cf_agents_schedules
663
1280
  WHERE time > ${Math.floor(Date.now() / 1000)}
664
- ORDER BY time ASC
1281
+ ORDER BY time ASC
665
1282
  LIMIT 1
666
1283
  `;
667
1284
  if (!result) return;
@@ -673,10 +1290,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
673
1290
  }
674
1291
 
675
1292
  /**
676
- * Method called when an alarm fires
677
- * Executes any scheduled tasks that are due
1293
+ * Method called when an alarm fires.
1294
+ * Executes any scheduled tasks that are due.
1295
+ *
1296
+ * @remarks
1297
+ * To schedule a task, please use the `this.schedule` method instead.
1298
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
678
1299
  */
679
- async alarm() {
1300
+ public readonly alarm = async () => {
680
1301
  const now = Math.floor(Date.now() / 1000);
681
1302
 
682
1303
  // Get all schedules that should be executed now
@@ -684,46 +1305,67 @@ export class Agent<Env, State = unknown> extends Server<Env> {
684
1305
  SELECT * FROM cf_agents_schedules WHERE time <= ${now}
685
1306
  `;
686
1307
 
687
- for (const row of result || []) {
688
- const callback = this[row.callback as keyof Agent<Env>];
689
- if (!callback) {
690
- console.error(`callback ${row.callback} not found`);
691
- continue;
692
- }
693
- await unstable_context.run(
694
- { agent: this, connection: undefined, request: undefined },
695
- async () => {
696
- try {
697
- await (
698
- callback as (
699
- payload: unknown,
700
- schedule: Schedule<unknown>
701
- ) => Promise<void>
702
- ).bind(this)(JSON.parse(row.payload as string), row);
703
- } catch (e) {
704
- console.error(`error executing callback "${row.callback}"`, e);
705
- }
1308
+ if (result && Array.isArray(result)) {
1309
+ for (const row of result) {
1310
+ const callback = this[row.callback as keyof Agent<Env>];
1311
+ if (!callback) {
1312
+ console.error(`callback ${row.callback} not found`);
1313
+ continue;
706
1314
  }
707
- );
708
- if (row.type === "cron") {
709
- // Update next execution time for cron schedules
710
- const nextExecutionTime = getNextCronTime(row.cron);
711
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1315
+ await agentContext.run(
1316
+ {
1317
+ agent: this,
1318
+ connection: undefined,
1319
+ request: undefined,
1320
+ email: undefined
1321
+ },
1322
+ async () => {
1323
+ try {
1324
+ this.observability?.emit(
1325
+ {
1326
+ displayMessage: `Schedule ${row.id} executed`,
1327
+ id: nanoid(),
1328
+ payload: {
1329
+ callback: row.callback,
1330
+ id: row.id
1331
+ },
1332
+ timestamp: Date.now(),
1333
+ type: "schedule:execute"
1334
+ },
1335
+ this.ctx
1336
+ );
712
1337
 
713
- this.sql`
1338
+ await (
1339
+ callback as (
1340
+ payload: unknown,
1341
+ schedule: Schedule<unknown>
1342
+ ) => Promise<void>
1343
+ ).bind(this)(JSON.parse(row.payload as string), row);
1344
+ } catch (e) {
1345
+ console.error(`error executing callback "${row.callback}"`, e);
1346
+ }
1347
+ }
1348
+ );
1349
+ if (row.type === "cron") {
1350
+ // Update next execution time for cron schedules
1351
+ const nextExecutionTime = getNextCronTime(row.cron);
1352
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);
1353
+
1354
+ this.sql`
714
1355
  UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
715
1356
  `;
716
- } else {
717
- // Delete one-time schedules after execution
718
- this.sql`
1357
+ } else {
1358
+ // Delete one-time schedules after execution
1359
+ this.sql`
719
1360
  DELETE FROM cf_agents_schedules WHERE id = ${row.id}
720
1361
  `;
1362
+ }
721
1363
  }
722
1364
  }
723
1365
 
724
1366
  // Schedule the next alarm
725
- await this.#scheduleNextAlarm();
726
- }
1367
+ await this._scheduleNextAlarm();
1368
+ };
727
1369
 
728
1370
  /**
729
1371
  * Destroy the Agent, removing all state and scheduled tasks
@@ -732,22 +1374,416 @@ export class Agent<Env, State = unknown> extends Server<Env> {
732
1374
  // drop all tables
733
1375
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
734
1376
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
1377
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
1378
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
735
1379
 
736
1380
  // delete all alarms
737
1381
  await this.ctx.storage.deleteAlarm();
738
1382
  await this.ctx.storage.deleteAll();
1383
+ this._disposables.dispose();
1384
+ await this.mcp.dispose?.();
1385
+ this.ctx.abort("destroyed"); // enforce that the agent is evicted
1386
+
1387
+ this.observability?.emit(
1388
+ {
1389
+ displayMessage: "Agent destroyed",
1390
+ id: nanoid(),
1391
+ payload: {},
1392
+ timestamp: Date.now(),
1393
+ type: "destroy"
1394
+ },
1395
+ this.ctx
1396
+ );
739
1397
  }
740
1398
 
741
1399
  /**
742
1400
  * Get all methods marked as callable on this Agent
743
1401
  * @returns A map of method names to their metadata
744
1402
  */
745
- #isCallable(method: string): boolean {
746
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
1403
+ private _isCallable(method: string): boolean {
747
1404
  return callableMetadata.has(this[method as keyof this] as Function);
748
1405
  }
1406
+
1407
+ /**
1408
+ * Connect to a new MCP Server
1409
+ *
1410
+ * @param serverName Name of the MCP server
1411
+ * @param url MCP Server SSE URL
1412
+ * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
1413
+ * @param agentsPrefix agents routing prefix if not using `agents`
1414
+ * @param options MCP client and transport options
1415
+ * @returns authUrl
1416
+ */
1417
+ async addMcpServer(
1418
+ serverName: string,
1419
+ url: string,
1420
+ callbackHost?: string,
1421
+ agentsPrefix = "agents",
1422
+ options?: {
1423
+ client?: ConstructorParameters<typeof Client>[1];
1424
+ transport?: {
1425
+ headers?: HeadersInit;
1426
+ type?: TransportType;
1427
+ };
1428
+ }
1429
+ ): Promise<{ id: string; authUrl: string | undefined }> {
1430
+ // If callbackHost is not provided, derive it from the current request
1431
+ let resolvedCallbackHost = callbackHost;
1432
+ if (!resolvedCallbackHost) {
1433
+ const { request } = getCurrentAgent();
1434
+ if (!request) {
1435
+ throw new Error(
1436
+ "callbackHost is required when not called within a request context"
1437
+ );
1438
+ }
1439
+
1440
+ // Extract the origin from the request
1441
+ const requestUrl = new URL(request.url);
1442
+ resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
1443
+ }
1444
+
1445
+ const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
1446
+
1447
+ // Generate a serverId upfront
1448
+ const serverId = nanoid(8);
1449
+
1450
+ // Persist to database BEFORE starting OAuth flow to survive DO hibernation
1451
+ this.sql`
1452
+ INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1453
+ VALUES (
1454
+ ${serverId},
1455
+ ${serverName},
1456
+ ${url},
1457
+ ${null},
1458
+ ${null},
1459
+ ${callbackUrl},
1460
+ ${options ? JSON.stringify(options) : null}
1461
+ );
1462
+ `;
1463
+
1464
+ // _connectToMcpServerInternal will call mcp.connect which registers the callback URL
1465
+ const result = await this._connectToMcpServerInternal(
1466
+ serverName,
1467
+ url,
1468
+ callbackUrl,
1469
+ options,
1470
+ { id: serverId }
1471
+ );
1472
+
1473
+ // Update database with OAuth client info if auth is required
1474
+ if (result.clientId || result.authUrl) {
1475
+ this.sql`
1476
+ UPDATE cf_agents_mcp_servers
1477
+ SET client_id = ${result.clientId ?? null}, auth_url = ${result.authUrl ?? null}
1478
+ WHERE id = ${serverId}
1479
+ `;
1480
+ }
1481
+
1482
+ this.broadcastMcpServers();
1483
+
1484
+ return result;
1485
+ }
1486
+
1487
+ /**
1488
+ * Handle potential OAuth callback requests after DO hibernation.
1489
+ * Detects OAuth callbacks, restores state from database, and processes the callback.
1490
+ * Returns a Response if this was an OAuth callback, otherwise returns undefined.
1491
+ */
1492
+ private async _handlePotentialOAuthCallback(
1493
+ request: Request
1494
+ ): Promise<Response | undefined> {
1495
+ // Quick check: must be GET with callback pattern and code parameter
1496
+ if (request.method !== "GET") {
1497
+ return undefined;
1498
+ }
1499
+
1500
+ const url = new URL(request.url);
1501
+ const hasCallbackPattern =
1502
+ url.pathname.includes("/callback/") && url.searchParams.has("code");
1503
+
1504
+ if (!hasCallbackPattern) {
1505
+ return undefined;
1506
+ }
1507
+
1508
+ // Extract serverId from callback URL
1509
+ const pathParts = url.pathname.split("/");
1510
+ const callbackIndex = pathParts.indexOf("callback");
1511
+ const serverId = callbackIndex !== -1 ? pathParts[callbackIndex + 1] : null;
1512
+
1513
+ if (!serverId) {
1514
+ return new Response("Invalid callback URL: missing serverId", {
1515
+ status: 400
1516
+ });
1517
+ }
1518
+
1519
+ // Check if callback is already registered AND connection exists (not hibernated)
1520
+ if (
1521
+ this.mcp.isCallbackRequest(request) &&
1522
+ this.mcp.mcpConnections[serverId]
1523
+ ) {
1524
+ // State already restored, handle normally
1525
+ return this._processOAuthCallback(request);
1526
+ }
1527
+
1528
+ // Need to restore from database after hibernation
1529
+ try {
1530
+ const server = this.sql<MCPServerRow>`
1531
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options
1532
+ FROM cf_agents_mcp_servers
1533
+ WHERE id = ${serverId}
1534
+ `.find((s) => s.id === serverId);
1535
+
1536
+ if (!server) {
1537
+ return new Response(
1538
+ `OAuth callback failed: Server ${serverId} not found in database`,
1539
+ { status: 404 }
1540
+ );
1541
+ }
1542
+
1543
+ // Register callback URL (restores it after hibernation)
1544
+ if (!server.callback_url) {
1545
+ return new Response(
1546
+ `OAuth callback failed: No callback URL stored for server ${serverId}`,
1547
+ { status: 500 }
1548
+ );
1549
+ }
1550
+
1551
+ this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);
1552
+
1553
+ // Restore connection if not in memory
1554
+ if (!this.mcp.mcpConnections[serverId]) {
1555
+ let parsedOptions:
1556
+ | {
1557
+ client?: ConstructorParameters<typeof Client>[1];
1558
+ transport?: {
1559
+ headers?: HeadersInit;
1560
+ type?: TransportType;
1561
+ };
1562
+ }
1563
+ | undefined;
1564
+ try {
1565
+ parsedOptions = server.server_options
1566
+ ? JSON.parse(server.server_options)
1567
+ : undefined;
1568
+ } catch {
1569
+ return new Response(
1570
+ `OAuth callback failed: Invalid server options in database for ${serverId}`,
1571
+ { status: 500 }
1572
+ );
1573
+ }
1574
+
1575
+ await this._connectToMcpServerInternal(
1576
+ server.name,
1577
+ server.server_url,
1578
+ server.callback_url,
1579
+ parsedOptions,
1580
+ {
1581
+ id: server.id,
1582
+ oauthClientId: server.client_id ?? undefined
1583
+ }
1584
+ );
1585
+ }
1586
+
1587
+ // Now process the OAuth callback
1588
+ return this._processOAuthCallback(request);
1589
+ } catch (error) {
1590
+ const errorMsg = error instanceof Error ? error.message : "Unknown error";
1591
+ console.error(`Failed to restore MCP state for ${serverId}:`, error);
1592
+ return new Response(
1593
+ `OAuth callback failed during state restoration: ${errorMsg}`,
1594
+ { status: 500 }
1595
+ );
1596
+ }
1597
+ }
1598
+
1599
+ /**
1600
+ * Process an OAuth callback request (assumes state is already restored)
1601
+ */
1602
+ private async _processOAuthCallback(request: Request): Promise<Response> {
1603
+ const result = await this.mcp.handleCallbackRequest(request);
1604
+ this.broadcastMcpServers();
1605
+
1606
+ if (result.authSuccess) {
1607
+ // Start background connection if auth was successful
1608
+ this.mcp
1609
+ .establishConnection(result.serverId)
1610
+ .catch((error) => {
1611
+ console.error("Background connection failed:", error);
1612
+ })
1613
+ .finally(() => {
1614
+ // Broadcast after background connection resolves (success/failure)
1615
+ this.broadcastMcpServers();
1616
+ });
1617
+ }
1618
+
1619
+ // Handle OAuth callback response using MCPClientManager configuration
1620
+ return this.handleOAuthCallbackResponse(result, request);
1621
+ }
1622
+
1623
+ private async _connectToMcpServerInternal(
1624
+ _serverName: string,
1625
+ url: string,
1626
+ callbackUrl: string,
1627
+ // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
1628
+ options?: {
1629
+ client?: ConstructorParameters<typeof Client>[1];
1630
+ /**
1631
+ * We don't expose the normal set of transport options because:
1632
+ * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
1633
+ * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
1634
+ *
1635
+ * 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).
1636
+ */
1637
+ transport?: {
1638
+ headers?: HeadersInit;
1639
+ type?: TransportType;
1640
+ };
1641
+ },
1642
+ reconnect?: {
1643
+ id: string;
1644
+ oauthClientId?: string;
1645
+ }
1646
+ ): Promise<{
1647
+ id: string;
1648
+ authUrl: string | undefined;
1649
+ clientId: string | undefined;
1650
+ }> {
1651
+ const authProvider = new DurableObjectOAuthClientProvider(
1652
+ this.ctx.storage,
1653
+ this.name,
1654
+ callbackUrl
1655
+ );
1656
+
1657
+ if (reconnect) {
1658
+ authProvider.serverId = reconnect.id;
1659
+ if (reconnect.oauthClientId) {
1660
+ authProvider.clientId = reconnect.oauthClientId;
1661
+ }
1662
+ }
1663
+
1664
+ // Use the transport type specified in options, or default to "auto"
1665
+ const transportType: TransportType = options?.transport?.type ?? "auto";
1666
+
1667
+ // allows passing through transport headers if necessary
1668
+ // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
1669
+ let headerTransportOpts: SSEClientTransportOptions = {};
1670
+ if (options?.transport?.headers) {
1671
+ headerTransportOpts = {
1672
+ eventSourceInit: {
1673
+ fetch: (url, init) =>
1674
+ fetch(url, {
1675
+ ...init,
1676
+ headers: options?.transport?.headers
1677
+ })
1678
+ },
1679
+ requestInit: {
1680
+ headers: options?.transport?.headers
1681
+ }
1682
+ };
1683
+ }
1684
+
1685
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
1686
+ client: options?.client,
1687
+ reconnect,
1688
+ transport: {
1689
+ ...headerTransportOpts,
1690
+ authProvider,
1691
+ type: transportType
1692
+ }
1693
+ });
1694
+
1695
+ return {
1696
+ authUrl,
1697
+ clientId,
1698
+ id
1699
+ };
1700
+ }
1701
+
1702
+ async removeMcpServer(id: string) {
1703
+ this.mcp.closeConnection(id);
1704
+ this.mcp.unregisterCallbackUrl(id);
1705
+ this.sql`
1706
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1707
+ `;
1708
+ this.broadcastMcpServers();
1709
+ }
1710
+
1711
+ getMcpServers(): MCPServersState {
1712
+ const mcpState: MCPServersState = {
1713
+ prompts: this.mcp.listPrompts(),
1714
+ resources: this.mcp.listResources(),
1715
+ servers: {},
1716
+ tools: this.mcp.listTools()
1717
+ };
1718
+
1719
+ const servers = this.sql<MCPServerRow>`
1720
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1721
+ `;
1722
+
1723
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1724
+ for (const server of servers) {
1725
+ const serverConn = this.mcp.mcpConnections[server.id];
1726
+ mcpState.servers[server.id] = {
1727
+ auth_url: server.auth_url,
1728
+ capabilities: serverConn?.serverCapabilities ?? null,
1729
+ instructions: serverConn?.instructions ?? null,
1730
+ name: server.name,
1731
+ server_url: server.server_url,
1732
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1733
+ state: serverConn?.connectionState ?? "authenticating"
1734
+ };
1735
+ }
1736
+ }
1737
+
1738
+ return mcpState;
1739
+ }
1740
+
1741
+ private broadcastMcpServers() {
1742
+ this.broadcast(
1743
+ JSON.stringify({
1744
+ mcp: this.getMcpServers(),
1745
+ type: MessageType.CF_AGENT_MCP_SERVERS
1746
+ })
1747
+ );
1748
+ }
1749
+
1750
+ /**
1751
+ * Handle OAuth callback response using MCPClientManager configuration
1752
+ * @param result OAuth callback result
1753
+ * @param request The original request (needed for base URL)
1754
+ * @returns Response for the OAuth callback
1755
+ */
1756
+ private handleOAuthCallbackResponse(
1757
+ result: MCPClientOAuthResult,
1758
+ request: Request
1759
+ ): Response {
1760
+ const config = this.mcp.getOAuthCallbackConfig();
1761
+
1762
+ // Use custom handler if configured
1763
+ if (config?.customHandler) {
1764
+ return config.customHandler(result);
1765
+ }
1766
+
1767
+ // Use redirect URLs if configured
1768
+ if (config?.successRedirect && result.authSuccess) {
1769
+ return Response.redirect(config.successRedirect);
1770
+ }
1771
+
1772
+ if (config?.errorRedirect && !result.authSuccess) {
1773
+ return Response.redirect(
1774
+ `${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`
1775
+ );
1776
+ }
1777
+
1778
+ // Default behavior - redirect to base URL
1779
+ const baseUrl = new URL(request.url).origin;
1780
+ return Response.redirect(baseUrl);
1781
+ }
749
1782
  }
750
1783
 
1784
+ // A set of classes that have been wrapped with agent context
1785
+ const wrappedClasses = new Set<typeof Agent.prototype.constructor>();
1786
+
751
1787
  /**
752
1788
  * Namespace for creating Agent instances
753
1789
  * @template Agentic Type of the Agent class
@@ -785,17 +1821,17 @@ export async function routeAgentRequest<Env>(
785
1821
  const corsHeaders =
786
1822
  options?.cors === true
787
1823
  ? {
788
- "Access-Control-Allow-Origin": "*",
789
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
790
1824
  "Access-Control-Allow-Credentials": "true",
791
- "Access-Control-Max-Age": "86400",
1825
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1826
+ "Access-Control-Allow-Origin": "*",
1827
+ "Access-Control-Max-Age": "86400"
792
1828
  }
793
1829
  : options?.cors;
794
1830
 
795
1831
  if (request.method === "OPTIONS") {
796
1832
  if (corsHeaders) {
797
1833
  return new Response(null, {
798
- headers: corsHeaders,
1834
+ headers: corsHeaders
799
1835
  });
800
1836
  }
801
1837
  console.warn(
@@ -808,7 +1844,7 @@ export async function routeAgentRequest<Env>(
808
1844
  env as Record<string, unknown>,
809
1845
  {
810
1846
  prefix: "agents",
811
- ...(options as PartyServerOptions<Record<string, unknown>>),
1847
+ ...(options as PartyServerOptions<Record<string, unknown>>)
812
1848
  }
813
1849
  );
814
1850
 
@@ -821,24 +1857,238 @@ export async function routeAgentRequest<Env>(
821
1857
  response = new Response(response.body, {
822
1858
  headers: {
823
1859
  ...response.headers,
824
- ...corsHeaders,
825
- },
1860
+ ...corsHeaders
1861
+ }
826
1862
  });
827
1863
  }
828
1864
  return response;
829
1865
  }
830
1866
 
1867
+ export type EmailResolver<Env> = (
1868
+ email: ForwardableEmailMessage,
1869
+ env: Env
1870
+ ) => Promise<{
1871
+ agentName: string;
1872
+ agentId: string;
1873
+ } | null>;
1874
+
1875
+ /**
1876
+ * Create a resolver that uses the message-id header to determine the agent to route the email to
1877
+ * @returns A function that resolves the agent to route the email to
1878
+ */
1879
+ export function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {
1880
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1881
+ const messageId = email.headers.get("message-id");
1882
+ if (messageId) {
1883
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1884
+ if (messageIdMatch) {
1885
+ const [, agentId, domain] = messageIdMatch;
1886
+ const agentName = domain.split(".")[0];
1887
+ return { agentName, agentId };
1888
+ }
1889
+ }
1890
+
1891
+ const references = email.headers.get("references");
1892
+ if (references) {
1893
+ const referencesMatch = references.match(
1894
+ /<([A-Za-z0-9+/]{43}=)@([^>]+)>/
1895
+ );
1896
+ if (referencesMatch) {
1897
+ const [, base64Id, domain] = referencesMatch;
1898
+ const agentId = Buffer.from(base64Id, "base64").toString("hex");
1899
+ const agentName = domain.split(".")[0];
1900
+ return { agentName, agentId };
1901
+ }
1902
+ }
1903
+
1904
+ const agentName = email.headers.get("x-agent-name");
1905
+ const agentId = email.headers.get("x-agent-id");
1906
+ if (agentName && agentId) {
1907
+ return { agentName, agentId };
1908
+ }
1909
+
1910
+ return null;
1911
+ };
1912
+ }
1913
+
1914
+ /**
1915
+ * Create a resolver that uses the email address to determine the agent to route the email to
1916
+ * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
1917
+ * @returns A function that resolves the agent to route the email to
1918
+ */
1919
+ export function createAddressBasedEmailResolver<Env>(
1920
+ defaultAgentName: string
1921
+ ): EmailResolver<Env> {
1922
+ return async (email: ForwardableEmailMessage, _env: Env) => {
1923
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1924
+ if (!emailMatch) {
1925
+ return null;
1926
+ }
1927
+
1928
+ const [, localPart, subAddress] = emailMatch;
1929
+
1930
+ if (subAddress) {
1931
+ return {
1932
+ agentName: localPart,
1933
+ agentId: subAddress
1934
+ };
1935
+ }
1936
+
1937
+ // Option 2: Use defaultAgentName namespace, localPart as agentId
1938
+ // Common for catch-all email routing to a single EmailAgent namespace
1939
+ return {
1940
+ agentName: defaultAgentName,
1941
+ agentId: localPart
1942
+ };
1943
+ };
1944
+ }
1945
+
1946
+ /**
1947
+ * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
1948
+ * @param agentName The name of the agent to route the email to
1949
+ * @param agentId The id of the agent to route the email to
1950
+ * @returns A function that resolves the agent to route the email to
1951
+ */
1952
+ export function createCatchAllEmailResolver<Env>(
1953
+ agentName: string,
1954
+ agentId: string
1955
+ ): EmailResolver<Env> {
1956
+ return async () => ({ agentName, agentId });
1957
+ }
1958
+
1959
+ export type EmailRoutingOptions<Env> = AgentOptions<Env> & {
1960
+ resolver: EmailResolver<Env>;
1961
+ };
1962
+
1963
+ // Cache the agent namespace map for email routing
1964
+ // This maps both kebab-case and original names to namespaces
1965
+ const agentMapCache = new WeakMap<
1966
+ Record<string, unknown>,
1967
+ Record<string, unknown>
1968
+ >();
1969
+
831
1970
  /**
832
1971
  * Route an email to the appropriate Agent
833
- * @param email Email message to route
834
- * @param env Environment containing Agent bindings
835
- * @param options Routing options
1972
+ * @param email The email to route
1973
+ * @param env The environment containing the Agent bindings
1974
+ * @param options The options for routing the email
1975
+ * @returns A promise that resolves when the email has been routed
836
1976
  */
837
1977
  export async function routeAgentEmail<Env>(
838
1978
  email: ForwardableEmailMessage,
839
1979
  env: Env,
840
- options?: AgentOptions<Env>
841
- ): Promise<void> {}
1980
+ options: EmailRoutingOptions<Env>
1981
+ ): Promise<void> {
1982
+ const routingInfo = await options.resolver(email, env);
1983
+
1984
+ if (!routingInfo) {
1985
+ console.warn("No routing information found for email, dropping message");
1986
+ return;
1987
+ }
1988
+
1989
+ // Build a map that includes both original names and kebab-case versions
1990
+ if (!agentMapCache.has(env as Record<string, unknown>)) {
1991
+ const map: Record<string, unknown> = {};
1992
+ for (const [key, value] of Object.entries(env as Record<string, unknown>)) {
1993
+ if (
1994
+ value &&
1995
+ typeof value === "object" &&
1996
+ "idFromName" in value &&
1997
+ typeof value.idFromName === "function"
1998
+ ) {
1999
+ // Add both the original name and kebab-case version
2000
+ map[key] = value;
2001
+ map[camelCaseToKebabCase(key)] = value;
2002
+ }
2003
+ }
2004
+ agentMapCache.set(env as Record<string, unknown>, map);
2005
+ }
2006
+
2007
+ const agentMap = agentMapCache.get(env as Record<string, unknown>)!;
2008
+ const namespace = agentMap[routingInfo.agentName];
2009
+
2010
+ if (!namespace) {
2011
+ // Provide helpful error message listing available agents
2012
+ const availableAgents = Object.keys(agentMap)
2013
+ .filter((key) => !key.includes("-")) // Show only original names, not kebab-case duplicates
2014
+ .join(", ");
2015
+ throw new Error(
2016
+ `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`
2017
+ );
2018
+ }
2019
+
2020
+ const agent = await getAgentByName(
2021
+ namespace as unknown as AgentNamespace<Agent<Env>>,
2022
+ routingInfo.agentId
2023
+ );
2024
+
2025
+ // let's make a serialisable version of the email
2026
+ const serialisableEmail: AgentEmail = {
2027
+ getRaw: async () => {
2028
+ const reader = email.raw.getReader();
2029
+ const chunks: Uint8Array[] = [];
2030
+
2031
+ let done = false;
2032
+ while (!done) {
2033
+ const { value, done: readerDone } = await reader.read();
2034
+ done = readerDone;
2035
+ if (value) {
2036
+ chunks.push(value);
2037
+ }
2038
+ }
2039
+
2040
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
2041
+ const combined = new Uint8Array(totalLength);
2042
+ let offset = 0;
2043
+ for (const chunk of chunks) {
2044
+ combined.set(chunk, offset);
2045
+ offset += chunk.length;
2046
+ }
2047
+
2048
+ return combined;
2049
+ },
2050
+ headers: email.headers,
2051
+ rawSize: email.rawSize,
2052
+ setReject: (reason: string) => {
2053
+ email.setReject(reason);
2054
+ },
2055
+ forward: (rcptTo: string, headers?: Headers) => {
2056
+ return email.forward(rcptTo, headers);
2057
+ },
2058
+ reply: (options: { from: string; to: string; raw: string }) => {
2059
+ return email.reply(
2060
+ new EmailMessage(options.from, options.to, options.raw)
2061
+ );
2062
+ },
2063
+ from: email.from,
2064
+ to: email.to
2065
+ };
2066
+
2067
+ await agent._onEmail(serialisableEmail);
2068
+ }
2069
+
2070
+ export type AgentEmail = {
2071
+ from: string;
2072
+ to: string;
2073
+ getRaw: () => Promise<Uint8Array>;
2074
+ headers: Headers;
2075
+ rawSize: number;
2076
+ setReject: (reason: string) => void;
2077
+ forward: (rcptTo: string, headers?: Headers) => Promise<void>;
2078
+ reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
2079
+ };
2080
+
2081
+ export type EmailSendOptions = {
2082
+ to: string;
2083
+ subject: string;
2084
+ body: string;
2085
+ contentType?: string;
2086
+ headers?: Record<string, string>;
2087
+ includeRoutingHeaders?: boolean;
2088
+ agentName?: string;
2089
+ agentId?: string;
2090
+ domain?: string;
2091
+ };
842
2092
 
843
2093
  /**
844
2094
  * Get or create an Agent by name
@@ -849,12 +2099,17 @@ export async function routeAgentEmail<Env>(
849
2099
  * @param options Options for Agent creation
850
2100
  * @returns Promise resolving to an Agent instance stub
851
2101
  */
852
- export function getAgentByName<Env, T extends Agent<Env>>(
2102
+ export async function getAgentByName<
2103
+ Env,
2104
+ T extends Agent<Env>,
2105
+ Props extends Record<string, unknown> = Record<string, unknown>
2106
+ >(
853
2107
  namespace: AgentNamespace<T>,
854
2108
  name: string,
855
2109
  options?: {
856
2110
  jurisdiction?: DurableObjectJurisdiction;
857
2111
  locationHint?: DurableObjectLocationHint;
2112
+ props?: Props;
858
2113
  }
859
2114
  ) {
860
2115
  return getServerByName<Env, T>(namespace, name, options);
@@ -864,13 +2119,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
864
2119
  * A wrapper for streaming responses in callable methods
865
2120
  */
866
2121
  export class StreamingResponse {
867
- #connection: Connection;
868
- #id: string;
869
- #closed = false;
2122
+ private _connection: Connection;
2123
+ private _id: string;
2124
+ private _closed = false;
870
2125
 
871
2126
  constructor(connection: Connection, id: string) {
872
- this.#connection = connection;
873
- this.#id = id;
2127
+ this._connection = connection;
2128
+ this._id = id;
874
2129
  }
875
2130
 
876
2131
  /**
@@ -878,17 +2133,17 @@ export class StreamingResponse {
878
2133
  * @param chunk The data to send
879
2134
  */
880
2135
  send(chunk: unknown) {
881
- if (this.#closed) {
2136
+ if (this._closed) {
882
2137
  throw new Error("StreamingResponse is already closed");
883
2138
  }
884
2139
  const response: RPCResponse = {
885
- type: "rpc",
886
- id: this.#id,
887
- success: true,
888
- result: chunk,
889
2140
  done: false,
2141
+ id: this._id,
2142
+ result: chunk,
2143
+ success: true,
2144
+ type: MessageType.RPC
890
2145
  };
891
- this.#connection.send(JSON.stringify(response));
2146
+ this._connection.send(JSON.stringify(response));
892
2147
  }
893
2148
 
894
2149
  /**
@@ -896,17 +2151,17 @@ export class StreamingResponse {
896
2151
  * @param finalChunk Optional final chunk of data to send
897
2152
  */
898
2153
  end(finalChunk?: unknown) {
899
- if (this.#closed) {
2154
+ if (this._closed) {
900
2155
  throw new Error("StreamingResponse is already closed");
901
2156
  }
902
- this.#closed = true;
2157
+ this._closed = true;
903
2158
  const response: RPCResponse = {
904
- type: "rpc",
905
- id: this.#id,
906
- success: true,
907
- result: finalChunk,
908
2159
  done: true,
2160
+ id: this._id,
2161
+ result: finalChunk,
2162
+ success: true,
2163
+ type: MessageType.RPC
909
2164
  };
910
- this.#connection.send(JSON.stringify(response));
2165
+ this._connection.send(JSON.stringify(response));
911
2166
  }
912
2167
  }