agents 0.0.0-316f98c → 0.0.0-33ff003

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 (38) hide show
  1. package/dist/ai-chat-agent.d.ts +49 -4
  2. package/dist/ai-chat-agent.js +128 -65
  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 +27 -18
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/ai-types.d.ts +5 -0
  8. package/dist/chunk-BZXOAZUX.js +106 -0
  9. package/dist/chunk-BZXOAZUX.js.map +1 -0
  10. package/dist/{chunk-HMLY7DHA.js → chunk-NOUFNU2O.js} +1 -5
  11. package/dist/{chunk-YMUU7QHV.js → chunk-NPGUKHFR.js} +310 -132
  12. package/dist/chunk-NPGUKHFR.js.map +1 -0
  13. package/dist/chunk-QSGN3REV.js +123 -0
  14. package/dist/chunk-QSGN3REV.js.map +1 -0
  15. package/dist/chunk-Y67CHZBI.js +464 -0
  16. package/dist/chunk-Y67CHZBI.js.map +1 -0
  17. package/dist/client.d.ts +9 -1
  18. package/dist/client.js +7 -126
  19. package/dist/client.js.map +1 -1
  20. package/dist/index.d.ts +83 -16
  21. package/dist/index.js +9 -8
  22. package/dist/mcp/client.d.ts +142 -34
  23. package/dist/mcp/client.js +4 -262
  24. package/dist/mcp/client.js.map +1 -1
  25. package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
  26. package/dist/mcp/do-oauth-client-provider.js +8 -0
  27. package/dist/mcp/do-oauth-client-provider.js.map +1 -0
  28. package/dist/mcp/index.d.ts +44 -5
  29. package/dist/mcp/index.js +611 -174
  30. package/dist/mcp/index.js.map +1 -1
  31. package/dist/react.d.ts +14 -0
  32. package/dist/react.js +25 -21
  33. package/dist/react.js.map +1 -1
  34. package/dist/schedule.js +1 -1
  35. package/package.json +30 -5
  36. package/src/index.ts +383 -59
  37. package/dist/chunk-YMUU7QHV.js.map +0 -1
  38. /package/dist/{chunk-HMLY7DHA.js.map → chunk-NOUFNU2O.js.map} +0 -0
@@ -1,9 +1,16 @@
1
+ import {
2
+ DurableObjectOAuthClientProvider
3
+ } from "./chunk-BZXOAZUX.js";
4
+ import {
5
+ camelCaseToKebabCase
6
+ } from "./chunk-QSGN3REV.js";
7
+ import {
8
+ MCPClientManager
9
+ } from "./chunk-Y67CHZBI.js";
1
10
  import {
2
11
  __privateAdd,
3
- __privateGet,
4
- __privateMethod,
5
- __privateSet
6
- } from "./chunk-HMLY7DHA.js";
12
+ __privateMethod
13
+ } from "./chunk-NOUFNU2O.js";
7
14
 
8
15
  // src/index.ts
9
16
  import {
@@ -14,7 +21,6 @@ import {
14
21
  import { parseCronExpression } from "cron-schedule";
15
22
  import { nanoid } from "nanoid";
16
23
  import { AsyncLocalStorage } from "node:async_hooks";
17
- import { WorkflowEntrypoint as CFWorkflowEntrypoint } from "cloudflare:workers";
18
24
  function isRPCRequest(msg) {
19
25
  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);
20
26
  }
@@ -30,8 +36,6 @@ function unstable_callable(metadata = {}) {
30
36
  return target;
31
37
  };
32
38
  }
