agents 0.0.0-8393f6f → 0.0.0-840f620

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 (41) hide show
  1. package/dist/ai-chat-agent.d.ts +31 -5
  2. package/dist/ai-chat-agent.js +119 -115
  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 +28 -29
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/chunk-767EASBA.js +106 -0
  8. package/dist/chunk-767EASBA.js.map +1 -0
  9. package/dist/{chunk-Q5ZBHY4Z.js → chunk-E3LCYPCB.js} +49 -36
  10. package/dist/chunk-E3LCYPCB.js.map +1 -0
  11. package/dist/chunk-NKZZ66QY.js +116 -0
  12. package/dist/chunk-NKZZ66QY.js.map +1 -0
  13. package/dist/{chunk-HD4VEHBA.js → chunk-ZRRXJUAA.js} +338 -158
  14. package/dist/chunk-ZRRXJUAA.js.map +1 -0
  15. package/dist/client.d.ts +15 -1
  16. package/dist/client.js +6 -126
  17. package/dist/client.js.map +1 -1
  18. package/dist/index.d.ts +109 -12
  19. package/dist/index.js +4 -3
  20. package/dist/mcp/client.d.ts +22 -16
  21. package/dist/mcp/client.js +1 -2
  22. package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
  23. package/dist/mcp/do-oauth-client-provider.js +3 -103
  24. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  25. package/dist/mcp/index.d.ts +20 -10
  26. package/dist/mcp/index.js +148 -173
  27. package/dist/mcp/index.js.map +1 -1
  28. package/dist/react.d.ts +85 -5
  29. package/dist/react.js +20 -8
  30. package/dist/react.js.map +1 -1
  31. package/dist/schedule.d.ts +2 -2
  32. package/dist/schedule.js +4 -6
  33. package/dist/schedule.js.map +1 -1
  34. package/dist/serializable.d.ts +32 -0
  35. package/dist/serializable.js +1 -0
  36. package/package.json +71 -68
  37. package/src/index.ts +393 -80
  38. package/dist/chunk-HD4VEHBA.js.map +0 -1
  39. package/dist/chunk-HMLY7DHA.js +0 -16
  40. package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
  41. /package/dist/{chunk-HMLY7DHA.js.map → serializable.js.map} +0 -0
package/src/index.ts CHANGED
@@ -1,20 +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";
10
-
11
- import { parseCronExpression } from "cron-schedule";
12
- import { nanoid } from "nanoid";
13
-
14
- import { AsyncLocalStorage } from "node:async_hooks";
22
+ import { camelCaseToKebabCase } from "./client";
15
23
  import { MCPClientManager } from "./mcp/client";
24
+ // import type { MCPClientConnection } from "./mcp/client-connection";
25
+ import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
16
26
 
17
- export type { Connection, WSMessage, ConnectionContext } from "partyserver";
27
+ export type { Connection, ConnectionContext, WSMessage } from "partyserver";
18
28
 
19
29
  /**
20
30
  * RPC request message from client
@@ -98,7 +108,6 @@ export type CallableMetadata = {
98
108
  streaming?: boolean;
99
109
  };
100
110
 
101
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
102
111
  const callableMetadata = new Map<Function, CallableMetadata>();
103
112
 
104
113
  /**
@@ -108,6 +117,7 @@ const callableMetadata = new Map<Function, CallableMetadata>();
108
117
  export function unstable_callable(metadata: CallableMetadata = {}) {
109
118
  return function callableDecorator<This, Args extends unknown[], Return>(
110
119
  target: (this: This, ...args: Args) => Return,
120
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: later
111
121
  context: ClassMethodDecoratorContext
112
122
  ) {
113
123
  if (!callableMetadata.has(target)) {
@@ -159,6 +169,48 @@ function getNextCronTime(cron: string) {
159
169
  return interval.getNextDate();
160
170
  }
161
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
+
162
214
  const STATE_ROW_ID = "cf_state_row_id";
163
215
  const STATE_WAS_CHANGED = "cf_state_was_changed";
164
216
 
@@ -200,12 +252,12 @@ export function getCurrentAgent<
200
252
  * @template State State type to store within the Agent
201
253
  */
