agents 0.0.0-352d62c → 0.0.0-35951

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