agents 0.0.0-067cd1a → 0.0.0-0ac89c6

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.
package/src/index.ts CHANGED
@@ -13,6 +13,20 @@ import { nanoid } from "nanoid";
13
13
 
14
14
  import { AsyncLocalStorage } from "node:async_hooks";
15
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";
16
30
 
17
31
  export type { Connection, WSMessage, ConnectionContext } from "partyserver";
18
32
 
@@ -98,7 +112,6 @@ export type CallableMetadata = {
98
112
  streaming?: boolean;
99
113
  };
100
114
 
101
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
102
115
  const callableMetadata = new Map<Function, CallableMetadata>();
103
116
 
104
117
  /**
@@ -159,6 +172,43 @@ function getNextCronTime(cron: string) {
159
172
  return interval.getNextDate();
160
173
  }
161
174
 
175
+ /**
176
+ * MCP Server state update message from server -> Client
177
+ */
178
+ export type MCPServerMessage = {
179
+ type: "cf_agent_mcp_servers";
180
+ mcp: MCPServersState;
181
+ };
182
+
183
+ export type MCPServersState = {
184
+ servers: {
185
+ [id: string]: MCPServer;
186
+ };
187
+ tools: Tool[];
188
+ prompts: Prompt[];
189
+ resources: Resource[];
190
+ };
191
+
192
+ export type MCPServer = {
193
+ name: string;
194
+ server_url: string;
195
+ auth_url: string | null;
196
+ state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
197
+ };
198
+
199
+ /**
200
+ * MCP Server data stored in DO SQL for resuming MCP Server connections
201
+ */
202
+ type MCPServerRow = {
203
+ id: string;
204
+ name: string;
205
+ server_url: string;
206
+ client_id: string | null;
207
+ auth_url: string | null;
208
+ callback_url: string;
209
+ server_options: string;
210
+ };
211
+
162
212
  const STATE_ROW_ID = "cf_state_row_id";
163
213
  const STATE_WAS_CHANGED = "cf_state_was_changed";
164
214
 
@@ -200,12 +250,12 @@ export function getCurrentAgent<
200
250
  * @template State State type to store within the Agent
201
251
  */
202
252
  export class Agent<Env, State = unknown> extends Server<Env> {
203
- #state = DEFAULT_STATE as State;
253
+ private _state = DEFAULT_STATE as State;
204
254
 
205
- #ParentClass: typeof Agent<Env, State> =
255
+ private _ParentClass: typeof Agent<Env, State> =
206
256
  Object.getPrototypeOf(this).constructor;
207
257
 
208
- mcp: MCPClientManager = new MCPClientManager(this.#ParentClass.name, "0.0.1");
258
+ mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
209
259
 
210
260
  /**
211
261
  * Initial state for the Agent
@@ -217,9 +267,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
217
267
  * Current state of the Agent
218
268
  */
219
269
  get state(): State {
220
- if (this.#state !== DEFAULT_STATE) {
270
+ if (this._state !== DEFAULT_STATE) {
221
271
  // state was previously set, and populated internal state
222
- return this.#state;
272
+ return this._state;
223
273
  }
224
274
  // looks like this is the first time the state is being accessed
225
275
  // check if the state was set in a previous life
@@ -239,8 +289,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
239
289
  ) {
240
290
  const state = result[0]?.state as string; // could be null?
241
291
 
242
- this.#state = JSON.parse(state);
243
- return this.#state;
292
+ this._state = JSON.parse(state);
293
+ return this._state;
244
294
  }
245
295
 
246
296
  // ok, this is the first time the state is being accessed
@@ -301,7 +351,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
301
351
  `;
302
352
 
303
353
  void this.ctx.blockConcurrencyWhile(async () => {
304
- return this.#tryCatch(async () => {
354
+ return this._tryCatch(async () => {
305
355
  // Create alarms table if it doesn't exist
306
356
  this.sql`
307
357
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
@@ -321,13 +371,53 @@ export class Agent<Env, State = unknown> extends Server<Env> {
321
371
  });
322
372
  });
323
373
 
