agents 0.0.0-0cd2489 → 0.0.0-1232c19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/ai-chat-agent.d.ts +31 -5
  2. package/dist/ai-chat-agent.js +119 -115
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-react.d.ts +17 -4
  5. package/dist/ai-react.js +27 -29
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/chunk-767EASBA.js +106 -0
  8. package/dist/chunk-767EASBA.js.map +1 -0
  9. package/dist/{chunk-Q5ZBHY4Z.js → chunk-E3LCYPCB.js} +49 -36
  10. package/dist/chunk-E3LCYPCB.js.map +1 -0
  11. package/dist/chunk-NKZZ66QY.js +116 -0
  12. package/dist/chunk-NKZZ66QY.js.map +1 -0
  13. package/dist/{chunk-5W7ZWKOP.js → chunk-ZRRXJUAA.js} +330 -159
  14. package/dist/chunk-ZRRXJUAA.js.map +1 -0
  15. package/dist/client.d.ts +15 -1
  16. package/dist/client.js +6 -126
  17. package/dist/client.js.map +1 -1
  18. package/dist/index.d.ts +109 -12
  19. package/dist/index.js +4 -3
  20. package/dist/mcp/client.d.ts +22 -16
  21. package/dist/mcp/client.js +1 -2
  22. package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
  23. package/dist/mcp/do-oauth-client-provider.js +3 -103
  24. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  25. package/dist/mcp/index.d.ts +17 -7
  26. package/dist/mcp/index.js +146 -173
  27. package/dist/mcp/index.js.map +1 -1
  28. package/dist/react.d.ts +85 -5
  29. package/dist/react.js +20 -8
  30. package/dist/react.js.map +1 -1
  31. package/dist/schedule.d.ts +2 -2
  32. package/dist/schedule.js +4 -6
  33. package/dist/schedule.js.map +1 -1
  34. package/dist/serializable.d.ts +32 -0
  35. package/dist/serializable.js +1 -0
  36. package/package.json +71 -69
  37. package/src/index.ts +384 -81
  38. package/dist/chunk-5W7ZWKOP.js.map +0 -1
  39. package/dist/chunk-HMLY7DHA.js +0 -16
  40. package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
  41. /package/dist/{chunk-HMLY7DHA.js.map → serializable.js.map} +0 -0
@@ -1,22 +1,22 @@
1
1
  import {
2
2
  MCPClientManager
3
- } from "./chunk-Q5ZBHY4Z.js";
3
+ } from "./chunk-E3LCYPCB.js";
4
4
  import {
5
- __privateAdd,
6
- __privateGet,
7
- __privateMethod,
8
- __privateSet
9
- } from "./chunk-HMLY7DHA.js";
5
+ DurableObjectOAuthClientProvider
6
+ } from "./chunk-767EASBA.js";
7
+ import {
8
+ camelCaseToKebabCase
9
+ } from "./chunk-NKZZ66QY.js";
10
10
 
11
11
  // src/index.ts
12
+ import { AsyncLocalStorage } from "async_hooks";
13
+ import { parseCronExpression } from "cron-schedule";
14
+ import { nanoid } from "nanoid";
12
15
  import {
13
- Server,
16
+ getServerByName,
14
17
  routePartykitRequest,
15
- getServerByName
18
+ Server
16
19
  } from "partyserver";
17
- import { parseCronExpression } from "cron-schedule";
18
- import { nanoid } from "nanoid";
19
- import { AsyncLocalStorage } from "node:async_hooks";
20
20
  function isRPCRequest(msg) {
21
21
  return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "rpc" && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
22
22
  }
@@ -51,19 +51,60 @@ function getCurrentAgent() {
51
51
  }
52
52
  return store;
53
53
  }
