agents 0.0.0-dd6a9e3 → 0.0.0-df41827

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 (46) hide show
  1. package/dist/ai-chat-agent.d.ts +50 -4
  2. package/dist/ai-chat-agent.js +150 -79
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-react.d.ts +17 -4
  5. package/dist/ai-react.js +62 -48
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/ai-types.d.ts +5 -0
  8. package/dist/chunk-767EASBA.js +106 -0
  9. package/dist/chunk-767EASBA.js.map +1 -0
  10. package/dist/chunk-E3LCYPCB.js +469 -0
  11. package/dist/chunk-E3LCYPCB.js.map +1 -0
  12. package/dist/chunk-NKZZ66QY.js +116 -0
  13. package/dist/chunk-NKZZ66QY.js.map +1 -0
  14. package/dist/chunk-ZRRXJUAA.js +788 -0
  15. package/dist/chunk-ZRRXJUAA.js.map +1 -0
  16. package/dist/client.d.ts +15 -1
  17. package/dist/client.js +6 -133
  18. package/dist/client.js.map +1 -1
  19. package/dist/index.d.ts +125 -16
  20. package/dist/index.js +6 -4
  21. package/dist/mcp/client.d.ts +783 -0
  22. package/dist/mcp/client.js +9 -0
  23. package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
  24. package/dist/mcp/do-oauth-client-provider.js +7 -0
  25. package/dist/mcp/do-oauth-client-provider.js.map +1 -0
  26. package/dist/mcp/index.d.ts +84 -0
  27. package/dist/mcp/index.js +783 -0
  28. package/dist/mcp/index.js.map +1 -0
  29. package/dist/react.d.ts +85 -5
  30. package/dist/react.js +50 -31
  31. package/dist/react.js.map +1 -1
  32. package/dist/schedule.d.ts +2 -2
  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 +79 -51
  39. package/src/index.ts +516 -149
  40. package/dist/chunk-HMLY7DHA.js +0 -16
  41. package/dist/chunk-X6BBKLSC.js +0 -568
  42. package/dist/chunk-X6BBKLSC.js.map +0 -1
  43. package/dist/mcp.d.ts +0 -58
  44. package/dist/mcp.js +0 -945
  45. package/dist/mcp.js.map +0 -1
  46. /package/dist/{chunk-HMLY7DHA.js.map → mcp/client.js.map} +0 -0
