hono-agents 0.0.0-e19fea6 → 0.0.0-e1af284

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