202
254
  export class Agent<Env, State = unknown> extends Server<Env> {
203
- #state = DEFAULT_STATE as State;
255
+ private _state = DEFAULT_STATE as State;
204
256
 
205
- #ParentClass: typeof Agent<Env, State> =
257
+ private _ParentClass: typeof Agent<Env, State> =
206
258
  Object.getPrototypeOf(this).constructor;
207
259
 
208
- mcp: MCPClientManager = new MCPClientManager(this.#ParentClass.name, "0.0.1");
260
+ mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
209
261
 
210
262
  /**
211
263
  * Initial state for the Agent
@@ -217,9 +269,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
217
269
  * Current state of the Agent
218
270
  */
219
271
  get state(): State {
220
- if (this.#state !== DEFAULT_STATE) {
272
+ if (this._state !== DEFAULT_STATE) {
221
273
  // state was previously set, and populated internal state
222
- return this.#state;
274
+ return this._state;
223
275
  }
224
276
  // looks like this is the first time the state is being accessed
225
277
  // check if the state was set in a previous life
@@ -239,8 +291,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
239
291
  ) {
240
292
  const state = result[0]?.state as string; // could be null?
241
293
 
242
- this.#state = JSON.parse(state);
243
- return this.#state;
294
+ this._state = JSON.parse(state);
295
+ return this._state;
244
296
  }
245
297
 
246
298
  // ok, this is the first time the state is being accessed
@@ -301,7 +353,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
301
353
  `;
302
354
 
303
355
  void this.ctx.blockConcurrencyWhile(async () => {
304
- return this.#tryCatch(async () => {
356
+ return this._tryCatch(async () => {
305
357
  // Create alarms table if it doesn't exist
306
358
  this.sql`
307
359
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
@@ -321,25 +373,65 @@ export class Agent<Env, State = unknown> extends Server<Env> {
321
373
  });
322
374
  });
323
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
+
324
416
  const _onMessage = this.onMessage.bind(this);
325
417
  this.onMessage = async (connection: Connection, message: WSMessage) => {
326
418
  return agentContext.run(
327
419
  { agent: this, connection, request: undefined },
328
420
  async () => {
329
421
  if (typeof message !== "string") {
330
- return this.#tryCatch(() => _onMessage(connection, message));
422
+ return this._tryCatch(() => _onMessage(connection, message));
331
423
  }
332
424
 
333
425
  let parsed: unknown;
334
426
  try {
335
427
  parsed = JSON.parse(message);
336
- } catch (e) {
428
+ } catch (_e) {
337
429
  // silently fail and let the onMessage handler handle it
338
- return this.#tryCatch(() => _onMessage(connection, message));
430
+ return this._tryCatch(() => _onMessage(connection, message));
339
431
  }
340
432
 
341
433
  if (isStateUpdateMessage(parsed)) {
342
- this.#setStateInternal(parsed.state as State, connection);
434
+ this._setStateInternal(parsed.state as State, connection);
343
435
  return;
344
436
  }
345
437
 
@@ -353,11 +445,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
353
445
  throw new Error(`Method ${method} does not exist`);
354
446
  }
355
447
 
356
- if (!this.#isCallable(method)) {
448
+ if (!this._isCallable(method)) {
357
449
  throw new Error(`Method ${method} is not callable`);
358
450
  }
359
451
 
360
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
361
452
  const metadata = callableMetadata.get(methodFn as Function);
362
453
 
363
454
  // For streaming methods, pass a StreamingResponse object
@@ -370,21 +461,21 @@ export class Agent<Env, State = unknown> extends Server<Env> {
370
461
  // For regular methods, execute and send response
371
462
  const result = await methodFn.apply(this, args);
372
463
  const response: RPCResponse = {
373
- type: "rpc",
464
+ done: true,
374
465
  id,
375
- success: true,
376
466
  result,
377
- done: true,
467
+ success: true,
468
+ type: "rpc",
378
469
  };
379
470
  connection.send(JSON.stringify(response));
380
471
  } catch (e) {
381
472
  // Send error response
382
473
  const response: RPCResponse = {
383
- type: "rpc",
384
- id: parsed.id,
385
- success: false,
386
474
  error:
387
475
  e instanceof Error ? e.message : "Unknown error occurred",
476
+ id: parsed.id,
477
+ success: false,
478
+ type: "rpc",
388
479
  };
389
480
  connection.send(JSON.stringify(response));
390
481
  console.error("RPC error:", e);
@@ -392,7 +483,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
392
483
  return;
393
484
  }
394
485
 
395
- return this.#tryCatch(() => _onMessage(connection, message));
486
+ return this._tryCatch(() => _onMessage(connection, message));
396
487
  }
397
488
  );
398
489
  };
@@ -408,20 +499,72 @@ export class Agent<Env, State = unknown> extends Server<Env> {
408
499
  if (this.state) {
409
500
  connection.send(
410
501
  JSON.stringify({
411
- type: "cf_agent_state",
412
502
  state: this.state,
503
+ type: "cf_agent_state",
413
504
  })
414
505
  );
415
506
  }
416
- 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));
417
516
  }, 20);
418
517
  }
