agents 0.0.0-e4a2352 → 0.0.0-e8f693b

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