agents 0.0.0-7c40201 → 0.0.0-7e0777b

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 (45) hide show
  1. package/dist/ai-chat-agent.d.ts +50 -5
  2. package/dist/ai-chat-agent.js +150 -79
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-react.d.ts +17 -4
  5. package/dist/ai-react.js +62 -48
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/ai-types.d.ts +5 -0
  8. package/dist/chunk-767EASBA.js +106 -0
  9. package/dist/chunk-767EASBA.js.map +1 -0
  10. package/dist/chunk-E3LCYPCB.js +469 -0
  11. package/dist/chunk-E3LCYPCB.js.map +1 -0
  12. package/dist/chunk-NKZZ66QY.js +116 -0
  13. package/dist/chunk-NKZZ66QY.js.map +1 -0
  14. package/dist/{chunk-KRBQHBPA.js → chunk-ZRRXJUAA.js} +357 -168
  15. package/dist/chunk-ZRRXJUAA.js.map +1 -0
  16. package/dist/client.d.ts +15 -1
  17. package/dist/client.js +6 -133
  18. package/dist/client.js.map +1 -1
  19. package/dist/index.d.ts +123 -21
  20. package/dist/index.js +8 -8
  21. package/dist/mcp/client.d.ts +783 -0
  22. package/dist/mcp/client.js +9 -0
  23. package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
  24. package/dist/mcp/do-oauth-client-provider.js +7 -0
  25. package/dist/mcp/do-oauth-client-provider.js.map +1 -0
  26. package/dist/mcp/index.d.ts +84 -0
  27. package/dist/mcp/index.js +783 -0
  28. package/dist/mcp/index.js.map +1 -0
  29. package/dist/react.d.ts +85 -5
  30. package/dist/react.js +50 -31
  31. package/dist/react.js.map +1 -1
  32. package/dist/schedule.d.ts +2 -2
  33. package/dist/schedule.js +4 -6
  34. package/dist/schedule.js.map +1 -1
  35. package/dist/serializable.d.ts +32 -0
  36. package/dist/serializable.js +1 -0
  37. package/dist/serializable.js.map +1 -0
  38. package/package.json +79 -51
  39. package/src/index.ts +429 -99
  40. package/dist/chunk-HMLY7DHA.js +0 -16
  41. package/dist/chunk-KRBQHBPA.js.map +0 -1
  42. package/dist/mcp.d.ts +0 -58
  43. package/dist/mcp.js +0 -945
  44. package/dist/mcp.js.map +0 -1
  45. /package/dist/{chunk-HMLY7DHA.js.map → mcp/client.js.map} +0 -0
package/src/index.ts CHANGED
@@ -1,21 +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
- import { AsyncLocalStorage } from "node:async_hooks";
15
-
16
- export type { Connection, WSMessage, ConnectionContext } from "partyserver";
17
-
18
- import { WorkflowEntrypoint as CFWorkflowEntrypoint } from "cloudflare:workers";
27
+ export type { Connection, ConnectionContext, WSMessage } from "partyserver";
19
28
 
20
29
  /**
21
30
  * RPC request message from client
@@ -99,7 +108,6 @@ export type CallableMetadata = {
99
108
  streaming?: boolean;
100
109
  };
101
110
 
102
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
103
111
  const callableMetadata = new Map<Function, CallableMetadata>();
104
112
 
105
113
  /**
@@ -109,6 +117,7 @@ const callableMetadata = new Map<Function, CallableMetadata>();
109
117
  export function unstable_callable(metadata: CallableMetadata = {}) {
110
118
  return function callableDecorator<This, Args extends unknown[], Return>(
111
119
  target: (this: This, ...args: Args) => Return,
120
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: later
112
121
  context: ClassMethodDecoratorContext
113
122
  ) {
114
123
  if (!callableMetadata.has(target)) {
@@ -119,11 +128,6 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
119
128
  };
120
129
  }
121
130
 
122
- /**
123
- * A class for creating workflow entry points that can be used with Cloudflare Workers
124
- */
125
- export class WorkflowEntrypoint extends CFWorkflowEntrypoint {}
126
-
127
131
  /**
128
132
  * Represents a scheduled task within an Agent
129
133
  * @template T Type of the payload data
@@ -165,24 +169,95 @@ function getNextCronTime(cron: string) {
165
169
  return interval.getNextDate();
166
170
  }
167
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
+
168
214
  const STATE_ROW_ID = "cf_state_row_id";
169
215
  const STATE_WAS_CHANGED = "cf_state_was_changed";
170
216
 
171
217
  const DEFAULT_STATE = {} as unknown;
172
218
 
173
- export const unstable_context = new AsyncLocalStorage<{
219
+ const agentContext = new AsyncLocalStorage<{
174
220
  agent: Agent<unknown>;
175
221
  connection: Connection | undefined;
176
222
  request: Request | undefined;
177
223
  }>();
178
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
+
179
249
  /**
180
250
  * Base class for creating Agent implementations
181
251
  * @template Env Environment type containing bindings
182
252
  * @template State State type to store within the Agent
183
253
  */
