agents 0.0.0-a73eac5 → 0.0.0-ac0e999

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 (39) 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 +130 -69
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +17 -3
  6. package/dist/ai-react.js +39 -23
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/ai-types.d.ts +5 -0
  9. package/dist/chunk-25YDMV4H.js +464 -0
  10. package/dist/chunk-25YDMV4H.js.map +1 -0
  11. package/dist/chunk-D6UOOELW.js +106 -0
  12. package/dist/chunk-D6UOOELW.js.map +1 -0
  13. package/dist/{chunk-X6BBKLSC.js → chunk-DMJ7L3FI.js} +372 -167
  14. package/dist/chunk-DMJ7L3FI.js.map +1 -0
  15. package/dist/{chunk-HMLY7DHA.js → chunk-NOUFNU2O.js} +1 -5
  16. package/dist/chunk-ZKIVUOTQ.js +123 -0
  17. package/dist/chunk-ZKIVUOTQ.js.map +1 -0
  18. package/dist/client.d.ts +9 -1
  19. package/dist/client.js +7 -133
  20. package/dist/client.js.map +1 -1
  21. package/dist/index.d.ts +85 -12
  22. package/dist/index.js +7 -4
  23. package/dist/mcp/client.d.ts +783 -0
  24. package/dist/mcp/client.js +10 -0
  25. package/dist/mcp/client.js.map +1 -0
  26. package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
  27. package/dist/mcp/do-oauth-client-provider.js +8 -0
  28. package/dist/mcp/do-oauth-client-provider.js.map +1 -0
  29. package/dist/mcp/index.d.ts +84 -0
  30. package/dist/mcp/index.js +780 -0
  31. package/dist/mcp/index.js.map +1 -0
  32. package/dist/react.d.ts +14 -0
  33. package/dist/react.js +39 -28
  34. package/dist/react.js.map +1 -1
  35. package/dist/schedule.js +1 -1
  36. package/package.json +41 -5
  37. package/src/index.ts +481 -126
  38. package/dist/chunk-X6BBKLSC.js.map +0 -1
  39. /package/dist/{chunk-HMLY7DHA.js.map → chunk-NOUFNU2O.js.map} +0 -0