419
518
  );
420
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
+ };
421
561
  }
422
562
 
423
- #setStateInternal(state: State, source: Connection | "server" = "server") {
424
- this.#state = state;
563
+ private _setStateInternal(
564
+ state: State,
565
+ source: Connection | "server" = "server"
566
+ ) {
567
+ this._state = state;
425
568
  this.sql`
426
569
  INSERT OR REPLACE INTO cf_agents_state (id, state)
427
570
  VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
@@ -432,12 +575,12 @@ export class Agent<Env, State = unknown> extends Server<Env> {
432
575
  `;
433
576
  this.broadcast(
434
577
  JSON.stringify({
435
- type: "cf_agent_state",
436
578
  state: state,
579
+ type: "cf_agent_state",
437
580
  }),
438
581
  source !== "server" ? [source.id] : []
439
582
  );
440
- return this.#tryCatch(() => {
583
+ return this._tryCatch(() => {
441
584
  const { connection, request } = agentContext.getStore() || {};
442
585
  return agentContext.run(
443
586
  { agent: this, connection, request },
@@ -453,7 +596,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
453
596
  * @param state New state to set
454
597
  */
455
598
  setState(state: State) {
456
- this.#setStateInternal(state, "server");
599
+ this._setStateInternal(state, "server");
457
600
  }
458
601
 
459
602
  /**
@@ -461,6 +604,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
461
604
  * @param state Updated state
462
605
  * @param source Source of the state update ("server" or a client connection)
463
606
  */
607
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
464
608
  onStateUpdate(state: State | undefined, source: Connection | "server") {
465
609
  // override this to handle state updates
466
610
  }
@@ -469,6 +613,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
469
613
  * Called when the Agent receives an email
470
614
  * @param email Email message to process
471
615
  */
616
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
472
617
  onEmail(email: ForwardableEmailMessage) {
473
618
  return agentContext.run(
474
619
  { agent: this, connection: undefined, request: undefined },
@@ -478,7 +623,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
478
623
  );
479
624
  }
480
625
 
481
- async #tryCatch<T>(fn: () => T | Promise<T>) {
626
+ private async _tryCatch<T>(fn: () => T | Promise<T>) {
482
627
  try {
483
628
  return await fn();
484
629
  } catch (e) {
@@ -552,11 +697,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
552
697
  )}, 'scheduled', ${timestamp})
553
698
  `;
554
699
 
555
- await this.#scheduleNextAlarm();
700
+ await this._scheduleNextAlarm();
556
701
 
557
702
  return {
558
- id,
559
703
  callback: callback,
704
+ id,
560
705
  payload: payload as T,
561
706
  time: timestamp,
562
707
  type: "scheduled",
@@ -573,13 +718,13 @@ export class Agent<Env, State = unknown> extends Server<Env> {
573
718
  )}, 'delayed', ${when}, ${timestamp})
574
719
  `;
575
720
 
576
- await this.#scheduleNextAlarm();
721
+ await this._scheduleNextAlarm();
577
722
 
578
723
  return {
579
- id,
580
724
  callback: callback,
581
- payload: payload as T,
582
725
  delayInSeconds: when,
726
+ id,
727
+ payload: payload as T,
583
728
  time: timestamp,
584
729
  type: "delayed",
585
730
  };
@@ -595,13 +740,13 @@ export class Agent<Env, State = unknown> extends Server<Env> {
595
740
  )}, 'cron', ${when}, ${timestamp})
596
741
  `;
597
742
 
598
- await this.#scheduleNextAlarm();
743
+ await this._scheduleNextAlarm();
599
744
 
600
745
  return {
601
- id,
602
746
  callback: callback,
603
- payload: payload as T,
604
747
  cron: when,
748
+ id,
749
+ payload: payload as T,
605
750
  time: timestamp,
606
751
  type: "cron",
607
752
  };
@@ -682,11 +827,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
682
827
  async cancelSchedule(id: string): Promise<boolean> {
683
828
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
684
829
 
685
- await this.#scheduleNextAlarm();
830
+ await this._scheduleNextAlarm();
686
831
  return true;
687
832
  }
688
833
 
689
- async #scheduleNextAlarm() {
834
+ private async _scheduleNextAlarm() {
690
835
  // Find the next schedule that needs to be executed
691
836
  const result = this.sql`
692
837
  SELECT time FROM cf_agents_schedules
@@ -703,10 +848,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
703
848
  }
704
849
 
705
850
  /**
706
- * Method called when an alarm fires
707
- * 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/}
708
857
  */
