agents 0.0.0-ac0e999 → 0.0.0-ac74811

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 (45) hide show
  1. package/dist/ai-chat-agent.d.ts +13 -12
  2. package/dist/ai-chat-agent.js +94 -57
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-react.d.ts +9 -8
  5. package/dist/ai-react.js +27 -29
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/{chunk-D6UOOELW.js → chunk-767EASBA.js} +15 -15
  8. package/dist/chunk-767EASBA.js.map +1 -0
  9. package/dist/{chunk-25YDMV4H.js → chunk-E3LCYPCB.js} +34 -29
  10. package/dist/chunk-E3LCYPCB.js.map +1 -0
  11. package/dist/{chunk-DMJ7L3FI.js → chunk-JFRK72K3.js} +305 -168
  12. package/dist/chunk-JFRK72K3.js.map +1 -0
  13. package/dist/{chunk-ZKIVUOTQ.js → chunk-NKZZ66QY.js} +14 -21
  14. package/dist/chunk-NKZZ66QY.js.map +1 -0
  15. package/dist/client.d.ts +7 -1
  16. package/dist/client.js +1 -2
  17. package/dist/index-CITGJflw.d.ts +486 -0
  18. package/dist/index.d.ts +25 -369
  19. package/dist/index.js +4 -5
  20. package/dist/mcp/client.d.ts +287 -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 +1 -2
  24. package/dist/mcp/index.d.ts +12 -12
  25. package/dist/mcp/index.js +124 -121
  26. package/dist/mcp/index.js.map +1 -1
  27. package/dist/observability/index.d.ts +12 -0
  28. package/dist/observability/index.js +10 -0
  29. package/dist/react.d.ts +76 -10
  30. package/dist/react.js +16 -8
  31. package/dist/react.js.map +1 -1
  32. package/dist/schedule.d.ts +6 -6
  33. package/dist/schedule.js +4 -6
  34. package/dist/schedule.js.map +1 -1
  35. package/dist/serializable.d.ts +32 -0
  36. package/dist/serializable.js +1 -0
  37. package/dist/serializable.js.map +1 -0
  38. package/package.json +75 -71
  39. package/src/index.ts +253 -131
  40. package/dist/chunk-25YDMV4H.js.map +0 -1
  41. package/dist/chunk-D6UOOELW.js.map +0 -1
  42. package/dist/chunk-DMJ7L3FI.js.map +0 -1
  43. package/dist/chunk-NOUFNU2O.js +0 -12
  44. package/dist/chunk-ZKIVUOTQ.js.map +0 -1
  45. /package/dist/{chunk-NOUFNU2O.js.map → observability/index.js.map} +0 -0
@@ -1,26 +1,22 @@
1
+ import {
2
+ MCPClientManager
3
+ } from "./chunk-E3LCYPCB.js";
1
4
  import {
2
5
  DurableObjectOAuthClientProvider
3
- } from "./chunk-D6UOOELW.js";
6
+ } from "./chunk-767EASBA.js";
4
7
  import {
5
8
  camelCaseToKebabCase
6
- } from "./chunk-ZKIVUOTQ.js";
7
- import {
8
- MCPClientManager
9
- } from "./chunk-25YDMV4H.js";
10
- import {
11
- __privateAdd,
12
- __privateMethod
13
- } from "./chunk-NOUFNU2O.js";
9
+ } from "./chunk-NKZZ66QY.js";
14
10
 
15
11
  // src/index.ts
12
+ import { AsyncLocalStorage } from "async_hooks";
13
+ import { parseCronExpression } from "cron-schedule";
14
+ import { nanoid } from "nanoid";
16
15
  import {
17
- Server,
16
+ getServerByName,
18
17
  routePartykitRequest,
19
- getServerByName
18
+ Server
20
19
  } from "partyserver";
21
- import { parseCronExpression } from "cron-schedule";
22
- import { nanoid } from "nanoid";
23
- import { AsyncLocalStorage } from "node:async_hooks";
24
20
  function isRPCRequest(msg) {
25
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);
26
22
  }