374
+ this.sql`
375
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
376
+ id TEXT PRIMARY KEY NOT NULL,
377
+ name TEXT NOT NULL,
378
+ server_url TEXT NOT NULL,
379
+ callback_url TEXT NOT NULL,
380
+ client_id TEXT,
381
+ auth_url TEXT,
382
+ server_options TEXT
383
+ )
384
+ `;
385
+
386
+ const _onRequest = this.onRequest.bind(this);
387
+ this.onRequest = (request: Request) => {
388
+ return agentContext.run(
389
+ { agent: this, connection: undefined, request },
390
+ async () => {
391
+ if (this.mcp.isCallbackRequest(request)) {
392
+ await this.mcp.handleCallbackRequest(request);
393
+
394
+ // after the MCP connection handshake, we can send updated mcp state
395
+ this.broadcast(
396
+ JSON.stringify({
397
+ type: "cf_agent_mcp_servers",
398
+ mcp: this._getMcpServerStateInternal(),
399
+ })
400
+ );
401
+
402
+ // We probably should let the user configure this response/redirect, but this is fine for now.
403
+ return new Response("<script>window.close();</script>", {
404
+ status: 200,
405
+ headers: { "content-type": "text/html" },
406
+ });
407
+ }
408
+
409
+ return this._tryCatch(() => _onRequest(request));
410
+ }
411
+ );
412
+ };
413
+
324
414
  const _onMessage = this.onMessage.bind(this);
325
415
  this.onMessage = async (connection: Connection, message: WSMessage) => {
326
416
  return agentContext.run(
327
417
  { agent: this, connection, request: undefined },
328
418
  async () => {
329
419
  if (typeof message !== "string") {
330
- return this.#tryCatch(() => _onMessage(connection, message));
420
+ return this._tryCatch(() => _onMessage(connection, message));
331
421
  }
332
422
 
333
423
  let parsed: unknown;
@@ -335,11 +425,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
335
425
  parsed = JSON.parse(message);
336
426
  } catch (e) {
337
427
  // silently fail and let the onMessage handler handle it
338
- return this.#tryCatch(() => _onMessage(connection, message));
428
+ return this._tryCatch(() => _onMessage(connection, message));
339
429
  }
340
430
 
341
431
  if (isStateUpdateMessage(parsed)) {
342
- this.#setStateInternal(parsed.state as State, connection);
432
+ this._setStateInternal(parsed.state as State, connection);
343
433
  return;
344
434
  }
345
435
 
@@ -353,11 +443,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
353
443
  throw new Error(`Method ${method} does not exist`);
354
444
  }
355
445
 
356
- if (!this.#isCallable(method)) {
446
+ if (!this._isCallable(method)) {
357
447
  throw new Error(`Method ${method} is not callable`);
358
448
  }
359
449
 
360
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
361
450
  const metadata = callableMetadata.get(methodFn as Function);
362
451
 
363
452
  // For streaming methods, pass a StreamingResponse object
@@ -392,7 +481,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
392
481
  return;
393
482
  }
394
483
 
395
- return this.#tryCatch(() => _onMessage(connection, message));
484
+ return this._tryCatch(() => _onMessage(connection, message));
396
485
  }
397
486
  );
398
487
  };
@@ -413,15 +502,65 @@ export class Agent<Env, State = unknown> extends Server<Env> {
413
502
  })
414
503
  );
415
504
  }
416
- return this.#tryCatch(() => _onConnect(connection, ctx));
505
+
506
+ connection.send(
507
+ JSON.stringify({
508
+ type: "cf_agent_mcp_servers",
509
+ mcp: this._getMcpServerStateInternal(),
510
+ })
511
+ );
512
+
513
+ return this._tryCatch(() => _onConnect(connection, ctx));
417
514
  }, 20);
418
515
  }
419
516
  );
420
517
  };