@@ -0,0 +1,788 @@
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
+ await Promise.allSettled(
257
+ servers.filter((server) => server.auth_url === null).map((server) => {
258
+ return this._connectToMcpServerInternal(
259
+ server.name,
260
+ server.server_url,
261
+ server.callback_url,
262
+ server.server_options ? JSON.parse(server.server_options) : void 0,
263
+ {
264
+ id: server.id,
265
+ oauthClientId: server.client_id ?? void 0
266
+ }
267
+ );
268
+ })
269
+ );
270
+ this.broadcast(
271
+ JSON.stringify({
272
+ mcp: this.getMcpServers(),
273
+ type: "cf_agent_mcp_servers"
274
+ })
275
+ );
276
+ await this._tryCatch(() => _onStart());
277
+ }
278
+ );
279
+ };
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
+ state,
339
+ type: "cf_agent_state"
340
+ }),
341
+ source !== "server" ? [source.id] : []
342
+ );
343
+ return this._tryCatch(() => {
344
+ const { connection, request } = agentContext.getStore() || {};
345
+ return agentContext.run(
346
+ { agent: this, connection, request },
347
+ async () => {
348
+ return this.onStateUpdate(state, source);
349
+ }
350
+ );
351
+ });
352
+ }
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
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
366
+ onStateUpdate(state, source) {
367
+ }
368
+ /**
369
+ * Called when the Agent receives an email
370
+ * @param email Email message to process
371
+ */
372
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later
373
+ onEmail(email) {
374
+ return agentContext.run(
375
+ { agent: this, connection: void 0, request: void 0 },
376
+ async () => {
377
+ console.error("onEmail not implemented");
378
+ }
379
+ );
380
+ }
381
+ async _tryCatch(fn) {
382
+ try {
383
+ return await fn();
384
+ } catch (e) {
385
+ throw this.onError(e);
386
+ }
387
+ }
388
+ onError(connectionOrError, error) {
389
+ let theError;
390
+ if (connectionOrError && error) {
391
+ theError = error;
392
+ console.error(
393
+ "Error on websocket connection:",
394
+ connectionOrError.id,
395
+ theError
396
+ );
397
+ console.error(
398
+ "Override onError(connection, error) to handle websocket connection errors"
399
+ );
400
+ } else {
401
+ theError = connectionOrError;
402
+ console.error("Error on server:", theError);
403
+ console.error("Override onError(error) to handle server errors");
404
+ }
405
+ throw theError;
406
+ }
407
+ /**
408
+ * Render content (not implemented in base class)
409
+ */
410
+ render() {
411
+ throw new Error("Not implemented");
412
+ }
413
+ /**
414
+ * Schedule a task to be executed in the future
415
+ * @template T Type of the payload data
416
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
417
+ * @param callback Name of the method to call
418
+ * @param payload Data to pass to the callback
419
+ * @returns Schedule object representing the scheduled task
420
+ */
421
+ async schedule(when, callback, payload) {
422
+ const id = nanoid(9);
423
+ if (typeof callback !== "string") {
424
+ throw new Error("Callback must be a string");
425
+ }
426
+ if (typeof this[callback] !== "function") {
427
+ throw new Error(`this.${callback} is not a function`);
428
+ }
429
+ if (when instanceof Date) {
430
+ const timestamp = Math.floor(when.getTime() / 1e3);
431
+ this.sql`
432
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
433
+ VALUES (${id}, ${callback}, ${JSON.stringify(
434
+ payload
435
+ )}, 'scheduled', ${timestamp})
436
+ `;
437
+ await this._scheduleNextAlarm();
438
+ return {
439
+ callback,
440
+ id,
441
+ payload,
442
+ time: timestamp,
443
+ type: "scheduled"
444
+ };
445
+ }
446
+ if (typeof when === "number") {
447
+ const time = new Date(Date.now() + when * 1e3);
448
+ const timestamp = Math.floor(time.getTime() / 1e3);
449
+ this.sql`
450
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
451
+ VALUES (${id}, ${callback}, ${JSON.stringify(
452
+ payload
453
+ )}, 'delayed', ${when}, ${timestamp})
454
+ `;
455
+ await this._scheduleNextAlarm();
456
+ return {
457
+ callback,
458
+ delayInSeconds: when,
459
+ id,
460
+ payload,
461
+ time: timestamp,
462
+ type: "delayed"
463
+ };
464
+ }
465
+ if (typeof when === "string") {
466
+ const nextExecutionTime = getNextCronTime(when);
467
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
468
+ this.sql`
469
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
470
+ VALUES (${id}, ${callback}, ${JSON.stringify(
471
+ payload
472
+ )}, 'cron', ${when}, ${timestamp})
473
+ `;
474
+ await this._scheduleNextAlarm();
475
+ return {
476
+ callback,
477
+ cron: when,
478
+ id,
479
+ payload,
480
+ time: timestamp,
481
+ type: "cron"
482
+ };
483
+ }
484
+ throw new Error("Invalid schedule type");
485
+ }
486
+ /**
487
+ * Get a scheduled task by ID
488
+ * @template T Type of the payload data
489
+ * @param id ID of the scheduled task
490
+ * @returns The Schedule object or undefined if not found
491
+ */
492
+ async getSchedule(id) {
493
+ const result = this.sql`
494
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
495
+ `;
496
+ if (!result) {
497
+ console.error(`schedule ${id} not found`);
498
+ return void 0;
499
+ }
500
+ return { ...result[0], payload: JSON.parse(result[0].payload) };
501
+ }
502
+ /**
503
+ * Get scheduled tasks matching the given criteria
504
+ * @template T Type of the payload data
505
+ * @param criteria Criteria to filter schedules
506
+ * @returns Array of matching Schedule objects
507
+ */
508
+ getSchedules(criteria = {}) {
509
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
510
+ const params = [];
511
+ if (criteria.id) {
512
+ query += " AND id = ?";
513
+ params.push(criteria.id);
514
+ }
515
+ if (criteria.type) {
516
+ query += " AND type = ?";
517
+ params.push(criteria.type);
518
+ }
519
+ if (criteria.timeRange) {
520
+ query += " AND time >= ? AND time <= ?";
521
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
522
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
523
+ params.push(
524
+ Math.floor(start.getTime() / 1e3),
525
+ Math.floor(end.getTime() / 1e3)
526
+ );
527
+ }
528
+ const result = this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
529
+ ...row,
530
+ payload: JSON.parse(row.payload)
531
+ }));
532
+ return result;
533
+ }
534
+ /**
535
+ * Cancel a scheduled task
536
+ * @param id ID of the task to cancel
537
+ * @returns true if the task was cancelled, false otherwise
538
+ */
539
+ async cancelSchedule(id) {
540
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
541
+ await this._scheduleNextAlarm();
542
+ return true;
543
+ }
544
+ async _scheduleNextAlarm() {
545
+ const result = this.sql`
546
+ SELECT time FROM cf_agents_schedules
547
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
548
+ ORDER BY time ASC
549
+ LIMIT 1
550
+ `;
551
+ if (!result) return;
552
+ if (result.length > 0 && "time" in result[0]) {
553
+ const nextTime = result[0].time * 1e3;
554
+ await this.ctx.storage.setAlarm(nextTime);
555
+ }
556
+ }
557
+ /**
558
+ * Destroy the Agent, removing all state and scheduled tasks
559
+ */
560
+ async destroy() {
561
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
562
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
563
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
564
+ await this.ctx.storage.deleteAlarm();
565
+ await this.ctx.storage.deleteAll();
566
+ this.ctx.abort("destroyed");
567
+ }
568
+ /**
569
+ * Get all methods marked as callable on this Agent
570
+ * @returns A map of method names to their metadata
571
+ */
572
+ _isCallable(method) {
573
+ return callableMetadata.has(this[method]);
574
+ }
575
+ /**
576
+ * Connect to a new MCP Server
577
+ *
578
+ * @param url MCP Server SSE URL
579
+ * @param callbackHost Base host for the agent, used for the redirect URI.
580
+ * @param agentsPrefix agents routing prefix if not using `agents`
581
+ * @param options MCP client and transport (header) options
582
+ * @returns authUrl
583
+ */
584
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
585
+ const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
586
+ const result = await this._connectToMcpServerInternal(
587
+ serverName,
588
+ url,
589
+ callbackUrl,
590
+ options
591
+ );
592
+ this.broadcast(
593
+ JSON.stringify({
594
+ mcp: this.getMcpServers(),
595
+ type: "cf_agent_mcp_servers"
596
+ })
597
+ );
598
+ return result;
599
+ }
600
+ async _connectToMcpServerInternal(serverName, url, callbackUrl, options, reconnect) {
601
+ const authProvider = new DurableObjectOAuthClientProvider(
602
+ this.ctx.storage,
603
+ this.name,
604
+ callbackUrl
605
+ );
606
+ if (reconnect) {
607
+ authProvider.serverId = reconnect.id;
608
+ if (reconnect.oauthClientId) {
609
+ authProvider.clientId = reconnect.oauthClientId;
610
+ }
611
+ }
612
+ let headerTransportOpts = {};
613
+ if (options?.transport?.headers) {
614
+ headerTransportOpts = {
615
+ eventSourceInit: {
616
+ fetch: (url2, init) => fetch(url2, {
617
+ ...init,
618
+ headers: options?.transport?.headers
619
+ })
620
+ },
621
+ requestInit: {
622
+ headers: options?.transport?.headers
623
+ }
624
+ };
625
+ }
626
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
627
+ client: options?.client,
628
+ reconnect,
629
+ transport: {
630
+ ...headerTransportOpts,
631
+ authProvider
632
+ }
633
+ });
634
+ this.sql`
635
+ INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
636
+ VALUES (
637
+ ${id},
638
+ ${serverName},
639
+ ${url},
640
+ ${clientId ?? null},
641
+ ${authUrl ?? null},
642
+ ${callbackUrl},
643
+ ${options ? JSON.stringify(options) : null}
644
+ );
645
+ `;
646
+ return {
647
+ authUrl,
648
+ id
649
+ };
650
+ }
651
+ async removeMcpServer(id) {
652
+ this.mcp.closeConnection(id);
653
+ this.sql`
654
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
655
+ `;
656
+ this.broadcast(
657
+ JSON.stringify({
658
+ mcp: this.getMcpServers(),
659
+ type: "cf_agent_mcp_servers"
660
+ })
661
+ );
662
+ }
663
+ getMcpServers() {
664
+ const mcpState = {
665
+ prompts: this.mcp.listPrompts(),
666
+ resources: this.mcp.listResources(),
667
+ servers: {},
668
+ tools: this.mcp.listTools()
669
+ };
670
+ const servers = this.sql`
671
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
672
+ `;
673
+ for (const server of servers) {
674
+ const serverConn = this.mcp.mcpConnections[server.id];
675
+ mcpState.servers[server.id] = {
676
+ auth_url: server.auth_url,
677
+ capabilities: serverConn?.serverCapabilities ?? null,
678
+ instructions: serverConn?.instructions ?? null,
679
+ name: server.name,
680
+ server_url: server.server_url,
681
+ // mark as "authenticating" because the server isn't automatically connected, so it's pending authenticating
682
+ state: serverConn?.connectionState ?? "authenticating"
683
+ };
684
+ }
685
+ return mcpState;
686
+ }
687
+ };
688
+ /**
689
+ * Agent configuration options
690
+ */
691
+ Agent.options = {
692
+ /** Whether the Agent should hibernate when inactive */
693
+ hibernate: true
694
+ // default to hibernate
695
+ };
696
+ async function routeAgentRequest(request, env, options) {
697
+ const corsHeaders = options?.cors === true ? {
698
+ "Access-Control-Allow-Credentials": "true",
699
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
700
+ "Access-Control-Allow-Origin": "*",
701
+ "Access-Control-Max-Age": "86400"
702
+ } : options?.cors;
703
+ if (request.method === "OPTIONS") {
704
+ if (corsHeaders) {
705
+ return new Response(null, {
706
+ headers: corsHeaders
707
+ });
708
+ }
709
+ console.warn(
710
+ "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
711
+ );
712
+ }
713
+ let response = await routePartykitRequest(
714
+ request,
715
+ env,
716
+ {
717
+ prefix: "agents",
718
+ ...options
719
+ }
720
+ );
721
+ if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
722
+ response = new Response(response.body, {
723
+ headers: {
724
+ ...response.headers,
725
+ ...corsHeaders
726
+ }
727
+ });
728
+ }
729
+ return response;
730
+ }
731
+ async function routeAgentEmail(_email, _env, _options) {
732
+ }
733
+ async function getAgentByName(namespace, name, options) {
734
+ return getServerByName(namespace, name, options);
735
+ }
736
+ var StreamingResponse = class {
737
+ constructor(connection, id) {
738
+ this._closed = false;
739
+ this._connection = connection;
740
+ this._id = id;
741
+ }
742
+ /**
743
+ * Send a chunk of data to the client
744
+ * @param chunk The data to send
745
+ */
746
+ send(chunk) {
747
+ if (this._closed) {
748
+ throw new Error("StreamingResponse is already closed");
749
+ }
750
+ const response = {
751
+ done: false,
752
+ id: this._id,
753
+ result: chunk,
754
+ success: true,
755
+ type: "rpc"
756
+ };
757
+ this._connection.send(JSON.stringify(response));
758
+ }
759
+ /**
760
+ * End the stream and send the final chunk (if any)
761
+ * @param finalChunk Optional final chunk of data to send
762
+ */
763
+ end(finalChunk) {
764
+ if (this._closed) {
765
+ throw new Error("StreamingResponse is already closed");
766
+ }
767
+ this._closed = true;
768
+ const response = {
769
+ done: true,
770
+ id: this._id,
771
+ result: finalChunk,
772
+ success: true,
773
+ type: "rpc"
774
+ };
775
+ this._connection.send(JSON.stringify(response));
776
+ }
777
+ };
778
+
779
+ export {
780
+ unstable_callable,
781
+ getCurrentAgent,
782
+ Agent,
783
+ routeAgentRequest,
784
+ routeAgentEmail,
785
+ getAgentByName,
786
+ StreamingResponse
787
+ };
788
+ //# sourceMappingURL=chunk-ZRRXJUAA.js.map