hono-agents 0.0.0-e8f693b → 0.0.0-eaeb1b3

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,17 +1,22 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  import "partysocket";
2
3
  import { nanoid } from "nanoid";
4
+ import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/cfworker-provider.js";
3
5
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
- import { ElicitRequestSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
5
6
  import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
6
7
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
7
- import { AsyncLocalStorage } from "node:async_hooks";
8
+ import { ElicitRequestSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
8
9
  import { parseCronExpression } from "cron-schedule";
9
10
  import "cloudflare:email";
10
11
  import { Server, routePartykitRequest } from "partyserver";
11
12
  import { env } from "hono/adapter";
12
13
  import { createMiddleware } from "hono/factory";
13
14
 
14
- //#region ../agents/dist/ai-types-B3aQaFv3.js
15
+ //#region ../agents/dist/context-BkKbAa1R.js
16
+ const agentContext = new AsyncLocalStorage();
17
+
18
+ //#endregion
19
+ //#region ../agents/dist/ai-types-DEtF_8Km.js
15
20
  /**
16
21
  * Enum for message types to improve type safety and maintainability
17
22
  */
@@ -21,15 +26,23 @@ let MessageType = /* @__PURE__ */ function(MessageType$1) {
21
26
  MessageType$1["CF_AGENT_USE_CHAT_RESPONSE"] = "cf_agent_use_chat_response";
22
27
  MessageType$1["CF_AGENT_CHAT_CLEAR"] = "cf_agent_chat_clear";
23
28
  MessageType$1["CF_AGENT_CHAT_REQUEST_CANCEL"] = "cf_agent_chat_request_cancel";
29
+ /** Sent by server when client connects and there's an active stream to resume */
30
+ MessageType$1["CF_AGENT_STREAM_RESUMING"] = "cf_agent_stream_resuming";
31
+ /** Sent by client to acknowledge stream resuming notification and request chunks */
32
+ MessageType$1["CF_AGENT_STREAM_RESUME_ACK"] = "cf_agent_stream_resume_ack";
24
33
  MessageType$1["CF_AGENT_MCP_SERVERS"] = "cf_agent_mcp_servers";
25
34
  MessageType$1["CF_MCP_AGENT_EVENT"] = "cf_mcp_agent_event";
26
35
  MessageType$1["CF_AGENT_STATE"] = "cf_agent_state";
27
36
  MessageType$1["RPC"] = "rpc";
37
+ /** Client sends tool result to server (for client-side tools) */
38
+ MessageType$1["CF_AGENT_TOOL_RESULT"] = "cf_agent_tool_result";
39
+ /** Server notifies client that a message was updated (e.g., tool result applied) */
40
+ MessageType$1["CF_AGENT_MESSAGE_UPDATED"] = "cf_agent_message_updated";
28
41
  return MessageType$1;
29
42
  }({});
30
43
 
31
44
  //#endregion
32
- //#region ../agents/dist/client-BfiZ3HQd.js
45
+ //#region ../agents/dist/client-DjTPRM8-.js
33
46
  /**
34
47
  * Convert a camelCase string to a kebab-case string
35
48
  * @param str The string to convert
@@ -43,7 +56,158 @@ function camelCaseToKebabCase(str) {
43
56
  }
44
57
 
45
58
  //#endregion
46
- //#region ../agents/dist/client-9Ld2_lnt.js
59
+ //#region ../agents/dist/do-oauth-client-provider-B1fVIshX.js
60
+ const STATE_EXPIRATION_MS = 600 * 1e3;
61
+ var DurableObjectOAuthClientProvider = class {
62
+ constructor(storage, clientName, baseRedirectUrl) {
63
+ this.storage = storage;
64
+ this.clientName = clientName;
65
+ this.baseRedirectUrl = baseRedirectUrl;
66
+ if (!storage) throw new Error("DurableObjectOAuthClientProvider requires a valid DurableObjectStorage instance");
67
+ }
68
+ get clientMetadata() {
69
+ return {
70
+ client_name: this.clientName,
71
+ client_uri: this.clientUri,
72
+ grant_types: ["authorization_code", "refresh_token"],
73
+ redirect_uris: [this.redirectUrl],
74
+ response_types: ["code"],
75
+ token_endpoint_auth_method: "none"
76
+ };
77
+ }
78
+ get clientUri() {
79
+ return new URL(this.redirectUrl).origin;
80
+ }
81
+ get redirectUrl() {
82
+ return this.baseRedirectUrl;
83
+ }
84
+ get clientId() {
85
+ if (!this._clientId_) throw new Error("Trying to access clientId before it was set");
86
+ return this._clientId_;
87
+ }
88
+ set clientId(clientId_) {
89
+ this._clientId_ = clientId_;
90
+ }
91
+ get serverId() {
92
+ if (!this._serverId_) throw new Error("Trying to access serverId before it was set");
93
+ return this._serverId_;
94
+ }
95
+ set serverId(serverId_) {
96
+ this._serverId_ = serverId_;
97
+ }
98
+ keyPrefix(clientId) {
99
+ return `/${this.clientName}/${this.serverId}/${clientId}`;
100
+ }
101
+ clientInfoKey(clientId) {
102
+ return `${this.keyPrefix(clientId)}/client_info/`;
103
+ }
104
+ async clientInformation() {
105
+ if (!this._clientId_) return;
106
+ return await this.storage.get(this.clientInfoKey(this.clientId)) ?? void 0;
107
+ }
108
+ async saveClientInformation(clientInformation) {
109
+ await this.storage.put(this.clientInfoKey(clientInformation.client_id), clientInformation);
110
+ this.clientId = clientInformation.client_id;
111
+ }
112
+ tokenKey(clientId) {
113
+ return `${this.keyPrefix(clientId)}/token`;
114
+ }
115
+ async tokens() {
116
+ if (!this._clientId_) return;
117
+ return await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;
118
+ }
119
+ async saveTokens(tokens) {
120
+ await this.storage.put(this.tokenKey(this.clientId), tokens);
121
+ }
122
+ get authUrl() {
123
+ return this._authUrl_;
124
+ }
125
+ stateKey(nonce) {
126
+ return `/${this.clientName}/${this.serverId}/state/${nonce}`;
127
+ }
128
+ async state() {
129
+ const nonce = nanoid();
130
+ const state = `${nonce}.${this.serverId}`;
131
+ const storedState = {
132
+ nonce,
133
+ serverId: this.serverId,
134
+ createdAt: Date.now()
135
+ };
136
+ await this.storage.put(this.stateKey(nonce), storedState);
137
+ return state;
138
+ }
139
+ async checkState(state) {
140
+ const parts = state.split(".");
141
+ if (parts.length !== 2) return {
142
+ valid: false,
143
+ error: "Invalid state format"
144
+ };
145
+ const [nonce, serverId] = parts;
146
+ const key = this.stateKey(nonce);
147
+ const storedState = await this.storage.get(key);
148
+ if (!storedState) return {
149
+ valid: false,
150
+ error: "State not found or already used"
151
+ };
152
+ if (storedState.serverId !== serverId) {
153
+ await this.storage.delete(key);
154
+ return {
155
+ valid: false,
156
+ error: "State serverId mismatch"
157
+ };
158
+ }
159
+ if (Date.now() - storedState.createdAt > STATE_EXPIRATION_MS) {
160
+ await this.storage.delete(key);
161
+ return {
162
+ valid: false,
163
+ error: "State expired"
164
+ };
165
+ }
166
+ return {
167
+ valid: true,
168
+ serverId
169
+ };
170
+ }
171
+ async consumeState(state) {
172
+ const parts = state.split(".");
173
+ if (parts.length !== 2) {
174
+ console.warn(`[OAuth] consumeState called with invalid state format: ${state.substring(0, 20)}...`);
175
+ return;
176
+ }
177
+ const [nonce] = parts;
178
+ await this.storage.delete(this.stateKey(nonce));
179
+ }
180
+ async redirectToAuthorization(authUrl) {
181
+ this._authUrl_ = authUrl.toString();
182
+ }
183
+ async invalidateCredentials(scope) {
184
+ if (!this._clientId_) return;
185
+ const deleteKeys = [];
186
+ if (scope === "all" || scope === "client") deleteKeys.push(this.clientInfoKey(this.clientId));
187
+ if (scope === "all" || scope === "tokens") deleteKeys.push(this.tokenKey(this.clientId));
188
+ if (scope === "all" || scope === "verifier") deleteKeys.push(this.codeVerifierKey(this.clientId));
189
+ if (deleteKeys.length > 0) await this.storage.delete(deleteKeys);
190
+ }
191
+ codeVerifierKey(clientId) {
192
+ return `${this.keyPrefix(clientId)}/code_verifier`;
193
+ }
194
+ async saveCodeVerifier(verifier) {
195
+ const key = this.codeVerifierKey(this.clientId);
196
+ if (await this.storage.get(key)) return;
197
+ await this.storage.put(key, verifier);
198
+ }
199
+ async codeVerifier() {
200
+ const codeVerifier = await this.storage.get(this.codeVerifierKey(this.clientId));
201
+ if (!codeVerifier) throw new Error("No code verifier found");
202
+ return codeVerifier;
203
+ }
204
+ async deleteCodeVerifier() {
205
+ await this.storage.delete(this.codeVerifierKey(this.clientId));
206
+ }
207
+ };
208
+
209
+ //#endregion
210
+ //#region ../agents/dist/client-QZa2Rq0l.js
47
211
  function toDisposable(fn) {
48
212
  return { dispose: fn };
49
213
  }
@@ -91,73 +255,21 @@ function isTransportNotImplemented(error) {
91
255
  const msg = toErrorMessage(error);
92
256
  return msg.includes("404") || msg.includes("405") || msg.includes("Not Implemented") || msg.includes("not implemented");
93
257
  }
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
- }
258
+ /**
259
+ * Connection state machine for MCP client connections.
260
+ *
261
+ * State transitions:
262
+ * - Non-OAuth: init() → CONNECTING → DISCOVERING → READY
263
+ * - OAuth: init() AUTHENTICATING → (callback) CONNECTING → DISCOVERING → READY
264
+ * - Any state can transition to FAILED on error
265
+ */
266
+ const MCPConnectionState = {
267
+ AUTHENTICATING: "authenticating",
268
+ CONNECTING: "connecting",
269
+ CONNECTED: "connected",
270
+ DISCOVERING: "discovering",
271
+ READY: "ready",
272
+ FAILED: "failed"
161
273
  };
162
274
  var MCPClientConnection = class {
163
275
  constructor(url, info, options = {
@@ -166,7 +278,7 @@ var MCPClientConnection = class {
166
278
  }) {
167
279
  this.url = url;
168
280
  this.options = options;
169
- this.connectionState = "connecting";
281
+ this.connectionState = MCPConnectionState.CONNECTING;
170
282
  this.tools = [];
171
283
  this.prompts = [];
172
284
  this.resources = [];
@@ -182,36 +294,49 @@ var MCPClientConnection = class {
182
294
  });
183
295
  }
184
296
  /**
185
- * Initialize a client connection
297
+ * Initialize a client connection, if authentication is required, the connection will be in the AUTHENTICATING state
298
+ * Sets connection state based on the result and emits observability events
186
299
  *
187
- * @returns
300
+ * @returns Error message if connection failed, undefined otherwise
188
301
  */
189
302
  async init() {
190
303
  const transportType = this.options.transport.type;
191
304
  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
- }
305
+ const res = await this.tryConnect(transportType);
306
+ this.connectionState = res.state;
307
+ if (res.state === MCPConnectionState.CONNECTED && res.transport) {
308
+ this.client.setRequestHandler(ElicitRequestSchema, async (request) => {
309
+ return await this.handleElicitationRequest(request);
310
+ });
311
+ this.lastConnectedTransport = res.transport;
312
+ this._onObservabilityEvent.fire({
313
+ type: "mcp:client:connect",
314
+ displayMessage: `Connected successfully using ${res.transport} transport for ${this.url.toString()}`,
315
+ payload: {
316
+ url: this.url.toString(),
317
+ transport: res.transport,
318
+ state: this.connectionState
319
+ },
320
+ timestamp: Date.now(),
321
+ id: nanoid()
322
+ });
323
+ return;
324
+ } else if (res.state === MCPConnectionState.FAILED && res.error) {
325
+ const errorMessage = toErrorMessage(res.error);
199
326
  this._onObservabilityEvent.fire({
200
327
  type: "mcp:client:connect",
201
- displayMessage: `Connection initialization failed for ${this.url.toString()}`,
328
+ displayMessage: `Failed to connect to ${this.url.toString()}: ${errorMessage}`,
202
329
  payload: {
203
330
  url: this.url.toString(),
204
331
  transport: transportType,
205
332
  state: this.connectionState,
206
- error: toErrorMessage(e)
333
+ error: errorMessage
207
334
  },
208
335
  timestamp: Date.now(),
209
336
  id: nanoid()
210
337
  });
211
- this.connectionState = "failed";
212
- return;
338
+ return errorMessage;
213
339
  }
214
- await this.discoverAndRegister();
215
340
  }
216
341
  /**
217
342
  * Finish OAuth by probing transports based on configured type.
@@ -243,113 +368,189 @@ var MCPClientConnection = class {
243
368
  * Complete OAuth authorization
244
369
  */
245
370
  async completeAuthorization(code) {
246
- if (this.connectionState !== "authenticating") throw new Error("Connection must be in authenticating state to complete authorization");
371
+ if (this.connectionState !== MCPConnectionState.AUTHENTICATING) throw new Error("Connection must be in authenticating state to complete authorization");
247
372
  try {
248
373
  await this.finishAuthProbe(code);
249
- this.connectionState = "connecting";
374
+ this.connectionState = MCPConnectionState.CONNECTING;
250
375
  } catch (error) {
251
- this.connectionState = "failed";
376
+ this.connectionState = MCPConnectionState.FAILED;
252
377
  throw error;
253
378
  }
254
379
  }
255
380
  /**
256
- * Establish connection after successful authorization
381
+ * Discover server capabilities and register tools, resources, prompts, and templates.
382
+ * This method does the work but does not manage connection state - that's handled by discover().
257
383
  */
258
- async establishConnection() {
259
- if (this.connectionState !== "connecting") throw new Error("Connection must be in connecting state to establish connection");
384
+ async discoverAndRegister() {
385
+ this.serverCapabilities = this.client.getServerCapabilities();
386
+ if (!this.serverCapabilities) throw new Error("The MCP Server failed to return server capabilities");
387
+ const operations = [];
388
+ const operationNames = [];
389
+ operations.push(Promise.resolve(this.client.getInstructions()));
390
+ operationNames.push("instructions");
391
+ if (this.serverCapabilities.tools) {
392
+ operations.push(this.registerTools());
393
+ operationNames.push("tools");
394
+ }
395
+ if (this.serverCapabilities.resources) {
396
+ operations.push(this.registerResources());
397
+ operationNames.push("resources");
398
+ }
399
+ if (this.serverCapabilities.prompts) {
400
+ operations.push(this.registerPrompts());
401
+ operationNames.push("prompts");
402
+ }
403
+ if (this.serverCapabilities.resources) {
404
+ operations.push(this.registerResourceTemplates());
405
+ operationNames.push("resource templates");
406
+ }
260
407
  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();
408
+ const results = await Promise.all(operations);
409
+ for (let i = 0; i < results.length; i++) {
410
+ const result = results[i];
411
+ switch (operationNames[i]) {
412
+ case "instructions":
413
+ this.instructions = result;
414
+ break;
415
+ case "tools":
416
+ this.tools = result;
417
+ break;
418
+ case "resources":
419
+ this.resources = result;
420
+ break;
421
+ case "prompts":
422
+ this.prompts = result;
423
+ break;
424
+ case "resource templates":
425
+ this.resourceTemplates = result;
426
+ break;
427
+ }
428
+ }
265
429
  } catch (error) {
266
- this.connectionState = "failed";
430
+ this._onObservabilityEvent.fire({
431
+ type: "mcp:client:discover",
432
+ displayMessage: `Failed to discover capabilities for ${this.url.toString()}: ${toErrorMessage(error)}`,
433
+ payload: {
434
+ url: this.url.toString(),
435
+ error: toErrorMessage(error)
436
+ },
437
+ timestamp: Date.now(),
438
+ id: nanoid()
439
+ });
267
440
  throw error;
268
441
  }
269
442
  }
270
443
  /**
271
- * Discover server capabilities and register tools, resources, prompts, and templates
444
+ * Discover server capabilities with timeout and cancellation support.
445
+ * If called while a previous discovery is in-flight, the previous discovery will be aborted.
446
+ *
447
+ * @param options Optional configuration
448
+ * @param options.timeoutMs Timeout in milliseconds (default: 15000)
449
+ * @returns Result indicating success/failure with optional error message
272
450
  */
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();
451
+ async discover(options = {}) {
452
+ const { timeoutMs = 15e3 } = options;
453
+ if (this.connectionState !== MCPConnectionState.CONNECTED && this.connectionState !== MCPConnectionState.READY) {
308
454
  this._onObservabilityEvent.fire({
309
455
  type: "mcp:client:discover",
310
- displayMessage: `Failed to discover ${name} for ${url}`,
456
+ displayMessage: `Discovery skipped for ${this.url.toString()}, state is ${this.connectionState}`,
311
457
  payload: {
312
- url,
313
- capability: name,
314
- error: result.reason
458
+ url: this.url.toString(),
459
+ state: this.connectionState
315
460
  },
316
461
  timestamp: Date.now(),
317
462
  id: nanoid()
318
463
  });
464
+ return {
465
+ success: false,
466
+ error: `Discovery skipped - connection in ${this.connectionState} state`
467
+ };
468
+ }
469
+ if (this._discoveryAbortController) {
470
+ this._discoveryAbortController.abort();
471
+ this._discoveryAbortController = void 0;
472
+ }
473
+ const abortController = new AbortController();
474
+ this._discoveryAbortController = abortController;
475
+ this.connectionState = MCPConnectionState.DISCOVERING;
476
+ let timeoutId;
477
+ try {
478
+ const timeoutPromise = new Promise((_, reject) => {
479
+ timeoutId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Discovery timed out after ${timeoutMs}ms`)), timeoutMs);
480
+ });
481
+ if (abortController.signal.aborted) throw new Error("Discovery was cancelled");
482
+ const abortPromise = new Promise((_, reject) => {
483
+ abortController.signal.addEventListener("abort", () => {
484
+ reject(/* @__PURE__ */ new Error("Discovery was cancelled"));
485
+ });
486
+ });
487
+ await Promise.race([
488
+ this.discoverAndRegister(),
489
+ timeoutPromise,
490
+ abortPromise
491
+ ]);
492
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
493
+ this.connectionState = MCPConnectionState.READY;
494
+ this._onObservabilityEvent.fire({
495
+ type: "mcp:client:discover",
496
+ displayMessage: `Discovery completed for ${this.url.toString()}`,
497
+ payload: { url: this.url.toString() },
498
+ timestamp: Date.now(),
499
+ id: nanoid()
500
+ });
501
+ return { success: true };
502
+ } catch (e) {
503
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
504
+ this.connectionState = MCPConnectionState.CONNECTED;
505
+ return {
506
+ success: false,
507
+ error: e instanceof Error ? e.message : String(e)
508
+ };
509
+ } finally {
510
+ this._discoveryAbortController = void 0;
511
+ }
512
+ }
513
+ /**
514
+ * Cancel any in-flight discovery operation.
515
+ * Called when closing the connection.
516
+ */
517
+ cancelDiscovery() {
518
+ if (this._discoveryAbortController) {
519
+ this._discoveryAbortController.abort();
520
+ this._discoveryAbortController = void 0;
319
521
  }
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
522
  }
327
523
  /**
328
- * Notification handler registration
524
+ * Notification handler registration for tools
525
+ * Should only be called if serverCapabilities.tools exists
329
526
  */
330
527
  async registerTools() {
331
- if (!this.serverCapabilities || !this.serverCapabilities.tools) return [];
332
- if (this.serverCapabilities.tools.listChanged) this.client.setNotificationHandler(ToolListChangedNotificationSchema, async (_notification) => {
528
+ if (this.serverCapabilities?.tools?.listChanged) this.client.setNotificationHandler(ToolListChangedNotificationSchema, async (_notification) => {
333
529
  this.tools = await this.fetchTools();
334
530
  });
335
531
  return this.fetchTools();
336
532
  }
533
+ /**
534
+ * Notification handler registration for resources
535
+ * Should only be called if serverCapabilities.resources exists
536
+ */
337
537
  async registerResources() {
338
- if (!this.serverCapabilities || !this.serverCapabilities.resources) return [];
339
- if (this.serverCapabilities.resources.listChanged) this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_notification) => {
538
+ if (this.serverCapabilities?.resources?.listChanged) this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_notification) => {
340
539
  this.resources = await this.fetchResources();
341
540
  });
342
541
  return this.fetchResources();
343
542
  }
543
+ /**
544
+ * Notification handler registration for prompts
545
+ * Should only be called if serverCapabilities.prompts exists
546
+ */
344
547
  async registerPrompts() {
345
- if (!this.serverCapabilities || !this.serverCapabilities.prompts) return [];
346
- if (this.serverCapabilities.prompts.listChanged) this.client.setNotificationHandler(PromptListChangedNotificationSchema, async (_notification) => {
548
+ if (this.serverCapabilities?.prompts?.listChanged) this.client.setNotificationHandler(PromptListChangedNotificationSchema, async (_notification) => {
347
549
  this.prompts = await this.fetchPrompts();
348
550
  });
349
551
  return this.fetchPrompts();
350
552
  }
351
553
  async registerResourceTemplates() {
352
- if (!this.serverCapabilities || !this.serverCapabilities.resources) return [];
353
554
  return this.fetchResourceTemplates();
354
555
  }
355
556
  async fetchTools() {
@@ -402,8 +603,8 @@ var MCPClientConnection = class {
402
603
  */
403
604
  getTransport(transportType) {
404
605
  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);
606
+ case "streamable-http": return new StreamableHTTPClientTransport(this.url, this.options.transport);
607
+ case "sse": return new SSEClientTransport(this.url, this.options.transport);
407
608
  default: throw new Error(`Unsupported transport type: ${transportType}`);
408
609
  }
409
610
  }
@@ -415,44 +616,24 @@ var MCPClientConnection = class {
415
616
  const transport = this.getTransport(currentTransportType);
416
617
  try {
417
618
  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;
619
+ return {
620
+ state: MCPConnectionState.CONNECTED,
621
+ transport: currentTransportType
622
+ };
432
623
  } catch (e) {
433
624
  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;
625
+ if (isUnauthorized(error)) return { state: MCPConnectionState.AUTHENTICATING };
626
+ if (isTransportNotImplemented(error) && hasFallback) continue;
627
+ return {
628
+ state: MCPConnectionState.FAILED,
629
+ error
630
+ };
451
631
  }
452
632
  }
453
- this.client.setRequestHandler(ElicitRequestSchema, async (request) => {
454
- return await this.handleElicitationRequest(request);
455
- });
633
+ return {
634
+ state: MCPConnectionState.FAILED,
635
+ error: /* @__PURE__ */ new Error("No transports available")
636
+ };
456
637
  }
457
638
  _capabilityErrorHandler(empty, method) {
458
639
  return (e) => {
@@ -475,6 +656,7 @@ var MCPClientConnection = class {
475
656
  };
476
657
  }
477
658
  };
659
+ const defaultClientOptions = { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() };
478
660
  /**
479
661
  * Utility class that aggregates multiple MCP clients into one
480
662
  */
@@ -482,26 +664,121 @@ var MCPClientManager = class {
482
664
  /**
483
665
  * @param _name Name of the MCP client
484
666
  * @param _version Version of the MCP Client
485
- * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
667
+ * @param options Storage adapter for persisting MCP server state
486
668
  */
487
- constructor(_name, _version) {
669
+ constructor(_name, _version, options) {
488
670
  this._name = _name;
489
671
  this._version = _version;
490
672
  this.mcpConnections = {};
491
- this._callbackUrls = [];
492
673
  this._didWarnAboutUnstableGetAITools = false;
493
674
  this._connectionDisposables = /* @__PURE__ */ new Map();
675
+ this._isRestored = false;
494
676
  this._onObservabilityEvent = new Emitter();
495
677
  this.onObservabilityEvent = this._onObservabilityEvent.event;
496
- this._onConnected = new Emitter();
497
- this.onConnected = this._onConnected.event;
678
+ this._onServerStateChanged = new Emitter();
679
+ this.onServerStateChanged = this._onServerStateChanged.event;
680
+ if (!options.storage) throw new Error("MCPClientManager requires a valid DurableObjectStorage instance");
681
+ this._storage = options.storage;
682
+ }
683
+ sql(query, ...bindings) {
684
+ return [...this._storage.sql.exec(query, ...bindings)];
685
+ }
686
+ saveServerToStorage(server) {
687
+ this.sql(`INSERT OR REPLACE INTO cf_agents_mcp_servers (
688
+ id, name, server_url, client_id, auth_url, callback_url, server_options
689
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)`, server.id, server.name, server.server_url, server.client_id ?? null, server.auth_url ?? null, server.callback_url, server.server_options ?? null);
690
+ }
691
+ removeServerFromStorage(serverId) {
692
+ this.sql("DELETE FROM cf_agents_mcp_servers WHERE id = ?", serverId);
693
+ }
694
+ getServersFromStorage() {
695
+ return this.sql("SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers");
696
+ }
697
+ clearServerAuthUrl(serverId) {
698
+ this.sql("UPDATE cf_agents_mcp_servers SET auth_url = NULL WHERE id = ?", serverId);
699
+ }
700
+ /**
701
+ * Create an auth provider for a server
702
+ * @internal
703
+ */
704
+ createAuthProvider(serverId, callbackUrl, clientName, clientId) {
705
+ if (!this._storage) throw new Error("Cannot create auth provider: storage is not initialized");
706
+ const authProvider = new DurableObjectOAuthClientProvider(this._storage, clientName, callbackUrl);
707
+ authProvider.serverId = serverId;
708
+ if (clientId) authProvider.clientId = clientId;
709
+ return authProvider;
710
+ }
711
+ /**
712
+ * Restore MCP server connections from storage
713
+ * This method is called on Agent initialization to restore previously connected servers
714
+ *
715
+ * @param clientName Name to use for OAuth client (typically the agent instance name)
716
+ */
717
+ async restoreConnectionsFromStorage(clientName) {
718
+ if (this._isRestored) return;
719
+ const servers = this.getServersFromStorage();
720
+ if (!servers || servers.length === 0) {
721
+ this._isRestored = true;
722
+ return;
723
+ }
724
+ for (const server of servers) {
725
+ const existingConn = this.mcpConnections[server.id];
726
+ if (existingConn) {
727
+ if (existingConn.connectionState === MCPConnectionState.READY) {
728
+ console.warn(`[MCPClientManager] Server ${server.id} already has a ready connection. Skipping recreation.`);
729
+ continue;
730
+ }
731
+ if (existingConn.connectionState === MCPConnectionState.AUTHENTICATING || existingConn.connectionState === MCPConnectionState.CONNECTING || existingConn.connectionState === MCPConnectionState.DISCOVERING) continue;
732
+ if (existingConn.connectionState === MCPConnectionState.FAILED) {
733
+ try {
734
+ await existingConn.client.close();
735
+ } catch (error) {
736
+ console.warn(`[MCPClientManager] Error closing failed connection ${server.id}:`, error);
737
+ }
738
+ delete this.mcpConnections[server.id];
739
+ this._connectionDisposables.get(server.id)?.dispose();
740
+ this._connectionDisposables.delete(server.id);
741
+ }
742
+ }
743
+ const parsedOptions = server.server_options ? JSON.parse(server.server_options) : null;
744
+ const authProvider = this.createAuthProvider(server.id, server.callback_url, clientName, server.client_id ?? void 0);
745
+ const conn = this.createConnection(server.id, server.server_url, {
746
+ client: parsedOptions?.client ?? {},
747
+ transport: {
748
+ ...parsedOptions?.transport ?? {},
749
+ type: parsedOptions?.transport?.type ?? "auto",
750
+ authProvider
751
+ }
752
+ });
753
+ if (server.auth_url) {
754
+ conn.connectionState = MCPConnectionState.AUTHENTICATING;
755
+ continue;
756
+ }
757
+ this._restoreServer(server.id);
758
+ }
759
+ this._isRestored = true;
760
+ }
761
+ /**
762
+ * Internal method to restore a single server connection and discovery
763
+ */
764
+ async _restoreServer(serverId) {
765
+ if ((await this.connectToServer(serverId).catch((error) => {
766
+ console.error(`Error connecting to ${serverId}:`, error);
767
+ return null;
768
+ }))?.state === MCPConnectionState.CONNECTED) {
769
+ const discoverResult = await this.discoverIfConnected(serverId);
770
+ if (discoverResult && !discoverResult.success) console.error(`Error discovering ${serverId}:`, discoverResult.error);
771
+ }
498
772
  }
499
773
  /**
500
774
  * Connect to and register an MCP server
501
775
  *
502
- * @param transportConfig Transport config
503
- * @param clientConfig Client config
504
- * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
776
+ * @deprecated This method is maintained for backward compatibility.
777
+ * For new code, use registerServer() and connectToServer() separately.
778
+ *
779
+ * @param url Server URL
780
+ * @param options Connection options
781
+ * @returns Object with server ID, auth URL (if OAuth), and client ID (if OAuth)
505
782
  */
506
783
  async connect(url, options = {}) {
507
784
  /**
@@ -511,10 +788,7 @@ var MCPClientManager = class {
511
788
  * .connect() is called on at least one server.
512
789
  * So it's safe to delay loading it until .connect() is called.
513
790
  */
514
- if (!this.jsonSchema) {
515
- const { jsonSchema } = await import("ai");
516
- this.jsonSchema = jsonSchema;
517
- }
791
+ await this.ensureJsonSchema();
518
792
  const id = options.reconnect?.id ?? nanoid(8);
519
793
  if (options.transport?.authProvider) {
520
794
  options.transport.authProvider.serverId = id;
@@ -543,7 +817,7 @@ var MCPClientManager = class {
543
817
  await this.mcpConnections[id].init();
544
818
  if (options.reconnect?.oauthCode) try {
545
819
  await this.mcpConnections[id].completeAuthorization(options.reconnect.oauthCode);
546
- await this.mcpConnections[id].establishConnection();
820
+ await this.mcpConnections[id].init();
547
821
  } catch (error) {
548
822
  this._onObservabilityEvent.fire({
549
823
  type: "mcp:client:connect",
@@ -560,57 +834,230 @@ var MCPClientManager = class {
560
834
  throw error;
561
835
  }
562
836
  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
837
+ if (this.mcpConnections[id].connectionState === MCPConnectionState.AUTHENTICATING && authUrl && options.transport?.authProvider?.redirectUrl) return {
838
+ authUrl,
839
+ clientId: options.transport?.authProvider?.clientId,
840
+ id
841
+ };
842
+ const discoverResult = await this.discoverIfConnected(id);
843
+ if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover server capabilities: ${discoverResult.error}`);
844
+ return { id };
845
+ }
846
+ /**
847
+ * Create an in-memory connection object and set up observability
848
+ * Does NOT save to storage - use registerServer() for that
849
+ * @returns The connection object (existing or newly created)
850
+ */
851
+ createConnection(id, url, options) {
852
+ if (this.mcpConnections[id]) return this.mcpConnections[id];
853
+ const normalizedTransport = {
854
+ ...options.transport,
855
+ type: options.transport?.type ?? "auto"
856
+ };
857
+ this.mcpConnections[id] = new MCPClientConnection(new URL(url), {
858
+ name: this._name,
859
+ version: this._version
860
+ }, {
861
+ client: {
862
+ ...defaultClientOptions,
863
+ ...options.client
864
+ },
865
+ transport: normalizedTransport
866
+ });
867
+ const store = new DisposableStore();
868
+ const existing = this._connectionDisposables.get(id);
869
+ if (existing) existing.dispose();
870
+ this._connectionDisposables.set(id, store);
871
+ store.add(this.mcpConnections[id].onObservabilityEvent((event) => {
872
+ this._onObservabilityEvent.fire(event);
873
+ }));
874
+ return this.mcpConnections[id];
875
+ }
876
+ /**
877
+ * Register an MCP server connection without connecting
878
+ * Creates the connection object, sets up observability, and saves to storage
879
+ *
880
+ * @param id Server ID
881
+ * @param options Registration options including URL, name, callback URL, and connection config
882
+ * @returns Server ID
883
+ */
884
+ async registerServer(id, options) {
885
+ this.createConnection(id, options.url, {
886
+ client: options.client,
887
+ transport: {
888
+ ...options.transport,
889
+ type: options.transport?.type ?? "auto"
890
+ }
891
+ });
892
+ const { authProvider: _, ...transportWithoutAuth } = options.transport ?? {};
893
+ this.saveServerToStorage({
894
+ id,
895
+ name: options.name,
896
+ server_url: options.url,
897
+ callback_url: options.callbackUrl,
898
+ client_id: options.clientId ?? null,
899
+ auth_url: options.authUrl ?? null,
900
+ server_options: JSON.stringify({
901
+ client: options.client,
902
+ transport: transportWithoutAuth
903
+ })
904
+ });
905
+ this._onServerStateChanged.fire();
906
+ return id;
907
+ }
908
+ /**
909
+ * Connect to an already registered MCP server and initialize the connection.
910
+ *
911
+ * For OAuth servers, returns `{ state: "authenticating", authUrl, clientId? }`.
912
+ * The user must complete the OAuth flow via the authUrl, which triggers a
913
+ * callback handled by `handleCallbackRequest()`.
914
+ *
915
+ * For non-OAuth servers, establishes the transport connection and returns
916
+ * `{ state: "connected" }`. Call `discoverIfConnected()` afterwards to
917
+ * discover capabilities and transition to "ready" state.
918
+ *
919
+ * @param id Server ID (must be registered first via registerServer())
920
+ * @returns Connection result with current state and OAuth info (if applicable)
921
+ */
922
+ async connectToServer(id) {
923
+ const conn = this.mcpConnections[id];
924
+ if (!conn) throw new Error(`Server ${id} is not registered. Call registerServer() first.`);
925
+ const error = await conn.init();
926
+ this._onServerStateChanged.fire();
927
+ switch (conn.connectionState) {
928
+ case MCPConnectionState.FAILED: return {
929
+ state: conn.connectionState,
930
+ error: error ?? "Unknown connection error"
931
+ };
932
+ case MCPConnectionState.AUTHENTICATING: {
933
+ const authUrl = conn.options.transport.authProvider?.authUrl;
934
+ const redirectUrl = conn.options.transport.authProvider?.redirectUrl;
935
+ if (!authUrl || !redirectUrl) return {
936
+ state: MCPConnectionState.FAILED,
937
+ error: `OAuth configuration incomplete: missing ${!authUrl ? "authUrl" : "redirectUrl"}`
938
+ };
939
+ const clientId = conn.options.transport.authProvider?.clientId;
940
+ const serverRow = this.getServersFromStorage().find((s) => s.id === id);
941
+ if (serverRow) {
942
+ this.saveServerToStorage({
943
+ ...serverRow,
944
+ auth_url: authUrl,
945
+ client_id: clientId ?? null
946
+ });
947
+ this._onServerStateChanged.fire();
948
+ }
949
+ return {
950
+ state: conn.connectionState,
951
+ authUrl,
952
+ clientId
953
+ };
954
+ }
955
+ case MCPConnectionState.CONNECTED: return { state: conn.connectionState };
956
+ default: return {
957
+ state: MCPConnectionState.FAILED,
958
+ error: `Unexpected connection state after init: ${conn.connectionState}`
569
959
  };
570
960
  }
571
- return { id };
961
+ }
962
+ extractServerIdFromState(state) {
963
+ if (!state) return null;
964
+ const parts = state.split(".");
965
+ return parts.length === 2 ? parts[1] : null;
572
966
  }
573
967
  isCallbackRequest(req) {
574
- return req.method === "GET" && !!this._callbackUrls.find((url) => {
575
- return req.url.startsWith(url);
576
- });
968
+ if (req.method !== "GET") return false;
969
+ if (!req.url.includes("/callback")) return false;
970
+ const state = new URL(req.url).searchParams.get("state");
971
+ const serverId = this.extractServerIdFromState(state);
972
+ if (!serverId) return false;
973
+ return this.getServersFromStorage().some((server) => server.id === serverId);
577
974
  }
578
975
  async handleCallbackRequest(req) {
579
976
  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
977
  const code = url.searchParams.get("code");
585
978
  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");
979
+ const error = url.searchParams.get("error");
980
+ const errorDescription = url.searchParams.get("error_description");
589
981
  if (!state) throw new Error("Unauthorized: no state provided");
982
+ const serverId = this.extractServerIdFromState(state);
983
+ if (!serverId) throw new Error("No serverId found in state parameter. Expected format: {nonce}.{serverId}");
984
+ if (!this.getServersFromStorage().some((server) => server.id === serverId)) throw new Error(`No server found with id "${serverId}". Was the request matched with \`isCallbackRequest()\`?`);
590
985
  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
986
  const conn = this.mcpConnections[serverId];
593
987
  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;
988
+ const authProvider = conn.options.transport.authProvider;
989
+ authProvider.serverId = serverId;
990
+ const stateValidation = await authProvider.checkState(state);
991
+ if (!stateValidation.valid) throw new Error(`Invalid state: ${stateValidation.error}`);
992
+ if (error) return {
993
+ serverId,
994
+ authSuccess: false,
995
+ authError: errorDescription || error
996
+ };
997
+ if (!code) throw new Error("Unauthorized: no code provided");
998
+ if (this.mcpConnections[serverId].connectionState === MCPConnectionState.READY || this.mcpConnections[serverId].connectionState === MCPConnectionState.CONNECTED) {
999
+ this.clearServerAuthUrl(serverId);
1000
+ return {
1001
+ serverId,
1002
+ authSuccess: true
1003
+ };
1004
+ }
1005
+ if (this.mcpConnections[serverId].connectionState !== MCPConnectionState.AUTHENTICATING) throw new Error(`Failed to authenticate: the client is in "${this.mcpConnections[serverId].connectionState}" state, expected "authenticating"`);
597
1006
  try {
1007
+ await authProvider.consumeState(state);
598
1008
  await conn.completeAuthorization(code);
1009
+ await authProvider.deleteCodeVerifier();
1010
+ this.clearServerAuthUrl(serverId);
1011
+ this._onServerStateChanged.fire();
599
1012
  return {
600
1013
  serverId,
601
1014
  authSuccess: true
602
1015
  };
603
- } catch (error) {
1016
+ } catch (authError) {
1017
+ const errorMessage = authError instanceof Error ? authError.message : String(authError);
1018
+ this._onServerStateChanged.fire();
604
1019
  return {
605
1020
  serverId,
606
1021
  authSuccess: false,
607
- authError: error instanceof Error ? error.message : String(error)
1022
+ authError: errorMessage
608
1023
  };
609
1024
  }
610
1025
  }
611
1026
  /**
1027
+ * Discover server capabilities if connection is in CONNECTED or READY state.
1028
+ * Transitions to DISCOVERING then READY (or CONNECTED on error).
1029
+ * Can be called to refresh server capabilities (e.g., from a UI refresh button).
1030
+ *
1031
+ * If called while a previous discovery is in-flight for the same server,
1032
+ * the previous discovery will be aborted.
1033
+ *
1034
+ * @param serverId The server ID to discover
1035
+ * @param options Optional configuration
1036
+ * @param options.timeoutMs Timeout in milliseconds (default: 30000)
1037
+ * @returns Result with current state and optional error, or undefined if connection not found
1038
+ */
1039
+ async discoverIfConnected(serverId, options = {}) {
1040
+ const conn = this.mcpConnections[serverId];
1041
+ if (!conn) {
1042
+ this._onObservabilityEvent.fire({
1043
+ type: "mcp:client:discover",
1044
+ displayMessage: `Connection not found for ${serverId}`,
1045
+ payload: {},
1046
+ timestamp: Date.now(),
1047
+ id: nanoid()
1048
+ });
1049
+ return;
1050
+ }
1051
+ const result = await conn.discover(options);
1052
+ this._onServerStateChanged.fire();
1053
+ return {
1054
+ ...result,
1055
+ state: conn.connectionState
1056
+ };
1057
+ }
1058
+ /**
612
1059
  * Establish connection in the background after OAuth completion
613
- * This method is called asynchronously and doesn't block the OAuth callback response
1060
+ * This method connects to the server and discovers its capabilities
614
1061
  * @param serverId The server ID to establish connection for
615
1062
  */
616
1063
  async establishConnection(serverId) {
@@ -625,38 +1072,34 @@ var MCPClientManager = class {
625
1072
  });
626
1073
  return;
627
1074
  }
628
- try {
629
- await conn.establishConnection();
630
- this._onConnected.fire(serverId);
631
- } catch (error) {
632
- const url = conn.url.toString();
1075
+ if (conn.connectionState === MCPConnectionState.DISCOVERING || conn.connectionState === MCPConnectionState.READY) {
633
1076
  this._onObservabilityEvent.fire({
634
1077
  type: "mcp:client:connect",
635
- displayMessage: `Failed to establish connection to server ${serverId} with url ${url}`,
1078
+ displayMessage: `establishConnection skipped for ${serverId}, already in ${conn.connectionState} state`,
636
1079
  payload: {
637
- url,
638
- transport: conn.options.transport.type ?? "auto",
639
- state: conn.connectionState,
640
- error: toErrorMessage(error)
1080
+ url: conn.url.toString(),
1081
+ transport: conn.options.transport.type || "unknown",
1082
+ state: conn.connectionState
641
1083
  },
642
1084
  timestamp: Date.now(),
643
1085
  id: nanoid()
644
1086
  });
1087
+ return;
645
1088
  }
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}`));
1089
+ const connectResult = await this.connectToServer(serverId);
1090
+ this._onServerStateChanged.fire();
1091
+ if (connectResult.state === MCPConnectionState.CONNECTED) await this.discoverIfConnected(serverId);
1092
+ this._onObservabilityEvent.fire({
1093
+ type: "mcp:client:connect",
1094
+ displayMessage: `establishConnection completed for ${serverId}, final state: ${conn.connectionState}`,
1095
+ payload: {
1096
+ url: conn.url.toString(),
1097
+ transport: conn.options.transport.type || "unknown",
1098
+ state: conn.connectionState
1099
+ },
1100
+ timestamp: Date.now(),
1101
+ id: nanoid()
1102
+ });
660
1103
  }
661
1104
  /**
662
1105
  * Configure OAuth callback handling
@@ -679,9 +1122,28 @@ var MCPClientManager = class {
679
1122
  return getNamespacedData(this.mcpConnections, "tools");
680
1123
  }
681
1124
  /**
1125
+ * Lazy-loads the jsonSchema function from the AI SDK.
1126
+ *
1127
+ * This defers importing the "ai" package until it's actually needed, which helps reduce
1128
+ * initial bundle size and startup time. The jsonSchema function is required for converting
1129
+ * MCP tools into AI SDK tool definitions via getAITools().
1130
+ *
1131
+ * @internal This method is for internal use only. It's automatically called before operations
1132
+ * that need jsonSchema (like getAITools() or OAuth flows). External consumers should not need
1133
+ * to call this directly.
1134
+ */
1135
+ async ensureJsonSchema() {
1136
+ if (!this.jsonSchema) {
1137
+ const { jsonSchema } = await import("ai");
1138
+ this.jsonSchema = jsonSchema;
1139
+ }
1140
+ }
1141
+ /**
682
1142
  * @returns a set of tools that you can use with the AI SDK
683
1143
  */
684
1144
  getAITools() {
1145
+ if (!this.jsonSchema) throw new Error("jsonSchema not initialized.");
1146
+ 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.`);
685
1147
  return Object.fromEntries(getNamespacedData(this.mcpConnections, "tools").map((tool) => {
686
1148
  return [`tool_${tool.serverId.replace(/-/g, "")}_${tool.name}`, {
687
1149
  description: tool.description,
@@ -711,10 +1173,18 @@ var MCPClientManager = class {
711
1173
  return this.getAITools();
712
1174
  }
713
1175
  /**
714
- * Closes all connections to MCP servers
1176
+ * Closes all active in-memory connections to MCP servers.
1177
+ *
1178
+ * Note: This only closes the transport connections - it does NOT remove
1179
+ * servers from storage. Servers will still be listed and their callback
1180
+ * URLs will still match incoming OAuth requests.
1181
+ *
1182
+ * Use removeServer() instead if you want to fully clean up a server
1183
+ * (closes connection AND removes from storage).
715
1184
  */
716
1185
  async closeAllConnections() {
717
1186
  const ids = Object.keys(this.mcpConnections);
1187
+ for (const id of ids) this.mcpConnections[id].cancelDiscovery();
718
1188
  await Promise.all(ids.map(async (id) => {
719
1189
  await this.mcpConnections[id].client.close();
720
1190
  }));
@@ -731,6 +1201,7 @@ var MCPClientManager = class {
731
1201
  */
732
1202
  async closeConnection(id) {
733
1203
  if (!this.mcpConnections[id]) throw new Error(`Connection with id "${id}" does not exist.`);
1204
+ this.mcpConnections[id].cancelDiscovery();
734
1205
  await this.mcpConnections[id].client.close();
735
1206
  delete this.mcpConnections[id];
736
1207
  const store = this._connectionDisposables.get(id);
@@ -738,13 +1209,29 @@ var MCPClientManager = class {
738
1209
  this._connectionDisposables.delete(id);
739
1210
  }
740
1211
  /**
1212
+ * Remove an MCP server - closes connection if active and removes from storage.
1213
+ */
1214
+ async removeServer(serverId) {
1215
+ if (this.mcpConnections[serverId]) try {
1216
+ await this.closeConnection(serverId);
1217
+ } catch (_e) {}
1218
+ this.removeServerFromStorage(serverId);
1219
+ this._onServerStateChanged.fire();
1220
+ }
1221
+ /**
1222
+ * List all MCP servers from storage
1223
+ */
1224
+ listServers() {
1225
+ return this.getServersFromStorage();
1226
+ }
1227
+ /**
741
1228
  * Dispose the manager and all resources.
742
1229
  */
743
1230
  async dispose() {
744
1231
  try {
745
1232
  await this.closeAllConnections();
746
1233
  } finally {
747
- this._onConnected.dispose();
1234
+ this._onServerStateChanged.dispose();
748
1235
  this._onObservabilityEvent.dispose();
749
1236
  }
750
1237
  }
@@ -806,96 +1293,7 @@ function getNamespacedData(mcpClients, type) {
806
1293
  }
807
1294
 
808
1295
  //#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
1296
+ //#region ../agents/dist/src-BZDh910Z.js
899
1297
  /**
900
1298
  * A generic observability implementation that logs events to the console.
901
1299
  */
@@ -933,7 +1331,6 @@ function getNextCronTime(cron) {
933
1331
  const STATE_ROW_ID = "cf_state_row_id";
934
1332
  const STATE_WAS_CHANGED = "cf_state_was_changed";
935
1333
  const DEFAULT_STATE = {};
936
- const agentContext = new AsyncLocalStorage();
937
1334
  function getCurrentAgent() {
938
1335
  const store = agentContext.getStore();
939
1336
  if (!store) return {
@@ -1014,9 +1411,8 @@ var Agent = class Agent$1 extends Server {
1014
1411
  super(ctx, env$1);
1015
1412
  this._state = DEFAULT_STATE;
1016
1413
  this._disposables = new DisposableStore();
1017
- this._mcpStateRestored = false;
1414
+ this._destroyed = false;
1018
1415
  this._ParentClass = Object.getPrototypeOf(this).constructor;
1019
- this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
1020
1416
  this.initialState = DEFAULT_STATE;
1021
1417
  this.observability = genericObservability;
1022
1418
  this._flushingQueue = false;
@@ -1054,27 +1450,37 @@ var Agent = class Agent$1 extends Server {
1054
1450
  }
1055
1451
  });
1056
1452
  if (row.type === "cron") {
1453
+ if (this._destroyed) return;
1057
1454
  const nextExecutionTime = getNextCronTime(row.cron);
1058
1455
  const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
1059
1456
  this.sql`
1060
1457
  UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
1061
1458
  `;
1062
- } else this.sql`
1459
+ } else {
1460
+ if (this._destroyed) return;
1461
+ this.sql`
1063
1462
  DELETE FROM cf_agents_schedules WHERE id = ${row.id}
1064
1463
  `;
1464
+ }
1065
1465
  }
1466
+ if (this._destroyed) return;
1066
1467
  await this._scheduleNextAlarm();
1067
1468
  };
1068
1469
  if (!wrappedClasses.has(this.constructor)) {
1069
1470
  this._autoWrapCustomMethods();
1070
1471
  wrappedClasses.add(this.constructor);
1071
1472
  }
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
- }));
1473
+ this.sql`
1474
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
1475
+ id TEXT PRIMARY KEY NOT NULL,
1476
+ name TEXT NOT NULL,
1477
+ server_url TEXT NOT NULL,
1478
+ callback_url TEXT NOT NULL,
1479
+ client_id TEXT,
1480
+ auth_url TEXT,
1481
+ server_options TEXT
1482
+ )
1483
+ `;
1078
1484
  this.sql`
1079
1485
  CREATE TABLE IF NOT EXISTS cf_agents_state (
1080
1486
  id TEXT PRIMARY KEY NOT NULL,
@@ -1089,34 +1495,25 @@ var Agent = class Agent$1 extends Server {
1089
1495
  created_at INTEGER DEFAULT (unixepoch())
1090
1496
  )
1091
1497
  `;
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
1498
  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
1499
+ CREATE TABLE IF NOT EXISTS cf_agents_schedules (
1500
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
1501
+ callback TEXT,
1502
+ payload TEXT,
1503
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
1504
+ time INTEGER,
1505
+ delayInSeconds INTEGER,
1506
+ cron TEXT,
1507
+ created_at INTEGER DEFAULT (unixepoch())
1118
1508
  )
1119
1509
  `;
1510
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1", { storage: this.ctx.storage });
1511
+ this._disposables.add(this.mcp.onServerStateChanged(async () => {
1512
+ this.broadcastMcpServers();
1513
+ }));
1514
+ this._disposables.add(this.mcp.onObservabilityEvent((event) => {
1515
+ this.observability?.emit(event);
1516
+ }));
1120
1517
  const _onRequest = this.onRequest.bind(this);
1121
1518
  this.onRequest = (request) => {
1122
1519
  return agentContext.run({
@@ -1125,17 +1522,9 @@ var Agent = class Agent$1 extends Server {
1125
1522
  request,
1126
1523
  email: void 0
1127
1524
  }, 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
- }
1525
+ await this.mcp.ensureJsonSchema();
1526
+ const oauthResponse = await this.handleMcpOAuthCallback(request);
1527
+ if (oauthResponse) return oauthResponse;
1139
1528
  return this._tryCatch(() => _onRequest(request));
1140
1529
  });
1141
1530
  };
@@ -1147,6 +1536,7 @@ var Agent = class Agent$1 extends Server {
1147
1536
  request: void 0,
1148
1537
  email: void 0
1149
1538
  }, async () => {
1539
+ await this.mcp.ensureJsonSchema();
1150
1540
  if (typeof message !== "string") return this._tryCatch(() => _onMessage(connection, message));
1151
1541
  let parsed;
1152
1542
  try {
@@ -1211,7 +1601,7 @@ var Agent = class Agent$1 extends Server {
1211
1601
  connection,
1212
1602
  request: ctx$1.request,
1213
1603
  email: void 0
1214
- }, () => {
1604
+ }, async () => {
1215
1605
  if (this.state) connection.send(JSON.stringify({
1216
1606
  state: this.state,
1217
1607
  type: MessageType.CF_AGENT_STATE
@@ -1239,7 +1629,7 @@ var Agent = class Agent$1 extends Server {
1239
1629
  email: void 0
1240
1630
  }, async () => {
1241
1631
  await this._tryCatch(async () => {
1242
- await this._ensureMcpStateRestored();
1632
+ await this.mcp.restoreConnectionsFromStorage(this.name);
1243
1633
  this.broadcastMcpServers();
1244
1634
  return _onStart(props);
1245
1635
  });
@@ -1585,10 +1975,7 @@ var Agent = class Agent$1 extends Server {
1585
1975
  const result = this.sql`
1586
1976
  SELECT * FROM cf_agents_schedules WHERE id = ${id}
1587
1977
  `;
1588
- if (!result) {
1589
- console.error(`schedule ${id} not found`);
1590
- return;
1591
- }
1978
+ if (!result || result.length === 0) return;
1592
1979
  return {
1593
1980
  ...result[0],
1594
1981
  payload: JSON.parse(result[0].payload)
@@ -1625,11 +2012,12 @@ var Agent = class Agent$1 extends Server {
1625
2012
  /**
1626
2013
  * Cancel a scheduled task
1627
2014
  * @param id ID of the task to cancel
1628
- * @returns true if the task was cancelled, false otherwise
2015
+ * @returns true if the task was cancelled, false if the task was not found
1629
2016
  */
1630
2017
  async cancelSchedule(id) {
1631
2018
  const schedule = await this.getSchedule(id);
1632
- if (schedule) this.observability?.emit({
2019
+ if (!schedule) return false;
2020
+ this.observability?.emit({
1633
2021
  displayMessage: `Schedule ${id} cancelled`,
1634
2022
  id: nanoid(),
1635
2023
  payload: {
@@ -1646,7 +2034,7 @@ var Agent = class Agent$1 extends Server {
1646
2034
  async _scheduleNextAlarm() {
1647
2035
  const result = this.sql`
1648
2036
  SELECT time FROM cf_agents_schedules
1649
- WHERE time > ${Math.floor(Date.now() / 1e3)}
2037
+ WHERE time >= ${Math.floor(Date.now() / 1e3)}
1650
2038
  ORDER BY time ASC
1651
2039
  LIMIT 1
1652
2040
  `;
@@ -1660,15 +2048,18 @@ var Agent = class Agent$1 extends Server {
1660
2048
  * Destroy the Agent, removing all state and scheduled tasks
1661
2049
  */
1662
2050
  async destroy() {
2051
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
1663
2052
  this.sql`DROP TABLE IF EXISTS cf_agents_state`;
1664
2053
  this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
1665
- this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
1666
2054
  this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
1667
2055
  await this.ctx.storage.deleteAlarm();
1668
2056
  await this.ctx.storage.deleteAll();
1669
2057
  this._disposables.dispose();
1670
- await this.mcp.dispose?.();
1671
- this.ctx.abort("destroyed");
2058
+ await this.mcp.dispose();
2059
+ this._destroyed = true;
2060
+ setTimeout(() => {
2061
+ this.ctx.abort("destroyed");
2062
+ }, 0);
1672
2063
  this.observability?.emit({
1673
2064
  displayMessage: "Agent destroyed",
1674
2065
  id: nanoid(),
@@ -1684,43 +2075,6 @@ var Agent = class Agent$1 extends Server {
1684
2075
  _isCallable(method) {
1685
2076
  return callableMetadata.has(this[method]);
1686
2077
  }
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
2078
  /**
1725
2079
  * Connect to a new MCP Server
1726
2080
  *
@@ -1729,7 +2083,8 @@ var Agent = class Agent$1 extends Server {
1729
2083
  * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
1730
2084
  * @param agentsPrefix agents routing prefix if not using `agents`
1731
2085
  * @param options MCP client and transport options
1732
- * @returns authUrl
2086
+ * @returns Server id and state - either "authenticating" with authUrl, or "ready"
2087
+ * @throws If connection or discovery fails
1733
2088
  */
1734
2089
  async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
1735
2090
  let resolvedCallbackHost = callbackHost;
@@ -1740,29 +2095,10 @@ var Agent = class Agent$1 extends Server {
1740
2095
  resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
1741
2096
  }
1742
2097
  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) {
2098
+ await this.mcp.ensureJsonSchema();
2099
+ const id = nanoid(8);
1761
2100
  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
- }
2101
+ authProvider.serverId = id;
1766
2102
  const transportType = options?.transport?.type ?? "auto";
1767
2103
  let headerTransportOpts = {};
1768
2104
  if (options?.transport?.headers) headerTransportOpts = {
@@ -1772,28 +2108,33 @@ var Agent = class Agent$1 extends Server {
1772
2108
  }) },
1773
2109
  requestInit: { headers: options?.transport?.headers }
1774
2110
  };
1775
- const { id, authUrl, clientId } = await this.mcp.connect(url, {
2111
+ await this.mcp.registerServer(id, {
2112
+ url,
2113
+ name: serverName,
2114
+ callbackUrl,
1776
2115
  client: options?.client,
1777
- reconnect,
1778
2116
  transport: {
1779
2117
  ...headerTransportOpts,
1780
2118
  authProvider,
1781
2119
  type: transportType
1782
2120
  }
1783
2121
  });
2122
+ const result = await this.mcp.connectToServer(id);
2123
+ if (result.state === MCPConnectionState.FAILED) throw new Error(`Failed to connect to MCP server at ${url}: ${result.error}`);
2124
+ if (result.state === MCPConnectionState.AUTHENTICATING) return {
2125
+ id,
2126
+ state: result.state,
2127
+ authUrl: result.authUrl
2128
+ };
2129
+ const discoverResult = await this.mcp.discoverIfConnected(id);
2130
+ if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover MCP server capabilities: ${discoverResult.error}`);
1784
2131
  return {
1785
- authUrl,
1786
- clientId,
1787
- id
2132
+ id,
2133
+ state: MCPConnectionState.READY
1788
2134
  };
1789
2135
  }
1790
2136
  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();
2137
+ await this.mcp.removeServer(id);
1797
2138
  }
1798
2139
  getMcpServers() {
1799
2140
  const mcpState = {
@@ -1802,18 +2143,18 @@ var Agent = class Agent$1 extends Server {
1802
2143
  servers: {},
1803
2144
  tools: this.mcp.listTools()
1804
2145
  };
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
- `;
2146
+ const servers = this.mcp.listServers();
1808
2147
  if (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {
1809
2148
  const serverConn = this.mcp.mcpConnections[server.id];
2149
+ let defaultState = "not-connected";
2150
+ if (!serverConn && server.auth_url) defaultState = "authenticating";
1810
2151
  mcpState.servers[server.id] = {
1811
2152
  auth_url: server.auth_url,
1812
2153
  capabilities: serverConn?.serverCapabilities ?? null,
1813
2154
  instructions: serverConn?.instructions ?? null,
1814
2155
  name: server.name,
1815
2156
  server_url: server.server_url,
1816
- state: serverConn?.connectionState ?? "authenticating"
2157
+ state: serverConn?.connectionState ?? defaultState
1817
2158
  };
1818
2159
  }
1819
2160
  return mcpState;
@@ -1825,6 +2166,28 @@ var Agent = class Agent$1 extends Server {
1825
2166
  }));
1826
2167
  }
1827
2168
  /**
2169
+ * Handle MCP OAuth callback request if it's an OAuth callback.
2170
+ *
2171
+ * This method encapsulates the entire OAuth callback flow:
2172
+ * 1. Checks if the request is an MCP OAuth callback
2173
+ * 2. Processes the OAuth code exchange
2174
+ * 3. Establishes the connection if successful
2175
+ * 4. Broadcasts MCP server state updates
2176
+ * 5. Returns the appropriate HTTP response
2177
+ *
2178
+ * @param request The incoming HTTP request
2179
+ * @returns Response if this was an OAuth callback, null otherwise
2180
+ */
2181
+ async handleMcpOAuthCallback(request) {
2182
+ if (!this.mcp.isCallbackRequest(request)) return null;
2183
+ const result = await this.mcp.handleCallbackRequest(request);
2184
+ if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
2185
+ console.error("[Agent handleMcpOAuthCallback] Connection establishment failed:", error);
2186
+ });
2187
+ this.broadcastMcpServers();
2188
+ return this.handleOAuthCallbackResponse(result, request);
2189
+ }
2190
+ /**
1828
2191
  * Handle OAuth callback response using MCPClientManager configuration
1829
2192
  * @param result OAuth callback result
1830
2193
  * @param request The original request (needed for base URL)
@@ -1833,10 +2196,21 @@ var Agent = class Agent$1 extends Server {
1833
2196
  handleOAuthCallbackResponse(result, request) {
1834
2197
  const config = this.mcp.getOAuthCallbackConfig();
1835
2198
  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);
2199
+ const baseOrigin = new URL(request.url).origin;
2200
+ if (config?.successRedirect && result.authSuccess) try {
2201
+ return Response.redirect(new URL(config.successRedirect, baseOrigin).href);
2202
+ } catch (e) {
2203
+ console.error("Invalid successRedirect URL:", config.successRedirect, e);
2204
+ return Response.redirect(baseOrigin);
2205
+ }
2206
+ if (config?.errorRedirect && !result.authSuccess) try {
2207
+ const errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`;
2208
+ return Response.redirect(new URL(errorUrl, baseOrigin).href);
2209
+ } catch (e) {
2210
+ console.error("Invalid errorRedirect URL:", config.errorRedirect, e);
2211
+ return Response.redirect(baseOrigin);
2212
+ }
2213
+ return Response.redirect(baseOrigin);
1840
2214
  }
1841
2215
  };
1842
2216
  const wrappedClasses = /* @__PURE__ */ new Set();
@@ -1862,10 +2236,15 @@ async function routeAgentRequest(request, env$1, options) {
1862
2236
  prefix: "agents",
1863
2237
  ...options
1864
2238
  });
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
- } });
2239
+ if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
2240
+ const newHeaders = new Headers(response.headers);
2241
+ for (const [key, value] of Object.entries(corsHeaders)) newHeaders.set(key, value);
2242
+ response = new Response(response.body, {
2243
+ status: response.status,
2244
+ statusText: response.statusText,
2245
+ headers: newHeaders
2246
+ });
2247
+ }
1869
2248
  return response;
1870
2249
  }
1871
2250
  /**