518
+
519
+ const _onStart = this.onStart.bind(this);
520
+ this.onStart = async () => {
521
+ return agentContext.run(
522
+ { agent: this, connection: undefined, request: undefined },
523
+ async () => {
524
+ const servers = this.sql<MCPServerRow>`
525
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
526
+ `;
527
+
528
+ // from DO storage, reconnect to all servers using our saved auth information
529
+ await Promise.allSettled(
530
+ servers.map((server) => {
531
+ return this._connectToMcpServerInternal(
532
+ server.name,
533
+ server.server_url,
534
+ server.callback_url,
535
+ server.server_options
536
+ ? JSON.parse(server.server_options)
537
+ : undefined,
538
+ {
539
+ id: server.id,
540
+ oauthClientId: server.client_id ?? undefined,
541
+ }
542
+ );
543
+ })
544
+ );
545
+
546
+ this.broadcast(
547
+ JSON.stringify({
548
+ type: "cf_agent_mcp_servers",
549
+ mcp: this._getMcpServerStateInternal(),
550
+ })
551
+ );
552
+
553
+ await this._tryCatch(() => _onStart());
554
+ }
555
+ );
556
+ };
421
557
  }
422
558
 
423
- #setStateInternal(state: State, source: Connection | "server" = "server") {
424
- this.#state = state;
559
+ private _setStateInternal(
560
+ state: State,
561
+ source: Connection | "server" = "server"
562
+ ) {
563
+ this._state = state;
425
564
  this.sql`
426
565
  INSERT OR REPLACE INTO cf_agents_state (id, state)
427
566
  VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
@@ -437,7 +576,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
437
576
  }),
438
577
  source !== "server" ? [source.id] : []
439
578
  );
440
- return this.#tryCatch(() => {
579
+ return this._tryCatch(() => {
441
580
  const { connection, request } = agentContext.getStore() || {};
442
581
  return agentContext.run(
443
582
  { agent: this, connection, request },
@@ -453,7 +592,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
453
592
  * @param state New state to set
454
593
  */
455
594
  setState(state: State) {
456
- this.#setStateInternal(state, "server");
595
+ this._setStateInternal(state, "server");
457
596
  }
458
597
 
459
598
  /**
@@ -478,7 +617,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
478
617
  );
479
618
  }
480
619
 
481
- async #tryCatch<T>(fn: () => T | Promise<T>) {
620
+ private async _tryCatch<T>(fn: () => T | Promise<T>) {
482
621
  try {
483
622
  return await fn();
484
623
  } catch (e) {
@@ -552,7 +691,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
552
691
  )}, 'scheduled', ${timestamp})
553
692
  `;
554
693
 
555
- await this.#scheduleNextAlarm();
694
+ await this._scheduleNextAlarm();
556
695
 
557
696
  return {
558
697
  id,
@@ -573,7 +712,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
573
712
  )}, 'delayed', ${when}, ${timestamp})
574
713
  `;
575
714
 
576
- await this.#scheduleNextAlarm();
715
+ await this._scheduleNextAlarm();
577
716
 
578
717
  return {
579
718
  id,
@@ -595,7 +734,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
595
734
  )}, 'cron', ${when}, ${timestamp})
596
735
  `;
597
736
 
598
- await this.#scheduleNextAlarm();
737
+ await this._scheduleNextAlarm();
599
738
 
