agents 0.0.0-c18c28a → 0.0.0-c4c9271

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 +13 -0
  5. package/dist/ai-react.js +1 -2
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/{chunk-HD4VEHBA.js → chunk-6RPGDIE2.js} +312 -134
  8. package/dist/chunk-6RPGDIE2.js.map +1 -0
  9. package/dist/chunk-BZXOAZUX.js +106 -0
  10. package/dist/chunk-BZXOAZUX.js.map +1 -0
  11. package/dist/{chunk-Q5ZBHY4Z.js → chunk-OYJXQRRH.js} +33 -24
  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 +104 -7
  19. package/dist/index.js +4 -3
  20. package/dist/mcp/client.d.ts +21 -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 +11 -1
  26. package/dist/mcp/index.js +109 -137
  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 +9 -7
  36. package/src/index.ts +361 -48
  37. package/dist/chunk-HD4VEHBA.js.map +0 -1
  38. package/dist/chunk-HMLY7DHA.js +0 -16
  39. package/dist/chunk-Q5ZBHY4Z.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,13 +375,53 @@ 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
+
390
+ const _onRequest = this.onRequest.bind(this);
391
+ this.onRequest = (request: Request) => {
392
+ return agentContext.run(
393
+ { agent: this, connection: undefined, request },
394
+ async () => {
395
+ if (this.mcp.isCallbackRequest(request)) {
396
+ await this.mcp.handleCallbackRequest(request);
397
+
398
+ // after the MCP connection handshake, we can send updated mcp state
399
+ this.broadcast(
400
+ JSON.stringify({
401
+ type: "cf_agent_mcp_servers",
402
+ mcp: this.getMcpServers(),
403
+ })
404
+ );
405
+
406
+ // We probably should let the user configure this response/redirect, but this is fine for now.
407
+ return new Response("<script>window.close();</script>", {
408
+ status: 200,
409
+ headers: { "content-type": "text/html" },
410
+ });
411
+ }
412
+
413
+ return this._tryCatch(() => _onRequest(request));
414
+ }
415
+ );
416
+ };
417
+
324
418
  const _onMessage = this.onMessage.bind(this);
325
419
  this.onMessage = async (connection: Connection, message: WSMessage) => {
326
420
  return agentContext.run(
327
421
  { agent: this, connection, request: undefined },
328
422
  async () => {
329
423
  if (typeof message !== "string") {
330
- return this.#tryCatch(() => _onMessage(connection, message));
424
+ return this._tryCatch(() => _onMessage(connection, message));
331
425
  }
332
426
 
333
427
  let parsed: unknown;
@@ -335,11 +429,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
335
429
  parsed = JSON.parse(message);
336
430
  } catch (e) {
337
431
  // silently fail and let the onMessage handler handle it
338
- return this.#tryCatch(() => _onMessage(connection, message));
432
+ return this._tryCatch(() => _onMessage(connection, message));
339
433
  }
340
434
 
341
435
  if (isStateUpdateMessage(parsed)) {
342
- this.#setStateInternal(parsed.state as State, connection);
436
+ this._setStateInternal(parsed.state as State, connection);
343
437
  return;
344
438
  }
345
439
 
@@ -353,11 +447,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
353
447
  throw new Error(`Method ${method} does not exist`);
354
448
  }
355
449
 
356
- if (!this.#isCallable(method)) {
450
+ if (!this._isCallable(method)) {
357
451
  throw new Error(`Method ${method} is not callable`);
358
452
  }
359
453
 
360
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
361
454
  const metadata = callableMetadata.get(methodFn as Function);
362
455
 
363
456
  // For streaming methods, pass a StreamingResponse object
@@ -392,7 +485,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
392
485
  return;
393
486
  }
394
487
 
395
- return this.#tryCatch(() => _onMessage(connection, message));
488
+ return this._tryCatch(() => _onMessage(connection, message));
396
489
  }
397
490
  );
398
491
  };
@@ -413,15 +506,67 @@ export class Agent<Env, State = unknown> extends Server<Env> {
413
506
  })
414
507
  );
415
508
  }
416
- 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));
417
518
  }, 20);
418
519
  }
419
520
  );
420
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
+ };
421
563
  }
422
564
 
423
- #setStateInternal(state: State, source: Connection | "server" = "server") {
424
- this.#state = state;
565
+ private _setStateInternal(
566
+ state: State,
567
+ source: Connection | "server" = "server"
568
+ ) {
569
+ this._state = state;
425
570
  this.sql`
426
571
  INSERT OR REPLACE INTO cf_agents_state (id, state)
427
572
  VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
@@ -437,7 +582,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
437
582
  }),
438
583
  source !== "server" ? [source.id] : []
439
584
  );
440
- return this.#tryCatch(() => {
585
+ return this._tryCatch(() => {
441
586
  const { connection, request } = agentContext.getStore() || {};
442
587
  return agentContext.run(
443
588
  { agent: this, connection, request },
@@ -453,7 +598,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
453
598
  * @param state New state to set
454
599
  */
455
600
  setState(state: State) {
456
- this.#setStateInternal(state, "server");
601
+ this._setStateInternal(state, "server");
457
602
  }
458
603
 
459
604
  /**
@@ -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,7 +697,7 @@ 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
703
  id,
@@ -573,7 +718,7 @@ 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
724
  id,
@@ -595,7 +740,7 @@ 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
746
  id,
@@ -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
+ type: "cf_agent_mcp_servers",
963
+ mcp: this.getMcpServers(),
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
+ reconnect,
1026
+ transport: {
1027
+ ...headerTransportOpts,
1028
+ authProvider,
1029
+ },
1030
+ client: options?.client,
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
+ id,
1048
+ authUrl,
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
+ type: "cf_agent_mcp_servers",
1060
+ mcp: this.getMcpServers(),
1061
+ })
1062
+ );
1063
+ }
1064
+
1065
+ getMcpServers(): MCPServersState {
1066
+ const mcpState: MCPServersState = {
1067
+ servers: {},
1068
+ tools: this.mcp.listTools(),
1069
+ prompts: this.mcp.listPrompts(),
1070
+ resources: this.mcp.listResources(),
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
+ name: server.name,
1081
+ server_url: server.server_url,
1082
+ auth_url: server.auth_url,
1083
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
1084
+ state: serverConn?.connectionState ?? "authenticating",
1085
+ instructions: serverConn?.instructions ?? null,
1086
+ capabilities: serverConn?.serverCapabilities ?? null,
1087
+ };
1088
+ }
1089
+
1090
+ return mcpState;
1091
+ }
779
1092
  }
780
1093
 
781
1094
  /**
@@ -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
1228
  type: "rpc",
916
- id: this.#id,
1229
+ id: this._id,
917
1230
  success: true,
918
1231
  result: chunk,
919
1232
  done: false,
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
1247
  type: "rpc",
935
- id: this.#id,
1248
+ id: this._id,
936
1249
  success: true,
937
1250
  result: finalChunk,
938
1251
  done: true,
939
1252
  };
940
- this.#connection.send(JSON.stringify(response));
1253
+ this._connection.send(JSON.stringify(response));
941
1254
  }
942
1255
  }