agents 0.0.0-ca5cdf0 → 0.0.0-cb5957e

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 (74) hide show
  1. package/README.md +255 -27
  2. package/dist/_esm-LV5FJ3HK.js +3922 -0
  3. package/dist/_esm-LV5FJ3HK.js.map +1 -0
  4. package/dist/ai-chat-agent.d.ts +12 -7
  5. package/dist/ai-chat-agent.js +462 -48
  6. package/dist/ai-chat-agent.js.map +1 -1
  7. package/dist/ai-chat-v5-migration.d.ts +152 -0
  8. package/dist/ai-chat-v5-migration.js +20 -0
  9. package/dist/ai-chat-v5-migration.js.map +1 -0
  10. package/dist/ai-react.d.ts +68 -70
  11. package/dist/ai-react.js +252 -99
  12. package/dist/ai-react.js.map +1 -1
  13. package/dist/ai-types.d.ts +37 -19
  14. package/dist/ai-types.js +7 -0
  15. package/dist/ccip-CMBYN64O.js +15 -0
  16. package/dist/ccip-CMBYN64O.js.map +1 -0
  17. package/dist/chunk-254F4GDT.js +1343 -0
  18. package/dist/chunk-254F4GDT.js.map +1 -0
  19. package/dist/chunk-3OT2NNEW.js +941 -0
  20. package/dist/chunk-3OT2NNEW.js.map +1 -0
  21. package/dist/chunk-5Y6BEZDY.js +276 -0
  22. package/dist/chunk-5Y6BEZDY.js.map +1 -0
  23. package/dist/chunk-BER7KXUJ.js +18 -0
  24. package/dist/chunk-BER7KXUJ.js.map +1 -0
  25. package/dist/chunk-JJBFIGUC.js +5202 -0
  26. package/dist/chunk-JJBFIGUC.js.map +1 -0
  27. package/dist/chunk-PR4QN5HX.js +43 -0
  28. package/dist/chunk-PR4QN5HX.js.map +1 -0
  29. package/dist/{chunk-NKZZ66QY.js → chunk-QEVM4BVL.js} +5 -5
  30. package/dist/chunk-QEVM4BVL.js.map +1 -0
  31. package/dist/chunk-TYAY6AU6.js +159 -0
  32. package/dist/chunk-TYAY6AU6.js.map +1 -0
  33. package/dist/chunk-UJVEAURM.js +150 -0
  34. package/dist/chunk-UJVEAURM.js.map +1 -0
  35. package/dist/{chunk-767EASBA.js → chunk-Z44WASMA.js} +11 -3
  36. package/dist/chunk-Z44WASMA.js.map +1 -0
  37. package/dist/client-DVoPb3-C.d.ts +5120 -0
  38. package/dist/client.d.ts +2 -2
  39. package/dist/client.js +3 -1
  40. package/dist/codemode/ai.d.ts +25 -0
  41. package/dist/codemode/ai.js +5112 -0
  42. package/dist/codemode/ai.js.map +1 -0
  43. package/dist/index.d.ts +196 -51
  44. package/dist/index.js +14 -4
  45. package/dist/mcp/client.d.ts +10 -1053
  46. package/dist/mcp/client.js +2 -1
  47. package/dist/mcp/do-oauth-client-provider.d.ts +1 -0
  48. package/dist/mcp/do-oauth-client-provider.js +2 -1
  49. package/dist/mcp/index.d.ts +58 -63
  50. package/dist/mcp/index.js +953 -637
  51. package/dist/mcp/index.js.map +1 -1
  52. package/dist/mcp/x402.d.ts +39 -0
  53. package/dist/mcp/x402.js +3195 -0
  54. package/dist/mcp/x402.js.map +1 -0
  55. package/dist/mcp-BH1fJeiU.d.ts +58 -0
  56. package/dist/observability/index.d.ts +34 -0
  57. package/dist/observability/index.js +12 -0
  58. package/dist/observability/index.js.map +1 -0
  59. package/dist/react.d.ts +18 -10
  60. package/dist/react.js +107 -7
  61. package/dist/react.js.map +1 -1
  62. package/dist/schedule.d.ts +79 -5
  63. package/dist/schedule.js +17 -2
  64. package/dist/schedule.js.map +1 -1
  65. package/dist/secp256k1-M22GZP2U.js +2193 -0
  66. package/dist/secp256k1-M22GZP2U.js.map +1 -0
  67. package/package.json +38 -9
  68. package/src/index.ts +949 -175
  69. package/dist/chunk-4CIGD73X.js +0 -791
  70. package/dist/chunk-4CIGD73X.js.map +0 -1
  71. package/dist/chunk-767EASBA.js.map +0 -1
  72. package/dist/chunk-E3LCYPCB.js +0 -469
  73. package/dist/chunk-E3LCYPCB.js.map +0 -1
  74. package/dist/chunk-NKZZ66QY.js.map +0 -1
