agents 0.0.0-d6a4eda → 0.0.0-d6d6d60

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 (77) hide show
  1. package/README.md +255 -27
  2. package/dist/ai-chat-agent.d.ts +20 -17
  3. package/dist/ai-chat-agent.js +532 -222
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-DBHGW4Hv.js +155 -0
  6. package/dist/ai-chat-v5-migration-DBHGW4Hv.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 +73 -84
  10. package/dist/ai-react.js +266 -199
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-B3aQaFv3.js +20 -0
  13. package/dist/ai-types-B3aQaFv3.js.map +1 -0
  14. package/dist/ai-types-D5YoPrBZ.d.ts +95 -0
  15. package/dist/ai-types.d.ts +6 -74
  16. package/dist/ai-types.js +3 -1
  17. package/dist/cli.d.ts +8 -0
  18. package/dist/cli.js +27 -0
  19. package/dist/cli.js.map +1 -0
  20. package/dist/client-BfiZ3HQd.js +117 -0
  21. package/dist/client-BfiZ3HQd.js.map +1 -0
  22. package/dist/client-Bws9q38u.d.ts +5427 -0
  23. package/dist/client-CbWe9FBd.d.ts +104 -0
  24. package/dist/client-DvK0u9vD.js +898 -0
  25. package/dist/client-DvK0u9vD.js.map +1 -0
  26. package/dist/client.d.ts +12 -87
  27. package/dist/client.js +4 -11
  28. package/dist/codemode/ai.d.ts +27 -0
  29. package/dist/codemode/ai.js +151 -0
  30. package/dist/codemode/ai.js.map +1 -0
  31. package/dist/do-oauth-client-provider-CcTno-25.d.ts +142 -0
  32. package/dist/do-oauth-client-provider-D2P1lSft.js +93 -0
  33. package/dist/do-oauth-client-provider-D2P1lSft.js.map +1 -0
  34. package/dist/index-Bdzb2feZ.d.ts +572 -0
  35. package/dist/index-DhJCaDWd.d.ts +58 -0
  36. package/dist/index.d.ts +62 -392
  37. package/dist/index.js +7 -22
  38. package/dist/mcp/client.d.ts +4 -783
  39. package/dist/mcp/client.js +4 -9
  40. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  41. package/dist/mcp/do-oauth-client-provider.js +3 -7
  42. package/dist/mcp/index.d.ts +190 -81
  43. package/dist/mcp/index.js +1428 -767
  44. package/dist/mcp/index.js.map +1 -1
  45. package/dist/mcp/x402.d.ts +34 -0
  46. package/dist/mcp/x402.js +194 -0
  47. package/dist/mcp/x402.js.map +1 -0
  48. package/dist/mcp-Dw5vDrY8.d.ts +61 -0
  49. package/dist/observability/index.d.ts +3 -0
  50. package/dist/observability/index.js +7 -0
  51. package/dist/react-DFNXTQzy.d.ts +113 -0
  52. package/dist/react.d.ts +10 -53
  53. package/dist/react.js +183 -100
  54. package/dist/react.js.map +1 -1
  55. package/dist/schedule.d.ts +89 -12
  56. package/dist/schedule.js +46 -21
  57. package/dist/schedule.js.map +1 -1
  58. package/dist/serializable-CymX8ovI.d.ts +39 -0
  59. package/dist/serializable.d.ts +7 -0
  60. package/dist/serializable.js +1 -0
  61. package/dist/src-C1WWpbRo.js +1247 -0
  62. package/dist/src-C1WWpbRo.js.map +1 -0
  63. package/package.json +125 -71
  64. package/dist/ai-types.js.map +0 -1
  65. package/dist/chunk-BZXOAZUX.js +0 -106
  66. package/dist/chunk-BZXOAZUX.js.map +0 -1
  67. package/dist/chunk-QSGN3REV.js +0 -123
  68. package/dist/chunk-QSGN3REV.js.map +0 -1
  69. package/dist/chunk-RIYR6FR6.js +0 -777
  70. package/dist/chunk-RIYR6FR6.js.map +0 -1
  71. package/dist/chunk-Y67CHZBI.js +0 -464
  72. package/dist/chunk-Y67CHZBI.js.map +0 -1
  73. package/dist/client.js.map +0 -1
  74. package/dist/index.js.map +0 -1
  75. package/dist/mcp/client.js.map +0 -1
  76. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  77. package/src/index.ts +0 -1243
