@nest-mcp/client 1.0.1 → 2.0.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/README.md +845 -69
  3. package/dist/ai-sdk/index.d.mts +14 -0
  4. package/dist/ai-sdk/index.d.mts.map +1 -0
  5. package/dist/ai-sdk/index.mjs +27 -0
  6. package/dist/ai-sdk/index.mjs.map +1 -0
  7. package/dist/bootstrap-BIAcDnHp.d.mts +394 -0
  8. package/dist/bootstrap-BIAcDnHp.d.mts.map +1 -0
  9. package/dist/index.d.mts +480 -0
  10. package/dist/index.d.mts.map +1 -0
  11. package/dist/index.mjs +1960 -0
  12. package/dist/index.mjs.map +1 -0
  13. package/dist/oauth/dynamic-registration.d.mts +92 -0
  14. package/dist/oauth/dynamic-registration.d.mts.map +1 -0
  15. package/dist/oauth/dynamic-registration.mjs +392 -0
  16. package/dist/oauth/dynamic-registration.mjs.map +1 -0
  17. package/dist/oauth/index.d.mts +422 -0
  18. package/dist/oauth/index.d.mts.map +1 -0
  19. package/dist/oauth/index.mjs +3349 -0
  20. package/dist/oauth/index.mjs.map +1 -0
  21. package/dist/scope-CxGBCDdr.mjs +22 -0
  22. package/dist/scope-CxGBCDdr.mjs.map +1 -0
  23. package/package.json +76 -50
  24. package/scripts/external-smoke.mjs +693 -0
  25. package/dist/decorators/inject-mcp-client.decorator.d.ts +0 -3
  26. package/dist/decorators/inject-mcp-client.decorator.js +0 -12
  27. package/dist/decorators/on-notification.decorator.d.ts +0 -7
  28. package/dist/decorators/on-notification.decorator.js +0 -13
  29. package/dist/health/mcp-client.health.d.ts +0 -20
  30. package/dist/health/mcp-client.health.js +0 -42
  31. package/dist/index.d.ts +0 -21
  32. package/dist/index.js +0 -64
  33. package/dist/interfaces/client-options.interface.d.ts +0 -139
  34. package/dist/interfaces/client-options.interface.js +0 -3
  35. package/dist/mcp-client.module.d.ts +0 -20
  36. package/dist/mcp-client.module.js +0 -188
  37. package/dist/mcp-client.service.d.ts +0 -558
  38. package/dist/mcp-client.service.js +0 -532
  39. package/dist/mcp-clients.service.d.ts +0 -39
  40. package/dist/mcp-clients.service.js +0 -104
  41. package/dist/testing/mock-client.d.ts +0 -67
  42. package/dist/testing/mock-client.js +0 -154
  43. package/dist/transport/apply-auth-headers.d.ts +0 -3
  44. package/dist/transport/apply-auth-headers.js +0 -13
  45. package/dist/transport/client-transport.factory.d.ts +0 -4
  46. package/dist/transport/client-transport.factory.js +0 -21
  47. package/dist/transport/sse-client.transport.d.ts +0 -4
  48. package/dist/transport/sse-client.transport.js +0 -15
  49. package/dist/transport/stdio-client.transport.d.ts +0 -4
  50. package/dist/transport/stdio-client.transport.js +0 -14
  51. package/dist/transport/streamable-client.transport.d.ts +0 -4
  52. package/dist/transport/streamable-client.transport.js +0 -17
  53. package/dist/utils/format-error-message.d.ts +0 -2
  54. package/dist/utils/format-error-message.js +0 -7