@@ -55,19 +51,21 @@ function getCurrentAgent() {
55
51
  }
56
52
  return store;
57
53
  }
58
- var _Agent_instances, connectToMcpServerInternal_fn, getMcpServerStateInternal_fn;
59
54
  var Agent = class extends Server {
60
55
  constructor(ctx, env) {
61
56
  super(ctx, env);
62
- __privateAdd(this, _Agent_instances);
63
57
  this._state = DEFAULT_STATE;
64
- this.ParentClass = Object.getPrototypeOf(this).constructor;
65
- this.mcp = new MCPClientManager(this.ParentClass.name, "0.0.1");
58
+ this._ParentClass = Object.getPrototypeOf(this).constructor;
59
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
66
60
  /**
67
61
  * Initial state for the Agent
68
62
  * Override to provide default state values
69
63
  */
70
64
  this.initialState = DEFAULT_STATE;
65
+ /**
66
+ * The observability implementation to use for the Agent
67
+ */
68
+ this.observability = genericObservability;
71
69
  /**
72
70
  * Method called when an alarm fires.
73
71
  * Executes any scheduled tasks that are due.
@@ -91,6 +89,16 @@ var Agent = class extends Server {
91
89
  { agent: this, connection: void 0, request: void 0 },
92
90
  async () => {
93
91
  try {
92
+ this.observability?.emit(
93
+ {
94
+ displayMessage: `Schedule ${row.id} executed`,
95
+ id: nanoid(),
96
+ payload: row,
97
+ timestamp: Date.now(),
98
+ type: "schedule:execute"
99
+ },
100
+ this.ctx
101
+ );
94
102
  await callback.bind(this)(JSON.parse(row.payload), row);
95
103
  } catch (e) {
96
104
  console.error(`error executing callback "${row.callback}"`, e);
@@ -109,7 +117,7 @@ var Agent = class extends Server {
109
117
  `;
110
118
  }
111
119
  }
112
- await this.scheduleNextAlarm();
120
+ await this._scheduleNextAlarm();
113
121
  };
114
122
  this.sql`
115
123
  CREATE TABLE IF NOT EXISTS cf_agents_state (
@@ -118,7 +126,7 @@ var Agent = class extends Server {
118
126
  )
119
127
  `;
120
128
  void this.ctx.blockConcurrencyWhile(async () => {
121
- return this.tryCatch(async () => {
129
+ return this._tryCatch(async () => {
122
130
  this.sql`
123
131
  CREATE TABLE IF NOT EXISTS cf_agents_schedules (
124
132
  id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
@@ -154,16 +162,16 @@ var Agent = class extends Server {
154
162
  await this.mcp.handleCallbackRequest(request);
155
163
  this.broadcast(
156
164
  JSON.stringify({
157
- type: "cf_agent_mcp_servers",
158
- mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
165
+ mcp: this.getMcpServers(),
166
+ type: "cf_agent_mcp_servers"
159
167
  })
160
168
  );
161
169
  return new Response("<script>window.close();</script>", {
162
- status: 200,
163
- headers: { "content-type": "text/html" }
170
+ headers: { "content-type": "text/html" },
171
+ status: 200
164
172
  });
165
173
  }
166
- return this.tryCatch(() => _onRequest(request));
174
+ return this._tryCatch(() => _onRequest(request));
167
175
  }
168
176
  );
169
177
  };
@@ -173,16 +181,16 @@ var Agent = class extends Server {
173
181
  { agent: this, connection, request: void 0 },
174
182
  async () => {
175
183
  if (typeof message !== "string") {
176
- return this.tryCatch(() => _onMessage(connection, message));
184
+ return this._tryCatch(() => _onMessage(connection, message));
177
185
  }
178
186
  let parsed;
179
187
  try {
180
188
  parsed = JSON.parse(message);
181
- } catch (e) {
182
- return this.tryCatch(() => _onMessage(connection, message));
189
+ } catch (_e) {
190
+ return this._tryCatch(() => _onMessage(connection, message));
183
191
  }
184
192
  if (isStateUpdateMessage(parsed)) {
185
- this.setStateInternal(parsed.state, connection);
193
+ this._setStateInternal(parsed.state, connection);
186
194
  return;
187
195
  }
188
196
  if (isRPCRequest(parsed)) {
@@ -192,7 +200,7 @@ var Agent = class extends Server {
192
200
  if (typeof methodFn !== "function") {
193
201
  throw new Error(`Method ${method} does not exist`);
194
202
  }
195
- if (!this.isCallable(method)) {
203
+ if (!this._isCallable(method)) {
196
204
  throw new Error(`Method ${method} is not callable`);
197
205
  }
198
206
  const metadata = callableMetadata.get(methodFn);
@@ -202,27 +210,42 @@ var Agent = class extends Server {
202
210
  return;
203
211
  }
204
212
  const result = await methodFn.apply(this, args);
213
+ this.observability?.emit(
214
+ {
215
+ displayMessage: `RPC call to ${method}`,
216
+ id: nanoid(),
217
+ payload: {
218
+ args,
219
+ method,
220
+ streaming: metadata?.streaming,
221
+ success: true
222
+ },
223
+ timestamp: Date.now(),
224
+ type: "rpc"
225
+ },
226
+ this.ctx
227
+ );
205
228
  const response = {
206
- type: "rpc",
229
+ done: true,
207
230
  id,
208
- success: true,
209
231
  result,
210
- done: true
232
+ success: true,
233
+ type: "rpc"
211
234
  };
212
235
  connection.send(JSON.stringify(response));
213
236
  } catch (e) {
214
237
  const response = {
215
- type: "rpc",
238
+ error: e instanceof Error ? e.message : "Unknown error occurred",
216
239
  id: parsed.id,
217
240
  success: false,
218
- error: e instanceof Error ? e.message : "Unknown error occurred"
241
+ type: "rpc"
219
242
  };
220
243
  connection.send(JSON.stringify(response));
221
244
  console.error("RPC error:", e);
222
245
  }
223
246
  return;
224
247
  }
225
- return this.tryCatch(() => _onMessage(connection, message));
248
+ return this._tryCatch(() => _onMessage(connection, message));
226
249
  }
227
250
  );
228
251
  };
@@ -235,18 +258,30 @@ var Agent = class extends Server {
235
258
  if (this.state) {
236
259
  connection.send(
237
260
  JSON.stringify({
238
- type: "cf_agent_state",
239
- state: this.state
261
+ state: this.state,
262
+ type: "cf_agent_state"
240
263
  })
241
264
  );
242
265
  }
243
266
  connection.send(
244
267
  JSON.stringify({
245
- type: "cf_agent_mcp_servers",
246
- mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
268
+ mcp: this.getMcpServers(),
269
+ type: "cf_agent_mcp_servers"
247
270
  })
248
271
  );
249
- return this.tryCatch(() => _onConnect(connection, ctx2));
272
+ this.observability?.emit(
273
+ {
274
+ displayMessage: "Connection established",
275
+ id: nanoid(),
276
+ payload: {
277
+ connectionId: connection.id
278
+ },
279
+ timestamp: Date.now(),
280
+ type: "connect"
281
+ },
282
+ this.ctx
283
+ );
284
+ return this._tryCatch(() => _onConnect(connection, ctx2));
250
285
  }, 20);
251
286
  }
252
287
  );
@@ -259,21 +294,28 @@ var Agent = class extends Server {
259
294
  const servers = this.sql`
260
295
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
261
296
  `;
262
- await Promise.allSettled(
297
+ Promise.allSettled(
263
298
  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)
299
+ return this._connectToMcpServerInternal(
300
+ server.name,
301
+ server.server_url,
302
+ server.callback_url,
303
+ server.server_options ? JSON.parse(server.server_options) : void 0,
304
+ {
305
+ id: server.id,
306
+ oauthClientId: server.client_id ?? void 0
307
+ }
308
+ );
274
309
  })
275
- );
276
- await this.tryCatch(() => _onStart());
310
+ ).then((_results) => {
311
+ this.broadcast(
312
+ JSON.stringify({
313
+ mcp: this.getMcpServers(),
314
+ type: "cf_agent_mcp_servers"
315
+ })
316
+ );
317
+ });
318
+ await this._tryCatch(() => _onStart());
277
319
  }
278
320
  );
279
321
  };
@@ -323,7 +365,8 @@ var Agent = class extends Server {
323
365
  throw this.onError(e);
324
366
  }
325
367
  }
326
- setStateInternal(state, source = "server") {
368
+ _setStateInternal(state, source = "server") {
369
+ const previousState = this._state;
327
370
  this._state = state;
328
371
  this.sql`
329
372
  INSERT OR REPLACE INTO cf_agents_state (id, state)
@@ -335,16 +378,29 @@ var Agent = class extends Server {
335
378
  `;
336
379
  this.broadcast(
337
380
  JSON.stringify({
338
- type: "cf_agent_state",
339
- state
381
+ state,
382
+ type: "cf_agent_state"
340
383
  }),
341
384
  source !== "server" ? [source.id] : []
342
385
  );
343
- return this.tryCatch(() => {
386
+ return this._tryCatch(() => {
344
387
  const { connection, request } = agentContext.getStore() || {};
345
388
  return agentContext.run(
346
389
  { agent: this, connection, request },
347
390
  async () => {
391
+ this.observability?.emit(
392
+ {
393
+ displayMessage: "State updated",
394
+ id: nanoid(),
395
+ payload: {
396
+ previousState,
397
+ state
398
+ },
399
+ timestamp: Date.now(),
400
+ type: "state:update"
401
+ },
402
+ this.ctx
403
+ );
348
404
  return this.onStateUpdate(state, source);
349
405
  }
350
406
  );
@@ -355,19 +411,21 @@ var Agent = class extends Server {
355
411
  * @param state New state to set
356
412
  */
357
413
  setState(state) {
358
- this.setStateInternal(state, "server");
414
+ this._setStateInternal(state, "server");
359
415
  }
360
416
  /**
361
417
  * Called when the Agent's state is updated
362
418
  * @param state Updated state
363
419
  * @param source Source of the state update ("server" or a client connection)
364
420
  */
421
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
365
422
  onStateUpdate(state, source) {
366
423
  }
367
424
  /**
368
425
  * Called when the Agent receives an email
369
426
  * @param email Email message to process
370
427
  */
428
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
371
429
  onEmail(email) {
372
430
  return agentContext.run(
373
431
  { agent: this, connection: void 0, request: void 0 },
@@ -376,7 +434,7 @@ var Agent = class extends Server {
376
434
  }
377
435
  );
378
436
  }
379
- async tryCatch(fn) {
437
+ async _tryCatch(fn) {
380
438
  try {
381
439
  return await fn();
382
440
  } catch (e) {
@@ -418,6 +476,16 @@ var Agent = class extends Server {
418
476
  */
419
477
  async schedule(when, callback, payload) {
420
478
  const id = nanoid(9);
479
+ const emitScheduleCreate = (schedule) => this.observability?.emit(
480
+ {
481
+ displayMessage: `Schedule ${schedule.id} created`,
482
+ id: nanoid(),
483
+ payload: schedule,
484
+ timestamp: Date.now(),
485
+ type: "schedule:create"
486
+ },
487
+ this.ctx
488
+ );
421
489
  if (typeof callback !== "string") {
422
490
  throw new Error("Callback must be a string");
423
491
  }
@@ -432,14 +500,16 @@ var Agent = class extends Server {
432
500
  payload
433
501
  )}, 'scheduled', ${timestamp})
434
502
  `;
435
- await this.scheduleNextAlarm();
436
- return {
437
- id,
503
+ await this._scheduleNextAlarm();
504
+ const schedule = {
438
505
  callback,
506
+ id,
439
507
  payload,
440
508
  time: timestamp,
441
509
  type: "scheduled"
442
510
  };
511
+ emitScheduleCreate(schedule);
512
+ return schedule;
443
513
  }
444
514
  if (typeof when === "number") {
445
515
  const time = new Date(Date.now() + when * 1e3);
@@ -450,15 +520,17 @@ var Agent = class extends Server {
450
520
  payload
451
521
  )}, 'delayed', ${when}, ${timestamp})
452
522
  `;
453
- await this.scheduleNextAlarm();
454
- return {
455
- id,
523
+ await this._scheduleNextAlarm();
524
+ const schedule = {
456
525
  callback,
457
- payload,
458
526
  delayInSeconds: when,
527
+ id,
528
+ payload,
459
529
  time: timestamp,
460
530
  type: "delayed"
461
531
  };
532
+ emitScheduleCreate(schedule);
533
+ return schedule;
462
534
  }
463
535
  if (typeof when === "string") {
464
536
  const nextExecutionTime = getNextCronTime(when);
@@ -469,15 +541,17 @@ var Agent = class extends Server {
469
541
  payload
470
542
  )}, 'cron', ${when}, ${timestamp})
471
543
  `;
472
- await this.scheduleNextAlarm();
473
- return {
474
- id,
544
+ await this._scheduleNextAlarm();
545
+ const schedule = {
475
546
  callback,
476
- payload,
477
547
  cron: when,
548
+ id,
549
+ payload,
478
550
  time: timestamp,
479
551
  type: "cron"
480
552
  };
553
+ emitScheduleCreate(schedule);
554
+ return schedule;
481
555
  }
482
556
  throw new Error("Invalid schedule type");
483
557
  }
@@ -535,11 +609,24 @@ var Agent = class extends Server {
535
609
  * @returns true if the task was cancelled, false otherwise
536
610
  */
537
611
  async cancelSchedule(id) {
612
+ const schedule = await this.getSchedule(id);
613
+ if (schedule) {
614
+ this.observability?.emit(
615
+ {
616
+ displayMessage: `Schedule ${id} cancelled`,
617
+ id: nanoid(),
618
+ payload: schedule,
619
+ timestamp: Date.now(),
620
+ type: "schedule:cancel"
621
+ },
622
+ this.ctx
623
+ );
624
+ }
538
625
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
539
- await this.scheduleNextAlarm();
626
+ await this._scheduleNextAlarm();
540
627
  return true;
541
628
  }
542
- async scheduleNextAlarm() {
629
+ async _scheduleNextAlarm() {
543
630
  const result = this.sql`
544
631
  SELECT time FROM cf_agents_schedules
545
632
  WHERE time > ${Math.floor(Date.now() / 1e3)}
@@ -561,8 +648,23 @@ var Agent = class extends Server {
561
648
  this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
562
649
  await this.ctx.storage.deleteAlarm();
563
650
  await this.ctx.storage.deleteAll();
651
+ this.ctx.abort("destroyed");
652
+ this.observability?.emit(
653
+ {
654
+ displayMessage: "Agent destroyed",
655
+ id: nanoid(),
656
+ payload: {},
657
+ timestamp: Date.now(),
658
+ type: "destroy"
659
+ },
660
+ this.ctx
661
+ );
564
662
  }
565
- isCallable(method) {
663
+ /**
664
+ * Get all methods marked as callable on this Agent
665
+ * @returns A map of method names to their metadata
666
+ */
667
+ _isCallable(method) {
566
668
  return callableMetadata.has(this[method]);
567
669
  }
568
670
  /**
@@ -575,16 +677,74 @@ var Agent = class extends Server {
575
677
  * @returns authUrl
576
678
  */
577
679
  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);
680
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
681
+ const result = await this._connectToMcpServerInternal(
682
+ serverName,
683
+ url,
684
+ callbackUrl,
685
+ options
686
+ );
687
+ this.sql`
688
+ INSERT
689
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
690
+ VALUES (
691
+ ${result.id},
692
+ ${serverName},
693
+ ${url},
694
+ ${result.clientId ?? null},
695
+ ${result.authUrl ?? null},
696
+ ${callbackUrl},
697
+ ${options ? JSON.stringify(options) : null}
698
+ );
699
+ `;
580
700
  this.broadcast(
581
701
  JSON.stringify({
582
- type: "cf_agent_mcp_servers",
583
- mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
702
+ mcp: this.getMcpServers(),
703
+ type: "cf_agent_mcp_servers"
584
704
  })
585
705
  );
586
706
  return result;
587
707
  }
708
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
709
+ const authProvider = new DurableObjectOAuthClientProvider(
710
+ this.ctx.storage,
711
+ this.name,
712
+ callbackUrl
713
+ );
714
+ if (reconnect) {
715
+ authProvider.serverId = reconnect.id;
716
+ if (reconnect.oauthClientId) {
717
+ authProvider.clientId = reconnect.oauthClientId;
718
+ }
719
+ }
720
+ let headerTransportOpts = {};
721
+ if (options?.transport?.headers) {
722
+ headerTransportOpts = {
723
+ eventSourceInit: {
724
+ fetch: (url2, init) => fetch(url2, {
725
+ ...init,
726
+ headers: options?.transport?.headers
727
+ })
728
+ },
729
+ requestInit: {
730
+ headers: options?.transport?.headers
731
+ }
732
+ };
733
+ }
734
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
735
+ client: options?.client,
736
+ reconnect,
737
+ transport: {
738
+ ...headerTransportOpts,
739
+ authProvider
740
+ }
741
+ });
742
+ return {
743
+ authUrl,
744
+ clientId,
745
+ id
746
+ };
747
+ }
588
748
  async removeMcpServer(id) {
589
749
  this.mcp.closeConnection(id);
590
750
  this.sql`
@@ -592,83 +752,35 @@ var Agent = class extends Server {
592
752
  `;
593
753
  this.broadcast(
594
754
  JSON.stringify({
595
- type: "cf_agent_mcp_servers",
596
- mcp: __privateMethod(this, _Agent_instances, getMcpServerStateInternal_fn).call(this)
755
+ mcp: this.getMcpServers(),
756
+ type: "cf_agent_mcp_servers"
597
757
  })
598
758
  );
599
759
  }