709
- async alarm() {
858
+ public readonly alarm = async () => {
710
859
  const now = Math.floor(Date.now() / 1000);
711
860
 
712
861
  // Get all schedules that should be executed now
@@ -752,8 +901,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
752
901
  }
753
902
 
754
903
  // Schedule the next alarm
755
- await this.#scheduleNextAlarm();
756
- }
904
+ await this._scheduleNextAlarm();
905
+ };
757
906
 
758
907
  /**
759
908
  * Destroy the Agent, removing all state and scheduled tasks
@@ -762,20 +911,184 @@ export class Agent<Env, State = unknown> extends Server<Env> {
762
911
  // drop all tables
763
912
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
764
913
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
914
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
765
915
 
766
916
  // delete all alarms
767
917
  await this.ctx.storage.deleteAlarm();
768
918
  await this.ctx.storage.deleteAll();
919
+ this.ctx.abort("destroyed"); // enforce that the agent is evicted
769
920
  }
770
921
 
771
922
  /**
772
923
  * Get all methods marked as callable on this Agent
773
924
  * @returns A map of method names to their metadata
774
925
  */
775
- #isCallable(method: string): boolean {
776
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
926
+ private _isCallable(method: string): boolean {
777
927
  return callableMetadata.has(this[method as keyof this] as Function);
778
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
+ }
779
1092
  }
780
1093
 
781
1094
  /**
@@ -815,9 +1128,9 @@ export async function routeAgentRequest<Env>(
815
1128
  const corsHeaders =
816
1129
  options?.cors === true
817
1130
  ? {
818
- "Access-Control-Allow-Origin": "*",
819
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
820
1131
  "Access-Control-Allow-Credentials": "true",
1132
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1133
+ "Access-Control-Allow-Origin": "*",
821
1134
  "Access-Control-Max-Age": "86400",
822
1135
  }
823
1136
  : options?.cors;
@@ -865,9 +1178,9 @@ export async function routeAgentRequest<Env>(
865
1178
  * @param options Routing options
866
1179
  */
867
1180
  export async function routeAgentEmail<Env>(
868
- email: ForwardableEmailMessage,
869
- env: Env,
870
- options?: AgentOptions<Env>
1181
+ _email: ForwardableEmailMessage,
1182
+ _env: Env,
1183
+ _options?: AgentOptions<Env>
871
1184
  ): Promise<void> {}
872
1185
 
873
1186
  /**
@@ -894,13 +1207,13 @@ export async function getAgentByName<Env, T extends Agent<Env>>(
894
1207
  * A wrapper for streaming responses in callable methods
895
1208
  */
896
1209
  export class StreamingResponse {
897
- #connection: Connection;
898
- #id: string;
899
- #closed = false;
1210
+ private _connection: Connection;
1211
+ private _id: string;
1212
+ private _closed = false;
900
1213
 
901
1214
  constructor(connection: Connection, id: string) {
902
- this.#connection = connection;
903
- this.#id = id;
1215
+ this._connection = connection;
1216
+ this._id = id;
904
1217
  }
905
1218
 
906
1219
  /**
@@ -908,17 +1221,17 @@ export class StreamingResponse {
908
1221
  * @param chunk The data to send
909
1222
  */
910
1223
  send(chunk: unknown) {
911
- if (this.#closed) {
1224
+ if (this._closed) {
912
1225
  throw new Error("StreamingResponse is already closed");
913
1226
  }
914
1227
  const response: RPCResponse = {
915
- type: "rpc",
916
- id: this.#id,
917
- success: true,
918
- result: chunk,
919
1228
  done: false,
1229
+ id: this._id,
1230
+ result: chunk,
1231
+ success: true,
1232
+ type: "rpc",
920
1233
  };
921
- this.#connection.send(JSON.stringify(response));
1234
+ this._connection.send(JSON.stringify(response));
922
1235
  }
923
1236
 
924
1237
  /**
@@ -926,17 +1239,17 @@ export class StreamingResponse {
926
1239
  * @param finalChunk Optional final chunk of data to send
927
1240
  */
928
1241
  end(finalChunk?: unknown) {
929
- if (this.#closed) {
1242
+ if (this._closed) {
930
1243
  throw new Error("StreamingResponse is already closed");
931
1244
  }
932
- this.#closed = true;
1245
+ this._closed = true;
933
1246
  const response: RPCResponse = {
934
- type: "rpc",
935
- id: this.#id,
936
- success: true,
937
- result: finalChunk,
938
1247
  done: true,
1248
+ id: this._id,
1249
+ result: finalChunk,
1250
+ success: true,
1251
+ type: "rpc",
939
1252
  };
940
- this.#connection.send(JSON.stringify(response));
1253
+ this._connection.send(JSON.stringify(response));
941
1254
  }
942
1255
  }