agents 0.0.0-fbaa8f7 → 0.0.0-fce47ef

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 (44) hide show
  1. package/README.md +2 -6
  2. package/dist/ai-chat-agent.d.ts +50 -7
  3. package/dist/ai-chat-agent.js +132 -63
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +22 -7
  6. package/dist/ai-react.js +62 -48
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/ai-types.d.ts +5 -0
  9. package/dist/chunk-767EASBA.js +106 -0
  10. package/dist/chunk-767EASBA.js.map +1 -0
  11. package/dist/chunk-E3LCYPCB.js +469 -0
  12. package/dist/chunk-E3LCYPCB.js.map +1 -0
  13. package/dist/chunk-NKZZ66QY.js +116 -0
  14. package/dist/chunk-NKZZ66QY.js.map +1 -0
  15. package/dist/chunk-ZRRXJUAA.js +788 -0
  16. package/dist/chunk-ZRRXJUAA.js.map +1 -0
  17. package/dist/client.d.ts +15 -1
  18. package/dist/client.js +6 -133
  19. package/dist/client.js.map +1 -1
  20. package/dist/index.d.ts +123 -18
  21. package/dist/index.js +6 -4
  22. package/dist/mcp/client.d.ts +783 -0
  23. package/dist/mcp/client.js +9 -0
  24. package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
  25. package/dist/mcp/do-oauth-client-provider.js +7 -0
  26. package/dist/mcp/do-oauth-client-provider.js.map +1 -0
  27. package/dist/mcp/index.d.ts +84 -0
  28. package/dist/mcp/index.js +783 -0
  29. package/dist/mcp/index.js.map +1 -0
  30. package/dist/react.d.ts +85 -5
  31. package/dist/react.js +50 -31
  32. package/dist/react.js.map +1 -1
  33. package/dist/schedule.d.ts +2 -2
  34. package/dist/schedule.js +4 -6
  35. package/dist/schedule.js.map +1 -1
  36. package/dist/serializable.d.ts +32 -0
  37. package/dist/serializable.js +1 -0
  38. package/dist/serializable.js.map +1 -0
  39. package/package.json +79 -43
  40. package/src/index.ts +558 -155
  41. package/dist/chunk-HMLY7DHA.js +0 -16
  42. package/dist/chunk-PDF5WEP4.js +0 -542
  43. package/dist/chunk-PDF5WEP4.js.map +0 -1
  44. /package/dist/{chunk-HMLY7DHA.js.map → mcp/client.js.map} +0 -0
package/src/index.ts CHANGED
@@ -1,19 +1,30 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
+ import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
4
+
5
+ import type {
6
+ Prompt,
7
+ Resource,
8
+ ServerCapabilities,
9
+ Tool,
10
+ } from "@modelcontextprotocol/sdk/types.js";
11
+ import { parseCronExpression } from "cron-schedule";
12
+ import { nanoid } from "nanoid";
1
13
  import {
2
- Server,
3
- routePartykitRequest,
4
- type PartyServerOptions,
5
- getServerByName,
6
14
  type Connection,
7
15
  type ConnectionContext,
16
+ getServerByName,
17
+ type PartyServerOptions,
18
+ routePartykitRequest,
19
+ Server,
8
20
  type WSMessage,
9
21
  } from "partyserver";
22
+ import { camelCaseToKebabCase } from "./client";
23
+ import { MCPClientManager } from "./mcp/client";
24
+ // import type { MCPClientConnection } from "./mcp/client-connection";
25
+ import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
10
26
 
11
- import { parseCronExpression } from "cron-schedule";
12
- import { nanoid } from "nanoid";
13
-
14
- export type { Connection, WSMessage, ConnectionContext } from "partyserver";
15
-
16
- import { WorkflowEntrypoint as CFWorkflowEntrypoint } from "cloudflare:workers";
27
+ export type { Connection, ConnectionContext, WSMessage } from "partyserver";
17
28
 