184
254
  export class Agent<Env, State = unknown> extends Server<Env> {
185
- #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");
186
261
 
187
262
  /**
188
263
  * Initial state for the Agent
@@ -194,9 +269,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
194
269
  * Current state of the Agent
195
270
  */
196
271
  get state(): State {
197
- if (this.#state !== DEFAULT_STATE) {
272
+ if (this._state !== DEFAULT_STATE) {
198
273
  // state was previously set, and populated internal state
199
- return this.#state;
274
+ return this._state;
200
275
  }
201
276
  // looks like this is the first time the state is being accessed
202
277
  // check if the state was set in a previous life
@@ -216,8 +291,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
216
291
  ) {
217
292
  const state = result[0]?.state as string; // could be null?
218
293
 
219
- this.#state = JSON.parse(state);
220
- return this.#state;
294
+ this._state = JSON.parse(state);
295
+ return this._state;
221
296
  }
222
297
 
223
298
  // ok, this is the first time the state is being accessed
@@ -278,7 +353,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
278
353
  `;
279
354
 
280
355
  void this.ctx.blockConcurrencyWhile(async () => {
281
- return this.#tryCatch(async () => {
356
+ return this._tryCatch(async () => {
282
357
  // Create alarms table if it doesn't exist
283
358
  this.sql`
284
359
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
@@ -298,25 +373,65 @@ export class Agent<Env, State = unknown> extends Server<Env> {
298
373
  });
299
374
  });