@@ -0,0 +1,898 @@
1
+ import { t as DurableObjectOAuthClientProvider } from "./do-oauth-client-provider-D2P1lSft.js";
2
+ import { nanoid } from "nanoid";
3
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
5
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
6
+ import { ElicitRequestSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
7
+
8
+ //#region src/core/events.ts
9
+ function toDisposable(fn) {
10
+ return { dispose: fn };
11
+ }
12
+ var DisposableStore = class {
13
+ constructor() {
14
+ this._items = [];
15
+ }
16
+ add(d) {
17
+ this._items.push(d);
18
+ return d;
19
+ }
20
+ dispose() {
21
+ while (this._items.length) try {
22
+ this._items.pop().dispose();
23
+ } catch {}
24
+ }
25
+ };
26
+ var Emitter = class {
27
+ constructor() {
28
+ this._listeners = /* @__PURE__ */ new Set();
29
+ this.event = (listener) => {
30
+ this._listeners.add(listener);
31
+ return toDisposable(() => this._listeners.delete(listener));
32
+ };
33
+ }
34
+ fire(data) {
35
+ for (const listener of [...this._listeners]) try {
36
+ listener(data);
37
+ } catch (err) {
38
+ console.error("Emitter listener error:", err);
39
+ }
40
+ }
41
+ dispose() {
42
+ this._listeners.clear();
43
+ }
44
+ };
45
+
46
+ //#endregion
47
+ //#region src/mcp/errors.ts
48
+ function toErrorMessage(error) {
49
+ return error instanceof Error ? error.message : String(error);
50
+ }
51
+ function isUnauthorized(error) {
52
+ const msg = toErrorMessage(error);
53
+ return msg.includes("Unauthorized") || msg.includes("401");
54
+ }
55
+ function isTransportNotImplemented(error) {
56
+ const msg = toErrorMessage(error);
57
+ return msg.includes("404") || msg.includes("405") || msg.includes("Not Implemented") || msg.includes("not implemented");
58
+ }
59
+
60
+ //#endregion
61
+ //#region src/mcp/client-connection.ts
62
+ var MCPClientConnection = class {
63
+ constructor(url, info, options = {
64
+ client: {},
65
+ transport: {}
66
+ }) {
67
+ this.url = url;
68
+ this.options = options;
69
+ this.connectionState = "connecting";
70
+ this.tools = [];
71
+ this.prompts = [];
72
+ this.resources = [];
73
+ this.resourceTemplates = [];
74
+ this._onObservabilityEvent = new Emitter();
75
+ this.onObservabilityEvent = this._onObservabilityEvent.event;
76
+ this.client = new Client(info, {
77
+ ...options.client,
78
+ capabilities: {
79
+ ...options.client?.capabilities,
80
+ elicitation: {}
81
+ }
82
+ });
83
+ }
84
+ /**
85
+ * Initialize a client connection
86
+ *
87
+ * @returns
88
+ */
89
+ async init() {
90
+ const transportType = this.options.transport.type;
91
+ if (!transportType) throw new Error("Transport type must be specified");
92
+ try {
93
+ await this.tryConnect(transportType);
94
+ } catch (e) {
95
+ if (isUnauthorized(e)) {
96
+ this.connectionState = "authenticating";
97
+ return;
98
+ }
99
+ this._onObservabilityEvent.fire({
100
+ type: "mcp:client:connect",
101
+ displayMessage: `Connection initialization failed for ${this.url.toString()}`,
102
+ payload: {
103
+ url: this.url.toString(),
104
+ transport: transportType,
105
+ state: this.connectionState,
106
+ error: toErrorMessage(e)
107
+ },
108
+ timestamp: Date.now(),
109
+ id: nanoid()
110
+ });
111
+ this.connectionState = "failed";
112
+ return;
113
+ }
114
+ await this.discoverAndRegister();
115
+ }
116
+ /**
117
+ * Finish OAuth by probing transports based on configured type.
118
+ * - Explicit: finish on that transport
119
+ * - Auto: try streamable-http, then sse on 404/405/Not Implemented
120
+ */
121
+ async finishAuthProbe(code) {
122
+ if (!this.options.transport.authProvider) throw new Error("No auth provider configured");
123
+ const configuredType = this.options.transport.type;
124
+ if (!configuredType) throw new Error("Transport type must be specified");
125
+ const finishAuth = async (base) => {
126
+ await this.getTransport(base).finishAuth(code);
127
+ };
128
+ if (configuredType === "sse" || configuredType === "streamable-http") {
129
+ await finishAuth(configuredType);
130
+ return;
131
+ }
132
+ try {
133
+ await finishAuth("streamable-http");
134
+ } catch (e) {
135
+ if (isTransportNotImplemented(e)) {
136
+ await finishAuth("sse");
137
+ return;
138
+ }
139
+ throw e;
140
+ }
141
+ }
142
+ /**
143
+ * Complete OAuth authorization
144
+ */
145
+ async completeAuthorization(code) {
146
+ if (this.connectionState !== "authenticating") throw new Error("Connection must be in authenticating state to complete authorization");
147
+ try {
148
+ await this.finishAuthProbe(code);
149
+ this.connectionState = "connecting";
150
+ } catch (error) {
151
+ this.connectionState = "failed";
152
+ throw error;
153
+ }
154
+ }
155
+ /**
156
+ * Establish connection after successful authorization
157
+ */
158
+ async establishConnection() {
159
+ if (this.connectionState !== "connecting") throw new Error("Connection must be in connecting state to establish connection");
160
+ try {
161
+ const transportType = this.options.transport.type;
162
+ if (!transportType) throw new Error("Transport type must be specified");
163
+ await this.tryConnect(transportType);
164
+ await this.discoverAndRegister();
165
+ } catch (error) {
166
+ this.connectionState = "failed";
167
+ throw error;
168
+ }
169
+ }
170
+ /**
171
+ * Discover server capabilities and register tools, resources, prompts, and templates
172
+ */
173
+ async discoverAndRegister() {
174
+ this.connectionState = "discovering";
175
+ this.serverCapabilities = this.client.getServerCapabilities();
176
+ if (!this.serverCapabilities) throw new Error("The MCP Server failed to return server capabilities");
177
+ const [instructionsResult, toolsResult, resourcesResult, promptsResult, resourceTemplatesResult] = await Promise.allSettled([
178
+ this.client.getInstructions(),
179
+ this.registerTools(),
180
+ this.registerResources(),
181
+ this.registerPrompts(),
182
+ this.registerResourceTemplates()
183
+ ]);
184
+ const operations = [
185
+ {
186
+ name: "instructions",
187
+ result: instructionsResult
188
+ },
189
+ {
190
+ name: "tools",
191
+ result: toolsResult
192
+ },
193
+ {
194
+ name: "resources",
195
+ result: resourcesResult
196
+ },
197
+ {
198
+ name: "prompts",
199
+ result: promptsResult
200
+ },
201
+ {
202
+ name: "resource templates",
203
+ result: resourceTemplatesResult
204
+ }
205
+ ];
206
+ for (const { name, result } of operations) if (result.status === "rejected") {
207
+ const url = this.url.toString();
208
+ this._onObservabilityEvent.fire({
209
+ type: "mcp:client:discover",
210
+ displayMessage: `Failed to discover ${name} for ${url}`,
211
+ payload: {
212
+ url,
213
+ capability: name,
214
+ error: result.reason
215
+ },
216
+ timestamp: Date.now(),
217
+ id: nanoid()
218
+ });
219
+ }
220
+ this.instructions = instructionsResult.status === "fulfilled" ? instructionsResult.value : void 0;
221
+ this.tools = toolsResult.status === "fulfilled" ? toolsResult.value : [];
222
+ this.resources = resourcesResult.status === "fulfilled" ? resourcesResult.value : [];
223
+ this.prompts = promptsResult.status === "fulfilled" ? promptsResult.value : [];
224
+ this.resourceTemplates = resourceTemplatesResult.status === "fulfilled" ? resourceTemplatesResult.value : [];
225
+ this.connectionState = "ready";
226
+ }
227
+ /**
228
+ * Notification handler registration
229
+ */
230
+ async registerTools() {
231
+ if (!this.serverCapabilities || !this.serverCapabilities.tools) return [];
232
+ if (this.serverCapabilities.tools.listChanged) this.client.setNotificationHandler(ToolListChangedNotificationSchema, async (_notification) => {
233
+ this.tools = await this.fetchTools();
234
+ });
235
+ return this.fetchTools();
236
+ }
237
+ async registerResources() {
238
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) return [];
239
+ if (this.serverCapabilities.resources.listChanged) this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_notification) => {
240
+ this.resources = await this.fetchResources();
241
+ });
242
+ return this.fetchResources();
243
+ }
244
+ async registerPrompts() {
245
+ if (!this.serverCapabilities || !this.serverCapabilities.prompts) return [];
246
+ if (this.serverCapabilities.prompts.listChanged) this.client.setNotificationHandler(PromptListChangedNotificationSchema, async (_notification) => {
247
+ this.prompts = await this.fetchPrompts();
248
+ });
249
+ return this.fetchPrompts();
250
+ }
251
+ async registerResourceTemplates() {
252
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) return [];
253
+ return this.fetchResourceTemplates();
254
+ }
255
+ async fetchTools() {
256
+ let toolsAgg = [];
257
+ let toolsResult = { tools: [] };
258
+ do {
259
+ toolsResult = await this.client.listTools({ cursor: toolsResult.nextCursor }).catch(this._capabilityErrorHandler({ tools: [] }, "tools/list"));
260
+ toolsAgg = toolsAgg.concat(toolsResult.tools);
261
+ } while (toolsResult.nextCursor);
262
+ return toolsAgg;
263
+ }
264
+ async fetchResources() {
265
+ let resourcesAgg = [];
266
+ let resourcesResult = { resources: [] };
267
+ do {
268
+ resourcesResult = await this.client.listResources({ cursor: resourcesResult.nextCursor }).catch(this._capabilityErrorHandler({ resources: [] }, "resources/list"));
269
+ resourcesAgg = resourcesAgg.concat(resourcesResult.resources);
270
+ } while (resourcesResult.nextCursor);
271
+ return resourcesAgg;
272
+ }
273
+ async fetchPrompts() {
274
+ let promptsAgg = [];
275
+ let promptsResult = { prompts: [] };
276
+ do {
277
+ promptsResult = await this.client.listPrompts({ cursor: promptsResult.nextCursor }).catch(this._capabilityErrorHandler({ prompts: [] }, "prompts/list"));
278
+ promptsAgg = promptsAgg.concat(promptsResult.prompts);
279
+ } while (promptsResult.nextCursor);
280
+ return promptsAgg;
281
+ }
282
+ async fetchResourceTemplates() {
283
+ let templatesAgg = [];
284
+ let templatesResult = { resourceTemplates: [] };
285
+ do {
286
+ templatesResult = await this.client.listResourceTemplates({ cursor: templatesResult.nextCursor }).catch(this._capabilityErrorHandler({ resourceTemplates: [] }, "resources/templates/list"));
287
+ templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);
288
+ } while (templatesResult.nextCursor);
289
+ return templatesAgg;
290
+ }
291
+ /**
292
+ * Handle elicitation request from server
293
+ * Automatically uses the Agent's built-in elicitation handling if available
294
+ */
295
+ async handleElicitationRequest(_request) {
296
+ throw new Error("Elicitation handler must be implemented for your platform. Override handleElicitationRequest method.");
297
+ }
298
+ /**
299
+ * Get the transport for the client
300
+ * @param transportType - The transport type to get
301
+ * @returns The transport for the client
302
+ */
303
+ getTransport(transportType) {
304
+ switch (transportType) {
305
+ case "streamable-http": return new StreamableHTTPClientTransport(this.url, this.options.transport);
306
+ case "sse": return new SSEClientTransport(this.url, this.options.transport);
307
+ default: throw new Error(`Unsupported transport type: ${transportType}`);
308
+ }
309
+ }
310
+ async tryConnect(transportType) {
311
+ const transports = transportType === "auto" ? ["streamable-http", "sse"] : [transportType];
312
+ for (const currentTransportType of transports) {
313
+ const isLastTransport = currentTransportType === transports[transports.length - 1];
314
+ const hasFallback = transportType === "auto" && currentTransportType === "streamable-http" && !isLastTransport;
315
+ const transport = this.getTransport(currentTransportType);
316
+ try {
317
+ await this.client.connect(transport);
318
+ this.lastConnectedTransport = currentTransportType;
319
+ const url = this.url.toString();
320
+ this._onObservabilityEvent.fire({
321
+ type: "mcp:client:connect",
322
+ displayMessage: `Connected successfully using ${currentTransportType} transport for ${url}`,
323
+ payload: {
324
+ url,
325
+ transport: currentTransportType,
326
+ state: this.connectionState
327
+ },
328
+ timestamp: Date.now(),
329
+ id: nanoid()
330
+ });
331
+ break;
332
+ } catch (e) {
333
+ const error = e instanceof Error ? e : new Error(String(e));
334
+ if (isUnauthorized(error)) throw e;
335
+ if (hasFallback && isTransportNotImplemented(error)) {
336
+ const url = this.url.toString();
337
+ this._onObservabilityEvent.fire({
338
+ type: "mcp:client:connect",
339
+ displayMessage: `${currentTransportType} transport not available, trying ${transports[transports.indexOf(currentTransportType) + 1]} for ${url}`,
340
+ payload: {
341
+ url,
342
+ transport: currentTransportType,
343
+ state: this.connectionState
344
+ },
345
+ timestamp: Date.now(),
346
+ id: nanoid()
347
+ });
348
+ continue;
349
+ }
350
+ throw e;
351
+ }
352
+ }
353
+ this.client.setRequestHandler(ElicitRequestSchema, async (request) => {
354
+ return await this.handleElicitationRequest(request);
355
+ });
356
+ }
357
+ _capabilityErrorHandler(empty, method) {
358
+ return (e) => {
359
+ if (e.code === -32601) {
360
+ const url = this.url.toString();
361
+ this._onObservabilityEvent.fire({
362
+ type: "mcp:client:discover",
363
+ displayMessage: `The server advertised support for the capability ${method.split("/")[0]}, but returned "Method not found" for '${method}' for ${url}`,
364
+ payload: {
365
+ url,
366
+ capability: method.split("/")[0],
367
+ error: toErrorMessage(e)
368
+ },
369
+ timestamp: Date.now(),
370
+ id: nanoid()
371
+ });
372
+ return empty;
373
+ }
374
+ throw e;
375
+ };
376
+ }
377
+ };
378
+
379
+ //#endregion
380
+ //#region src/mcp/client.ts
381
+ /**
382
+ * Utility class that aggregates multiple MCP clients into one
383
+ */
384
+ var MCPClientManager = class {
385
+ /**
386
+ * @param _name Name of the MCP client
387
+ * @param _version Version of the MCP Client
388
+ * @param options Storage adapter for persisting MCP server state
389
+ */
390
+ constructor(_name, _version, options) {
391
+ this._name = _name;
392
+ this._version = _version;
393
+ this.mcpConnections = {};
394
+ this._didWarnAboutUnstableGetAITools = false;
395
+ this._connectionDisposables = /* @__PURE__ */ new Map();
396
+ this._isRestored = false;
397
+ this._onObservabilityEvent = new Emitter();
398
+ this.onObservabilityEvent = this._onObservabilityEvent.event;
399
+ this._onServerStateChanged = new Emitter();
400
+ this.onServerStateChanged = this._onServerStateChanged.event;
401
+ this._storage = options.storage;
402
+ }
403
+ /**
404
+ * Create an auth provider for a server
405
+ * @internal
406
+ */
407
+ createAuthProvider(serverId, callbackUrl, clientName, clientId) {
408
+ const authProvider = new DurableObjectOAuthClientProvider(this._storage, clientName, callbackUrl);
409
+ authProvider.serverId = serverId;
410
+ if (clientId) authProvider.clientId = clientId;
411
+ return authProvider;
412
+ }
413
+ /**
414
+ * Restore MCP server connections from storage
415
+ * This method is called on Agent initialization to restore previously connected servers
416
+ *
417
+ * @param clientName Name to use for OAuth client (typically the agent instance name)
418
+ */
419
+ async restoreConnectionsFromStorage(clientName) {
420
+ if (this._isRestored) return;
421
+ await this._storage.create();
422
+ const servers = await this._storage.listServers();
423
+ if (!servers || servers.length === 0) {
424
+ this._isRestored = true;
425
+ return;
426
+ }
427
+ for (const server of servers) {
428
+ const existingConn = this.mcpConnections[server.id];
429
+ if (existingConn) {
430
+ if (existingConn.connectionState === "ready") {
431
+ console.warn(`[MCPClientManager] Server ${server.id} already has a ready connection. Skipping recreation.`);
432
+ continue;
433
+ }
434
+ if (existingConn.connectionState === "authenticating" || existingConn.connectionState === "connecting" || existingConn.connectionState === "discovering") continue;
435
+ if (existingConn.connectionState === "failed") {
436
+ try {
437
+ await existingConn.client.close();
438
+ } catch (error) {
439
+ console.warn(`[MCPClientManager] Error closing failed connection ${server.id}:`, error);
440
+ }
441
+ delete this.mcpConnections[server.id];
442
+ this._connectionDisposables.get(server.id)?.dispose();
443
+ this._connectionDisposables.delete(server.id);
444
+ }
445
+ }
446
+ const parsedOptions = server.server_options ? JSON.parse(server.server_options) : null;
447
+ const authProvider = this.createAuthProvider(server.id, server.callback_url, clientName, server.client_id ?? void 0);
448
+ this.createConnection(server.id, server.server_url, {
449
+ client: parsedOptions?.client ?? {},
450
+ transport: {
451
+ ...parsedOptions?.transport ?? {},
452
+ type: parsedOptions?.transport?.type ?? "auto",
453
+ authProvider
454
+ }
455
+ });
456
+ await this.connectToServer(server.id).catch((error) => {
457
+ console.error(`Error restoring ${server.id}:`, error);
458
+ });
459
+ }
460
+ this._isRestored = true;
461
+ }
462
+ /**
463
+ * Connect to and register an MCP server
464
+ *
465
+ * @deprecated This method is maintained for backward compatibility.
466
+ * For new code, use registerServer() and connectToServer() separately.
467
+ *
468
+ * @param url Server URL
469
+ * @param options Connection options
470
+ * @returns Object with server ID, auth URL (if OAuth), and client ID (if OAuth)
471
+ */
472
+ async connect(url, options = {}) {
473
+ /**
474
+ * We need to delay loading ai sdk, because putting it in module scope is
475
+ * causing issues with startup time.
476
+ * The only place it's used is in getAITools, which only matters after
477
+ * .connect() is called on at least one server.
478
+ * So it's safe to delay loading it until .connect() is called.
479
+ */
480
+ await this.ensureJsonSchema();
481
+ const id = options.reconnect?.id ?? nanoid(8);
482
+ if (options.transport?.authProvider) {
483
+ options.transport.authProvider.serverId = id;
484
+ if (options.reconnect?.oauthClientId) options.transport.authProvider.clientId = options.reconnect?.oauthClientId;
485
+ }
486
+ if (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {
487
+ const normalizedTransport = {
488
+ ...options.transport,
489
+ type: options.transport?.type ?? "auto"
490
+ };
491
+ this.mcpConnections[id] = new MCPClientConnection(new URL(url), {
492
+ name: this._name,
493
+ version: this._version
494
+ }, {
495
+ client: options.client ?? {},
496
+ transport: normalizedTransport
497
+ });
498
+ const store = new DisposableStore();
499
+ const existing = this._connectionDisposables.get(id);
500
+ if (existing) existing.dispose();
501
+ this._connectionDisposables.set(id, store);
502
+ store.add(this.mcpConnections[id].onObservabilityEvent((event) => {
503
+ this._onObservabilityEvent.fire(event);
504
+ }));
505
+ }
506
+ await this.mcpConnections[id].init();
507
+ if (options.reconnect?.oauthCode) try {
508
+ await this.mcpConnections[id].completeAuthorization(options.reconnect.oauthCode);
509
+ await this.mcpConnections[id].establishConnection();
510
+ } catch (error) {
511
+ this._onObservabilityEvent.fire({
512
+ type: "mcp:client:connect",
513
+ displayMessage: `Failed to complete OAuth reconnection for ${id} for ${url}`,
514
+ payload: {
515
+ url,
516
+ transport: options.transport?.type ?? "auto",
517
+ state: this.mcpConnections[id].connectionState,
518
+ error: toErrorMessage(error)
519
+ },
520
+ timestamp: Date.now(),
521
+ id
522
+ });
523
+ throw error;
524
+ }
525
+ const authUrl = options.transport?.authProvider?.authUrl;
526
+ if (this.mcpConnections[id].connectionState === "authenticating" && authUrl && options.transport?.authProvider?.redirectUrl) return {
527
+ authUrl,
528
+ clientId: options.transport?.authProvider?.clientId,
529
+ id
530
+ };
531
+ return { id };
532
+ }
533
+ /**
534
+ * Create an in-memory connection object and set up observability
535
+ * Does NOT save to storage - use registerServer() for that
536
+ */
537
+ createConnection(id, url, options) {
538
+ if (this.mcpConnections[id]) return;
539
+ const normalizedTransport = {
540
+ ...options.transport,
541
+ type: options.transport?.type ?? "auto"
542
+ };
543
+ this.mcpConnections[id] = new MCPClientConnection(new URL(url), {
544
+ name: this._name,
545
+ version: this._version
546
+ }, {
547
+ client: options.client ?? {},
548
+ transport: normalizedTransport
549
+ });
550
+ const store = new DisposableStore();
551
+ const existing = this._connectionDisposables.get(id);
552
+ if (existing) existing.dispose();
553
+ this._connectionDisposables.set(id, store);
554
+ store.add(this.mcpConnections[id].onObservabilityEvent((event) => {
555
+ this._onObservabilityEvent.fire(event);
556
+ }));
557
+ }
558
+ /**
559
+ * Register an MCP server connection without connecting
560
+ * Creates the connection object, sets up observability, and saves to storage
561
+ *
562
+ * @param id Server ID
563
+ * @param options Registration options including URL, name, callback URL, and connection config
564
+ * @returns Server ID
565
+ */
566
+ async registerServer(id, options) {
567
+ this.createConnection(id, options.url, {
568
+ client: options.client,
569
+ transport: {
570
+ ...options.transport,
571
+ type: options.transport?.type ?? "auto"
572
+ }
573
+ });
574
+ await this._storage.saveServer({
575
+ id,
576
+ name: options.name,
577
+ server_url: options.url,
578
+ callback_url: options.callbackUrl,
579
+ client_id: options.clientId ?? null,
580
+ auth_url: options.authUrl ?? null,
581
+ server_options: JSON.stringify({
582
+ client: options.client,
583
+ transport: options.transport
584
+ })
585
+ });
586
+ this._onServerStateChanged.fire();
587
+ return id;
588
+ }
589
+ /**
590
+ * Connect to an already registered MCP server and initialize the connection.
591
+ *
592
+ * For OAuth servers, this returns `{ state: "authenticating", authUrl, clientId? }`
593
+ * without establishing the connection. The user must complete the OAuth flow via
594
+ * the authUrl, which will trigger a callback handled by `handleCallbackRequest()`.
595
+ *
596
+ * For non-OAuth servers, this establishes the connection immediately and returns
597
+ * `{ state: "ready" }`.
598
+ *
599
+ * Updates storage with auth URL and client ID after connection.
600
+ *
601
+ * @param id Server ID (must be registered first via registerServer())
602
+ * @returns Connection result with current state and OAuth info (if applicable)
603
+ */
604
+ async connectToServer(id) {
605
+ const conn = this.mcpConnections[id];
606
+ if (!conn) throw new Error(`Server ${id} is not registered. Call registerServer() first.`);
607
+ await conn.init();
608
+ const authUrl = conn.options.transport.authProvider?.authUrl;
609
+ if (conn.connectionState === "authenticating" && authUrl && conn.options.transport.authProvider?.redirectUrl) {
610
+ const clientId = conn.options.transport.authProvider?.clientId;
611
+ const serverRow = (await this._storage.listServers()).find((s) => s.id === id);
612
+ if (serverRow) await this._storage.saveServer({
613
+ ...serverRow,
614
+ auth_url: authUrl,
615
+ client_id: clientId ?? null
616
+ });
617
+ this._onServerStateChanged.fire();
618
+ return {
619
+ state: "authenticating",
620
+ authUrl,
621
+ clientId
622
+ };
623
+ }
624
+ if (conn.connectionState === "ready") this._onServerStateChanged.fire();
625
+ return { state: "ready" };
626
+ }
627
+ async isCallbackRequest(req) {
628
+ if (req.method !== "GET") return false;
629
+ if (!req.url.includes("/callback")) return false;
630
+ return (await this._storage.listServers()).some((server) => server.callback_url && req.url.startsWith(server.callback_url));
631
+ }
632
+ async handleCallbackRequest(req) {
633
+ const url = new URL(req.url);
634
+ const matchingServer = (await this._storage.listServers()).find((server) => {
635
+ return server.callback_url && req.url.startsWith(server.callback_url);
636
+ });
637
+ if (!matchingServer) throw new Error(`No callback URI match found for the request url: ${req.url}. Was the request matched with \`isCallbackRequest()\`?`);
638
+ const serverId = matchingServer.id;
639
+ const code = url.searchParams.get("code");
640
+ const state = url.searchParams.get("state");
641
+ const error = url.searchParams.get("error");
642
+ const errorDescription = url.searchParams.get("error_description");
643
+ if (error) return {
644
+ serverId,
645
+ authSuccess: false,
646
+ authError: errorDescription || error
647
+ };
648
+ if (!code) throw new Error("Unauthorized: no code provided");
649
+ if (!state) throw new Error("Unauthorized: no state provided");
650
+ if (this.mcpConnections[serverId] === void 0) throw new Error(`Could not find serverId: ${serverId}`);
651
+ if (this.mcpConnections[serverId].connectionState === "ready") return {
652
+ serverId,
653
+ authSuccess: true
654
+ };
655
+ if (this.mcpConnections[serverId].connectionState !== "authenticating") throw new Error(`Failed to authenticate: the client is in "${this.mcpConnections[serverId].connectionState}" state, expected "authenticating"`);
656
+ const conn = this.mcpConnections[serverId];
657
+ if (!conn.options.transport.authProvider) throw new Error("Trying to finalize authentication for a server connection without an authProvider");
658
+ const clientId = conn.options.transport.authProvider.clientId || state;
659
+ conn.options.transport.authProvider.clientId = clientId;
660
+ conn.options.transport.authProvider.serverId = serverId;
661
+ try {
662
+ await conn.completeAuthorization(code);
663
+ await this._storage.clearAuthUrl(serverId);
664
+ this._onServerStateChanged.fire();
665
+ return {
666
+ serverId,
667
+ authSuccess: true
668
+ };
669
+ } catch (error$1) {
670
+ const errorMessage = error$1 instanceof Error ? error$1.message : String(error$1);
671
+ this._onServerStateChanged.fire();
672
+ return {
673
+ serverId,
674
+ authSuccess: false,
675
+ authError: errorMessage
676
+ };
677
+ }
678
+ }
679
+ /**
680
+ * Establish connection in the background after OAuth completion
681
+ * This method is called asynchronously and doesn't block the OAuth callback response
682
+ * @param serverId The server ID to establish connection for
683
+ */
684
+ async establishConnection(serverId) {
685
+ const conn = this.mcpConnections[serverId];
686
+ if (!conn) {
687
+ this._onObservabilityEvent.fire({
688
+ type: "mcp:client:preconnect",
689
+ displayMessage: `Connection not found for serverId: ${serverId}`,
690
+ payload: { serverId },
691
+ timestamp: Date.now(),
692
+ id: nanoid()
693
+ });
694
+ return;
695
+ }
696
+ try {
697
+ await conn.establishConnection();
698
+ this._onServerStateChanged.fire();
699
+ } catch (error) {
700
+ const url = conn.url.toString();
701
+ this._onObservabilityEvent.fire({
702
+ type: "mcp:client:connect",
703
+ displayMessage: `Failed to establish connection to server ${serverId} with url ${url}`,
704
+ payload: {
705
+ url,
706
+ transport: conn.options.transport.type ?? "auto",
707
+ state: conn.connectionState,
708
+ error: toErrorMessage(error)
709
+ },
710
+ timestamp: Date.now(),
711
+ id: nanoid()
712
+ });
713
+ this._onServerStateChanged.fire();
714
+ }
715
+ }
716
+ /**
717
+ * Configure OAuth callback handling
718
+ * @param config OAuth callback configuration
719
+ */
720
+ configureOAuthCallback(config) {
721
+ this._oauthCallbackConfig = config;
722
+ }
723
+ /**
724
+ * Get the current OAuth callback configuration
725
+ * @returns The current OAuth callback configuration
726
+ */
727
+ getOAuthCallbackConfig() {
728
+ return this._oauthCallbackConfig;
729
+ }
730
+ /**
731
+ * @returns namespaced list of tools
732
+ */
733
+ listTools() {
734
+ return getNamespacedData(this.mcpConnections, "tools");
735
+ }
736
+ /**
737
+ * Lazy-loads the jsonSchema function from the AI SDK.
738
+ *
739
+ * This defers importing the "ai" package until it's actually needed, which helps reduce
740
+ * initial bundle size and startup time. The jsonSchema function is required for converting
741
+ * MCP tools into AI SDK tool definitions via getAITools().
742
+ *
743
+ * @internal This method is for internal use only. It's automatically called before operations
744
+ * that need jsonSchema (like getAITools() or OAuth flows). External consumers should not need
745
+ * to call this directly.
746
+ */
747
+ async ensureJsonSchema() {
748
+ if (!this.jsonSchema) {
749
+ const { jsonSchema } = await import("ai");
750
+ this.jsonSchema = jsonSchema;
751
+ }
752
+ }
753
+ /**
754
+ * @returns a set of tools that you can use with the AI SDK
755
+ */
756
+ getAITools() {
757
+ if (!this.jsonSchema) throw new Error("jsonSchema not initialized.");
758
+ for (const [id, conn] of Object.entries(this.mcpConnections)) if (conn.connectionState !== "ready" && conn.connectionState !== "authenticating") console.warn(`[getAITools] WARNING: Reading tools from connection ${id} in state "${conn.connectionState}". Tools may not be loaded yet.`);
759
+ return Object.fromEntries(getNamespacedData(this.mcpConnections, "tools").map((tool) => {
760
+ return [`tool_${tool.serverId.replace(/-/g, "")}_${tool.name}`, {
761
+ description: tool.description,
762
+ execute: async (args) => {
763
+ const result = await this.callTool({
764
+ arguments: args,
765
+ name: tool.name,
766
+ serverId: tool.serverId
767
+ });
768
+ if (result.isError) throw new Error(result.content[0].text);
769
+ return result;
770
+ },
771
+ inputSchema: this.jsonSchema(tool.inputSchema),
772
+ outputSchema: tool.outputSchema ? this.jsonSchema(tool.outputSchema) : void 0
773
+ }];
774
+ }));
775
+ }
776
+ /**
777
+ * @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version
778
+ * @returns a set of tools that you can use with the AI SDK
779
+ */
780
+ unstable_getAITools() {
781
+ if (!this._didWarnAboutUnstableGetAITools) {
782
+ this._didWarnAboutUnstableGetAITools = true;
783
+ console.warn("unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version.");
784
+ }
785
+ return this.getAITools();
786
+ }
787
+ /**
788
+ * Closes all connections to MCP servers
789
+ */
790
+ async closeAllConnections() {
791
+ const ids = Object.keys(this.mcpConnections);
792
+ await Promise.all(ids.map(async (id) => {
793
+ await this.mcpConnections[id].client.close();
794
+ }));
795
+ for (const id of ids) {
796
+ const store = this._connectionDisposables.get(id);
797
+ if (store) store.dispose();
798
+ this._connectionDisposables.delete(id);
799
+ delete this.mcpConnections[id];
800
+ }
801
+ }
802
+ /**
803
+ * Closes a connection to an MCP server
804
+ * @param id The id of the connection to close
805
+ */
806
+ async closeConnection(id) {
807
+ if (!this.mcpConnections[id]) throw new Error(`Connection with id "${id}" does not exist.`);
808
+ await this.mcpConnections[id].client.close();
809
+ delete this.mcpConnections[id];
810
+ const store = this._connectionDisposables.get(id);
811
+ if (store) store.dispose();
812
+ this._connectionDisposables.delete(id);
813
+ }
814
+ /**
815
+ * Remove an MCP server from storage
816
+ */
817
+ async removeServer(serverId) {
818
+ await this._storage.removeServer(serverId);
819
+ this._onServerStateChanged.fire();
820
+ }
821
+ /**
822
+ * List all MCP servers from storage
823
+ */
824
+ async listServers() {
825
+ return await this._storage.listServers();
826
+ }
827
+ /**
828
+ * Dispose the manager and all resources.
829
+ */
830
+ async dispose() {
831
+ try {
832
+ await this.closeAllConnections();
833
+ } finally {
834
+ this._onServerStateChanged.dispose();
835
+ this._onObservabilityEvent.dispose();
836
+ await this._storage.destroy();
837
+ }
838
+ }
839
+ /**
840
+ * @returns namespaced list of prompts
841
+ */
842
+ listPrompts() {
843
+ return getNamespacedData(this.mcpConnections, "prompts");
844
+ }
845
+ /**
846
+ * @returns namespaced list of tools
847
+ */
848
+ listResources() {
849
+ return getNamespacedData(this.mcpConnections, "resources");
850
+ }
851
+ /**
852
+ * @returns namespaced list of resource templates
853
+ */
854
+ listResourceTemplates() {
855
+ return getNamespacedData(this.mcpConnections, "resourceTemplates");
856
+ }
857
+ /**
858
+ * Namespaced version of callTool
859
+ */
860
+ async callTool(params, resultSchema, options) {
861
+ const unqualifiedName = params.name.replace(`${params.serverId}.`, "");
862
+ return this.mcpConnections[params.serverId].client.callTool({
863
+ ...params,
864
+ name: unqualifiedName
865
+ }, resultSchema, options);
866
+ }
867
+ /**
868
+ * Namespaced version of readResource
869
+ */
870
+ readResource(params, options) {
871
+ return this.mcpConnections[params.serverId].client.readResource(params, options);
872
+ }
873
+ /**
874
+ * Namespaced version of getPrompt
875
+ */
876
+ getPrompt(params, options) {
877
+ return this.mcpConnections[params.serverId].client.getPrompt(params, options);
878
+ }
879
+ };
880
+ function getNamespacedData(mcpClients, type) {
881
+ return Object.entries(mcpClients).map(([name, conn]) => {
882
+ return {
883
+ data: conn[type],
884
+ name
885
+ };
886
+ }).flatMap(({ name: serverId, data }) => {
887
+ return data.map((item) => {
888
+ return {
889
+ ...item,
890
+ serverId
891
+ };
892
+ });
893
+ });
894
+ }
895
+
896
+ //#endregion
897
+ export { getNamespacedData as n, DisposableStore as r, MCPClientManager as t };
898
+ //# sourceMappingURL=client-DvK0u9vD.js.map