agents 0.0.0-d6a4eda → 0.0.0-d6d6d60

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 (77) hide show
  1. package/README.md +255 -27
  2. package/dist/ai-chat-agent.d.ts +20 -17
  3. package/dist/ai-chat-agent.js +532 -222
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-DBHGW4Hv.js +155 -0
  6. package/dist/ai-chat-v5-migration-DBHGW4Hv.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +73 -84
  10. package/dist/ai-react.js +266 -199
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-B3aQaFv3.js +20 -0
  13. package/dist/ai-types-B3aQaFv3.js.map +1 -0
  14. package/dist/ai-types-D5YoPrBZ.d.ts +95 -0
  15. package/dist/ai-types.d.ts +6 -74
  16. package/dist/ai-types.js +3 -1
  17. package/dist/cli.d.ts +8 -0
  18. package/dist/cli.js +27 -0
  19. package/dist/cli.js.map +1 -0
  20. package/dist/client-BfiZ3HQd.js +117 -0
  21. package/dist/client-BfiZ3HQd.js.map +1 -0
  22. package/dist/client-Bws9q38u.d.ts +5427 -0
  23. package/dist/client-CbWe9FBd.d.ts +104 -0
  24. package/dist/client-DvK0u9vD.js +898 -0
  25. package/dist/client-DvK0u9vD.js.map +1 -0
  26. package/dist/client.d.ts +12 -87
  27. package/dist/client.js +4 -11
  28. package/dist/codemode/ai.d.ts +27 -0
  29. package/dist/codemode/ai.js +151 -0
  30. package/dist/codemode/ai.js.map +1 -0
  31. package/dist/do-oauth-client-provider-CcTno-25.d.ts +142 -0
  32. package/dist/do-oauth-client-provider-D2P1lSft.js +93 -0
  33. package/dist/do-oauth-client-provider-D2P1lSft.js.map +1 -0
  34. package/dist/index-Bdzb2feZ.d.ts +572 -0
  35. package/dist/index-DhJCaDWd.d.ts +58 -0
  36. package/dist/index.d.ts +62 -392
  37. package/dist/index.js +7 -22
  38. package/dist/mcp/client.d.ts +4 -783
  39. package/dist/mcp/client.js +4 -9
  40. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  41. package/dist/mcp/do-oauth-client-provider.js +3 -7
  42. package/dist/mcp/index.d.ts +190 -81
  43. package/dist/mcp/index.js +1428 -767
  44. package/dist/mcp/index.js.map +1 -1
  45. package/dist/mcp/x402.d.ts +34 -0
  46. package/dist/mcp/x402.js +194 -0
  47. package/dist/mcp/x402.js.map +1 -0
  48. package/dist/mcp-Dw5vDrY8.d.ts +61 -0
  49. package/dist/observability/index.d.ts +3 -0
  50. package/dist/observability/index.js +7 -0
  51. package/dist/react-DFNXTQzy.d.ts +113 -0
  52. package/dist/react.d.ts +10 -53
  53. package/dist/react.js +183 -100
  54. package/dist/react.js.map +1 -1
  55. package/dist/schedule.d.ts +89 -12
  56. package/dist/schedule.js +46 -21
  57. package/dist/schedule.js.map +1 -1
  58. package/dist/serializable-CymX8ovI.d.ts +39 -0
  59. package/dist/serializable.d.ts +7 -0
  60. package/dist/serializable.js +1 -0
  61. package/dist/src-C1WWpbRo.js +1247 -0
  62. package/dist/src-C1WWpbRo.js.map +1 -0
  63. package/package.json +125 -71
  64. package/dist/ai-types.js.map +0 -1
  65. package/dist/chunk-BZXOAZUX.js +0 -106
  66. package/dist/chunk-BZXOAZUX.js.map +0 -1
  67. package/dist/chunk-QSGN3REV.js +0 -123
  68. package/dist/chunk-QSGN3REV.js.map +0 -1
  69. package/dist/chunk-RIYR6FR6.js +0 -777
  70. package/dist/chunk-RIYR6FR6.js.map +0 -1
  71. package/dist/chunk-Y67CHZBI.js +0 -464
  72. package/dist/chunk-Y67CHZBI.js.map +0 -1
  73. package/dist/client.js.map +0 -1
  74. package/dist/index.js.map +0 -1
  75. package/dist/mcp/client.js.map +0 -1
  76. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  77. package/src/index.ts +0 -1243
