@nest-mcp/client 0.3.1 → 1.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.
- package/dist/index.d.ts +1 -1
- package/dist/interfaces/client-options.interface.d.ts +68 -5
- package/dist/mcp-client.service.d.ts +80 -12
- package/dist/mcp-client.service.js +337 -97
- package/dist/testing/mock-client.d.ts +2 -2
- package/dist/testing/mock-client.js +1 -1
- package/dist/transport/sse-client.transport.js +1 -0
- package/dist/transport/stdio-client.transport.js +1 -0
- package/dist/transport/streamable-client.transport.js +3 -0
- package/package.json +9 -6
package/dist/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export { McpClientsService } from './mcp-clients.service';
|
|
|
4
4
|
export { InjectMcpClient, getMcpClientToken } from './decorators/inject-mcp-client.decorator';
|
|
5
5
|
export { OnMcpNotification, MCP_NOTIFICATION_METADATA, } from './decorators/on-notification.decorator';
|
|
6
6
|
export type { McpNotificationMetadata } from './decorators/on-notification.decorator';
|
|
7
|
-
export type { McpClientModuleOptions, McpClientModuleAsyncOptions, McpClientConnection, McpClientHttpConnectionBase, McpClientStreamableHttpConnection, McpClientSseConnection, McpClientStdioConnection, McpClientReconnectOptions, McpClientAuthOptions, McpClientTransportType, McpSamplingHandler, McpElicitationHandler, McpRootsHandler, } from './interfaces/client-options.interface';
|
|
7
|
+
export type { McpClientModuleOptions, McpClientModuleAsyncOptions, McpClientConnection, McpClientHttpConnectionBase, McpClientStreamableHttpConnection, McpClientSseConnection, McpClientStdioConnection, McpClientReconnectOptions, McpClientAuthOptions, McpClientTransportType, McpSamplingHandler, McpElicitationHandler, McpElicitationHandlerOptions, McpElicitationMode, McpRootsHandler, McpClientRequestHandlerExtra, McpClientInfo, } from './interfaces/client-options.interface';
|
|
8
8
|
export { createClientTransport } from './transport/client-transport.factory';
|
|
9
9
|
export { createStreamableHttpTransport } from './transport/streamable-client.transport';
|
|
10
10
|
export { createSseTransport } from './transport/sse-client.transport';
|
|
@@ -1,10 +1,35 @@
|
|
|
1
1
|
import type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';
|
|
2
|
-
import type {
|
|
2
|
+
import type { StdioServerParameters } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
3
|
+
import type { StreamableHTTPReconnectionOptions } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
4
|
+
import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
|
|
5
|
+
import type { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';
|
|
6
|
+
import type { ClientCapabilities, ClientNotification, ClientRequest, CreateMessageRequest, CreateMessageResult, ElicitRequestFormParams, ElicitRequestURLParams, ElicitResult, Implementation, ListRootsResult, Notification as McpNotification, Request as McpRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
3
7
|
import type { InjectionToken, ModuleMetadata } from '@nestjs/common';
|
|
4
8
|
export type McpClientTransportType = 'streamable-http' | 'sse' | 'stdio';
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Per-request context the SDK passes to server-to-client request handlers: the abort `signal`
|
|
11
|
+
* (fired when the server cancels the request), `requestId`, `_meta`, and `sendNotification` /
|
|
12
|
+
* `sendRequest` for messages related to the request being handled.
|
|
13
|
+
*/
|
|
14
|
+
export type McpClientRequestHandlerExtra = RequestHandlerExtra<ClientRequest | McpRequest, ClientNotification | McpNotification>;
|
|
15
|
+
export type McpSamplingHandler = (request: CreateMessageRequest, extra?: McpClientRequestHandlerExtra) => CreateMessageResult | Promise<CreateMessageResult>;
|
|
16
|
+
export type McpElicitationHandler = (params: ElicitRequestFormParams | ElicitRequestURLParams, extra?: McpClientRequestHandlerExtra) => ElicitResult | Promise<ElicitResult>;
|
|
17
|
+
export type McpRootsHandler = (extra?: McpClientRequestHandlerExtra) => ListRootsResult | Promise<ListRootsResult>;
|
|
18
|
+
/** Elicitation modes a client can declare support for. */
|
|
19
|
+
export type McpElicitationMode = 'form' | 'url';
|
|
20
|
+
export interface McpElicitationHandlerOptions {
|
|
21
|
+
/**
|
|
22
|
+
* Elicitation modes to advertise in the `elicitation` capability.
|
|
23
|
+
* Omitted or empty: form mode only (declared as `elicitation: {}`, the backward-compatible form).
|
|
24
|
+
* `['form', 'url']` declares `{ form: {}, url: {} }`; `['url']` declares URL mode only.
|
|
25
|
+
*/
|
|
26
|
+
modes?: McpElicitationMode[];
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* `clientInfo` sent in the `initialize` request. Every field is optional; `name` defaults to
|
|
30
|
+
* `nestjs-mcp-client-<connection name>` and `version` to `1.0.0`.
|
|
31
|
+
*/
|
|
32
|
+
export type McpClientInfo = Partial<Implementation>;
|
|
8
33
|
export interface McpClientReconnectOptions {
|
|
9
34
|
maxAttempts?: number;
|
|
10
35
|
delay?: number;
|
|
@@ -15,11 +40,21 @@ export interface McpClientAuthOptions {
|
|
|
15
40
|
}
|
|
16
41
|
interface McpClientConnectionBase {
|
|
17
42
|
name: string;
|
|
43
|
+
/**
|
|
44
|
+
* Timeout in milliseconds for the `initialize` handshake performed by `connect()` and by each
|
|
45
|
+
* reconnection attempt. Defaults to the SDK request timeout (60 seconds).
|
|
46
|
+
*/
|
|
18
47
|
connectTimeout?: number;
|
|
19
48
|
reconnect?: McpClientReconnectOptions;
|
|
49
|
+
/**
|
|
50
|
+
* Identity sent as `clientInfo` in the `initialize` request.
|
|
51
|
+
* Defaults to `{ name: 'nestjs-mcp-client-<connection name>', version: '1.0.0' }`.
|
|
52
|
+
*/
|
|
53
|
+
clientInfo?: McpClientInfo;
|
|
20
54
|
/**
|
|
21
55
|
* Client capabilities to advertise during the MCP initialization handshake.
|
|
22
|
-
* Merged with
|
|
56
|
+
* Merged per key with the capabilities implicitly declared by setSamplingHandler /
|
|
57
|
+
* setElicitationHandler / setRootsHandler; values set here win over those defaults.
|
|
23
58
|
*/
|
|
24
59
|
capabilities?: ClientCapabilities;
|
|
25
60
|
/**
|
|
@@ -33,6 +68,11 @@ interface McpClientConnectionBase {
|
|
|
33
68
|
* Setting this automatically declares the `elicitation` client capability.
|
|
34
69
|
*/
|
|
35
70
|
elicitationHandler?: McpElicitationHandler;
|
|
71
|
+
/**
|
|
72
|
+
* Elicitation modes declared for `elicitationHandler`. Defaults to form mode only.
|
|
73
|
+
* Include `'url'` to accept URL-mode elicitation requests.
|
|
74
|
+
*/
|
|
75
|
+
elicitationModes?: McpElicitationMode[];
|
|
36
76
|
/**
|
|
37
77
|
* Register a handler for server-to-client `roots/list` requests.
|
|
38
78
|
* Setting this automatically declares the `roots` client capability.
|
|
@@ -41,12 +81,30 @@ interface McpClientConnectionBase {
|
|
|
41
81
|
}
|
|
42
82
|
export interface McpClientHttpConnectionBase extends McpClientConnectionBase {
|
|
43
83
|
url: string;
|
|
84
|
+
/**
|
|
85
|
+
* Static bearer token sent as the `Authorization` header on every request.
|
|
86
|
+
* Do not combine with `authProvider`: this header overrides the OAuth access token.
|
|
87
|
+
*/
|
|
44
88
|
auth?: McpClientAuthOptions;
|
|
45
89
|
authProvider?: OAuthClientProvider;
|
|
46
90
|
requestInit?: RequestInit;
|
|
91
|
+
/** Custom `fetch` implementation the transport uses for its HTTP requests. */
|
|
92
|
+
fetch?: FetchLike;
|
|
47
93
|
}
|
|
48
94
|
export interface McpClientStreamableHttpConnection extends McpClientHttpConnectionBase {
|
|
49
95
|
transport: 'streamable-http';
|
|
96
|
+
/**
|
|
97
|
+
* How the transport itself re-opens dropped SSE streams (the GET stream and resumable request
|
|
98
|
+
* streams). Independent of the client-level `reconnect` option.
|
|
99
|
+
*/
|
|
100
|
+
reconnectionOptions?: StreamableHTTPReconnectionOptions;
|
|
101
|
+
/**
|
|
102
|
+
* Resume an existing session instead of starting a new one. When set, the SDK skips the
|
|
103
|
+
* `initialize` handshake on the first connect, so server capabilities, server version and
|
|
104
|
+
* instructions are not available. Only used for the first connect; reconnections always
|
|
105
|
+
* start a new session.
|
|
106
|
+
*/
|
|
107
|
+
sessionId?: string;
|
|
50
108
|
}
|
|
51
109
|
export interface McpClientSseConnection extends McpClientHttpConnectionBase {
|
|
52
110
|
transport: 'sse';
|
|
@@ -57,6 +115,11 @@ export interface McpClientStdioConnection extends McpClientConnectionBase {
|
|
|
57
115
|
args?: string[];
|
|
58
116
|
env?: Record<string, string>;
|
|
59
117
|
cwd?: string;
|
|
118
|
+
/**
|
|
119
|
+
* How the child process's stderr is handled. The SDK default is `'inherit'`. Use `'pipe'` to
|
|
120
|
+
* read it from the transport's `stderr` stream, or `'ignore'` to discard it.
|
|
121
|
+
*/
|
|
122
|
+
stderr?: StdioServerParameters['stderr'];
|
|
60
123
|
}
|
|
61
124
|
export type McpClientConnection = McpClientStreamableHttpConnection | McpClientSseConnection | McpClientStdioConnection;
|
|
62
125
|
export interface McpClientModuleOptions {
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
2
2
|
import type { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol.js';
|
|
3
3
|
import type { CallToolRequest, CompleteRequest, GetPromptRequest, ListPromptsRequest, ListResourceTemplatesRequest, ListResourcesRequest, ListToolsRequest, LoggingLevel, Prompt, ReadResourceRequest, Resource, ResourceTemplate, SubscribeRequest, Tool, UnsubscribeRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
4
|
-
import type { McpClientConnection, McpElicitationHandler, McpRootsHandler, McpSamplingHandler } from './interfaces/client-options.interface';
|
|
4
|
+
import type { McpClientConnection, McpElicitationHandler, McpElicitationHandlerOptions, McpRootsHandler, McpSamplingHandler } from './interfaces/client-options.interface';
|
|
5
|
+
type McpNotificationHandler = (notification: {
|
|
6
|
+
method: string;
|
|
7
|
+
params?: Record<string, unknown>;
|
|
8
|
+
}) => void | Promise<void>;
|
|
5
9
|
export declare class McpClient {
|
|
6
10
|
readonly name: string;
|
|
7
11
|
private readonly connection;
|
|
@@ -11,15 +15,33 @@ export declare class McpClient {
|
|
|
11
15
|
private connected;
|
|
12
16
|
private reconnectAttempts;
|
|
13
17
|
private reconnecting;
|
|
18
|
+
/** Set by `disconnect()`; stops reconnection and suppresses transport error handling. */
|
|
19
|
+
private closing;
|
|
20
|
+
/** Incremented by every `disconnect()`, so a reconnect loop started earlier can detect it. */
|
|
21
|
+
private lifecycle;
|
|
22
|
+
/** Whether a transport has been created at least once (`sessionId` only applies to the first). */
|
|
23
|
+
private transportCreated;
|
|
14
24
|
private readonly _notificationHandlerStore;
|
|
15
|
-
/**
|
|
16
|
-
private
|
|
25
|
+
/** URIs subscribed through `subscribeResource`, replayed after a reconnect. */
|
|
26
|
+
private readonly _subscriptions;
|
|
27
|
+
/** Capabilities passed by the user in the connection options. */
|
|
28
|
+
private readonly _userCapabilities;
|
|
29
|
+
/** Capabilities implied by registered handlers (sampling, elicitation, roots). */
|
|
30
|
+
private _handlerCapabilities;
|
|
17
31
|
private _samplingHandler?;
|
|
18
32
|
private _elicitationHandler?;
|
|
19
33
|
private _rootsHandler?;
|
|
20
34
|
constructor(name: string, connection: McpClientConnection);
|
|
35
|
+
/** Capabilities advertised on the next handshake: handler defaults, overridden by user values. */
|
|
36
|
+
private get _declaredCapabilities();
|
|
37
|
+
private _clientInfo;
|
|
21
38
|
private _createClient;
|
|
22
39
|
connect(): Promise<void>;
|
|
40
|
+
/**
|
|
41
|
+
* Close the connection. For Streamable HTTP, the session is ended first with an HTTP DELETE
|
|
42
|
+
* (errors, including a 405 from servers that do not support it, are ignored). Stops any
|
|
43
|
+
* reconnection in progress and forgets tracked resource subscriptions.
|
|
44
|
+
*/
|
|
23
45
|
disconnect(): Promise<void>;
|
|
24
46
|
isConnected(): boolean;
|
|
25
47
|
getClient(): Client;
|
|
@@ -79,6 +101,7 @@ export declare class McpClient {
|
|
|
79
101
|
type: "resource_link";
|
|
80
102
|
description?: string | undefined;
|
|
81
103
|
mimeType?: string | undefined;
|
|
104
|
+
size?: number | undefined;
|
|
82
105
|
annotations?: {
|
|
83
106
|
audience?: ("user" | "assistant")[] | undefined;
|
|
84
107
|
priority?: number | undefined;
|
|
@@ -188,6 +211,7 @@ export declare class McpClient {
|
|
|
188
211
|
name: string;
|
|
189
212
|
description?: string | undefined;
|
|
190
213
|
mimeType?: string | undefined;
|
|
214
|
+
size?: number | undefined;
|
|
191
215
|
annotations?: {
|
|
192
216
|
audience?: ("user" | "assistant")[] | undefined;
|
|
193
217
|
priority?: number | undefined;
|
|
@@ -303,6 +327,7 @@ export declare class McpClient {
|
|
|
303
327
|
type: "resource_link";
|
|
304
328
|
description?: string | undefined;
|
|
305
329
|
mimeType?: string | undefined;
|
|
330
|
+
size?: number | undefined;
|
|
306
331
|
annotations?: {
|
|
307
332
|
audience?: ("user" | "assistant")[] | undefined;
|
|
308
333
|
priority?: number | undefined;
|
|
@@ -372,6 +397,10 @@ export declare class McpClient {
|
|
|
372
397
|
} | undefined;
|
|
373
398
|
} | undefined;
|
|
374
399
|
}>;
|
|
400
|
+
/**
|
|
401
|
+
* Subscribe to updates for a resource. Successful subscriptions are remembered and
|
|
402
|
+
* re-sent after the client reconnects.
|
|
403
|
+
*/
|
|
375
404
|
subscribeResource(params: SubscribeRequest['params'], options?: RequestOptions): Promise<{
|
|
376
405
|
_meta?: {
|
|
377
406
|
[x: string]: unknown;
|
|
@@ -381,6 +410,10 @@ export declare class McpClient {
|
|
|
381
410
|
} | undefined;
|
|
382
411
|
} | undefined;
|
|
383
412
|
}>;
|
|
413
|
+
/**
|
|
414
|
+
* Unsubscribe from a resource. The URI is always dropped from the set replayed on reconnect,
|
|
415
|
+
* even if the request itself fails.
|
|
416
|
+
*/
|
|
384
417
|
unsubscribeResource(params: UnsubscribeRequest['params'], options?: RequestOptions): Promise<{
|
|
385
418
|
_meta?: {
|
|
386
419
|
[x: string]: unknown;
|
|
@@ -424,21 +457,22 @@ export declare class McpClient {
|
|
|
424
457
|
setSamplingHandler(handler: McpSamplingHandler): void;
|
|
425
458
|
/**
|
|
426
459
|
* Register a handler for server→client `elicitation/create` requests.
|
|
427
|
-
* Automatically declares the `elicitation` capability
|
|
460
|
+
* Automatically declares the `elicitation` capability: form mode only by default, or the
|
|
461
|
+
* modes listed in `options.modes` (e.g. `['form', 'url']` to also accept URL-mode requests).
|
|
428
462
|
*/
|
|
429
|
-
setElicitationHandler(handler: McpElicitationHandler): void;
|
|
463
|
+
setElicitationHandler(handler: McpElicitationHandler, options?: McpElicitationHandlerOptions): void;
|
|
430
464
|
/**
|
|
431
465
|
* Register a handler for server→client `roots/list` requests.
|
|
432
466
|
* Automatically declares the `roots` capability with `listChanged: true`.
|
|
433
467
|
*/
|
|
434
468
|
setRootsHandler(handler: McpRootsHandler): void;
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
469
|
+
/**
|
|
470
|
+
* Register a handler for a server notification method. Several handlers can be registered for
|
|
471
|
+
* the same method; they run in registration order, each isolated from the others' errors.
|
|
472
|
+
* Handlers the SDK installs itself (e.g. for `notifications/progress` and
|
|
473
|
+
* `notifications/cancelled`) keep running before them. Handlers survive reconnects.
|
|
474
|
+
*/
|
|
475
|
+
onNotification(method: string, handler: McpNotificationHandler): void;
|
|
442
476
|
getServerCapabilities(): {
|
|
443
477
|
experimental?: {
|
|
444
478
|
[x: string]: object;
|
|
@@ -467,6 +501,9 @@ export declare class McpClient {
|
|
|
467
501
|
} | undefined;
|
|
468
502
|
} | undefined;
|
|
469
503
|
} | undefined;
|
|
504
|
+
extensions?: {
|
|
505
|
+
[x: string]: object;
|
|
506
|
+
} | undefined;
|
|
470
507
|
} | undefined;
|
|
471
508
|
getServerVersion(): {
|
|
472
509
|
version: string;
|
|
@@ -482,9 +519,40 @@ export declare class McpClient {
|
|
|
482
519
|
title?: string | undefined;
|
|
483
520
|
} | undefined;
|
|
484
521
|
getInstructions(): string | undefined;
|
|
522
|
+
/**
|
|
523
|
+
* Record a handler-implied capability and, while not connected, register the resulting
|
|
524
|
+
* capability on the current SDK client. User-supplied values for the same key win.
|
|
525
|
+
*/
|
|
526
|
+
private _declareCapability;
|
|
527
|
+
private _applySamplingHandler;
|
|
528
|
+
private _applyElicitationHandler;
|
|
529
|
+
private _applyRootsHandler;
|
|
530
|
+
private _applyRequestHandlers;
|
|
531
|
+
/**
|
|
532
|
+
* The SDK only exposes `setNotificationHandler` with a schema carrying a literal method, so the
|
|
533
|
+
* dispatcher is installed in its handler map directly. The handler already there (if any) is
|
|
534
|
+
* kept and called first.
|
|
535
|
+
*/
|
|
536
|
+
private _sdkNotificationHandlers;
|
|
537
|
+
private _installNotificationDispatcher;
|
|
538
|
+
private _installNotificationDispatchers;
|
|
539
|
+
private _warnTruncated;
|
|
540
|
+
private _connectOptions;
|
|
541
|
+
/** Create a transport; a configured `sessionId` is only used for the very first one. */
|
|
542
|
+
private _createTransport;
|
|
543
|
+
private _bindTransport;
|
|
544
|
+
private _handleTransportError;
|
|
545
|
+
private _terminateSession;
|
|
546
|
+
private _replaySubscriptions;
|
|
485
547
|
private assertConnected;
|
|
486
548
|
private handleDisconnect;
|
|
549
|
+
/** Whether the reconnect loop started in `lifecycle` must stop. */
|
|
550
|
+
private _reconnectCancelled;
|
|
487
551
|
private attemptReconnect;
|
|
552
|
+
/** One reconnection attempt with a fresh SDK client and transport; throws if it fails. */
|
|
553
|
+
private _reconnectOnce;
|
|
554
|
+
private _closeQuietly;
|
|
488
555
|
private sleep;
|
|
489
556
|
}
|
|
557
|
+
export {};
|
|
490
558
|
//# sourceMappingURL=mcp-client.service.d.ts.map
|
|
@@ -2,10 +2,44 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.McpClient = void 0;
|
|
4
4
|
const index_js_1 = require("@modelcontextprotocol/sdk/client/index.js");
|
|
5
|
+
const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
|
|
5
6
|
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
|
|
6
7
|
const common_1 = require("@nest-mcp/common");
|
|
7
8
|
const common_2 = require("@nestjs/common");
|
|
8
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
|
+
}
|
|
9
43
|
class McpClient {
|
|
10
44
|
name;
|
|
11
45
|
connection;
|
|
@@ -15,9 +49,19 @@ class McpClient {
|
|
|
15
49
|
connected = false;
|
|
16
50
|
reconnectAttempts = 0;
|
|
17
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;
|
|
18
58
|
_notificationHandlerStore = new Map();
|
|
19
|
-
/**
|
|
20
|
-
|
|
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 = {};
|
|
21
65
|
_samplingHandler;
|
|
22
66
|
_elicitationHandler;
|
|
23
67
|
_rootsHandler;
|
|
@@ -25,47 +69,70 @@ class McpClient {
|
|
|
25
69
|
this.name = name;
|
|
26
70
|
this.connection = connection;
|
|
27
71
|
this.logger = new common_2.Logger(`McpClient[${name}]`);
|
|
28
|
-
this.
|
|
72
|
+
this._userCapabilities = connection.capabilities ?? {};
|
|
29
73
|
this.client = this._createClient();
|
|
30
74
|
if (connection.samplingHandler)
|
|
31
75
|
this.setSamplingHandler(connection.samplingHandler);
|
|
32
|
-
if (connection.elicitationHandler)
|
|
33
|
-
this.setElicitationHandler(connection.elicitationHandler
|
|
76
|
+
if (connection.elicitationHandler) {
|
|
77
|
+
this.setElicitationHandler(connection.elicitationHandler, {
|
|
78
|
+
modes: connection.elicitationModes,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
34
81
|
if (connection.rootsHandler)
|
|
35
82
|
this.setRootsHandler(connection.rootsHandler);
|
|
36
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
|
+
}
|
|
37
96
|
_createClient() {
|
|
38
|
-
return new index_js_1.Client(
|
|
97
|
+
return new index_js_1.Client(this._clientInfo(), { capabilities: this._declaredCapabilities });
|
|
39
98
|
}
|
|
40
99
|
async connect() {
|
|
41
100
|
if (this.connected)
|
|
42
101
|
return;
|
|
43
|
-
this.
|
|
44
|
-
|
|
45
|
-
this.transport
|
|
102
|
+
this.closing = false;
|
|
103
|
+
const transport = this._createTransport();
|
|
104
|
+
this.transport = transport;
|
|
105
|
+
this._bindTransport(transport);
|
|
46
106
|
try {
|
|
47
|
-
await this.client.connect(this.
|
|
107
|
+
await this.client.connect(transport, this._connectOptions());
|
|
48
108
|
this.connected = true;
|
|
49
|
-
this.
|
|
109
|
+
this._installNotificationDispatchers();
|
|
50
110
|
this.reconnectAttempts = 0;
|
|
51
111
|
this.logger.log(`Connected to MCP server "${this.name}"`);
|
|
112
|
+
await this._replaySubscriptions();
|
|
52
113
|
}
|
|
53
114
|
catch (err) {
|
|
54
|
-
this.logger.error(`Failed to connect to "${this.name}": ${
|
|
115
|
+
this.logger.error(`Failed to connect to "${this.name}": ${errorMessage(err)}`);
|
|
55
116
|
throw err;
|
|
56
117
|
}
|
|
57
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
|
+
*/
|
|
58
124
|
async disconnect() {
|
|
125
|
+
this.closing = true;
|
|
126
|
+
this.lifecycle++;
|
|
59
127
|
this.connected = false;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
}
|
|
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);
|
|
69
136
|
}
|
|
70
137
|
isConnected() {
|
|
71
138
|
return this.connected;
|
|
@@ -106,14 +173,14 @@ class McpClient {
|
|
|
106
173
|
return (0, common_1.drainAllPages)(async (cursor) => {
|
|
107
174
|
const result = await this.client.listTools(cursor ? { cursor } : undefined, options);
|
|
108
175
|
return { data: (result.tools ?? []), nextCursor: result.nextCursor };
|
|
109
|
-
});
|
|
176
|
+
}, { onTruncated: this._warnTruncated('tools') });
|
|
110
177
|
}
|
|
111
178
|
async listAllResources(options) {
|
|
112
179
|
this.assertConnected();
|
|
113
180
|
return (0, common_1.drainAllPages)(async (cursor) => {
|
|
114
181
|
const result = await this.client.listResources(cursor ? { cursor } : undefined, options);
|
|
115
182
|
return { data: (result.resources ?? []), nextCursor: result.nextCursor };
|
|
116
|
-
});
|
|
183
|
+
}, { onTruncated: this._warnTruncated('resources') });
|
|
117
184
|
}
|
|
118
185
|
async listAllResourceTemplates(options) {
|
|
119
186
|
this.assertConnected();
|
|
@@ -123,24 +190,35 @@ class McpClient {
|
|
|
123
190
|
data: (result.resourceTemplates ?? []),
|
|
124
191
|
nextCursor: result.nextCursor,
|
|
125
192
|
};
|
|
126
|
-
});
|
|
193
|
+
}, { onTruncated: this._warnTruncated('resource templates') });
|
|
127
194
|
}
|
|
128
195
|
async listAllPrompts(options) {
|
|
129
196
|
this.assertConnected();
|
|
130
197
|
return (0, common_1.drainAllPages)(async (cursor) => {
|
|
131
198
|
const result = await this.client.listPrompts(cursor ? { cursor } : undefined, options);
|
|
132
199
|
return { data: (result.prompts ?? []), nextCursor: result.nextCursor };
|
|
133
|
-
});
|
|
200
|
+
}, { onTruncated: this._warnTruncated('prompts') });
|
|
134
201
|
}
|
|
135
202
|
async ping(options) {
|
|
136
203
|
this.assertConnected();
|
|
137
204
|
return this.client.ping(options);
|
|
138
205
|
}
|
|
206
|
+
/**
|
|
207
|
+
* Subscribe to updates for a resource. Successful subscriptions are remembered and
|
|
208
|
+
* re-sent after the client reconnects.
|
|
209
|
+
*/
|
|
139
210
|
async subscribeResource(params, options) {
|
|
140
211
|
this.assertConnected();
|
|
141
|
-
|
|
212
|
+
const result = await this.client.subscribeResource(params, options);
|
|
213
|
+
this._subscriptions.add(params.uri);
|
|
214
|
+
return result;
|
|
142
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
|
+
*/
|
|
143
220
|
async unsubscribeResource(params, options) {
|
|
221
|
+
this._subscriptions.delete(params.uri);
|
|
144
222
|
this.assertConnected();
|
|
145
223
|
return this.client.unsubscribeResource(params, options);
|
|
146
224
|
}
|
|
@@ -163,23 +241,22 @@ class McpClient {
|
|
|
163
241
|
*/
|
|
164
242
|
setSamplingHandler(handler) {
|
|
165
243
|
this._samplingHandler = handler;
|
|
166
|
-
this.
|
|
167
|
-
|
|
168
|
-
this.client.registerCapabilities({ sampling: {} });
|
|
169
|
-
}
|
|
170
|
-
this.client.setRequestHandler(types_js_1.CreateMessageRequestSchema, (req) => handler(req));
|
|
244
|
+
this._declareCapability('sampling', {});
|
|
245
|
+
this._applySamplingHandler(handler);
|
|
171
246
|
}
|
|
172
247
|
/**
|
|
173
248
|
* Register a handler for server→client `elicitation/create` requests.
|
|
174
|
-
* Automatically declares the `elicitation` capability
|
|
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).
|
|
175
251
|
*/
|
|
176
|
-
setElicitationHandler(handler) {
|
|
252
|
+
setElicitationHandler(handler, options) {
|
|
177
253
|
this._elicitationHandler = handler;
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
this.
|
|
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);
|
|
183
260
|
}
|
|
184
261
|
/**
|
|
185
262
|
* Register a handler for server→client `roots/list` requests.
|
|
@@ -187,47 +264,24 @@ class McpClient {
|
|
|
187
264
|
*/
|
|
188
265
|
setRootsHandler(handler) {
|
|
189
266
|
this._rootsHandler = handler;
|
|
190
|
-
this.
|
|
191
|
-
|
|
192
|
-
roots: { listChanged: true },
|
|
193
|
-
};
|
|
194
|
-
if (!this.connected) {
|
|
195
|
-
this.client.registerCapabilities({ roots: { listChanged: true } });
|
|
196
|
-
}
|
|
197
|
-
this.client.setRequestHandler(types_js_1.ListRootsRequestSchema, () => handler());
|
|
267
|
+
this._declareCapability('roots', { listChanged: true });
|
|
268
|
+
this._applyRootsHandler(handler);
|
|
198
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
|
+
*/
|
|
199
276
|
onNotification(method, handler) {
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
// which is not practical for arbitrary notification method strings.
|
|
204
|
-
const wrapped = (n) => Promise.resolve(handler(n));
|
|
205
|
-
this._notificationHandlerStore.set(method, wrapped);
|
|
206
|
-
if (this.connected) {
|
|
207
|
-
this._applyNotificationHandler(method, wrapped);
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
_applyNotificationHandler(method, wrapped) {
|
|
211
|
-
this.client._notificationHandlers.set(method, wrapped);
|
|
212
|
-
}
|
|
213
|
-
_reapplyNotificationHandlers() {
|
|
214
|
-
for (const [method, wrapped] of this._notificationHandlerStore) {
|
|
215
|
-
this._applyNotificationHandler(method, wrapped);
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
_reapplyRequestHandlers() {
|
|
219
|
-
if (this._samplingHandler) {
|
|
220
|
-
const h = this._samplingHandler;
|
|
221
|
-
this.client.setRequestHandler(types_js_1.CreateMessageRequestSchema, (req) => h(req));
|
|
277
|
+
const handlers = this._notificationHandlerStore.get(method);
|
|
278
|
+
if (handlers) {
|
|
279
|
+
handlers.push(handler);
|
|
222
280
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
this.client.setRequestHandler(types_js_1.ElicitRequestSchema, (req) => h(req.params));
|
|
226
|
-
}
|
|
227
|
-
if (this._rootsHandler) {
|
|
228
|
-
const h = this._rootsHandler;
|
|
229
|
-
this.client.setRequestHandler(types_js_1.ListRootsRequestSchema, () => h());
|
|
281
|
+
else {
|
|
282
|
+
this._notificationHandlerStore.set(method, [handler]);
|
|
230
283
|
}
|
|
284
|
+
this._installNotificationDispatcher(method);
|
|
231
285
|
}
|
|
232
286
|
getServerCapabilities() {
|
|
233
287
|
return this.client.getServerCapabilities();
|
|
@@ -238,6 +292,158 @@ class McpClient {
|
|
|
238
292
|
getInstructions() {
|
|
239
293
|
return this.client.getInstructions();
|
|
240
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
|
+
}
|
|
241
447
|
assertConnected() {
|
|
242
448
|
if (!this.connected) {
|
|
243
449
|
throw new Error(`McpClient "${this.name}" is not connected`);
|
|
@@ -247,42 +453,76 @@ class McpClient {
|
|
|
247
453
|
if (!this.connected)
|
|
248
454
|
return;
|
|
249
455
|
this.connected = false;
|
|
456
|
+
if (this.closing)
|
|
457
|
+
return;
|
|
250
458
|
this.logger.warn(`Connection lost to "${this.name}"`);
|
|
251
459
|
const reconnect = this.connection.reconnect;
|
|
252
460
|
if (reconnect) {
|
|
253
461
|
await this.attemptReconnect(reconnect);
|
|
254
462
|
}
|
|
255
463
|
}
|
|
464
|
+
/** Whether the reconnect loop started in `lifecycle` must stop. */
|
|
465
|
+
_reconnectCancelled(lifecycle) {
|
|
466
|
+
return this.closing || lifecycle !== this.lifecycle;
|
|
467
|
+
}
|
|
256
468
|
async attemptReconnect(options) {
|
|
257
469
|
if (this.reconnecting)
|
|
258
470
|
return;
|
|
259
471
|
this.reconnecting = true;
|
|
472
|
+
const lifecycle = this.lifecycle;
|
|
260
473
|
const maxAttempts = options.maxAttempts ?? 5;
|
|
261
474
|
const delay = options.delay ?? 1000;
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
this.
|
|
268
|
-
this.
|
|
269
|
-
this.
|
|
270
|
-
|
|
271
|
-
this.
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
catch (err) {
|
|
281
|
-
this.logger.warn(`Reconnection attempt ${this.reconnectAttempts} failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
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
|
+
}
|
|
282
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
|
|
283
525
|
}
|
|
284
|
-
this.reconnecting = false;
|
|
285
|
-
this.logger.error(`Failed to reconnect to "${this.name}" after ${maxAttempts} attempts`);
|
|
286
526
|
}
|
|
287
527
|
sleep(ms) {
|
|
288
528
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
2
2
|
import type { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol.js';
|
|
3
3
|
import type { CallToolRequest, CallToolResult, CompleteRequest, CompleteResult, GetPromptRequest, GetPromptResult, Implementation, ListPromptsRequest, ListPromptsResult, ListResourceTemplatesRequest, ListResourceTemplatesResult, ListResourcesRequest, ListResourcesResult, ListToolsRequest, ListToolsResult, LoggingLevel, Prompt, ReadResourceRequest, ReadResourceResult, Resource, ResourceTemplate, ServerCapabilities, SubscribeRequest, Tool, UnsubscribeRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
4
|
-
import type { McpElicitationHandler, McpRootsHandler, McpSamplingHandler } from '../interfaces/client-options.interface';
|
|
4
|
+
import type { McpElicitationHandler, McpElicitationHandlerOptions, McpRootsHandler, McpSamplingHandler } from '../interfaces/client-options.interface';
|
|
5
5
|
type PingResult = Awaited<ReturnType<Client['ping']>>;
|
|
6
6
|
export declare class MockMcpClient {
|
|
7
7
|
readonly name: string;
|
|
@@ -41,7 +41,7 @@ export declare class MockMcpClient {
|
|
|
41
41
|
complete(_params: CompleteRequest['params'], _options?: RequestOptions): Promise<CompleteResult>;
|
|
42
42
|
sendRootsListChanged(): Promise<void>;
|
|
43
43
|
setSamplingHandler(_handler: McpSamplingHandler): void;
|
|
44
|
-
setElicitationHandler(_handler: McpElicitationHandler): void;
|
|
44
|
+
setElicitationHandler(_handler: McpElicitationHandler, _options?: McpElicitationHandlerOptions): void;
|
|
45
45
|
setRootsHandler(_handler: McpRootsHandler): void;
|
|
46
46
|
onNotification(method: string, handler: (notification: {
|
|
47
47
|
method: string;
|
|
@@ -83,7 +83,7 @@ class MockMcpClient {
|
|
|
83
83
|
setSamplingHandler(_handler) {
|
|
84
84
|
// no-op in mock — handler not invoked
|
|
85
85
|
}
|
|
86
|
-
setElicitationHandler(_handler) {
|
|
86
|
+
setElicitationHandler(_handler, _options) {
|
|
87
87
|
// no-op in mock — handler not invoked
|
|
88
88
|
}
|
|
89
89
|
setRootsHandler(_handler) {
|
|
@@ -9,6 +9,7 @@ function createSseTransport(connection) {
|
|
|
9
9
|
return new sse_js_1.SSEClientTransport(url, {
|
|
10
10
|
requestInit,
|
|
11
11
|
authProvider: connection.authProvider,
|
|
12
|
+
...(connection.fetch && { fetch: connection.fetch }),
|
|
12
13
|
});
|
|
13
14
|
}
|
|
14
15
|
//# sourceMappingURL=sse-client.transport.js.map
|
|
@@ -9,6 +9,9 @@ function createStreamableHttpTransport(connection) {
|
|
|
9
9
|
return new streamableHttp_js_1.StreamableHTTPClientTransport(url, {
|
|
10
10
|
requestInit,
|
|
11
11
|
authProvider: connection.authProvider,
|
|
12
|
+
...(connection.fetch && { fetch: connection.fetch }),
|
|
13
|
+
...(connection.reconnectionOptions && { reconnectionOptions: connection.reconnectionOptions }),
|
|
14
|
+
...(connection.sessionId && { sessionId: connection.sessionId }),
|
|
12
15
|
});
|
|
13
16
|
}
|
|
14
17
|
//# sourceMappingURL=streamable-client.transport.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nest-mcp/client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "NestJS MCP Client - Connect to and consume MCP servers from NestJS",
|
|
5
5
|
"license": "BSD-3-Clause",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -39,18 +39,21 @@
|
|
|
39
39
|
"publishConfig": {
|
|
40
40
|
"access": "public"
|
|
41
41
|
},
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": ">=20.0.0"
|
|
44
|
+
},
|
|
42
45
|
"dependencies": {
|
|
43
|
-
"@nest-mcp/common": "0.
|
|
46
|
+
"@nest-mcp/common": "1.0.0"
|
|
44
47
|
},
|
|
45
48
|
"peerDependencies": {
|
|
46
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
47
|
-
"@nestjs/common": "^10.0.0 || ^11.0.0",
|
|
48
|
-
"@nestjs/core": "^10.0.0 || ^11.0.0",
|
|
49
|
+
"@modelcontextprotocol/sdk": "^1.32.0",
|
|
50
|
+
"@nestjs/common": "^10.0.0 || ^11.0.0 || ^12.0.0",
|
|
51
|
+
"@nestjs/core": "^10.0.0 || ^11.0.0 || ^12.0.0",
|
|
49
52
|
"reflect-metadata": ">=0.1.13",
|
|
50
53
|
"rxjs": "^7.0.0"
|
|
51
54
|
},
|
|
52
55
|
"devDependencies": {
|
|
53
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
56
|
+
"@modelcontextprotocol/sdk": "^1.32.0",
|
|
54
57
|
"@nestjs/common": "^11.0.0",
|
|
55
58
|
"@nestjs/core": "^11.0.0",
|
|
56
59
|
"@nestjs/testing": "^11.0.0",
|