hono-agents 2.0.3 → 2.0.4

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.
package/dist/index.js CHANGED
@@ -1,43 +1,1940 @@
1
- // src/index.ts
2
- import { routeAgentRequest } from "agents";
1
+ import { createRequire } from "node:module";
2
+ import { nanoid } from "nanoid";
3
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
+ import { ElicitRequestSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
5
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
6
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
7
+ import "partysocket";
8
+ import { AsyncLocalStorage } from "node:async_hooks";
9
+ import { parseCronExpression } from "cron-schedule";
10
+ import "cloudflare:email";
11
+ import { Server, routePartykitRequest } from "partyserver";
3
12
  import { env } from "hono/adapter";
4
13
  import { createMiddleware } from "hono/factory";
14
+
15
+ //#region ../agents/dist/client-WbaRgKYN.js
16
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
17
+ function toDisposable(fn) {
18
+ return { dispose: fn };
19
+ }
20
+ var DisposableStore = class {
21
+ constructor() {
22
+ this._items = [];
23
+ }
24
+ add(d) {
25
+ this._items.push(d);
26
+ return d;
27
+ }
28
+ dispose() {
29
+ while (this._items.length) try {
30
+ this._items.pop().dispose();
31
+ } catch {}
32
+ }
33
+ };
34
+ var Emitter = class {
35
+ constructor() {
36
+ this._listeners = /* @__PURE__ */ new Set();
37
+ this.event = (listener) => {
38
+ this._listeners.add(listener);
39
+ return toDisposable(() => this._listeners.delete(listener));
40
+ };
41
+ }
42
+ fire(data) {
43
+ for (const listener of [...this._listeners]) try {
44
+ listener(data);
45
+ } catch (err) {
46
+ console.error("Emitter listener error:", err);
47
+ }
48
+ }
49
+ dispose() {
50
+ this._listeners.clear();
51
+ }
52
+ };
53
+ function toErrorMessage(error) {
54
+ return error instanceof Error ? error.message : String(error);
55
+ }
56
+ function isUnauthorized(error) {
57
+ const msg = toErrorMessage(error);
58
+ return msg.includes("Unauthorized") || msg.includes("401");
59
+ }
60
+ function isTransportNotImplemented(error) {
61
+ const msg = toErrorMessage(error);
62
+ return msg.includes("404") || msg.includes("405") || msg.includes("Not Implemented") || msg.includes("not implemented");
63
+ }
64
+ var SSEEdgeClientTransport = class extends SSEClientTransport {
65
+ /**
66
+ * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment
67
+ */
68
+ constructor(url, options) {
69
+ const fetchOverride = async (fetchUrl, fetchInit = {}) => {
70
+ const headers = await this.authHeaders();
71
+ const workerOptions = {
72
+ ...fetchInit,
73
+ headers: {
74
+ ...options.requestInit?.headers,
75
+ ...fetchInit?.headers,
76
+ ...headers
77
+ }
78
+ };
79
+ delete workerOptions.mode;
80
+ return options.eventSourceInit?.fetch?.(fetchUrl, workerOptions) || fetch(fetchUrl, workerOptions);
81
+ };
82
+ super(url, {
83
+ ...options,
84
+ eventSourceInit: {
85
+ ...options.eventSourceInit,
86
+ fetch: fetchOverride
87
+ }
88
+ });
89
+ this.authProvider = options.authProvider;
90
+ }
91
+ async authHeaders() {
92
+ if (this.authProvider) {
93
+ const tokens = await this.authProvider.tokens();
94
+ if (tokens) return { Authorization: `Bearer ${tokens.access_token}` };
95
+ }
96
+ }
97
+ };
98
+ var StreamableHTTPEdgeClientTransport = class extends StreamableHTTPClientTransport {
99
+ /**
100
+ * Creates a new StreamableHTTPEdgeClientTransport, which overrides fetch to be compatible with the CF workers environment
101
+ */
102
+ constructor(url, options) {
103
+ const fetchOverride = async (fetchUrl, fetchInit = {}) => {
104
+ const headers = await this.authHeaders();
105
+ const workerOptions = {
106
+ ...fetchInit,
107
+ headers: {
108
+ ...options.requestInit?.headers,
109
+ ...fetchInit?.headers,
110
+ ...headers
111
+ }
112
+ };
113
+ delete workerOptions.mode;
114
+ return options.requestInit?.fetch?.(fetchUrl, workerOptions) || fetch(fetchUrl, workerOptions);
115
+ };
116
+ super(url, {
117
+ ...options,
118
+ requestInit: {
119
+ ...options.requestInit,
120
+ fetch: fetchOverride
121
+ }
122
+ });
123
+ this.authProvider = options.authProvider;
124
+ }
125
+ async authHeaders() {
126
+ if (this.authProvider) {
127
+ const tokens = await this.authProvider.tokens();
128
+ if (tokens) return { Authorization: `Bearer ${tokens.access_token}` };
129
+ }
130
+ }
131
+ };
132
+ var MCPClientConnection = class {
133
+ constructor(url, info, options = {
134
+ client: {},
135
+ transport: {}
136
+ }) {
137
+ this.url = url;
138
+ this.options = options;
139
+ this.connectionState = "connecting";
140
+ this.tools = [];
141
+ this.prompts = [];
142
+ this.resources = [];
143
+ this.resourceTemplates = [];
144
+ this._onObservabilityEvent = new Emitter();
145
+ this.onObservabilityEvent = this._onObservabilityEvent.event;
146
+ this.client = new Client(info, {
147
+ ...options.client,
148
+ capabilities: {
149
+ ...options.client?.capabilities,
150
+ elicitation: {}
151
+ }
152
+ });
153
+ }
154
+ /**
155
+ * Initialize a client connection
156
+ *
157
+ * @returns
158
+ */
159
+ async init() {
160
+ const transportType = this.options.transport.type;
161
+ if (!transportType) throw new Error("Transport type must be specified");
162
+ try {
163
+ await this.tryConnect(transportType);
164
+ } catch (e) {
165
+ if (isUnauthorized(e)) {
166
+ this.connectionState = "authenticating";
167
+ return;
168
+ }
169
+ this._onObservabilityEvent.fire({
170
+ type: "mcp:client:connect",
171
+ displayMessage: `Connection initialization failed for ${this.url.toString()}`,
172
+ payload: {
173
+ url: this.url.toString(),
174
+ transport: transportType,
175
+ state: this.connectionState,
176
+ error: toErrorMessage(e)
177
+ },
178
+ timestamp: Date.now(),
179
+ id: nanoid()
180
+ });
181
+ this.connectionState = "failed";
182
+ return;
183
+ }
184
+ await this.discoverAndRegister();
185
+ }
186
+ /**
187
+ * Finish OAuth by probing transports based on configured type.
188
+ * - Explicit: finish on that transport
189
+ * - Auto: try streamable-http, then sse on 404/405/Not Implemented
190
+ */
191
+ async finishAuthProbe(code) {
192
+ if (!this.options.transport.authProvider) throw new Error("No auth provider configured");
193
+ const configuredType = this.options.transport.type;
194
+ if (!configuredType) throw new Error("Transport type must be specified");
195
+ const finishAuth = async (base) => {
196
+ await this.getTransport(base).finishAuth(code);
197
+ };
198
+ if (configuredType === "sse" || configuredType === "streamable-http") {
199
+ await finishAuth(configuredType);
200
+ return;
201
+ }
202
+ try {
203
+ await finishAuth("streamable-http");
204
+ } catch (e) {
205
+ if (isTransportNotImplemented(e)) {
206
+ await finishAuth("sse");
207
+ return;
208
+ }
209
+ throw e;
210
+ }
211
+ }
212
+ /**
213
+ * Complete OAuth authorization
214
+ */
215
+ async completeAuthorization(code) {
216
+ if (this.connectionState !== "authenticating") throw new Error("Connection must be in authenticating state to complete authorization");
217
+ try {
218
+ await this.finishAuthProbe(code);
219
+ this.connectionState = "connecting";
220
+ } catch (error) {
221
+ this.connectionState = "failed";
222
+ throw error;
223
+ }
224
+ }
225
+ /**
226
+ * Establish connection after successful authorization
227
+ */
228
+ async establishConnection() {
229
+ if (this.connectionState !== "connecting") throw new Error("Connection must be in connecting state to establish connection");
230
+ try {
231
+ const transportType = this.options.transport.type;
232
+ if (!transportType) throw new Error("Transport type must be specified");
233
+ await this.tryConnect(transportType);
234
+ await this.discoverAndRegister();
235
+ } catch (error) {
236
+ this.connectionState = "failed";
237
+ throw error;
238
+ }
239
+ }
240
+ /**
241
+ * Discover server capabilities and register tools, resources, prompts, and templates
242
+ */
243
+ async discoverAndRegister() {
244
+ this.connectionState = "discovering";
245
+ this.serverCapabilities = this.client.getServerCapabilities();
246
+ if (!this.serverCapabilities) throw new Error("The MCP Server failed to return server capabilities");
247
+ const [instructionsResult, toolsResult, resourcesResult, promptsResult, resourceTemplatesResult] = await Promise.allSettled([
248
+ this.client.getInstructions(),
249
+ this.registerTools(),
250
+ this.registerResources(),
251
+ this.registerPrompts(),
252
+ this.registerResourceTemplates()
253
+ ]);
254
+ const operations = [
255
+ {
256
+ name: "instructions",
257
+ result: instructionsResult
258
+ },
259
+ {
260
+ name: "tools",
261
+ result: toolsResult
262
+ },
263
+ {
264
+ name: "resources",
265
+ result: resourcesResult
266
+ },
267
+ {
268
+ name: "prompts",
269
+ result: promptsResult
270
+ },
271
+ {
272
+ name: "resource templates",
273
+ result: resourceTemplatesResult
274
+ }
275
+ ];
276
+ for (const { name, result } of operations) if (result.status === "rejected") {
277
+ const url = this.url.toString();
278
+ this._onObservabilityEvent.fire({
279
+ type: "mcp:client:discover",
280
+ displayMessage: `Failed to discover ${name} for ${url}`,
281
+ payload: {
282
+ url,
283
+ capability: name,
284
+ error: result.reason
285
+ },
286
+ timestamp: Date.now(),
287
+ id: nanoid()
288
+ });
289
+ }
290
+ this.instructions = instructionsResult.status === "fulfilled" ? instructionsResult.value : void 0;
291
+ this.tools = toolsResult.status === "fulfilled" ? toolsResult.value : [];
292
+ this.resources = resourcesResult.status === "fulfilled" ? resourcesResult.value : [];
293
+ this.prompts = promptsResult.status === "fulfilled" ? promptsResult.value : [];
294
+ this.resourceTemplates = resourceTemplatesResult.status === "fulfilled" ? resourceTemplatesResult.value : [];
295
+ this.connectionState = "ready";
296
+ }
297
+ /**
298
+ * Notification handler registration
299
+ */
300
+ async registerTools() {
301
+ if (!this.serverCapabilities || !this.serverCapabilities.tools) return [];
302
+ if (this.serverCapabilities.tools.listChanged) this.client.setNotificationHandler(ToolListChangedNotificationSchema, async (_notification) => {
303
+ this.tools = await this.fetchTools();
304
+ });
305
+ return this.fetchTools();
306
+ }
307
+ async registerResources() {
308
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) return [];
309
+ if (this.serverCapabilities.resources.listChanged) this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_notification) => {
310
+ this.resources = await this.fetchResources();
311
+ });
312
+ return this.fetchResources();
313
+ }
314
+ async registerPrompts() {
315
+ if (!this.serverCapabilities || !this.serverCapabilities.prompts) return [];
316
+ if (this.serverCapabilities.prompts.listChanged) this.client.setNotificationHandler(PromptListChangedNotificationSchema, async (_notification) => {
317
+ this.prompts = await this.fetchPrompts();
318
+ });
319
+ return this.fetchPrompts();
320
+ }
321
+ async registerResourceTemplates() {
322
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) return [];
323
+ return this.fetchResourceTemplates();
324
+ }
325
+ async fetchTools() {
326
+ let toolsAgg = [];
327
+ let toolsResult = { tools: [] };
328
+ do {
329
+ toolsResult = await this.client.listTools({ cursor: toolsResult.nextCursor }).catch(this._capabilityErrorHandler({ tools: [] }, "tools/list"));
330
+ toolsAgg = toolsAgg.concat(toolsResult.tools);
331
+ } while (toolsResult.nextCursor);
332
+ return toolsAgg;
333
+ }
334
+ async fetchResources() {
335
+ let resourcesAgg = [];
336
+ let resourcesResult = { resources: [] };
337
+ do {
338
+ resourcesResult = await this.client.listResources({ cursor: resourcesResult.nextCursor }).catch(this._capabilityErrorHandler({ resources: [] }, "resources/list"));
339
+ resourcesAgg = resourcesAgg.concat(resourcesResult.resources);
340
+ } while (resourcesResult.nextCursor);
341
+ return resourcesAgg;
342
+ }
343
+ async fetchPrompts() {
344
+ let promptsAgg = [];
345
+ let promptsResult = { prompts: [] };
346
+ do {
347
+ promptsResult = await this.client.listPrompts({ cursor: promptsResult.nextCursor }).catch(this._capabilityErrorHandler({ prompts: [] }, "prompts/list"));
348
+ promptsAgg = promptsAgg.concat(promptsResult.prompts);
349
+ } while (promptsResult.nextCursor);
350
+ return promptsAgg;
351
+ }
352
+ async fetchResourceTemplates() {
353
+ let templatesAgg = [];
354
+ let templatesResult = { resourceTemplates: [] };
355
+ do {
356
+ templatesResult = await this.client.listResourceTemplates({ cursor: templatesResult.nextCursor }).catch(this._capabilityErrorHandler({ resourceTemplates: [] }, "resources/templates/list"));
357
+ templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);
358
+ } while (templatesResult.nextCursor);
359
+ return templatesAgg;
360
+ }
361
+ /**
362
+ * Handle elicitation request from server
363
+ * Automatically uses the Agent's built-in elicitation handling if available
364
+ */
365
+ async handleElicitationRequest(_request) {
366
+ throw new Error("Elicitation handler must be implemented for your platform. Override handleElicitationRequest method.");
367
+ }
368
+ /**
369
+ * Get the transport for the client
370
+ * @param transportType - The transport type to get
371
+ * @returns The transport for the client
372
+ */
373
+ getTransport(transportType) {
374
+ switch (transportType) {
375
+ case "streamable-http": return new StreamableHTTPEdgeClientTransport(this.url, this.options.transport);
376
+ case "sse": return new SSEEdgeClientTransport(this.url, this.options.transport);
377
+ default: throw new Error(`Unsupported transport type: ${transportType}`);
378
+ }
379
+ }
380
+ async tryConnect(transportType) {
381
+ const transports = transportType === "auto" ? ["streamable-http", "sse"] : [transportType];
382
+ for (const currentTransportType of transports) {
383
+ const isLastTransport = currentTransportType === transports[transports.length - 1];
384
+ const hasFallback = transportType === "auto" && currentTransportType === "streamable-http" && !isLastTransport;
385
+ const transport = this.getTransport(currentTransportType);
386
+ try {
387
+ await this.client.connect(transport);
388
+ this.lastConnectedTransport = currentTransportType;
389
+ const url = this.url.toString();
390
+ this._onObservabilityEvent.fire({
391
+ type: "mcp:client:connect",
392
+ displayMessage: `Connected successfully using ${currentTransportType} transport for ${url}`,
393
+ payload: {
394
+ url,
395
+ transport: currentTransportType,
396
+ state: this.connectionState
397
+ },
398
+ timestamp: Date.now(),
399
+ id: nanoid()
400
+ });
401
+ break;
402
+ } catch (e) {
403
+ const error = e instanceof Error ? e : new Error(String(e));
404
+ if (isUnauthorized(error)) throw e;
405
+ if (hasFallback && isTransportNotImplemented(error)) {
406
+ const url = this.url.toString();
407
+ this._onObservabilityEvent.fire({
408
+ type: "mcp:client:connect",
409
+ displayMessage: `${currentTransportType} transport not available, trying ${transports[transports.indexOf(currentTransportType) + 1]} for ${url}`,
410
+ payload: {
411
+ url,
412
+ transport: currentTransportType,
413
+ state: this.connectionState
414
+ },
415
+ timestamp: Date.now(),
416
+ id: nanoid()
417
+ });
418
+ continue;
419
+ }
420
+ throw e;
421
+ }
422
+ }
423
+ this.client.setRequestHandler(ElicitRequestSchema, async (request) => {
424
+ return await this.handleElicitationRequest(request);
425
+ });
426
+ }
427
+ _capabilityErrorHandler(empty, method) {
428
+ return (e) => {
429
+ if (e.code === -32601) {
430
+ const url = this.url.toString();
431
+ this._onObservabilityEvent.fire({
432
+ type: "mcp:client:discover",
433
+ displayMessage: `The server advertised support for the capability ${method.split("/")[0]}, but returned "Method not found" for '${method}' for ${url}`,
434
+ payload: {
435
+ url,
436
+ capability: method.split("/")[0],
437
+ error: toErrorMessage(e)
438
+ },
439
+ timestamp: Date.now(),
440
+ id: nanoid()
441
+ });
442
+ return empty;
443
+ }
444
+ throw e;
445
+ };
446
+ }
447
+ };
448
+ let jsonSchemaFn;
449
+ function getJsonSchema() {
450
+ if (!jsonSchemaFn) {
451
+ const { jsonSchema } = __require("ai");
452
+ jsonSchemaFn = jsonSchema;
453
+ }
454
+ return jsonSchemaFn;
455
+ }
456
+ /**
457
+ * Utility class that aggregates multiple MCP clients into one
458
+ */
459
+ var MCPClientManager = class {
460
+ /**
461
+ * @param _name Name of the MCP client
462
+ * @param _version Version of the MCP Client
463
+ * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
464
+ */
465
+ constructor(_name, _version) {
466
+ this._name = _name;
467
+ this._version = _version;
468
+ this.mcpConnections = {};
469
+ this._callbackUrls = [];
470
+ this._didWarnAboutUnstableGetAITools = false;
471
+ this._connectionDisposables = /* @__PURE__ */ new Map();
472
+ this._onObservabilityEvent = new Emitter();
473
+ this.onObservabilityEvent = this._onObservabilityEvent.event;
474
+ this._onConnected = new Emitter();
475
+ this.onConnected = this._onConnected.event;
476
+ }
477
+ /**
478
+ * Connect to and register an MCP server
479
+ *
480
+ * @param transportConfig Transport config
481
+ * @param clientConfig Client config
482
+ * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
483
+ */
484
+ async connect(url, options = {}) {
485
+ const id = options.reconnect?.id ?? nanoid(8);
486
+ if (options.transport?.authProvider) {
487
+ options.transport.authProvider.serverId = id;
488
+ if (options.reconnect?.oauthClientId) options.transport.authProvider.clientId = options.reconnect?.oauthClientId;
489
+ }
490
+ if (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {
491
+ const normalizedTransport = {
492
+ ...options.transport,
493
+ type: options.transport?.type ?? "auto"
494
+ };
495
+ this.mcpConnections[id] = new MCPClientConnection(new URL(url), {
496
+ name: this._name,
497
+ version: this._version
498
+ }, {
499
+ client: options.client ?? {},
500
+ transport: normalizedTransport
501
+ });
502
+ const store = new DisposableStore();
503
+ const existing = this._connectionDisposables.get(id);
504
+ if (existing) existing.dispose();
505
+ this._connectionDisposables.set(id, store);
506
+ store.add(this.mcpConnections[id].onObservabilityEvent((event) => {
507
+ this._onObservabilityEvent.fire(event);
508
+ }));
509
+ }
510
+ await this.mcpConnections[id].init();
511
+ if (options.reconnect?.oauthCode) try {
512
+ await this.mcpConnections[id].completeAuthorization(options.reconnect.oauthCode);
513
+ await this.mcpConnections[id].establishConnection();
514
+ } catch (error) {
515
+ this._onObservabilityEvent.fire({
516
+ type: "mcp:client:connect",
517
+ displayMessage: `Failed to complete OAuth reconnection for ${id} for ${url}`,
518
+ payload: {
519
+ url,
520
+ transport: options.transport?.type ?? "auto",
521
+ state: this.mcpConnections[id].connectionState,
522
+ error: toErrorMessage(error)
523
+ },
524
+ timestamp: Date.now(),
525
+ id
526
+ });
527
+ throw error;
528
+ }
529
+ const authUrl = options.transport?.authProvider?.authUrl;
530
+ if (this.mcpConnections[id].connectionState === "authenticating" && authUrl && options.transport?.authProvider?.redirectUrl) {
531
+ this._callbackUrls.push(options.transport.authProvider.redirectUrl.toString());
532
+ return {
533
+ authUrl,
534
+ clientId: options.transport?.authProvider?.clientId,
535
+ id
536
+ };
537
+ }
538
+ return { id };
539
+ }
540
+ isCallbackRequest(req) {
541
+ return req.method === "GET" && !!this._callbackUrls.find((url) => {
542
+ return req.url.startsWith(url);
543
+ });
544
+ }
545
+ async handleCallbackRequest(req) {
546
+ const url = new URL(req.url);
547
+ const urlMatch = this._callbackUrls.find((url$1) => {
548
+ return req.url.startsWith(url$1);
549
+ });
550
+ if (!urlMatch) throw new Error(`No callback URI match found for the request url: ${req.url}. Was the request matched with \`isCallbackRequest()\`?`);
551
+ const code = url.searchParams.get("code");
552
+ const state = url.searchParams.get("state");
553
+ const urlParams = urlMatch.split("/");
554
+ const serverId = urlParams[urlParams.length - 1];
555
+ if (!code) throw new Error("Unauthorized: no code provided");
556
+ if (!state) throw new Error("Unauthorized: no state provided");
557
+ if (this.mcpConnections[serverId] === void 0) throw new Error(`Could not find serverId: ${serverId}`);
558
+ if (this.mcpConnections[serverId].connectionState !== "authenticating") throw new Error("Failed to authenticate: the client isn't in the `authenticating` state");
559
+ const conn = this.mcpConnections[serverId];
560
+ if (!conn.options.transport.authProvider) throw new Error("Trying to finalize authentication for a server connection without an authProvider");
561
+ const clientId = conn.options.transport.authProvider.clientId || state;
562
+ conn.options.transport.authProvider.clientId = clientId;
563
+ conn.options.transport.authProvider.serverId = serverId;
564
+ try {
565
+ await conn.completeAuthorization(code);
566
+ return {
567
+ serverId,
568
+ authSuccess: true
569
+ };
570
+ } catch (error) {
571
+ return {
572
+ serverId,
573
+ authSuccess: false,
574
+ authError: error instanceof Error ? error.message : String(error)
575
+ };
576
+ }
577
+ }
578
+ /**
579
+ * Establish connection in the background after OAuth completion
580
+ * This method is called asynchronously and doesn't block the OAuth callback response
581
+ * @param serverId The server ID to establish connection for
582
+ */
583
+ async establishConnection(serverId) {
584
+ const conn = this.mcpConnections[serverId];
585
+ if (!conn) {
586
+ this._onObservabilityEvent.fire({
587
+ type: "mcp:client:preconnect",
588
+ displayMessage: `Connection not found for serverId: ${serverId}`,
589
+ payload: { serverId },
590
+ timestamp: Date.now(),
591
+ id: nanoid()
592
+ });
593
+ return;
594
+ }
595
+ try {
596
+ await conn.establishConnection();
597
+ this._onConnected.fire(serverId);
598
+ } catch (error) {
599
+ const url = conn.url.toString();
600
+ this._onObservabilityEvent.fire({
601
+ type: "mcp:client:connect",
602
+ displayMessage: `Failed to establish connection to server ${serverId} with url ${url}`,
603
+ payload: {
604
+ url,
605
+ transport: conn.options.transport.type ?? "auto",
606
+ state: conn.connectionState,
607
+ error: toErrorMessage(error)
608
+ },
609
+ timestamp: Date.now(),
610
+ id: nanoid()
611
+ });
612
+ }
613
+ }
614
+ /**
615
+ * Register a callback URL for OAuth handling
616
+ * @param url The callback URL to register
617
+ */
618
+ registerCallbackUrl(url) {
619
+ if (!this._callbackUrls.includes(url)) this._callbackUrls.push(url);
620
+ }
621
+ /**
622
+ * Unregister a callback URL
623
+ * @param serverId The server ID whose callback URL should be removed
624
+ */
625
+ unregisterCallbackUrl(serverId) {
626
+ this._callbackUrls = this._callbackUrls.filter((url) => !url.endsWith(`/${serverId}`));
627
+ }
628
+ /**
629
+ * Configure OAuth callback handling
630
+ * @param config OAuth callback configuration
631
+ */
632
+ configureOAuthCallback(config) {
633
+ this._oauthCallbackConfig = config;
634
+ }
635
+ /**
636
+ * Get the current OAuth callback configuration
637
+ * @returns The current OAuth callback configuration
638
+ */
639
+ getOAuthCallbackConfig() {
640
+ return this._oauthCallbackConfig;
641
+ }
642
+ /**
643
+ * @returns namespaced list of tools
644
+ */
645
+ listTools() {
646
+ return getNamespacedData(this.mcpConnections, "tools");
647
+ }
648
+ /**
649
+ * @returns a set of tools that you can use with the AI SDK
650
+ */
651
+ getAITools() {
652
+ return Object.fromEntries(getNamespacedData(this.mcpConnections, "tools").map((tool) => {
653
+ return [`tool_${tool.serverId.replace(/-/g, "")}_${tool.name}`, {
654
+ description: tool.description,
655
+ execute: async (args) => {
656
+ const result = await this.callTool({
657
+ arguments: args,
658
+ name: tool.name,
659
+ serverId: tool.serverId
660
+ });
661
+ if (result.isError) throw new Error(result.content[0].text);
662
+ return result;
663
+ },
664
+ inputSchema: getJsonSchema()(tool.inputSchema),
665
+ outputSchema: tool.outputSchema ? getJsonSchema()(tool.outputSchema) : void 0
666
+ }];
667
+ }));
668
+ }
669
+ /**
670
+ * @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version
671
+ * @returns a set of tools that you can use with the AI SDK
672
+ */
673
+ unstable_getAITools() {
674
+ if (!this._didWarnAboutUnstableGetAITools) {
675
+ this._didWarnAboutUnstableGetAITools = true;
676
+ console.warn("unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version.");
677
+ }
678
+ return this.getAITools();
679
+ }
680
+ /**
681
+ * Closes all connections to MCP servers
682
+ */
683
+ async closeAllConnections() {
684
+ const ids = Object.keys(this.mcpConnections);
685
+ await Promise.all(ids.map(async (id) => {
686
+ await this.mcpConnections[id].client.close();
687
+ }));
688
+ for (const id of ids) {
689
+ const store = this._connectionDisposables.get(id);
690
+ if (store) store.dispose();
691
+ this._connectionDisposables.delete(id);
692
+ delete this.mcpConnections[id];
693
+ }
694
+ }
695
+ /**
696
+ * Closes a connection to an MCP server
697
+ * @param id The id of the connection to close
698
+ */
699
+ async closeConnection(id) {
700
+ if (!this.mcpConnections[id]) throw new Error(`Connection with id "${id}" does not exist.`);
701
+ await this.mcpConnections[id].client.close();
702
+ delete this.mcpConnections[id];
703
+ const store = this._connectionDisposables.get(id);
704
+ if (store) store.dispose();
705
+ this._connectionDisposables.delete(id);
706
+ }
707
+ /**
708
+ * Dispose the manager and all resources.
709
+ */
710
+ async dispose() {
711
+ try {
712
+ await this.closeAllConnections();
713
+ } finally {
714
+ this._onConnected.dispose();
715
+ this._onObservabilityEvent.dispose();
716
+ }
717
+ }
718
+ /**
719
+ * @returns namespaced list of prompts
720
+ */
721
+ listPrompts() {
722
+ return getNamespacedData(this.mcpConnections, "prompts");
723
+ }
724
+ /**
725
+ * @returns namespaced list of tools
726
+ */
727
+ listResources() {
728
+ return getNamespacedData(this.mcpConnections, "resources");
729
+ }
730
+ /**
731
+ * @returns namespaced list of resource templates
732
+ */
733
+ listResourceTemplates() {
734
+ return getNamespacedData(this.mcpConnections, "resourceTemplates");
735
+ }
736
+ /**
737
+ * Namespaced version of callTool
738
+ */
739
+ async callTool(params, resultSchema, options) {
740
+ const unqualifiedName = params.name.replace(`${params.serverId}.`, "");
741
+ return this.mcpConnections[params.serverId].client.callTool({
742
+ ...params,
743
+ name: unqualifiedName
744
+ }, resultSchema, options);
745
+ }
746
+ /**
747
+ * Namespaced version of readResource
748
+ */
749
+ readResource(params, options) {
750
+ return this.mcpConnections[params.serverId].client.readResource(params, options);
751
+ }
752
+ /**
753
+ * Namespaced version of getPrompt
754
+ */
755
+ getPrompt(params, options) {
756
+ return this.mcpConnections[params.serverId].client.getPrompt(params, options);
757
+ }
758
+ };
759
+ function getNamespacedData(mcpClients, type) {
760
+ return Object.entries(mcpClients).map(([name, conn]) => {
761
+ return {
762
+ data: conn[type],
763
+ name
764
+ };
765
+ }).flatMap(({ name: serverId, data }) => {
766
+ return data.map((item) => {
767
+ return {
768
+ ...item,
769
+ serverId
770
+ };
771
+ });
772
+ });
773
+ }
774
+
775
+ //#endregion
776
+ //#region ../agents/dist/ai-types-B0GBFDwi.js
777
+ /**
778
+ * Enum for message types to improve type safety and maintainability
779
+ */
780
+ let MessageType = /* @__PURE__ */ function(MessageType$1) {
781
+ MessageType$1["CF_AGENT_CHAT_MESSAGES"] = "cf_agent_chat_messages";
782
+ MessageType$1["CF_AGENT_USE_CHAT_REQUEST"] = "cf_agent_use_chat_request";
783
+ MessageType$1["CF_AGENT_USE_CHAT_RESPONSE"] = "cf_agent_use_chat_response";
784
+ MessageType$1["CF_AGENT_CHAT_CLEAR"] = "cf_agent_chat_clear";
785
+ MessageType$1["CF_AGENT_CHAT_REQUEST_CANCEL"] = "cf_agent_chat_request_cancel";
786
+ MessageType$1["CF_AGENT_MCP_SERVERS"] = "cf_agent_mcp_servers";
787
+ MessageType$1["CF_MCP_AGENT_EVENT"] = "cf_mcp_agent_event";
788
+ MessageType$1["CF_AGENT_STATE"] = "cf_agent_state";
789
+ MessageType$1["RPC"] = "rpc";
790
+ return MessageType$1;
791
+ }({});
792
+
793
+ //#endregion
794
+ //#region ../agents/dist/client-zS-OCVJA.js
795
+ /**
796
+ * Convert a camelCase string to a kebab-case string
797
+ * @param str The string to convert
798
+ * @returns The kebab-case string
799
+ */
800
+ function camelCaseToKebabCase(str) {
801
+ if (str === str.toUpperCase() && str !== str.toLowerCase()) return str.toLowerCase().replace(/_/g, "-");
802
+ let kebabified = str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
803
+ kebabified = kebabified.startsWith("-") ? kebabified.slice(1) : kebabified;
804
+ return kebabified.replace(/_/g, "-").replace(/-$/, "");
805
+ }
806
+
807
+ //#endregion
808
+ //#region ../agents/dist/do-oauth-client-provider-B2jr6UNq.js
809
+ var DurableObjectOAuthClientProvider = class {
810
+ constructor(storage, clientName, baseRedirectUrl) {
811
+ this.storage = storage;
812
+ this.clientName = clientName;
813
+ this.baseRedirectUrl = baseRedirectUrl;
814
+ }
815
+ get clientMetadata() {
816
+ return {
817
+ client_name: this.clientName,
818
+ client_uri: this.clientUri,
819
+ grant_types: ["authorization_code", "refresh_token"],
820
+ redirect_uris: [this.redirectUrl],
821
+ response_types: ["code"],
822
+ token_endpoint_auth_method: "none"
823
+ };
824
+ }
825
+ get clientUri() {
826
+ return new URL(this.redirectUrl).origin;
827
+ }
828
+ get redirectUrl() {
829
+ return `${this.baseRedirectUrl}/${this.serverId}`;
830
+ }
831
+ get clientId() {
832
+ if (!this._clientId_) throw new Error("Trying to access clientId before it was set");
833
+ return this._clientId_;
834
+ }
835
+ set clientId(clientId_) {
836
+ this._clientId_ = clientId_;
837
+ }
838
+ get serverId() {
839
+ if (!this._serverId_) throw new Error("Trying to access serverId before it was set");
840
+ return this._serverId_;
841
+ }
842
+ set serverId(serverId_) {
843
+ this._serverId_ = serverId_;
844
+ }
845
+ keyPrefix(clientId) {
846
+ return `/${this.clientName}/${this.serverId}/${clientId}`;
847
+ }
848
+ clientInfoKey(clientId) {
849
+ return `${this.keyPrefix(clientId)}/client_info/`;
850
+ }
851
+ async clientInformation() {
852
+ if (!this._clientId_) return;
853
+ return await this.storage.get(this.clientInfoKey(this.clientId)) ?? void 0;
854
+ }
855
+ async saveClientInformation(clientInformation) {
856
+ await this.storage.put(this.clientInfoKey(clientInformation.client_id), clientInformation);
857
+ this.clientId = clientInformation.client_id;
858
+ }
859
+ tokenKey(clientId) {
860
+ return `${this.keyPrefix(clientId)}/token`;
861
+ }
862
+ async tokens() {
863
+ if (!this._clientId_) return;
864
+ return await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;
865
+ }
866
+ async saveTokens(tokens) {
867
+ await this.storage.put(this.tokenKey(this.clientId), tokens);
868
+ }
869
+ get authUrl() {
870
+ return this._authUrl_;
871
+ }
872
+ /**
873
+ * Because this operates on the server side (but we need browser auth), we send this url back to the user
874
+ * and require user interact to initiate the redirect flow
875
+ */
876
+ async redirectToAuthorization(authUrl) {
877
+ const stateToken = nanoid();
878
+ authUrl.searchParams.set("state", stateToken);
879
+ this._authUrl_ = authUrl.toString();
880
+ }
881
+ codeVerifierKey(clientId) {
882
+ return `${this.keyPrefix(clientId)}/code_verifier`;
883
+ }
884
+ async saveCodeVerifier(verifier) {
885
+ const key = this.codeVerifierKey(this.clientId);
886
+ if (await this.storage.get(key)) return;
887
+ await this.storage.put(key, verifier);
888
+ }
889
+ async codeVerifier() {
890
+ const codeVerifier = await this.storage.get(this.codeVerifierKey(this.clientId));
891
+ if (!codeVerifier) throw new Error("No code verifier found");
892
+ return codeVerifier;
893
+ }
894
+ };
895
+
896
+ //#endregion
897
+ //#region ../agents/dist/src-C9xZ0CrH.js
898
+ /**
899
+ * A generic observability implementation that logs events to the console.
900
+ */
901
+ const genericObservability = { emit(event) {
902
+ if (isLocalMode()) {
903
+ console.log(event.displayMessage);
904
+ return;
905
+ }
906
+ console.log(event);
907
+ } };
908
+ let localMode = false;
909
+ function isLocalMode() {
910
+ if (localMode) return true;
911
+ const { request } = getCurrentAgent();
912
+ if (!request) return false;
913
+ localMode = new URL(request.url).hostname === "localhost";
914
+ return localMode;
915
+ }
916
+ /**
917
+ * Type guard for RPC request messages
918
+ */
919
+ function isRPCRequest(msg) {
920
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.RPC && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
921
+ }
922
+ /**
923
+ * Type guard for state update messages
924
+ */
925
+ function isStateUpdateMessage(msg) {
926
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.CF_AGENT_STATE && "state" in msg;
927
+ }
928
+ const callableMetadata = /* @__PURE__ */ new Map();
929
+ function getNextCronTime(cron) {
930
+ return parseCronExpression(cron).getNextDate();
931
+ }
932
+ const STATE_ROW_ID = "cf_state_row_id";
933
+ const STATE_WAS_CHANGED = "cf_state_was_changed";
934
+ const DEFAULT_STATE = {};
935
+ const agentContext = new AsyncLocalStorage();
936
+ function getCurrentAgent() {
937
+ const store = agentContext.getStore();
938
+ if (!store) return {
939
+ agent: void 0,
940
+ connection: void 0,
941
+ request: void 0,
942
+ email: void 0
943
+ };
944
+ return store;
945
+ }
946
+ /**
947
+ * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
948
+ * @param agent The agent instance
949
+ * @param method The method to wrap
950
+ * @returns A wrapped method that runs within the agent context
951
+ */
952
+ function withAgentContext(method) {
953
+ return function(...args) {
954
+ const { connection, request, email, agent } = getCurrentAgent();
955
+ if (agent === this) return method.apply(this, args);
956
+ return agentContext.run({
957
+ agent: this,
958
+ connection,
959
+ request,
960
+ email
961
+ }, () => {
962
+ return method.apply(this, args);
963
+ });
964
+ };
965
+ }
966
+ /**
967
+ * Base class for creating Agent implementations
968
+ * @template Env Environment type containing bindings
969
+ * @template State State type to store within the Agent
970
+ */
971
+ var Agent = class Agent$1 extends Server {
972
+ /**
973
+ * Current state of the Agent
974
+ */
975
+ get state() {
976
+ if (this._state !== DEFAULT_STATE) return this._state;
977
+ const wasChanged = this.sql`
978
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
979
+ `;
980
+ const result = this.sql`
981
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
982
+ `;
983
+ if (wasChanged[0]?.state === "true" || result[0]?.state) {
984
+ const state = result[0]?.state;
985
+ this._state = JSON.parse(state);
986
+ return this._state;
987
+ }
988
+ if (this.initialState === DEFAULT_STATE) return;
989
+ this.setState(this.initialState);
990
+ return this.initialState;
991
+ }
992
+ static {
993
+ this.options = { hibernate: true };
994
+ }
995
+ /**
996
+ * Execute SQL queries against the Agent's database
997
+ * @template T Type of the returned rows
998
+ * @param strings SQL query template strings
999
+ * @param values Values to be inserted into the query
1000
+ * @returns Array of query results
1001
+ */
1002
+ sql(strings, ...values) {
1003
+ let query = "";
1004
+ try {
1005
+ query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? "?" : ""), "");
1006
+ return [...this.ctx.storage.sql.exec(query, ...values)];
1007
+ } catch (e) {
1008
+ console.error(`failed to execute sql query: ${query}`, e);
1009
+ throw this.onError(e);
1010
+ }
1011
+ }
1012
+ constructor(ctx, env$1) {
1013
+ super(ctx, env$1);
1014
+ this._state = DEFAULT_STATE;
1015
+ this._disposables = new DisposableStore();
1016
+ this._ParentClass = Object.getPrototypeOf(this).constructor;
1017
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
1018
+ this.initialState = DEFAULT_STATE;
1019
+ this.observability = genericObservability;
1020
+ this._flushingQueue = false;
1021
+ this.alarm = async () => {
1022
+ const now = Math.floor(Date.now() / 1e3);
1023
+ const result = this.sql`
1024
+ SELECT * FROM cf_agents_schedules WHERE time <= ${now}
1025
+ `;
1026
+ if (result && Array.isArray(result)) for (const row of result) {
1027
+ const callback = this[row.callback];
1028
+ if (!callback) {
1029
+ console.error(`callback ${row.callback} not found`);
1030
+ continue;
1031
+ }
1032
+ await agentContext.run({
1033
+ agent: this,
1034
+ connection: void 0,
1035
+ request: void 0,
1036
+ email: void 0
1037
+ }, async () => {
1038
+ try {
1039
+ this.observability?.emit({
1040
+ displayMessage: `Schedule ${row.id} executed`,
1041
+ id: nanoid(),
1042
+ payload: {
1043
+ callback: row.callback,
1044
+ id: row.id
1045
+ },
1046
+ timestamp: Date.now(),
1047
+ type: "schedule:execute"
1048
+ }, this.ctx);
1049
+ await callback.bind(this)(JSON.parse(row.payload), row);
1050
+ } catch (e) {
1051
+ console.error(`error executing callback "${row.callback}"`, e);
1052
+ }
1053
+ });
1054
+ if (row.type === "cron") {
1055
+ const nextExecutionTime = getNextCronTime(row.cron);
1056
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
1057
+ this.sql`
1058
+ UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
1059
+ `;
1060
+ } else this.sql`
1061
+ DELETE FROM cf_agents_schedules WHERE id = ${row.id}
1062
+ `;
1063
+ }
1064
+ await this._scheduleNextAlarm();
1065
+ };
1066
+ if (!wrappedClasses.has(this.constructor)) {
1067
+ this._autoWrapCustomMethods();
1068
+ wrappedClasses.add(this.constructor);
1069
+ }
1070
+ this._disposables.add(this.mcp.onConnected(async () => {
1071
+ this.broadcastMcpServers();
1072
+ }));
1073
+ this._disposables.add(this.mcp.onObservabilityEvent((event) => {
1074
+ this.observability?.emit(event);
1075
+ }));
1076
+ this.sql`
1077
+ CREATE TABLE IF NOT EXISTS cf_agents_state (
1078
+ id TEXT PRIMARY KEY NOT NULL,
1079
+ state TEXT
1080
+ )
1081
+ `;
1082
+ this.sql`
1083
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
1084
+ id TEXT PRIMARY KEY NOT NULL,
1085
+ payload TEXT,
1086
+ callback TEXT,
1087
+ created_at INTEGER DEFAULT (unixepoch())
1088
+ )
1089
+ `;
1090
+ this.ctx.blockConcurrencyWhile(async () => {
1091
+ return this._tryCatch(async () => {
1092
+ this.sql`
1093
+ CREATE TABLE IF NOT EXISTS cf_agents_schedules (
1094
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
1095
+ callback TEXT,
1096
+ payload TEXT,
1097
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
1098
+ time INTEGER,
1099
+ delayInSeconds INTEGER,
1100
+ cron TEXT,
1101
+ created_at INTEGER DEFAULT (unixepoch())
1102
+ )
1103
+ `;
1104
+ await this.alarm();
1105
+ });
1106
+ });
1107
+ this.sql`
1108
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
1109
+ id TEXT PRIMARY KEY NOT NULL,
1110
+ name TEXT NOT NULL,
1111
+ server_url TEXT NOT NULL,
1112
+ callback_url TEXT NOT NULL,
1113
+ client_id TEXT,
1114
+ auth_url TEXT,
1115
+ server_options TEXT
1116
+ )
1117
+ `;
1118
+ const _onRequest = this.onRequest.bind(this);
1119
+ this.onRequest = (request) => {
1120
+ return agentContext.run({
1121
+ agent: this,
1122
+ connection: void 0,
1123
+ request,
1124
+ email: void 0
1125
+ }, async () => {
1126
+ if (this.mcp.isCallbackRequest(request)) {
1127
+ const result = await this.mcp.handleCallbackRequest(request);
1128
+ this.broadcastMcpServers();
1129
+ if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
1130
+ console.error("Background connection failed:", error);
1131
+ }).finally(() => {
1132
+ this.broadcastMcpServers();
1133
+ });
1134
+ return this.handleOAuthCallbackResponse(result, request);
1135
+ }
1136
+ return this._tryCatch(() => _onRequest(request));
1137
+ });
1138
+ };
1139
+ const _onMessage = this.onMessage.bind(this);
1140
+ this.onMessage = async (connection, message) => {
1141
+ return agentContext.run({
1142
+ agent: this,
1143
+ connection,
1144
+ request: void 0,
1145
+ email: void 0
1146
+ }, async () => {
1147
+ if (typeof message !== "string") return this._tryCatch(() => _onMessage(connection, message));
1148
+ let parsed;
1149
+ try {
1150
+ parsed = JSON.parse(message);
1151
+ } catch (_e) {
1152
+ return this._tryCatch(() => _onMessage(connection, message));
1153
+ }
1154
+ if (isStateUpdateMessage(parsed)) {
1155
+ this._setStateInternal(parsed.state, connection);
1156
+ return;
1157
+ }
1158
+ if (isRPCRequest(parsed)) {
1159
+ try {
1160
+ const { id, method, args } = parsed;
1161
+ const methodFn = this[method];
1162
+ if (typeof methodFn !== "function") throw new Error(`Method ${method} does not exist`);
1163
+ if (!this._isCallable(method)) throw new Error(`Method ${method} is not callable`);
1164
+ const metadata = callableMetadata.get(methodFn);
1165
+ if (metadata?.streaming) {
1166
+ const stream = new StreamingResponse(connection, id);
1167
+ await methodFn.apply(this, [stream, ...args]);
1168
+ return;
1169
+ }
1170
+ const result = await methodFn.apply(this, args);
1171
+ this.observability?.emit({
1172
+ displayMessage: `RPC call to ${method}`,
1173
+ id: nanoid(),
1174
+ payload: {
1175
+ method,
1176
+ streaming: metadata?.streaming
1177
+ },
1178
+ timestamp: Date.now(),
1179
+ type: "rpc"
1180
+ }, this.ctx);
1181
+ const response = {
1182
+ done: true,
1183
+ id,
1184
+ result,
1185
+ success: true,
1186
+ type: MessageType.RPC
1187
+ };
1188
+ connection.send(JSON.stringify(response));
1189
+ } catch (e) {
1190
+ const response = {
1191
+ error: e instanceof Error ? e.message : "Unknown error occurred",
1192
+ id: parsed.id,
1193
+ success: false,
1194
+ type: MessageType.RPC
1195
+ };
1196
+ connection.send(JSON.stringify(response));
1197
+ console.error("RPC error:", e);
1198
+ }
1199
+ return;
1200
+ }
1201
+ return this._tryCatch(() => _onMessage(connection, message));
1202
+ });
1203
+ };
1204
+ const _onConnect = this.onConnect.bind(this);
1205
+ this.onConnect = (connection, ctx$1) => {
1206
+ return agentContext.run({
1207
+ agent: this,
1208
+ connection,
1209
+ request: ctx$1.request,
1210
+ email: void 0
1211
+ }, () => {
1212
+ if (this.state) connection.send(JSON.stringify({
1213
+ state: this.state,
1214
+ type: MessageType.CF_AGENT_STATE
1215
+ }));
1216
+ connection.send(JSON.stringify({
1217
+ mcp: this.getMcpServers(),
1218
+ type: MessageType.CF_AGENT_MCP_SERVERS
1219
+ }));
1220
+ this.observability?.emit({
1221
+ displayMessage: "Connection established",
1222
+ id: nanoid(),
1223
+ payload: { connectionId: connection.id },
1224
+ timestamp: Date.now(),
1225
+ type: "connect"
1226
+ }, this.ctx);
1227
+ return this._tryCatch(() => _onConnect(connection, ctx$1));
1228
+ });
1229
+ };
1230
+ const _onStart = this.onStart.bind(this);
1231
+ this.onStart = async (props) => {
1232
+ return agentContext.run({
1233
+ agent: this,
1234
+ connection: void 0,
1235
+ request: void 0,
1236
+ email: void 0
1237
+ }, async () => {
1238
+ await this._tryCatch(() => {
1239
+ const servers = this.sql`
1240
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1241
+ `;
1242
+ this.broadcastMcpServers();
1243
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1244
+ servers.forEach((server) => {
1245
+ if (server.callback_url) this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);
1246
+ });
1247
+ servers.forEach((server) => {
1248
+ this._connectToMcpServerInternal(server.name, server.server_url, server.callback_url, server.server_options ? JSON.parse(server.server_options) : void 0, {
1249
+ id: server.id,
1250
+ oauthClientId: server.client_id ?? void 0
1251
+ }).then(() => {
1252
+ this.broadcastMcpServers();
1253
+ }).catch((error) => {
1254
+ console.error(`Error connecting to MCP server: ${server.name} (${server.server_url})`, error);
1255
+ this.broadcastMcpServers();
1256
+ });
1257
+ });
1258
+ }
1259
+ return _onStart(props);
1260
+ });
1261
+ });
1262
+ };
1263
+ }
1264
+ _setStateInternal(state, source = "server") {
1265
+ this._state = state;
1266
+ this.sql`
1267
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
1268
+ VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
1269
+ `;
1270
+ this.sql`
1271
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
1272
+ VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
1273
+ `;
1274
+ this.broadcast(JSON.stringify({
1275
+ state,
1276
+ type: MessageType.CF_AGENT_STATE
1277
+ }), source !== "server" ? [source.id] : []);
1278
+ return this._tryCatch(() => {
1279
+ const { connection, request, email } = agentContext.getStore() || {};
1280
+ return agentContext.run({
1281
+ agent: this,
1282
+ connection,
1283
+ request,
1284
+ email
1285
+ }, async () => {
1286
+ this.observability?.emit({
1287
+ displayMessage: "State updated",
1288
+ id: nanoid(),
1289
+ payload: {},
1290
+ timestamp: Date.now(),
1291
+ type: "state:update"
1292
+ }, this.ctx);
1293
+ return this.onStateUpdate(state, source);
1294
+ });
1295
+ });
1296
+ }
1297
+ /**
1298
+ * Update the Agent's state
1299
+ * @param state New state to set
1300
+ */
1301
+ setState(state) {
1302
+ this._setStateInternal(state, "server");
1303
+ }
1304
+ /**
1305
+ * Called when the Agent's state is updated
1306
+ * @param state Updated state
1307
+ * @param source Source of the state update ("server" or a client connection)
1308
+ */
1309
+ onStateUpdate(state, source) {}
1310
+ /**
1311
+ * Called when the Agent receives an email via routeAgentEmail()
1312
+ * Override this method to handle incoming emails
1313
+ * @param email Email message to process
1314
+ */
1315
+ async _onEmail(email) {
1316
+ return agentContext.run({
1317
+ agent: this,
1318
+ connection: void 0,
1319
+ request: void 0,
1320
+ email
1321
+ }, async () => {
1322
+ if ("onEmail" in this && typeof this.onEmail === "function") return this._tryCatch(() => this.onEmail(email));
1323
+ else {
1324
+ console.log("Received email from:", email.from, "to:", email.to);
1325
+ console.log("Subject:", email.headers.get("subject"));
1326
+ console.log("Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails");
1327
+ }
1328
+ });
1329
+ }
1330
+ /**
1331
+ * Reply to an email
1332
+ * @param email The email to reply to
1333
+ * @param options Options for the reply
1334
+ * @returns void
1335
+ */
1336
+ async replyToEmail(email, options) {
1337
+ return this._tryCatch(async () => {
1338
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
1339
+ const agentId = this.name;
1340
+ const { createMimeMessage } = await import("mimetext");
1341
+ const msg = createMimeMessage();
1342
+ msg.setSender({
1343
+ addr: email.to,
1344
+ name: options.fromName
1345
+ });
1346
+ msg.setRecipient(email.from);
1347
+ msg.setSubject(options.subject || `Re: ${email.headers.get("subject")}` || "No subject");
1348
+ msg.addMessage({
1349
+ contentType: options.contentType || "text/plain",
1350
+ data: options.body
1351
+ });
1352
+ const messageId = `<${agentId}@${email.from.split("@")[1]}>`;
1353
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
1354
+ msg.setHeader("Message-ID", messageId);
1355
+ msg.setHeader("X-Agent-Name", agentName);
1356
+ msg.setHeader("X-Agent-ID", agentId);
1357
+ if (options.headers) for (const [key, value] of Object.entries(options.headers)) msg.setHeader(key, value);
1358
+ await email.reply({
1359
+ from: email.to,
1360
+ raw: msg.asRaw(),
1361
+ to: email.from
1362
+ });
1363
+ });
1364
+ }
1365
+ async _tryCatch(fn) {
1366
+ try {
1367
+ return await fn();
1368
+ } catch (e) {
1369
+ throw this.onError(e);
1370
+ }
1371
+ }
1372
+ /**
1373
+ * Automatically wrap custom methods with agent context
1374
+ * This ensures getCurrentAgent() works in all custom methods without decorators
1375
+ */
1376
+ _autoWrapCustomMethods() {
1377
+ const basePrototypes = [Agent$1.prototype, Server.prototype];
1378
+ const baseMethods = /* @__PURE__ */ new Set();
1379
+ for (const baseProto of basePrototypes) {
1380
+ let proto$1 = baseProto;
1381
+ while (proto$1 && proto$1 !== Object.prototype) {
1382
+ const methodNames = Object.getOwnPropertyNames(proto$1);
1383
+ for (const methodName of methodNames) baseMethods.add(methodName);
1384
+ proto$1 = Object.getPrototypeOf(proto$1);
1385
+ }
1386
+ }
1387
+ let proto = Object.getPrototypeOf(this);
1388
+ let depth = 0;
1389
+ while (proto && proto !== Object.prototype && depth < 10) {
1390
+ const methodNames = Object.getOwnPropertyNames(proto);
1391
+ for (const methodName of methodNames) {
1392
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
1393
+ if (baseMethods.has(methodName) || methodName.startsWith("_") || !descriptor || !!descriptor.get || typeof descriptor.value !== "function") continue;
1394
+ const wrappedFunction = withAgentContext(this[methodName]);
1395
+ if (this._isCallable(methodName)) callableMetadata.set(wrappedFunction, callableMetadata.get(this[methodName]));
1396
+ this.constructor.prototype[methodName] = wrappedFunction;
1397
+ }
1398
+ proto = Object.getPrototypeOf(proto);
1399
+ depth++;
1400
+ }
1401
+ }
1402
+ onError(connectionOrError, error) {
1403
+ let theError;
1404
+ if (connectionOrError && error) {
1405
+ theError = error;
1406
+ console.error("Error on websocket connection:", connectionOrError.id, theError);
1407
+ console.error("Override onError(connection, error) to handle websocket connection errors");
1408
+ } else {
1409
+ theError = connectionOrError;
1410
+ console.error("Error on server:", theError);
1411
+ console.error("Override onError(error) to handle server errors");
1412
+ }
1413
+ throw theError;
1414
+ }
1415
+ /**
1416
+ * Render content (not implemented in base class)
1417
+ */
1418
+ render() {
1419
+ throw new Error("Not implemented");
1420
+ }
1421
+ /**
1422
+ * Queue a task to be executed in the future
1423
+ * @param payload Payload to pass to the callback
1424
+ * @param callback Name of the method to call
1425
+ * @returns The ID of the queued task
1426
+ */
1427
+ async queue(callback, payload) {
1428
+ const id = nanoid(9);
1429
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
1430
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
1431
+ this.sql`
1432
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
1433
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
1434
+ `;
1435
+ this._flushQueue().catch((e) => {
1436
+ console.error("Error flushing queue:", e);
1437
+ });
1438
+ return id;
1439
+ }
1440
+ async _flushQueue() {
1441
+ if (this._flushingQueue) return;
1442
+ this._flushingQueue = true;
1443
+ while (true) {
1444
+ const result = this.sql`
1445
+ SELECT * FROM cf_agents_queues
1446
+ ORDER BY created_at ASC
1447
+ `;
1448
+ if (!result || result.length === 0) break;
1449
+ for (const row of result || []) {
1450
+ const callback = this[row.callback];
1451
+ if (!callback) {
1452
+ console.error(`callback ${row.callback} not found`);
1453
+ continue;
1454
+ }
1455
+ const { connection, request, email } = agentContext.getStore() || {};
1456
+ await agentContext.run({
1457
+ agent: this,
1458
+ connection,
1459
+ request,
1460
+ email
1461
+ }, async () => {
1462
+ await callback.bind(this)(JSON.parse(row.payload), row);
1463
+ await this.dequeue(row.id);
1464
+ });
1465
+ }
1466
+ }
1467
+ this._flushingQueue = false;
1468
+ }
1469
+ /**
1470
+ * Dequeue a task by ID
1471
+ * @param id ID of the task to dequeue
1472
+ */
1473
+ async dequeue(id) {
1474
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
1475
+ }
1476
+ /**
1477
+ * Dequeue all tasks
1478
+ */
1479
+ async dequeueAll() {
1480
+ this.sql`DELETE FROM cf_agents_queues`;
1481
+ }
1482
+ /**
1483
+ * Dequeue all tasks by callback
1484
+ * @param callback Name of the callback to dequeue
1485
+ */
1486
+ async dequeueAllByCallback(callback) {
1487
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
1488
+ }
1489
+ /**
1490
+ * Get a queued task by ID
1491
+ * @param id ID of the task to get
1492
+ * @returns The task or undefined if not found
1493
+ */
1494
+ async getQueue(id) {
1495
+ const result = this.sql`
1496
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
1497
+ `;
1498
+ return result ? {
1499
+ ...result[0],
1500
+ payload: JSON.parse(result[0].payload)
1501
+ } : void 0;
1502
+ }
1503
+ /**
1504
+ * Get all queues by key and value
1505
+ * @param key Key to filter by
1506
+ * @param value Value to filter by
1507
+ * @returns Array of matching QueueItem objects
1508
+ */
1509
+ async getQueues(key, value) {
1510
+ return this.sql`
1511
+ SELECT * FROM cf_agents_queues
1512
+ `.filter((row) => JSON.parse(row.payload)[key] === value);
1513
+ }
1514
+ /**
1515
+ * Schedule a task to be executed in the future
1516
+ * @template T Type of the payload data
1517
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
1518
+ * @param callback Name of the method to call
1519
+ * @param payload Data to pass to the callback
1520
+ * @returns Schedule object representing the scheduled task
1521
+ */
1522
+ async schedule(when, callback, payload) {
1523
+ const id = nanoid(9);
1524
+ const emitScheduleCreate = (schedule) => this.observability?.emit({
1525
+ displayMessage: `Schedule ${schedule.id} created`,
1526
+ id: nanoid(),
1527
+ payload: {
1528
+ callback,
1529
+ id
1530
+ },
1531
+ timestamp: Date.now(),
1532
+ type: "schedule:create"
1533
+ }, this.ctx);
1534
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
1535
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
1536
+ if (when instanceof Date) {
1537
+ const timestamp = Math.floor(when.getTime() / 1e3);
1538
+ this.sql`
1539
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
1540
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})
1541
+ `;
1542
+ await this._scheduleNextAlarm();
1543
+ const schedule = {
1544
+ callback,
1545
+ id,
1546
+ payload,
1547
+ time: timestamp,
1548
+ type: "scheduled"
1549
+ };
1550
+ emitScheduleCreate(schedule);
1551
+ return schedule;
1552
+ }
1553
+ if (typeof when === "number") {
1554
+ const time = new Date(Date.now() + when * 1e3);
1555
+ const timestamp = Math.floor(time.getTime() / 1e3);
1556
+ this.sql`
1557
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
1558
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${timestamp})
1559
+ `;
1560
+ await this._scheduleNextAlarm();
1561
+ const schedule = {
1562
+ callback,
1563
+ delayInSeconds: when,
1564
+ id,
1565
+ payload,
1566
+ time: timestamp,
1567
+ type: "delayed"
1568
+ };
1569
+ emitScheduleCreate(schedule);
1570
+ return schedule;
1571
+ }
1572
+ if (typeof when === "string") {
1573
+ const nextExecutionTime = getNextCronTime(when);
1574
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
1575
+ this.sql`
1576
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
1577
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'cron', ${when}, ${timestamp})
1578
+ `;
1579
+ await this._scheduleNextAlarm();
1580
+ const schedule = {
1581
+ callback,
1582
+ cron: when,
1583
+ id,
1584
+ payload,
1585
+ time: timestamp,
1586
+ type: "cron"
1587
+ };
1588
+ emitScheduleCreate(schedule);
1589
+ return schedule;
1590
+ }
1591
+ throw new Error("Invalid schedule type");
1592
+ }
1593
+ /**
1594
+ * Get a scheduled task by ID
1595
+ * @template T Type of the payload data
1596
+ * @param id ID of the scheduled task
1597
+ * @returns The Schedule object or undefined if not found
1598
+ */
1599
+ async getSchedule(id) {
1600
+ const result = this.sql`
1601
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
1602
+ `;
1603
+ if (!result) {
1604
+ console.error(`schedule ${id} not found`);
1605
+ return;
1606
+ }
1607
+ return {
1608
+ ...result[0],
1609
+ payload: JSON.parse(result[0].payload)
1610
+ };
1611
+ }
1612
+ /**
1613
+ * Get scheduled tasks matching the given criteria
1614
+ * @template T Type of the payload data
1615
+ * @param criteria Criteria to filter schedules
1616
+ * @returns Array of matching Schedule objects
1617
+ */
1618
+ getSchedules(criteria = {}) {
1619
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
1620
+ const params = [];
1621
+ if (criteria.id) {
1622
+ query += " AND id = ?";
1623
+ params.push(criteria.id);
1624
+ }
1625
+ if (criteria.type) {
1626
+ query += " AND type = ?";
1627
+ params.push(criteria.type);
1628
+ }
1629
+ if (criteria.timeRange) {
1630
+ query += " AND time >= ? AND time <= ?";
1631
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
1632
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
1633
+ params.push(Math.floor(start.getTime() / 1e3), Math.floor(end.getTime() / 1e3));
1634
+ }
1635
+ return this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
1636
+ ...row,
1637
+ payload: JSON.parse(row.payload)
1638
+ }));
1639
+ }
1640
+ /**
1641
+ * Cancel a scheduled task
1642
+ * @param id ID of the task to cancel
1643
+ * @returns true if the task was cancelled, false otherwise
1644
+ */
1645
+ async cancelSchedule(id) {
1646
+ const schedule = await this.getSchedule(id);
1647
+ if (schedule) this.observability?.emit({
1648
+ displayMessage: `Schedule ${id} cancelled`,
1649
+ id: nanoid(),
1650
+ payload: {
1651
+ callback: schedule.callback,
1652
+ id: schedule.id
1653
+ },
1654
+ timestamp: Date.now(),
1655
+ type: "schedule:cancel"
1656
+ }, this.ctx);
1657
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
1658
+ await this._scheduleNextAlarm();
1659
+ return true;
1660
+ }
1661
+ async _scheduleNextAlarm() {
1662
+ const result = this.sql`
1663
+ SELECT time FROM cf_agents_schedules
1664
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
1665
+ ORDER BY time ASC
1666
+ LIMIT 1
1667
+ `;
1668
+ if (!result) return;
1669
+ if (result.length > 0 && "time" in result[0]) {
1670
+ const nextTime = result[0].time * 1e3;
1671
+ await this.ctx.storage.setAlarm(nextTime);
1672
+ }
1673
+ }
1674
+ /**
1675
+ * Destroy the Agent, removing all state and scheduled tasks
1676
+ */
1677
+ async destroy() {
1678
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
1679
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
1680
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
1681
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
1682
+ await this.ctx.storage.deleteAlarm();
1683
+ await this.ctx.storage.deleteAll();
1684
+ this._disposables.dispose();
1685
+ await this.mcp.dispose?.();
1686
+ this.ctx.abort("destroyed");
1687
+ this.observability?.emit({
1688
+ displayMessage: "Agent destroyed",
1689
+ id: nanoid(),
1690
+ payload: {},
1691
+ timestamp: Date.now(),
1692
+ type: "destroy"
1693
+ }, this.ctx);
1694
+ }
1695
+ /**
1696
+ * Get all methods marked as callable on this Agent
1697
+ * @returns A map of method names to their metadata
1698
+ */
1699
+ _isCallable(method) {
1700
+ return callableMetadata.has(this[method]);
1701
+ }
1702
+ /**
1703
+ * Connect to a new MCP Server
1704
+ *
1705
+ * @param serverName Name of the MCP server
1706
+ * @param url MCP Server SSE URL
1707
+ * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
1708
+ * @param agentsPrefix agents routing prefix if not using `agents`
1709
+ * @param options MCP client and transport options
1710
+ * @returns authUrl
1711
+ */
1712
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
1713
+ let resolvedCallbackHost = callbackHost;
1714
+ if (!resolvedCallbackHost) {
1715
+ const { request } = getCurrentAgent();
1716
+ if (!request) throw new Error("callbackHost is required when not called within a request context");
1717
+ const requestUrl = new URL(request.url);
1718
+ resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
1719
+ }
1720
+ const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
1721
+ const result = await this._connectToMcpServerInternal(serverName, url, callbackUrl, options);
1722
+ this.sql`
1723
+ INSERT
1724
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1725
+ VALUES (
1726
+ ${result.id},
1727
+ ${serverName},
1728
+ ${url},
1729
+ ${result.clientId ?? null},
1730
+ ${result.authUrl ?? null},
1731
+ ${callbackUrl},
1732
+ ${options ? JSON.stringify(options) : null}
1733
+ );
1734
+ `;
1735
+ this.broadcastMcpServers();
1736
+ return result;
1737
+ }
1738
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
1739
+ const authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);
1740
+ if (reconnect) {
1741
+ authProvider.serverId = reconnect.id;
1742
+ if (reconnect.oauthClientId) authProvider.clientId = reconnect.oauthClientId;
1743
+ }
1744
+ const transportType = options?.transport?.type ?? "auto";
1745
+ let headerTransportOpts = {};
1746
+ if (options?.transport?.headers) headerTransportOpts = {
1747
+ eventSourceInit: { fetch: (url$1, init) => fetch(url$1, {
1748
+ ...init,
1749
+ headers: options?.transport?.headers
1750
+ }) },
1751
+ requestInit: { headers: options?.transport?.headers }
1752
+ };
1753
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
1754
+ client: options?.client,
1755
+ reconnect,
1756
+ transport: {
1757
+ ...headerTransportOpts,
1758
+ authProvider,
1759
+ type: transportType
1760
+ }
1761
+ });
1762
+ return {
1763
+ authUrl,
1764
+ clientId,
1765
+ id
1766
+ };
1767
+ }
1768
+ async removeMcpServer(id) {
1769
+ this.mcp.closeConnection(id);
1770
+ this.mcp.unregisterCallbackUrl(id);
1771
+ this.sql`
1772
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1773
+ `;
1774
+ this.broadcastMcpServers();
1775
+ }
1776
+ getMcpServers() {
1777
+ const mcpState = {
1778
+ prompts: this.mcp.listPrompts(),
1779
+ resources: this.mcp.listResources(),
1780
+ servers: {},
1781
+ tools: this.mcp.listTools()
1782
+ };
1783
+ const servers = this.sql`
1784
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1785
+ `;
1786
+ if (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {
1787
+ const serverConn = this.mcp.mcpConnections[server.id];
1788
+ mcpState.servers[server.id] = {
1789
+ auth_url: server.auth_url,
1790
+ capabilities: serverConn?.serverCapabilities ?? null,
1791
+ instructions: serverConn?.instructions ?? null,
1792
+ name: server.name,
1793
+ server_url: server.server_url,
1794
+ state: serverConn?.connectionState ?? "authenticating"
1795
+ };
1796
+ }
1797
+ return mcpState;
1798
+ }
1799
+ broadcastMcpServers() {
1800
+ this.broadcast(JSON.stringify({
1801
+ mcp: this.getMcpServers(),
1802
+ type: MessageType.CF_AGENT_MCP_SERVERS
1803
+ }));
1804
+ }
1805
+ /**
1806
+ * Handle OAuth callback response using MCPClientManager configuration
1807
+ * @param result OAuth callback result
1808
+ * @param request The original request (needed for base URL)
1809
+ * @returns Response for the OAuth callback
1810
+ */
1811
+ handleOAuthCallbackResponse(result, request) {
1812
+ const config = this.mcp.getOAuthCallbackConfig();
1813
+ if (config?.customHandler) return config.customHandler(result);
1814
+ if (config?.successRedirect && result.authSuccess) return Response.redirect(config.successRedirect);
1815
+ if (config?.errorRedirect && !result.authSuccess) return Response.redirect(`${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`);
1816
+ const baseUrl = new URL(request.url).origin;
1817
+ return Response.redirect(baseUrl);
1818
+ }
1819
+ };
1820
+ const wrappedClasses = /* @__PURE__ */ new Set();
1821
+ /**
1822
+ * Route a request to the appropriate Agent
1823
+ * @param request Request to route
1824
+ * @param env Environment containing Agent bindings
1825
+ * @param options Routing options
1826
+ * @returns Response from the Agent or undefined if no route matched
1827
+ */
1828
+ async function routeAgentRequest(request, env$1, options) {
1829
+ const corsHeaders = options?.cors === true ? {
1830
+ "Access-Control-Allow-Credentials": "true",
1831
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1832
+ "Access-Control-Allow-Origin": "*",
1833
+ "Access-Control-Max-Age": "86400"
1834
+ } : options?.cors;
1835
+ if (request.method === "OPTIONS") {
1836
+ if (corsHeaders) return new Response(null, { headers: corsHeaders });
1837
+ console.warn("Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.");
1838
+ }
1839
+ let response = await routePartykitRequest(request, env$1, {
1840
+ prefix: "agents",
1841
+ ...options
1842
+ });
1843
+ if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") response = new Response(response.body, { headers: {
1844
+ ...response.headers,
1845
+ ...corsHeaders
1846
+ } });
1847
+ return response;
1848
+ }
1849
+ /**
1850
+ * A wrapper for streaming responses in callable methods
1851
+ */
1852
+ var StreamingResponse = class {
1853
+ constructor(connection, id) {
1854
+ this._closed = false;
1855
+ this._connection = connection;
1856
+ this._id = id;
1857
+ }
1858
+ /**
1859
+ * Send a chunk of data to the client
1860
+ * @param chunk The data to send
1861
+ */
1862
+ send(chunk) {
1863
+ if (this._closed) throw new Error("StreamingResponse is already closed");
1864
+ const response = {
1865
+ done: false,
1866
+ id: this._id,
1867
+ result: chunk,
1868
+ success: true,
1869
+ type: MessageType.RPC
1870
+ };
1871
+ this._connection.send(JSON.stringify(response));
1872
+ }
1873
+ /**
1874
+ * End the stream and send the final chunk (if any)
1875
+ * @param finalChunk Optional final chunk of data to send
1876
+ */
1877
+ end(finalChunk) {
1878
+ if (this._closed) throw new Error("StreamingResponse is already closed");
1879
+ this._closed = true;
1880
+ const response = {
1881
+ done: true,
1882
+ id: this._id,
1883
+ result: finalChunk,
1884
+ success: true,
1885
+ type: MessageType.RPC
1886
+ };
1887
+ this._connection.send(JSON.stringify(response));
1888
+ }
1889
+ };
1890
+
1891
+ //#endregion
1892
+ //#region src/index.ts
1893
+ /**
1894
+ * Creates a middleware for handling Cloudflare Agents WebSocket and HTTP requests
1895
+ * Processes both WebSocket upgrades and standard HTTP requests, delegating them to Cloudflare Agents
1896
+ */
5
1897
  function agentsMiddleware(ctx) {
6
- return createMiddleware(async (c, next) => {
7
- try {
8
- const handler = isWebSocketUpgrade(c) ? handleWebSocketUpgrade : handleHttpRequest;
9
- const response = await handler(c, ctx?.options);
10
- return response === null ? await next() : response;
11
- } catch (error) {
12
- if (ctx?.onError) {
13
- ctx.onError(error);
14
- return next();
15
- }
16
- throw error;
17
- }
18
- });
1898
+ return createMiddleware(async (c, next) => {
1899
+ try {
1900
+ const response = await (isWebSocketUpgrade(c) ? handleWebSocketUpgrade : handleHttpRequest)(c, ctx?.options);
1901
+ return response === null ? await next() : response;
1902
+ } catch (error) {
1903
+ if (ctx?.onError) {
1904
+ ctx.onError(error);
1905
+ return next();
1906
+ }
1907
+ throw error;
1908
+ }
1909
+ });
19
1910
  }