300
375
 
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
+ `;
387
+
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
+ }
410
+
411
+ return this._tryCatch(() => _onRequest(request));
412
+ }
413
+ );
414
+ };
415
+
301
416
  const _onMessage = this.onMessage.bind(this);
302
417
  this.onMessage = async (connection: Connection, message: WSMessage) => {
303
- return unstable_context.run(
418
+ return agentContext.run(
304
419
  { agent: this, connection, request: undefined },
305
420
  async () => {
306
421
  if (typeof message !== "string") {
307
- return this.#tryCatch(() => _onMessage(connection, message));
422
+ return this._tryCatch(() => _onMessage(connection, message));
308
423
  }
309
424
 
310
425
  let parsed: unknown;
311
426
  try {
312
427
  parsed = JSON.parse(message);
313
- } catch (e) {
428
+ } catch (_e) {
314
429
  // silently fail and let the onMessage handler handle it
315
- return this.#tryCatch(() => _onMessage(connection, message));
430
+ return this._tryCatch(() => _onMessage(connection, message));
316
431
  }
317
432
 
318
433
  if (isStateUpdateMessage(parsed)) {
319
- this.#setStateInternal(parsed.state as State, connection);
434
+ this._setStateInternal(parsed.state as State, connection);
320
435
  return;
321
436
  }
322
437
 
@@ -330,11 +445,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
330
445
  throw new Error(`Method ${method} does not exist`);
331
446
  }
332
447
 
333
- if (!this.#isCallable(method)) {
448
+ if (!this._isCallable(method)) {
334
449
  throw new Error(`Method ${method} is not callable`);
335
450
  }
336
451
 
337
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
338
452
  const metadata = callableMetadata.get(methodFn as Function);
339
453
 
340
454
  // For streaming methods, pass a StreamingResponse object
@@ -347,21 +461,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
347
461
  // For regular methods, execute and send response
348
462
  const result = await methodFn.apply(this, args);
349
463
  const response: RPCResponse = {
350
- type: "rpc",
464
+ done: true,
351
465
  id,
352
- success: true,
353
466
  result,
354
- done: true,
467
+ success: true,
468
+ type: "rpc",
355
469
  };
356
470
  connection.send(JSON.stringify(response));
357
471
  } catch (e) {
358
472
  // Send error response
359
473
  const response: RPCResponse = {
360
- type: "rpc",
361
- id: parsed.id,
362
- success: false,
363
474
  error:
364
475
  e instanceof Error ? e.message : "Unknown error occurred",
476
+ id: parsed.id,
477
+ success: false,
478
+ type: "rpc",
365
479
  };
366
480
  connection.send(JSON.stringify(response));
367
481
  console.error("RPC error:", e);
@@ -369,7 +483,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
369
483
  return;
370
484
  }
371
485
 
372
- return this.#tryCatch(() => _onMessage(connection, message));
486
+ return this._tryCatch(() => _onMessage(connection, message));
373
487
  }
374
488
  );
375
489
  };
@@ -378,27 +492,79 @@ export class Agent<Env, State = unknown> extends Server<Env> {
378
492
  this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
379
493
  // TODO: This is a hack to ensure the state is sent after the connection is established
380
494
  // must fix this
381
- return unstable_context.run(
495
+ return agentContext.run(
382
496
  { agent: this, connection, request: ctx.request },
383
497
  async () => {
384
498
  setTimeout(() => {
385
499
  if (this.state) {
386
500
  connection.send(
387
501
  JSON.stringify({
388
- type: "cf_agent_state",
389
502
  state: this.state,
503
+ type: "cf_agent_state",
390
504
  })
391
505
  );
392
506
  }
393
- return this.#tryCatch(() => _onConnect(connection, ctx));
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));
394
516
  }, 20);
395
517
  }
396
518
  );
397
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(
551
+ JSON.stringify({
552
+ mcp: this.getMcpServers(),
553
+ type: "cf_agent_mcp_servers",
554
+ })
555
+ );
556
+
557
+ await this._tryCatch(() => _onStart());
558
+ }
559
+ );
560
+ };
398
561
  }
399
562
 
400
- #setStateInternal(state: State, source: Connection | "server" = "server") {
401
- this.#state = state;
563
+ private _setStateInternal(
564
+ state: State,
565
+ source: Connection | "server" = "server"
566
+ ) {
567
+ this._state = state;
402
568
  this.sql`
403
569
  INSERT OR REPLACE INTO cf_agents_state (id, state)
404
570
  VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
@@ -409,14 +575,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
409
575
  `;
410
576
  this.broadcast(
411
577
  JSON.stringify({
412
- type: "cf_agent_state",
413
578
  state: state,
579
+ type: "cf_agent_state",
414
580
  }),
415
581
  source !== "server" ? [source.id] : []
416
582
  );
417
- return this.#tryCatch(() => {
418
- const { connection, request } = unstable_context.getStore() || {};
419
- return unstable_context.run(
583
+ return this._tryCatch(() => {
584
+ const { connection, request } = agentContext.getStore() || {};
585
+ return agentContext.run(
420
586
  { agent: this, connection, request },
421
587
  async () => {
422
588
  return this.onStateUpdate(state, source);
@@ -430,7 +596,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
430
596
  * @param state New state to set
431
597
  */
432
598
  setState(state: State) {
433
- this.#setStateInternal(state, "server");
599
+ this._setStateInternal(state, "server");
434
600
  }
435
601
 
436
602
  /**
@@ -438,6 +604,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
438
604
  * @param state Updated state
439
605
  * @param source Source of the state update ("server" or a client connection)
440
606
  */
607
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
441
608
  onStateUpdate(state: State | undefined, source: Connection | "server") {
442
609
  // override this to handle state updates
443
610
  }
@@ -446,8 +613,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
446
613
  * Called when the Agent receives an email
447
614
  * @param email Email message to process
448
615
  */
616
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
449
617
  onEmail(email: ForwardableEmailMessage) {
450
- return unstable_context.run(
618
+ return agentContext.run(
451
619
  { agent: this, connection: undefined, request: undefined },
452
620
  async () => {
453
621
  console.error("onEmail not implemented");
@@ -455,7 +623,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
455
623
  );
456
624
  }
457
625
 
458
- async #tryCatch<T>(fn: () => T | Promise<T>) {
626
+ private async _tryCatch<T>(fn: () => T | Promise<T>) {
459
627
  try {
460
628
  return await fn();
461
629
  } catch (e) {
@@ -529,11 +697,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
529
697
  )}, 'scheduled', ${timestamp})
530
698
  `;