package/src/index.ts CHANGED
@@ -11,9 +11,24 @@ import {
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 { AsyncLocalStorage } from "node:async_hooks";
15
+ import { MCPClientManager } from "./mcp/client";
16
+ import {
17
+ DurableObjectOAuthClientProvider,
18
+ type AgentsOAuthProvider,
19
+ } from "./mcp/do-oauth-client-provider";
20
+ import type {
21
+ Tool,
22
+ Resource,
23
+ Prompt,
24
+ } from "@modelcontextprotocol/sdk/types.js";
25
+
26
+ import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
27
+ import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
28
+
29
+ import { camelCaseToKebabCase } from "./client";
15
30
 
16
- import { WorkflowEntrypoint as CFWorkflowEntrypoint } from "cloudflare:workers";
31
+ export type { Connection, WSMessage, ConnectionContext } from "partyserver";
17
32
 
18
33
  /**
19
34
  * RPC request message from client
@@ -117,11 +132,6 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
117
132
  };
118
133
  }
119
134
 
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
135
  /**
126
136
  * Represents a scheduled task within an Agent
127
137
  * @template T Type of the payload data
@@ -163,18 +173,90 @@ function getNextCronTime(cron: string) {
163
173
  return interval.getNextDate();
164
174
  }
165
175
 
176
+ /**
177
+ * MCP Server state update message from server -> Client
178
+ */
179
+ export type MCPServerMessage = {
180
+ type: "cf_agent_mcp_servers";
181
+ mcp: MCPServersState;
182
+ };
183
+
184
+ export type MCPServersState = {
185
+ servers: {
186
+ [id: string]: MCPServer;
187
+ };
188
+ tools: Tool[];
189
+ prompts: Prompt[];
190
+ resources: Resource[];
191
+ };
192
+
193
+ export type MCPServer = {
194
+ name: string;
195
+ server_url: string;
196
+ auth_url: string | null;
197
+ state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
198
+ };
199
+
200
+ /**
201
+ * MCP Server data stored in DO SQL for resuming MCP Server connections
202
+ */
203
+ type MCPServerRow = {
204
+ id: string;
205
+ name: string;
206
+ server_url: string;
207
+ client_id: string | null;
208
+ auth_url: string | null;
209
+ callback_url: string;
210
+ server_options: string;
211
+ };
212
+
166
213
  const STATE_ROW_ID = "cf_state_row_id";
167
214
  const STATE_WAS_CHANGED = "cf_state_was_changed";
168
215
 
169
216
  const DEFAULT_STATE = {} as unknown;
170
217
 
218
+ const agentContext = new AsyncLocalStorage<{
219
+ agent: Agent<unknown>;
220
+ connection: Connection | undefined;
221
+ request: Request | undefined;
222
+ }>();
223
+
224
+ export function getCurrentAgent<
225
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
226
+ >(): {
227
+ agent: T | undefined;
228
+ connection: Connection | undefined;
229
+ request: Request<unknown, CfProperties<unknown>> | undefined;
230
+ } {
231
+ const store = agentContext.getStore() as
232
+ | {
233
+ agent: T;
234
+ connection: Connection | undefined;
235
+ request: Request<unknown, CfProperties<unknown>> | undefined;
236
+ }
237
+ | undefined;
238
+ if (!store) {
239
+ return {
240
+ agent: undefined,
241
+ connection: undefined,
242
+ request: undefined,
243
+ };
244
+ }
245
+ return store;
246
+ }
247
+
171
248
  /**
172
249
  * Base class for creating Agent implementations
173
250
  * @template Env Environment type containing bindings
174
251
  * @template State State type to store within the Agent
175
252
  */
176
253
  export class Agent<Env, State = unknown> extends Server<Env> {
177
- #state = DEFAULT_STATE as State;
254
+ private _state = DEFAULT_STATE as State;
255
+
256
+ private ParentClass: typeof Agent<Env, State> =
257
+ Object.getPrototypeOf(this).constructor;
258
+
259
+ mcp: MCPClientManager = new MCPClientManager(this.ParentClass.name, "0.0.1");
178
260
 
179
261
  /**
180
262
  * Initial state for the Agent
@@ -186,9 +268,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
186
268
  * Current state of the Agent
187
269
  */
188
270
  get state(): State {
189
- if (this.#state !== DEFAULT_STATE) {
271
+ if (this._state !== DEFAULT_STATE) {
190
272
  // state was previously set, and populated internal state
191
- return this.#state;
273
+ return this._state;
192
274
  }
193
275
  // looks like this is the first time the state is being accessed
194
276
  // check if the state was set in a previous life
@@ -208,8 +290,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
208
290
  ) {
209
291
  const state = result[0]?.state as string; // could be null?
210
292
 
211
- this.#state = JSON.parse(state);
212
- return this.#state;
293
+ this._state = JSON.parse(state);
294
+ return this._state;
213
295
  }
214
296
 
215
297
  // ok, this is the first time the state is being accessed
@@ -270,7 +352,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
270
352
  `;
271
353
 
272
354
  void this.ctx.blockConcurrencyWhile(async () => {
273
- return this.#tryCatch(async () => {
355
+ return this.tryCatch(async () => {
274
356
  // Create alarms table if it doesn't exist
275
357
  this.sql`
276
358
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
@@ -290,96 +372,197 @@ export class Agent<Env, State = unknown> extends Server<Env> {
290
372
  });
291
373
  });
292
374
 
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
- }
375
+ this.sql`
376
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
377
+ id TEXT PRIMARY KEY NOT NULL,
378
+ name TEXT NOT NULL,
379
+ server_url TEXT NOT NULL,
380
+ callback_url TEXT NOT NULL,
381
+ client_id TEXT,
382
+ auth_url TEXT,
383
+ server_options TEXT
384
+ )
385
+ `;
306
386
 
