agents 0.0.0-881f11e → 0.0.0-89b649a

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 (40) hide show
  1. package/dist/ai-chat-agent.d.ts +28 -2
  2. package/dist/ai-chat-agent.js +99 -103
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-react.d.ts +12 -0
  5. package/dist/ai-react.js +0 -2
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/chunk-BZXOAZUX.js +106 -0
  8. package/dist/chunk-BZXOAZUX.js.map +1 -0
  9. package/dist/{chunk-JR3NW4A7.js → chunk-MXJNY43J.js} +265 -101
  10. package/dist/chunk-MXJNY43J.js.map +1 -0
  11. package/dist/{chunk-7VFQNJFK.js → chunk-OYJXQRRH.js} +26 -23
  12. package/dist/chunk-OYJXQRRH.js.map +1 -0
  13. package/dist/chunk-VCSB47AK.js +116 -0
  14. package/dist/chunk-VCSB47AK.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 +97 -4
  19. package/dist/index.js +4 -3
  20. package/dist/mcp/client.d.ts +13 -15
  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 +10 -1
  26. package/dist/mcp/index.js +90 -124
  27. package/dist/mcp/index.js.map +1 -1
  28. package/dist/react.d.ts +85 -5
  29. package/dist/react.js +14 -2
  30. package/dist/react.js.map +1 -1
  31. package/dist/schedule.js +0 -2
  32. package/dist/schedule.js.map +1 -1
  33. package/dist/serializable.d.ts +32 -0
  34. package/dist/serializable.js +1 -0
  35. package/package.json +8 -8
  36. package/src/index.ts +343 -45
  37. package/dist/chunk-7VFQNJFK.js.map +0 -1
  38. package/dist/chunk-HMLY7DHA.js +0 -16
  39. package/dist/chunk-JR3NW4A7.js.map +0 -1
  40. /package/dist/{chunk-HMLY7DHA.js.map → serializable.js.map} +0 -0
package/src/index.ts CHANGED
@@ -1,20 +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
+ import type {
15
+ Prompt,
16
+ Resource,
17
+ ServerCapabilities,
18
+ Tool,
19
+ } from "@modelcontextprotocol/sdk/types.js";
14
20
  import { AsyncLocalStorage } from "node:async_hooks";
15
21
  import { MCPClientManager } from "./mcp/client";
22
+ import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider";
23
+
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";
16
29
 
17
- export type { Connection, WSMessage, ConnectionContext } from "partyserver";
30
+ export type { Connection, ConnectionContext, WSMessage } from "partyserver";
18
31
 
19
32
  /**
20
33
  * RPC request message from client
@@ -98,7 +111,6 @@ export type CallableMetadata = {
98
111
  streaming?: boolean;
99
112
  };
100
113
 
101
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
102
114
  const callableMetadata = new Map<Function, CallableMetadata>();
103
115
 
104
116
  /**
@@ -159,6 +171,48 @@ function getNextCronTime(cron: string) {
159
171
  return interval.getNextDate();
160
172
  }
161
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
+
162
216
  const STATE_ROW_ID = "cf_state_row_id";
163
217
  const STATE_WAS_CHANGED = "cf_state_was_changed";
164
218
 
@@ -200,12 +254,12 @@ export function getCurrentAgent<
200
254
  * @template State State type to store within the Agent
201
255
  */
202
256
  export class Agent<Env, State = unknown> extends Server<Env> {
203
- #state = DEFAULT_STATE as State;
257
+ private _state = DEFAULT_STATE as State;
204
258
 
205
- #ParentClass: typeof Agent<Env, State> =
259
+ private _ParentClass: typeof Agent<Env, State> =
206
260
  Object.getPrototypeOf(this).constructor;
207
261
 
208
- mcp: MCPClientManager = new MCPClientManager(this.#ParentClass.name, "0.0.1");
262
+ mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
209
263
 
210
264
  /**
211
265
  * Initial state for the Agent
@@ -217,9 +271,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
217
271
  * Current state of the Agent
218
272
  */
219
273
  get state(): State {
220
- if (this.#state !== DEFAULT_STATE) {
274
+ if (this._state !== DEFAULT_STATE) {
221
275
  // state was previously set, and populated internal state
222
- return this.#state;
276
+ return this._state;
223
277
  }
224
278
  // looks like this is the first time the state is being accessed
225
279
  // check if the state was set in a previous life
@@ -239,8 +293,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
239
293
  ) {
240
294
  const state = result[0]?.state as string; // could be null?
241
295
 
242
- this.#state = JSON.parse(state);
243
- return this.#state;
296
+ this._state = JSON.parse(state);
297
+ return this._state;
244
298
  }
245
299
 
246
300
  // ok, this is the first time the state is being accessed
@@ -301,7 +355,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
301
355
  `;
302
356
 
303
357
  void this.ctx.blockConcurrencyWhile(async () => {
304
- return this.#tryCatch(async () => {
358
+ return this._tryCatch(async () => {
305
359
  // Create alarms table if it doesn't exist
306
360
  this.sql`
307
361
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
@@ -321,12 +375,42 @@ export class Agent<Env, State = unknown> extends Server<Env> {
321
375
  });
322
376
  });
