@draht/mcp 2026.11.27 → 2026.12.3
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/client.d.ts +105 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +318 -33
- package/dist/client.js.map +1 -1
- package/dist/config-schema.d.ts +109 -0
- package/dist/config-schema.d.ts.map +1 -0
- package/dist/config-schema.js +105 -0
- package/dist/config-schema.js.map +1 -0
- package/dist/config.d.ts +6 -74
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +9 -2
- package/dist/config.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/oauth/callback.d.ts.map +1 -1
- package/dist/oauth/callback.js +4 -2
- package/dist/oauth/callback.js.map +1 -1
- package/dist/protocol/http-headers.d.ts +31 -0
- package/dist/protocol/http-headers.d.ts.map +1 -0
- package/dist/protocol/http-headers.js +129 -0
- package/dist/protocol/http-headers.js.map +1 -0
- package/dist/protocol/stateless.d.ts +47 -0
- package/dist/protocol/stateless.d.ts.map +1 -0
- package/dist/protocol/stateless.js +102 -0
- package/dist/protocol/stateless.js.map +1 -0
- package/dist/protocol/types.d.ts +33 -0
- package/dist/protocol/types.d.ts.map +1 -1
- package/dist/protocol/types.js +5 -0
- package/dist/protocol/types.js.map +1 -1
- package/dist/transports/streamable-http.d.ts +14 -4
- package/dist/transports/streamable-http.d.ts.map +1 -1
- package/dist/transports/streamable-http.js +81 -26
- package/dist/transports/streamable-http.js.map +1 -1
- package/dist/transports/transport.d.ts +12 -0
- package/dist/transports/transport.d.ts.map +1 -1
- package/dist/transports/transport.js.map +1 -1
- package/package.json +8 -2
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { CallToolResult } from "./protocol/content.ts";
|
|
2
|
-
import { type ClientCapabilities, type Implementation, type InitializeResult, type ListResourcesResult, type ListResourceTemplatesResult, type ProgressNotification, type ReadResourceResult, type Resource, type ResourceTemplate, type Root, type ServerCapabilities, type SupportedProtocolVersion, type Tool } from "./protocol/types.ts";
|
|
2
|
+
import { type ClientCapabilities, type Implementation, type InitializeResult, type ListResourcesResult, type ListResourceTemplatesResult, type LoggingLevel, type McpProtocolMode, type ProgressNotification, type ReadResourceResult, type Resource, type ResourceTemplate, type Root, type ServerCapabilities, type SubscriptionFilter, type SupportedProtocolVersion, type Tool } from "./protocol/types.ts";
|
|
3
3
|
import type { McpTransport } from "./transports/transport.ts";
|
|
4
4
|
type ClientState = "idle" | "connecting" | "connected" | "closed";
|
|
5
5
|
type NotificationListener = (params: unknown) => void;
|
|
@@ -10,14 +10,60 @@ type RequestHandler = (params: unknown, context: {
|
|
|
10
10
|
}) => unknown | Promise<unknown>;
|
|
11
11
|
export interface McpClientOptions extends Implementation {
|
|
12
12
|
capabilities?: ClientCapabilities;
|
|
13
|
+
/** Version the `initialize` handshake asks for. Default: {@link LATEST_PROTOCOL_VERSION}. */
|
|
13
14
|
protocolVersion?: SupportedProtocolVersion;
|
|
15
|
+
/** How the protocol is picked (see {@link McpProtocolMode}). Default: `auto`. */
|
|
16
|
+
protocol?: McpProtocolMode;
|
|
17
|
+
/**
|
|
18
|
+
* Servers on the stateless revision send log messages (`notifications/message`) only for requests
|
|
19
|
+
* that name a level, so every such request names this one. Without it, they send none.
|
|
20
|
+
*/
|
|
21
|
+
logLevel?: LoggingLevel;
|
|
14
22
|
requestTimeoutMs?: number;
|
|
23
|
+
/** Timeout of the request that opens the connection (`initialize` or `server/discover`). Default: `requestTimeoutMs`. */
|
|
24
|
+
connectTimeoutMs?: number;
|
|
15
25
|
roots?: readonly Root[] | (() => readonly Root[] | Promise<readonly Root[]>);
|
|
16
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* Answers a result whose `resultType` an MCP extension defines (`upload_required`, say) and returns the
|
|
29
|
+
* `requestState` to send the request again with. Throwing fails the request without sending it again.
|
|
30
|
+
*/
|
|
31
|
+
export type McpExtensionResultHandler = (
|
|
32
|
+
/** The whole result, including `resultType`, as the server sent it (unchecked). */
|
|
33
|
+
result: Record<string, unknown>, context: {
|
|
34
|
+
signal: AbortSignal;
|
|
35
|
+
}) => Promise<{
|
|
36
|
+
requestState: string;
|
|
37
|
+
}>;
|
|
17
38
|
export interface McpRequestOptions {
|
|
18
39
|
signal?: AbortSignal;
|
|
19
40
|
timeoutMs?: number;
|
|
20
41
|
onProgress?: (progress: ProgressNotification) => void;
|
|
42
|
+
onExtensionResult?: McpExtensionResultHandler;
|
|
43
|
+
}
|
|
44
|
+
/** An open `subscriptions/listen` stream of a server on the stateless revision. */
|
|
45
|
+
export interface McpSubscription {
|
|
46
|
+
/** The notification types the server agreed to send. */
|
|
47
|
+
readonly notifications: SubscriptionFilter;
|
|
48
|
+
/**
|
|
49
|
+
* Settles when the subscription ends: resolves when the server ended it or `close()` was called,
|
|
50
|
+
* rejects when the connection or the stream failed.
|
|
51
|
+
*/
|
|
52
|
+
readonly closed: Promise<void>;
|
|
53
|
+
close(): void;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* `connect()` failed after the server rejected `initialize`: `server/discover` on the same connection
|
|
57
|
+
* failed too. Some stdio servers that only speak the stateless revision exit after rejecting
|
|
58
|
+
* `initialize`, or refuse it on a process that saw `initialize`; a new process connected with
|
|
59
|
+
* `protocol: "2026-07-28"` may still work.
|
|
60
|
+
*/
|
|
61
|
+
export declare class McpInitializeRejectedError extends Error {
|
|
62
|
+
/** The server's answer to `initialize`. */
|
|
63
|
+
readonly rejection: unknown;
|
|
64
|
+
/** Why `server/discover` failed. */
|
|
65
|
+
readonly discoverError: unknown;
|
|
66
|
+
constructor(message: string, rejection: unknown, discoverError: unknown);
|
|
21
67
|
}
|
|
22
68
|
export declare class McpClient {
|
|
23
69
|
readonly options: Readonly<McpClientOptions>;
|
|
@@ -28,6 +74,13 @@ export declare class McpClient {
|
|
|
28
74
|
private serverCapabilitiesValue;
|
|
29
75
|
private instructionsValue;
|
|
30
76
|
private protocolVersionValue;
|
|
77
|
+
/** Whether the connection speaks the stateless revision: every request carries {@link meta}. */
|
|
78
|
+
private stateless;
|
|
79
|
+
private readonly meta;
|
|
80
|
+
/** `Mcp-Param-*` bindings of the tools last listed, for servers on the stateless revision. */
|
|
81
|
+
private toolHeaders;
|
|
82
|
+
/** Open `subscriptions/listen` requests by id. */
|
|
83
|
+
private subscriptions;
|
|
31
84
|
private pending;
|
|
32
85
|
private progressRequests;
|
|
33
86
|
private incoming;
|
|
@@ -42,15 +95,39 @@ export declare class McpClient {
|
|
|
42
95
|
get serverCapabilities(): ServerCapabilities | undefined;
|
|
43
96
|
get instructions(): string | undefined;
|
|
44
97
|
get protocolVersion(): string | undefined;
|
|
98
|
+
/**
|
|
99
|
+
* Connect over `transport`. Resolves to what the server reported about itself; for servers on the
|
|
100
|
+
* stateless revision, a result in the shape of `initialize` built from `server/discover`.
|
|
101
|
+
*/
|
|
45
102
|
connect(transport: McpTransport): Promise<InitializeResult>;
|
|
103
|
+
/**
|
|
104
|
+
* `initialize` first, so servers of every earlier revision see what they always saw. Only a server
|
|
105
|
+
* that rejects it is asked with `server/discover`. When that fails too, the error is an
|
|
106
|
+
* {@link McpInitializeRejectedError} with the rejection's message, or with the message of
|
|
107
|
+
* `server/discover` when the rejection proved a stateless server that is still there. Such a server
|
|
108
|
+
* failing `server/discover` without answering it (sign-in required, say) fails with that error.
|
|
109
|
+
*/
|
|
110
|
+
private initializeOrDiscover;
|
|
111
|
+
private initialize;
|
|
112
|
+
/** Speak the stateless revision: no handshake, `server/discover` tells what the server offers. */
|
|
113
|
+
private discover;
|
|
46
114
|
request<Result = unknown>(method: string, params?: Record<string, unknown>, options?: McpRequestOptions): Promise<Result>;
|
|
47
115
|
notify(method: string, params?: Record<string, unknown>): Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* Answer requests of `method` from the server: requests a legacy server sends, and the input requests
|
|
118
|
+
* of the same method that results of the stateless revision ask for (`roots/list`, say).
|
|
119
|
+
*/
|
|
48
120
|
setRequestHandler(method: string, handler: RequestHandler): () => void;
|
|
49
121
|
onNotification(method: string, listener: NotificationListener): () => void;
|
|
50
122
|
onError(listener: ErrorListener): () => void;
|
|
51
123
|
/** Called once when the connection closes, whether the transport dropped or `close()` was called. */
|
|
52
124
|
onClose(listener: CloseListener): () => void;
|
|
125
|
+
/** Check that the server answers: `ping`, or `server/discover` on the stateless revision, which has no `ping`. */
|
|
53
126
|
ping(options?: McpRequestOptions): Promise<void>;
|
|
127
|
+
/**
|
|
128
|
+
* Every tool, following `nextCursor` through all pages. On the stateless revision over HTTP, tools
|
|
129
|
+
* whose `x-mcp-header` annotations are invalid are left out and reported through `onError`.
|
|
130
|
+
*/
|
|
54
131
|
listTools(options?: McpRequestOptions): Promise<Tool[]>;
|
|
55
132
|
/** Every resource, following `nextCursor` through all pages. */
|
|
56
133
|
listResources(options?: McpRequestOptions): Promise<Resource[]>;
|
|
@@ -64,8 +141,33 @@ export declare class McpClient {
|
|
|
64
141
|
private listPage;
|
|
65
142
|
/** Every item of a paginated list method. */
|
|
66
143
|
private listAll;
|
|
144
|
+
/**
|
|
145
|
+
* Call a tool. On the stateless revision, arguments the tool marks with `x-mcp-header` go into
|
|
146
|
+
* `Mcp-Param-*` headers too; when the server reports that they do not match, the tools are listed
|
|
147
|
+
* again for their current annotations and the call is sent once more.
|
|
148
|
+
*/
|
|
67
149
|
callTool(name: string, args?: Record<string, unknown>, options?: McpRequestOptions): Promise<CallToolResult>;
|
|
150
|
+
/**
|
|
151
|
+
* Open a `subscriptions/listen` stream of a server on the stateless revision, which delivers the
|
|
152
|
+
* notifications `filter` names to `onNotification` listeners. Resolves once the server acknowledged
|
|
153
|
+
* it; servers of earlier revisions send their notifications without one.
|
|
154
|
+
*/
|
|
155
|
+
listen(filter: SubscriptionFilter, options?: {
|
|
156
|
+
signal?: AbortSignal;
|
|
157
|
+
}): Promise<McpSubscription>;
|
|
68
158
|
close(): Promise<void>;
|
|
159
|
+
/**
|
|
160
|
+
* A request on the connection. On the stateless revision, a result that asks for input is answered
|
|
161
|
+
* with the handlers of the input requests' methods, and one of an extension result type with
|
|
162
|
+
* `onExtensionResult`; the request is sent again with the answers until it completes. Every attempt
|
|
163
|
+
* is a new JSON-RPC request.
|
|
164
|
+
*/
|
|
165
|
+
private requestConnected;
|
|
166
|
+
/** The params that answer a result asking for more, which the request is sent again with. */
|
|
167
|
+
private answerResult;
|
|
168
|
+
private answerInputRequests;
|
|
169
|
+
private requestTimeoutMs;
|
|
170
|
+
private connectTimeoutMs;
|
|
69
171
|
private requestInternal;
|
|
70
172
|
private notifyInternal;
|
|
71
173
|
private requireTransport;
|
|
@@ -74,7 +176,9 @@ export declare class McpClient {
|
|
|
74
176
|
private handleRequest;
|
|
75
177
|
private handleNotification;
|
|
76
178
|
private handleProgress;
|
|
179
|
+
/** Servers cancel requests they sent, and on the stateless revision end subscriptions this way. */
|
|
77
180
|
private handleCancelled;
|
|
181
|
+
private subscriptionOf;
|
|
78
182
|
private armTimeout;
|
|
79
183
|
private cancelPending;
|
|
80
184
|
private removePending;
|
package/dist/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AA+B5D,OAAO,EACN,KAAK,kBAAkB,EACvB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EAGrB,KAAK,mBAAmB,EACxB,KAAK,2BAA2B,EAChC,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,KAAK,QAAQ,EACb,KAAK,gB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;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAM3B;IAED;;;;;OAKG;YACW,gBAAgB;IAqB9B,6FAA6F;YAC/E,YAAY;YAkBZ,mBAAmB;IAajC,OAAO,CAAC,gBAAgB;IAIxB,OAAO,CAAC,gBAAgB;YAIV,eAAe;YAsDf,cAAc;IAY5B,OAAO,CAAC,gBAAgB;IAOxB,OAAO,CAAC,aAAa;IAgBrB,OAAO,CAAC,cAAc;YAYR,aAAa;IAgC3B,OAAO,CAAC,kBAAkB;IAc1B,OAAO,CAAC,cAAc;IAatB,mGAAmG;IACnG,OAAO,CAAC,eAAe;IAMvB,OAAO,CAAC,cAAc;IAKtB,OAAO,CAAC,UAAU;IAQlB,OAAO,CAAC,aAAa;IAgBrB,OAAO,CAAC,aAAa;IAQrB,OAAO,CAAC,aAAa;IAOrB,OAAO,CAAC,oBAAoB;IAI5B,0GAA0G;IAC1G,OAAO,CAAC,UAAU;IAgBlB,OAAO,CAAC,SAAS;IAKjB,OAAO,CAAC,yBAAyB;CAGjC"}
|
package/dist/client.js
CHANGED
|
@@ -1,7 +1,40 @@
|
|
|
1
|
+
import { toolHeaderBindings, toolParamHeaders } from "./protocol/http-headers.js";
|
|
1
2
|
import { isJsonRpcId, isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse, isObject, JSON_RPC_ERROR_CODES, McpAbortError, McpConnectionClosedError, McpError, McpTimeoutError, normalizeOwnRequestId, toError, } from "./protocol/jsonrpc.js";
|
|
2
|
-
import {
|
|
3
|
+
import { HEADER_MISMATCH_ERROR_CODE, readStatelessResult, readSubscriptionFilter, STATELESS_ERROR_CODES, subscriptionIdOf, validateDiscoverResult, withStatelessMeta, } from "./protocol/stateless.js";
|
|
4
|
+
import { LATEST_PROTOCOL_VERSION, STATELESS_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, } from "./protocol/types.js";
|
|
5
|
+
import { jsonRpcErrorIn, McpHttpError } from "./transports/streamable-http.js";
|
|
3
6
|
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
|
|
4
7
|
const MAX_LIST_PAGES = 1_000;
|
|
8
|
+
/**
|
|
9
|
+
* Bounds `server/discover` after a rejected `initialize`. The server already answered once, so a
|
|
10
|
+
* stateless server answers quickly; a legacy server that ignores the request must not hold up the error.
|
|
11
|
+
*/
|
|
12
|
+
const DISCOVER_AFTER_INITIALIZE_TIMEOUT_MS = 10_000;
|
|
13
|
+
/**
|
|
14
|
+
* Rounds of input a server may ask for before one request completes. Servers may ask again until they
|
|
15
|
+
* have what they need; this bounds a server that never does.
|
|
16
|
+
*/
|
|
17
|
+
const MAX_INPUT_ROUNDS = 16;
|
|
18
|
+
/** Methods whose results may ask for input in MCP 2026-07-28 (multi round-trip requests). */
|
|
19
|
+
const INPUT_METHODS = new Set(["tools/call", "resources/read", "prompts/get"]);
|
|
20
|
+
/**
|
|
21
|
+
* `connect()` failed after the server rejected `initialize`: `server/discover` on the same connection
|
|
22
|
+
* failed too. Some stdio servers that only speak the stateless revision exit after rejecting
|
|
23
|
+
* `initialize`, or refuse it on a process that saw `initialize`; a new process connected with
|
|
24
|
+
* `protocol: "2026-07-28"` may still work.
|
|
25
|
+
*/
|
|
26
|
+
export class McpInitializeRejectedError extends Error {
|
|
27
|
+
/** The server's answer to `initialize`. */
|
|
28
|
+
rejection;
|
|
29
|
+
/** Why `server/discover` failed. */
|
|
30
|
+
discoverError;
|
|
31
|
+
constructor(message, rejection, discoverError) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "McpInitializeRejectedError";
|
|
34
|
+
this.rejection = rejection;
|
|
35
|
+
this.discoverError = discoverError;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
5
38
|
function validateInitializeResult(value) {
|
|
6
39
|
if (!isObject(value) ||
|
|
7
40
|
typeof value.protocolVersion !== "string" ||
|
|
@@ -67,6 +100,30 @@ function validateCallToolResult(value) {
|
|
|
67
100
|
}
|
|
68
101
|
return (value.content === undefined ? { ...value, content: [] } : value);
|
|
69
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* What a failed `initialize` tells about the server. Servers that only speak the stateless revision
|
|
105
|
+
* reject it with a JSON-RPC error, over HTTP with a 400: `stateless` when the error has a code only that
|
|
106
|
+
* revision uses, `unknown` for other such rejections, and undefined for failures that are no answer
|
|
107
|
+
* (timeouts, closed connections, authorization).
|
|
108
|
+
*/
|
|
109
|
+
function initializeRejection(error) {
|
|
110
|
+
const code = error instanceof McpError
|
|
111
|
+
? error.code
|
|
112
|
+
: error instanceof McpHttpError && error.status === 400
|
|
113
|
+
? jsonRpcErrorIn(error.body)?.code
|
|
114
|
+
: null;
|
|
115
|
+
if (code === null)
|
|
116
|
+
return undefined;
|
|
117
|
+
return code !== undefined && STATELESS_ERROR_CODES.includes(code) ? "stateless" : "unknown";
|
|
118
|
+
}
|
|
119
|
+
/** The connection closed under a request: the transport closed, or the stdio server was gone when written to. */
|
|
120
|
+
function isConnectionLost(error) {
|
|
121
|
+
// Node's write errors are the trust boundary here: `code` is all they carry.
|
|
122
|
+
return (error instanceof McpConnectionClosedError || (error instanceof Error && "code" in error && error.code === "EPIPE"));
|
|
123
|
+
}
|
|
124
|
+
/** Thrown for an `initialize` answered with the stateless revision, which has no handshake. */
|
|
125
|
+
class StatelessInitializeError extends Error {
|
|
126
|
+
}
|
|
70
127
|
export class McpClient {
|
|
71
128
|
options;
|
|
72
129
|
state = "idle";
|
|
@@ -76,6 +133,13 @@ export class McpClient {
|
|
|
76
133
|
serverCapabilitiesValue;
|
|
77
134
|
instructionsValue;
|
|
78
135
|
protocolVersionValue;
|
|
136
|
+
/** Whether the connection speaks the stateless revision: every request carries {@link meta}. */
|
|
137
|
+
stateless = false;
|
|
138
|
+
meta;
|
|
139
|
+
/** `Mcp-Param-*` bindings of the tools last listed, for servers on the stateless revision. */
|
|
140
|
+
toolHeaders = new Map();
|
|
141
|
+
/** Open `subscriptions/listen` requests by id. */
|
|
142
|
+
subscriptions = new Map();
|
|
79
143
|
pending = new Map();
|
|
80
144
|
progressRequests = new Map();
|
|
81
145
|
incoming = new Map();
|
|
@@ -86,6 +150,19 @@ export class McpClient {
|
|
|
86
150
|
disposers = [];
|
|
87
151
|
constructor(options) {
|
|
88
152
|
this.options = Object.freeze({ ...options });
|
|
153
|
+
const capabilities = { ...options.capabilities };
|
|
154
|
+
if (options.roots && capabilities.roots === undefined)
|
|
155
|
+
capabilities.roots = {};
|
|
156
|
+
this.meta = {
|
|
157
|
+
protocolVersion: STATELESS_PROTOCOL_VERSION,
|
|
158
|
+
clientInfo: {
|
|
159
|
+
name: options.name,
|
|
160
|
+
version: options.version,
|
|
161
|
+
...(options.title === undefined ? {} : { title: options.title }),
|
|
162
|
+
},
|
|
163
|
+
clientCapabilities: capabilities,
|
|
164
|
+
logLevel: options.logLevel,
|
|
165
|
+
};
|
|
89
166
|
this.requestHandlers.set("ping", () => ({}));
|
|
90
167
|
const roots = options.roots;
|
|
91
168
|
if (roots) {
|
|
@@ -109,6 +186,10 @@ export class McpClient {
|
|
|
109
186
|
get protocolVersion() {
|
|
110
187
|
return this.protocolVersionValue;
|
|
111
188
|
}
|
|
189
|
+
/**
|
|
190
|
+
* Connect over `transport`. Resolves to what the server reported about itself; for servers on the
|
|
191
|
+
* stateless revision, a result in the shape of `initialize` built from `server/discover`.
|
|
192
|
+
*/
|
|
112
193
|
async connect(transport) {
|
|
113
194
|
if (this.state !== "idle")
|
|
114
195
|
throw new Error(`Cannot connect MCP client in ${this.state} state`);
|
|
@@ -122,27 +203,9 @@ export class McpClient {
|
|
|
122
203
|
];
|
|
123
204
|
try {
|
|
124
205
|
await transport.start();
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
const result = validateInitializeResult(await this.requestInternal("initialize", {
|
|
129
|
-
protocolVersion: this.options.protocolVersion ?? LATEST_PROTOCOL_VERSION,
|
|
130
|
-
capabilities,
|
|
131
|
-
clientInfo: {
|
|
132
|
-
name: this.options.name,
|
|
133
|
-
version: this.options.version,
|
|
134
|
-
...(this.options.title === undefined ? {} : { title: this.options.title }),
|
|
135
|
-
},
|
|
136
|
-
}, {}, true));
|
|
137
|
-
if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
|
|
138
|
-
throw new Error(`MCP server selected unsupported protocol version ${result.protocolVersion}`);
|
|
139
|
-
}
|
|
140
|
-
this.protocolVersionValue = result.protocolVersion;
|
|
141
|
-
this.serverInfoValue = result.serverInfo;
|
|
142
|
-
this.serverCapabilitiesValue = result.capabilities;
|
|
143
|
-
this.instructionsValue = result.instructions;
|
|
144
|
-
transport.setProtocolVersion?.(result.protocolVersion);
|
|
145
|
-
await this.notifyInternal("notifications/initialized", undefined, true);
|
|
206
|
+
const result = this.options.protocol === STATELESS_PROTOCOL_VERSION
|
|
207
|
+
? await this.discover(transport, this.connectTimeoutMs())
|
|
208
|
+
: await this.initializeOrDiscover(transport);
|
|
146
209
|
this.state = "connected";
|
|
147
210
|
return result;
|
|
148
211
|
}
|
|
@@ -151,12 +214,85 @@ export class McpClient {
|
|
|
151
214
|
throw error;
|
|
152
215
|
}
|
|
153
216
|
}
|
|
217
|
+
/**
|
|
218
|
+
* `initialize` first, so servers of every earlier revision see what they always saw. Only a server
|
|
219
|
+
* that rejects it is asked with `server/discover`. When that fails too, the error is an
|
|
220
|
+
* {@link McpInitializeRejectedError} with the rejection's message, or with the message of
|
|
221
|
+
* `server/discover` when the rejection proved a stateless server that is still there. Such a server
|
|
222
|
+
* failing `server/discover` without answering it (sign-in required, say) fails with that error.
|
|
223
|
+
*/
|
|
224
|
+
async initializeOrDiscover(transport) {
|
|
225
|
+
try {
|
|
226
|
+
return await this.initialize(transport);
|
|
227
|
+
}
|
|
228
|
+
catch (error) {
|
|
229
|
+
const rejection = error instanceof StatelessInitializeError ? "stateless" : initializeRejection(error);
|
|
230
|
+
if (rejection === undefined)
|
|
231
|
+
throw error;
|
|
232
|
+
const timeoutMs = rejection === "stateless"
|
|
233
|
+
? this.connectTimeoutMs()
|
|
234
|
+
: Math.min(this.connectTimeoutMs(), DISCOVER_AFTER_INITIALIZE_TIMEOUT_MS);
|
|
235
|
+
try {
|
|
236
|
+
return await this.discover(transport, timeoutMs);
|
|
237
|
+
}
|
|
238
|
+
catch (discoverError) {
|
|
239
|
+
const answered = discoverError instanceof McpError;
|
|
240
|
+
if (rejection === "stateless" && !answered && !isConnectionLost(discoverError))
|
|
241
|
+
throw discoverError;
|
|
242
|
+
const message = rejection === "stateless" && answered ? discoverError.message : toError(error).message;
|
|
243
|
+
throw new McpInitializeRejectedError(message, error, discoverError);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
async initialize(transport) {
|
|
248
|
+
const result = validateInitializeResult(await this.requestInternal("initialize", {
|
|
249
|
+
protocolVersion: this.options.protocolVersion ?? LATEST_PROTOCOL_VERSION,
|
|
250
|
+
capabilities: this.meta.clientCapabilities,
|
|
251
|
+
clientInfo: this.meta.clientInfo,
|
|
252
|
+
}, { timeoutMs: this.connectTimeoutMs() }, true));
|
|
253
|
+
if (result.protocolVersion === STATELESS_PROTOCOL_VERSION) {
|
|
254
|
+
throw new StatelessInitializeError("MCP server answered initialize with the stateless protocol revision");
|
|
255
|
+
}
|
|
256
|
+
if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
|
|
257
|
+
throw new Error(`MCP server selected unsupported protocol version ${result.protocolVersion}`);
|
|
258
|
+
}
|
|
259
|
+
this.protocolVersionValue = result.protocolVersion;
|
|
260
|
+
this.serverInfoValue = result.serverInfo;
|
|
261
|
+
this.serverCapabilitiesValue = result.capabilities;
|
|
262
|
+
this.instructionsValue = result.instructions;
|
|
263
|
+
transport.setProtocolVersion?.(result.protocolVersion);
|
|
264
|
+
await this.notifyInternal("notifications/initialized", undefined, true);
|
|
265
|
+
return result;
|
|
266
|
+
}
|
|
267
|
+
/** Speak the stateless revision: no handshake, `server/discover` tells what the server offers. */
|
|
268
|
+
async discover(transport, timeoutMs) {
|
|
269
|
+
this.stateless = true;
|
|
270
|
+
transport.setProtocolVersion?.(STATELESS_PROTOCOL_VERSION);
|
|
271
|
+
const { result, serverInfo } = validateDiscoverResult(await this.requestInternal("server/discover", undefined, { timeoutMs }, true));
|
|
272
|
+
if (!result.supportedVersions.includes(STATELESS_PROTOCOL_VERSION)) {
|
|
273
|
+
throw new Error(`MCP server supports none of this client's protocol versions: ${result.supportedVersions}`);
|
|
274
|
+
}
|
|
275
|
+
this.protocolVersionValue = STATELESS_PROTOCOL_VERSION;
|
|
276
|
+
this.serverInfoValue = serverInfo;
|
|
277
|
+
this.serverCapabilitiesValue = result.capabilities;
|
|
278
|
+
this.instructionsValue = result.instructions;
|
|
279
|
+
return {
|
|
280
|
+
protocolVersion: STATELESS_PROTOCOL_VERSION,
|
|
281
|
+
capabilities: result.capabilities,
|
|
282
|
+
serverInfo: serverInfo ?? { name: "", version: "" },
|
|
283
|
+
...(result.instructions === undefined ? {} : { instructions: result.instructions }),
|
|
284
|
+
};
|
|
285
|
+
}
|
|
154
286
|
request(method, params, options = {}) {
|
|
155
|
-
return this.
|
|
287
|
+
return this.requestConnected(method, params, options);
|
|
156
288
|
}
|
|
157
289
|
notify(method, params) {
|
|
158
290
|
return this.notifyInternal(method, params, false);
|
|
159
291
|
}
|
|
292
|
+
/**
|
|
293
|
+
* Answer requests of `method` from the server: requests a legacy server sends, and the input requests
|
|
294
|
+
* of the same method that results of the stateless revision ask for (`roots/list`, say).
|
|
295
|
+
*/
|
|
160
296
|
setRequestHandler(method, handler) {
|
|
161
297
|
this.requestHandlers.set(method, handler);
|
|
162
298
|
return () => {
|
|
@@ -183,11 +319,32 @@ export class McpClient {
|
|
|
183
319
|
this.closeListeners.add(listener);
|
|
184
320
|
return () => this.closeListeners.delete(listener);
|
|
185
321
|
}
|
|
322
|
+
/** Check that the server answers: `ping`, or `server/discover` on the stateless revision, which has no `ping`. */
|
|
186
323
|
async ping(options = {}) {
|
|
187
|
-
await this.request("ping", undefined, options);
|
|
324
|
+
await this.request(this.stateless ? "server/discover" : "ping", undefined, options);
|
|
188
325
|
}
|
|
326
|
+
/**
|
|
327
|
+
* Every tool, following `nextCursor` through all pages. On the stateless revision over HTTP, tools
|
|
328
|
+
* whose `x-mcp-header` annotations are invalid are left out and reported through `onError`.
|
|
329
|
+
*/
|
|
189
330
|
async listTools(options = {}) {
|
|
190
|
-
|
|
331
|
+
const tools = (await this.listAll("tools/list", "tools", isTool, options));
|
|
332
|
+
if (!this.stateless || !this.transport?.sendsHeaders)
|
|
333
|
+
return tools;
|
|
334
|
+
const kept = [];
|
|
335
|
+
const headers = new Map();
|
|
336
|
+
for (const tool of tools) {
|
|
337
|
+
const bindings = toolHeaderBindings(tool.inputSchema);
|
|
338
|
+
if (bindings.kind === "invalid") {
|
|
339
|
+
this.emitError(new Error(`Excluded MCP tool "${tool.name}": ${bindings.reason}`));
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
if (bindings.bindings.length > 0)
|
|
343
|
+
headers.set(tool.name, bindings.bindings);
|
|
344
|
+
kept.push(tool);
|
|
345
|
+
}
|
|
346
|
+
this.toolHeaders = headers;
|
|
347
|
+
return kept;
|
|
191
348
|
}
|
|
192
349
|
/** Every resource, following `nextCursor` through all pages. */
|
|
193
350
|
async listResources(options = {}) {
|
|
@@ -231,8 +388,72 @@ export class McpClient {
|
|
|
231
388
|
}
|
|
232
389
|
throw new Error(`MCP ${method} exceeded ${MAX_LIST_PAGES} pages`);
|
|
233
390
|
}
|
|
391
|
+
/**
|
|
392
|
+
* Call a tool. On the stateless revision, arguments the tool marks with `x-mcp-header` go into
|
|
393
|
+
* `Mcp-Param-*` headers too; when the server reports that they do not match, the tools are listed
|
|
394
|
+
* again for their current annotations and the call is sent once more.
|
|
395
|
+
*/
|
|
234
396
|
async callTool(name, args, options = {}) {
|
|
235
|
-
|
|
397
|
+
const params = { name, ...(args === undefined ? {} : { arguments: args }) };
|
|
398
|
+
const call = async () => {
|
|
399
|
+
const bindings = this.toolHeaders.get(name);
|
|
400
|
+
const headers = bindings ? toolParamHeaders(bindings, args) : undefined;
|
|
401
|
+
return validateCallToolResult(await this.requestConnected("tools/call", params, options, headers));
|
|
402
|
+
};
|
|
403
|
+
try {
|
|
404
|
+
return await call();
|
|
405
|
+
}
|
|
406
|
+
catch (error) {
|
|
407
|
+
if (!(this.stateless && error instanceof McpError && error.code === HEADER_MISMATCH_ERROR_CODE))
|
|
408
|
+
throw error;
|
|
409
|
+
await this.listTools(options.signal ? { signal: options.signal } : {});
|
|
410
|
+
return await call();
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Open a `subscriptions/listen` stream of a server on the stateless revision, which delivers the
|
|
415
|
+
* notifications `filter` names to `onNotification` listeners. Resolves once the server acknowledged
|
|
416
|
+
* it; servers of earlier revisions send their notifications without one.
|
|
417
|
+
*/
|
|
418
|
+
async listen(filter, options = {}) {
|
|
419
|
+
if (!this.stateless)
|
|
420
|
+
throw new Error("subscriptions/listen needs a server on the stateless revision");
|
|
421
|
+
const controller = new AbortController();
|
|
422
|
+
const close = () => controller.abort();
|
|
423
|
+
options.signal?.addEventListener("abort", close, { once: true });
|
|
424
|
+
let id;
|
|
425
|
+
let endedByServer = false;
|
|
426
|
+
let acknowledge = (_notifications) => { };
|
|
427
|
+
const acknowledged = new Promise((resolve) => {
|
|
428
|
+
acknowledge = resolve;
|
|
429
|
+
});
|
|
430
|
+
const request = this.requestInternal("subscriptions/listen", { notifications: filter }, { signal: controller.signal, timeoutMs: Number.POSITIVE_INFINITY }, false, {
|
|
431
|
+
onId: (requestId) => {
|
|
432
|
+
id = requestId;
|
|
433
|
+
const end = () => {
|
|
434
|
+
endedByServer = true;
|
|
435
|
+
this.cancelPending(requestId, new McpConnectionClosedError("MCP subscription ended"), false);
|
|
436
|
+
};
|
|
437
|
+
this.subscriptions.set(requestId, { acknowledge, end });
|
|
438
|
+
},
|
|
439
|
+
});
|
|
440
|
+
// The server ends a subscription with a result or `notifications/cancelled`; the client by aborting it.
|
|
441
|
+
const closed = request
|
|
442
|
+
.then(() => undefined, (error) => {
|
|
443
|
+
if (!endedByServer && !controller.signal.aborted)
|
|
444
|
+
throw error;
|
|
445
|
+
})
|
|
446
|
+
.finally(() => {
|
|
447
|
+
if (id !== undefined)
|
|
448
|
+
this.subscriptions.delete(id);
|
|
449
|
+
options.signal?.removeEventListener("abort", close);
|
|
450
|
+
});
|
|
451
|
+
const endedEarly = closed.then(() => {
|
|
452
|
+
throw new Error("MCP subscription ended before the server acknowledged it");
|
|
453
|
+
});
|
|
454
|
+
// Only the race waits for it; once acknowledged, the caller waits for `closed`.
|
|
455
|
+
endedEarly.catch(() => { });
|
|
456
|
+
return { notifications: await Promise.race([acknowledged, endedEarly]), closed, close };
|
|
236
457
|
}
|
|
237
458
|
async close() {
|
|
238
459
|
const transport = this.transport;
|
|
@@ -241,15 +462,70 @@ export class McpClient {
|
|
|
241
462
|
this.markClosed(new McpConnectionClosedError());
|
|
242
463
|
await transport?.close();
|
|
243
464
|
}
|
|
244
|
-
|
|
465
|
+
/**
|
|
466
|
+
* A request on the connection. On the stateless revision, a result that asks for input is answered
|
|
467
|
+
* with the handlers of the input requests' methods, and one of an extension result type with
|
|
468
|
+
* `onExtensionResult`; the request is sent again with the answers until it completes. Every attempt
|
|
469
|
+
* is a new JSON-RPC request.
|
|
470
|
+
*/
|
|
471
|
+
async requestConnected(method, params, options, headers) {
|
|
472
|
+
if (!this.stateless)
|
|
473
|
+
return this.requestInternal(method, params, options, false, { headers });
|
|
474
|
+
let input = {};
|
|
475
|
+
for (let round = 0;; round++) {
|
|
476
|
+
const result = readStatelessResult(method, await this.requestInternal(method, { ...params, ...input }, options, false, { headers }));
|
|
477
|
+
if (result.kind === "complete")
|
|
478
|
+
return result.result;
|
|
479
|
+
if (round + 1 >= MAX_INPUT_ROUNDS) {
|
|
480
|
+
throw new Error(`MCP ${method} still asks for input after ${MAX_INPUT_ROUNDS} rounds`);
|
|
481
|
+
}
|
|
482
|
+
input = await this.answerResult(method, result, options);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
/** The params that answer a result asking for more, which the request is sent again with. */
|
|
486
|
+
async answerResult(method, result, options) {
|
|
487
|
+
const signal = options.signal ?? new AbortController().signal;
|
|
488
|
+
if (result.kind === "extension") {
|
|
489
|
+
if (!options.onExtensionResult)
|
|
490
|
+
throw invalid(`Unsupported MCP ${method} result type: ${result.resultType}`);
|
|
491
|
+
const { requestState } = await options.onExtensionResult(result.result, { signal });
|
|
492
|
+
return { requestState };
|
|
493
|
+
}
|
|
494
|
+
if (!INPUT_METHODS.has(method))
|
|
495
|
+
throw new Error(`MCP ${method} result asks for input, which it may not`);
|
|
496
|
+
return {
|
|
497
|
+
inputResponses: await this.answerInputRequests(result.inputRequests, signal),
|
|
498
|
+
...(result.requestState === undefined ? {} : { requestState: result.requestState }),
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
async answerInputRequests(requests, signal) {
|
|
502
|
+
const responses = {};
|
|
503
|
+
for (const [key, request] of Object.entries(requests)) {
|
|
504
|
+
const handler = this.requestHandlers.get(request.method);
|
|
505
|
+
if (!handler)
|
|
506
|
+
throw new Error(`MCP server asked for input this client does not provide: ${request.method}`);
|
|
507
|
+
responses[key] = (await handler(request.params, { signal })) ?? {};
|
|
508
|
+
}
|
|
509
|
+
return responses;
|
|
510
|
+
}
|
|
511
|
+
requestTimeoutMs() {
|
|
512
|
+
return this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
513
|
+
}
|
|
514
|
+
connectTimeoutMs() {
|
|
515
|
+
return this.options.connectTimeoutMs ?? this.requestTimeoutMs();
|
|
516
|
+
}
|
|
517
|
+
async requestInternal(method, params, options, allowConnecting, send = {}) {
|
|
245
518
|
const transport = this.requireTransport(allowConnecting);
|
|
246
519
|
if (options.signal?.aborted)
|
|
247
520
|
throw new McpAbortError();
|
|
248
521
|
const id = this.nextRequestId++;
|
|
522
|
+
send.onId?.(id);
|
|
523
|
+
const { headers } = send;
|
|
249
524
|
const progressToken = options.onProgress ? id : undefined;
|
|
525
|
+
const metaParams = this.stateless ? withStatelessMeta(params, this.meta) : params;
|
|
250
526
|
const requestParams = progressToken === undefined
|
|
251
|
-
?
|
|
252
|
-
: { ...
|
|
527
|
+
? metaParams
|
|
528
|
+
: { ...metaParams, _meta: { ...(isObject(metaParams?._meta) ? metaParams._meta : {}), progressToken } };
|
|
253
529
|
const message = {
|
|
254
530
|
jsonrpc: "2.0",
|
|
255
531
|
id,
|
|
@@ -260,7 +536,7 @@ export class McpClient {
|
|
|
260
536
|
const entry = {
|
|
261
537
|
resolve,
|
|
262
538
|
reject,
|
|
263
|
-
timeoutMs: options.timeoutMs ?? this.
|
|
539
|
+
timeoutMs: options.timeoutMs ?? this.requestTimeoutMs(),
|
|
264
540
|
timer: undefined,
|
|
265
541
|
signal: options.signal,
|
|
266
542
|
// The spec forbids cancelling `initialize`.
|
|
@@ -276,7 +552,7 @@ export class McpClient {
|
|
|
276
552
|
options.signal?.addEventListener("abort", entry.onAbort, { once: true });
|
|
277
553
|
this.armTimeout(id, entry);
|
|
278
554
|
transport
|
|
279
|
-
.send(message, { signal: entry.sendController.signal })
|
|
555
|
+
.send(message, { signal: entry.sendController.signal, ...(headers === undefined ? {} : { headers }) })
|
|
280
556
|
.catch((error) => this.cancelPending(id, error, false));
|
|
281
557
|
});
|
|
282
558
|
}
|
|
@@ -359,6 +635,8 @@ export class McpClient {
|
|
|
359
635
|
this.handleProgress(params);
|
|
360
636
|
else if (method === "notifications/cancelled")
|
|
361
637
|
this.handleCancelled(params);
|
|
638
|
+
else if (method === "notifications/subscriptions/acknowledged")
|
|
639
|
+
this.subscriptionOf(params)?.acknowledge(readSubscriptionFilter(params));
|
|
362
640
|
for (const listener of this.notificationListeners.get(method) ?? []) {
|
|
363
641
|
try {
|
|
364
642
|
listener(params);
|
|
@@ -383,9 +661,16 @@ export class McpClient {
|
|
|
383
661
|
this.emitError(error);
|
|
384
662
|
}
|
|
385
663
|
}
|
|
664
|
+
/** Servers cancel requests they sent, and on the stateless revision end subscriptions this way. */
|
|
386
665
|
handleCancelled(params) {
|
|
387
|
-
if (isObject(params)
|
|
388
|
-
|
|
666
|
+
if (!isObject(params) || !isJsonRpcId(params.requestId))
|
|
667
|
+
return;
|
|
668
|
+
this.incoming.get(params.requestId)?.abort(params.reason);
|
|
669
|
+
this.subscriptions.get(normalizeOwnRequestId(params.requestId))?.end();
|
|
670
|
+
}
|
|
671
|
+
subscriptionOf(params) {
|
|
672
|
+
const id = subscriptionIdOf(params);
|
|
673
|
+
return isJsonRpcId(id) ? this.subscriptions.get(normalizeOwnRequestId(id)) : undefined;
|
|
389
674
|
}
|
|
390
675
|
armTimeout(id, entry) {
|
|
391
676
|
if (entry.timer)
|