18
29
  /**
19
30
  * RPC request message from client
@@ -97,7 +108,6 @@ export type CallableMetadata = {
97
108
  streaming?: boolean;
98
109
  };
99
110
 
100
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
101
111
  const callableMetadata = new Map<Function, CallableMetadata>();
102
112
 
103
113
  /**
@@ -107,6 +117,7 @@ const callableMetadata = new Map<Function, CallableMetadata>();
107
117
  export function unstable_callable(metadata: CallableMetadata = {}) {
108
118
  return function callableDecorator<This, Args extends unknown[], Return>(
109
119
  target: (this: This, ...args: Args) => Return,
120
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: later
110
121
  context: ClassMethodDecoratorContext
111
122
  ) {
112
123
  if (!callableMetadata.has(target)) {
@@ -117,11 +128,6 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
117
128
  };
118
129
  }
119
130
 
120
- /**
121
- * A class for creating workflow entry points that can be used with Cloudflare Workers
122
- */
123
- export class WorkflowEntrypoint extends CFWorkflowEntrypoint {}
124
-
125
131
  /**
126
132
  * Represents a scheduled task within an Agent
127
133
  * @template T Type of the payload data
@@ -163,18 +169,95 @@ function getNextCronTime(cron: string) {
163
169
  return interval.getNextDate();
164
170
  }
165
171
 
172
+ /**
173
+ * MCP Server state update message from server -> Client
174
+ */
175
+ export type MCPServerMessage = {
176
+ type: "cf_agent_mcp_servers";
177
+ mcp: MCPServersState;
178
+ };
179
+
180
+ export type MCPServersState = {
181
+ servers: {
182
+ [id: string]: MCPServer;
183
+ };
184
+ tools: Tool[];
185
+ prompts: Prompt[];
186
+ resources: Resource[];
187
+ };
188
+
189
+ export type MCPServer = {
190
+ name: string;
191
+ server_url: string;
192
+ auth_url: string | null;
193
+ // This state is specifically about the temporary process of getting a token (if needed).
194
+ // Scope outside of that can't be relied upon because when the DO sleeps, there's no way
195
+ // to communicate a change to a non-ready state.
196
+ state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
197
+ instructions: string | null;
198
+ capabilities: ServerCapabilities | null;
199
+ };
200
+
201
+ /**
202
+ * MCP Server data stored in DO SQL for resuming MCP Server connections
203
+ */
204
+ type MCPServerRow = {
205
+ id: string;
206
+ name: string;
207
+ server_url: string;
208
+ client_id: string | null;
209
+ auth_url: string | null;
210
+ callback_url: string;
211
+ server_options: string;
212
+ };
213
+
166
214
  const STATE_ROW_ID = "cf_state_row_id";
167
215
  const STATE_WAS_CHANGED = "cf_state_was_changed";
168
216
 
169
217
  const DEFAULT_STATE = {} as unknown;
170
218
 
219
+ const agentContext = new AsyncLocalStorage<{
220
+ agent: Agent<unknown>;
221
+ connection: Connection | undefined;
222
+ request: Request | undefined;
223
+ }>();
224
+
225
+ export function getCurrentAgent<
226
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
227
+ >(): {
228
+ agent: T | undefined;
229
+ connection: Connection | undefined;
230
+ request: Request<unknown, CfProperties<unknown>> | undefined;
231
+ } {
232
+ const store = agentContext.getStore() as
233
+ | {
234
+ agent: T;
235
+ connection: Connection | undefined;
236
+ request: Request<unknown, CfProperties<unknown>> | undefined;
237
+ }
238
+ | undefined;
239
+ if (!store) {
240
+ return {
241
+ agent: undefined,
242
+ connection: undefined,
243
+ request: undefined,
244
+ };
245
+ }
246
+ return store;
247
+ }
248
+
171
249
  /**
172
250
  * Base class for creating Agent implementations
173
251
  * @template Env Environment type containing bindings
174
252
  * @template State State type to store within the Agent
175
253
  */
176
254
  export class Agent<Env, State = unknown> extends Server<Env> {
177
- #state = DEFAULT_STATE as State;
255
+ private _state = DEFAULT_STATE as State;
256
+
257
+ private _ParentClass: typeof Agent<Env, State> =
258
+ Object.getPrototypeOf(this).constructor;
259
+
260
+ mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
178
261
 
179
262
  /**
180
263
  * Initial state for the Agent
@@ -186,9 +269,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
186
269
  * Current state of the Agent
187
270
  */
188
271
  get state(): State {
189
- if (this.#state !== DEFAULT_STATE) {
272
+ if (this._state !== DEFAULT_STATE) {
190
273
  // state was previously set, and populated internal state
191
- return this.#state;
274
+ return this._state;
192
275
  }
193
276
  // looks like this is the first time the state is being accessed
194
277
  // check if the state was set in a previous life
@@ -208,8 +291,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
208
291
  ) {
209
292
  const state = result[0]?.state as string; // could be null?
210
293
 
211
- this.#state = JSON.parse(state);
212
- return this.#state;
294
+ this._state = JSON.parse(state);
295
+ return this._state;
213
296
  }
214
297
 
215
298
  // ok, this is the first time the state is being accessed
@@ -256,7 +339,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
256
339
  return [...this.ctx.storage.sql.exec(query, ...values)] as T[];
257
340
  } catch (e) {
258
341
  console.error(`failed to execute sql query: ${query}`, e);
259
- throw e;
342
+ throw this.onError(e);
260
343
  }
261
344
  }
