@mcpjam/sdk 0.1.0

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.
@@ -0,0 +1,738 @@
1
+ import "../chunk-PZ5AY32C.js";
2
+
3
+ // mcp-client-manager/index.ts
4
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
6
+ import {
7
+ getDefaultEnvironment,
8
+ StdioClientTransport
9
+ } from "@modelcontextprotocol/sdk/client/stdio.js";
10
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
11
+ import { DEFAULT_REQUEST_TIMEOUT_MSEC } from "@modelcontextprotocol/sdk/shared/protocol.js";
12
+ import {
13
+ CallToolResultSchema as CallToolResultSchema2,
14
+ ElicitRequestSchema,
15
+ ResourceListChangedNotificationSchema,
16
+ ResourceUpdatedNotificationSchema,
17
+ PromptListChangedNotificationSchema
18
+ } from "@modelcontextprotocol/sdk/types.js";
19
+
20
+ // mcp-client-manager/tool-converters.ts
21
+ import {
22
+ CallToolResultSchema
23
+ } from "@modelcontextprotocol/sdk/types.js";
24
+ import {
25
+ dynamicTool,
26
+ jsonSchema,
27
+ tool as defineTool
28
+ } from "ai";
29
+ var ensureJsonSchemaObject = (schema) => {
30
+ var _a;
31
+ if (schema && typeof schema === "object") {
32
+ const record = schema;
33
+ const base = record.jsonSchema ? ensureJsonSchemaObject(record.jsonSchema) : record;
34
+ if (!("type" in base) || base.type === void 0) {
35
+ base.type = "object";
36
+ }
37
+ if (base.type === "object") {
38
+ base.properties = (_a = base.properties) != null ? _a : {};
39
+ if (base.additionalProperties === void 0) {
40
+ base.additionalProperties = false;
41
+ }
42
+ }
43
+ return base;
44
+ }
45
+ return {
46
+ type: "object",
47
+ properties: {},
48
+ additionalProperties: false
49
+ };
50
+ };
51
+ async function convertMCPToolsToVercelTools(listToolsResult, {
52
+ schemas = "automatic",
53
+ callTool
54
+ }) {
55
+ var _a, _b;
56
+ const tools = {};
57
+ for (const toolDescription of listToolsResult.tools) {
58
+ const { name, description, inputSchema } = toolDescription;
59
+ const execute = async (args, options) => {
60
+ var _a2, _b2;
61
+ (_b2 = (_a2 = options == null ? void 0 : options.abortSignal) == null ? void 0 : _a2.throwIfAborted) == null ? void 0 : _b2.call(_a2);
62
+ const result = await callTool({ name, args, options });
63
+ return CallToolResultSchema.parse(result);
64
+ };
65
+ let vercelTool;
66
+ if (schemas === "automatic") {
67
+ const normalizedInputSchema = ensureJsonSchemaObject(inputSchema);
68
+ vercelTool = dynamicTool({
69
+ description,
70
+ inputSchema: jsonSchema({
71
+ type: "object",
72
+ properties: (_a = normalizedInputSchema.properties) != null ? _a : {},
73
+ additionalProperties: (_b = normalizedInputSchema.additionalProperties) != null ? _b : false
74
+ }),
75
+ execute
76
+ });
77
+ } else {
78
+ const overrides = schemas;
79
+ if (!(name in overrides)) {
80
+ continue;
81
+ }
82
+ vercelTool = defineTool({
83
+ description,
84
+ inputSchema: overrides[name].inputSchema,
85
+ execute
86
+ });
87
+ }
88
+ tools[name] = vercelTool;
89
+ }
90
+ return tools;
91
+ }
92
+
93
+ // mcp-client-manager/index.ts
94
+ var MCPClientManager = class {
95
+ constructor(servers = {}, options = {}) {
96
+ this.clientStates = /* @__PURE__ */ new Map();
97
+ this.notificationHandlers = /* @__PURE__ */ new Map();
98
+ this.elicitationHandlers = /* @__PURE__ */ new Map();
99
+ this.toolsMetadataCache = /* @__PURE__ */ new Map();
100
+ this.pendingElicitations = /* @__PURE__ */ new Map();
101
+ var _a, _b, _c;
102
+ this.defaultClientVersion = (_a = options.defaultClientVersion) != null ? _a : "1.0.0";
103
+ this.defaultCapabilities = { ...(_b = options.defaultCapabilities) != null ? _b : {} };
104
+ this.defaultTimeout = (_c = options.defaultTimeout) != null ? _c : DEFAULT_REQUEST_TIMEOUT_MSEC;
105
+ for (const [id, config] of Object.entries(servers)) {
106
+ void this.connectToServer(id, config);
107
+ }
108
+ }
109
+ listServers() {
110
+ return Array.from(this.clientStates.keys());
111
+ }
112
+ hasServer(serverId) {
113
+ return this.clientStates.has(serverId);
114
+ }
115
+ getServerSummaries() {
116
+ return Array.from(this.clientStates.entries()).map(([serverId, state]) => ({
117
+ id: serverId,
118
+ status: this.resolveConnectionStatus(state),
119
+ config: state.config
120
+ }));
121
+ }
122
+ getConnectionStatus(serverId) {
123
+ return this.resolveConnectionStatus(this.clientStates.get(serverId));
124
+ }
125
+ getServerConfig(serverId) {
126
+ var _a;
127
+ return (_a = this.clientStates.get(serverId)) == null ? void 0 : _a.config;
128
+ }
129
+ async connectToServer(serverId, config) {
130
+ var _a;
131
+ if (this.clientStates.has(serverId)) {
132
+ throw new Error(`MCP server "${serverId}" is already connected.`);
133
+ }
134
+ const timeout = this.getTimeout(config);
135
+ const state = (_a = this.clientStates.get(serverId)) != null ? _a : {
136
+ config,
137
+ timeout
138
+ };
139
+ state.config = config;
140
+ state.timeout = timeout;
141
+ if (state.client) {
142
+ this.clientStates.set(serverId, state);
143
+ return state.client;
144
+ }
145
+ if (state.promise) {
146
+ this.clientStates.set(serverId, state);
147
+ return state.promise;
148
+ }
149
+ const connectionPromise = (async () => {
150
+ var _a2;
151
+ const client = new Client(
152
+ {
153
+ name: serverId,
154
+ version: (_a2 = config.version) != null ? _a2 : this.defaultClientVersion
155
+ },
156
+ {
157
+ capabilities: this.buildCapabilities(config)
158
+ }
159
+ );
160
+ this.applyNotificationHandlers(serverId, client);
161
+ this.applyElicitationHandler(serverId, client);
162
+ if (config.onError) {
163
+ client.onerror = (error) => {
164
+ var _a3;
165
+ (_a3 = config.onError) == null ? void 0 : _a3.call(config, error);
166
+ };
167
+ }
168
+ client.onclose = () => {
169
+ this.resetState(serverId);
170
+ };
171
+ let transport;
172
+ if (this.isStdioConfig(config)) {
173
+ transport = await this.connectViaStdio(client, config, timeout);
174
+ } else {
175
+ transport = await this.connectViaHttp(
176
+ serverId,
177
+ client,
178
+ config,
179
+ timeout
180
+ );
181
+ }
182
+ state.client = client;
183
+ state.transport = transport;
184
+ state.promise = void 0;
185
+ this.clientStates.set(serverId, state);
186
+ return client;
187
+ })().catch((error) => {
188
+ state.promise = void 0;
189
+ state.client = void 0;
190
+ state.transport = void 0;
191
+ this.clientStates.set(serverId, state);
192
+ throw error;
193
+ });
194
+ state.promise = connectionPromise;
195
+ this.clientStates.set(serverId, state);
196
+ return connectionPromise;
197
+ }
198
+ async disconnectServer(serverId) {
199
+ const client = this.getClientById(serverId);
200
+ try {
201
+ await client.close();
202
+ } finally {
203
+ if (client.transport) {
204
+ await this.safeCloseTransport(client.transport);
205
+ }
206
+ this.resetState(serverId);
207
+ }
208
+ }
209
+ removeServer(serverId) {
210
+ this.resetState(serverId);
211
+ this.notificationHandlers.delete(serverId);
212
+ this.elicitationHandlers.delete(serverId);
213
+ }
214
+ async disconnectAllServers() {
215
+ const serverIds = this.listServers();
216
+ await Promise.all(
217
+ serverIds.map((serverId) => this.disconnectServer(serverId))
218
+ );
219
+ for (const serverId of serverIds) {
220
+ this.resetState(serverId);
221
+ this.notificationHandlers.delete(serverId);
222
+ this.elicitationHandlers.delete(serverId);
223
+ }
224
+ }
225
+ async listTools(serverId, params, options) {
226
+ await this.ensureConnected(serverId);
227
+ const client = this.getClientById(serverId);
228
+ try {
229
+ const result = await client.listTools(
230
+ params,
231
+ this.withTimeout(serverId, options)
232
+ );
233
+ const metadataMap = /* @__PURE__ */ new Map();
234
+ for (const tool of result.tools) {
235
+ if (tool._meta) {
236
+ metadataMap.set(tool.name, tool._meta);
237
+ }
238
+ }
239
+ this.toolsMetadataCache.set(serverId, metadataMap);
240
+ return result;
241
+ } catch (error) {
242
+ if (this.isMethodUnavailableError(error, "tools/list")) {
243
+ this.toolsMetadataCache.set(serverId, /* @__PURE__ */ new Map());
244
+ return { tools: [] };
245
+ }
246
+ throw error;
247
+ }
248
+ }
249
+ async getTools(serverIds) {
250
+ const targetServerIds = serverIds && serverIds.length > 0 ? serverIds : this.listServers();
251
+ const toolLists = await Promise.all(
252
+ targetServerIds.map(async (serverId) => {
253
+ await this.ensureConnected(serverId);
254
+ const client = this.getClientById(serverId);
255
+ const result = await client.listTools(
256
+ void 0,
257
+ this.withTimeout(serverId)
258
+ );
259
+ const metadataMap = /* @__PURE__ */ new Map();
260
+ for (const tool of result.tools) {
261
+ if (tool._meta) {
262
+ metadataMap.set(tool.name, tool._meta);
263
+ }
264
+ }
265
+ this.toolsMetadataCache.set(serverId, metadataMap);
266
+ return result.tools;
267
+ })
268
+ );
269
+ return { tools: toolLists.flat() };
270
+ }
271
+ getAllToolsMetadata(serverId) {
272
+ const metadataMap = this.toolsMetadataCache.get(serverId);
273
+ return metadataMap ? Object.fromEntries(metadataMap) : {};
274
+ }
275
+ pingServer(serverId, options) {
276
+ const client = this.getClientById(serverId);
277
+ try {
278
+ client.ping(options);
279
+ } catch (error) {
280
+ throw new Error(
281
+ `Failed to ping MCP server "${serverId}": ${error instanceof Error ? error.message : "Unknown error"}`
282
+ );
283
+ }
284
+ }
285
+ async getToolsForAiSdk(serverIds, options = {}) {
286
+ const ids = Array.isArray(serverIds) ? serverIds : serverIds ? [serverIds] : this.listServers();
287
+ const loadForServer = async (id) => {
288
+ await this.ensureConnected(id);
289
+ const listToolsResult = await this.listTools(id);
290
+ return convertMCPToolsToVercelTools(listToolsResult, {
291
+ schemas: options.schemas,
292
+ callTool: async ({ name, args, options: callOptions }) => {
293
+ const requestOptions = (callOptions == null ? void 0 : callOptions.abortSignal) ? { signal: callOptions.abortSignal } : void 0;
294
+ const result = await this.executeTool(
295
+ id,
296
+ name,
297
+ args != null ? args : {},
298
+ requestOptions
299
+ );
300
+ return CallToolResultSchema2.parse(result);
301
+ }
302
+ });
303
+ };
304
+ const perServerTools = await Promise.all(
305
+ ids.map(async (id) => {
306
+ try {
307
+ const tools = await loadForServer(id);
308
+ for (const [name, tool] of Object.entries(tools)) {
309
+ tool._serverId = id;
310
+ }
311
+ return tools;
312
+ } catch (error) {
313
+ if (this.isMethodUnavailableError(error, "tools/list")) {
314
+ return {};
315
+ }
316
+ throw error;
317
+ }
318
+ })
319
+ );
320
+ const flattened = {};
321
+ for (const toolset of perServerTools) {
322
+ for (const [name, tool] of Object.entries(toolset)) {
323
+ flattened[name] = tool;
324
+ }
325
+ }
326
+ return flattened;
327
+ }
328
+ async executeTool(serverId, toolName, args = {}, options) {
329
+ await this.ensureConnected(serverId);
330
+ const client = this.getClientById(serverId);
331
+ return client.callTool(
332
+ {
333
+ name: toolName,
334
+ arguments: args
335
+ },
336
+ CallToolResultSchema2,
337
+ this.withTimeout(serverId, options)
338
+ );
339
+ }
340
+ async listResources(serverId, params, options) {
341
+ await this.ensureConnected(serverId);
342
+ const client = this.getClientById(serverId);
343
+ try {
344
+ return await client.listResources(
345
+ params,
346
+ this.withTimeout(serverId, options)
347
+ );
348
+ } catch (error) {
349
+ if (this.isMethodUnavailableError(error, "resources/list")) {
350
+ return {
351
+ resources: []
352
+ };
353
+ }
354
+ throw error;
355
+ }
356
+ }
357
+ async readResource(serverId, params, options) {
358
+ await this.ensureConnected(serverId);
359
+ const client = this.getClientById(serverId);
360
+ return client.readResource(params, this.withTimeout(serverId, options));
361
+ }
362
+ async subscribeResource(serverId, params, options) {
363
+ await this.ensureConnected(serverId);
364
+ const client = this.getClientById(serverId);
365
+ return client.subscribeResource(
366
+ params,
367
+ this.withTimeout(serverId, options)
368
+ );
369
+ }
370
+ async unsubscribeResource(serverId, params, options) {
371
+ await this.ensureConnected(serverId);
372
+ const client = this.getClientById(serverId);
373
+ return client.unsubscribeResource(
374
+ params,
375
+ this.withTimeout(serverId, options)
376
+ );
377
+ }
378
+ async listResourceTemplates(serverId, params, options) {
379
+ await this.ensureConnected(serverId);
380
+ const client = this.getClientById(serverId);
381
+ return client.listResourceTemplates(
382
+ params,
383
+ this.withTimeout(serverId, options)
384
+ );
385
+ }
386
+ async listPrompts(serverId, params, options) {
387
+ await this.ensureConnected(serverId);
388
+ const client = this.getClientById(serverId);
389
+ try {
390
+ return await client.listPrompts(
391
+ params,
392
+ this.withTimeout(serverId, options)
393
+ );
394
+ } catch (error) {
395
+ if (this.isMethodUnavailableError(error, "prompts/list")) {
396
+ return {
397
+ prompts: []
398
+ };
399
+ }
400
+ throw error;
401
+ }
402
+ }
403
+ async getPrompt(serverId, params, options) {
404
+ await this.ensureConnected(serverId);
405
+ const client = this.getClientById(serverId);
406
+ return client.getPrompt(params, this.withTimeout(serverId, options));
407
+ }
408
+ getSessionIdByServer(serverId) {
409
+ const state = this.clientStates.get(serverId);
410
+ if (!(state == null ? void 0 : state.transport)) {
411
+ throw new Error(`Unknown MCP server "${serverId}".`);
412
+ }
413
+ if (state.transport instanceof StreamableHTTPClientTransport) {
414
+ return state.transport.sessionId;
415
+ }
416
+ throw new Error(
417
+ `Server "${serverId}" must be Streamable HTTP to get the session ID.`
418
+ );
419
+ }
420
+ addNotificationHandler(serverId, schema, handler) {
421
+ var _a, _b, _c;
422
+ const serverHandlers = (_a = this.notificationHandlers.get(serverId)) != null ? _a : /* @__PURE__ */ new Map();
423
+ const handlersForSchema = (_b = serverHandlers.get(schema)) != null ? _b : /* @__PURE__ */ new Set();
424
+ handlersForSchema.add(handler);
425
+ serverHandlers.set(schema, handlersForSchema);
426
+ this.notificationHandlers.set(serverId, serverHandlers);
427
+ const client = (_c = this.clientStates.get(serverId)) == null ? void 0 : _c.client;
428
+ if (client) {
429
+ client.setNotificationHandler(
430
+ schema,
431
+ this.createNotificationDispatcher(serverId, schema)
432
+ );
433
+ }
434
+ }
435
+ onResourceListChanged(serverId, handler) {
436
+ this.addNotificationHandler(
437
+ serverId,
438
+ ResourceListChangedNotificationSchema,
439
+ handler
440
+ );
441
+ }
442
+ onResourceUpdated(serverId, handler) {
443
+ this.addNotificationHandler(
444
+ serverId,
445
+ ResourceUpdatedNotificationSchema,
446
+ handler
447
+ );
448
+ }
449
+ onPromptListChanged(serverId, handler) {
450
+ this.addNotificationHandler(
451
+ serverId,
452
+ PromptListChangedNotificationSchema,
453
+ handler
454
+ );
455
+ }
456
+ getClient(serverId) {
457
+ var _a;
458
+ return (_a = this.clientStates.get(serverId)) == null ? void 0 : _a.client;
459
+ }
460
+ setElicitationHandler(serverId, handler) {
461
+ var _a;
462
+ if (!this.clientStates.has(serverId)) {
463
+ throw new Error(`Unknown MCP server "${serverId}".`);
464
+ }
465
+ this.elicitationHandlers.set(serverId, handler);
466
+ const client = (_a = this.clientStates.get(serverId)) == null ? void 0 : _a.client;
467
+ if (client) {
468
+ this.applyElicitationHandler(serverId, client);
469
+ }
470
+ }
471
+ clearElicitationHandler(serverId) {
472
+ var _a;
473
+ this.elicitationHandlers.delete(serverId);
474
+ const client = (_a = this.clientStates.get(serverId)) == null ? void 0 : _a.client;
475
+ if (client) {
476
+ client.removeRequestHandler("elicitation/create");
477
+ }
478
+ }
479
+ // Global elicitation callback API (no serverId required)
480
+ setElicitationCallback(callback) {
481
+ this.elicitationCallback = callback;
482
+ for (const [serverId, state] of this.clientStates.entries()) {
483
+ const client = state.client;
484
+ if (!client) continue;
485
+ if (this.elicitationHandlers.has(serverId)) {
486
+ this.applyElicitationHandler(serverId, client);
487
+ } else {
488
+ this.applyElicitationHandler(serverId, client);
489
+ }
490
+ }
491
+ }
492
+ clearElicitationCallback() {
493
+ this.elicitationCallback = void 0;
494
+ for (const [serverId, state] of this.clientStates.entries()) {
495
+ const client = state.client;
496
+ if (!client) continue;
497
+ if (this.elicitationHandlers.has(serverId)) {
498
+ this.applyElicitationHandler(serverId, client);
499
+ } else {
500
+ client.removeRequestHandler("elicitation/create");
501
+ }
502
+ }
503
+ }
504
+ // Expose the pending elicitation map so callers can add resolvers
505
+ getPendingElicitations() {
506
+ return this.pendingElicitations;
507
+ }
508
+ // Helper to resolve a pending elicitation from outside
509
+ respondToElicitation(requestId, response) {
510
+ const pending = this.pendingElicitations.get(requestId);
511
+ if (!pending) return false;
512
+ try {
513
+ pending.resolve(response);
514
+ return true;
515
+ } finally {
516
+ this.pendingElicitations.delete(requestId);
517
+ }
518
+ }
519
+ async connectViaStdio(client, config, timeout) {
520
+ var _a;
521
+ const transport = new StdioClientTransport({
522
+ command: config.command,
523
+ args: config.args,
524
+ env: { ...getDefaultEnvironment(), ...(_a = config.env) != null ? _a : {} }
525
+ });
526
+ await client.connect(transport, { timeout });
527
+ return transport;
528
+ }
529
+ async connectViaHttp(serverId, client, config, timeout) {
530
+ var _a;
531
+ const preferSSE = (_a = config.preferSSE) != null ? _a : config.url.pathname.endsWith("/sse");
532
+ let streamableError;
533
+ if (!preferSSE) {
534
+ const streamableTransport = new StreamableHTTPClientTransport(
535
+ config.url,
536
+ {
537
+ requestInit: config.requestInit,
538
+ reconnectionOptions: config.reconnectionOptions,
539
+ authProvider: config.authProvider,
540
+ sessionId: config.sessionId
541
+ }
542
+ );
543
+ try {
544
+ await client.connect(streamableTransport, {
545
+ timeout: Math.min(timeout, 3e3)
546
+ });
547
+ return streamableTransport;
548
+ } catch (error) {
549
+ streamableError = error;
550
+ await this.safeCloseTransport(streamableTransport);
551
+ }
552
+ }
553
+ const sseTransport = new SSEClientTransport(config.url, {
554
+ requestInit: config.requestInit,
555
+ eventSourceInit: config.eventSourceInit,
556
+ authProvider: config.authProvider
557
+ });
558
+ try {
559
+ await client.connect(sseTransport, { timeout });
560
+ return sseTransport;
561
+ } catch (error) {
562
+ await this.safeCloseTransport(sseTransport);
563
+ const streamableMessage = streamableError ? ` Streamable HTTP error: ${this.formatError(streamableError)}.` : "";
564
+ throw new Error(
565
+ `Failed to connect to MCP server "${serverId}" using HTTP transports.${streamableMessage} SSE error: ${this.formatError(error)}.`
566
+ );
567
+ }
568
+ }
569
+ async safeCloseTransport(transport) {
570
+ try {
571
+ await transport.close();
572
+ } catch {
573
+ }
574
+ }
575
+ applyNotificationHandlers(serverId, client) {
576
+ const serverHandlers = this.notificationHandlers.get(serverId);
577
+ if (!serverHandlers) {
578
+ return;
579
+ }
580
+ for (const [schema] of serverHandlers) {
581
+ client.setNotificationHandler(
582
+ schema,
583
+ this.createNotificationDispatcher(serverId, schema)
584
+ );
585
+ }
586
+ }
587
+ createNotificationDispatcher(serverId, schema) {
588
+ return (notification) => {
589
+ const serverHandlers = this.notificationHandlers.get(serverId);
590
+ const handlersForSchema = serverHandlers == null ? void 0 : serverHandlers.get(schema);
591
+ if (!handlersForSchema || handlersForSchema.size === 0) {
592
+ return;
593
+ }
594
+ for (const handler of handlersForSchema) {
595
+ try {
596
+ handler(notification);
597
+ } catch {
598
+ }
599
+ }
600
+ };
601
+ }
602
+ applyElicitationHandler(serverId, client) {
603
+ const serverSpecific = this.elicitationHandlers.get(serverId);
604
+ if (serverSpecific) {
605
+ client.setRequestHandler(
606
+ ElicitRequestSchema,
607
+ async (request) => serverSpecific(request.params)
608
+ );
609
+ return;
610
+ }
611
+ if (this.elicitationCallback) {
612
+ client.setRequestHandler(ElicitRequestSchema, async (request) => {
613
+ var _a, _b, _c, _d;
614
+ const reqId = `elicit_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
615
+ return await this.elicitationCallback({
616
+ requestId: reqId,
617
+ message: (_a = request.params) == null ? void 0 : _a.message,
618
+ schema: (_d = (_b = request.params) == null ? void 0 : _b.requestedSchema) != null ? _d : (_c = request.params) == null ? void 0 : _c.schema
619
+ });
620
+ });
621
+ return;
622
+ }
623
+ }
624
+ async ensureConnected(serverId) {
625
+ const state = this.clientStates.get(serverId);
626
+ if (state == null ? void 0 : state.client) {
627
+ return;
628
+ }
629
+ if (!state) {
630
+ throw new Error(`Unknown MCP server "${serverId}".`);
631
+ }
632
+ if (state.promise) {
633
+ await state.promise;
634
+ return;
635
+ }
636
+ await this.connectToServer(serverId, state.config);
637
+ }
638
+ resetState(serverId) {
639
+ this.clientStates.delete(serverId);
640
+ this.toolsMetadataCache.delete(serverId);
641
+ }
642
+ resolveConnectionStatus(state) {
643
+ if (!state) {
644
+ return "disconnected";
645
+ }
646
+ if (state.client) {
647
+ return "connected";
648
+ }
649
+ if (state.promise) {
650
+ return "connecting";
651
+ }
652
+ return "disconnected";
653
+ }
654
+ withTimeout(serverId, options) {
655
+ var _a;
656
+ const state = this.clientStates.get(serverId);
657
+ const timeout = (_a = state == null ? void 0 : state.timeout) != null ? _a : state ? this.getTimeout(state.config) : this.defaultTimeout;
658
+ if (!options) {
659
+ return { timeout };
660
+ }
661
+ if (options.timeout === void 0) {
662
+ return { ...options, timeout };
663
+ }
664
+ return options;
665
+ }
666
+ buildCapabilities(config) {
667
+ var _a;
668
+ const capabilities = {
669
+ ...this.defaultCapabilities,
670
+ ...(_a = config.capabilities) != null ? _a : {}
671
+ };
672
+ if (!capabilities.elicitation) {
673
+ capabilities.elicitation = {};
674
+ }
675
+ return capabilities;
676
+ }
677
+ formatError(error) {
678
+ if (error instanceof Error) {
679
+ return error.message;
680
+ }
681
+ try {
682
+ return JSON.stringify(error);
683
+ } catch {
684
+ return String(error);
685
+ }
686
+ }
687
+ isMethodUnavailableError(error, method) {
688
+ if (!(error instanceof Error)) {
689
+ return false;
690
+ }
691
+ const message = error.message.toLowerCase();
692
+ const methodTokens = /* @__PURE__ */ new Set();
693
+ const pushToken = (token) => {
694
+ if (token) {
695
+ methodTokens.add(token.toLowerCase());
696
+ }
697
+ };
698
+ pushToken(method);
699
+ for (const part of method.split(/[\/:._-]/)) {
700
+ pushToken(part);
701
+ }
702
+ const indicators = [
703
+ "method not found",
704
+ "not implemented",
705
+ "unsupported",
706
+ "does not support",
707
+ "unimplemented"
708
+ ];
709
+ const indicatorMatch = indicators.some(
710
+ (indicator) => message.includes(indicator)
711
+ );
712
+ if (!indicatorMatch) {
713
+ return false;
714
+ }
715
+ if (Array.from(methodTokens).some((token) => message.includes(token))) {
716
+ return true;
717
+ }
718
+ return true;
719
+ }
720
+ getTimeout(config) {
721
+ var _a;
722
+ return (_a = config.timeout) != null ? _a : this.defaultTimeout;
723
+ }
724
+ isStdioConfig(config) {
725
+ return "command" in config;
726
+ }
727
+ getClientById(serverId) {
728
+ const state = this.clientStates.get(serverId);
729
+ if (!(state == null ? void 0 : state.client)) {
730
+ throw new Error(`MCP server "${serverId}" is not connected.`);
731
+ }
732
+ return state.client;
733
+ }
734
+ };
735
+ export {
736
+ MCPClientManager
737
+ };
738
+ //# sourceMappingURL=index.js.map