33
- var WorkflowEntrypoint = class extends CFWorkflowEntrypoint {
34
- };
35
39
  function getNextCronTime(cron) {
36
40
  const interval = parseCronExpression(cron);
37
41
  return interval.getNextDate();
@@ -39,18 +43,74 @@ function getNextCronTime(cron) {
39
43
  var STATE_ROW_ID = "cf_state_row_id";
40
44
  var STATE_WAS_CHANGED = "cf_state_was_changed";
41
45
  var DEFAULT_STATE = {};
42
- var unstable_context = new AsyncLocalStorage();
43
- var _state, _Agent_instances, setStateInternal_fn, tryCatch_fn, scheduleNextAlarm_fn, isCallable_fn;
46
+ var agentContext = new AsyncLocalStorage();
47
+ function getCurrentAgent() {
48
+ const store = agentContext.getStore();
49
+ if (!store) {
50
+ return {
51
+ agent: void 0,
52
+ connection: void 0,
53
+ request: void 0
54
+ };
55
+ }
56
+ return store;
57
+ }
58
+ var _Agent_instances, connectToMcpServerInternal_fn, getMcpServerStateInternal_fn;
44
59
  var Agent = class extends Server {
45
60
  constructor(ctx, env) {
46
61
  super(ctx, env);
47
62
  __privateAdd(this, _Agent_instances);
48
- __privateAdd(this, _state, DEFAULT_STATE);
63
+ this._state = DEFAULT_STATE;
64
+ this._ParentClass = Object.getPrototypeOf(this).constructor;
65
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
49
66
  /**
50
67
  * Initial state for the Agent
51
68
  * Override to provide default state values
52
69
  */
53
70
  this.initialState = DEFAULT_STATE;
71
+ /**
72
+ * Method called when an alarm fires.
73
+ * Executes any scheduled tasks that are due.
74
+ *
75
+ * @remarks
76
+ * To schedule a task, please use the `this.schedule` method instead.
77
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
78
+ */
79
+ this.alarm = async () => {
80
+ const now = Math.floor(Date.now() / 1e3);
81
+ const result = this.sql`
82
+ SELECT * FROM cf_agents_schedules WHERE time <= ${now}
83
+ `;
84
+ for (const row of result || []) {
85
+ const callback = this[row.callback];
86
+ if (!callback) {
87
+ console.error(`callback ${row.callback} not found`);
88
+ continue;
89
+ }
90
+ await agentContext.run(
91
+ { agent: this, connection: void 0, request: void 0 },
92
+ async () => {
93
+ try {
94
+ await callback.bind(this)(JSON.parse(row.payload), row);
95
+ } catch (e) {
96
+ console.error(`error executing callback "${row.callback}"`, e);
97
+ }
98
+ }
99
+ );
100
+ if (row.type === "cron") {
101
+ const nextExecutionTime = getNextCronTime(row.cron);
102
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
103
+ this.sql`
104
+ UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
105
+ `;
106
+ } else {
107
+ this.sql`
108
+ DELETE FROM cf_agents_schedules WHERE id = ${row.id}
109
+ `;
110
+ }
111
+ }
112
+ await this._scheduleNextAlarm();
113
+ };
54
114
  this.sql`
55
115
  CREATE TABLE IF NOT EXISTS cf_agents_state (
56
116
  id TEXT PRIMARY KEY NOT NULL,
@@ -58,7 +118,7 @@ var Agent = class extends Server {
58
118
  )
59
119
  `;
60
120
  void this.ctx.blockConcurrencyWhile(async () => {
61
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, async () => {
121
+ return this._tryCatch(async () => {
62
122
  this.sql`
63
123
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
64
124
  id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
@@ -74,22 +134,55 @@ var Agent = class extends Server {
74
134
  await this.alarm();
75
135
  });
76
136
  });
137
+ this.sql`
138
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
139
+ id TEXT PRIMARY KEY NOT NULL,
140
+ name TEXT NOT NULL,
141
+ server_url TEXT NOT NULL,
142
+ callback_url TEXT NOT NULL,
143
+ client_id TEXT,
144
+ auth_url TEXT,
145
+ server_options TEXT
146
+ )
147
+ `;
148
+ const _onRequest = this.onRequest.bind(this);
149
+ this.onRequest = (request) => {
150
+ return agentContext.run(
151
+ { agent: this, connection: void 0, request },
152
+ async () => {
153
+ if (this.mcp.isCallbackRequest(request)) {
154
+ await this.mcp.handleCallbackRequest(request);
155
+ this.broadcast(
156
+ JSON.stringify({
157
+ type: "cf_agent_mcp_servers",
158
+ mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
159
+ })
160
+ );
161
+ return new Response("<script>window.close();</script>", {
162
+ status: 200,
163
+ headers: { "content-type": "text/html" }
164
+ });
165
+ }
166
+ return this._tryCatch(() => _onRequest(request));
167
+ }
168
+ );
169
+ };
77
170
  const _onMessage = this.onMessage.bind(this);
78
171
  this.onMessage = async (connection, message) => {
79
- return unstable_context.run(
172
+ return agentContext.run(
80
173
  { agent: this, connection, request: void 0 },
81
174
  async () => {
82
175
  if (typeof message !== "string") {
83
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
176
+ return this._tryCatch(() => _onMessage(connection, message));
84
177
  }
85
178
  let parsed;
86
179
  try {
87
180
  parsed = JSON.parse(message);
88
181
  } catch (e) {
89
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
182
+ return this._tryCatch(() => _onMessage(connection, message));
90
183
  }
91
184
  if (isStateUpdateMessage(parsed)) {
92
- __privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, parsed.state, connection);
185
+ this._setStateInternal(parsed.state, connection);
93
186
  return;
94
187
  }
95
188
  if (isRPCRequest(parsed)) {
@@ -99,7 +192,7 @@ var Agent = class extends Server {
99
192
  if (typeof methodFn !== "function") {
100
193
  throw new Error(`Method ${method} does not exist`);
101
194
  }
102
- if (!__privateMethod(this, _Agent_instances, isCallable_fn).call(this, method)) {
195
+ if (!this._isCallable(method)) {
103
196
  throw new Error(`Method ${method} is not callable`);
104
197
  }
105
198
  const metadata = callableMetadata.get(methodFn);
@@ -129,13 +222,13 @@ var Agent = class extends Server {
129
222
  }
130
223
  return;
131
224
  }
132
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
225
+ return this._tryCatch(() => _onMessage(connection, message));
133
226
  }
134
227
  );
135
228
  };
136
229
  const _onConnect = this.onConnect.bind(this);
137
230
  this.onConnect = (connection, ctx2) => {
138
- return unstable_context.run(
231
+ return agentContext.run(
139
232
  { agent: this, connection, request: ctx2.request },
140
233
  async () => {
141
234
  setTimeout(() => {
@@ -147,18 +240,50 @@ var Agent = class extends Server {
147
240
  })
148
241
  );
149
242
  }
150
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onConnect(connection, ctx2));
243
+ connection.send(
244
+ JSON.stringify({
245
+ type: "cf_agent_mcp_servers",
246
+ mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
247
+ })
248
+ );
249
+ return this._tryCatch(() => _onConnect(connection, ctx2));
151
250
  }, 20);
152
251
  }
153
252
  );
154
253
  };
254
+ const _onStart = this.onStart.bind(this);
255
+ this.onStart = async () => {
256
+ return agentContext.run(
257
+ { agent: this, connection: void 0, request: void 0 },
258
+ async () => {
259
+ const servers = this.sql`
260
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
261
+ `;
262
+ await Promise.allSettled(
263
+ servers.map((server) => {
264
+ 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, {
265
+ id: server.id,
266
+ oauthClientId: server.client_id ?? void 0
267
+ });
268
+ })
269
+ );
270
+ this.broadcast(
271
+ JSON.stringify({
272
+ type: "cf_agent_mcp_servers",
273
+ mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
274
+ })
275
+ );
276
+ await this._tryCatch(() => _onStart());
277
+ }
278
+ );
279
+ };
155
280
  }
156
281
  /**
157
282
  * Current state of the Agent
158
283
  */
159
284
  get state() {
160
- if (__privateGet(this, _state) !== DEFAULT_STATE) {
161
- return __privateGet(this, _state);
285
+ if (this._state !== DEFAULT_STATE) {
286
+ return this._state;
162
287
  }
163
288
  const wasChanged = this.sql`
164
289
  SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
@@ -169,8 +294,8 @@ var Agent = class extends Server {
169
294
  if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
170
295
  result[0]?.state) {
171
296
  const state = result[0]?.state;
172
- __privateSet(this, _state, JSON.parse(state));
173
- return __privateGet(this, _state);
297
+ this._state = JSON.parse(state);
298
+ return this._state;
174
299
  }
175
300
  if (this.initialState === DEFAULT_STATE) {
176
301
  return void 0;
@@ -198,12 +323,39 @@ var Agent = class extends Server {
198
323
  throw this.onError(e);
199
324
  }
200
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
+ }
201
353
  /**
202
354
  * Update the Agent's state
203
355
  * @param state New state to set
204
356
  */
205
357
  setState(state) {
206
- __privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, state, "server");
358
+ this._setStateInternal(state, "server");
207
359
  }
208
360
  /**
209
361
  * Called when the Agent's state is updated
@@ -217,13 +369,20 @@ var Agent = class extends Server {
217
369
  * @param email Email message to process
218
370
  */
219
371
  onEmail(email) {
220
- return unstable_context.run(
372
+ return agentContext.run(
221
373
  { agent: this, connection: void 0, request: void 0 },
222
374
  async () => {
223
375
  console.error("onEmail not implemented");
224
376
  }
225
377
  );
226
378
  }
379
+ async _tryCatch(fn) {
380
+ try {
381
+ return await fn();
382
+ } catch (e) {
383
+ throw this.onError(e);
384
+ }
385
+ }
227
386
  onError(connectionOrError, error) {
228
387
  let theError;
229
388
  if (connectionOrError && error) {
@@ -273,7 +432,7 @@ var Agent = class extends Server {
273
432
  payload
274
433
  )}, 'scheduled', ${timestamp})
275
434
  `;
276
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
435
+ await this._scheduleNextAlarm();
277
436
  return {
278
437
  id,
279
438
  callback,
@@ -291,7 +450,7 @@ var Agent = class extends Server {
291
450
  payload
292
451
  )}, 'delayed', ${when}, ${timestamp})
293
452
  `;
294
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
453
+ await this._scheduleNextAlarm();
295
454
  return {
296
455
  id,
297
456
  callback,
@@ -310,7 +469,7 @@ var Agent = class extends Server {
310
469
  payload
311
470
  )}, 'cron', ${when}, ${timestamp})
312
471
  `;
313
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
472
+ await this._scheduleNextAlarm();
314
473
  return {
315
474
  id,
316
475
  callback,
@@ -377,47 +536,21 @@ var Agent = class extends Server {
377
536
  */
378
537
  async cancelSchedule(id) {
379
538
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
380
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
539
+ await this._scheduleNextAlarm();
381
540
  return true;
382
541
  }
383
- /**
384
- * Method called when an alarm fires
385
- * Executes any scheduled tasks that are due
386
- */
387
- async alarm() {
388
- const now = Math.floor(Date.now() / 1e3);
542
+ async _scheduleNextAlarm() {
389
543
  const result = this.sql`
390
- SELECT * FROM cf_agents_schedules WHERE time <= ${now}
544
+ SELECT time FROM cf_agents_schedules
545
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
546
+ ORDER BY time ASC
547
+ LIMIT 1
391
548
  `;
392
- for (const row of result || []) {
393
- const callback = this[row.callback];
394
- if (!callback) {
395
- console.error(`callback ${row.callback} not found`);
396
- continue;
397
- }
398
- await unstable_context.run(
399
- { agent: this, connection: void 0, request: void 0 },
400
- async () => {
401
- try {
402
- await callback.bind(this)(JSON.parse(row.payload), row);
403
- } catch (e) {
404
- console.error(`error executing callback "${row.callback}"`, e);
405
- }
406
- }
407
- );
408
- if (row.type === "cron") {
409
- const nextExecutionTime = getNextCronTime(row.cron);
410
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
411
- this.sql`
412
- UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
413
- `;
414
- } else {
415
- this.sql`
416
- DELETE FROM cf_agents_schedules WHERE id = ${row.id}
417
- `;
418
- }
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);
419
553
  }
420
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
421
554
  }
422
555
  /**
423
556
  * Destroy the Agent, removing all state and scheduled tasks
@@ -425,65 +558,117 @@ var Agent = class extends Server {
425
558
  async destroy() {
426
559
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
427
560
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
561
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
428
562
  await this.ctx.storage.deleteAlarm();
429
563
  await this.ctx.storage.deleteAll();
430
564
  }
565
+ _isCallable(method) {
566
+ return callableMetadata.has(this[method]);
567
+ }
568
+ /**
569
+ * Connect to a new MCP Server
570
+ *
571
+ * @param url MCP Server SSE URL
572
+ * @param callbackHost Base host for the agent, used for the redirect URI.
573
+ * @param agentsPrefix agents routing prefix if not using `agents`
574
+ * @param options MCP client and transport (header) options
575
+ * @returns authUrl
576
+ */
577
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
578
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
579
+ const result = await __privateMethod(this, _Agent_instances, connectToMcpServerInternal_fn).call(this, serverName, url, callbackUrl, options);
580
+ this.broadcast(
581
+ JSON.stringify({
582
+ type: "cf_agent_mcp_servers",
583
+ mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
584
+ })
585
+ );
586
+ return result;
587
+ }
588
+ async removeMcpServer(id) {
589
+ this.mcp.closeConnection(id);
590
+ this.sql`
591
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
592
+ `;
593
+ this.broadcast(
594
+ JSON.stringify({
595
+ type: "cf_agent_mcp_servers",
596
+ mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
597
+ })
598
+ );
599
+ }
431
600
  };
432
- _state = new WeakMap();
433
601
  _Agent_instances = new WeakSet();
434
- setStateInternal_fn = function(state, source = "server") {
435
- __privateSet(this, _state, state);
436
- this.sql`
437
- INSERT OR REPLACE INTO cf_agents_state (id, state)
438
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
439
- `;
440
- this.sql`
441
- INSERT OR REPLACE INTO cf_agents_state (id, state)
442
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
443
- `;
444
- this.broadcast(
445
- JSON.stringify({
446
- type: "cf_agent_state",
447
- state
448
- }),
449
- source !== "server" ? [source.id] : []
602
+ connectToMcpServerInternal_fn = async function(serverName, url, callbackUrl, options, reconnect) {
603
+ const authProvider = new DurableObjectOAuthClientProvider(
604
+ this.ctx.storage,
605
+ this.name,
606
+ callbackUrl
450
607
  );
451
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => {
452
- const { connection, request } = unstable_context.getStore() || {};
453
- return unstable_context.run(
454
- { agent: this, connection, request },
455
- async () => {
456
- return this.onStateUpdate(state, source);
608
+ if (reconnect) {
609
+ authProvider.serverId = reconnect.id;
610
+ if (reconnect.oauthClientId) {
611
+ authProvider.clientId = reconnect.oauthClientId;
612
+ }
613
+ }
614
+ let headerTransportOpts = {};
615
+ if (options?.transport?.headers) {
616
+ headerTransportOpts = {
617
+ eventSourceInit: {
618
+ fetch: (url2, init) => fetch(url2, {
619
+ ...init,
620
+ headers: options?.transport?.headers
621
+ })
622
+ },
623
+ requestInit: {
624
+ headers: options?.transport?.headers
457
625
  }
458
- );
459
- });
460
- };
461
- tryCatch_fn = async function(fn) {
462
- try {
463
- return await fn();
464
- } catch (e) {
465
- throw this.onError(e);
626
+ };
466
627
  }
628
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
629
+ reconnect,
630
+ transport: {
631
+ ...headerTransportOpts,
632
+ authProvider
633
+ },
634
+ client: options?.client
635
+ });
636
+ this.sql`
637
+ INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
638
+ VALUES (
639
+ ${id},
640
+ ${serverName},
641
+ ${url},
642
+ ${clientId ?? null},
643
+ ${authUrl ?? null},
644
+ ${callbackUrl},
645
+ ${options ? JSON.stringify(options) : null}
646
+ );
647
+ `;
648
+ return {
649
+ id,
650
+ authUrl
651
+ };
467
652
  };
468
- scheduleNextAlarm_fn = async function() {
469
- const result = this.sql`
470
- SELECT time FROM cf_agents_schedules
471
- WHERE time > ${Math.floor(Date.now() / 1e3)}
472
- ORDER BY time ASC
473
- LIMIT 1
653
+ getMcpServerStateInternal_fn = function() {
654
+ const mcpState = {
655
+ servers: {},
656
+ tools: this.mcp.listTools(),
657
+ prompts: this.mcp.listPrompts(),
658
+ resources: this.mcp.listResources()
659
+ };
660
+ const servers = this.sql`
661
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
474
662
  `;
475
- if (!result) return;
476
- if (result.length > 0 && "time" in result[0]) {
477
- const nextTime = result[0].time * 1e3;
478
- await this.ctx.storage.setAlarm(nextTime);
663
+ for (const server of servers) {
664
+ mcpState.servers[server.id] = {
665
+ name: server.name,
666
+ server_url: server.server_url,
667
+ auth_url: server.auth_url,
668
+ state: this.mcp.mcpConnections[server.id].connectionState
669
+ };
479
670
  }
480
- };
481
- /**
482
- * Get all methods marked as callable on this Agent
483
- * @returns A map of method names to their metadata
484
- */
485
- isCallable_fn = function(method) {
486
- return callableMetadata.has(this[method]);
671
+ return mcpState;
487
672
  };
488
673
  /**
489
674
  * Agent configuration options
@@ -530,66 +715,59 @@ async function routeAgentRequest(request, env, options) {
530
715
  }
531
716
  async function routeAgentEmail(email, env, options) {
532
717
  }
533
- function getAgentByName(namespace, name, options) {
718
+ async function getAgentByName(namespace, name, options) {
534
719
  return getServerByName(namespace, name, options);
535
720
  }
536
- var _connection, _id, _closed;
537
721
  var StreamingResponse = class {
538
722
  constructor(connection, id) {
539
- __privateAdd(this, _connection);
540
- __privateAdd(this, _id);
541
- __privateAdd(this, _closed, false);
542
- __privateSet(this, _connection, connection);
543
- __privateSet(this, _id, id);
723
+ this._closed = false;
724
+ this._connection = connection;
725
+ this._id = id;
544
726
  }
545
727
  /**
546
728
  * Send a chunk of data to the client
547
729
  * @param chunk The data to send
548
730
  */
549
731
  send(chunk) {
550
- if (__privateGet(this, _closed)) {
732
+ if (this._closed) {
551
733
  throw new Error("StreamingResponse is already closed");
552
734
  }
553
735
  const response = {
554
736
  type: "rpc",
555
- id: __privateGet(this, _id),
737
+ id: this._id,
556
738
  success: true,
557
739
  result: chunk,
558
740
  done: false
559
741
  };
560
- __privateGet(this, _connection).send(JSON.stringify(response));
742
+ this._connection.send(JSON.stringify(response));
561
743
  }
562
744
  /**
563
745
  * End the stream and send the final chunk (if any)
564
746
  * @param finalChunk Optional final chunk of data to send
565
747
  */
566
748
  end(finalChunk) {
567
- if (__privateGet(this, _closed)) {
749
+ if (this._closed) {
568
750
  throw new Error("StreamingResponse is already closed");
569
751
  }
570
- __privateSet(this, _closed, true);
752
+ this._closed = true;
571
753
  const response = {
572
754
  type: "rpc",
573
- id: __privateGet(this, _id),
755
+ id: this._id,
574
756
  success: true,
575
757
  result: finalChunk,
576
758
  done: true
577
759
  };
578
- __privateGet(this, _connection).send(JSON.stringify(response));
760
+ this._connection.send(JSON.stringify(response));
579
761
  }
580
762
  };
581
- _connection = new WeakMap();
582
- _id = new WeakMap();
583
- _closed = new WeakMap();
584
763
 
585
764
  export {
586
765
  unstable_callable,
587
- WorkflowEntrypoint,
588
- unstable_context,
766
+ getCurrentAgent,
589
767
  Agent,
590
768
  routeAgentRequest,
591
769
  routeAgentEmail,
592
770
  getAgentByName,
593
771
  StreamingResponse
594
772
  };
595
- //# sourceMappingURL=chunk-YMUU7QHV.js.map
773
+ //# sourceMappingURL=chunk-NPGUKHFR.js.map