531
699
 
532
- await this.#scheduleNextAlarm();
700
+ await this._scheduleNextAlarm();
533
701
 
534
702
  return {
535
- id,
536
703
  callback: callback,
704
+ id,
537
705
  payload: payload as T,
538
706
  time: timestamp,
539
707
  type: "scheduled",
@@ -550,13 +718,13 @@ export class Agent<Env, State = unknown> extends Server<Env> {
550
718
  )}, 'delayed', ${when}, ${timestamp})
551
719
  `;
552
720
 
553
- await this.#scheduleNextAlarm();
721
+ await this._scheduleNextAlarm();
554
722
 
555
723
  return {
556
- id,
557
724
  callback: callback,
558
- payload: payload as T,
559
725
  delayInSeconds: when,
726
+ id,
727
+ payload: payload as T,
560
728
  time: timestamp,
561
729
  type: "delayed",
562
730
  };
@@ -572,13 +740,13 @@ export class Agent<Env, State = unknown> extends Server<Env> {
572
740
  )}, 'cron', ${when}, ${timestamp})
573
741
  `;
574
742
 
575
- await this.#scheduleNextAlarm();
743
+ await this._scheduleNextAlarm();
576
744
 
577
745
  return {
578
- id,
579
746
  callback: callback,
580
- payload: payload as T,
581
747
  cron: when,
748
+ id,
749
+ payload: payload as T,
582
750
  time: timestamp,
583
751
  type: "cron",
584
752
  };
@@ -612,7 +780,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
612
780
  */