1911
+ /**
1912
+ * Checks if the incoming request is a WebSocket upgrade request
1913
+ * Looks for the 'upgrade' header with a value of 'websocket' (case-insensitive)
1914
+ */
20
1915
  function isWebSocketUpgrade(c) {
21
- return c.req.header("upgrade")?.toLowerCase() === "websocket";
1916
+ return c.req.header("upgrade")?.toLowerCase() === "websocket";
22
1917
  }
1918
+ /**
1919
+ * Handles WebSocket upgrade requests
1920
+ * Returns a WebSocket upgrade response if successful, null otherwise
1921
+ */
23
1922
  async function handleWebSocketUpgrade(c, options) {
24
- const response = await routeAgentRequest(
25
- c.req.raw,
26
- env(c),
27
- options
28
- );
29
- if (!response?.webSocket) {
30
- return null;
31
- }
32
- return new Response(null, {
33
- status: 101,
34
- webSocket: response.webSocket
35
- });
1923
+ const response = await routeAgentRequest(c.req.raw, env(c), options);
1924
+ if (!response?.webSocket) return null;
1925
+ return new Response(null, {
1926
+ status: 101,
1927
+ webSocket: response.webSocket
1928
+ });
36
1929
  }
1930
+ /**
1931
+ * Handles standard HTTP requests
1932
+ * Forwards the request to Cloudflare Agents and returns the response
1933
+ */
37
1934
  async function handleHttpRequest(c, options) {
38
- return routeAgentRequest(c.req.raw, env(c), options);
1935
+ return routeAgentRequest(c.req.raw, env(c), options);
39
1936
  }
40
- export {
41
- agentsMiddleware
42
- };
1937
+
1938
+ //#endregion
1939
+ export { agentsMiddleware };
43
1940
  //# sourceMappingURL=index.js.map