323
377
 
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
+ `;
389
+
324
390
  const _onRequest = this.onRequest.bind(this);
325
391
  this.onRequest = (request: Request) => {
326
392
  return agentContext.run(
327
393
  { agent: this, connection: undefined, request },
328
394
  async () => {
329
- return this.#tryCatch(() => _onRequest(request));
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
+ }
412
+
413
+ return this._tryCatch(() => _onRequest(request));
330
414
  }
331
415
  );
332
416
  };
@@ -337,7 +421,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
337
421
  { agent: this, connection, request: undefined },
338
422
  async () => {
339
423
  if (typeof message !== "string") {
340
- return this.#tryCatch(() => _onMessage(connection, message));
424
+ return this._tryCatch(() => _onMessage(connection, message));
341
425
  }
342
426
 
343
427
  let parsed: unknown;
@@ -345,11 +429,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
345
429
  parsed = JSON.parse(message);
346
430
  } catch (e) {
347
431
  // silently fail and let the onMessage handler handle it
348
- return this.#tryCatch(() => _onMessage(connection, message));
432
+ return this._tryCatch(() => _onMessage(connection, message));
349
433
  }
350
434
 
351
435
  if (isStateUpdateMessage(parsed)) {
352
- this.#setStateInternal(parsed.state as State, connection);
436
+ this._setStateInternal(parsed.state as State, connection);
353
437
  return;
354
438
  }
355
439
 
@@ -363,11 +447,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
363
447
  throw new Error(`Method ${method} does not exist`);
364
448
  }
365
449
 
366
- if (!this.#isCallable(method)) {
450
+ if (!this._isCallable(method)) {
367
451
  throw new Error(`Method ${method} is not callable`);
368
452
  }
369
453
 
370
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
371
454
  const metadata = callableMetadata.get(methodFn as Function);
372
455
 
373
456
  // For streaming methods, pass a StreamingResponse object
@@ -402,7 +485,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
402
485
  return;
403
486
  }
404
487
 
405
- return this.#tryCatch(() => _onMessage(connection, message));
488
+ return this._tryCatch(() => _onMessage(connection, message));
406
489
  }
407
490
  );
408
491
  };
@@ -423,15 +506,67 @@ export class Agent<Env, State = unknown> extends Server<Env> {
423
506
  })
424
507
  );
425
508
  }
426
- return this.#tryCatch(() => _onConnect(connection, ctx));
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));
427
518
  }, 20);
428
519
  }
429
520
  );
430
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(
553
+ JSON.stringify({
554
+ type: "cf_agent_mcp_servers",
555
+ mcp: this.getMcpServers(),
556
+ })
557
+ );
558
+
559
+ await this._tryCatch(() => _onStart());
560
+ }
561
+ );
562
+ };
431
563
  }
432
564
 
433
- #setStateInternal(state: State, source: Connection | "server" = "server") {
434
- this.#state = state;
565
+ private _setStateInternal(
566
+ state: State,
567
+ source: Connection | "server" = "server"
568
+ ) {
569
+ this._state = state;
435
570
  this.sql`
436
571
  INSERT OR REPLACE INTO cf_agents_state (id, state)
437
572
  VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
@@ -447,7 +582,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
447
582
  }),
448
583
  source !== "server" ? [source.id] : []
449
584
  );