613
781
  getSchedules<T = string>(
614
782
  criteria: {
615
- description?: string;
616
783
  id?: string;
617
784
  type?: "scheduled" | "delayed" | "cron";
618
785
  timeRange?: { start?: Date; end?: Date };
@@ -626,11 +793,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
626
793
  params.push(criteria.id);
627
794
  }
628
795
 
629
- if (criteria.description) {
630
- query += " AND description = ?";
631
- params.push(criteria.description);
632
- }
633
-
634
796
  if (criteria.type) {
635
797
  query += " AND type = ?";
636
798
  params.push(criteria.type);
@@ -665,11 +827,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
665
827
  async cancelSchedule(id: string): Promise<boolean> {
666
828
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
667
829
 
668
- await this.#scheduleNextAlarm();
830
+ await this._scheduleNextAlarm();
669
831
  return true;
670
832
  }
671
833
 
672
- async #scheduleNextAlarm() {
834
+ private async _scheduleNextAlarm() {
673
835
  // Find the next schedule that needs to be executed
674
836
  const result = this.sql`
675
837
  SELECT time FROM cf_agents_schedules
@@ -686,10 +848,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
686
848
  }
687
849
 
688
850
  /**
689
- * Method called when an alarm fires
690
- * 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/}
691
857
  */
692
- async alarm() {
858
+ public readonly alarm = async () => {
693
859
  const now = Math.floor(Date.now() / 1000);
694
860
 
695
861
  // Get all schedules that should be executed now
@@ -703,7 +869,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
703
869
  console.error(`callback ${row.callback} not found`);
704
870
  continue;
705
871
  }
706
- await unstable_context.run(
872
+ await agentContext.run(
707
873
  { agent: this, connection: undefined, request: undefined },
708
874
  async () => {
709
875
  try {
@@ -735,8 +901,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
735
901
  }
736
902
 
737
903
  // Schedule the next alarm
738
- await this.#scheduleNextAlarm();
739
- }
904
+ await this._scheduleNextAlarm();
905
+ };
740
906
 
741
907
  /**
742
908
  * Destroy the Agent, removing all state and scheduled tasks
@@ -745,20 +911,184 @@ export class Agent<Env, State = unknown> extends Server<Env> {
745
911
  // drop all tables
746
912
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
747
913
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
914
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
748
915
 
749
916
  // delete all alarms
750
917
  await this.ctx.storage.deleteAlarm();
751
918
  await this.ctx.storage.deleteAll();
919
+ this.ctx.abort("destroyed"); // enforce that the agent is evicted
752
920
  }
753
921
 
754
922
  /**
755
923
  * Get all methods marked as callable on this Agent
756
924
  * @returns A map of method names to their metadata
757
925
  */
758
- #isCallable(method: string): boolean {
759
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
926
+ private _isCallable(method: string): boolean {
760
927
  return callableMetadata.has(this[method as keyof this] as Function);
761
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
+ }
762
1092
  }
763
1093
 
764
1094
  /**
@@ -798,9 +1128,9 @@ export async function routeAgentRequest<Env>(
798
1128
  const corsHeaders =
799
1129
  options?.cors === true
800
1130
  ? {
801
- "Access-Control-Allow-Origin": "*",
802
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
803
1131
  "Access-Control-Allow-Credentials": "true",
1132
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1133
+ "Access-Control-Allow-Origin": "*",
804
1134
  "Access-Control-Max-Age": "86400",
805
1135
  }
806
1136
  : options?.cors;
@@ -848,9 +1178,9 @@ export async function routeAgentRequest<Env>(
848
1178
  * @param options Routing options
849
1179
  */
850
1180
  export async function routeAgentEmail<Env>(
851
- email: ForwardableEmailMessage,
852
- env: Env,
853
- options?: AgentOptions<Env>
1181
+ _email: ForwardableEmailMessage,
1182
+ _env: Env,
1183
+ _options?: AgentOptions<Env>
854
1184
  ): Promise<void> {}
855
1185
 
856
1186
  /**
@@ -862,7 +1192,7 @@ export async function routeAgentEmail<Env>(
862
1192
  * @param options Options for Agent creation
863
1193
  * @returns Promise resolving to an Agent instance stub
864
1194
  */
865
- export function getAgentByName<Env, T extends Agent<Env>>(
1195
+ export async function getAgentByName<Env, T extends Agent<Env>>(
866
1196
  namespace: AgentNamespace<T>,
867
1197
  name: string,
868
1198
  options?: {
@@ -877,13 +1207,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
877
1207
  * A wrapper for streaming responses in callable methods
878
1208
  */
879
1209
  export class StreamingResponse {
880
- #connection: Connection;
881
- #id: string;
882
- #closed = false;
1210
+ private _connection: Connection;
1211
+ private _id: string;
1212
+ private _closed = false;
883
1213
 
884
1214
  constructor(connection: Connection, id: string) {
885
- this.#connection = connection;
886
- this.#id = id;
1215
+ this._connection = connection;
1216
+ this._id = id;
887
1217
  }
888
1218
 
889
1219
  /**
@@ -891,17 +1221,17 @@ export class StreamingResponse {
891
1221
  * @param chunk The data to send
892
1222
  */
893
1223
  send(chunk: unknown) {
894
- if (this.#closed) {
1224
+ if (this._closed) {
895
1225
  throw new Error("StreamingResponse is already closed");
896
1226
  }
897
1227
  const response: RPCResponse = {
898
- type: "rpc",
899
- id: this.#id,
900
- success: true,
901
- result: chunk,
902
1228
  done: false,
1229
+ id: this._id,
1230
+ result: chunk,
1231
+ success: true,
1232
+ type: "rpc",
903
1233
  };
904
- this.#connection.send(JSON.stringify(response));
1234
+ this._connection.send(JSON.stringify(response));
905
1235
  }
906
1236
 
907
1237
  /**
@@ -909,17 +1239,17 @@ export class StreamingResponse {
909
1239
  * @param finalChunk Optional final chunk of data to send
910
1240
  */
911
1241
  end(finalChunk?: unknown) {
912
- if (this.#closed) {
1242
+ if (this._closed) {
913
1243
  throw new Error("StreamingResponse is already closed");
914
1244
  }
915
- this.#closed = true;
1245
+ this._closed = true;
916
1246
  const response: RPCResponse = {
917
- type: "rpc",
918
- id: this.#id,
919
- success: true,
920
- result: finalChunk,
921
1247
  done: true,
1248
+ id: this._id,
1249
+ result: finalChunk,
1250
+ success: true,
1251
+ type: "rpc",
922
1252
  };
923
- this.#connection.send(JSON.stringify(response));
1253
+ this._connection.send(JSON.stringify(response));
924
1254
  }
925
1255
  }