600
- };
601
- _Agent_instances = new WeakSet();
602
- connectToMcpServerInternal_fn = async function(serverName, url, callbackUrl, options, reconnect) {
603
- const authProvider = new DurableObjectOAuthClientProvider(
604
- this.ctx.storage,
605
- this.name,
606
- callbackUrl
607
- );
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
625
- }
760
+ getMcpServers() {
761
+ const mcpState = {
762
+ prompts: this.mcp.listPrompts(),
763
+ resources: this.mcp.listResources(),
764
+ servers: {},
765
+ tools: this.mcp.listTools()
626
766
  };
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
- };
652
- };
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`
767
+ const servers = this.sql`
661
768
  SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
662
769
  `;
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
- };
770
+ for (const server of servers) {
771
+ const serverConn = this.mcp.mcpConnections[server.id];
772
+ mcpState.servers[server.id] = {
773
+ auth_url: server.auth_url,
774
+ capabilities: serverConn?.serverCapabilities ?? null,
775
+ instructions: serverConn?.instructions ?? null,
776
+ name: server.name,
777
+ server_url: server.server_url,
778
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
779
+ state: serverConn?.connectionState ?? "authenticating"
780
+ };
781
+ }
782
+ return mcpState;
670
783
  }
671
- return mcpState;
672
784
  };
673
785
  /**
674
786
  * Agent configuration options
@@ -680,9 +792,9 @@ Agent.options = {
680
792
  };
681
793
  async function routeAgentRequest(request, env, options) {
682
794
  const corsHeaders = options?.cors === true ? {
683
- "Access-Control-Allow-Origin": "*",
684
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
685
795
  "Access-Control-Allow-Credentials": "true",
796
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
797
+ "Access-Control-Allow-Origin": "*",
686
798
  "Access-Control-Max-Age": "86400"
687
799
  } : options?.cors;
688
800
  if (request.method === "OPTIONS") {
@@ -713,55 +825,80 @@ async function routeAgentRequest(request, env, options) {
713
825
  }
714
826
  return response;
715
827
  }
716
- async function routeAgentEmail(email, env, options) {
828
+ async function routeAgentEmail(_email, _env, _options) {
717
829
  }
718
830
  async function getAgentByName(namespace, name, options) {
719
831
  return getServerByName(namespace, name, options);
720
832
  }
721
833
  var StreamingResponse = class {
722
834
  constructor(connection, id) {
723
- this.closed = false;
724
- this.connection = connection;
725
- this.id = id;
835
+ this._closed = false;
836
+ this._connection = connection;
837
+ this._id = id;
726
838
  }
727
839
  /**
728
840
  * Send a chunk of data to the client
729
841
  * @param chunk The data to send
730
842
  */
731
843
  send(chunk) {
732
- if (this.closed) {
844
+ if (this._closed) {
733
845
  throw new Error("StreamingResponse is already closed");
734
846
  }
735
847
  const response = {
736
- type: "rpc",
737
- id: this.id,
738
- success: true,
848
+ done: false,
849
+ id: this._id,
739
850
  result: chunk,
740
- done: false
851
+ success: true,
852
+ type: "rpc"
741
853
  };
742
- this.connection.send(JSON.stringify(response));
854
+ this._connection.send(JSON.stringify(response));
743
855
  }
744
856
  /**
745
857
  * End the stream and send the final chunk (if any)
746
858
  * @param finalChunk Optional final chunk of data to send
747
859
  */
748
860
  end(finalChunk) {
749
- if (this.closed) {
861
+ if (this._closed) {
750
862
  throw new Error("StreamingResponse is already closed");
751
863
  }
752
- this.closed = true;
864
+ this._closed = true;
753
865
  const response = {
754
- type: "rpc",
755
- id: this.id,
756
- success: true,
866
+ done: true,
867
+ id: this._id,
757
868
  result: finalChunk,
758
- done: true
869
+ success: true,
870
+ type: "rpc"
759
871
  };
760
- this.connection.send(JSON.stringify(response));
872
+ this._connection.send(JSON.stringify(response));
873
+ }
874
+ };
875
+
876
+ // src/observability/index.ts
877
+ var genericObservability = {
878
+ emit(event) {
879
+ if (isLocalMode()) {
880
+ console.log(event.displayMessage);
881
+ return;
882
+ }
883
+ console.log(event);
761
884
  }
762
885
  };
886
+ var localMode = false;
887
+ function isLocalMode() {
888
+ if (localMode) {
889
+ return true;
890
+ }
891
+ const { request } = getCurrentAgent();
892
+ if (!request) {
893
+ return false;
894
+ }
895
+ const url = new URL(request.url);
896
+ localMode = url.hostname === "localhost";
897
+ return localMode;
898
+ }
763
899
 
764
900
  export {
901
+ genericObservability,
765
902
  unstable_callable,
766
903
  getCurrentAgent,
767
904
  Agent,
@@ -770,4 +907,4 @@ export {
770
907
  getAgentByName,
771
908
  StreamingResponse
772
909
  };
773
- //# sourceMappingURL=chunk-DMJ7L3FI.js.map
910
+ //# sourceMappingURL=chunk-JFRK72K3.js.map