450
- return this.#tryCatch(() => {
585
+ return this._tryCatch(() => {
451
586
  const { connection, request } = agentContext.getStore() || {};
452
587
  return agentContext.run(
453
588
  { agent: this, connection, request },
@@ -463,7 +598,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
463
598
  * @param state New state to set
464
599
  */
465
600
  setState(state: State) {
466
- this.#setStateInternal(state, "server");
601
+ this._setStateInternal(state, "server");
467
602
  }
468
603
 
469
604
  /**
@@ -488,7 +623,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
488
623
  );
489
624
  }
490
625
 
491
- async #tryCatch<T>(fn: () => T | Promise<T>) {
626
+ private async _tryCatch<T>(fn: () => T | Promise<T>) {
492
627
  try {
493
628
  return await fn();
494
629
  } catch (e) {
@@ -562,7 +697,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
562
697
  )}, 'scheduled', ${timestamp})
563
698
  `;
564
699
 
565
- await this.#scheduleNextAlarm();
700
+ await this._scheduleNextAlarm();
566
701
 
567
702
  return {
568
703
  id,
@@ -583,7 +718,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
583
718
  )}, 'delayed', ${when}, ${timestamp})
584
719
  `;
585
720
 
586
- await this.#scheduleNextAlarm();
721
+ await this._scheduleNextAlarm();
587
722
 
588
723
  return {
589
724
  id,
@@ -605,7 +740,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
605
740
  )}, 'cron', ${when}, ${timestamp})
606
741
  `;
607
742
 
608
- await this.#scheduleNextAlarm();
743
+ await this._scheduleNextAlarm();
609
744
 
610
745
  return {
611
746
  id,
@@ -692,11 +827,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
692
827
  async cancelSchedule(id: string): Promise<boolean> {
693
828
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
694
829
 
695
- await this.#scheduleNextAlarm();
830
+ await this._scheduleNextAlarm();
696
831
  return true;
697
832
  }
698
833
 
699
- async #scheduleNextAlarm() {
834
+ private async _scheduleNextAlarm() {
700
835
  // Find the next schedule that needs to be executed
701
836
  const result = this.sql`
702
837
  SELECT time FROM cf_agents_schedules
@@ -766,7 +901,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
766
901
  }
767
902
 
768
903
  // Schedule the next alarm
769
- await this.#scheduleNextAlarm();
904
+ await this._scheduleNextAlarm();
770
905
  };
771
906
 
772
907
  /**
@@ -776,6 +911,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
776
911
  // drop all tables
777
912
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
778
913
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
914
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
779
915
 
780
916
  // delete all alarms
781
917
  await this.ctx.storage.deleteAlarm();
@@ -786,10 +922,172 @@ export class Agent<Env, State = unknown> extends Server<Env> {
786
922
  * Get all methods marked as callable on this Agent
787
923
  * @returns A map of method names to their metadata
788
924
  */
789
- #isCallable(method: string): boolean {
790
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
925
+ private _isCallable(method: string): boolean {
791
926
  return callableMetadata.has(this[method as keyof this] as Function);
792
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
+ }
793
1091
  }
794
1092
 
795
1093
  /**
@@ -908,13 +1206,13 @@ export async function getAgentByName<Env, T extends Agent<Env>>(
908
1206
  * A wrapper for streaming responses in callable methods
909
1207
  */
910
1208
  export class StreamingResponse {
911
- #connection: Connection;
912
- #id: string;
913
- #closed = false;
1209
+ private _connection: Connection;
1210
+ private _id: string;
1211
+ private _closed = false;
914
1212
 
915
1213
  constructor(connection: Connection, id: string) {
916
- this.#connection = connection;
917
- this.#id = id;
1214
+ this._connection = connection;
1215
+ this._id = id;
918
1216
  }
919
1217
 
920
1218
  /**
@@ -922,17 +1220,17 @@ export class StreamingResponse {
922
1220
  * @param chunk The data to send
923
1221
  */
924
1222
  send(chunk: unknown) {
925
- if (this.#closed) {
1223
+ if (this._closed) {
926
1224
  throw new Error("StreamingResponse is already closed");
927
1225
  }
928
1226
  const response: RPCResponse = {
929
1227
  type: "rpc",
930
- id: this.#id,
1228
+ id: this._id,
931
1229
  success: true,
932
1230
  result: chunk,
933
1231
  done: false,
934
1232
  };
935
- this.#connection.send(JSON.stringify(response));
1233
+ this._connection.send(JSON.stringify(response));
936
1234
  }
937
1235
 
938
1236
  /**
@@ -940,17 +1238,17 @@ export class StreamingResponse {
940
1238
  * @param finalChunk Optional final chunk of data to send
941
1239
  */
942
1240
  end(finalChunk?: unknown) {
943
- if (this.#closed) {
1241
+ if (this._closed) {
944
1242
  throw new Error("StreamingResponse is already closed");
945
1243
  }
946
- this.#closed = true;
1244
+ this._closed = true;
947
1245
  const response: RPCResponse = {
948
1246
  type: "rpc",
949
- id: this.#id,
1247
+ id: this._id,
950
1248
  success: true,
951
1249
  result: finalChunk,
952
1250
  done: true,
953
1251
  };
954
- this.#connection.send(JSON.stringify(response));
1252
+ this._connection.send(JSON.stringify(response));
955
1253
  }
956
1254
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/mcp/sse-edge.ts","../src/mcp/client-connection.ts","../src/mcp/client.ts"],"sourcesContent":["import {\n SSEClientTransport,\n type SSEClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\n\nexport class SSEEdgeClientTransport extends SSEClientTransport {\n private authProvider: OAuthClientProvider | undefined;\n /**\n * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment\n */\n constructor(url: URL, options: SSEClientTransportOptions) {\n const fetchOverride: typeof fetch = async (\n fetchUrl: RequestInfo | URL,\n fetchInit: RequestInit = {}\n ) => {\n // add auth headers\n const headers = await this.authHeaders();\n const workerOptions = {\n ...fetchInit,\n headers: {\n ...options.requestInit?.headers,\n ...fetchInit?.headers,\n ...headers,\n },\n };\n\n // Remove unsupported properties\n // biome-ignore lint/performance/noDelete: workaround for workers environment\n delete workerOptions.mode;\n\n // Call the original fetch with fixed options\n return (\n (options.eventSourceInit?.fetch?.(\n fetchUrl as URL | string,\n // @ts-expect-error Expects FetchLikeInit from EventSource but is compatible with RequestInit\n workerOptions\n ) as Promise<Response>) || fetch(fetchUrl, workerOptions)\n );\n };\n\n super(url, {\n ...options,\n eventSourceInit: {\n ...options.eventSourceInit,\n fetch: fetchOverride,\n },\n });\n this.authProvider = options.authProvider;\n }\n\n async authHeaders() {\n if (this.authProvider) {\n const tokens = await this.authProvider.tokens();\n if (tokens) {\n return {\n Authorization: `Bearer ${tokens.access_token}`,\n };\n }\n }\n }\n}\n","import { SSEEdgeClientTransport } from \"./sse-edge\";\n\nimport {\n ToolListChangedNotificationSchema,\n type ClientCapabilities,\n type Resource,\n type Tool,\n type Prompt,\n ResourceListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n type ListToolsResult,\n type ListResourcesResult,\n type ListPromptsResult,\n type ServerCapabilities,\n type ResourceTemplate,\n type ListResourceTemplatesResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\n\nexport class MCPClientConnection {\n client: Client;\n connectionState:\n | \"authenticating\"\n | \"connecting\"\n | \"ready\"\n | \"discovering\"\n | \"failed\" = \"connecting\";\n instructions?: string;\n tools: Tool[] = [];\n prompts: Prompt[] = [];\n resources: Resource[] = [];\n resourceTemplates: ResourceTemplate[] = [];\n serverCapabilities: ServerCapabilities | undefined;\n\n constructor(\n public url: URL,\n info: ConstructorParameters<typeof Client>[0],\n public options: {\n transport: SSEClientTransportOptions & {\n authProvider?: AgentsOAuthProvider;\n };\n client: ConstructorParameters<typeof Client>[1];\n capabilities: ClientCapabilities;\n } = { transport: {}, client: {}, capabilities: {} }\n ) {\n this.client = new Client(info, options.client);\n this.client.registerCapabilities(options.capabilities);\n }\n\n /**\n * Initialize a client connection\n *\n * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized\n * @returns\n */\n async init(code?: string, clientId?: string) {\n try {\n const transport = new SSEEdgeClientTransport(\n this.url,\n this.options.transport\n );\n if (code) {\n await transport.finishAuth(code);\n }\n\n await this.client.connect(transport);\n // biome-ignore lint/suspicious/noExplicitAny: allow for the error check here\n } catch (e: any) {\n if (e.toString().includes(\"Unauthorized\")) {\n // unauthorized, we should wait for the user to authenticate\n this.connectionState = \"authenticating\";\n return;\n }\n this.connectionState = \"failed\";\n throw e;\n }\n\n this.connectionState = \"discovering\";\n\n this.serverCapabilities = await this.client.getServerCapabilities();\n if (!this.serverCapabilities) {\n throw new Error(\"The MCP Server failed to return server capabilities\");\n }\n\n const [instructions, tools, resources, prompts, resourceTemplates] =\n await Promise.all([\n this.client.getInstructions(),\n this.registerTools(),\n this.registerResources(),\n this.registerPrompts(),\n this.registerResourceTemplates(),\n ]);\n\n this.instructions = instructions;\n this.tools = tools;\n this.resources = resources;\n this.prompts = prompts;\n this.resourceTemplates = resourceTemplates;\n\n this.connectionState = \"ready\";\n }\n\n /**\n * Notification handler registration\n */\n async registerTools(): Promise<Tool[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.tools) {\n return [];\n }\n\n if (this.serverCapabilities.tools.listChanged) {\n this.client.setNotificationHandler(\n ToolListChangedNotificationSchema,\n async (_notification) => {\n this.tools = await this.fetchTools();\n }\n );\n }\n\n return this.fetchTools();\n }\n\n async registerResources(): Promise<Resource[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n if (this.serverCapabilities.resources.listChanged) {\n this.client.setNotificationHandler(\n ResourceListChangedNotificationSchema,\n async (_notification) => {\n this.resources = await this.fetchResources();\n }\n );\n }\n\n return this.fetchResources();\n }\n\n async registerPrompts(): Promise<Prompt[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.prompts) {\n return [];\n }\n\n if (this.serverCapabilities.prompts.listChanged) {\n this.client.setNotificationHandler(\n PromptListChangedNotificationSchema,\n async (_notification) => {\n this.prompts = await this.fetchPrompts();\n }\n );\n }\n\n return this.fetchPrompts();\n }\n\n async registerResourceTemplates(): Promise<ResourceTemplate[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n return this.fetchResourceTemplates();\n }\n\n async fetchTools() {\n let toolsAgg: Tool[] = [];\n let toolsResult: ListToolsResult = { tools: [] };\n do {\n toolsResult = await this.client\n .listTools({\n cursor: toolsResult.nextCursor,\n })\n .catch(capabilityErrorHandler({ tools: [] }, \"tools/list\"));\n toolsAgg = toolsAgg.concat(toolsResult.tools);\n } while (toolsResult.nextCursor);\n return toolsAgg;\n }\n\n async fetchResources() {\n let resourcesAgg: Resource[] = [];\n let resourcesResult: ListResourcesResult = { resources: [] };\n do {\n resourcesResult = await this.client\n .listResources({\n cursor: resourcesResult.nextCursor,\n })\n .catch(capabilityErrorHandler({ resources: [] }, \"resources/list\"));\n resourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n } while (resourcesResult.nextCursor);\n return resourcesAgg;\n }\n\n async fetchPrompts() {\n let promptsAgg: Prompt[] = [];\n let promptsResult: ListPromptsResult = { prompts: [] };\n do {\n promptsResult = await this.client\n .listPrompts({\n cursor: promptsResult.nextCursor,\n })\n .catch(capabilityErrorHandler({ prompts: [] }, \"prompts/list\"));\n promptsAgg = promptsAgg.concat(promptsResult.prompts);\n } while (promptsResult.nextCursor);\n return promptsAgg;\n }\n\n async fetchResourceTemplates() {\n let templatesAgg: ResourceTemplate[] = [];\n let templatesResult: ListResourceTemplatesResult = {\n resourceTemplates: [],\n };\n do {\n templatesResult = await this.client\n .listResourceTemplates({\n cursor: templatesResult.nextCursor,\n })\n .catch(\n capabilityErrorHandler(\n { resourceTemplates: [] },\n \"resources/templates/list\"\n )\n );\n templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n } while (templatesResult.nextCursor);\n return templatesAgg;\n }\n}\n\nfunction capabilityErrorHandler<T>(empty: T, method: string) {\n return (e: { code: number }) => {\n // server is badly behaved and returning invalid capabilities. This commonly occurs for resource templates\n if (e.code === -32601) {\n console.error(\n `The server advertised support for the capability ${method.split(\"/\")[0]}, but returned \"Method not found\" for '${method}'.`\n );\n return empty;\n }\n throw e;\n };\n}\n","import { MCPClientConnection } from \"./client-connection\";\n\nimport type {\n ClientCapabilities,\n CallToolRequest,\n CallToolResultSchema,\n CompatibilityCallToolResultSchema,\n ReadResourceRequest,\n GetPromptRequest,\n Tool,\n Resource,\n Prompt,\n ResourceTemplate,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\nimport { jsonSchema, type ToolSet } from \"ai\";\nimport { nanoid } from \"nanoid\";\n\n/**\n * Utility class that aggregates multiple MCP clients into one\n */\nexport class MCPClientManager {\n public mcpConnections: Record<string, MCPClientConnection> = {};\n private callbackUrls: string[] = [];\n\n /**\n * @param name Name of the MCP client\n * @param version Version of the MCP Client\n * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider\n */\n constructor(\n private name: string,\n private version: string\n ) {}\n\n /**\n * Connect to and register an MCP server\n *\n * @param transportConfig Transport config\n * @param clientConfig Client config\n * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)\n */\n async connect(\n url: string,\n options: {\n // Allows you to reconnect to a server (in the case of a auth reconnect)\n // Doesn't handle session reconnection\n reconnect?: {\n id: string;\n oauthClientId?: string;\n oauthCode?: string;\n };\n // we're overriding authProvider here because we want to be able to access the auth URL\n transport?: SSEClientTransportOptions & {\n authProvider?: AgentsOAuthProvider;\n };\n client?: ConstructorParameters<typeof Client>[1];\n capabilities?: ClientCapabilities;\n } = {}\n ): Promise<{ id: string; authUrl: string | undefined }> {\n const id = options.reconnect?.id ?? nanoid(8);\n\n if (!options.transport?.authProvider) {\n console.warn(\n \"No authProvider provided in the transport options. This client will only support unauthenticated remote MCP Servers\"\n );\n } else {\n options.transport.authProvider.serverId = id;\n }\n\n this.mcpConnections[id] = new MCPClientConnection(\n new URL(url),\n {\n name: this.name,\n version: this.version,\n },\n {\n transport: options.transport ?? {},\n client: options.client ?? {},\n capabilities: options.client ?? {},\n }\n );\n\n await this.mcpConnections[id].init(\n options.reconnect?.oauthCode,\n options.reconnect?.oauthClientId\n );\n\n const authUrl = options.transport?.authProvider?.authUrl;\n if (authUrl && options.transport?.authProvider?.redirectUrl) {\n this.callbackUrls.push(\n options.transport.authProvider.redirectUrl.toString()\n );\n }\n\n return {\n id,\n authUrl,\n };\n }\n\n isCallbackRequest(req: Request): boolean {\n return (\n req.method === \"GET\" &&\n !!this.callbackUrls.find((url) => {\n return req.url.startsWith(url);\n })\n );\n }\n\n async handleCallbackRequest(req: Request) {\n const url = new URL(req.url);\n const urlMatch = this.callbackUrls.find((url) => {\n return req.url.startsWith(url);\n });\n if (!urlMatch) {\n throw new Error(\n `No callback URI match found for the request url: ${req.url}. Was the request matched with \\`isCallbackRequest()\\`?`\n );\n }\n const code = url.searchParams.get(\"code\");\n const clientId = url.searchParams.get(\"state\");\n const urlParams = urlMatch.split(\"/\");\n const serverId = urlParams[urlParams.length - 1];\n if (!code) {\n throw new Error(\"Unauthorized: no code provided\");\n }\n if (!clientId) {\n throw new Error(\"Unauthorized: no state provided\");\n }\n\n if (this.mcpConnections[serverId] === undefined) {\n throw new Error(`Could not find serverId: ${serverId}`);\n }\n\n if (this.mcpConnections[serverId].connectionState !== \"authenticating\") {\n throw new Error(\n \"Failed to authenticate: the client isn't in the `authenticating` state\"\n );\n }\n\n const conn = this.mcpConnections[serverId];\n if (!conn.options.transport.authProvider) {\n throw new Error(\n \"Trying to finalize authentication for a server connection without an authProvider\"\n );\n }\n\n conn.options.transport.authProvider.clientId = clientId;\n conn.options.transport.authProvider.serverId = serverId;\n\n // reconnect to server with authorization\n const serverUrl = conn.url.toString();\n await this.connect(serverUrl, {\n reconnect: {\n id: serverId,\n oauthClientId: clientId,\n oauthCode: code,\n },\n ...conn.options,\n });\n\n if (this.mcpConnections[serverId].connectionState === \"authenticating\") {\n throw new Error(\"Failed to authenticate: client failed to initialize\");\n }\n\n return { serverId };\n }\n\n /**\n * @returns namespaced list of tools\n */\n listTools(): NamespacedData[\"tools\"] {\n return getNamespacedData(this.mcpConnections, \"tools\");\n }\n\n /**\n * @returns a set of tools that you can use with the AI SDK\n */\n unstable_getAITools(): ToolSet {\n return Object.fromEntries(\n getNamespacedData(this.mcpConnections, \"tools\").map((tool) => {\n return [\n `${tool.serverId}_${tool.name}`,\n {\n parameters: jsonSchema(tool.inputSchema),\n description: tool.description,\n execute: async (args) => {\n const result = await this.callTool({\n name: tool.name,\n arguments: args,\n serverId: tool.serverId,\n });\n if (result.isError) {\n // @ts-expect-error TODO we should fix this\n throw new Error(result.content[0].text);\n }\n return result;\n },\n },\n ];\n })\n );\n }\n\n /**\n * Closes all connections to MCP servers\n */\n async closeAllConnections() {\n return Promise.all(\n Object.values(this.mcpConnections).map(async (connection) => {\n await connection.client.close();\n })\n );\n }\n\n /**\n * Closes a connection to an MCP server\n * @param id The id of the connection to close\n */\n async closeConnection(id: string) {\n if (!this.mcpConnections[id]) {\n throw new Error(`Connection with id \"${id}\" does not exist.`);\n }\n await this.mcpConnections[id].client.close();\n }\n\n /**\n * @returns namespaced list of prompts\n */\n listPrompts(): NamespacedData[\"prompts\"] {\n return getNamespacedData(this.mcpConnections, \"prompts\");\n }\n\n /**\n * @returns namespaced list of tools\n */\n listResources(): NamespacedData[\"resources\"] {\n return getNamespacedData(this.mcpConnections, \"resources\");\n }\n\n /**\n * @returns namespaced list of resource templates\n */\n listResourceTemplates(): NamespacedData[\"resourceTemplates\"] {\n return getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n }\n\n /**\n * Namespaced version of callTool\n */\n callTool(\n params: CallToolRequest[\"params\"] & { serverId: string },\n resultSchema?:\n | typeof CallToolResultSchema\n | typeof CompatibilityCallToolResultSchema,\n options?: RequestOptions\n ) {\n const unqualifiedName = params.name.replace(`${params.serverId}.`, \"\");\n return this.mcpConnections[params.serverId].client.callTool(\n {\n ...params,\n name: unqualifiedName,\n },\n resultSchema,\n options\n );\n }\n\n /**\n * Namespaced version of readResource\n */\n readResource(\n params: ReadResourceRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.readResource(\n params,\n options\n );\n }\n\n /**\n * Namespaced version of getPrompt\n */\n getPrompt(\n params: GetPromptRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.getPrompt(\n params,\n options\n );\n }\n}\n\ntype NamespacedData = {\n tools: (Tool & { serverId: string })[];\n prompts: (Prompt & { serverId: string })[];\n resources: (Resource & { serverId: string })[];\n resourceTemplates: (ResourceTemplate & { serverId: string })[];\n};\n\nexport function getNamespacedData<T extends keyof NamespacedData>(\n mcpClients: Record<string, MCPClientConnection>,\n type: T\n): NamespacedData[T] {\n const sets = Object.entries(mcpClients).map(([name, conn]) => {\n return { name, data: conn[type] };\n });\n\n const namespacedData = sets.flatMap(({ name: serverId, data }) => {\n return data.map((item) => {\n return {\n ...item,\n // we add a serverId so we can easily pull it out and send the tool call to the right server\n serverId,\n };\n });\n });\n\n return namespacedData as NamespacedData[T]; // Type assertion needed due to TS limitations with conditional return types\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAEK;AAGA,IAAM,yBAAN,cAAqC,mBAAmB;AAAA;AAAA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