@@ -1,791 +0,0 @@
1
- import {
2
- MCPClientManager
3
- } from "./chunk-E3LCYPCB.js";
4
- import {
5
- DurableObjectOAuthClientProvider
6
- } from "./chunk-767EASBA.js";
7
- import {
8
- camelCaseToKebabCase
9
- } from "./chunk-NKZZ66QY.js";
10
-
11
- // src/index.ts
12
- import { AsyncLocalStorage } from "async_hooks";
13
- import { parseCronExpression } from "cron-schedule";
14
- import { nanoid } from "nanoid";
15
- import {
16
- getServerByName,
17
- routePartykitRequest,
18
- Server
19
- } from "partyserver";
20
- function isRPCRequest(msg) {
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
- }
23
- function isStateUpdateMessage(msg) {
24
- return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "cf_agent_state" && "state" in msg;
25
- }
26
- var callableMetadata = /* @__PURE__ */ new Map();
27
- function unstable_callable(metadata = {}) {
28
- return function callableDecorator(target, context) {
29
- if (!callableMetadata.has(target)) {
30
- callableMetadata.set(target, metadata);
31
- }
32
- return target;
33
- };
34
- }
35
- function getNextCronTime(cron) {
36
- const interval = parseCronExpression(cron);
37
- return interval.getNextDate();
38
- }
39
- var STATE_ROW_ID = "cf_state_row_id";
40
- var STATE_WAS_CHANGED = "cf_state_was_changed";
41
- var DEFAULT_STATE = {};
42
- var agentContext = new AsyncLocalStorage();
43
- function getCurrentAgent() {
44
- const store = agentContext.getStore();
45
- if (!store) {
46
- return {
47
- agent: void 0,
48
- connection: void 0,
49
- request: void 0
50
- };
51
- }
52
- return store;
53
- }
54
- var Agent = class extends Server {
55
- constructor(ctx, env) {
56
- super(ctx, env);
57
- this._state = DEFAULT_STATE;
58
- this._ParentClass = Object.getPrototypeOf(this).constructor;
59
- this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
60
- /**
61
- * Initial state for the Agent
62
- * Override to provide default state values
63
- */
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
- };
108
- this.sql`
109
- CREATE TABLE IF NOT EXISTS cf_agents_state (
110
- id TEXT PRIMARY KEY NOT NULL,
111
- state TEXT
112
- )
113
- `;
114
- void this.ctx.blockConcurrencyWhile(async () => {
115
- return this._tryCatch(async () => {
116
- this.sql`
117
- CREATE TABLE IF NOT EXISTS cf_agents_schedules (
118
- id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
119
- callback TEXT,
120
- payload TEXT,
121
- type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
122
- time INTEGER,
123
- delayInSeconds INTEGER,
124
- cron TEXT,
125
- created_at INTEGER DEFAULT (unixepoch())
126
- )
127
- `;
128
- await this.alarm();
129
- });
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
- `;
142
- const _onRequest = this.onRequest.bind(this);
143
- this.onRequest = (request) => {
144
- return agentContext.run(
145
- { agent: this, connection: void 0, request },
146
- async () => {
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));
161
- }
162
- );
163
- };
164
- const _onMessage = this.onMessage.bind(this);
165
- this.onMessage = async (connection, message) => {
166
- return agentContext.run(
167
- { agent: this, connection, request: void 0 },
168
- async () => {
169
- if (typeof message !== "string") {
170
- return this._tryCatch(() => _onMessage(connection, message));
171
- }
172
- let parsed;
173
- try {
174
- parsed = JSON.parse(message);
175
- } catch (_e) {
176
- return this._tryCatch(() => _onMessage(connection, message));
177
- }
178
- if (isStateUpdateMessage(parsed)) {
179
- this._setStateInternal(parsed.state, connection);
180
- return;
181
- }
182
- if (isRPCRequest(parsed)) {
183
- try {
184
- const { id, method, args } = parsed;
185
- const methodFn = this[method];
186
- if (typeof methodFn !== "function") {
187
- throw new Error(`Method ${method} does not exist`);
188
- }
189
- if (!this._isCallable(method)) {
190
- throw new Error(`Method ${method} is not callable`);
191
- }
192
- const metadata = callableMetadata.get(methodFn);
193
- if (metadata?.streaming) {
194
- const stream = new StreamingResponse(connection, id);
195
- await methodFn.apply(this, [stream, ...args]);
196
- return;
197
- }
198
- const result = await methodFn.apply(this, args);
199
- const response = {
200
- done: true,
201
- id,
202
- result,
203
- success: true,
204
- type: "rpc"
205
- };
206
- connection.send(JSON.stringify(response));
207
- } catch (e) {
208
- const response = {
209
- error: e instanceof Error ? e.message : "Unknown error occurred",
210
- id: parsed.id,
211
- success: false,
212
- type: "rpc"
213
- };
214
- connection.send(JSON.stringify(response));
215
- console.error("RPC error:", e);
216
- }
217
- return;
218
- }
219
- return this._tryCatch(() => _onMessage(connection, message));
220
- }
221
- );
222
- };
223
- const _onConnect = this.onConnect.bind(this);
224
- this.onConnect = (connection, ctx2) => {
225
- return agentContext.run(
226
- { agent: this, connection, request: ctx2.request },
227
- async () => {
228
- setTimeout(() => {
229
- if (this.state) {
230
- connection.send(
231
- JSON.stringify({
232
- state: this.state,
233
- type: "cf_agent_state"
234
- })
235
- );
236
- }
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));
244
- }, 20);
245
- }
246
- );
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
- Promise.allSettled(
257
- servers.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
- ).then((_results) => {
270
- this.broadcast(
271
- JSON.stringify({
272
- mcp: this.getMcpServers(),
273
- type: "cf_agent_mcp_servers"
274
- })
275
- );
276
- });
277
- await this._tryCatch(() => _onStart());
278
- }
279
- );
280
- };
281
- }
282
- /**
283
- * Current state of the Agent
284
- */
285
- get state() {
286
- if (this._state !== DEFAULT_STATE) {
287
- return this._state;
288
- }
289
- const wasChanged = this.sql`
290
- SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
291
- `;
292
- const result = this.sql`
293
- SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
294
- `;
295
- if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
296
- result[0]?.state) {
297
- const state = result[0]?.state;
298
- this._state = JSON.parse(state);
299
- return this._state;
300
- }
301
- if (this.initialState === DEFAULT_STATE) {
302
- return void 0;
303
- }
304
- this.setState(this.initialState);
305
- return this.initialState;
306
- }
307
- /**
308
- * Execute SQL queries against the Agent's database
309
- * @template T Type of the returned rows
310
- * @param strings SQL query template strings
311
- * @param values Values to be inserted into the query
312
- * @returns Array of query results
313
- */
314
- sql(strings, ...values) {
315
- let query = "";
316
- try {
317
- query = strings.reduce(
318
- (acc, str, i) => acc + str + (i < values.length ? "?" : ""),
319
- ""
320
- );
321
- return [...this.ctx.storage.sql.exec(query, ...values)];
322
- } catch (e) {
323
- console.error(`failed to execute sql query: ${query}`, e);
324
- throw this.onError(e);
325
- }
326
- }
327
- _setStateInternal(state, source = "server") {
328
- this._state = state;
329
- this.sql`
330
- INSERT OR REPLACE INTO cf_agents_state (id, state)
331
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
332
- `;
333
- this.sql`
334
- INSERT OR REPLACE INTO cf_agents_state (id, state)
335
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
336
- `;
337
- this.broadcast(
338
- JSON.stringify({
339
- state,
340
- type: "cf_agent_state"
341
- }),
342
- source !== "server" ? [source.id] : []
343
- );
344
- return this._tryCatch(() => {
345
- const { connection, request } = agentContext.getStore() || {};
346
- return agentContext.run(
347
- { agent: this, connection, request },
348
- async () => {
349
- return this.onStateUpdate(state, source);
350
- }
351
- );
352
- });
353
- }
354
- /**
355
- * Update the Agent's state
356
- * @param state New state to set
357
- */
358
- setState(state) {
359
- this._setStateInternal(state, "server");
360
- }
361
- /**
362
- * Called when the Agent's state is updated
363
- * @param state Updated state
364
- * @param source Source of the state update ("server" or a client connection)
365
- */
366
- // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
367
- onStateUpdate(state, source) {
368
- }
369
- /**
370
- * Called when the Agent receives an email
371
- * @param email Email message to process
372
- */
373
- // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
374
- onEmail(email) {
375
- return agentContext.run(
376
- { agent: this, connection: void 0, request: void 0 },
377
- async () => {
378
- console.error("onEmail not implemented");
379
- }
380
- );
381
- }
382
- async _tryCatch(fn) {
383
- try {
384
- return await fn();
385
- } catch (e) {
386
- throw this.onError(e);
387
- }
388
- }
389
- onError(connectionOrError, error) {
390
- let theError;
391
- if (connectionOrError && error) {
392
- theError = error;
393
- console.error(
394
- "Error on websocket connection:",
395
- connectionOrError.id,
396
- theError
397
- );
398
- console.error(
399
- "Override onError(connection, error) to handle websocket connection errors"
400
- );
401
- } else {
402
- theError = connectionOrError;
403
- console.error("Error on server:", theError);
404
- console.error("Override onError(error) to handle server errors");
405
- }
406
- throw theError;
407
- }
408
- /**
409
- * Render content (not implemented in base class)
410
- */
411
- render() {
412
- throw new Error("Not implemented");
413
- }
414
- /**
415
- * Schedule a task to be executed in the future
416
- * @template T Type of the payload data
417
- * @param when When to execute the task (Date, seconds delay, or cron expression)
418
- * @param callback Name of the method to call
419
- * @param payload Data to pass to the callback
420
- * @returns Schedule object representing the scheduled task
421
- */
422
- async schedule(when, callback, payload) {
423
- const id = nanoid(9);
424
- if (typeof callback !== "string") {
425
- throw new Error("Callback must be a string");
426
- }
427
- if (typeof this[callback] !== "function") {
428
- throw new Error(`this.${callback} is not a function`);
429
- }
430
- if (when instanceof Date) {
431
- const timestamp = Math.floor(when.getTime() / 1e3);
432
- this.sql`
433
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
434
- VALUES (${id}, ${callback}, ${JSON.stringify(
435
- payload
436
- )}, 'scheduled', ${timestamp})
437
- `;
438
- await this._scheduleNextAlarm();
439
- return {
440
- callback,
441
- id,
442
- payload,
443
- time: timestamp,
444
- type: "scheduled"
445
- };
446
- }
447
- if (typeof when === "number") {
448
- const time = new Date(Date.now() + when * 1e3);
449
- const timestamp = Math.floor(time.getTime() / 1e3);
450
- this.sql`
451
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
452
- VALUES (${id}, ${callback}, ${JSON.stringify(
453
- payload
454
- )}, 'delayed', ${when}, ${timestamp})
455
- `;
456
- await this._scheduleNextAlarm();
457
- return {
458
- callback,
459
- delayInSeconds: when,
460
- id,
461
- payload,
462
- time: timestamp,
463
- type: "delayed"
464
- };
465
- }
466
- if (typeof when === "string") {
467
- const nextExecutionTime = getNextCronTime(when);
468
- const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
469
- this.sql`
470
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
471
- VALUES (${id}, ${callback}, ${JSON.stringify(
472
- payload
473
- )}, 'cron', ${when}, ${timestamp})
474
- `;
475
- await this._scheduleNextAlarm();
476
- return {
477
- callback,
478
- cron: when,
479
- id,
480
- payload,
481
- time: timestamp,
482
- type: "cron"
483
- };
484
- }
485
- throw new Error("Invalid schedule type");
486
- }
487
- /**
488
- * Get a scheduled task by ID
489
- * @template T Type of the payload data
490
- * @param id ID of the scheduled task
491
- * @returns The Schedule object or undefined if not found
492
- */
493
- async getSchedule(id) {
494
- const result = this.sql`
495
- SELECT * FROM cf_agents_schedules WHERE id = ${id}
496
- `;
497
- if (!result) {
498
- console.error(`schedule ${id} not found`);
499
- return void 0;
500
- }
501
- return { ...result[0], payload: JSON.parse(result[0].payload) };
502
- }
503
- /**
504
- * Get scheduled tasks matching the given criteria
505
- * @template T Type of the payload data
506
- * @param criteria Criteria to filter schedules
507
- * @returns Array of matching Schedule objects
508
- */
509
- getSchedules(criteria = {}) {
510
- let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
511
- const params = [];
512
- if (criteria.id) {
513
- query += " AND id = ?";
514
- params.push(criteria.id);
515
- }
516
- if (criteria.type) {
517
- query += " AND type = ?";
518
- params.push(criteria.type);
519
- }
520
- if (criteria.timeRange) {
521
- query += " AND time >= ? AND time <= ?";
522
- const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
523
- const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
524
- params.push(
525
- Math.floor(start.getTime() / 1e3),
526
- Math.floor(end.getTime() / 1e3)
527
- );
528
- }
529
- const result = this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
530
- ...row,
531
- payload: JSON.parse(row.payload)
532
- }));
533
- return result;
534
- }
535
- /**
536
- * Cancel a scheduled task
537
- * @param id ID of the task to cancel
538
- * @returns true if the task was cancelled, false otherwise
539
- */
540
- async cancelSchedule(id) {
541
- this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
542
- await this._scheduleNextAlarm();
543
- return true;
544
- }
545
- async _scheduleNextAlarm() {
546
- const result = this.sql`
547
- SELECT time FROM cf_agents_schedules
548
- WHERE time > ${Math.floor(Date.now() / 1e3)}
549
- ORDER BY time ASC
550
- LIMIT 1
551
- `;
552
- if (!result) return;
553
- if (result.length > 0 && "time" in result[0]) {
554
- const nextTime = result[0].time * 1e3;
555
- await this.ctx.storage.setAlarm(nextTime);
556
- }
557
- }
558
- /**
559
- * Destroy the Agent, removing all state and scheduled tasks
560
- */
561
- async destroy() {
562
- this.sql`DROP TABLE IF EXISTS cf_agents_state`;
563
- this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
564
- this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
565
- await this.ctx.storage.deleteAlarm();
566
- await this.ctx.storage.deleteAll();
567
- this.ctx.abort("destroyed");
568
- }
569
- /**
570
- * Get all methods marked as callable on this Agent
571
- * @returns A map of method names to their metadata
572
- */
573
- _isCallable(method) {
574
- return callableMetadata.has(this[method]);
575
- }
576
- /**
577
- * Connect to a new MCP Server
578
- *
579
- * @param url MCP Server SSE URL
580
- * @param callbackHost Base host for the agent, used for the redirect URI.
581
- * @param agentsPrefix agents routing prefix if not using `agents`
582
- * @param options MCP client and transport (header) options
583
- * @returns authUrl
584
- */
585
- async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
586
- const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
587
- const result = await this._connectToMcpServerInternal(
588
- serverName,
589
- url,
590
- callbackUrl,
591
- options
592
- );
593
- this.sql`
594
- INSERT
595
- OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
596
- VALUES (
597
- ${result.id},
598
- ${serverName},
599
- ${url},
600
- ${result.clientId ?? null},
601
- ${result.authUrl ?? null},
602
- ${callbackUrl},
603
- ${options ? JSON.stringify(options) : null}
604
- );
605
- `;
606
- this.broadcast(
607
- JSON.stringify({
608
- mcp: this.getMcpServers(),
609
- type: "cf_agent_mcp_servers"
610
- })
611
- );
612
- return result;
613
- }
614
- async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
615
- const authProvider = new DurableObjectOAuthClientProvider(
616
- this.ctx.storage,
617
- this.name,
618
- callbackUrl
619
- );
620
- if (reconnect) {
621
- authProvider.serverId = reconnect.id;
622
- if (reconnect.oauthClientId) {
623
- authProvider.clientId = reconnect.oauthClientId;
624
- }
625
- }
626
- let headerTransportOpts = {};
627
- if (options?.transport?.headers) {
628
- headerTransportOpts = {
629
- eventSourceInit: {
630
- fetch: (url2, init) => fetch(url2, {
631
- ...init,
632
- headers: options?.transport?.headers
633
- })
634
- },
635
- requestInit: {
636
- headers: options?.transport?.headers
637
- }
638
- };
639
- }
640
- const { id, authUrl, clientId } = await this.mcp.connect(url, {
641
- client: options?.client,
642
- reconnect,
643
- transport: {
644
- ...headerTransportOpts,
645
- authProvider
646
- }
647
- });
648
- return {
649
- authUrl,
650
- clientId,
651
- id
652
- };
653
- }
654
- async removeMcpServer(id) {
655
- this.mcp.closeConnection(id);
656
- this.sql`
657
- DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
658
- `;
659
- this.broadcast(
660
- JSON.stringify({
661
- mcp: this.getMcpServers(),
662
- type: "cf_agent_mcp_servers"
663
- })
664
- );
665
- }
666
- getMcpServers() {
667
- const mcpState = {
668
- prompts: this.mcp.listPrompts(),
669
- resources: this.mcp.listResources(),
670
- servers: {},
671
- tools: this.mcp.listTools()
672
- };
673
- const servers = this.sql`
674
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
675
- `;
676
- for (const server of servers) {
677
- const serverConn = this.mcp.mcpConnections[server.id];
678
- mcpState.servers[server.id] = {
679
- auth_url: server.auth_url,
680
- capabilities: serverConn?.serverCapabilities ?? null,
681
- instructions: serverConn?.instructions ?? null,
682
- name: server.name,
683
- server_url: server.server_url,
684
- // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
685
- state: serverConn?.connectionState ?? "authenticating"
686
- };
687
- }
688
- return mcpState;
689
- }
690
- };
691
- /**
692
- * Agent configuration options
693
- */
694
- Agent.options = {
695
- /** Whether the Agent should hibernate when inactive */
696
- hibernate: true
697
- // default to hibernate
698
- };
699
- async function routeAgentRequest(request, env, options) {
700
- const corsHeaders = options?.cors === true ? {
701
- "Access-Control-Allow-Credentials": "true",
702
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
703
- "Access-Control-Allow-Origin": "*",
704
- "Access-Control-Max-Age": "86400"
705
- } : options?.cors;
706
- if (request.method === "OPTIONS") {
707
- if (corsHeaders) {
708
- return new Response(null, {
709
- headers: corsHeaders
710
- });
711
- }
712
- console.warn(
713
- "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
714
- );
715
- }
716
- let response = await routePartykitRequest(
717
- request,
718
- env,
719
- {
720
- prefix: "agents",
721
- ...options
722
- }
723
- );
724
- if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
725
- response = new Response(response.body, {
726
- headers: {
727
- ...response.headers,
728
- ...corsHeaders
729
- }
730
- });
731
- }
732
- return response;
733
- }
734
- async function routeAgentEmail(_email, _env, _options) {
735
- }
736
- async function getAgentByName(namespace, name, options) {
737
- return getServerByName(namespace, name, options);
738
- }
739
- var StreamingResponse = class {
740
- constructor(connection, id) {
741
- this._closed = false;
742
- this._connection = connection;
743
- this._id = id;
744
- }
745
- /**
746
- * Send a chunk of data to the client
747
- * @param chunk The data to send
748
- */
749
- send(chunk) {
750
- if (this._closed) {
751
- throw new Error("StreamingResponse is already closed");
752
- }
753
- const response = {
754
- done: false,
755
- id: this._id,
756
- result: chunk,
757
- success: true,
758
- type: "rpc"
759
- };
760
- this._connection.send(JSON.stringify(response));
761
- }
762
- /**
763
- * End the stream and send the final chunk (if any)
764
- * @param finalChunk Optional final chunk of data to send
765
- */
766
- end(finalChunk) {
767
- if (this._closed) {
768
- throw new Error("StreamingResponse is already closed");
769
- }
770
- this._closed = true;
771
- const response = {
772
- done: true,
773
- id: this._id,
774
- result: finalChunk,
775
- success: true,
776
- type: "rpc"
777
- };
778
- this._connection.send(JSON.stringify(response));
779
- }
780
- };
781
-
782
- export {
783
- unstable_callable,
784
- getCurrentAgent,
785
- Agent,
786
- routeAgentRequest,
787
- routeAgentEmail,
788
- getAgentByName,
789
- StreamingResponse
790
- };
791
- //# sourceMappingURL=chunk-4CIGD73X.js.map