hono-agents 2.0.6 → 2.0.8

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