600
739
  return {
601
740
  id,
@@ -682,11 +821,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
682
821
  async cancelSchedule(id: string): Promise<boolean> {
683
822
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
684
823
 
685
- await this.#scheduleNextAlarm();
824
+ await this._scheduleNextAlarm();
686
825
  return true;
687
826
  }
688
827
 
689
- async #scheduleNextAlarm() {
828
+ private async _scheduleNextAlarm() {
690
829
  // Find the next schedule that needs to be executed
691
830
  const result = this.sql`
692
831
  SELECT time FROM cf_agents_schedules
@@ -703,10 +842,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
703
842
  }
704
843
 
705
844
  /**
706
- * Method called when an alarm fires
707
- * Executes any scheduled tasks that are due
845
+ * Method called when an alarm fires.
846
+ * Executes any scheduled tasks that are due.
847
+ *
848
+ * @remarks
849
+ * To schedule a task, please use the `this.schedule` method instead.
850
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
708
851
  */
709
- async alarm() {
852
+ public readonly alarm = async () => {
710
853
  const now = Math.floor(Date.now() / 1000);
711
854
 
712
855
  // Get all schedules that should be executed now
@@ -752,8 +895,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
752
895
  }
753
896
 
754
897
  // Schedule the next alarm
755
- await this.#scheduleNextAlarm();
756
- }
898
+ await this._scheduleNextAlarm();
899
+ };
757
900
 
758
901
  /**
759
902
  * Destroy the Agent, removing all state and scheduled tasks
@@ -762,6 +905,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
762
905
  // drop all tables
763
906
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
764
907
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
908
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
765
909
 
766
910
  // delete all alarms
767
911
  await this.ctx.storage.deleteAlarm();
@@ -772,10 +916,168 @@ export class Agent<Env, State = unknown> extends Server<Env> {
772
916
  * Get all methods marked as callable on this Agent
773
917
  * @returns A map of method names to their metadata
774
918
  */
775
- #isCallable(method: string): boolean {
776
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
919
+ private _isCallable(method: string): boolean {
777
920
  return callableMetadata.has(this[method as keyof this] as Function);
778
921
  }
922
+
923
+ /**
924
+ * Connect to a new MCP Server
925
+ *
926
+ * @param url MCP Server SSE URL
927
+ * @param callbackHost Base host for the agent, used for the redirect URI.
928
+ * @param agentsPrefix agents routing prefix if not using `agents`
929
+ * @param options MCP client and transport (header) options
930
+ * @returns authUrl
931
+ */
932
+ async addMcpServer(
933
+ serverName: string,
934
+ url: string,
935
+ callbackHost: string,
936
+ agentsPrefix = "agents",
937
+ options?: {
938
+ client?: ConstructorParameters<typeof Client>[1];
939
+ transport?: {
940
+ headers: HeadersInit;
941
+ };
942
+ }
943
+ ): Promise<{ id: string; authUrl: string | undefined }> {
944
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
945
+
946
+ const result = await this._connectToMcpServerInternal(
947
+ serverName,
948
+ url,
949
+ callbackUrl,
950
+ options
951
+ );
952
+
953
+ this.broadcast(
954
+ JSON.stringify({
955
+ type: "cf_agent_mcp_servers",
956
+ mcp: this._getMcpServerStateInternal(),
957
+ })
958
+ );
959
+
960
+ return result;
961
+ }
962
+
963
+ async _connectToMcpServerInternal(
964
+ serverName: string,
965
+ url: string,
966
+ callbackUrl: string,
967
+ // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
968
+ options?: {
969
+ client?: ConstructorParameters<typeof Client>[1];
970
+ /**
971
+ * We don't expose the normal set of transport options because:
972
+ * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
973
+ * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
974
+ *
975
+ * 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).
976
+ */
977
+ transport?: {
978
+ headers?: HeadersInit;
979
+ };
980
+ },
981
+ reconnect?: {
982
+ id: string;
983
+ oauthClientId?: string;
984
+ }
985
+ ): Promise<{ id: string; authUrl: string | undefined }> {
986
+ const authProvider = new DurableObjectOAuthClientProvider(
987
+ this.ctx.storage,
988
+ this.name,
989
+ callbackUrl
990
+ );
991
+
992
+ if (reconnect) {
993
+ authProvider.serverId = reconnect.id;
994
+ if (reconnect.oauthClientId) {
995
+ authProvider.clientId = reconnect.oauthClientId;
996
+ }
997
+ }
998
+
999
+ // allows passing through transport headers if necessary
1000
+ // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
1001
+ let headerTransportOpts: SSEClientTransportOptions = {};
1002
+ if (options?.transport?.headers) {
1003
+ headerTransportOpts = {
1004
+ eventSourceInit: {
1005
+ fetch: (url, init) =>
1006
+ fetch(url, {
1007
+ ...init,
1008
+ headers: options?.transport?.headers,
1009
+ }),
1010
+ },
1011
+ requestInit: {
1012
+ headers: options?.transport?.headers,
1013
+ },
1014
+ };
1015
+ }
1016
+
1017
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
1018
+ reconnect,
1019
+ transport: {
1020
+ ...headerTransportOpts,
1021
+ authProvider,
1022
+ },
1023
+ client: options?.client,
1024
+ });
1025
+
1026
+ this.sql`
1027
+ INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1028
+ VALUES (
1029
+ ${id},
1030
+ ${serverName},
1031
+ ${url},
1032
+ ${clientId ?? null},
1033
+ ${authUrl ?? null},
1034
+ ${callbackUrl},
1035
+ ${options ? JSON.stringify(options) : null}
1036
+ );
1037
+ `;
1038
+
1039
+ return {
1040
+ id,
1041
+ authUrl,
1042
+ };
1043
+ }
1044
+
1045
+ async removeMcpServer(id: string) {
1046
+ this.mcp.closeConnection(id);
1047
+ this.sql`
1048
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1049
+ `;
1050
+ this.broadcast(
1051
+ JSON.stringify({
1052
+ type: "cf_agent_mcp_servers",
1053
+ mcp: this._getMcpServerStateInternal(),
1054
+ })
1055
+ );
1056
+ }
1057
+
1058
+ private _getMcpServerStateInternal(): MCPServersState {
1059
+ const mcpState: MCPServersState = {
1060
+ servers: {},
1061
+ tools: this.mcp.listTools(),
1062
+ prompts: this.mcp.listPrompts(),
1063
+ resources: this.mcp.listResources(),
1064
+ };
1065
+
1066
+ const servers = this.sql<MCPServerRow>`
1067
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1068
+ `;
1069
+
1070
+ for (const server of servers) {
1071
+ mcpState.servers[server.id] = {
1072
+ name: server.name,
1073
+ server_url: server.server_url,
1074
+ auth_url: server.auth_url,
1075
+ state: this.mcp.mcpConnections[server.id].connectionState,
1076
+ };
1077
+ }
1078
+
1079
+ return mcpState;
1080
+ }
779
1081
  }
780
1082
 
781
1083
  /**
@@ -894,13 +1196,13 @@ export async function getAgentByName<Env, T extends Agent<Env>>(
894
1196
  * A wrapper for streaming responses in callable methods
895
1197
  */
896
1198
  export class StreamingResponse {
897
- #connection: Connection;
898
- #id: string;
899
- #closed = false;
1199
+ private _connection: Connection;
1200
+ private _id: string;
1201
+ private _closed = false;
900
1202
 
901
1203
  constructor(connection: Connection, id: string) {
902
- this.#connection = connection;
903
- this.#id = id;
1204
+ this._connection = connection;
1205
+ this._id = id;
904
1206
  }
905
1207
 
906
1208
  /**
@@ -908,17 +1210,17 @@ export class StreamingResponse {
908
1210
  * @param chunk The data to send
909
1211
  */
910
1212
  send(chunk: unknown) {
911
- if (this.#closed) {
1213
+ if (this._closed) {
912
1214
  throw new Error("StreamingResponse is already closed");
913
1215
  }
914
1216
  const response: RPCResponse = {
915
1217
  type: "rpc",
916
- id: this.#id,
1218
+ id: this._id,
917
1219
  success: true,
918
1220
  result: chunk,
919
1221
  done: false,
920
1222
  };
921
- this.#connection.send(JSON.stringify(response));
1223
+ this._connection.send(JSON.stringify(response));
922
1224
  }
923
1225
 
924
1226
  /**
@@ -926,17 +1228,17 @@ export class StreamingResponse {
926
1228
  * @param finalChunk Optional final chunk of data to send
927
1229
  */
928
1230
  end(finalChunk?: unknown) {
929
- if (this.#closed) {
1231
+ if (this._closed) {
930
1232
  throw new Error("StreamingResponse is already closed");
931
1233
  }
932
- this.#closed = true;
1234
+ this._closed = true;
933
1235
  const response: RPCResponse = {
934
1236
  type: "rpc",
935
- id: this.#id,
1237
+ id: this._id,
936
1238
  success: true,
937
1239
  result: finalChunk,
938
1240
  done: true,
939
1241
  };
940
- this.#connection.send(JSON.stringify(response));
1242
+ this._connection.send(JSON.stringify(response));
941
1243
  }
942
1244
  }