307
- if (isStateUpdateMessage(parsed)) {
308
- this.#setStateInternal(parsed.state as State, connection);
309
- return;
310
- }
387
+ const _onRequest = this.onRequest.bind(this);
388
+ this.onRequest = (request: Request) => {
389
+ return agentContext.run(
390
+ { agent: this, connection: undefined, request },
391
+ async () => {
392
+ if (this.mcp.isCallbackRequest(request)) {
393
+ await this.mcp.handleCallbackRequest(request);
394
+
395
+ // after the MCP connection handshake, we can send updated mcp state
396
+ this.broadcast(
397
+ JSON.stringify({
398
+ type: "cf_agent_mcp_servers",
399
+ mcp: this.#getMcpServerStateInternal(),
400
+ })
401
+ );
402
+
403
+ // We probably should let the user configure this response/redirect, but this is fine for now.
404
+ return new Response("<script>window.close();</script>", {
405
+ status: 200,
406
+ headers: { "content-type": "text/html" },
407
+ });
408
+ }
311
409
 
312
- if (isRPCRequest(parsed)) {
313
- try {
314
- const { id, method, args } = parsed;
410
+ return this.tryCatch(() => _onRequest(request));
411
+ }
412
+ );
413
+ };
315
414
 
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`);
415
+ const _onMessage = this.onMessage.bind(this);
416
+ this.onMessage = async (connection: Connection, message: WSMessage) => {
417
+ return agentContext.run(
418
+ { agent: this, connection, request: undefined },
419
+ async () => {
420
+ if (typeof message !== "string") {
421
+ return this.tryCatch(() => _onMessage(connection, message));
320
422
  }
321
423
 
322
- if (!this.#isCallable(method)) {
323
- throw new Error(`Method ${method} is not callable`);
424
+ let parsed: unknown;
425
+ try {
426
+ parsed = JSON.parse(message);
427
+ } catch (e) {
428
+ // silently fail and let the onMessage handler handle it
429
+ return this.tryCatch(() => _onMessage(connection, message));
324
430
  }
325
431
 
326
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
327
- const metadata = callableMetadata.get(methodFn as Function);
432
+ if (isStateUpdateMessage(parsed)) {
433
+ this.setStateInternal(parsed.state as State, connection);
434
+ return;
435
+ }
328
436
 
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]);
437
+ if (isRPCRequest(parsed)) {
438
+ try {
439
+ const { id, method, args } = parsed;
440
+
441
+ // Check if method exists and is callable
442
+ const methodFn = this[method as keyof this];
443
+ if (typeof methodFn !== "function") {
444
+ throw new Error(`Method ${method} does not exist`);
445
+ }
446
+
447
+ if (!this.isCallable(method)) {
448
+ throw new Error(`Method ${method} is not callable`);
449
+ }
450
+
451
+ // biome-ignore lint/complexity/noBannedTypes: <explanation>
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
+ type: "rpc",
465
+ id,
466
+ success: true,
467
+ result,
468
+ done: true,
469
+ };
470
+ connection.send(JSON.stringify(response));
471
+ } catch (e) {
472
+ // Send error response
473
+ const response: RPCResponse = {
474
+ type: "rpc",
475
+ id: parsed.id,
476
+ success: false,
477
+ error:
478
+ e instanceof Error ? e.message : "Unknown error occurred",
479
+ };
480
+ connection.send(JSON.stringify(response));
481
+ console.error("RPC error:", e);
482
+ }
333
483
  return;
334
484
  }
335
485
 
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);
486
+ return this.tryCatch(() => _onMessage(connection, message));
356
487
  }
357
- return;
358
- }
359
-
360
- return this.#tryCatch(() => _onMessage(connection, message));
488
+ );
361
489
  };
362
490
 
363
491
  const _onConnect = this.onConnect.bind(this);
364
492
  this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
365
493
  // TODO: This is a hack to ensure the state is sent after the connection is established
366
494
  // must fix this
367
- setTimeout(() => {
368
- if (this.state) {
369
- 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
+ type: "cf_agent_state",
503
+ state: this.state,
504
+ })
505
+ );
506
+ }
507
+
508
+ connection.send(
509
+ JSON.stringify({
510
+ type: "cf_agent_mcp_servers",
511
+ mcp: this.#getMcpServerStateInternal(),
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 using our saved auth information
531
+ await Promise.allSettled(
532
+ servers.map((server) => {
533
+ return this.#connectToMcpServerInternal(
534
+ server.name,
535
+ server.server_url,
536
+ server.callback_url,
537
+ server.server_options
538
+ ? JSON.parse(server.server_options)
539
+ : undefined,
540
+ {
541
+ id: server.id,
542
+ oauthClientId: server.client_id ?? undefined,
543
+ }
544
+ );
545
+ })
546
+ );
547
+
548
+ this.broadcast(
370
549
  JSON.stringify({
371
- type: "cf_agent_state",
372
- state: this.state,
550
+ type: "cf_agent_mcp_servers",
551
+ mcp: this.#getMcpServerStateInternal(),
373
552
  })
374
553
  );
554
+
555
+ await this.tryCatch(() => _onStart());
375
556
  }
376
- return this.#tryCatch(() => _onConnect(connection, ctx));
377
- }, 20);
557
+ );
378
558
  };
379
559
  }
380
560
 
381
- #setStateInternal(state: State, source: Connection | "server" = "server") {
382
- this.#state = state;
561
+ private setStateInternal(
562
+ state: State,
563
+ source: Connection | "server" = "server"
564
+ ) {
565
+ this._state = state;
383
566
  this.sql`
384
567
  INSERT OR REPLACE INTO cf_agents_state (id, state)
385
568
  VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
@@ -395,7 +578,15 @@ export class Agent<Env, State = unknown> extends Server<Env> {
395
578
  }),
396
579
  source !== "server" ? [source.id] : []
397
580
  );
