agents 0.0.0-fb4d0a6 → 0.0.0-fb503ba

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