@@ -1,532 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.McpClient = void 0;
4
- const index_js_1 = require("@modelcontextprotocol/sdk/client/index.js");
5
- const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
6
- const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
7
- const common_1 = require("@nest-mcp/common");
8
- const common_2 = require("@nestjs/common");
9
- const client_transport_factory_1 = require("./transport/client-transport.factory");
10
- /** Upper bound on the HTTP DELETE sent by `disconnect()`, so a silent server cannot stall shutdown. */
11
- const TERMINATE_SESSION_TIMEOUT_MS = 5000;
12
- /** Dispatchers installed by `onNotification`, so they are not wrapped twice on the same SDK client. */
13
- const installedDispatchers = new WeakSet();
14
- function isPlainObject(value) {
15
- return value !== null && typeof value === 'object' && !Array.isArray(value);
16
- }
17
- /**
18
- * Merge capabilities per key: nested objects are shallow-merged, `additional` wins on conflicts.
19
- * Same semantics as the SDK's `Client.registerCapabilities`.
20
- */
21
- function mergeCapabilities(base, additional) {
22
- const result = { ...base };
23
- for (const [key, value] of Object.entries(additional)) {
24
- if (value === undefined)
25
- continue;
26
- const current = result[key];
27
- result[key] = isPlainObject(current) && isPlainObject(value) ? { ...current, ...value } : value;
28
- }
29
- return result;
30
- }
31
- /** Streamable HTTP answers 404 to a request carrying an expired or unknown `Mcp-Session-Id`. */
32
- function isSessionExpiredError(err) {
33
- if (err instanceof streamableHttp_js_1.StreamableHTTPError)
34
- return err.code === 404;
35
- // Also recognise errors from another copy of the SDK (instanceof fails across copies).
36
- return (err instanceof Error &&
37
- err.code === 404 &&
38
- err.message.startsWith('Streamable HTTP error'));
39
- }
40
- function errorMessage(err) {
41
- return err instanceof Error ? err.message : String(err);
42
- }
43
- class McpClient {
44
- name;
45
- connection;
46
- logger;
47
- client;
48
- transport = null;
49
- connected = false;
50
- reconnectAttempts = 0;
51
- reconnecting = false;
52
- /** Set by `disconnect()`; stops reconnection and suppresses transport error handling. */
53
- closing = false;
54
- /** Incremented by every `disconnect()`, so a reconnect loop started earlier can detect it. */
55
- lifecycle = 0;
56
- /** Whether a transport has been created at least once (`sessionId` only applies to the first). */
57
- transportCreated = false;
58
- _notificationHandlerStore = new Map();
59
- /** URIs subscribed through `subscribeResource`, replayed after a reconnect. */
60
- _subscriptions = new Set();
61
- /** Capabilities passed by the user in the connection options. */
62
- _userCapabilities;
63
- /** Capabilities implied by registered handlers (sampling, elicitation, roots). */
64
- _handlerCapabilities = {};
65
- _samplingHandler;
66
- _elicitationHandler;
67
- _rootsHandler;
68
- constructor(name, connection) {
69
- this.name = name;
70
- this.connection = connection;
71
- this.logger = new common_2.Logger(`McpClient[${name}]`);
72
- this._userCapabilities = connection.capabilities ?? {};
73
- this.client = this._createClient();
74
- if (connection.samplingHandler)
75
- this.setSamplingHandler(connection.samplingHandler);
76
- if (connection.elicitationHandler) {
77
- this.setElicitationHandler(connection.elicitationHandler, {
78
- modes: connection.elicitationModes,
79
- });
80
- }
81
- if (connection.rootsHandler)
82
- this.setRootsHandler(connection.rootsHandler);
83
- }
84
- /** Capabilities advertised on the next handshake: handler defaults, overridden by user values. */
85
- get _declaredCapabilities() {
86
- return mergeCapabilities(this._handlerCapabilities, this._userCapabilities);
87
- }
88
- _clientInfo() {
89
- const info = this.connection.clientInfo ?? {};
90
- return {
91
- ...info,
92
- name: info.name ?? `nestjs-mcp-client-${this.name}`,
93
- version: info.version ?? '1.0.0',
94
- };
95
- }
96
- _createClient() {
97
- return new index_js_1.Client(this._clientInfo(), { capabilities: this._declaredCapabilities });
98
- }
99
- async connect() {
100
- if (this.connected)
101
- return;
102
- this.closing = false;
103
- const transport = this._createTransport();
104
- this.transport = transport;
105
- this._bindTransport(transport);
106
- try {
107
- await this.client.connect(transport, this._connectOptions());
108
- this.connected = true;
109
- this._installNotificationDispatchers();
110
- this.reconnectAttempts = 0;
111
- this.logger.log(`Connected to MCP server "${this.name}"`);
112
- await this._replaySubscriptions();
113
- }
114
- catch (err) {
115
- this.logger.error(`Failed to connect to "${this.name}": ${errorMessage(err)}`);
116
- throw err;
117
- }
118
- }
119
- /**
120
- * Close the connection. For Streamable HTTP, the session is ended first with an HTTP DELETE
121
- * (errors, including a 405 from servers that do not support it, are ignored). Stops any
122
- * reconnection in progress and forgets tracked resource subscriptions.
123
- */
124
- async disconnect() {
125
- this.closing = true;
126
- this.lifecycle++;
127
- this.connected = false;
128
- this._subscriptions.clear();
129
- const transport = this.transport;
130
- // Detach first so the transport's onclose does not re-enter handleDisconnect.
131
- this.transport = null;
132
- if (!transport)
133
- return;
134
- await this._terminateSession(transport);
135
- await this._closeQuietly(transport);
136
- }
137
- isConnected() {
138
- return this.connected;
139
- }
140
- getClient() {
141
- return this.client;
142
- }
143
- async callTool(params, options) {
144
- this.assertConnected();
145
- return this.client.callTool(params, undefined, options);
146
- }
147
- async readResource(params, options) {
148
- this.assertConnected();
149
- return this.client.readResource(params, options);
150
- }
151
- async listTools(params, options) {
152
- this.assertConnected();
153
- return this.client.listTools(params, options);
154
- }
155
- async listResources(params, options) {
156
- this.assertConnected();
157
- return this.client.listResources(params, options);
158
- }
159
- async listResourceTemplates(params, options) {
160
- this.assertConnected();
161
- return this.client.listResourceTemplates(params, options);
162
- }
163
- async getPrompt(params, options) {
164
- this.assertConnected();
165
- return this.client.getPrompt(params, options);
166
- }
167
- async listPrompts(params, options) {
168
- this.assertConnected();
169
- return this.client.listPrompts(params, options);
170
- }
171
- async listAllTools(options) {
172
- this.assertConnected();
173
- return (0, common_1.drainAllPages)(async (cursor) => {
174
- const result = await this.client.listTools(cursor ? { cursor } : undefined, options);
175
- return { data: (result.tools ?? []), nextCursor: result.nextCursor };
176
- }, { onTruncated: this._warnTruncated('tools') });
177
- }
178
- async listAllResources(options) {
179
- this.assertConnected();
180
- return (0, common_1.drainAllPages)(async (cursor) => {
181
- const result = await this.client.listResources(cursor ? { cursor } : undefined, options);
182
- return { data: (result.resources ?? []), nextCursor: result.nextCursor };
183
- }, { onTruncated: this._warnTruncated('resources') });
184
- }
185
- async listAllResourceTemplates(options) {
186
- this.assertConnected();
187
- return (0, common_1.drainAllPages)(async (cursor) => {
188
- const result = await this.client.listResourceTemplates(cursor ? { cursor } : undefined, options);
189
- return {
190
- data: (result.resourceTemplates ?? []),
191
- nextCursor: result.nextCursor,
192
- };
193
- }, { onTruncated: this._warnTruncated('resource templates') });
194
- }
195
- async listAllPrompts(options) {
196
- this.assertConnected();
197
- return (0, common_1.drainAllPages)(async (cursor) => {
198
- const result = await this.client.listPrompts(cursor ? { cursor } : undefined, options);
199
- return { data: (result.prompts ?? []), nextCursor: result.nextCursor };
200
- }, { onTruncated: this._warnTruncated('prompts') });
201
- }
202
- async ping(options) {
203
- this.assertConnected();
204
- return this.client.ping(options);
205
- }
206
- /**
207
- * Subscribe to updates for a resource. Successful subscriptions are remembered and
208
- * re-sent after the client reconnects.
209
- */
210
- async subscribeResource(params, options) {
211
- this.assertConnected();
212
- const result = await this.client.subscribeResource(params, options);
213
- this._subscriptions.add(params.uri);
214
- return result;
215
- }
216
- /**
217
- * Unsubscribe from a resource. The URI is always dropped from the set replayed on reconnect,
218
- * even if the request itself fails.
219
- */
220
- async unsubscribeResource(params, options) {
221
- this._subscriptions.delete(params.uri);
222
- this.assertConnected();
223
- return this.client.unsubscribeResource(params, options);
224
- }
225
- async setLoggingLevel(level, options) {
226
- this.assertConnected();
227
- return this.client.setLoggingLevel(level, options);
228
- }
229
- async complete(params, options) {
230
- this.assertConnected();
231
- return this.client.complete(params, options);
232
- }
233
- async sendRootsListChanged() {
234
- this.assertConnected();
235
- return this.client.sendRootsListChanged();
236
- }
237
- /**
238
- * Register a handler for server→client `sampling/createMessage` requests.
239
- * Automatically declares the `sampling` capability. Should be called before `connect()`
240
- * so the capability is advertised during initialization.
241
- */
242
- setSamplingHandler(handler) {
243
- this._samplingHandler = handler;
244
- this._declareCapability('sampling', {});
245
- this._applySamplingHandler(handler);
246
- }
247
- /**
248
- * Register a handler for server→client `elicitation/create` requests.
249
- * Automatically declares the `elicitation` capability: form mode only by default, or the
250
- * modes listed in `options.modes` (e.g. `['form', 'url']` to also accept URL-mode requests).
251
- */
252
- setElicitationHandler(handler, options) {
253
- this._elicitationHandler = handler;
254
- const modes = options?.modes ?? [];
255
- const capability = {};
256
- for (const mode of modes)
257
- capability[mode] = {};
258
- this._declareCapability('elicitation', capability);
259
- this._applyElicitationHandler(handler);
260
- }
261
- /**
262
- * Register a handler for server→client `roots/list` requests.
263
- * Automatically declares the `roots` capability with `listChanged: true`.
264
- */
265
- setRootsHandler(handler) {
266
- this._rootsHandler = handler;
267
- this._declareCapability('roots', { listChanged: true });
268
- this._applyRootsHandler(handler);
269
- }
270
- /**
271
- * Register a handler for a server notification method. Several handlers can be registered for
272
- * the same method; they run in registration order, each isolated from the others' errors.
273
- * Handlers the SDK installs itself (e.g. for `notifications/progress` and
274
- * `notifications/cancelled`) keep running before them. Handlers survive reconnects.
275
- */
276
- onNotification(method, handler) {
277
- const handlers = this._notificationHandlerStore.get(method);
278
- if (handlers) {
279
- handlers.push(handler);
280
- }
281
- else {
282
- this._notificationHandlerStore.set(method, [handler]);
283
- }
284
- this._installNotificationDispatcher(method);
285
- }
286
- getServerCapabilities() {
287
- return this.client.getServerCapabilities();
288
- }
289
- getServerVersion() {
290
- return this.client.getServerVersion();
291
- }
292
- getInstructions() {
293
- return this.client.getInstructions();
294
- }
295
- /**
296
- * Record a handler-implied capability and, while not connected, register the resulting
297
- * capability on the current SDK client. User-supplied values for the same key win.
298
- */
299
- _declareCapability(key, value) {
300
- this._handlerCapabilities = {
301
- ...this._handlerCapabilities,
302
- [key]: value,
303
- };
304
- if (this.connected)
305
- return;
306
- try {
307
- this.client.registerCapabilities({
308
- [key]: this._declaredCapabilities[key],
309
- });
310
- }
311
- catch {
312
- // A handshake is in progress; the capability is advertised on the next connect.
313
- }
314
- }
315
- _applySamplingHandler(handler) {
316
- this.client.setRequestHandler(types_js_1.CreateMessageRequestSchema, (req, extra) => handler(req, extra));
317
- }
318
- _applyElicitationHandler(handler) {
319
- this.client.setRequestHandler(types_js_1.ElicitRequestSchema, (req, extra) => handler(req.params, extra));
320
- }
321
- _applyRootsHandler(handler) {
322
- this.client.setRequestHandler(types_js_1.ListRootsRequestSchema, (_req, extra) => handler(extra));
323
- }
324
- _applyRequestHandlers() {
325
- if (this._samplingHandler)
326
- this._applySamplingHandler(this._samplingHandler);
327
- if (this._elicitationHandler)
328
- this._applyElicitationHandler(this._elicitationHandler);
329
- if (this._rootsHandler)
330
- this._applyRootsHandler(this._rootsHandler);
331
- }
332
- /**
333
- * The SDK only exposes `setNotificationHandler` with a schema carrying a literal method, so the
334
- * dispatcher is installed in its handler map directly. The handler already there (if any) is
335
- * kept and called first.
336
- */
337
- _sdkNotificationHandlers() {
338
- return this.client._notificationHandlers;
339
- }
340
- _installNotificationDispatcher(method) {
341
- const sdkHandlers = this._sdkNotificationHandlers();
342
- if (!sdkHandlers)
343
- return;
344
- const previous = sdkHandlers.get(method);
345
- if (previous && installedDispatchers.has(previous))
346
- return;
347
- const dispatcher = async (notification) => {
348
- let previousFailed = false;
349
- let previousError;
350
- if (previous) {
351
- try {
352
- await previous(notification);
353
- }
354
- catch (err) {
355
- previousFailed = true;
356
- previousError = err;
357
- }
358
- }
359
- for (const handler of [...(this._notificationHandlerStore.get(method) ?? [])]) {
360
- try {
361
- await handler(notification);
362
- }
363
- catch (err) {
364
- this.logger.error(`Notification handler for "${method}" failed: ${errorMessage(err)}`);
365
- }
366
- }
367
- // Surface the SDK handler's own failure the way the SDK would have.
368
- if (previousFailed)
369
- throw previousError;
370
- };
371
- installedDispatchers.add(dispatcher);
372
- sdkHandlers.set(method, dispatcher);
373
- }
374
- _installNotificationDispatchers() {
375
- for (const method of this._notificationHandlerStore.keys()) {
376
- this._installNotificationDispatcher(method);
377
- }
378
- }
379
- _warnTruncated(kind) {
380
- return ({ maxPages, itemCount }) => this.logger.warn(`Listing ${kind} from "${this.name}" stopped after ${maxPages} pages (${itemCount} items); the result is incomplete`);
381
- }
382
- _connectOptions() {
383
- const timeout = this.connection.connectTimeout;
384
- return timeout !== undefined ? { timeout } : undefined;
385
- }
386
- /** Create a transport; a configured `sessionId` is only used for the very first one. */
387
- _createTransport() {
388
- const first = !this.transportCreated;
389
- this.transportCreated = true;
390
- if (!first && this.connection.transport === 'streamable-http' && this.connection.sessionId) {
391
- return (0, client_transport_factory_1.createClientTransport)({ ...this.connection, sessionId: undefined });
392
- }
393
- return (0, client_transport_factory_1.createClientTransport)(this.connection);
394
- }
395
- _bindTransport(transport) {
396
- // Events from a transport that has since been replaced or detached are ignored.
397
- transport.onclose = () => (this.transport === transport ? this.handleDisconnect() : undefined);
398
- transport.onerror = (err) => this._handleTransportError(transport, err);
399
- }
400
- async _handleTransportError(transport, err) {
401
- if (this.closing) {
402
- this.logger.debug(`Transport error while closing: ${err.message}`);
403
- return;
404
- }
405
- this.logger.error(`Transport error: ${err.message}`);
406
- if (!isSessionExpiredError(err) || transport !== this.transport || !this.connected)
407
- return;
408
- // The server no longer knows this session: the client must start a new one with a fresh
409
- // initialize. The SDK leaves the transport open, so close it and go through the
410
- // disconnect/reconnect path.
411
- this.logger.warn(`Session with "${this.name}" expired (HTTP 404); starting a new session`);
412
- this.transport = null;
413
- await this._closeQuietly(transport);
414
- await this.handleDisconnect();
415
- }
416
- async _terminateSession(transport) {
417
- const terminate = transport.terminateSession;
418
- if (typeof terminate !== 'function')
419
- return;
420
- let timer;
421
- try {
422
- await Promise.race([
423
- terminate.call(transport),
424
- new Promise((resolve) => {
425
- timer = setTimeout(resolve, TERMINATE_SESSION_TIMEOUT_MS);
426
- timer.unref?.();
427
- }),
428
- ]);
429
- }
430
- catch (err) {
431
- this.logger.debug(`Session termination for "${this.name}" failed: ${errorMessage(err)}`);
432
- }
433
- finally {
434
- clearTimeout(timer);
435
- }
436
- }
437
- async _replaySubscriptions() {
438
- for (const uri of [...this._subscriptions]) {
439
- try {
440
- await this.client.subscribeResource({ uri });
441
- }
442
- catch (err) {
443
- this.logger.warn(`Failed to re-subscribe to resource "${uri}": ${errorMessage(err)}`);
444
- }
445
- }
446
- }
447
- assertConnected() {
448
- if (!this.connected) {
449
- throw new Error(`McpClient "${this.name}" is not connected`);
450
- }
451
- }
452
- async handleDisconnect() {
453
- if (!this.connected)
454
- return;
455
- this.connected = false;
456
- if (this.closing)
457
- return;
458
- this.logger.warn(`Connection lost to "${this.name}"`);
459
- const reconnect = this.connection.reconnect;
460
- if (reconnect) {
461
- await this.attemptReconnect(reconnect);
462
- }
463
- }
464
- /** Whether the reconnect loop started in `lifecycle` must stop. */
465
- _reconnectCancelled(lifecycle) {
466
- return this.closing || lifecycle !== this.lifecycle;
467
- }
468
- async attemptReconnect(options) {
469
- if (this.reconnecting)
470
- return;
471
- this.reconnecting = true;
472
- const lifecycle = this.lifecycle;
473
- const maxAttempts = options.maxAttempts ?? 5;
474
- const delay = options.delay ?? 1000;
475
- this.reconnectAttempts = 0;
476
- try {
477
- while (this.reconnectAttempts < maxAttempts) {
478
- if (this._reconnectCancelled(lifecycle))
479
- return;
480
- this.reconnectAttempts++;
481
- this.logger.log(`Reconnecting to "${this.name}" (attempt ${this.reconnectAttempts}/${maxAttempts})...`);
482
- await this.sleep(delay * this.reconnectAttempts);
483
- // Stop if the client was closed, or connected again by an explicit connect(), meanwhile.
484
- if (this._reconnectCancelled(lifecycle) || this.connected)
485
- return;
486
- try {
487
- await this._reconnectOnce(lifecycle);
488
- return;
489
- }
490
- catch (err) {
491
- this.logger.warn(`Reconnection attempt ${this.reconnectAttempts} failed: ${errorMessage(err)}`);
492
- }
493
- }
494
- this.logger.error(`Failed to reconnect to "${this.name}" after ${maxAttempts} attempts`);
495
- }
496
- finally {
497
- this.reconnecting = false;
498
- }
499
- }
500
- /** One reconnection attempt with a fresh SDK client and transport; throws if it fails. */
501
- async _reconnectOnce(lifecycle) {
502
- this.client = this._createClient();
503
- this._applyRequestHandlers();
504
- this._installNotificationDispatchers();
505
- const transport = this._createTransport();
506
- this.transport = transport;
507
- this._bindTransport(transport);
508
- await this.client.connect(transport, this._connectOptions());
509
- if (this._reconnectCancelled(lifecycle)) {
510
- // disconnect() ran while the handshake was in flight: do not resurrect the connection.
511
- await this._closeQuietly(transport);
512
- return;
513
- }
514
- this.connected = true;
515
- this.reconnectAttempts = 0;
516
- this.logger.log(`Reconnected to "${this.name}"`);
517
- await this._replaySubscriptions();
518
- }
519
- async _closeQuietly(transport) {
520
- try {
521
- await transport.close();
522
- }
523
- catch {
524
- // ignore close errors
525
- }
526
- }
527
- sleep(ms) {
528
- return new Promise((resolve) => setTimeout(resolve, ms));
529
- }
530
- }
531
- exports.McpClient = McpClient;
532
- //# sourceMappingURL=mcp-client.service.js.map
@@ -1,39 +0,0 @@
1
- import type { McpClientConnection } from './interfaces/client-options.interface';
2
- import { McpClient } from './mcp-client.service';
3
- export declare class McpClientsService {
4
- private readonly clients;
5
- private readonly logger;
6
- private readonly pending;
7
- constructor(clients: McpClient[]);
8
- getClient(name: string): McpClient;
9
- getClients(): McpClient[];
10
- /** Whether a client is currently registered under `name` (regardless of connection state). */
11
- has(name: string): boolean;
12
- /**
13
- * Idempotently ensure a connected client for `connection.name`, creating and connecting one if
14
- * absent. This is the runtime counterpart to the static `connections` passed to
15
- * `McpClientModule.forRoot` — use it when upstreams are discovered at runtime (e.g. per-tenant
16
- * MCP servers registered by users).
17
- *
18
- * - If a client with that name exists and is connected, it is returned unchanged.
19
- * - If a client with that name exists but is disconnected, it is dropped and replaced with a
20
- * fresh connection.
21
- * - Concurrent calls for the same name share a single connect.
22
- *
23
- * The new client is registered in the same collection as the static ones, so it is returned by
24
- * `getClient`/`getClients` and torn down on application shutdown. A client that fails to connect
25
- * is NOT registered (the rejection propagates).
26
- *
27
- * @throws the underlying connect error if the upstream cannot be reached.
28
- */
29
- addConnection(connection: McpClientConnection): Promise<McpClient>;
30
- /** Alias for {@link addConnection}: return the connected client for `connection`, creating it if needed. */
31
- getOrCreate(connection: McpClientConnection): Promise<McpClient>;
32
- /**
33
- * Disconnect and unregister every client registered under `name` (idempotent — a no-op if none
34
- * exist). Mutates the registered collection in place so existing `getClients()` references stay
35
- * valid.
36
- */
37
- removeConnection(name: string): Promise<void>;
38
- }
39
- //# sourceMappingURL=mcp-clients.service.d.ts.map
@@ -1,104 +0,0 @@
1
- "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- };
8
- var __metadata = (this && this.__metadata) || function (k, v) {
9
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
- };
11
- var __param = (this && this.__param) || function (paramIndex, decorator) {
12
- return function (target, key) { decorator(target, key, paramIndex); }
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.McpClientsService = void 0;
16
- const common_1 = require("@nestjs/common");
17
- const mcp_client_service_1 = require("./mcp-client.service");
18
- let McpClientsService = class McpClientsService {
19
- clients;
20
- logger = new common_1.Logger('McpClientsService');
21
- // In-flight connects keyed by connection name, so concurrent addConnection/getOrCreate calls
22
- // for the same name share a single connect instead of racing to create duplicate clients.
23
- pending = new Map();
24
- constructor(clients) {
25
- this.clients = clients;
26
- }
27
- getClient(name) {
28
- const client = this.clients.find((c) => c.name === name);
29
- if (!client) {
30
- throw new Error(`McpClientsService: No client named "${name}" found.`);
31
- }
32
- return client;
33
- }
34
- getClients() {
35
- return this.clients;
36
- }
37
- /** Whether a client is currently registered under `name` (regardless of connection state). */
38
- has(name) {
39
- return this.clients.some((c) => c.name === name);
40
- }
41
- /**
42
- * Idempotently ensure a connected client for `connection.name`, creating and connecting one if
43
- * absent. This is the runtime counterpart to the static `connections` passed to
44
- * `McpClientModule.forRoot` — use it when upstreams are discovered at runtime (e.g. per-tenant
45
- * MCP servers registered by users).
46
- *
47
- * - If a client with that name exists and is connected, it is returned unchanged.
48
- * - If a client with that name exists but is disconnected, it is dropped and replaced with a
49
- * fresh connection.
50
- * - Concurrent calls for the same name share a single connect.
51
- *
52
- * The new client is registered in the same collection as the static ones, so it is returned by
53
- * `getClient`/`getClients` and torn down on application shutdown. A client that fails to connect
54
- * is NOT registered (the rejection propagates).
55
- *
56
- * @throws the underlying connect error if the upstream cannot be reached.
57
- */
58
- async addConnection(connection) {
59
- const existing = this.clients.find((c) => c.name === connection.name);
60
- if (existing?.isConnected())
61
- return existing;
62
- const inFlight = this.pending.get(connection.name);
63
- if (inFlight)
64
- return inFlight;
65
- const promise = (async () => {
66
- // Replace a stale (disconnected) client with the same name before reconnecting fresh.
67
- if (existing)
68
- await this.removeConnection(connection.name);
69
- const client = new mcp_client_service_1.McpClient(connection.name, connection);
70
- await client.connect();
71
- this.clients.push(client);
72
- this.logger.log(`Registered runtime MCP client "${connection.name}"`);
73
- return client;
74
- })().finally(() => this.pending.delete(connection.name));
75
- this.pending.set(connection.name, promise);
76
- return promise;
77
- }
78
- /** Alias for {@link addConnection}: return the connected client for `connection`, creating it if needed. */
79
- getOrCreate(connection) {
80
- return this.addConnection(connection);
81
- }
82
- /**
83
- * Disconnect and unregister every client registered under `name` (idempotent — a no-op if none
84
- * exist). Mutates the registered collection in place so existing `getClients()` references stay
85
- * valid.
86
- */
87
- async removeConnection(name) {
88
- const removed = [];
89
- for (let i = this.clients.length - 1; i >= 0; i--) {
90
- if (this.clients[i].name === name)
91
- removed.push(...this.clients.splice(i, 1));
92
- }
93
- await Promise.all(removed.map((c) => c
94
- .disconnect()
95
- .catch((e) => this.logger.warn(`Failed to disconnect "${name}": ${String(e)}`))));
96
- }
97
- };
98
- exports.McpClientsService = McpClientsService;
99
- exports.McpClientsService = McpClientsService = __decorate([
100
- (0, common_1.Injectable)(),
101
- __param(0, (0, common_1.Inject)('MCP_CLIENT_CONNECTIONS')),
102
- __metadata("design:paramtypes", [Array])
103
- ], McpClientsService);
104
- //# sourceMappingURL=mcp-clients.service.js.map