@@ -1,777 +0,0 @@
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";
10
-
11
- // src/index.ts
12
- import {
13
- Server,
14
- routePartykitRequest,
15
- getServerByName
16
- } from "partyserver";
17
- import { parseCronExpression } from "cron-schedule";
18
- import { nanoid } from "nanoid";
19
- import { AsyncLocalStorage } from "node:async_hooks";
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
- type: "cf_agent_mcp_servers",
152
- mcp: this._getMcpServerStateInternal()
153
- })
154
- );
155
- return new Response("<script>window.close();</script>", {
156
- status: 200,
157
- headers: { "content-type": "text/html" }
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
- type: "rpc",
201
- id,
202
- success: true,
203
- result,
204
- done: true
205
- };
206
- connection.send(JSON.stringify(response));
207
- } catch (e) {
208
- const response = {
209
- type: "rpc",
210
- id: parsed.id,
211
- success: false,
212
- error: e instanceof Error ? e.message : "Unknown error occurred"
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
- type: "cf_agent_state",
233
- state: this.state
234
- })
235
- );
236
- }
237
- connection.send(
238
- JSON.stringify({
239
- type: "cf_agent_mcp_servers",
240
- mcp: this._getMcpServerStateInternal()
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
- await 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
- );
270
- this.broadcast(
271
- JSON.stringify({
272
- type: "cf_agent_mcp_servers",
273
- mcp: this._getMcpServerStateInternal()
274
- })
275
- );
276
- await this._tryCatch(() => _onStart());
277
- }
278
- );
279
- };
280
- }
281
- /**
282
- * Current state of the Agent
283
- */
284
- get state() {
285
- if (this._state !== DEFAULT_STATE) {
286
- return this._state;
287
- }
288
- const wasChanged = this.sql`
289
- SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
290
- `;
291
- const result = this.sql`
292
- SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
293
- `;
294
- if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
295
- result[0]?.state) {
296
- const state = result[0]?.state;
297
- this._state = JSON.parse(state);
298
- return this._state;
299
- }
300
- if (this.initialState === DEFAULT_STATE) {
301
- return void 0;
302
- }
303
- this.setState(this.initialState);
304
- return this.initialState;
305
- }
306
- /**
307
- * Execute SQL queries against the Agent's database
308
- * @template T Type of the returned rows
309
- * @param strings SQL query template strings
310
- * @param values Values to be inserted into the query
311
- * @returns Array of query results
312
- */
313
- sql(strings, ...values) {
314
- let query = "";
315
- try {
316
- query = strings.reduce(
317
- (acc, str, i) => acc + str + (i < values.length ? "?" : ""),
318
- ""
319
- );
320
- return [...this.ctx.storage.sql.exec(query, ...values)];
321
- } catch (e) {
322
- console.error(`failed to execute sql query: ${query}`, e);
323
- throw this.onError(e);
324
- }
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
- }
353
- /**
354
- * Update the Agent's state
355
- * @param state New state to set
356
- */
357
- setState(state) {
358
- this._setStateInternal(state, "server");
359
- }
360
- /**
361
- * Called when the Agent's state is updated
362
- * @param state Updated state
363
- * @param source Source of the state update ("server" or a client connection)
364
- */
365
- onStateUpdate(state, source) {
366
- }
367
- /**
368
- * Called when the Agent receives an email
369
- * @param email Email message to process
370
- */
371
- onEmail(email) {
372
- return agentContext.run(
373
- { agent: this, connection: void 0, request: void 0 },
374
- async () => {
375
- console.error("onEmail not implemented");
376
- }
377
- );
378
- }
379
- async _tryCatch(fn) {
380
- try {
381
- return await fn();
382
- } catch (e) {
383
- throw this.onError(e);
384
- }
385
- }
386
- onError(connectionOrError, error) {
387
- let theError;
388
- if (connectionOrError && error) {
389
- theError = error;
390
- console.error(
391
- "Error on websocket connection:",
392
- connectionOrError.id,
393
- theError
394
- );
395
- console.error(
396
- "Override onError(connection, error) to handle websocket connection errors"
397
- );
398
- } else {
399
- theError = connectionOrError;
400
- console.error("Error on server:", theError);
401
- console.error("Override onError(error) to handle server errors");
402
- }
403
- throw theError;
404
- }
405
- /**
406
- * Render content (not implemented in base class)
407
- */
408
- render() {
409
- throw new Error("Not implemented");
410
- }
411
- /**
412
- * Schedule a task to be executed in the future
413
- * @template T Type of the payload data
414
- * @param when When to execute the task (Date, seconds delay, or cron expression)
415
- * @param callback Name of the method to call
416
- * @param payload Data to pass to the callback
417
- * @returns Schedule object representing the scheduled task
418
- */
419
- async schedule(when, callback, payload) {
420
- const id = nanoid(9);
421
- if (typeof callback !== "string") {
422
- throw new Error("Callback must be a string");
423
- }
424
- if (typeof this[callback] !== "function") {
425
- throw new Error(`this.${callback} is not a function`);
426
- }
427
- if (when instanceof Date) {
428
- const timestamp = Math.floor(when.getTime() / 1e3);
429
- this.sql`
430
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
431
- VALUES (${id}, ${callback}, ${JSON.stringify(
432
- payload
433
- )}, 'scheduled', ${timestamp})
434
- `;
435
- await this._scheduleNextAlarm();
436
- return {
437
- id,
438
- callback,
439
- payload,
440
- time: timestamp,
441
- type: "scheduled"
442
- };
443
- }
444
- if (typeof when === "number") {
445
- const time = new Date(Date.now() + when * 1e3);
446
- const timestamp = Math.floor(time.getTime() / 1e3);
447
- this.sql`
448
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
449
- VALUES (${id}, ${callback}, ${JSON.stringify(
450
- payload
451
- )}, 'delayed', ${when}, ${timestamp})
452
- `;
453
- await this._scheduleNextAlarm();
454
- return {
455
- id,
456
- callback,
457
- payload,
458
- delayInSeconds: when,
459
- time: timestamp,
460
- type: "delayed"
461
- };
462
- }
463
- if (typeof when === "string") {
464
- const nextExecutionTime = getNextCronTime(when);
465
- const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
466
- this.sql`
467
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
468
- VALUES (${id}, ${callback}, ${JSON.stringify(
469
- payload
470
- )}, 'cron', ${when}, ${timestamp})
471
- `;
472
- await this._scheduleNextAlarm();
473
- return {
474
- id,
475
- callback,
476
- payload,
477
- cron: when,
478
- time: timestamp,
479
- type: "cron"
480
- };
481
- }
482
- throw new Error("Invalid schedule type");
483
- }
484
- /**
485
- * Get a scheduled task by ID
486
- * @template T Type of the payload data
487
- * @param id ID of the scheduled task
488
- * @returns The Schedule object or undefined if not found
489
- */
490
- async getSchedule(id) {
491
- const result = this.sql`
492
- SELECT * FROM cf_agents_schedules WHERE id = ${id}
493
- `;
494
- if (!result) {
495
- console.error(`schedule ${id} not found`);
496
- return void 0;
497
- }
498
- return { ...result[0], payload: JSON.parse(result[0].payload) };
499
- }
500
- /**
501
- * Get scheduled tasks matching the given criteria
502
- * @template T Type of the payload data
503
- * @param criteria Criteria to filter schedules
504
- * @returns Array of matching Schedule objects
505
- */
506
- getSchedules(criteria = {}) {
507
- let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
508
- const params = [];
509
- if (criteria.id) {
510
- query += " AND id = ?";
511
- params.push(criteria.id);
512
- }
513
- if (criteria.type) {
514
- query += " AND type = ?";
515
- params.push(criteria.type);
516
- }
517
- if (criteria.timeRange) {
518
- query += " AND time >= ? AND time <= ?";
519
- const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
520
- const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
521
- params.push(
522
- Math.floor(start.getTime() / 1e3),
523
- Math.floor(end.getTime() / 1e3)
524
- );
525
- }
526
- const result = this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
527
- ...row,
528
- payload: JSON.parse(row.payload)
529
- }));
530
- return result;
531
- }
532
- /**
533
- * Cancel a scheduled task
534
- * @param id ID of the task to cancel
535
- * @returns true if the task was cancelled, false otherwise
536
- */
537
- async cancelSchedule(id) {
538
- this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
539
- await this._scheduleNextAlarm();
540
- return true;
541
- }
542
- async _scheduleNextAlarm() {
543
- const result = this.sql`
544
- SELECT time FROM cf_agents_schedules
545
- WHERE time > ${Math.floor(Date.now() / 1e3)}
546
- ORDER BY time ASC
547
- LIMIT 1
548
- `;
549
- if (!result) return;
550
- if (result.length > 0 && "time" in result[0]) {
551
- const nextTime = result[0].time * 1e3;
552
- await this.ctx.storage.setAlarm(nextTime);
553
- }
554
- }
555
- /**
556
- * Destroy the Agent, removing all state and scheduled tasks
557
- */
558
- async destroy() {
559
- this.sql`DROP TABLE IF EXISTS cf_agents_state`;
560
- this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
561
- this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
562
- await this.ctx.storage.deleteAlarm();
563
- await this.ctx.storage.deleteAll();
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 this._connectToMcpServerInternal(
580
- serverName,
581
- url,
582
- callbackUrl,
583
- options
584
- );
585
- this.broadcast(
586
- JSON.stringify({
587
- type: "cf_agent_mcp_servers",
588
- mcp: this._getMcpServerStateInternal()
589
- })
590
- );
591
- return result;
592
- }
593
- async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
594
- const authProvider = new DurableObjectOAuthClientProvider(
595
- this.ctx.storage,
596
- this.name,
597
- callbackUrl
598
- );
599
- if (reconnect) {
600
- authProvider.serverId = reconnect.id;
601
- if (reconnect.oauthClientId) {
602
- authProvider.clientId = reconnect.oauthClientId;
603
- }
604
- }
605
- let headerTransportOpts = {};
606
- if (options?.transport?.headers) {
607
- headerTransportOpts = {
608
- eventSourceInit: {
609
- fetch: (url2, init) => fetch(url2, {
610
- ...init,
611
- headers: options?.transport?.headers
612
- })
613
- },
614
- requestInit: {
615
- headers: options?.transport?.headers
616
- }
617
- };
618
- }
619
- const { id, authUrl, clientId } = await this.mcp.connect(url, {
620
- reconnect,
621
- transport: {
622
- ...headerTransportOpts,
623
- authProvider
624
- },
625
- client: options?.client
626
- });
627
- this.sql`
628
- INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
629
- VALUES (
630
- ${id},
631
- ${serverName},
632
- ${url},
633
- ${clientId ?? null},
634
- ${authUrl ?? null},
635
- ${callbackUrl},
636
- ${options ? JSON.stringify(options) : null}
637
- );
638
- `;
639
- return {
640
- id,
641
- authUrl
642
- };
643
- }
644
- async removeMcpServer(id) {
645
- this.mcp.closeConnection(id);
646
- this.sql`
647
- DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
648
- `;
649
- this.broadcast(
650
- JSON.stringify({
651
- type: "cf_agent_mcp_servers",
652
- mcp: this._getMcpServerStateInternal()
653
- })
654
- );
655
- }
656
- _getMcpServerStateInternal() {
657
- const mcpState = {
658
- servers: {},
659
- tools: this.mcp.listTools(),
660
- prompts: this.mcp.listPrompts(),
661
- resources: this.mcp.listResources()
662
- };
663
- const servers = this.sql`
664
- SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
665
- `;
666
- for (const server of servers) {
667
- mcpState.servers[server.id] = {
668
- name: server.name,
669
- server_url: server.server_url,
670
- auth_url: server.auth_url,
671
- state: this.mcp.mcpConnections[server.id].connectionState
672
- };
673
- }
674
- return mcpState;
675
- }
676
- };
677
- /**
678
- * Agent configuration options
679
- */
680
- Agent.options = {
681
- /** Whether the Agent should hibernate when inactive */
682
- hibernate: true
683
- // default to hibernate
684
- };
685
- async function routeAgentRequest(request, env, options) {
686
- const corsHeaders = options?.cors === true ? {
687
- "Access-Control-Allow-Origin": "*",
688
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
689
- "Access-Control-Allow-Credentials": "true",
690
- "Access-Control-Max-Age": "86400"
691
- } : options?.cors;
692
- if (request.method === "OPTIONS") {
693
- if (corsHeaders) {
694
- return new Response(null, {
695
- headers: corsHeaders
696
- });
697
- }
698
- console.warn(
699
- "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
700
- );
701
- }
702
- let response = await routePartykitRequest(
703
- request,
704
- env,
705
- {
706
- prefix: "agents",
707
- ...options
708
- }
709
- );
710
- if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
711
- response = new Response(response.body, {
712
- headers: {
713
- ...response.headers,
714
- ...corsHeaders
715
- }
716
- });
717
- }
718
- return response;
719
- }
720
- async function routeAgentEmail(email, env, options) {
721
- }
722
- async function getAgentByName(namespace, name, options) {
723
- return getServerByName(namespace, name, options);
724
- }
725
- var StreamingResponse = class {
726
- constructor(connection, id) {
727
- this._closed = false;
728
- this._connection = connection;
729
- this._id = id;
730
- }
731
- /**
732
- * Send a chunk of data to the client
733
- * @param chunk The data to send
734
- */
735
- send(chunk) {
736
- if (this._closed) {
737
- throw new Error("StreamingResponse is already closed");
738
- }
739
- const response = {
740
- type: "rpc",
741
- id: this._id,
742
- success: true,
743
- result: chunk,
744
- done: false
745
- };
746
- this._connection.send(JSON.stringify(response));
747
- }
748
- /**
749
- * End the stream and send the final chunk (if any)
750
- * @param finalChunk Optional final chunk of data to send
751
- */
752
- end(finalChunk) {
753
- if (this._closed) {
754
- throw new Error("StreamingResponse is already closed");
755
- }
756
- this._closed = true;
757
- const response = {
758
- type: "rpc",
759
- id: this._id,
760
- success: true,
761
- result: finalChunk,
762
- done: true
763
- };
764
- this._connection.send(JSON.stringify(response));
765
- }
766
- };
767
-
768
- export {
769
- unstable_callable,
770
- getCurrentAgent,
771
- Agent,
772
- routeAgentRequest,
773
- routeAgentEmail,
774
- getAgentByName,
775
- StreamingResponse
776
- };
777
- //# sourceMappingURL=chunk-RIYR6FR6.js.map