agents 0.0.0-d045755 → 0.0.0-d08612f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +257 -27
  2. package/dist/ai-chat-agent.d.ts +142 -12
  3. package/dist/ai-chat-agent.js +812 -159
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-DguhuLKF.js +155 -0
  6. package/dist/ai-chat-v5-migration-DguhuLKF.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +79 -72
  10. package/dist/ai-react.js +411 -185
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-CwgHzwUb.js +24 -0
  13. package/dist/ai-types-CwgHzwUb.js.map +1 -0
  14. package/dist/ai-types-D_hTbf25.d.ts +103 -0
  15. package/dist/ai-types.d.ts +6 -69
  16. package/dist/ai-types.js +3 -1
  17. package/dist/cli/index.d.ts +1 -0
  18. package/dist/cli/index.js +28 -0
  19. package/dist/cli/index.js.map +1 -0
  20. package/dist/client-CcyhkGfN.js +117 -0
  21. package/dist/client-CcyhkGfN.js.map +1 -0
  22. package/dist/client-ClORm6f0.d.ts +104 -0
  23. package/dist/client-DfIOsabL.d.ts +834 -0
  24. package/dist/client-QZa2Rq0l.js +1105 -0
  25. package/dist/client-QZa2Rq0l.js.map +1 -0
  26. package/dist/client.d.ts +12 -79
  27. package/dist/client.js +3 -137
  28. package/dist/codemode/ai.d.ts +27 -0
  29. package/dist/codemode/ai.js +152 -0
  30. package/dist/codemode/ai.js.map +1 -0
  31. package/dist/context-BkKbAa1R.js +8 -0
  32. package/dist/context-BkKbAa1R.js.map +1 -0
  33. package/dist/context-_sPQqJWv.d.ts +24 -0
  34. package/dist/context.d.ts +6 -0
  35. package/dist/context.js +3 -0
  36. package/dist/do-oauth-client-provider-B-ryFIPr.d.ts +70 -0
  37. package/dist/do-oauth-client-provider-B1fVIshX.js +155 -0
  38. package/dist/do-oauth-client-provider-B1fVIshX.js.map +1 -0
  39. package/dist/index-CyDpAVHZ.d.ts +58 -0
  40. package/dist/index-DPJ32qQn.d.ts +577 -0
  41. package/dist/index.d.ts +63 -302
  42. package/dist/index.js +8 -22
  43. package/dist/mcp/client.d.ts +4 -0
  44. package/dist/mcp/client.js +4 -0
  45. package/dist/mcp/do-oauth-client-provider.d.ts +2 -0
  46. package/dist/mcp/do-oauth-client-provider.js +3 -0
  47. package/dist/mcp/index.d.ts +194 -0
  48. package/dist/mcp/index.js +1448 -0
  49. package/dist/mcp/index.js.map +1 -0
  50. package/dist/mcp/x402.d.ts +34 -0
  51. package/dist/mcp/x402.js +198 -0
  52. package/dist/mcp/x402.js.map +1 -0
  53. package/dist/mcp-CzbSsLfc.d.ts +61 -0
  54. package/dist/observability/index.d.ts +3 -0
  55. package/dist/observability/index.js +8 -0
  56. package/dist/react-DTzwSLAh.d.ts +137 -0
  57. package/dist/react.d.ts +15 -39
  58. package/dist/react.js +192 -93
  59. package/dist/react.js.map +1 -1
  60. package/dist/schedule.d.ts +89 -12
  61. package/dist/schedule.js +46 -23
  62. package/dist/schedule.js.map +1 -1
  63. package/dist/serializable-C4GLimgv.d.ts +39 -0
  64. package/dist/serializable.d.ts +7 -0
  65. package/dist/serializable.js +1 -0
  66. package/dist/src-BmbDclOA.js +1181 -0
  67. package/dist/src-BmbDclOA.js.map +1 -0
  68. package/package.json +133 -51
  69. package/dist/ai-types.js.map +0 -1
  70. package/dist/chunk-3PRPPPJY.js +0 -596
  71. package/dist/chunk-3PRPPPJY.js.map +0 -1
  72. package/dist/chunk-HMLY7DHA.js +0 -16
  73. package/dist/chunk-HMLY7DHA.js.map +0 -1
  74. package/dist/client.js.map +0 -1
  75. package/dist/index.js.map +0 -1
  76. package/dist/mcp.d.ts +0 -58
  77. package/dist/mcp.js +0 -945
  78. package/dist/mcp.js.map +0 -1
  79. package/src/index.ts +0 -922
