agents 0.0.80 → 0.0.82

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"sourcesContent":["import {\n PartySocket,\n type PartySocketOptions,\n type PartyFetchOptions,\n} from \"partysocket\";\nimport type { RPCRequest, RPCResponse } from \"./\";\n\n/**\n * Options for creating an AgentClient\n */\nexport type AgentClientOptions<State = unknown> = Omit<\n PartySocketOptions,\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n /** Called when the Agent's state is updated */\n onStateUpdate?: (state: State, source: \"server\" | \"client\") => void;\n};\n\n/**\n * Options for streaming RPC calls\n */\nexport type StreamOptions = {\n /** Called when a chunk of data is received */\n onChunk?: (chunk: unknown) => void;\n /** Called when the stream ends */\n onDone?: (finalChunk: unknown) => void;\n /** Called when an error occurs */\n onError?: (error: string) => void;\n};\n\n/**\n * Options for the agentFetch function\n */\nexport type AgentClientFetchOptions = Omit<\n PartyFetchOptions,\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n};\n\n/**\n * Convert a camelCase string to a kebab-case string\n * @param str The string to convert\n * @returns The kebab-case string\n */\nexport function camelCaseToKebabCase(str: string): string {\n // If string is all uppercase, convert to lowercase\n if (str === str.toUpperCase() && str !== str.toLowerCase()) {\n return str.toLowerCase().replace(/_/g, \"-\");\n }\n\n // Otherwise handle camelCase to kebab-case\n let kebabified = str.replace(\n /[A-Z]/g,\n (letter) => `-${letter.toLowerCase()}`\n );\n kebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n // Convert any remaining underscores to hyphens and remove trailing -'s\n return kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n\n/**\n * WebSocket client for connecting to an Agent\n */\nexport class AgentClient<State = unknown> extends PartySocket {\n /**\n * @deprecated Use agentFetch instead\n */\n static fetch(_opts: PartyFetchOptions): Promise<Response> {\n throw new Error(\n \"AgentClient.fetch is not implemented, use agentFetch instead\"\n );\n }\n agent: string;\n name: string;\n private options: AgentClientOptions<State>;\n private _pendingCalls = new Map<\n string,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n stream?: StreamOptions;\n type?: unknown;\n }\n >();\n\n constructor(options: AgentClientOptions<State>) {\n const agentNamespace = camelCaseToKebabCase(options.agent);\n super({\n prefix: \"agents\",\n party: agentNamespace,\n room: options.name || \"default\",\n ...options,\n });\n this.agent = agentNamespace;\n this.name = options.name || \"default\";\n this.options = options;\n\n this.addEventListener(\"message\", (event) => {\n if (typeof event.data === \"string\") {\n let parsedMessage: Record<string, unknown>;\n try {\n parsedMessage = JSON.parse(event.data);\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (parsedMessage.type === \"cf_agent_state\") {\n this.options.onStateUpdate?.(parsedMessage.state as State, \"server\");\n return;\n }\n if (parsedMessage.type === \"rpc\") {\n const response = parsedMessage as RPCResponse;\n const pending = this._pendingCalls.get(response.id);\n if (!pending) return;\n\n if (!response.success) {\n pending.reject(new Error(response.error));\n this._pendingCalls.delete(response.id);\n pending.stream?.onError?.(response.error);\n return;\n }\n\n // Handle streaming responses\n if (\"done\" in response) {\n if (response.done) {\n pending.resolve(response.result);\n this._pendingCalls.delete(response.id);\n pending.stream?.onDone?.(response.result);\n } else {\n pending.stream?.onChunk?.(response.result);\n }\n } else {\n // Non-streaming response\n pending.resolve(response.result);\n this._pendingCalls.delete(response.id);\n }\n }\n }\n });\n }\n\n setState(state: State) {\n this.send(JSON.stringify({ type: \"cf_agent_state\", state }));\n this.options.onStateUpdate?.(state, \"client\");\n }\n\n /**\n * Call a method on the Agent\n * @param method Name of the method to call\n * @param args Arguments to pass to the method\n * @param streamOptions Options for handling streaming responses\n * @returns Promise that resolves with the method's return value\n */\n async call<T = unknown>(\n method: string,\n args: unknown[] = [],\n streamOptions?: StreamOptions\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const id = Math.random().toString(36).slice(2);\n this._pendingCalls.set(id, {\n resolve: (value: unknown) => resolve(value as T),\n reject,\n stream: streamOptions,\n type: null as T,\n });\n\n const request: RPCRequest = {\n type: \"rpc\",\n id,\n method,\n args,\n };\n\n this.send(JSON.stringify(request));\n });\n }\n}\n\n/**\n * Make an HTTP request to an Agent\n * @param opts Connection options\n * @param init Request initialization options\n * @returns Promise resolving to a Response\n */\nexport function agentFetch(opts: AgentClientFetchOptions, init?: RequestInit) {\n const agentNamespace = camelCaseToKebabCase(opts.agent);\n\n return PartySocket.fetch(\n {\n prefix: \"agents\",\n party: agentNamespace,\n room: opts.name || \"default\",\n ...opts,\n },\n init\n );\n}\n"],"mappings":"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","names":[]}
@@ -1,18 +1,12 @@
1
1
  import {
2
2
  DurableObjectOAuthClientProvider
3
- } from "./chunk-D6UOOELW.js";
3
+ } from "./chunk-BZXOAZUX.js";
4
4
  import {
5
5
  camelCaseToKebabCase
6
- } from "./chunk-RN4SNE73.js";
6
+ } from "./chunk-QSGN3REV.js";
7
7
  import {
8
8
  MCPClientManager
9
- } from "./chunk-25YDMV4H.js";
10
- import {
11
- __privateAdd,
12
- __privateGet,
13
- __privateMethod,
14
- __privateSet
15
- } from "./chunk-HMLY7DHA.js";
9
+ } from "./chunk-Y67CHZBI.js";
16
10
 