262
345
  constructor(ctx: AgentContext, env: Env) {
@@ -270,7 +353,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
270
353
  `;
271
354
 
272
355
  void this.ctx.blockConcurrencyWhile(async () => {
273
- try {
356
+ return this._tryCatch(async () => {
274
357
  // Create alarms table if it doesn't exist
275
358
  this.sql`
276
359
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
@@ -287,102 +370,201 @@ export class Agent<Env, State = unknown> extends Server<Env> {
287
370
 
288
371
  // execute any pending alarms and schedule the next alarm
289
372
  await this.alarm();
290
- } catch (e) {
291
- console.error(e);
292
- throw e;
293
- }
373
+ });
294
374
  });
295
375
 
296
- const _onMessage = this.onMessage.bind(this);
297
- this.onMessage = async (connection: Connection, message: WSMessage) => {
298
- if (typeof message !== "string") {
299
- return _onMessage(connection, message);
300
- }
301
-
302
- let parsed: unknown;
303
- try {
304
- parsed = JSON.parse(message);
305
- } catch (e) {
306
- // silently fail and let the onMessage handler handle it
307
- return _onMessage(connection, message);
308
- }
376
+ this.sql`
377
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
378
+ id TEXT PRIMARY KEY NOT NULL,
379
+ name TEXT NOT NULL,
380
+ server_url TEXT NOT NULL,
381
+ callback_url TEXT NOT NULL,
382
+ client_id TEXT,
383
+ auth_url TEXT,
384
+ server_options TEXT
385
+ )
386
+ `;
309
387
 
310
- if (isStateUpdateMessage(parsed)) {
311
- this.#setStateInternal(parsed.state as State, connection);
312
- return;
313
- }
388
+ const _onRequest = this.onRequest.bind(this);
389
+ this.onRequest = (request: Request) => {
390
+ return agentContext.run(
391
+ { agent: this, connection: undefined, request },
392
+ async () => {
393
+ if (this.mcp.isCallbackRequest(request)) {
394
+ await this.mcp.handleCallbackRequest(request);
395
+
396
+ // after the MCP connection handshake, we can send updated mcp state
397
+ this.broadcast(
398
+ JSON.stringify({
399
+ mcp: this.getMcpServers(),
400
+ type: "cf_agent_mcp_servers",
401
+ })
402
+ );
403
+
404
+ // We probably should let the user configure this response/redirect, but this is fine for now.
405
+ return new Response("<script>window.close();</script>", {
406
+ headers: { "content-type": "text/html" },
407
+ status: 200,
408
+ });
409
+ }
314
410
 
315
- if (isRPCRequest(parsed)) {
316
- try {
317
- const { id, method, args } = parsed;
411
+ return this._tryCatch(() => _onRequest(request));
412
+ }
413
+ );
414
+ };
318
415
 
319
- // Check if method exists and is callable
320
- const methodFn = this[method as keyof this];
321
- if (typeof methodFn !== "function") {
322
- throw new Error(`Method ${method} does not exist`);
416
+ const _onMessage = this.onMessage.bind(this);
417
+ this.onMessage = async (connection: Connection, message: WSMessage) => {
418
+ return agentContext.run(
419
+ { agent: this, connection, request: undefined },
420
+ async () => {
421
+ if (typeof message !== "string") {
422
+ return this._tryCatch(() => _onMessage(connection, message));
323
423
  }
324
424
 
325
- if (!this.isCallable(method)) {
326
- throw new Error(`Method ${method} is not callable`);
425
+ let parsed: unknown;
426
+ try {
427
+ parsed = JSON.parse(message);
428
+ } catch (_e) {
429
+ // silently fail and let the onMessage handler handle it
430
+ return this._tryCatch(() => _onMessage(connection, message));
327
431
  }
328
432
 
329
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
330
- const metadata = callableMetadata.get(methodFn as Function);
433
+ if (isStateUpdateMessage(parsed)) {
434
+ this._setStateInternal(parsed.state as State, connection);
435
+ return;
436
+ }
331
437
 
332
- // For streaming methods, pass a StreamingResponse object
333
- if (metadata?.streaming) {
334
- const stream = new StreamingResponse(connection, id);
335
- await methodFn.apply(this, [stream, ...args]);
438
+ if (isRPCRequest(parsed)) {
439
+ try {
440
+ const { id, method, args } = parsed;
441
+
442
+ // Check if method exists and is callable
443
+ const methodFn = this[method as keyof this];
444
+ if (typeof methodFn !== "function") {
445
+ throw new Error(`Method ${method} does not exist`);
446
+ }
447
+
448
+ if (!this._isCallable(method)) {
449
+ throw new Error(`Method ${method} is not callable`);
450
+ }
451
+
452
+ const metadata = callableMetadata.get(methodFn as Function);
453
+
454
+ // For streaming methods, pass a StreamingResponse object
455
+ if (metadata?.streaming) {
456
+ const stream = new StreamingResponse(connection, id);
457
+ await methodFn.apply(this, [stream, ...args]);
458
+ return;
459
+ }
460
+
461
+ // For regular methods, execute and send response
462
+ const result = await methodFn.apply(this, args);
463
+ const response: RPCResponse = {
464
+ done: true,
465
+ id,
466
+ result,
467
+ success: true,
468
+ type: "rpc",
469
+ };
470
+ connection.send(JSON.stringify(response));
471
+ } catch (e) {
472
+ // Send error response
473
+ const response: RPCResponse = {
474
+ error:
475
+ e instanceof Error ? e.message : "Unknown error occurred",
476
+ id: parsed.id,
477
+ success: false,
478
+ type: "rpc",
479
+ };
480
+ connection.send(JSON.stringify(response));
481
+ console.error("RPC error:", e);
482
+ }
336
483
  return;
337
484
  }
338
485
 
339
- // For regular methods, execute and send response
340
- const result = await methodFn.apply(this, args);
341
- const response: RPCResponse = {
342
- type: "rpc",
343
- id,
344
- success: true,
345
- result,
346
- done: true,
347
- };
348
- connection.send(JSON.stringify(response));
349
- } catch (e) {
350
- // Send error response
351
- const response: RPCResponse = {
352
- type: "rpc",
353
- id: parsed.id,
354
- success: false,
355
- error: e instanceof Error ? e.message : "Unknown error occurred",
356
- };
357
- connection.send(JSON.stringify(response));
358
- console.error("RPC error:", e);
486
+ return this._tryCatch(() => _onMessage(connection, message));
359
487
  }
360
- return;
361
- }
362
-
363
- return _onMessage(connection, message);
488
+ );
364
489
  };
365
490
 
366
491
  const _onConnect = this.onConnect.bind(this);
367
492
  this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
368
493
  // TODO: This is a hack to ensure the state is sent after the connection is established
369
494
  // must fix this
370
- setTimeout(() => {
371
- if (this.state) {
372
- connection.send(
495
+ return agentContext.run(
496
+ { agent: this, connection, request: ctx.request },
497
+ async () => {
498
+ setTimeout(() => {
499
+ if (this.state) {
500
+ connection.send(
501
+ JSON.stringify({
502
+ state: this.state,
503
+ type: "cf_agent_state",
504
+ })
505
+ );
506
+ }
507
+
508
+ connection.send(
509
+ JSON.stringify({
510
+ mcp: this.getMcpServers(),
511
+ type: "cf_agent_mcp_servers",
512
+ })
513
+ );
514
+
515
+ return this._tryCatch(() => _onConnect(connection, ctx));
516
+ }, 20);
517
+ }
518
+ );
519
+ };
520
+
521
+ const _onStart = this.onStart.bind(this);
522
+ this.onStart = async () => {
523
+ return agentContext.run(
524
+ { agent: this, connection: undefined, request: undefined },
525
+ async () => {
526
+ const servers = this.sql<MCPServerRow>`
527
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
528
+ `;
529
+
530
+ // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information
531
+ await Promise.allSettled(
532
+ servers
533
+ .filter((server) => server.auth_url === null)
534
+ .map((server) => {
535
+ return this._connectToMcpServerInternal(
536
+ server.name,
537
+ server.server_url,
538
+ server.callback_url,
539
+ server.server_options
540
+ ? JSON.parse(server.server_options)
541
+ : undefined,
542
+ {
543
+ id: server.id,
544
+ oauthClientId: server.client_id ?? undefined,
545
+ }
546
+ );
547
+ })
548
+ );
549
+
550
+ this.broadcast(
373
551
  JSON.stringify({
374
- type: "cf_agent_state",
375
- state: this.state,
552
+ mcp: this.getMcpServers(),
553
+ type: "cf_agent_mcp_servers",
376
554
  })
377
555
  );
556
+
557
+ await this._tryCatch(() => _onStart());
378
558
  }
379
- _onConnect(connection, ctx);
380
- }, 20);
559
+ );
381
560
  };
382
561
  }
383
562
 
384
- #setStateInternal(state: State, source: Connection | "server" = "server") {
385
- this.#state = state;
563
+ private _setStateInternal(
564
+ state: State,
565
+ source: Connection | "server" = "server"
566
+ ) {
567
+ this._state = state;
386
568
  this.sql`
387
569
  INSERT OR REPLACE INTO cf_agents_state (id, state)
388
570
  VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
@@ -393,12 +575,20 @@ export class Agent<Env, State = unknown> extends Server<Env> {
393
575
  `;
394
576
  this.broadcast(
395
577
  JSON.stringify({
396
- type: "cf_agent_state",
397
578
  state: state,
579
+ type: "cf_agent_state",
398
580
  }),
399
581
  source !== "server" ? [source.id] : []
400
582
  );
401
- this.onStateUpdate(state, source);
583
+ return this._tryCatch(() => {
584
+ const { connection, request } = agentContext.getStore() || {};
585
+ return agentContext.run(
586
+ { agent: this, connection, request },
587
+ async () => {
588
+ return this.onStateUpdate(state, source);
589
+ }
590
+ );
591
+ });
402
592
  }
403
593
 
404
594
  /**
@@ -406,7 +596,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
406
596
  * @param state New state to set
407
597
  */
408
598
  setState(state: State) {
409
- this.#setStateInternal(state, "server");
599
+ this._setStateInternal(state, "server");
410
600
  }
411
601
 
412
602
  /**
@@ -414,6 +604,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
414
604
  * @param state Updated state
415
605
  * @param source Source of the state update ("server" or a client connection)
416
606
  */
607
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
417
608
  onStateUpdate(state: State | undefined, source: Connection | "server") {
418
609
  // override this to handle state updates
419
610
  }
@@ -422,8 +613,49 @@ export class Agent<Env, State = unknown> extends Server<Env> {
422
613
  * Called when the Agent receives an email
423
614
  * @param email Email message to process
424
615
  */
616
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
425
617
  onEmail(email: ForwardableEmailMessage) {
426
- throw new Error("Not implemented");
618
+ return agentContext.run(
619
+ { agent: this, connection: undefined, request: undefined },
620
+ async () => {
621
+ console.error("onEmail not implemented");
622
+ }
623
+ );
624
+ }
625
+
626
+ private async _tryCatch<T>(fn: () => T | Promise<T>) {
627
+ try {
628
+ return await fn();
629
+ } catch (e) {
630
+ throw this.onError(e);
631
+ }
632
+ }
633
+
634
+ override onError(
635
+ connection: Connection,
636
+ error: unknown
637
+ ): void | Promise<void>;
638
+ override onError(error: unknown): void | Promise<void>;
639
+ override onError(connectionOrError: Connection | unknown, error?: unknown) {
640
+ let theError: unknown;
641
+ if (connectionOrError && error) {
642
+ theError = error;
643
+ // this is a websocket connection error
644
+ console.error(
645
+ "Error on websocket connection:",
646
+ (connectionOrError as Connection).id,
647
+ theError
648
+ );
649
+ console.error(
650
+ "Override onError(connection, error) to handle websocket connection errors"
651
+ );
652
+ } else {
653
+ theError = connectionOrError;
654
+ // this is a server error
655
+ console.error("Error on server:", theError);
656
+ console.error("Override onError(error) to handle server errors");
657
+ }
658
+ throw theError;
427
659
  }
428
660
 
429
661
  /**
@@ -465,11 +697,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
465
697
  )}, 'scheduled', ${timestamp})
466
698
  `;
467
699
 
468
- await this.scheduleNextAlarm();
700
+ await this._scheduleNextAlarm();
469
701
 
470
702
  return {
471
- id,
472
703
  callback: callback,
704
+ id,
473
705
  payload: payload as T,
474
706
  time: timestamp,
475
707
  type: "scheduled",
@@ -486,13 +718,13 @@ export class Agent<Env, State = unknown> extends Server<Env> {
486
718
  )}, 'delayed', ${when}, ${timestamp})
487
719
  `;
488
720
 
489
- await this.scheduleNextAlarm();
721
+ await this._scheduleNextAlarm();
490
722
 
491
723
  return {
492
- id,
493
724
  callback: callback,
494
- payload: payload as T,
495
725
  delayInSeconds: when,
726
+ id,
727
+ payload: payload as T,
496
728
  time: timestamp,
497
729
  type: "delayed",
498
730
  };
@@ -508,13 +740,13 @@ export class Agent<Env, State = unknown> extends Server<Env> {
508
740
  )}, 'cron', ${when}, ${timestamp})
509
741
  `;
510
742
 
511
- await this.scheduleNextAlarm();
743
+ await this._scheduleNextAlarm();
512
744
 
513
745
  return {
514
- id,
515
746
  callback: callback,
516
- payload: payload as T,
517
747
  cron: when,
748
+ id,
749
+ payload: payload as T,
518
750
  time: timestamp,
519
751
  type: "cron",
520
752
  };
@@ -532,7 +764,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
532
764
  const result = this.sql<Schedule<string>>`
533
765
  SELECT * FROM cf_agents_schedules WHERE id = ${id}
534
766
  `;
535
- if (!result) return undefined;
767
+ if (!result) {
768
+ console.error(`schedule ${id} not found`);
769
+ return undefined;
770
+ }
536
771
 
537
772
  return { ...result[0], payload: JSON.parse(result[0].payload) as T };
538
773
  }
@@ -545,7 +780,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
545
780
  */
546
781
  getSchedules<T = string>(
547
782
  criteria: {
548
- description?: string;
549
783
  id?: string;
550
784
  type?: "scheduled" | "delayed" | "cron";
551
785
  timeRange?: { start?: Date; end?: Date };
@@ -559,11 +793,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
559
793
  params.push(criteria.id);
560
794
  }
561
795
 
562
- if (criteria.description) {
563
- query += " AND description = ?";
564
- params.push(criteria.description);
565
- }
566
-
567
796
  if (criteria.type) {
568
797
  query += " AND type = ?";
569
798
  params.push(criteria.type);
@@ -598,11 +827,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
598
827
  async cancelSchedule(id: string): Promise<boolean> {
599
828
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
600
829
 
601
- await this.scheduleNextAlarm();
830
+ await this._scheduleNextAlarm();
602
831
  return true;
603
832
  }
604
833
 
605
- private async scheduleNextAlarm() {
834
+ private async _scheduleNextAlarm() {
606
835
  // Find the next schedule that needs to be executed
607
836
  const result = this.sql`
608
837
  SELECT time FROM cf_agents_schedules
@@ -619,10 +848,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
619
848
  }
620
849
 
621
850
  /**
622
- * Method called when an alarm fires
623
- * Executes any scheduled tasks that are due
851
+ * Method called when an alarm fires.
852
+ * Executes any scheduled tasks that are due.
853
+ *
854
+ * @remarks
855
+ * To schedule a task, please use the `this.schedule` method instead.
856
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
624
857
  */
625
- async alarm() {
858
+ public readonly alarm = async () => {
626
859
  const now = Math.floor(Date.now() / 1000);
627
860
 
628
861
  // Get all schedules that should be executed now
@@ -636,16 +869,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
636
869
  console.error(`callback ${row.callback} not found`);
637
870
  continue;
638
871
  }
639
- try {
640
- (
641
- callback as (
642
- payload: unknown,
643
- schedule: Schedule<unknown>
644
- ) => Promise<void>
645
- ).bind(this)(JSON.parse(row.payload as string), row);
646
- } catch (e) {
647
- console.error(`error executing callback ${row.callback}`, e);
648
- }
872
+ await agentContext.run(
873
+ { agent: this, connection: undefined, request: undefined },
874
+ async () => {
875
+ try {
876
+ await (
877
+ callback as (
878
+ payload: unknown,
879
+ schedule: Schedule<unknown>
880
+ ) => Promise<void>
881
+ ).bind(this)(JSON.parse(row.payload as string), row);
882
+ } catch (e) {
883
+ console.error(`error executing callback "${row.callback}"`, e);
884
+ }
885
+ }
886
+ );
649
887
  if (row.type === "cron") {
650
888
  // Update next execution time for cron schedules
651
889
  const nextExecutionTime = getNextCronTime(row.cron);
@@ -663,8 +901,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
663
901
  }
664
902
 
665
903
  // Schedule the next alarm
666
- await this.scheduleNextAlarm();
667
- }
904
+ await this._scheduleNextAlarm();
905
+ };
668
906
 
669
907
  /**
670
908
  * Destroy the Agent, removing all state and scheduled tasks
@@ -673,20 +911,184 @@ export class Agent<Env, State = unknown> extends Server<Env> {
673
911
  // drop all tables
674
912
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
675
913
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
914
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
676
915
 
677
916
  // delete all alarms
678
917
  await this.ctx.storage.deleteAlarm();
679
918
  await this.ctx.storage.deleteAll();
919
+ this.ctx.abort("destroyed"); // enforce that the agent is evicted
680
920
  }
681
921
 
682
922
  /**
683
923
  * Get all methods marked as callable on this Agent
684
924
  * @returns A map of method names to their metadata
685
925
  */
686
- private isCallable(method: string): boolean {
687
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
926
+ private _isCallable(method: string): boolean {
688
927
  return callableMetadata.has(this[method as keyof this] as Function);
689
928
  }
929
+
930
+ /**
931
+ * Connect to a new MCP Server
932
+ *
933
+ * @param url MCP Server SSE URL
934
+ * @param callbackHost Base host for the agent, used for the redirect URI.
935
+ * @param agentsPrefix agents routing prefix if not using `agents`
936
+ * @param options MCP client and transport (header) options
937
+ * @returns authUrl
938
+ */
939
+ async addMcpServer(
940
+ serverName: string,
941
+ url: string,
942
+ callbackHost: string,
943
+ agentsPrefix = "agents",
944
+ options?: {
945
+ client?: ConstructorParameters<typeof Client>[1];
946
+ transport?: {
947
+ headers: HeadersInit;
948
+ };
949
+ }
950
+ ): Promise<{ id: string; authUrl: string | undefined }> {
951
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
952
+
953
+ const result = await this._connectToMcpServerInternal(
954
+ serverName,
955
+ url,
956
+ callbackUrl,
957
+ options
958
+ );
959
+
960
+ this.broadcast(
961
+ JSON.stringify({
962
+ mcp: this.getMcpServers(),
963
+ type: "cf_agent_mcp_servers",
964
+ })
965
+ );
966
+
967
+ return result;
968
+ }
969
+
970
+ async _connectToMcpServerInternal(
971
+ serverName: string,
972
+ url: string,
973
+ callbackUrl: string,
974
+ // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
975
+ options?: {
976
+ client?: ConstructorParameters<typeof Client>[1];
977
+ /**
978
+ * We don't expose the normal set of transport options because:
979
+ * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
980
+ * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
981
+ *
982
+ * 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).
983
+ */
984
+ transport?: {
985
+ headers?: HeadersInit;
986
+ };
987
+ },
988
+ reconnect?: {
989
+ id: string;
990
+ oauthClientId?: string;
991
+ }
992
+ ): Promise<{ id: string; authUrl: string | undefined }> {
993
+ const authProvider = new DurableObjectOAuthClientProvider(
994
+ this.ctx.storage,
995
+ this.name,
996
+ callbackUrl
997
+ );
998
+
999
+ if (reconnect) {
1000
+ authProvider.serverId = reconnect.id;
1001
+ if (reconnect.oauthClientId) {
1002
+ authProvider.clientId = reconnect.oauthClientId;
1003
+ }
1004
+ }
1005
+
1006
+ // allows passing through transport headers if necessary
1007
+ // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
1008
+ let headerTransportOpts: SSEClientTransportOptions = {};
1009
+ if (options?.transport?.headers) {
1010
+ headerTransportOpts = {
1011
+ eventSourceInit: {
1012
+ fetch: (url, init) =>
1013
+ fetch(url, {
1014
+ ...init,
1015
+ headers: options?.transport?.headers,
1016
+ }),
1017
+ },
1018
+ requestInit: {
1019
+ headers: options?.transport?.headers,
1020
+ },
1021
+ };
1022
+ }
1023
+
1024
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
1025
+ client: options?.client,
1026
+ reconnect,
1027
+ transport: {
1028
+ ...headerTransportOpts,
1029
+ authProvider,
1030
+ },
1031
+ });
1032
+
1033
+ this.sql`
1034
+ INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1035
+ VALUES (
1036
+ ${id},
1037
+ ${serverName},
1038
+ ${url},
1039
+ ${clientId ?? null},
1040
+ ${authUrl ?? null},
1041
+ ${callbackUrl},
1042
+ ${options ? JSON.stringify(options) : null}
1043
+ );
1044
+ `;
1045
+
1046
+ return {
1047
+ authUrl,
1048
+ id,
1049
+ };
1050
+ }
1051
+
1052
+ async removeMcpServer(id: string) {
1053
+ this.mcp.closeConnection(id);
1054
+ this.sql`
1055
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1056
+ `;
1057
+ this.broadcast(
1058
+ JSON.stringify({
1059
+ mcp: this.getMcpServers(),
1060
+ type: "cf_agent_mcp_servers",
1061
+ })
1062
+ );
1063
+ }
1064
+
1065
+ getMcpServers(): MCPServersState {
1066
+ const mcpState: MCPServersState = {
1067
+ prompts: this.mcp.listPrompts(),
1068
+ resources: this.mcp.listResources(),
1069
+ servers: {},
1070
+ tools: this.mcp.listTools(),
1071
+ };
1072
+
1073
+ const servers = this.sql<MCPServerRow>`
1074
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1075
+ `;
1076
+
1077
+ for (const server of servers) {
1078
+ const serverConn = this.mcp.mcpConnections[server.id];
1079
+ mcpState.servers[server.id] = {
1080
+ auth_url: server.auth_url,
1081
+ capabilities: serverConn?.serverCapabilities ?? null,
1082
+ instructions: serverConn?.instructions ?? null,
1083
+ name: server.name,
1084
+ server_url: server.server_url,
1085
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1086
+ state: serverConn?.connectionState ?? "authenticating",
1087
+ };
1088
+ }
1089
+
1090
+ return mcpState;
1091
+ }
690
1092
  }
691
1093
 
692
1094
  /**
@@ -726,9 +1128,9 @@ export async function routeAgentRequest<Env>(
726
1128
  const corsHeaders =
727
1129
  options?.cors === true
728
1130
  ? {
729
- "Access-Control-Allow-Origin": "*",
730
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
731
1131
  "Access-Control-Allow-Credentials": "true",
1132
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1133
+ "Access-Control-Allow-Origin": "*",
732
1134
  "Access-Control-Max-Age": "86400",
733
1135
  }
734
1136
  : options?.cors;
@@ -756,7 +1158,8 @@ export async function routeAgentRequest<Env>(
756
1158
  if (
757
1159
  response &&
758
1160
  corsHeaders &&
759
- request.headers.get("upgrade") !== "websocket"
1161
+ request.headers.get("upgrade")?.toLowerCase() !== "websocket" &&
1162
+ request.headers.get("Upgrade")?.toLowerCase() !== "websocket"
760
1163
  ) {
761
1164
  response = new Response(response.body, {
762
1165
  headers: {
@@ -775,9 +1178,9 @@ export async function routeAgentRequest<Env>(
775
1178
  * @param options Routing options
776
1179
  */
777
1180
  export async function routeAgentEmail<Env>(
778
- email: ForwardableEmailMessage,
779
- env: Env,
780
- options?: AgentOptions<Env>
1181
+ _email: ForwardableEmailMessage,
1182
+ _env: Env,
1183
+ _options?: AgentOptions<Env>
781
1184
  ): Promise<void> {}
782
1185
 
783
1186
  /**
@@ -789,7 +1192,7 @@ export async function routeAgentEmail<Env>(
789
1192
  * @param options Options for Agent creation
790
1193
  * @returns Promise resolving to an Agent instance stub
791
1194
  */
792
- export function getAgentByName<Env, T extends Agent<Env>>(
1195
+ export async function getAgentByName<Env, T extends Agent<Env>>(
793
1196
  namespace: AgentNamespace<T>,
794
1197
  name: string,
795
1198
  options?: {
@@ -804,13 +1207,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
804
1207
  * A wrapper for streaming responses in callable methods
805
1208
  */
806
1209
  export class StreamingResponse {
807
- #connection: Connection;
808
- #id: string;
809
- #closed = false;
1210
+ private _connection: Connection;
1211
+ private _id: string;
1212
+ private _closed = false;
810
1213
 
811
1214
  constructor(connection: Connection, id: string) {
812
- this.#connection = connection;
813
- this.#id = id;
1215
+ this._connection = connection;
1216
+ this._id = id;
814
1217
  }
815
1218
 
816
1219
  /**
@@ -818,17 +1221,17 @@ export class StreamingResponse {
818
1221
  * @param chunk The data to send
819
1222
  */
820
1223
  send(chunk: unknown) {
821
- if (this.#closed) {
1224
+ if (this._closed) {
822
1225
  throw new Error("StreamingResponse is already closed");
823
1226
  }
824
1227
  const response: RPCResponse = {
825
- type: "rpc",
826
- id: this.#id,
827
- success: true,
828
- result: chunk,
829
1228
  done: false,
1229
+ id: this._id,
1230
+ result: chunk,
1231
+ success: true,
1232
+ type: "rpc",
830
1233
  };
831
- this.#connection.send(JSON.stringify(response));
1234
+ this._connection.send(JSON.stringify(response));
832
1235
  }
833
1236
 
834
1237
  /**
@@ -836,17 +1239,17 @@ export class StreamingResponse {
836
1239
  * @param finalChunk Optional final chunk of data to send
837
1240
  */
838
1241
  end(finalChunk?: unknown) {
839
- if (this.#closed) {
1242
+ if (this._closed) {
840
1243
  throw new Error("StreamingResponse is already closed");
841
1244
  }
842
- this.#closed = true;
1245
+ this._closed = true;
843
1246
  const response: RPCResponse = {
844
- type: "rpc",
845
- id: this.#id,
846
- success: true,
847
- result: finalChunk,
848
1247
  done: true,
1248
+ id: this._id,
1249
+ result: finalChunk,
1250
+ success: true,
1251
+ type: "rpc",
849
1252
  };
850
- this.#connection.send(JSON.stringify(response));
1253
+ this._connection.send(JSON.stringify(response));
851
1254
  }
852
1255
  }