398
- return this.#tryCatch(() => this.onStateUpdate(state, source));
581
+ return this.tryCatch(() => {
582
+ const { connection, request } = agentContext.getStore() || {};
583
+ return agentContext.run(
584
+ { agent: this, connection, request },
585
+ async () => {
586
+ return this.onStateUpdate(state, source);
587
+ }
588
+ );
589
+ });
399
590
  }
400
591
 
401
592
  /**
@@ -403,7 +594,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
403
594
  * @param state New state to set
404
595
  */
405
596
  setState(state: State) {
406
- this.#setStateInternal(state, "server");
597
+ this.setStateInternal(state, "server");
407
598
  }
408
599
 
409
600
  /**
@@ -420,10 +611,15 @@ export class Agent<Env, State = unknown> extends Server<Env> {
420
611
  * @param email Email message to process
421
612
  */
422
613
  onEmail(email: ForwardableEmailMessage) {
423
- throw new Error("Not implemented");
614
+ return agentContext.run(
615
+ { agent: this, connection: undefined, request: undefined },
616
+ async () => {
617
+ console.error("onEmail not implemented");
618
+ }
619
+ );
424
620
  }
425
621
 
426
- async #tryCatch<T>(fn: () => T | Promise<T>) {
622
+ private async tryCatch<T>(fn: () => T | Promise<T>) {
427
623
  try {
428
624
  return await fn();
429
625
  } catch (e) {
@@ -497,7 +693,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
497
693
  )}, 'scheduled', ${timestamp})
498
694
  `;
499
695
 
500
- await this.#scheduleNextAlarm();
696
+ await this.scheduleNextAlarm();
501
697
 
502
698
  return {
503
699
  id,
@@ -518,7 +714,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
518
714
  )}, 'delayed', ${when}, ${timestamp})
519
715
  `;