17
11
  // src/index.ts
18
12
  import {
@@ -57,14 +51,12 @@ function getCurrentAgent() {
57
51
  }
58
52
  return store;
59
53
  }
60
- var _state, _ParentClass, _Agent_instances, setStateInternal_fn, tryCatch_fn, scheduleNextAlarm_fn, isCallable_fn, connectToMcpServerInternal_fn, getMcpServerStateInternal_fn;
61
54
  var Agent = class extends Server {
62
55
  constructor(ctx, env) {
63
56
  super(ctx, env);
64
- __privateAdd(this, _Agent_instances);
65
- __privateAdd(this, _state, DEFAULT_STATE);
66
- __privateAdd(this, _ParentClass, Object.getPrototypeOf(this).constructor);
67
- this.mcp = new MCPClientManager(__privateGet(this, _ParentClass).name, "0.0.1");
57
+ this._state = DEFAULT_STATE;
58
+ this._ParentClass = Object.getPrototypeOf(this).constructor;
59
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
68
60
  /**
69
61
  * Initial state for the Agent
70
62
  * Override to provide default state values
@@ -111,7 +103,7 @@ var Agent = class extends Server {
111
103
  `;
112
104
  }
113
105
  }
114
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
106
+ await this._scheduleNextAlarm();
115
107
  };
116
108
  this.sql`
117
109
  CREATE TABLE IF NOT EXISTS cf_agents_state (
@@ -120,7 +112,7 @@ var Agent = class extends Server {
120
112
  )
121
113
  `;
122
114
  void this.ctx.blockConcurrencyWhile(async () => {
123
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, async () => {
115
+ return this._tryCatch(async () => {
124
116
  this.sql`
125
117
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
126
118
  id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
@@ -157,7 +149,7 @@ var Agent = class extends Server {
157
149
  this.broadcast(
158
150
  JSON.stringify({
159
151
  type: "cf_agent_mcp_servers",
160
- mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
152
+ mcp: this._getMcpServerStateInternal()
161
153
  })
162
154
  );
163
155
  return new Response("<script>window.close();</script>", {
@@ -165,7 +157,7 @@ var Agent = class extends Server {
165
157
  headers: { "content-type": "text/html" }
166
158
  });
167
159
  }
168
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onRequest(request));
160
+ return this._tryCatch(() => _onRequest(request));
169
161
  }
170
162
  );
171
163
  };
@@ -175,16 +167,16 @@ var Agent = class extends Server {
175
167
  { agent: this, connection, request: void 0 },
176
168
  async () => {
177
169
  if (typeof message !== "string") {
178
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
170
+ return this._tryCatch(() => _onMessage(connection, message));
179
171
  }
180
172
  let parsed;
181
173
  try {
182
174
  parsed = JSON.parse(message);
183
175
  } catch (e) {
184
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
176
+ return this._tryCatch(() => _onMessage(connection, message));
185
177
  }
186
178
  if (isStateUpdateMessage(parsed)) {
187
- __privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, parsed.state, connection);
179
+ this._setStateInternal(parsed.state, connection);
188
180
  return;
189
181
  }
190
182
  if (isRPCRequest(parsed)) {
@@ -194,7 +186,7 @@ var Agent = class extends Server {
194
186
  if (typeof methodFn !== "function") {
195
187
  throw new Error(`Method ${method} does not exist`);
196
188
  }
197
- if (!__privateMethod(this, _Agent_instances, isCallable_fn).call(this, method)) {
189
+ if (!this._isCallable(method)) {
198
190
  throw new Error(`Method ${method} is not callable`);
199
191
  }
200
192
  const metadata = callableMetadata.get(methodFn);
@@ -224,7 +216,7 @@ var Agent = class extends Server {
224
216
  }
225
217
  return;
226
218
  }
227
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
219
+ return this._tryCatch(() => _onMessage(connection, message));
228
220
  }
229
221
  );
230
222
  };
@@ -245,10 +237,10 @@ var Agent = class extends Server {
245
237
  connection.send(
246
238
  JSON.stringify({
247
239
  type: "cf_agent_mcp_servers",
248
- mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
240
+ mcp: this._getMcpServerStateInternal()
249
241
  })
250
242
  );
251
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onConnect(connection, ctx2));
243
+ return this._tryCatch(() => _onConnect(connection, ctx2));
252
244
  }, 20);
253
245
  }
254
246
  );
@@ -263,19 +255,25 @@ var Agent = class extends Server {
263
255
  `;
264
256
  await Promise.allSettled(
265
257
  servers.map((server) => {
266
- return __privateMethod(this, _Agent_instances, connectToMcpServerInternal_fn).call(this, server.name, server.server_url, server.callback_url, server.server_options ? JSON.parse(server.server_options) : void 0, {
267
- id: server.id,
268
- oauthClientId: server.client_id ?? void 0
269
- });
258
+ return this._connectToMcpServerInternal(
259
+ server.name,
260
+ server.server_url,
261
+ server.callback_url,
262
+ server.server_options ? JSON.parse(server.server_options) : void 0,
263
+ {
264
+ id: server.id,
265
+ oauthClientId: server.client_id ?? void 0
266
+ }
267
+ );
270
268
  })
271
269
  );
272
270
  this.broadcast(
273
271
  JSON.stringify({
274
272
  type: "cf_agent_mcp_servers",
275
- mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
273
+ mcp: this._getMcpServerStateInternal()
276
274
  })
277
275
  );
278
- await __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onStart());
276
+ await this._tryCatch(() => _onStart());
279
277
  }
280
278
  );
281
279
  };
@@ -284,8 +282,8 @@ var Agent = class extends Server {
284
282
  * Current state of the Agent
285
283
  */
286
284
  get state() {
287
- if (__privateGet(this, _state) !== DEFAULT_STATE) {
288
- return __privateGet(this, _state);
285
+ if (this._state !== DEFAULT_STATE) {
286
+ return this._state;
289
287
  }
290
288
  const wasChanged = this.sql`
291
289
  SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
@@ -296,8 +294,8 @@ var Agent = class extends Server {
296
294
  if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
297
295
  result[0]?.state) {
298
296
  const state = result[0]?.state;
299
- __privateSet(this, _state, JSON.parse(state));
300
- return __privateGet(this, _state);
297
+ this._state = JSON.parse(state);
298
+ return this._state;
301
299
  }
302
300
  if (this.initialState === DEFAULT_STATE) {
303
301
  return void 0;
@@ -325,12 +323,39 @@ var Agent = class extends Server {
325
323
  throw this.onError(e);
326
324
  }
327
325
  }
326
+ _setStateInternal(state, source = "server") {
327
+ this._state = state;
328
+ this.sql`
329
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
330
+ VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
331
+ `;
332
+ this.sql`
333
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
334
+ VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
335
+ `;
336
+ this.broadcast(
337
+ JSON.stringify({
338
+ type: "cf_agent_state",
339
+ state
340
+ }),
341
+ source !== "server" ? [source.id] : []
342
+ );
343
+ return this._tryCatch(() => {
344
+ const { connection, request } = agentContext.getStore() || {};
345
+ return agentContext.run(
346
+ { agent: this, connection, request },
347
+ async () => {
348
+ return this.onStateUpdate(state, source);
349
+ }
350
+ );
351
+ });
352
+ }
328
353
  /**
329
354
  * Update the Agent's state
330
355
  * @param state New state to set
331
356
  */
332
357
  setState(state) {
333
- __privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, state, "server");
358
+ this._setStateInternal(state, "server");
334
359
  }
335
360
  /**
336
361
  * Called when the Agent's state is updated
@@ -351,6 +376,13 @@ var Agent = class extends Server {
351
376
  }
352
377
  );
353
378
  }
379
+ async _tryCatch(fn) {
380
+ try {
381
+ return await fn();
382
+ } catch (e) {
383
+ throw this.onError(e);
384
+ }
385
+ }
354
386
  onError(connectionOrError, error) {
355
387
  let theError;
356
388
  if (connectionOrError && error) {
@@ -400,7 +432,7 @@ var Agent = class extends Server {
400
432
  payload
401
433
  )}, 'scheduled', ${timestamp})
402
434
  `;
403
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
435
+ await this._scheduleNextAlarm();
404
436
  return {
405
437
  id,
406
438
  callback,
@@ -418,7 +450,7 @@ var Agent = class extends Server {
418
450
  payload
419
451
  )}, 'delayed', ${when}, ${timestamp})
420
452
  `;
421
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
453
+ await this._scheduleNextAlarm();
422
454
  return {
423
455
  id,
424
456
  callback,
@@ -437,7 +469,7 @@ var Agent = class extends Server {
437
469
  payload
438
470
  )}, 'cron', ${when}, ${timestamp})
439
471
  `;
440
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
472
+ await this._scheduleNextAlarm();
441
473
  return {
442
474
  id,
443
475
  callback,
@@ -504,9 +536,22 @@ var Agent = class extends Server {
504
536
  */
505
537
  async cancelSchedule(id) {
506
538
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
507
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
539
+ await this._scheduleNextAlarm();
508
540
  return true;
509
541
  }
542
+ async _scheduleNextAlarm() {
543
+ const result = this.sql`
544
+ SELECT time FROM cf_agents_schedules
545
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
546
+ ORDER BY time ASC
547
+ LIMIT 1
548
+ `;
549
+ if (!result) return;
550
+ if (result.length > 0 && "time" in result[0]) {
551
+ const nextTime = result[0].time * 1e3;
552
+ await this.ctx.storage.setAlarm(nextTime);
553
+ }
554
+ }
510
555
  /**
511
556
  * Destroy the Agent, removing all state and scheduled tasks
512
557
  */
@@ -517,6 +562,9 @@ var Agent = class extends Server {
517
562
  await this.ctx.storage.deleteAlarm();
518
563
  await this.ctx.storage.deleteAll();
519
564
  }
565
+ _isCallable(method) {
566
+ return callableMetadata.has(this[method]);
567
+ }
520
568
  /**
521
569
  * Connect to a new MCP Server
522
570
  *
@@ -527,121 +575,56 @@ var Agent = class extends Server {
527
575
  * @returns authUrl
528
576
  */
529
577
  async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
530
- const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(__privateGet(this, _ParentClass).name)}/${this.name}/callback`;
531
- const result = await __privateMethod(this, _Agent_instances, connectToMcpServerInternal_fn).call(this, serverName, url, callbackUrl, options);
578
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
579
+ const result = await this._connectToMcpServerInternal(
580
+ serverName,
581
+ url,
582
+ callbackUrl,
583
+ options
584
+ );
532
585
  this.broadcast(
533
586
  JSON.stringify({
534
587
  type: "cf_agent_mcp_servers",
535
- mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
588
+ mcp: this._getMcpServerStateInternal()
536
589
  })
537
590
  );
538
591
  return result;
539
592
  }
540
- async removeMcpServer(id) {
541
- this.mcp.closeConnection(id);
542
- this.sql`
543
- DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
544
- `;
545
- this.broadcast(
546
- JSON.stringify({
547
- type: "cf_agent_mcp_servers",
548
- mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
549
- })
593
+ async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
594
+ const authProvider = new DurableObjectOAuthClientProvider(
595
+ this.ctx.storage,
596
+ this.name,
597
+ callbackUrl
550
598
  );
551
- }
552
- };
553
- _state = new WeakMap();
554
- _ParentClass = new WeakMap();
555
- _Agent_instances = new WeakSet();
556
- setStateInternal_fn = function(state, source = "server") {
557
- __privateSet(this, _state, state);
558
- this.sql`
559
- INSERT OR REPLACE INTO cf_agents_state (id, state)
560
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
561
- `;
562
- this.sql`
563
- INSERT OR REPLACE INTO cf_agents_state (id, state)
564
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
565
- `;
566
- this.broadcast(
567
- JSON.stringify({
568
- type: "cf_agent_state",
569
- state
570
- }),
571
- source !== "server" ? [source.id] : []
572
- );
573
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => {
574
- const { connection, request } = agentContext.getStore() || {};
575
- return agentContext.run(
576
- { agent: this, connection, request },
577
- async () => {
578
- return this.onStateUpdate(state, source);
599
+ if (reconnect) {
600
+ authProvider.serverId = reconnect.id;
601
+ if (reconnect.oauthClientId) {
602
+ authProvider.clientId = reconnect.oauthClientId;
579
603
  }
580
- );
581
- });
582
- };
583
- tryCatch_fn = async function(fn) {
584
- try {
585
- return await fn();
586
- } catch (e) {
587
- throw this.onError(e);
588
- }
589
- };
590
- scheduleNextAlarm_fn = async function() {
591
- const result = this.sql`
592
- SELECT time FROM cf_agents_schedules
593
- WHERE time > ${Math.floor(Date.now() / 1e3)}
594
- ORDER BY time ASC
595
- LIMIT 1
596
- `;
597
- if (!result) return;
598
- if (result.length > 0 && "time" in result[0]) {
599
- const nextTime = result[0].time * 1e3;
600
- await this.ctx.storage.setAlarm(nextTime);
601
- }
602
- };
603
- /**
604
- * Get all methods marked as callable on this Agent
605
- * @returns A map of method names to their metadata
606
- */
607
- isCallable_fn = function(method) {
608
- return callableMetadata.has(this[method]);
609
- };
610
- connectToMcpServerInternal_fn = async function(serverName, url, callbackUrl, options, reconnect) {
611
- const authProvider = new DurableObjectOAuthClientProvider(
612
- this.ctx.storage,
613
- this.name,
614
- callbackUrl
615
- );
616
- if (reconnect) {
617
- authProvider.serverId = reconnect.id;
618
- if (reconnect.oauthClientId) {
619
- authProvider.clientId = reconnect.oauthClientId;
620
604
  }
621
- }
622
- let headerTransportOpts = {};
623
- if (options?.transport?.headers) {
624
- headerTransportOpts = {
625
- eventSourceInit: {
626
- fetch: (url2, init) => fetch(url2, {
627
- ...init,
605
+ let headerTransportOpts = {};
606
+ if (options?.transport?.headers) {
607
+ headerTransportOpts = {
608
+ eventSourceInit: {
609
+ fetch: (url2, init) => fetch(url2, {
610
+ ...init,
611
+ headers: options?.transport?.headers
612
+ })
613
+ },
614
+ requestInit: {
628
615
  headers: options?.transport?.headers
629
- })
616
+ }
617
+ };
618
+ }
619
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
620
+ reconnect,
621
+ transport: {
622
+ ...headerTransportOpts,
623
+ authProvider
630
624
  },
631
- requestInit: {
632
- headers: options?.transport?.headers
633
- }
634
- };
635
- }
636
- const { id, authUrl, clientId } = await this.mcp.connect(url, {
637
- reconnect,
638
- transport: {
639
- ...headerTransportOpts,
640
- authProvider
641
- },
642
- client: options?.client
643
- });
644
- this.sql`
625
+ client: options?.client
626
+ });
627
+ this.sql`
645
628
  INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
646
629
  VALUES (
647
630
  ${id},
@@ -653,30 +636,43 @@ connectToMcpServerInternal_fn = async function(serverName, url, callbackUrl, opt
653
636
  ${options ? JSON.stringify(options) : null}
654
637
  );
655
638
  `;
656
- return {
657
- id,
658
- authUrl
659
- };
660
- };
661
- getMcpServerStateInternal_fn = function() {
662
- const mcpState = {
663
- servers: {},
664
- tools: this.mcp.listTools(),
665
- prompts: this.mcp.listPrompts(),
666
- resources: this.mcp.listResources()
667
- };
668
- const servers = this.sql`
669
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
639
+ return {
640
+ id,
641
+ authUrl
642
+ };
643
+ }
644
+ async removeMcpServer(id) {
645
+ this.mcp.closeConnection(id);
646
+ this.sql`
647
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
670
648
  `;
671
- for (const server of servers) {
672
- mcpState.servers[server.id] = {
673
- name: server.name,
674
- server_url: server.server_url,
675
- auth_url: server.auth_url,
676
- state: this.mcp.mcpConnections[server.id].connectionState
649
+ this.broadcast(
650
+ JSON.stringify({
651
+ type: "cf_agent_mcp_servers",
652
+ mcp: this._getMcpServerStateInternal()
653
+ })
654
+ );
655
+ }
656
+ _getMcpServerStateInternal() {
657
+ const mcpState = {
658
+ servers: {},
659
+ tools: this.mcp.listTools(),
660
+ prompts: this.mcp.listPrompts(),
661
+ resources: this.mcp.listResources()
677
662
  };
663
+ const servers = this.sql`
664
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
665
+ `;
666
+ for (const server of servers) {
667
+ mcpState.servers[server.id] = {
668
+ name: server.name,
669
+ server_url: server.server_url,
670
+ auth_url: server.auth_url,
671
+ state: this.mcp.mcpConnections[server.id].connectionState
672
+ };
673
+ }
674
+ return mcpState;
678
675
  }
679
- return mcpState;
680
676
  };
681
677
  /**
682
678
  * Agent configuration options
@@ -726,54 +722,48 @@ async function routeAgentEmail(email, env, options) {
726
722
  async function getAgentByName(namespace, name, options) {
727
723
  return getServerByName(namespace, name, options);
728
724
  }
729
- var _connection, _id, _closed;
730
725
  var StreamingResponse = class {
731
726
  constructor(connection, id) {
732
- __privateAdd(this, _connection);
733
- __privateAdd(this, _id);
734
- __privateAdd(this, _closed, false);
735
- __privateSet(this, _connection, connection);
736
- __privateSet(this, _id, id);
727
+ this._closed = false;
728
+ this._connection = connection;
729
+ this._id = id;
737
730
  }
738
731
  /**
739
732
  * Send a chunk of data to the client
740
733
  * @param chunk The data to send
741
734
  */
742
735
  send(chunk) {
743
- if (__privateGet(this, _closed)) {
736
+ if (this._closed) {
744
737
  throw new Error("StreamingResponse is already closed");
745
738
  }
746
739
  const response = {
747
740
  type: "rpc",
748
- id: __privateGet(this, _id),
741
+ id: this._id,
749
742
  success: true,
750
743
  result: chunk,
751
744
  done: false
752
745
  };
753
- __privateGet(this, _connection).send(JSON.stringify(response));
746
+ this._connection.send(JSON.stringify(response));
754
747
  }
755
748
  /**
756
749
  * End the stream and send the final chunk (if any)
757
750
  * @param finalChunk Optional final chunk of data to send
758
751
  */
759
752
  end(finalChunk) {
760
- if (__privateGet(this, _closed)) {
753
+ if (this._closed) {
761
754
  throw new Error("StreamingResponse is already closed");
762
755
  }
763
- __privateSet(this, _closed, true);
756
+ this._closed = true;
764
757
  const response = {
765
758
  type: "rpc",
766
- id: __privateGet(this, _id),
759
+ id: this._id,
767
760
  success: true,
768
761
  result: finalChunk,
769
762
  done: true
770
763
  };
771
- __privateGet(this, _connection).send(JSON.stringify(response));
764
+ this._connection.send(JSON.stringify(response));
772
765
  }
773
766
  };
774
- _connection = new WeakMap();
775
- _id = new WeakMap();
776
- _closed = new WeakMap();
777
767
 
778
768
  export {
779
769
  unstable_callable,
@@ -784,4 +774,4 @@ export {
784
774
  getAgentByName,
785
775
  StreamingResponse
786
776
  };
787
- //# sourceMappingURL=chunk-YFPCCSZO.js.map
777
+ //# sourceMappingURL=chunk-RIYR6FR6.js.map