@@ -0,0 +1,1105 @@
1
+ import { t as DurableObjectOAuthClientProvider } from "./do-oauth-client-provider-B1fVIshX.js";
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
+
9
+ //#region src/core/events.ts
10
+ function toDisposable(fn) {
11
+ return { dispose: fn };
12
+ }
13
+ var DisposableStore = class {
14
+ constructor() {
15
+ this._items = [];
16
+ }
17
+ add(d) {
18
+ this._items.push(d);
19
+ return d;
20
+ }
21
+ dispose() {
22
+ while (this._items.length) try {
23
+ this._items.pop().dispose();
24
+ } catch {}
25
+ }
26
+ };
27
+ var Emitter = class {
28
+ constructor() {
29
+ this._listeners = /* @__PURE__ */ new Set();
30
+ this.event = (listener) => {
31
+ this._listeners.add(listener);
32
+ return toDisposable(() => this._listeners.delete(listener));
33
+ };
34
+ }
35
+ fire(data) {
36
+ for (const listener of [...this._listeners]) try {
37
+ listener(data);
38
+ } catch (err) {
39
+ console.error("Emitter listener error:", err);
40
+ }
41
+ }
42
+ dispose() {
43
+ this._listeners.clear();
44
+ }
45
+ };
46
+
47
+ //#endregion
48
+ //#region src/mcp/errors.ts
49
+ function toErrorMessage(error) {
50
+ return error instanceof Error ? error.message : String(error);
51
+ }
52
+ function isUnauthorized(error) {
53
+ const msg = toErrorMessage(error);
54
+ return msg.includes("Unauthorized") || msg.includes("401");
55
+ }
56
+ function isTransportNotImplemented(error) {
57
+ const msg = toErrorMessage(error);
58
+ return msg.includes("404") || msg.includes("405") || msg.includes("Not Implemented") || msg.includes("not implemented");
59
+ }
60
+
61
+ //#endregion
62
+ //#region src/mcp/client-connection.ts
63
+ /**
64
+ * Connection state machine for MCP client connections.
65
+ *
66
+ * State transitions:
67
+ * - Non-OAuth: init() → CONNECTING → DISCOVERING → READY
68
+ * - OAuth: init() → AUTHENTICATING → (callback) → CONNECTING → DISCOVERING → READY
69
+ * - Any state can transition to FAILED on error
70
+ */
71
+ const MCPConnectionState = {
72
+ AUTHENTICATING: "authenticating",
73
+ CONNECTING: "connecting",
74
+ CONNECTED: "connected",
75
+ DISCOVERING: "discovering",
76
+ READY: "ready",
77
+ FAILED: "failed"
78
+ };
79
+ var MCPClientConnection = class {
80
+ constructor(url, info, options = {
81
+ client: {},
82
+ transport: {}
83
+ }) {
84
+ this.url = url;
85
+ this.options = options;
86
+ this.connectionState = MCPConnectionState.CONNECTING;
87
+ this.tools = [];
88
+ this.prompts = [];
89
+ this.resources = [];
90
+ this.resourceTemplates = [];
91
+ this._onObservabilityEvent = new Emitter();
92
+ this.onObservabilityEvent = this._onObservabilityEvent.event;
93
+ this.client = new Client(info, {
94
+ ...options.client,
95
+ capabilities: {
96
+ ...options.client?.capabilities,
97
+ elicitation: {}
98
+ }
99
+ });
100
+ }
101
+ /**
102
+ * Initialize a client connection, if authentication is required, the connection will be in the AUTHENTICATING state
103
+ * Sets connection state based on the result and emits observability events
104
+ *
105
+ * @returns Error message if connection failed, undefined otherwise
106
+ */
107
+ async init() {
108
+ const transportType = this.options.transport.type;
109
+ if (!transportType) throw new Error("Transport type must be specified");
110
+ const res = await this.tryConnect(transportType);
111
+ this.connectionState = res.state;
112
+ if (res.state === MCPConnectionState.CONNECTED && res.transport) {
113
+ this.client.setRequestHandler(ElicitRequestSchema, async (request) => {
114
+ return await this.handleElicitationRequest(request);
115
+ });
116
+ this.lastConnectedTransport = res.transport;
117
+ this._onObservabilityEvent.fire({
118
+ type: "mcp:client:connect",
119
+ displayMessage: `Connected successfully using ${res.transport} transport for ${this.url.toString()}`,
120
+ payload: {
121
+ url: this.url.toString(),
122
+ transport: res.transport,
123
+ state: this.connectionState
124
+ },
125
+ timestamp: Date.now(),
126
+ id: nanoid()
127
+ });
128
+ return;
129
+ } else if (res.state === MCPConnectionState.FAILED && res.error) {
130
+ const errorMessage = toErrorMessage(res.error);
131
+ this._onObservabilityEvent.fire({
132
+ type: "mcp:client:connect",
133
+ displayMessage: `Failed to connect to ${this.url.toString()}: ${errorMessage}`,
134
+ payload: {
135
+ url: this.url.toString(),
136
+ transport: transportType,
137
+ state: this.connectionState,
138
+ error: errorMessage
139
+ },
140
+ timestamp: Date.now(),
141
+ id: nanoid()
142
+ });
143
+ return errorMessage;
144
+ }
145
+ }
146
+ /**
147
+ * Finish OAuth by probing transports based on configured type.
148
+ * - Explicit: finish on that transport
149
+ * - Auto: try streamable-http, then sse on 404/405/Not Implemented
150
+ */
151
+ async finishAuthProbe(code) {
152
+ if (!this.options.transport.authProvider) throw new Error("No auth provider configured");
153
+ const configuredType = this.options.transport.type;
154
+ if (!configuredType) throw new Error("Transport type must be specified");
155
+ const finishAuth = async (base) => {
156
+ await this.getTransport(base).finishAuth(code);
157
+ };
158
+ if (configuredType === "sse" || configuredType === "streamable-http") {
159
+ await finishAuth(configuredType);
160
+ return;
161
+ }
162
+ try {
163
+ await finishAuth("streamable-http");
164
+ } catch (e) {
165
+ if (isTransportNotImplemented(e)) {
166
+ await finishAuth("sse");
167
+ return;
168
+ }
169
+ throw e;
170
+ }
171
+ }
172
+ /**
173
+ * Complete OAuth authorization
174
+ */
175
+ async completeAuthorization(code) {
176
+ if (this.connectionState !== MCPConnectionState.AUTHENTICATING) throw new Error("Connection must be in authenticating state to complete authorization");
177
+ try {
178
+ await this.finishAuthProbe(code);
179
+ this.connectionState = MCPConnectionState.CONNECTING;
180
+ } catch (error) {
181
+ this.connectionState = MCPConnectionState.FAILED;
182
+ throw error;
183
+ }
184
+ }
185
+ /**
186
+ * Discover server capabilities and register tools, resources, prompts, and templates.
187
+ * This method does the work but does not manage connection state - that's handled by discover().
188
+ */
189
+ async discoverAndRegister() {
190
+ this.serverCapabilities = this.client.getServerCapabilities();
191
+ if (!this.serverCapabilities) throw new Error("The MCP Server failed to return server capabilities");
192
+ const operations = [];
193
+ const operationNames = [];
194
+ operations.push(Promise.resolve(this.client.getInstructions()));
195
+ operationNames.push("instructions");
196
+ if (this.serverCapabilities.tools) {
197
+ operations.push(this.registerTools());
198
+ operationNames.push("tools");
199
+ }
200
+ if (this.serverCapabilities.resources) {
201
+ operations.push(this.registerResources());
202
+ operationNames.push("resources");
203
+ }
204
+ if (this.serverCapabilities.prompts) {
205
+ operations.push(this.registerPrompts());
206
+ operationNames.push("prompts");
207
+ }
208
+ if (this.serverCapabilities.resources) {
209
+ operations.push(this.registerResourceTemplates());
210
+ operationNames.push("resource templates");
211
+ }
212
+ try {
213
+ const results = await Promise.all(operations);
214
+ for (let i = 0; i < results.length; i++) {
215
+ const result = results[i];
216
+ switch (operationNames[i]) {
217
+ case "instructions":
218
+ this.instructions = result;
219
+ break;
220
+ case "tools":
221
+ this.tools = result;
222
+ break;
223
+ case "resources":
224
+ this.resources = result;
225
+ break;
226
+ case "prompts":
227
+ this.prompts = result;
228
+ break;
229
+ case "resource templates":
230
+ this.resourceTemplates = result;
231
+ break;
232
+ }
233
+ }
234
+ } catch (error) {
235
+ this._onObservabilityEvent.fire({
236
+ type: "mcp:client:discover",
237
+ displayMessage: `Failed to discover capabilities for ${this.url.toString()}: ${toErrorMessage(error)}`,
238
+ payload: {
239
+ url: this.url.toString(),
240
+ error: toErrorMessage(error)
241
+ },
242
+ timestamp: Date.now(),
243
+ id: nanoid()
244
+ });
245
+ throw error;
246
+ }
247
+ }
248
+ /**
249
+ * Discover server capabilities with timeout and cancellation support.
250
+ * If called while a previous discovery is in-flight, the previous discovery will be aborted.
251
+ *
252
+ * @param options Optional configuration
253
+ * @param options.timeoutMs Timeout in milliseconds (default: 15000)
254
+ * @returns Result indicating success/failure with optional error message
255
+ */
256
+ async discover(options = {}) {
257
+ const { timeoutMs = 15e3 } = options;
258
+ if (this.connectionState !== MCPConnectionState.CONNECTED && this.connectionState !== MCPConnectionState.READY) {
259
+ this._onObservabilityEvent.fire({
260
+ type: "mcp:client:discover",
261
+ displayMessage: `Discovery skipped for ${this.url.toString()}, state is ${this.connectionState}`,
262
+ payload: {
263
+ url: this.url.toString(),
264
+ state: this.connectionState
265
+ },
266
+ timestamp: Date.now(),
267
+ id: nanoid()
268
+ });
269
+ return {
270
+ success: false,
271
+ error: `Discovery skipped - connection in ${this.connectionState} state`
272
+ };
273
+ }
274
+ if (this._discoveryAbortController) {
275
+ this._discoveryAbortController.abort();
276
+ this._discoveryAbortController = void 0;
277
+ }
278
+ const abortController = new AbortController();
279
+ this._discoveryAbortController = abortController;
280
+ this.connectionState = MCPConnectionState.DISCOVERING;
281
+ let timeoutId;
282
+ try {
283
+ const timeoutPromise = new Promise((_, reject) => {
284
+ timeoutId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Discovery timed out after ${timeoutMs}ms`)), timeoutMs);
285
+ });
286
+ if (abortController.signal.aborted) throw new Error("Discovery was cancelled");
287
+ const abortPromise = new Promise((_, reject) => {
288
+ abortController.signal.addEventListener("abort", () => {
289
+ reject(/* @__PURE__ */ new Error("Discovery was cancelled"));
290
+ });
291
+ });
292
+ await Promise.race([
293
+ this.discoverAndRegister(),
294
+ timeoutPromise,
295
+ abortPromise
296
+ ]);
297
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
298
+ this.connectionState = MCPConnectionState.READY;
299
+ this._onObservabilityEvent.fire({
300
+ type: "mcp:client:discover",
301
+ displayMessage: `Discovery completed for ${this.url.toString()}`,
302
+ payload: { url: this.url.toString() },
303
+ timestamp: Date.now(),
304
+ id: nanoid()
305
+ });
306
+ return { success: true };
307
+ } catch (e) {
308
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
309
+ this.connectionState = MCPConnectionState.CONNECTED;
310
+ return {
311
+ success: false,
312
+ error: e instanceof Error ? e.message : String(e)
313
+ };
314
+ } finally {
315
+ this._discoveryAbortController = void 0;
316
+ }
317
+ }
318
+ /**
319
+ * Cancel any in-flight discovery operation.
320
+ * Called when closing the connection.
321
+ */
322
+ cancelDiscovery() {
323
+ if (this._discoveryAbortController) {
324
+ this._discoveryAbortController.abort();
325
+ this._discoveryAbortController = void 0;
326
+ }
327
+ }
328
+ /**
329
+ * Notification handler registration for tools
330
+ * Should only be called if serverCapabilities.tools exists
331
+ */
332
+ async registerTools() {
333
+ if (this.serverCapabilities?.tools?.listChanged) this.client.setNotificationHandler(ToolListChangedNotificationSchema, async (_notification) => {
334
+ this.tools = await this.fetchTools();
335
+ });
336
+ return this.fetchTools();
337
+ }
338
+ /**
339
+ * Notification handler registration for resources
340
+ * Should only be called if serverCapabilities.resources exists
341
+ */
342
+ async registerResources() {
343
+ if (this.serverCapabilities?.resources?.listChanged) this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_notification) => {
344
+ this.resources = await this.fetchResources();
345
+ });
346
+ return this.fetchResources();
347
+ }
348
+ /**
349
+ * Notification handler registration for prompts
350
+ * Should only be called if serverCapabilities.prompts exists
351
+ */
352
+ async registerPrompts() {
353
+ if (this.serverCapabilities?.prompts?.listChanged) this.client.setNotificationHandler(PromptListChangedNotificationSchema, async (_notification) => {
354
+ this.prompts = await this.fetchPrompts();
355
+ });
356
+ return this.fetchPrompts();
357
+ }
358
+ async registerResourceTemplates() {
359
+ return this.fetchResourceTemplates();
360
+ }
361
+ async fetchTools() {
362
+ let toolsAgg = [];
363
+ let toolsResult = { tools: [] };
364
+ do {
365
+ toolsResult = await this.client.listTools({ cursor: toolsResult.nextCursor }).catch(this._capabilityErrorHandler({ tools: [] }, "tools/list"));
366
+ toolsAgg = toolsAgg.concat(toolsResult.tools);
367
+ } while (toolsResult.nextCursor);
368
+ return toolsAgg;
369
+ }
370
+ async fetchResources() {
371
+ let resourcesAgg = [];
372
+ let resourcesResult = { resources: [] };
373
+ do {
374
+ resourcesResult = await this.client.listResources({ cursor: resourcesResult.nextCursor }).catch(this._capabilityErrorHandler({ resources: [] }, "resources/list"));
375
+ resourcesAgg = resourcesAgg.concat(resourcesResult.resources);
376
+ } while (resourcesResult.nextCursor);
377
+ return resourcesAgg;
378
+ }
379
+ async fetchPrompts() {
380
+ let promptsAgg = [];
381
+ let promptsResult = { prompts: [] };
382
+ do {
383
+ promptsResult = await this.client.listPrompts({ cursor: promptsResult.nextCursor }).catch(this._capabilityErrorHandler({ prompts: [] }, "prompts/list"));
384
+ promptsAgg = promptsAgg.concat(promptsResult.prompts);
385
+ } while (promptsResult.nextCursor);
386
+ return promptsAgg;
387
+ }
388
+ async fetchResourceTemplates() {
389
+ let templatesAgg = [];
390
+ let templatesResult = { resourceTemplates: [] };
391
+ do {
392
+ templatesResult = await this.client.listResourceTemplates({ cursor: templatesResult.nextCursor }).catch(this._capabilityErrorHandler({ resourceTemplates: [] }, "resources/templates/list"));
393
+ templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);
394
+ } while (templatesResult.nextCursor);
395
+ return templatesAgg;
396
+ }
397
+ /**
398
+ * Handle elicitation request from server
399
+ * Automatically uses the Agent's built-in elicitation handling if available
400
+ */
401
+ async handleElicitationRequest(_request) {
402
+ throw new Error("Elicitation handler must be implemented for your platform. Override handleElicitationRequest method.");
403
+ }
404
+ /**
405
+ * Get the transport for the client
406
+ * @param transportType - The transport type to get
407
+ * @returns The transport for the client
408
+ */
409
+ getTransport(transportType) {
410
+ switch (transportType) {
411
+ case "streamable-http": return new StreamableHTTPClientTransport(this.url, this.options.transport);
412
+ case "sse": return new SSEClientTransport(this.url, this.options.transport);
413
+ default: throw new Error(`Unsupported transport type: ${transportType}`);
414
+ }
415
+ }
416
+ async tryConnect(transportType) {
417
+ const transports = transportType === "auto" ? ["streamable-http", "sse"] : [transportType];
418
+ for (const currentTransportType of transports) {
419
+ const isLastTransport = currentTransportType === transports[transports.length - 1];
420
+ const hasFallback = transportType === "auto" && currentTransportType === "streamable-http" && !isLastTransport;
421
+ const transport = this.getTransport(currentTransportType);
422
+ try {
423
+ await this.client.connect(transport);
424
+ return {
425
+ state: MCPConnectionState.CONNECTED,
426
+ transport: currentTransportType
427
+ };
428
+ } catch (e) {
429
+ const error = e instanceof Error ? e : new Error(String(e));
430
+ if (isUnauthorized(error)) return { state: MCPConnectionState.AUTHENTICATING };
431
+ if (isTransportNotImplemented(error) && hasFallback) continue;
432
+ return {
433
+ state: MCPConnectionState.FAILED,
434
+ error
435
+ };
436
+ }
437
+ }
438
+ return {
439
+ state: MCPConnectionState.FAILED,
440
+ error: /* @__PURE__ */ new Error("No transports available")
441
+ };
442
+ }
443
+ _capabilityErrorHandler(empty, method) {
444
+ return (e) => {
445
+ if (e.code === -32601) {
446
+ const url = this.url.toString();
447
+ this._onObservabilityEvent.fire({
448
+ type: "mcp:client:discover",
449
+ displayMessage: `The server advertised support for the capability ${method.split("/")[0]}, but returned "Method not found" for '${method}' for ${url}`,
450
+ payload: {
451
+ url,
452
+ capability: method.split("/")[0],
453
+ error: toErrorMessage(e)
454
+ },
455
+ timestamp: Date.now(),
456
+ id: nanoid()
457
+ });
458
+ return empty;
459
+ }
460
+ throw e;
461
+ };
462
+ }
463
+ };
464
+
465
+ //#endregion
466
+ //#region src/mcp/client.ts
467
+ const defaultClientOptions = { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() };
468
+ /**
469
+ * Utility class that aggregates multiple MCP clients into one
470
+ */
471
+ var MCPClientManager = class {
472
+ /**
473
+ * @param _name Name of the MCP client
474
+ * @param _version Version of the MCP Client
475
+ * @param options Storage adapter for persisting MCP server state
476
+ */
477
+ constructor(_name, _version, options) {
478
+ this._name = _name;
479
+ this._version = _version;
480
+ this.mcpConnections = {};
481
+ this._didWarnAboutUnstableGetAITools = false;
482
+ this._connectionDisposables = /* @__PURE__ */ new Map();
483
+ this._isRestored = false;
484
+ this._onObservabilityEvent = new Emitter();
485
+ this.onObservabilityEvent = this._onObservabilityEvent.event;
486
+ this._onServerStateChanged = new Emitter();
487
+ this.onServerStateChanged = this._onServerStateChanged.event;
488
+ if (!options.storage) throw new Error("MCPClientManager requires a valid DurableObjectStorage instance");
489
+ this._storage = options.storage;
490
+ }
491
+ sql(query, ...bindings) {
492
+ return [...this._storage.sql.exec(query, ...bindings)];
493
+ }
494
+ saveServerToStorage(server) {
495
+ this.sql(`INSERT OR REPLACE INTO cf_agents_mcp_servers (
496
+ id, name, server_url, client_id, auth_url, callback_url, server_options
497
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)`, server.id, server.name, server.server_url, server.client_id ?? null, server.auth_url ?? null, server.callback_url, server.server_options ?? null);
498
+ }
499
+ removeServerFromStorage(serverId) {
500
+ this.sql("DELETE FROM cf_agents_mcp_servers WHERE id = ?", serverId);
501
+ }
502
+ getServersFromStorage() {
503
+ return this.sql("SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers");
504
+ }
505
+ clearServerAuthUrl(serverId) {
506
+ this.sql("UPDATE cf_agents_mcp_servers SET auth_url = NULL WHERE id = ?", serverId);
507
+ }
508
+ /**
509
+ * Create an auth provider for a server
510
+ * @internal
511
+ */
512
+ createAuthProvider(serverId, callbackUrl, clientName, clientId) {
513
+ if (!this._storage) throw new Error("Cannot create auth provider: storage is not initialized");
514
+ const authProvider = new DurableObjectOAuthClientProvider(this._storage, clientName, callbackUrl);
515
+ authProvider.serverId = serverId;
516
+ if (clientId) authProvider.clientId = clientId;
517
+ return authProvider;
518
+ }
519
+ /**
520
+ * Restore MCP server connections from storage
521
+ * This method is called on Agent initialization to restore previously connected servers
522
+ *
523
+ * @param clientName Name to use for OAuth client (typically the agent instance name)
524
+ */
525
+ async restoreConnectionsFromStorage(clientName) {
526
+ if (this._isRestored) return;
527
+ const servers = this.getServersFromStorage();
528
+ if (!servers || servers.length === 0) {
529
+ this._isRestored = true;
530
+ return;
531
+ }
532
+ for (const server of servers) {
533
+ const existingConn = this.mcpConnections[server.id];
534
+ if (existingConn) {
535
+ if (existingConn.connectionState === MCPConnectionState.READY) {
536
+ console.warn(`[MCPClientManager] Server ${server.id} already has a ready connection. Skipping recreation.`);
537
+ continue;
538
+ }
539
+ if (existingConn.connectionState === MCPConnectionState.AUTHENTICATING || existingConn.connectionState === MCPConnectionState.CONNECTING || existingConn.connectionState === MCPConnectionState.DISCOVERING) continue;
540
+ if (existingConn.connectionState === MCPConnectionState.FAILED) {
541
+ try {
542
+ await existingConn.client.close();
543
+ } catch (error) {
544
+ console.warn(`[MCPClientManager] Error closing failed connection ${server.id}:`, error);
545
+ }
546
+ delete this.mcpConnections[server.id];
547
+ this._connectionDisposables.get(server.id)?.dispose();
548
+ this._connectionDisposables.delete(server.id);
549
+ }
550
+ }
551
+ const parsedOptions = server.server_options ? JSON.parse(server.server_options) : null;
552
+ const authProvider = this.createAuthProvider(server.id, server.callback_url, clientName, server.client_id ?? void 0);
553
+ const conn = this.createConnection(server.id, server.server_url, {
554
+ client: parsedOptions?.client ?? {},
555
+ transport: {
556
+ ...parsedOptions?.transport ?? {},
557
+ type: parsedOptions?.transport?.type ?? "auto",
558
+ authProvider
559
+ }
560
+ });
561
+ if (server.auth_url) {
562
+ conn.connectionState = MCPConnectionState.AUTHENTICATING;
563
+ continue;
564
+ }
565
+ this._restoreServer(server.id);
566
+ }
567
+ this._isRestored = true;
568
+ }
569
+ /**
570
+ * Internal method to restore a single server connection and discovery
571
+ */
572
+ async _restoreServer(serverId) {
573
+ if ((await this.connectToServer(serverId).catch((error) => {
574
+ console.error(`Error connecting to ${serverId}:`, error);
575
+ return null;
576
+ }))?.state === MCPConnectionState.CONNECTED) {
577
+ const discoverResult = await this.discoverIfConnected(serverId);
578
+ if (discoverResult && !discoverResult.success) console.error(`Error discovering ${serverId}:`, discoverResult.error);
579
+ }
580
+ }
581
+ /**
582
+ * Connect to and register an MCP server
583
+ *
584
+ * @deprecated This method is maintained for backward compatibility.
585
+ * For new code, use registerServer() and connectToServer() separately.
586
+ *
587
+ * @param url Server URL
588
+ * @param options Connection options
589
+ * @returns Object with server ID, auth URL (if OAuth), and client ID (if OAuth)
590
+ */
591
+ async connect(url, options = {}) {
592
+ /**
593
+ * We need to delay loading ai sdk, because putting it in module scope is
594
+ * causing issues with startup time.
595
+ * The only place it's used is in getAITools, which only matters after
596
+ * .connect() is called on at least one server.
597
+ * So it's safe to delay loading it until .connect() is called.
598
+ */
599
+ await this.ensureJsonSchema();
600
+ const id = options.reconnect?.id ?? nanoid(8);
601
+ if (options.transport?.authProvider) {
602
+ options.transport.authProvider.serverId = id;
603
+ if (options.reconnect?.oauthClientId) options.transport.authProvider.clientId = options.reconnect?.oauthClientId;
604
+ }
605
+ if (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {
606
+ const normalizedTransport = {
607
+ ...options.transport,
608
+ type: options.transport?.type ?? "auto"
609
+ };
610
+ this.mcpConnections[id] = new MCPClientConnection(new URL(url), {
611
+ name: this._name,
612
+ version: this._version
613
+ }, {
614
+ client: options.client ?? {},
615
+ transport: normalizedTransport
616
+ });
617
+ const store = new DisposableStore();
618
+ const existing = this._connectionDisposables.get(id);
619
+ if (existing) existing.dispose();
620
+ this._connectionDisposables.set(id, store);
621
+ store.add(this.mcpConnections[id].onObservabilityEvent((event) => {
622
+ this._onObservabilityEvent.fire(event);
623
+ }));
624
+ }
625
+ await this.mcpConnections[id].init();
626
+ if (options.reconnect?.oauthCode) try {
627
+ await this.mcpConnections[id].completeAuthorization(options.reconnect.oauthCode);
628
+ await this.mcpConnections[id].init();
629
+ } catch (error) {
630
+ this._onObservabilityEvent.fire({
631
+ type: "mcp:client:connect",
632
+ displayMessage: `Failed to complete OAuth reconnection for ${id} for ${url}`,
633
+ payload: {
634
+ url,
635
+ transport: options.transport?.type ?? "auto",
636
+ state: this.mcpConnections[id].connectionState,
637
+ error: toErrorMessage(error)
638
+ },
639
+ timestamp: Date.now(),
640
+ id
641
+ });
642
+ throw error;
643
+ }
644
+ const authUrl = options.transport?.authProvider?.authUrl;
645
+ if (this.mcpConnections[id].connectionState === MCPConnectionState.AUTHENTICATING && authUrl && options.transport?.authProvider?.redirectUrl) return {
646
+ authUrl,
647
+ clientId: options.transport?.authProvider?.clientId,
648
+ id
649
+ };
650
+ const discoverResult = await this.discoverIfConnected(id);
651
+ if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover server capabilities: ${discoverResult.error}`);
652
+ return { id };
653
+ }
654
+ /**
655
+ * Create an in-memory connection object and set up observability
656
+ * Does NOT save to storage - use registerServer() for that
657
+ * @returns The connection object (existing or newly created)
658
+ */
659
+ createConnection(id, url, options) {
660
+ if (this.mcpConnections[id]) return this.mcpConnections[id];
661
+ const normalizedTransport = {
662
+ ...options.transport,
663
+ type: options.transport?.type ?? "auto"
664
+ };
665
+ this.mcpConnections[id] = new MCPClientConnection(new URL(url), {
666
+ name: this._name,
667
+ version: this._version
668
+ }, {
669
+ client: {
670
+ ...defaultClientOptions,
671
+ ...options.client
672
+ },
673
+ transport: normalizedTransport
674
+ });
675
+ const store = new DisposableStore();
676
+ const existing = this._connectionDisposables.get(id);
677
+ if (existing) existing.dispose();
678
+ this._connectionDisposables.set(id, store);
679
+ store.add(this.mcpConnections[id].onObservabilityEvent((event) => {
680
+ this._onObservabilityEvent.fire(event);
681
+ }));
682
+ return this.mcpConnections[id];
683
+ }
684
+ /**
685
+ * Register an MCP server connection without connecting
686
+ * Creates the connection object, sets up observability, and saves to storage
687
+ *
688
+ * @param id Server ID
689
+ * @param options Registration options including URL, name, callback URL, and connection config
690
+ * @returns Server ID
691
+ */
692
+ async registerServer(id, options) {
693
+ this.createConnection(id, options.url, {
694
+ client: options.client,
695
+ transport: {
696
+ ...options.transport,
697
+ type: options.transport?.type ?? "auto"
698
+ }
699
+ });
700
+ const { authProvider: _, ...transportWithoutAuth } = options.transport ?? {};
701
+ this.saveServerToStorage({
702
+ id,
703
+ name: options.name,
704
+ server_url: options.url,
705
+ callback_url: options.callbackUrl,
706
+ client_id: options.clientId ?? null,
707
+ auth_url: options.authUrl ?? null,
708
+ server_options: JSON.stringify({
709
+ client: options.client,
710
+ transport: transportWithoutAuth
711
+ })
712
+ });
713
+ this._onServerStateChanged.fire();
714
+ return id;
715
+ }
716
+ /**
717
+ * Connect to an already registered MCP server and initialize the connection.
718
+ *
719
+ * For OAuth servers, returns `{ state: "authenticating", authUrl, clientId? }`.
720
+ * The user must complete the OAuth flow via the authUrl, which triggers a
721
+ * callback handled by `handleCallbackRequest()`.
722
+ *
723
+ * For non-OAuth servers, establishes the transport connection and returns
724
+ * `{ state: "connected" }`. Call `discoverIfConnected()` afterwards to
725
+ * discover capabilities and transition to "ready" state.
726
+ *
727
+ * @param id Server ID (must be registered first via registerServer())
728
+ * @returns Connection result with current state and OAuth info (if applicable)
729
+ */
730
+ async connectToServer(id) {
731
+ const conn = this.mcpConnections[id];
732
+ if (!conn) throw new Error(`Server ${id} is not registered. Call registerServer() first.`);
733
+ const error = await conn.init();
734
+ this._onServerStateChanged.fire();
735
+ switch (conn.connectionState) {
736
+ case MCPConnectionState.FAILED: return {
737
+ state: conn.connectionState,
738
+ error: error ?? "Unknown connection error"
739
+ };
740
+ case MCPConnectionState.AUTHENTICATING: {
741
+ const authUrl = conn.options.transport.authProvider?.authUrl;
742
+ const redirectUrl = conn.options.transport.authProvider?.redirectUrl;
743
+ if (!authUrl || !redirectUrl) return {
744
+ state: MCPConnectionState.FAILED,
745
+ error: `OAuth configuration incomplete: missing ${!authUrl ? "authUrl" : "redirectUrl"}`
746
+ };
747
+ const clientId = conn.options.transport.authProvider?.clientId;
748
+ const serverRow = this.getServersFromStorage().find((s) => s.id === id);
749
+ if (serverRow) {
750
+ this.saveServerToStorage({
751
+ ...serverRow,
752
+ auth_url: authUrl,
753
+ client_id: clientId ?? null
754
+ });
755
+ this._onServerStateChanged.fire();
756
+ }
757
+ return {
758
+ state: conn.connectionState,
759
+ authUrl,
760
+ clientId
761
+ };
762
+ }
763
+ case MCPConnectionState.CONNECTED: return { state: conn.connectionState };
764
+ default: return {
765
+ state: MCPConnectionState.FAILED,
766
+ error: `Unexpected connection state after init: ${conn.connectionState}`
767
+ };
768
+ }
769
+ }
770
+ extractServerIdFromState(state) {
771
+ if (!state) return null;
772
+ const parts = state.split(".");
773
+ return parts.length === 2 ? parts[1] : null;
774
+ }
775
+ isCallbackRequest(req) {
776
+ if (req.method !== "GET") return false;
777
+ if (!req.url.includes("/callback")) return false;
778
+ const state = new URL(req.url).searchParams.get("state");
779
+ const serverId = this.extractServerIdFromState(state);
780
+ if (!serverId) return false;
781
+ return this.getServersFromStorage().some((server) => server.id === serverId);
782
+ }
783
+ async handleCallbackRequest(req) {
784
+ const url = new URL(req.url);
785
+ const code = url.searchParams.get("code");
786
+ const state = url.searchParams.get("state");
787
+ const error = url.searchParams.get("error");
788
+ const errorDescription = url.searchParams.get("error_description");
789
+ if (!state) throw new Error("Unauthorized: no state provided");
790
+ const serverId = this.extractServerIdFromState(state);
791
+ if (!serverId) throw new Error("No serverId found in state parameter. Expected format: {nonce}.{serverId}");
792
+ if (!this.getServersFromStorage().some((server) => server.id === serverId)) throw new Error(`No server found with id "${serverId}". Was the request matched with \`isCallbackRequest()\`?`);
793
+ if (this.mcpConnections[serverId] === void 0) throw new Error(`Could not find serverId: ${serverId}`);
794
+ const conn = this.mcpConnections[serverId];
795
+ if (!conn.options.transport.authProvider) throw new Error("Trying to finalize authentication for a server connection without an authProvider");
796
+ const authProvider = conn.options.transport.authProvider;
797
+ authProvider.serverId = serverId;
798
+ const stateValidation = await authProvider.checkState(state);
799
+ if (!stateValidation.valid) throw new Error(`Invalid state: ${stateValidation.error}`);
800
+ if (error) return {
801
+ serverId,
802
+ authSuccess: false,
803
+ authError: errorDescription || error
804
+ };
805
+ if (!code) throw new Error("Unauthorized: no code provided");
806
+ if (this.mcpConnections[serverId].connectionState === MCPConnectionState.READY || this.mcpConnections[serverId].connectionState === MCPConnectionState.CONNECTED) {
807
+ this.clearServerAuthUrl(serverId);
808
+ return {
809
+ serverId,
810
+ authSuccess: true
811
+ };
812
+ }
813
+ if (this.mcpConnections[serverId].connectionState !== MCPConnectionState.AUTHENTICATING) throw new Error(`Failed to authenticate: the client is in "${this.mcpConnections[serverId].connectionState}" state, expected "authenticating"`);
814
+ try {
815
+ await authProvider.consumeState(state);
816
+ await conn.completeAuthorization(code);
817
+ await authProvider.deleteCodeVerifier();
818
+ this.clearServerAuthUrl(serverId);
819
+ this._onServerStateChanged.fire();
820
+ return {
821
+ serverId,
822
+ authSuccess: true
823
+ };
824
+ } catch (authError) {
825
+ const errorMessage = authError instanceof Error ? authError.message : String(authError);
826
+ this._onServerStateChanged.fire();
827
+ return {
828
+ serverId,
829
+ authSuccess: false,
830
+ authError: errorMessage
831
+ };
832
+ }
833
+ }
834
+ /**
835
+ * Discover server capabilities if connection is in CONNECTED or READY state.
836
+ * Transitions to DISCOVERING then READY (or CONNECTED on error).
837
+ * Can be called to refresh server capabilities (e.g., from a UI refresh button).
838
+ *
839
+ * If called while a previous discovery is in-flight for the same server,
840
+ * the previous discovery will be aborted.
841
+ *
842
+ * @param serverId The server ID to discover
843
+ * @param options Optional configuration
844
+ * @param options.timeoutMs Timeout in milliseconds (default: 30000)
845
+ * @returns Result with current state and optional error, or undefined if connection not found
846
+ */
847
+ async discoverIfConnected(serverId, options = {}) {
848
+ const conn = this.mcpConnections[serverId];
849
+ if (!conn) {
850
+ this._onObservabilityEvent.fire({
851
+ type: "mcp:client:discover",
852
+ displayMessage: `Connection not found for ${serverId}`,
853
+ payload: {},
854
+ timestamp: Date.now(),
855
+ id: nanoid()
856
+ });
857
+ return;
858
+ }
859
+ const result = await conn.discover(options);
860
+ this._onServerStateChanged.fire();
861
+ return {
862
+ ...result,
863
+ state: conn.connectionState
864
+ };
865
+ }
866
+ /**
867
+ * Establish connection in the background after OAuth completion
868
+ * This method connects to the server and discovers its capabilities
869
+ * @param serverId The server ID to establish connection for
870
+ */
871
+ async establishConnection(serverId) {
872
+ const conn = this.mcpConnections[serverId];
873
+ if (!conn) {
874
+ this._onObservabilityEvent.fire({
875
+ type: "mcp:client:preconnect",
876
+ displayMessage: `Connection not found for serverId: ${serverId}`,
877
+ payload: { serverId },
878
+ timestamp: Date.now(),
879
+ id: nanoid()
880
+ });
881
+ return;
882
+ }
883
+ if (conn.connectionState === MCPConnectionState.DISCOVERING || conn.connectionState === MCPConnectionState.READY) {
884
+ this._onObservabilityEvent.fire({
885
+ type: "mcp:client:connect",
886
+ displayMessage: `establishConnection skipped for ${serverId}, already in ${conn.connectionState} state`,
887
+ payload: {
888
+ url: conn.url.toString(),
889
+ transport: conn.options.transport.type || "unknown",
890
+ state: conn.connectionState
891
+ },
892
+ timestamp: Date.now(),
893
+ id: nanoid()
894
+ });
895
+ return;
896
+ }
897
+ const connectResult = await this.connectToServer(serverId);
898
+ this._onServerStateChanged.fire();
899
+ if (connectResult.state === MCPConnectionState.CONNECTED) await this.discoverIfConnected(serverId);
900
+ this._onObservabilityEvent.fire({
901
+ type: "mcp:client:connect",
902
+ displayMessage: `establishConnection completed for ${serverId}, final state: ${conn.connectionState}`,
903
+ payload: {
904
+ url: conn.url.toString(),
905
+ transport: conn.options.transport.type || "unknown",
906
+ state: conn.connectionState
907
+ },
908
+ timestamp: Date.now(),
909
+ id: nanoid()
910
+ });
911
+ }
912
+ /**
913
+ * Configure OAuth callback handling
914
+ * @param config OAuth callback configuration
915
+ */
916
+ configureOAuthCallback(config) {
917
+ this._oauthCallbackConfig = config;
918
+ }
919
+ /**
920
+ * Get the current OAuth callback configuration
921
+ * @returns The current OAuth callback configuration
922
+ */
923
+ getOAuthCallbackConfig() {
924
+ return this._oauthCallbackConfig;
925
+ }
926
+ /**
927
+ * @returns namespaced list of tools
928
+ */
929
+ listTools() {
930
+ return getNamespacedData(this.mcpConnections, "tools");
931
+ }
932
+ /**
933
+ * Lazy-loads the jsonSchema function from the AI SDK.
934
+ *
935
+ * This defers importing the "ai" package until it's actually needed, which helps reduce
936
+ * initial bundle size and startup time. The jsonSchema function is required for converting
937
+ * MCP tools into AI SDK tool definitions via getAITools().
938
+ *
939
+ * @internal This method is for internal use only. It's automatically called before operations
940
+ * that need jsonSchema (like getAITools() or OAuth flows). External consumers should not need
941
+ * to call this directly.
942
+ */
943
+ async ensureJsonSchema() {
944
+ if (!this.jsonSchema) {
945
+ const { jsonSchema } = await import("ai");
946
+ this.jsonSchema = jsonSchema;
947
+ }
948
+ }
949
+ /**
950
+ * @returns a set of tools that you can use with the AI SDK
951
+ */
952
+ getAITools() {
953
+ if (!this.jsonSchema) throw new Error("jsonSchema not initialized.");
954
+ 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.`);
955
+ return Object.fromEntries(getNamespacedData(this.mcpConnections, "tools").map((tool) => {
956
+ return [`tool_${tool.serverId.replace(/-/g, "")}_${tool.name}`, {
957
+ description: tool.description,
958
+ execute: async (args) => {
959
+ const result = await this.callTool({
960
+ arguments: args,
961
+ name: tool.name,
962
+ serverId: tool.serverId
963
+ });
964
+ if (result.isError) throw new Error(result.content[0].text);
965
+ return result;
966
+ },
967
+ inputSchema: this.jsonSchema(tool.inputSchema),
968
+ outputSchema: tool.outputSchema ? this.jsonSchema(tool.outputSchema) : void 0
969
+ }];
970
+ }));
971
+ }
972
+ /**
973
+ * @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version
974
+ * @returns a set of tools that you can use with the AI SDK
975
+ */
976
+ unstable_getAITools() {
977
+ if (!this._didWarnAboutUnstableGetAITools) {
978
+ this._didWarnAboutUnstableGetAITools = true;
979
+ console.warn("unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version.");
980
+ }
981
+ return this.getAITools();
982
+ }
983
+ /**
984
+ * Closes all active in-memory connections to MCP servers.
985
+ *
986
+ * Note: This only closes the transport connections - it does NOT remove
987
+ * servers from storage. Servers will still be listed and their callback
988
+ * URLs will still match incoming OAuth requests.
989
+ *
990
+ * Use removeServer() instead if you want to fully clean up a server
991
+ * (closes connection AND removes from storage).
992
+ */
993
+ async closeAllConnections() {
994
+ const ids = Object.keys(this.mcpConnections);
995
+ for (const id of ids) this.mcpConnections[id].cancelDiscovery();
996
+ await Promise.all(ids.map(async (id) => {
997
+ await this.mcpConnections[id].client.close();
998
+ }));
999
+ for (const id of ids) {
1000
+ const store = this._connectionDisposables.get(id);
1001
+ if (store) store.dispose();
1002
+ this._connectionDisposables.delete(id);
1003
+ delete this.mcpConnections[id];
1004
+ }
1005
+ }
1006
+ /**
1007
+ * Closes a connection to an MCP server
1008
+ * @param id The id of the connection to close
1009
+ */
1010
+ async closeConnection(id) {
1011
+ if (!this.mcpConnections[id]) throw new Error(`Connection with id "${id}" does not exist.`);
1012
+ this.mcpConnections[id].cancelDiscovery();
1013
+ await this.mcpConnections[id].client.close();
1014
+ delete this.mcpConnections[id];
1015
+ const store = this._connectionDisposables.get(id);
1016
+ if (store) store.dispose();
1017
+ this._connectionDisposables.delete(id);
1018
+ }
1019
+ /**
1020
+ * Remove an MCP server - closes connection if active and removes from storage.
1021
+ */
1022
+ async removeServer(serverId) {
1023
+ if (this.mcpConnections[serverId]) try {
1024
+ await this.closeConnection(serverId);
1025
+ } catch (_e) {}
1026
+ this.removeServerFromStorage(serverId);
1027
+ this._onServerStateChanged.fire();
1028
+ }
1029
+ /**
1030
+ * List all MCP servers from storage
1031
+ */
1032
+ listServers() {
1033
+ return this.getServersFromStorage();
1034
+ }
1035
+ /**
1036
+ * Dispose the manager and all resources.
1037
+ */
1038
+ async dispose() {
1039
+ try {
1040
+ await this.closeAllConnections();
1041
+ } finally {
1042
+ this._onServerStateChanged.dispose();
1043
+ this._onObservabilityEvent.dispose();
1044
+ }
1045
+ }
1046
+ /**
1047
+ * @returns namespaced list of prompts
1048
+ */
1049
+ listPrompts() {
1050
+ return getNamespacedData(this.mcpConnections, "prompts");
1051
+ }
1052
+ /**
1053
+ * @returns namespaced list of tools
1054
+ */
1055
+ listResources() {
1056
+ return getNamespacedData(this.mcpConnections, "resources");
1057
+ }
1058
+ /**
1059
+ * @returns namespaced list of resource templates
1060
+ */
1061
+ listResourceTemplates() {
1062
+ return getNamespacedData(this.mcpConnections, "resourceTemplates");
1063
+ }
1064
+ /**
1065
+ * Namespaced version of callTool
1066
+ */
1067
+ async callTool(params, resultSchema, options) {
1068
+ const unqualifiedName = params.name.replace(`${params.serverId}.`, "");
1069
+ return this.mcpConnections[params.serverId].client.callTool({
1070
+ ...params,
1071
+ name: unqualifiedName
1072
+ }, resultSchema, options);
1073
+ }
1074
+ /**
1075
+ * Namespaced version of readResource
1076
+ */
1077
+ readResource(params, options) {
1078
+ return this.mcpConnections[params.serverId].client.readResource(params, options);
1079
+ }
1080
+ /**
1081
+ * Namespaced version of getPrompt
1082
+ */
1083
+ getPrompt(params, options) {
1084
+ return this.mcpConnections[params.serverId].client.getPrompt(params, options);
1085
+ }
1086
+ };
1087
+ function getNamespacedData(mcpClients, type) {
1088
+ return Object.entries(mcpClients).map(([name, conn]) => {
1089
+ return {
1090
+ data: conn[type],
1091
+ name
1092
+ };
1093
+ }).flatMap(({ name: serverId, data }) => {
1094
+ return data.map((item) => {
1095
+ return {
1096
+ ...item,
1097
+ serverId
1098
+ };
1099
+ });
1100
+ });
1101
+ }
1102
+
1103
+ //#endregion
1104
+ export { DisposableStore as i, getNamespacedData as n, MCPConnectionState as r, MCPClientManager as t };
1105
+ //# sourceMappingURL=client-QZa2Rq0l.js.map