520
716
 
521
- await this.#scheduleNextAlarm();
717
+ await this.scheduleNextAlarm();
522
718
 
523
719
  return {
524
720
  id,
@@ -540,7 +736,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
540
736
  )}, 'cron', ${when}, ${timestamp})
541
737
  `;
542
738
 
543
- await this.#scheduleNextAlarm();
739
+ await this.scheduleNextAlarm();
544
740
 
545
741
  return {
546
742
  id,
@@ -580,7 +776,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
580
776
  */
581
777
  getSchedules<T = string>(
582
778
  criteria: {
583
- description?: string;
584
779
  id?: string;
585
780
  type?: "scheduled" | "delayed" | "cron";
586
781
  timeRange?: { start?: Date; end?: Date };
@@ -594,11 +789,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
594
789
  params.push(criteria.id);
595
790
  }
596
791
 
597
- if (criteria.description) {
598
- query += " AND description = ?";
599
- params.push(criteria.description);
600
- }
601
-
602
792
  if (criteria.type) {
603
793
  query += " AND type = ?";
604
794
  params.push(criteria.type);
@@ -633,11 +823,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
633
823
  async cancelSchedule(id: string): Promise<boolean> {
634
824
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
635
825
 
636
- await this.#scheduleNextAlarm();
826
+ await this.scheduleNextAlarm();
637
827
  return true;
638
828
  }
639
829
 
640
- async #scheduleNextAlarm() {
830
+ private async scheduleNextAlarm() {
641
831
  // Find the next schedule that needs to be executed
642
832
  const result = this.sql`
643
833
  SELECT time FROM cf_agents_schedules
@@ -654,10 +844,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
654
844
  }
655
845
 
656
846
  /**
657
- * Method called when an alarm fires
658
- * Executes any scheduled tasks that are due
847
+ * Method called when an alarm fires.
848
+ * Executes any scheduled tasks that are due.
849
+ *
850
+ * @remarks
851
+ * To schedule a task, please use the `this.schedule` method instead.
852
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
659
853
  */
660
- async alarm() {
854
+ public readonly alarm = async () => {
661
855
  const now = Math.floor(Date.now() / 1000);
662
856
 
663
857
  // Get all schedules that should be executed now
@@ -671,16 +865,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
671
865
  console.error(`callback ${row.callback} not found`);
672
866
  continue;
673
867
  }
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
- }
868
+ await agentContext.run(
869
+ { agent: this, connection: undefined, request: undefined },
870
+ async () => {
871
+ try {
872
+ await (
873
+ callback as (
874
+ payload: unknown,
875
+ schedule: Schedule<unknown>
876
+ ) => Promise<void>
877
+ ).bind(this)(JSON.parse(row.payload as string), row);
878
+ } catch (e) {
879
+ console.error(`error executing callback "${row.callback}"`, e);
880
+ }
881
+ }
882
+ );
684
883
  if (row.type === "cron") {
685
884
  // Update next execution time for cron schedules
686
885
  const nextExecutionTime = getNextCronTime(row.cron);
@@ -698,8 +897,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
698
897
  }
699
898
 
700
899
  // Schedule the next alarm
701
- await this.#scheduleNextAlarm();
702
- }
900
+ await this.scheduleNextAlarm();
901
+ };
703
902
 
704
903
  /**
705
904
  * Destroy the Agent, removing all state and scheduled tasks
@@ -708,20 +907,176 @@ export class Agent<Env, State = unknown> extends Server<Env> {
708
907
  // drop all tables
709
908
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
710
909
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
910
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
711
911
 
712
912
  // delete all alarms
713
913
  await this.ctx.storage.deleteAlarm();
714
914
  await this.ctx.storage.deleteAll();
715
915
  }
716
916
 
717
- /**
718
- * Get all methods marked as callable on this Agent
719
- * @returns A map of method names to their metadata
720
- */
721
- #isCallable(method: string): boolean {
917
+ private isCallable(method: string): boolean {
722
918
  // biome-ignore lint/complexity/noBannedTypes: <explanation>
723
919
  return callableMetadata.has(this[method as keyof this] as Function);
724
920
  }