54
- var _state, _ParentClass, _Agent_instances, setStateInternal_fn, tryCatch_fn, scheduleNextAlarm_fn, isCallable_fn;
55
54
  var Agent = class extends Server {
56
55
  constructor(ctx, env) {
57
56
  super(ctx, env);
58
- __privateAdd(this, _Agent_instances);
59
- __privateAdd(this, _state, DEFAULT_STATE);
60
- __privateAdd(this, _ParentClass, Object.getPrototypeOf(this).constructor);
61
- 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");
62
60
  /**
63
61
  * Initial state for the Agent
64
62
  * Override to provide default state values
65
63
  */
66
64
  this.initialState = DEFAULT_STATE;
65
+ /**
66
+ * Method called when an alarm fires.
67
+ * Executes any scheduled tasks that are due.
68
+ *
69
+ * @remarks
70
+ * To schedule a task, please use the `this.schedule` method instead.
71
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
72
+ */
73
+ this.alarm = async () => {
74
+ const now = Math.floor(Date.now() / 1e3);
75
+ const result = this.sql`
76
+ SELECT * FROM cf_agents_schedules WHERE time <= ${now}
77
+ `;
78
+ for (const row of result || []) {
79
+ const callback = this[row.callback];
80
+ if (!callback) {
81
+ console.error(`callback ${row.callback} not found`);
82
+ continue;
83
+ }
84
+ await agentContext.run(
85
+ { agent: this, connection: void 0, request: void 0 },
86
+ async () => {
87
+ try {
88
+ await callback.bind(this)(JSON.parse(row.payload), row);
89
+ } catch (e) {
90
+ console.error(`error executing callback "${row.callback}"`, e);
91
+ }
92
+ }
93
+ );
94
+ if (row.type === "cron") {
95
+ const nextExecutionTime = getNextCronTime(row.cron);
96
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
97
+ this.sql`
98
+ UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
99
+ `;
100
+ } else {
101
+ this.sql`
102
+ DELETE FROM cf_agents_schedules WHERE id = ${row.id}
103
+ `;
104
+ }
105
+ }
106
+ await this._scheduleNextAlarm();
107
+ };
67
108
  this.sql`
68
109
  CREATE TABLE IF NOT EXISTS cf_agents_state (
69
110
  id TEXT PRIMARY KEY NOT NULL,
@@ -71,7 +112,7 @@ var Agent = class extends Server {
71
112
  )
72
113
  `;
73
114
  void this.ctx.blockConcurrencyWhile(async () => {
74
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, async () => {
115
+ return this._tryCatch(async () => {
75
116
  this.sql`
76
117
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
77
118
  id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
@@ -87,12 +128,36 @@ var Agent = class extends Server {
87
128
  await this.alarm();
88
129
  });
89
130
  });
131
+ this.sql`
132
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
133
+ id TEXT PRIMARY KEY NOT NULL,
134
+ name TEXT NOT NULL,
135
+ server_url TEXT NOT NULL,
136
+ callback_url TEXT NOT NULL,
137
+ client_id TEXT,
138
+ auth_url TEXT,
139
+ server_options TEXT
140
+ )
141
+ `;
90
142
  const _onRequest = this.onRequest.bind(this);
91
143
  this.onRequest = (request) => {
92
144
  return agentContext.run(
93
145
  { agent: this, connection: void 0, request },
94
146
  async () => {
95
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onRequest(request));
147
+ if (this.mcp.isCallbackRequest(request)) {
148
+ await this.mcp.handleCallbackRequest(request);
149
+ this.broadcast(
150
+ JSON.stringify({
151
+ mcp: this.getMcpServers(),
152
+ type: "cf_agent_mcp_servers"
153
+ })
154
+ );
155
+ return new Response("<script>window.close();</script>", {
156
+ headers: { "content-type": "text/html" },
157
+ status: 200
158
+ });
159
+ }
160
+ return this._tryCatch(() => _onRequest(request));
96
161
  }
97
162
  );
98
163
  };
@@ -102,16 +167,16 @@ var Agent = class extends Server {
102
167
  { agent: this, connection, request: void 0 },
103
168
  async () => {
104
169
  if (typeof message !== "string") {
105
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
170
+ return this._tryCatch(() => _onMessage(connection, message));
106
171
  }
107
172
  let parsed;
108
173
  try {
109
174
  parsed = JSON.parse(message);
110
- } catch (e) {
111
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
175
+ } catch (_e) {
176
+ return this._tryCatch(() => _onMessage(connection, message));
112
177
  }
113
178
  if (isStateUpdateMessage(parsed)) {
114
- __privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, parsed.state, connection);
179
+ this._setStateInternal(parsed.state, connection);
115
180
  return;
116
181
  }
117
182
  if (isRPCRequest(parsed)) {
@@ -121,7 +186,7 @@ var Agent = class extends Server {
121
186
  if (typeof methodFn !== "function") {
122
187
  throw new Error(`Method ${method} does not exist`);
123
188
  }
124
- if (!__privateMethod(this, _Agent_instances, isCallable_fn).call(this, method)) {
189
+ if (!this._isCallable(method)) {
125
190
  throw new Error(`Method ${method} is not callable`);
126
191
  }
127
192
  const metadata = callableMetadata.get(methodFn);
@@ -132,26 +197,26 @@ var Agent = class extends Server {
132
197
  }
133
198
  const result = await methodFn.apply(this, args);
134
199
  const response = {
135
- type: "rpc",
200
+ done: true,
136
201
  id,
137
- success: true,
138
202
  result,
139
- done: true
203
+ success: true,
204
+ type: "rpc"
140
205
  };
141
206
  connection.send(JSON.stringify(response));
142
207
  } catch (e) {
143
208
  const response = {
144
- type: "rpc",
209
+ error: e instanceof Error ? e.message : "Unknown error occurred",
145
210
  id: parsed.id,
146
211
  success: false,
147
- error: e instanceof Error ? e.message : "Unknown error occurred"
212
+ type: "rpc"
148
213
  };
149
214
  connection.send(JSON.stringify(response));
150
215
  console.error("RPC error:", e);
151
216
  }
152
217
  return;
153
218
  }
154
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
219
+ return this._tryCatch(() => _onMessage(connection, message));
155
220
  }
156
221
  );
157
222
  };
@@ -164,23 +229,61 @@ var Agent = class extends Server {
164
229
  if (this.state) {
165
230
  connection.send(
166
231
  JSON.stringify({
167
- type: "cf_agent_state",
168
- state: this.state
232
+ state: this.state,
233
+ type: "cf_agent_state"
169
234
  })
170
235
  );
171
236
  }
172
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onConnect(connection, ctx2));
237
+ connection.send(
238
+ JSON.stringify({
239
+ mcp: this.getMcpServers(),
240
+ type: "cf_agent_mcp_servers"
241
+ })
242
+ );
243
+ return this._tryCatch(() => _onConnect(connection, ctx2));
173
244
  }, 20);
174
245
  }
175
246
  );
176
247
  };
248
+ const _onStart = this.onStart.bind(this);
249
+ this.onStart = async () => {
250
+ return agentContext.run(
251
+ { agent: this, connection: void 0, request: void 0 },
252
+ async () => {
253
+ const servers = this.sql`
254
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
255
+ `;
256
+ await Promise.allSettled(
257
+ servers.filter((server) => server.auth_url === null).map((server) => {
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
+ );
268
+ })
269
+ );
270
+ this.broadcast(
271
+ JSON.stringify({
272
+ mcp: this.getMcpServers(),
273
+ type: "cf_agent_mcp_servers"
274
+ })
275
+ );
276
+ await this._tryCatch(() => _onStart());
277
+ }
278
+ );
279
+ };
177
280
  }
178
281
  /**
179
282
  * Current state of the Agent
180
283
  */
181
284
  get state() {
182
- if (__privateGet(this, _state) !== DEFAULT_STATE) {
183
- return __privateGet(this, _state);
285
+ if (this._state !== DEFAULT_STATE) {
286
+ return this._state;
184
287
  }
185
288
  const wasChanged = this.sql`
186
289
  SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
@@ -191,8 +294,8 @@ var Agent = class extends Server {
191
294
  if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
192
295
  result[0]?.state) {
193
296
  const state = result[0]?.state;
194
- __privateSet(this, _state, JSON.parse(state));
195
- return __privateGet(this, _state);
297
+ this._state = JSON.parse(state);
298
+ return this._state;
196
299
  }
197
300
  if (this.initialState === DEFAULT_STATE) {
198
301
  return void 0;
@@ -220,24 +323,53 @@ var Agent = class extends Server {
220
323
  throw this.onError(e);
221
324
  }
222
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
+ state,
339
+ type: "cf_agent_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
+ }
223
353
  /**
224
354
  * Update the Agent's state
225
355
  * @param state New state to set
226
356
  */
227
357
  setState(state) {
228
- __privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, state, "server");
358
+ this._setStateInternal(state, "server");
229
359
  }
230
360
  /**
231
361
  * Called when the Agent's state is updated
232
362
  * @param state Updated state
233
363
  * @param source Source of the state update ("server" or a client connection)
234
364
  */
365
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
235
366
  onStateUpdate(state, source) {
236
367
  }
237
368
  /**
238
369
  * Called when the Agent receives an email
239
370
  * @param email Email message to process
240
371
  */
372
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
241
373
  onEmail(email) {
242
374
  return agentContext.run(
243
375
  { agent: this, connection: void 0, request: void 0 },
@@ -246,6 +378,13 @@ var Agent = class extends Server {
246
378
  }
247
379
  );
248
380
  }
381
+ async _tryCatch(fn) {
382
+ try {
383
+ return await fn();
384
+ } catch (e) {
385
+ throw this.onError(e);
386
+ }
387
+ }
249
388
  onError(connectionOrError, error) {
250
389
  let theError;
251
390
  if (connectionOrError && error) {
@@ -295,10 +434,10 @@ var Agent = class extends Server {
295
434
  payload
296
435
  )}, 'scheduled', ${timestamp})
297
436
  `;
298
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
437
+ await this._scheduleNextAlarm();
299
438
  return {
300
- id,
301
439
  callback,
440
+ id,
302
441
  payload,
303
442
  time: timestamp,
304
443
  type: "scheduled"
@@ -313,12 +452,12 @@ var Agent = class extends Server {
313
452
  payload
314
453
  )}, 'delayed', ${when}, ${timestamp})
315
454
  `;
316
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
455
+ await this._scheduleNextAlarm();
317
456
  return {
318
- id,
319
457
  callback,
320
- payload,
321
458
  delayInSeconds: when,
459
+ id,
460
+ payload,
322
461
  time: timestamp,
323
462
  type: "delayed"
324
463
  };
@@ -332,12 +471,12 @@ var Agent = class extends Server {
332
471
  payload
333
472
  )}, 'cron', ${when}, ${timestamp})
334
473
  `;
335
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
474
+ await this._scheduleNextAlarm();
336
475
  return {
337
- id,
338
476
  callback,
339
- payload,
340
477
  cron: when,
478
+ id,
479
+ payload,
341
480
  time: timestamp,
342
481
  type: "cron"
343
482
  };
@@ -399,47 +538,21 @@ var Agent = class extends Server {
399
538
  */
400
539
  async cancelSchedule(id) {
401
540
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
402
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
541
+ await this._scheduleNextAlarm();
403
542
  return true;
404
543
  }
405
- /**
406
- * Method called when an alarm fires
407
- * Executes any scheduled tasks that are due
408
- */
409
- async alarm() {
410
- const now = Math.floor(Date.now() / 1e3);
544
+ async _scheduleNextAlarm() {
411
545
  const result = this.sql`
412
- SELECT * FROM cf_agents_schedules WHERE time <= ${now}
546
+ SELECT time FROM cf_agents_schedules
547
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
548
+ ORDER BY time ASC
549
+ LIMIT 1
413
550
  `;
414
- for (const row of result || []) {
415
- const callback = this[row.callback];
416
- if (!callback) {
417
- console.error(`callback ${row.callback} not found`);
418
- continue;
419
- }
420
- await agentContext.run(
421
- { agent: this, connection: void 0, request: void 0 },
422
- async () => {
423
- try {
424
- await callback.bind(this)(JSON.parse(row.payload), row);
425
- } catch (e) {
426
- console.error(`error executing callback "${row.callback}"`, e);
427
- }
428
- }
429
- );
430
- if (row.type === "cron") {
431
- const nextExecutionTime = getNextCronTime(row.cron);
432
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
433
- this.sql`
434
- UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
435
- `;
436
- } else {
437
- this.sql`
438
- DELETE FROM cf_agents_schedules WHERE id = ${row.id}
439
- `;
440
- }
551
+ if (!result) return;
552
+ if (result.length > 0 && "time" in result[0]) {
553
+ const nextTime = result[0].time * 1e3;
554
+ await this.ctx.storage.setAlarm(nextTime);
441
555
  }
442
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
443
556
  }
444
557
  /**
445
558
  * Destroy the Agent, removing all state and scheduled tasks
@@ -447,67 +560,131 @@ var Agent = class extends Server {
447
560
  async destroy() {
448
561
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
449
562
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
563
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
450
564
  await this.ctx.storage.deleteAlarm();
451
565
  await this.ctx.storage.deleteAll();
566
+ this.ctx.abort("destroyed");
452
567
  }
453
- };
454
- _state = new WeakMap();
455
- _ParentClass = new WeakMap();
456
- _Agent_instances = new WeakSet();
457
- setStateInternal_fn = function(state, source = "server") {
458
- __privateSet(this, _state, state);
459
- this.sql`
460
- INSERT OR REPLACE INTO cf_agents_state (id, state)
461
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
462
- `;
463
- this.sql`
464
- INSERT OR REPLACE INTO cf_agents_state (id, state)
465
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
466
- `;
467
- this.broadcast(
468
- JSON.stringify({
469
- type: "cf_agent_state",
470
- state
471
- }),
472
- source !== "server" ? [source.id] : []
473
- );
474
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => {
475
- const { connection, request } = agentContext.getStore() || {};
476
- return agentContext.run(
477
- { agent: this, connection, request },
478
- async () => {
479
- return this.onStateUpdate(state, source);
568
+ /**
569
+ * Get all methods marked as callable on this Agent
570
+ * @returns A map of method names to their metadata
571
+ */
572
+ _isCallable(method) {
573
+ return callableMetadata.has(this[method]);
574
+ }
575
+ /**
576
+ * Connect to a new MCP Server
577
+ *
578
+ * @param url MCP Server SSE URL
579
+ * @param callbackHost Base host for the agent, used for the redirect URI.
580
+ * @param agentsPrefix agents routing prefix if not using `agents`
581
+ * @param options MCP client and transport (header) options
582
+ * @returns authUrl
583
+ */
584
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
585
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
586
+ const result = await this._connectToMcpServerInternal(
587
+ serverName,
588
+ url,
589
+ callbackUrl,
590
+ options
591
+ );
592
+ this.broadcast(
593
+ JSON.stringify({
594
+ mcp: this.getMcpServers(),
595
+ type: "cf_agent_mcp_servers"
596
+ })
597
+ );
598
+ return result;
599
+ }
600
+ async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
601
+ const authProvider = new DurableObjectOAuthClientProvider(
602
+ this.ctx.storage,
603
+ this.name,
604
+ callbackUrl
605
+ );
606
+ if (reconnect) {
607
+ authProvider.serverId = reconnect.id;
608
+ if (reconnect.oauthClientId) {
609
+ authProvider.clientId = reconnect.oauthClientId;
480
610
  }
611
+ }
612
+ let headerTransportOpts = {};
613
+ if (options?.transport?.headers) {
614
+ headerTransportOpts = {
615
+ eventSourceInit: {
616
+ fetch: (url2, init) => fetch(url2, {
617
+ ...init,
618
+ headers: options?.transport?.headers
619
+ })
620
+ },
621
+ requestInit: {
622
+ headers: options?.transport?.headers
623
+ }
624
+ };
625
+ }
626
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
627
+ client: options?.client,
628
+ reconnect,
629
+ transport: {
630
+ ...headerTransportOpts,
631
+ authProvider
632
+ }
633
+ });
634
+ this.sql`
635
+ INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
636
+ VALUES (
637
+ ${id},
638
+ ${serverName},
639
+ ${url},
640
+ ${clientId ?? null},
641
+ ${authUrl ?? null},
642
+ ${callbackUrl},
643
+ ${options ? JSON.stringify(options) : null}
644
+ );
645
+ `;
646
+ return {
647
+ authUrl,
648
+ id
649
+ };
650
+ }
651
+ async removeMcpServer(id) {
652
+ this.mcp.closeConnection(id);
653
+ this.sql`
654
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
655
+ `;
656
+ this.broadcast(
657
+ JSON.stringify({
658
+ mcp: this.getMcpServers(),
659
+ type: "cf_agent_mcp_servers"
660
+ })
481
661
  );
482
- });
483
- };
484
- tryCatch_fn = async function(fn) {
485
- try {
486
- return await fn();
487
- } catch (e) {
488
- throw this.onError(e);
489
662
  }
490
- };
491
- scheduleNextAlarm_fn = async function() {
492
- const result = this.sql`
493
- SELECT time FROM cf_agents_schedules
494
- WHERE time > ${Math.floor(Date.now() / 1e3)}
495
- ORDER BY time ASC
496
- LIMIT 1
663
+ getMcpServers() {
664
+ const mcpState = {
665
+ prompts: this.mcp.listPrompts(),
666
+ resources: this.mcp.listResources(),
667
+ servers: {},
668
+ tools: this.mcp.listTools()
669
+ };
670
+ const servers = this.sql`
671
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
497
672
  `;
498
- if (!result) return;
499
- if (result.length > 0 && "time" in result[0]) {
500
- const nextTime = result[0].time * 1e3;
501
- await this.ctx.storage.setAlarm(nextTime);
673
+ for (const server of servers) {
674
+ const serverConn = this.mcp.mcpConnections[server.id];
675
+ mcpState.servers[server.id] = {
676
+ auth_url: server.auth_url,
677
+ capabilities: serverConn?.serverCapabilities ?? null,
678
+ instructions: serverConn?.instructions ?? null,
679
+ name: server.name,
680
+ server_url: server.server_url,
681
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
682
+ state: serverConn?.connectionState ?? "authenticating"
683
+ };
684
+ }
685
+ return mcpState;
502
686
  }
503
687
  };
504
- /**
505
- * Get all methods marked as callable on this Agent
506
- * @returns A map of method names to their metadata
507
- */
508
- isCallable_fn = function(method) {
509
- return callableMetadata.has(this[method]);
510
- };
511
688
  /**
512
689
  * Agent configuration options
513
690
  */
@@ -518,9 +695,9 @@ Agent.options = {
518
695
  };
519
696
  async function routeAgentRequest(request, env, options) {
520
697
  const corsHeaders = options?.cors === true ? {
521
- "Access-Control-Allow-Origin": "*",
522
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
523
698
  "Access-Control-Allow-Credentials": "true",
699
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
700
+ "Access-Control-Allow-Origin": "*",
524
701
  "Access-Control-Max-Age": "86400"
525
702
  } : options?.cors;
526
703
  if (request.method === "OPTIONS") {
@@ -551,59 +728,53 @@ async function routeAgentRequest(request, env, options) {
551
728
  }
552
729
  return response;
553
730
  }
554
- async function routeAgentEmail(email, env, options) {
731
+ async function routeAgentEmail(_email, _env, _options) {
555
732
  }
556
733
  async function getAgentByName(namespace, name, options) {
557
734
  return getServerByName(namespace, name, options);
558
735
  }
559
- var _connection, _id, _closed;
560
736
  var StreamingResponse = class {
561
737
  constructor(connection, id) {
562
- __privateAdd(this, _connection);
563
- __privateAdd(this, _id);
564
- __privateAdd(this, _closed, false);
565
- __privateSet(this, _connection, connection);
566
- __privateSet(this, _id, id);
738
+ this._closed = false;
739
+ this._connection = connection;
740
+ this._id = id;
567
741
  }
568
742
  /**
569
743
  * Send a chunk of data to the client
570
744
  * @param chunk The data to send
571
745
  */
572
746
  send(chunk) {
573
- if (__privateGet(this, _closed)) {
747
+ if (this._closed) {
574
748
  throw new Error("StreamingResponse is already closed");
575
749
  }
576
750
  const response = {
577
- type: "rpc",
578
- id: __privateGet(this, _id),
579
- success: true,
751
+ done: false,
752
+ id: this._id,
580
753
  result: chunk,
581
- done: false
754
+ success: true,
755
+ type: "rpc"
582
756
  };
583
- __privateGet(this, _connection).send(JSON.stringify(response));
757
+ this._connection.send(JSON.stringify(response));
584
758
  }
585
759
  /**
586
760
  * End the stream and send the final chunk (if any)
587
761
  * @param finalChunk Optional final chunk of data to send
588
762
  */
589
763
  end(finalChunk) {
590
- if (__privateGet(this, _closed)) {
764
+ if (this._closed) {
591
765
  throw new Error("StreamingResponse is already closed");
592
766
  }
593
- __privateSet(this, _closed, true);
767
+ this._closed = true;
594
768
  const response = {
595
- type: "rpc",
596
- id: __privateGet(this, _id),
597
- success: true,
769
+ done: true,
770
+ id: this._id,
598
771
  result: finalChunk,
599
- done: true
772
+ success: true,
773
+ type: "rpc"
600
774
  };
601
- __privateGet(this, _connection).send(JSON.stringify(response));
775
+ this._connection.send(JSON.stringify(response));
602
776
  }
603
777
  };
604
- _connection = new WeakMap();
605
- _id = new WeakMap();
606
- _closed = new WeakMap();
607
778
 
608
779
  export {
609
780
  unstable_callable,
@@ -614,4 +785,4 @@ export {
614
785
  getAgentByName,
615
786
  StreamingResponse
616
787
  };
617
- //# sourceMappingURL=chunk-5W7ZWKOP.js.map
788
+ //# sourceMappingURL=chunk-ZRRXJUAA.js.map