921
+
922
+ /**
923
+ * Connect to a new MCP Server
924
+ *
925
+ * @param url MCP Server SSE URL
926
+ * @param callbackHost Base host for the agent, used for the redirect URI.
927
+ * @param agentsPrefix agents routing prefix if not using `agents`
928
+ * @param options MCP client and transport (header) options
929
+ * @returns authUrl
930
+ */
931
+ async addMcpServer(
932
+ serverName: string,
933
+ url: string,
934
+ callbackHost: string,
935
+ agentsPrefix = "agents",
936
+ options?: {
937
+ client?: ConstructorParameters<typeof Client>[1];
938
+ transport?: {
939
+ headers: HeadersInit;
940
+ };
941
+ }
942
+ ): Promise<{ id: string; authUrl: string | undefined }> {
943
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this.ParentClass.name)}/${this.name}/callback`;
944
+
945
+ const result = await this.#connectToMcpServerInternal(
946
+ serverName,
947
+ url,
948
+ callbackUrl,
949
+ options
950
+ );
951
+
952
+ this.broadcast(
953
+ JSON.stringify({
954
+ type: "cf_agent_mcp_servers",
955
+ mcp: this.#getMcpServerStateInternal(),
956
+ })
957
+ );
958
+
959
+ return result;
960
+ }
961
+
962
+ async #connectToMcpServerInternal(
963
+ serverName: string,
964
+ url: string,
965
+ callbackUrl: string,
966
+ // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
967
+ options?: {
968
+ client?: ConstructorParameters<typeof Client>[1];
969
+ /**
970
+ * We don't expose the normal set of transport options because:
971
+ * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
972
+ * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
973
+ *
974
+ * 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).
975
+ */
976
+ transport?: {
977
+ headers?: HeadersInit;
978
+ };
979
+ },
980
+ reconnect?: {
981
+ id: string;
982
+ oauthClientId?: string;
983
+ }
984
+ ): Promise<{ id: string; authUrl: string | undefined }> {
985
+ const authProvider = new DurableObjectOAuthClientProvider(
986
+ this.ctx.storage,
987
+ this.name,
988
+ callbackUrl
989
+ );
990
+
991
+ if (reconnect) {
992
+ authProvider.serverId = reconnect.id;
993
+ if (reconnect.oauthClientId) {
994
+ authProvider.clientId = reconnect.oauthClientId;
995
+ }
996
+ }
997
+
998
+ // allows passing through transport headers if necessary
999
+ // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
1000
+ let headerTransportOpts: SSEClientTransportOptions = {};
1001
+ if (options?.transport?.headers) {
1002
+ headerTransportOpts = {
1003
+ eventSourceInit: {
1004
+ fetch: (url, init) =>
1005
+ fetch(url, {
1006
+ ...init,
1007
+ headers: options?.transport?.headers,
1008
+ }),
1009
+ },
1010
+ requestInit: {
1011
+ headers: options?.transport?.headers,
1012
+ },
1013
+ };
1014
+ }
1015
+
1016
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
1017
+ reconnect,
1018
+ transport: {
1019
+ ...headerTransportOpts,
1020
+ authProvider,
1021
+ },
1022
+ client: options?.client,
1023
+ });
1024
+
1025
+ this.sql`
1026
+ INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1027
+ VALUES (
1028
+ ${id},
1029
+ ${serverName},
1030
+ ${url},
1031
+ ${clientId ?? null},
1032
+ ${authUrl ?? null},
1033
+ ${callbackUrl},
1034
+ ${options ? JSON.stringify(options) : null}
1035
+ );
1036
+ `;
1037
+
1038
+ return {
1039
+ id,
1040
+ authUrl,
1041
+ };
1042
+ }
1043
+
1044
+ async removeMcpServer(id: string) {
1045
+ this.mcp.closeConnection(id);
1046
+ this.sql`
1047
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1048
+ `;
1049
+ this.broadcast(
1050
+ JSON.stringify({
1051
+ type: "cf_agent_mcp_servers",
1052
+ mcp: this.#getMcpServerStateInternal(),
1053
+ })
1054
+ );
1055
+ }
1056
+
1057
+ #getMcpServerStateInternal(): MCPServersState {
1058
+ const mcpState: MCPServersState = {
1059
+ servers: {},
1060
+ tools: this.mcp.listTools(),
1061
+ prompts: this.mcp.listPrompts(),
1062
+ resources: this.mcp.listResources(),
1063
+ };
1064
+
1065
+ const servers = this.sql<MCPServerRow>`
1066
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1067
+ `;
1068
+
1069
+ for (const server of servers) {
1070
+ mcpState.servers[server.id] = {
1071
+ name: server.name,
1072
+ server_url: server.server_url,
1073
+ auth_url: server.auth_url,
1074
+ state: this.mcp.mcpConnections[server.id].connectionState,
1075
+ };
1076
+ }
1077
+
1078
+ return mcpState;
1079
+ }
725
1080
  }
726
1081
 
727
1082
  /**
@@ -825,7 +1180,7 @@ export async function routeAgentEmail<Env>(
825
1180
  * @param options Options for Agent creation
826
1181
  * @returns Promise resolving to an Agent instance stub
827
1182
  */
828
- export function getAgentByName<Env, T extends Agent<Env>>(
1183
+ export async function getAgentByName<Env, T extends Agent<Env>>(
829
1184
  namespace: AgentNamespace<T>,
830
1185
  name: string,
831
1186
  options?: {
@@ -840,13 +1195,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
840
1195
  * A wrapper for streaming responses in callable methods
841
1196
  */
842
1197
  export class StreamingResponse {
843
- #connection: Connection;
844
- #id: string;
845
- #closed = false;
1198
+ private connection: Connection;
1199
+ private id: string;
1200
+ private closed = false;
846
1201
 
847
1202
  constructor(connection: Connection, id: string) {
848
- this.#connection = connection;
849
- this.#id = id;
1203
+ this.connection = connection;
1204
+ this.id = id;
850
1205
  }
851
1206
 
852
1207
  /**
@@ -854,17 +1209,17 @@ export class StreamingResponse {
854
1209
  * @param chunk The data to send
855
1210
  */
856
1211
  send(chunk: unknown) {
857
- if (this.#closed) {
1212
+ if (this.closed) {
858
1213
  throw new Error("StreamingResponse is already closed");
859
1214
  }
860
1215
  const response: RPCResponse = {
861
1216
  type: "rpc",
862
- id: this.#id,
1217
+ id: this.id,
863
1218
  success: true,
864
1219
  result: chunk,
865
1220
  done: false,
866
1221
  };
867
- this.#connection.send(JSON.stringify(response));
1222
+ this.connection.send(JSON.stringify(response));
868
1223
  }
869
1224
 
870
1225
  /**
@@ -872,17 +1227,17 @@ export class StreamingResponse {
872
1227
  * @param finalChunk Optional final chunk of data to send
873
1228
  */
874
1229
  end(finalChunk?: unknown) {
875
- if (this.#closed) {
1230
+ if (this.closed) {
876
1231
  throw new Error("StreamingResponse is already closed");
877
1232
  }
878
- this.#closed = true;
1233
+ this.closed = true;
879
1234
  const response: RPCResponse = {
880
1235
  type: "rpc",
881
- id: this.#id,
1236
+ id: this.id,
882
1237
  success: true,
883
1238
  result: finalChunk,
884
1239
  done: true,
885
1240
  };
886
- this.#connection.send(JSON.stringify(response));
1241
+ this.connection.send(JSON.stringify(response));
887
1242
  }
888
1243
  }