@intentrax/sdk 1.6.0 → 1.8.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/README.md +56 -3
- package/cli/intentrax.mjs +57 -1
- package/index.js +4 -2
- package/index.ts +4 -2
- package/mcp/README.md +138 -0
- package/mcp/canonical.d.ts +12 -0
- package/mcp/canonical.mjs +70 -0
- package/mcp/cli.d.ts +16 -0
- package/mcp/cli.mjs +214 -0
- package/mcp/client.d.ts +131 -0
- package/mcp/client.mjs +955 -0
- package/mcp/commands.d.ts +113 -0
- package/mcp/commands.mjs +575 -0
- package/mcp/index.d.ts +12 -0
- package/mcp/index.mjs +12 -0
- package/mcp/proxy.d.ts +47 -0
- package/mcp/proxy.mjs +434 -0
- package/mcp/receipt-meta.d.ts +59 -0
- package/mcp/receipt-meta.mjs +178 -0
- package/mcp/tool-manifest.d.ts +74 -0
- package/mcp/tool-manifest.mjs +154 -0
- package/package.json +19 -1
- package/readback/README.md +352 -0
- package/readback/bridge.mjs +71 -0
- package/readback/cli.mjs +150 -0
- package/readback/confirm.mjs +404 -0
- package/readback/index.mjs +12 -0
- package/readback/recipe-worker.mjs +33 -0
- package/readback/recipes/_shared.mjs +126 -0
- package/readback/recipes/email-delivery.mjs +136 -0
- package/readback/recipes/github-issue.mjs +88 -0
- package/readback/recipes/http-json.mjs +109 -0
- package/readback/recipes/sql-row.mjs +96 -0
- package/readback/recipes/stripe-refund.mjs +73 -0
- package/readback/redact.mjs +68 -0
- package/sandbox/README.md +255 -0
- package/sandbox/authority.mjs +66 -0
- package/sandbox/bundle.mjs +93 -0
- package/sandbox/canonical.mjs +64 -0
- package/sandbox/check-runner.mjs +50 -0
- package/sandbox/check-worker.mjs +30 -0
- package/sandbox/cli.mjs +376 -0
- package/sandbox/effect-verifier.mjs +242 -0
- package/sandbox/effects.mjs +80 -0
- package/sandbox/envelope.mjs +174 -0
- package/sandbox/examples/read-only-check.example.mjs +32 -0
- package/sandbox/external-decision.mjs +364 -0
- package/sandbox/keys.mjs +179 -0
- package/sandbox/model.mjs +170 -0
- package/sandbox/run.mjs +324 -0
- package/sandbox/time.mjs +18 -0
- package/sandbox/verifier.mjs +503 -0
- package/scan/README.md +211 -0
- package/scan/classify.mjs +276 -0
- package/scan/cli.mjs +102 -0
- package/scan/configs.mjs +261 -0
- package/scan/credentials.mjs +121 -0
- package/scan/extract.mjs +323 -0
- package/scan/gates.mjs +94 -0
- package/scan/report.mjs +58 -0
- package/scan/scan.mjs +571 -0
- package/scan/text.mjs +186 -0
package/mcp/client.mjs
ADDED
|
@@ -0,0 +1,955 @@
|
|
|
1
|
+
// Minimal, dependency-free MCP client for R1b (`intentrax mcp pin|check|proxy`).
|
|
2
|
+
//
|
|
3
|
+
// It does exactly what pinning needs and nothing more:
|
|
4
|
+
// - transports: stdio (spawn a command, newline-delimited JSON-RPC) and
|
|
5
|
+
// Streamable HTTP (POST via fetch; JSON or SSE responses; optional GET
|
|
6
|
+
// stream for server notifications);
|
|
7
|
+
// - protocol: MCP 2026-07-28 via `server/discover` (stateless, `_meta` on
|
|
8
|
+
// every request), falling back to the legacy `initialize` handshake for
|
|
9
|
+
// 2025-11-25, 2025-06-18 and 2025-03-26;
|
|
10
|
+
// - `tools/list` following every `nextCursor` (a partial list is an error);
|
|
11
|
+
// - a timeout on every request.
|
|
12
|
+
//
|
|
13
|
+
// Credentials: a server spec may carry `${ENV_VAR}` placeholders in the URL,
|
|
14
|
+
// headers, command arguments and env values. They are expanded only when the
|
|
15
|
+
// transport opens and are never written to logs, errors or pin files:
|
|
16
|
+
// describeServer() works on the UNEXPANDED spec and redacts query strings,
|
|
17
|
+
// URL user-info and secret-looking arguments.
|
|
18
|
+
//
|
|
19
|
+
// Nothing here writes to stdout. Diagnostics go through an optional `log`
|
|
20
|
+
// callback, which the CLI points at stderr.
|
|
21
|
+
|
|
22
|
+
import { spawn } from "node:child_process";
|
|
23
|
+
import { randomBytes } from "node:crypto";
|
|
24
|
+
import { existsSync, statSync } from "node:fs";
|
|
25
|
+
import { basename, delimiter, extname, isAbsolute, join } from "node:path";
|
|
26
|
+
|
|
27
|
+
export const MODERN_PROTOCOL_VERSION = "2026-07-28";
|
|
28
|
+
export const LEGACY_PROTOCOL_VERSIONS = Object.freeze(["2025-11-25", "2025-06-18", "2025-03-26"]);
|
|
29
|
+
export const SUPPORTED_PROTOCOL_VERSIONS = Object.freeze([MODERN_PROTOCOL_VERSION, ...LEGACY_PROTOCOL_VERSIONS]);
|
|
30
|
+
export const DEFAULT_TIMEOUT_MS = 15_000;
|
|
31
|
+
export const DEFAULT_DISCOVER_TIMEOUT_MS = 5_000;
|
|
32
|
+
export const DEFAULT_MAX_PAGES = 100;
|
|
33
|
+
export const MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
|
|
34
|
+
export const CLIENT_INFO = Object.freeze({ name: "intentrax-mcp-check", version: "0.1.0" });
|
|
35
|
+
|
|
36
|
+
export const META_PROTOCOL_VERSION = "io.modelcontextprotocol/protocolVersion";
|
|
37
|
+
export const META_CLIENT_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities";
|
|
38
|
+
export const META_CLIENT_INFO = "io.modelcontextprotocol/clientInfo";
|
|
39
|
+
export const META_SERVER_INFO = "io.modelcontextprotocol/serverInfo";
|
|
40
|
+
|
|
41
|
+
const METHOD_NOT_FOUND = -32601;
|
|
42
|
+
const SENSITIVE_NAME = /(?:api[-_]?key|auth|cookie|password|passwd|private[-_]?key|secret|token|credential|session|bearer|signature|sig\b)/i;
|
|
43
|
+
const SECRET_PREFIX = /^(?:ghp_|gho_|ghs_|github_pat_|sk-|sk_live_|sk_test_|xox[abpr]-|AKIA|ya29\.|glpat-)/;
|
|
44
|
+
const PLACEHOLDER = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
|
|
45
|
+
|
|
46
|
+
export class McpClientError extends Error {
|
|
47
|
+
constructor(code, message, details = undefined) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.name = "McpClientError";
|
|
50
|
+
this.code = code;
|
|
51
|
+
if (details !== undefined) this.details = details;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function isPlainObject(value) {
|
|
56
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
57
|
+
const proto = Object.getPrototypeOf(value);
|
|
58
|
+
return proto === Object.prototype || proto === null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function clip(text, max = 200) {
|
|
62
|
+
const s = String(text);
|
|
63
|
+
return s.length > max ? s.slice(0, max) + "…" : s;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ---------------------------------------------------------------------------
|
|
67
|
+
// Server specs
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
// splitCommandLine("node server.mjs --flag 'a b'") -> ["node", "server.mjs", "--flag", "a b"].
|
|
71
|
+
// Plain quoting only: no globbing, no variable expansion, no operators.
|
|
72
|
+
export function splitCommandLine(line) {
|
|
73
|
+
const out = [];
|
|
74
|
+
let current = "";
|
|
75
|
+
let quote = null;
|
|
76
|
+
let started = false;
|
|
77
|
+
for (let i = 0; i < line.length; i += 1) {
|
|
78
|
+
const ch = line[i];
|
|
79
|
+
if (quote) {
|
|
80
|
+
if (ch === quote) quote = null;
|
|
81
|
+
else if (ch === "\\" && quote === '"' && (line[i + 1] === '"' || line[i + 1] === "\\")) current += line[++i];
|
|
82
|
+
else current += ch;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (ch === '"' || ch === "'") {
|
|
86
|
+
quote = ch;
|
|
87
|
+
started = true;
|
|
88
|
+
} else if (/\s/.test(ch)) {
|
|
89
|
+
if (started) out.push(current);
|
|
90
|
+
current = "";
|
|
91
|
+
started = false;
|
|
92
|
+
} else {
|
|
93
|
+
current += ch;
|
|
94
|
+
started = true;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (quote) throw new McpClientError("invalid_spec", "server command has an unterminated quote");
|
|
98
|
+
if (started) out.push(current);
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// parseServerSpec(input) -> a normalized, UNEXPANDED spec:
|
|
103
|
+
// { transport: "stdio", command: [file, ...args], env?: {}, cwd? }
|
|
104
|
+
// { transport: "streamable-http", url, headers?: {} }
|
|
105
|
+
// `input` is a URL string, a command line string, an argv array, or a spec object.
|
|
106
|
+
export function parseServerSpec(input) {
|
|
107
|
+
if (typeof input === "string") {
|
|
108
|
+
const trimmed = input.trim();
|
|
109
|
+
if (trimmed === "") throw new McpClientError("invalid_spec", "server is required");
|
|
110
|
+
if (/^https?:\/\//i.test(trimmed)) return parseServerSpec({ transport: "streamable-http", url: trimmed });
|
|
111
|
+
return parseServerSpec({ transport: "stdio", command: splitCommandLine(trimmed) });
|
|
112
|
+
}
|
|
113
|
+
if (Array.isArray(input)) return parseServerSpec({ transport: "stdio", command: input });
|
|
114
|
+
if (!isPlainObject(input)) throw new McpClientError("invalid_spec", "server must be a command, a URL or a spec object");
|
|
115
|
+
const transport = input.transport ?? (input.url !== undefined ? "streamable-http" : "stdio");
|
|
116
|
+
if (transport === "stdio") {
|
|
117
|
+
const command = typeof input.command === "string" ? splitCommandLine(input.command) : input.command;
|
|
118
|
+
if (!Array.isArray(command) || command.length === 0 || !command.every((part) => typeof part === "string") || command[0] === "") {
|
|
119
|
+
throw new McpClientError("invalid_spec", "stdio server needs a non-empty command");
|
|
120
|
+
}
|
|
121
|
+
const spec = { transport: "stdio", command: [...command] };
|
|
122
|
+
if (input.env !== undefined) spec.env = stringMap(input.env, "env");
|
|
123
|
+
if (input.cwd !== undefined) {
|
|
124
|
+
if (typeof input.cwd !== "string" || input.cwd === "") throw new McpClientError("invalid_spec", "cwd must be a string");
|
|
125
|
+
spec.cwd = input.cwd;
|
|
126
|
+
}
|
|
127
|
+
return spec;
|
|
128
|
+
}
|
|
129
|
+
if (transport === "streamable-http" || transport === "http") {
|
|
130
|
+
if (typeof input.url !== "string" || !/^https?:\/\//i.test(input.url)) {
|
|
131
|
+
throw new McpClientError("invalid_spec", "HTTP server needs an http(s) URL");
|
|
132
|
+
}
|
|
133
|
+
const spec = { transport: "streamable-http", url: input.url };
|
|
134
|
+
if (input.headers !== undefined) spec.headers = stringMap(input.headers, "headers");
|
|
135
|
+
return spec;
|
|
136
|
+
}
|
|
137
|
+
throw new McpClientError("invalid_spec", "unsupported transport " + JSON.stringify(clip(transport, 40)));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function stringMap(value, label) {
|
|
141
|
+
if (!isPlainObject(value)) throw new McpClientError("invalid_spec", label + " must be an object of strings");
|
|
142
|
+
const out = {};
|
|
143
|
+
for (const key of Object.keys(value).sort()) {
|
|
144
|
+
if (typeof value[key] !== "string") throw new McpClientError("invalid_spec", label + " values must be strings");
|
|
145
|
+
out[key] = value[key];
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// expandEnv("Bearer ${TOKEN}", env). A missing variable is an error that names
|
|
151
|
+
// the variable, never a value.
|
|
152
|
+
export function expandEnv(text, env = process.env) {
|
|
153
|
+
return text.replace(PLACEHOLDER, (_, name) => {
|
|
154
|
+
const value = env[name];
|
|
155
|
+
if (typeof value !== "string" || value === "") {
|
|
156
|
+
throw new McpClientError("env_missing", "environment variable " + name + " is not set");
|
|
157
|
+
}
|
|
158
|
+
return value;
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function hasPlaceholder(text) {
|
|
163
|
+
PLACEHOLDER.lastIndex = 0;
|
|
164
|
+
const found = PLACEHOLDER.test(text);
|
|
165
|
+
PLACEHOLDER.lastIndex = 0;
|
|
166
|
+
return found;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function looksSecret(arg) {
|
|
170
|
+
if (hasPlaceholder(arg)) return false;
|
|
171
|
+
if (SECRET_PREFIX.test(arg)) return true;
|
|
172
|
+
return arg.length >= 24 && /^[A-Za-z0-9_\-+=.]+$/.test(arg) && /[0-9]/.test(arg) && /[A-Za-z]/.test(arg);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function redactArgs(args) {
|
|
176
|
+
const out = [];
|
|
177
|
+
let redactNext = false;
|
|
178
|
+
for (const arg of args) {
|
|
179
|
+
if (redactNext && !hasPlaceholder(arg)) {
|
|
180
|
+
out.push("[redacted]");
|
|
181
|
+
redactNext = false;
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
redactNext = false;
|
|
185
|
+
const eq = arg.indexOf("=");
|
|
186
|
+
if (arg.startsWith("-") && eq > 0) {
|
|
187
|
+
const flag = arg.slice(0, eq);
|
|
188
|
+
const value = arg.slice(eq + 1);
|
|
189
|
+
out.push(SENSITIVE_NAME.test(flag) || looksSecret(value) ? flag + "=[redacted]" : arg);
|
|
190
|
+
} else if (arg.startsWith("-")) {
|
|
191
|
+
out.push(arg);
|
|
192
|
+
if (SENSITIVE_NAME.test(arg)) redactNext = true;
|
|
193
|
+
} else {
|
|
194
|
+
out.push(looksSecret(arg) ? "[redacted]" : arg);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function redactUrl(raw) {
|
|
201
|
+
let text = String(raw);
|
|
202
|
+
const hadQuery = /[?#]/.test(text);
|
|
203
|
+
text = text.replace(/[?#].*$/, "");
|
|
204
|
+
text = text.replace(/^(https?:\/\/)[^@/]*@/i, "$1");
|
|
205
|
+
return hadQuery ? text + "?[redacted]" : text;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// describeServer(spec) -> a short, log-safe description of an UNEXPANDED spec.
|
|
209
|
+
export function describeServer(specInput) {
|
|
210
|
+
let spec;
|
|
211
|
+
try {
|
|
212
|
+
spec = parseServerSpec(specInput);
|
|
213
|
+
} catch {
|
|
214
|
+
return "[invalid server spec]";
|
|
215
|
+
}
|
|
216
|
+
if (spec.transport === "streamable-http") return redactUrl(spec.url);
|
|
217
|
+
const [file, ...args] = spec.command;
|
|
218
|
+
return [basename(file), ...redactArgs(args)].join(" ");
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Secrets that would be WRITTEN to a pin file: literal values in sensitive
|
|
222
|
+
// headers, env entries or URL query parameters, and URL user-info. Returns a
|
|
223
|
+
// list of problems (names only). Stdio arguments are only warned about, since
|
|
224
|
+
// they cannot be classified reliably.
|
|
225
|
+
export function findStoredSecrets(specInput) {
|
|
226
|
+
const spec = parseServerSpec(specInput);
|
|
227
|
+
const problems = [];
|
|
228
|
+
const warnings = [];
|
|
229
|
+
if (spec.transport === "streamable-http") {
|
|
230
|
+
if (/^https?:\/\/[^/]*@/i.test(spec.url)) problems.push("URL user-info (user:password@)");
|
|
231
|
+
const query = spec.url.includes("?") ? spec.url.slice(spec.url.indexOf("?") + 1).replace(/#.*$/, "") : "";
|
|
232
|
+
for (const part of query.split("&").filter(Boolean)) {
|
|
233
|
+
const [key, value = ""] = part.split("=");
|
|
234
|
+
if ((SENSITIVE_NAME.test(key) || looksSecret(value)) && !hasPlaceholder(value)) problems.push("URL query parameter " + clip(key, 40));
|
|
235
|
+
}
|
|
236
|
+
for (const [key, value] of Object.entries(spec.headers ?? {})) {
|
|
237
|
+
if (SENSITIVE_NAME.test(key) && !hasPlaceholder(value)) problems.push("header " + clip(key, 40));
|
|
238
|
+
}
|
|
239
|
+
} else {
|
|
240
|
+
for (const [key, value] of Object.entries(spec.env ?? {})) {
|
|
241
|
+
if ((SENSITIVE_NAME.test(key) || looksSecret(value)) && !hasPlaceholder(value)) problems.push("env " + clip(key, 40));
|
|
242
|
+
}
|
|
243
|
+
const redacted = redactArgs(spec.command.slice(1));
|
|
244
|
+
if (redacted.some((arg) => arg.includes("[redacted]"))) warnings.push("a command argument looks like a credential; prefer ${ENV_VAR}");
|
|
245
|
+
}
|
|
246
|
+
return { problems, warnings };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// ---------------------------------------------------------------------------
|
|
250
|
+
// Line framing (stdio) and SSE parsing (HTTP)
|
|
251
|
+
// ---------------------------------------------------------------------------
|
|
252
|
+
|
|
253
|
+
export function createLineSplitter(onLine, { maxBytes = MAX_MESSAGE_BYTES, onOverflow } = {}) {
|
|
254
|
+
let buffer = "";
|
|
255
|
+
// One decoder for the whole stream: a multibyte UTF-8 character split across
|
|
256
|
+
// two chunks is held back, not replaced with U+FFFD.
|
|
257
|
+
const decoder = new TextDecoder("utf-8");
|
|
258
|
+
return (chunk) => {
|
|
259
|
+
buffer += typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
|
|
260
|
+
let index;
|
|
261
|
+
while ((index = buffer.indexOf("\n")) !== -1) {
|
|
262
|
+
const line = buffer.slice(0, index).replace(/\r$/, "");
|
|
263
|
+
buffer = buffer.slice(index + 1);
|
|
264
|
+
if (line.trim() !== "") onLine(line);
|
|
265
|
+
}
|
|
266
|
+
if (buffer.length > maxBytes) {
|
|
267
|
+
buffer = "";
|
|
268
|
+
if (onOverflow) onOverflow();
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async function readSse(body, onData, { maxBytes = MAX_MESSAGE_BYTES } = {}) {
|
|
274
|
+
const decoder = new TextDecoder();
|
|
275
|
+
let buffer = "";
|
|
276
|
+
let data = [];
|
|
277
|
+
let dataBytes = 0;
|
|
278
|
+
const flushLine = (line) => {
|
|
279
|
+
if (line === "") {
|
|
280
|
+
if (data.length > 0) onData(data.join("\n"));
|
|
281
|
+
data = [];
|
|
282
|
+
dataBytes = 0;
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (line.startsWith(":")) return;
|
|
286
|
+
const colon = line.indexOf(":");
|
|
287
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
288
|
+
let value = colon === -1 ? "" : line.slice(colon + 1);
|
|
289
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
290
|
+
if (field === "data") {
|
|
291
|
+
dataBytes += value.length;
|
|
292
|
+
if (dataBytes > maxBytes) throw new McpClientError("protocol", "SSE event exceeds the size limit");
|
|
293
|
+
data.push(value);
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
for await (const chunk of body) {
|
|
297
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
298
|
+
for (;;) {
|
|
299
|
+
const match = /\r\n|\r|\n/.exec(buffer);
|
|
300
|
+
if (!match) break;
|
|
301
|
+
// A trailing "\r" may be the first half of "\r\n": wait for more bytes.
|
|
302
|
+
if (match[0] === "\r" && match.index === buffer.length - 1) break;
|
|
303
|
+
flushLine(buffer.slice(0, match.index));
|
|
304
|
+
buffer = buffer.slice(match.index + match[0].length);
|
|
305
|
+
}
|
|
306
|
+
if (buffer.length > maxBytes) throw new McpClientError("protocol", "SSE line exceeds the size limit");
|
|
307
|
+
}
|
|
308
|
+
buffer += decoder.decode();
|
|
309
|
+
if (buffer !== "") flushLine(buffer.replace(/\r$/, ""));
|
|
310
|
+
flushLine("");
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function isRequest(message) {
|
|
314
|
+
return isPlainObject(message) && typeof message.method === "string" && Object.hasOwn(message, "id");
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function isResponse(message) {
|
|
318
|
+
return isPlainObject(message) && typeof message.method !== "string" && Object.hasOwn(message, "id") && (Object.hasOwn(message, "result") || Object.hasOwn(message, "error"));
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function modernVersionOf(message) {
|
|
322
|
+
const meta = isPlainObject(message) && isPlainObject(message.params) && isPlainObject(message.params._meta) ? message.params._meta : null;
|
|
323
|
+
return meta && typeof meta[META_PROTOCOL_VERSION] === "string" ? meta[META_PROTOCOL_VERSION] : null;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// ---------------------------------------------------------------------------
|
|
327
|
+
// Transports. Interface: { kind, start(), send(message), close(), onmessage,
|
|
328
|
+
// onclose, onnoise }. send() throws McpClientError on transport failure.
|
|
329
|
+
// ---------------------------------------------------------------------------
|
|
330
|
+
|
|
331
|
+
function findOnPath(command, env) {
|
|
332
|
+
const pathVar = env.PATH ?? env.Path ?? "";
|
|
333
|
+
const exts = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
|
|
334
|
+
const candidates = extname(command) ? [command] : exts.map((ext) => command + ext.toLowerCase());
|
|
335
|
+
const dirs = isAbsolute(command) || command.includes("\\") || command.includes("/") ? [""] : pathVar.split(delimiter).filter(Boolean);
|
|
336
|
+
for (const dir of dirs) {
|
|
337
|
+
for (const candidate of candidates) {
|
|
338
|
+
const full = dir === "" ? candidate : join(dir, candidate);
|
|
339
|
+
try {
|
|
340
|
+
if (existsSync(full) && statSync(full).isFile()) return full;
|
|
341
|
+
} catch {
|
|
342
|
+
// keep looking
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
return null;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// On Windows, npm-style shims (`npx`, `uvx.cmd`) are batch files that
|
|
350
|
+
// CreateProcess cannot start. They run through cmd.exe, with every argument
|
|
351
|
+
// checked for characters cmd.exe would interpret (fail closed, no injection).
|
|
352
|
+
function resolveSpawn(command, args, env) {
|
|
353
|
+
if (process.platform !== "win32") return { file: command, args, options: {} };
|
|
354
|
+
const resolved = findOnPath(command, env);
|
|
355
|
+
if (!resolved || !/\.(cmd|bat)$/i.test(resolved)) return { file: resolved ?? command, args, options: {} };
|
|
356
|
+
for (const arg of [resolved, ...args]) {
|
|
357
|
+
if (/[&|<>^%!"\r\n]/.test(arg)) {
|
|
358
|
+
throw new McpClientError("invalid_spec", "a command argument contains a character cmd.exe would interpret");
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
const quote = (arg) => (arg === "" || /\s/.test(arg) ? '"' + arg + '"' : arg);
|
|
362
|
+
const line = '"' + [resolved, ...args].map(quote).join(" ") + '"';
|
|
363
|
+
return { file: env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", line], options: { windowsVerbatimArguments: true } };
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
export class StdioTransport {
|
|
367
|
+
constructor(spec, { env = process.env, stderr = "ignore", maxBytes = MAX_MESSAGE_BYTES } = {}) {
|
|
368
|
+
this.kind = "stdio";
|
|
369
|
+
this.spec = spec;
|
|
370
|
+
this.env = env;
|
|
371
|
+
this.stderrMode = stderr;
|
|
372
|
+
this.maxBytes = maxBytes;
|
|
373
|
+
this.onmessage = null;
|
|
374
|
+
this.onclose = null;
|
|
375
|
+
this.onnoise = null;
|
|
376
|
+
this.child = null;
|
|
377
|
+
this.closed = false;
|
|
378
|
+
this.exitInfo = null;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
start() {
|
|
382
|
+
const [command, ...rawArgs] = this.spec.command.map((part) => expandEnv(part, this.env));
|
|
383
|
+
const extraEnv = {};
|
|
384
|
+
for (const [key, value] of Object.entries(this.spec.env ?? {})) extraEnv[key] = expandEnv(value, this.env);
|
|
385
|
+
const childEnv = { ...this.env, ...extraEnv };
|
|
386
|
+
const { file, args, options } = resolveSpawn(command, rawArgs, childEnv);
|
|
387
|
+
const stderrMode = typeof this.stderrMode === "function" ? "pipe" : this.stderrMode;
|
|
388
|
+
return new Promise((resolve, reject) => {
|
|
389
|
+
let child;
|
|
390
|
+
try {
|
|
391
|
+
child = spawn(file, args, {
|
|
392
|
+
...options,
|
|
393
|
+
cwd: this.spec.cwd,
|
|
394
|
+
env: childEnv,
|
|
395
|
+
stdio: ["pipe", "pipe", stderrMode],
|
|
396
|
+
shell: false,
|
|
397
|
+
windowsHide: true,
|
|
398
|
+
});
|
|
399
|
+
} catch (error) {
|
|
400
|
+
reject(new McpClientError("spawn_failed", "could not start the server command (" + clip(error.code ?? error.message, 60) + ")"));
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
this.child = child;
|
|
404
|
+
let spawned = false;
|
|
405
|
+
child.once("spawn", () => {
|
|
406
|
+
spawned = true;
|
|
407
|
+
resolve();
|
|
408
|
+
});
|
|
409
|
+
child.once("error", (error) => {
|
|
410
|
+
if (!spawned) reject(new McpClientError("spawn_failed", "could not start the server command (" + clip(error.code ?? "error", 60) + ")"));
|
|
411
|
+
this.#finish({ code: null, signal: null, error: error.code ?? "error" });
|
|
412
|
+
});
|
|
413
|
+
child.once("exit", (code, signal) => this.#finish({ code, signal }));
|
|
414
|
+
child.stdin.on("error", () => {}); // EPIPE after exit: reported through "exit"
|
|
415
|
+
if (typeof this.stderrMode === "function") {
|
|
416
|
+
child.stderr.on("data", (chunk) => this.stderrMode(chunk));
|
|
417
|
+
}
|
|
418
|
+
const split = createLineSplitter((line) => this.#line(line), {
|
|
419
|
+
maxBytes: this.maxBytes,
|
|
420
|
+
onOverflow: () => this.onnoise?.("oversized_line"),
|
|
421
|
+
});
|
|
422
|
+
child.stdout.on("data", split);
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
#line(line) {
|
|
427
|
+
let message;
|
|
428
|
+
try {
|
|
429
|
+
message = JSON.parse(line);
|
|
430
|
+
} catch {
|
|
431
|
+
this.onnoise?.("non_json_line");
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
this.onmessage?.(message);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
#finish(info) {
|
|
438
|
+
if (this.closed) return;
|
|
439
|
+
this.closed = true;
|
|
440
|
+
this.exitInfo = info;
|
|
441
|
+
this.onclose?.(info);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
async send(message) {
|
|
445
|
+
if (this.closed || !this.child || this.child.stdin.destroyed) {
|
|
446
|
+
throw new McpClientError("transport_closed", "the server process is not running");
|
|
447
|
+
}
|
|
448
|
+
const text = JSON.stringify(message) + "\n";
|
|
449
|
+
await new Promise((resolve, reject) => {
|
|
450
|
+
this.child.stdin.write(text, (error) => (error ? reject(new McpClientError("transport_closed", "could not write to the server process")) : resolve()));
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
async close() {
|
|
455
|
+
const child = this.child;
|
|
456
|
+
if (!child || this.closed) return;
|
|
457
|
+
const exited = new Promise((resolve) => child.once("exit", resolve));
|
|
458
|
+
const wait = (ms) => Promise.race([exited.then(() => true), new Promise((resolve) => setTimeout(() => resolve(false), ms).unref())]);
|
|
459
|
+
try {
|
|
460
|
+
child.stdin.end();
|
|
461
|
+
} catch {
|
|
462
|
+
// already closed
|
|
463
|
+
}
|
|
464
|
+
if (await wait(1_000)) return;
|
|
465
|
+
child.kill();
|
|
466
|
+
if (await wait(1_000)) return;
|
|
467
|
+
child.kill("SIGKILL");
|
|
468
|
+
await wait(1_000);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
|
473
|
+
|
|
474
|
+
export class HttpTransport {
|
|
475
|
+
constructor(spec, { env = process.env, timeoutMs = DEFAULT_TIMEOUT_MS, fetchImpl = globalThis.fetch, allowInsecureHttp = false, maxBytes = MAX_MESSAGE_BYTES } = {}) {
|
|
476
|
+
this.kind = "streamable-http";
|
|
477
|
+
this.spec = spec;
|
|
478
|
+
this.env = env;
|
|
479
|
+
this.timeoutMs = timeoutMs;
|
|
480
|
+
this.fetchImpl = fetchImpl;
|
|
481
|
+
this.allowInsecureHttp = allowInsecureHttp;
|
|
482
|
+
this.maxBytes = maxBytes;
|
|
483
|
+
this.onmessage = null;
|
|
484
|
+
this.onclose = null;
|
|
485
|
+
this.onnoise = null;
|
|
486
|
+
this.sessionId = null;
|
|
487
|
+
this.negotiatedVersion = null;
|
|
488
|
+
this.initializeIds = new Set();
|
|
489
|
+
this.controllers = new Set();
|
|
490
|
+
this.closed = false;
|
|
491
|
+
this.description = describeServer(spec);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
start() {
|
|
495
|
+
const url = expandEnv(this.spec.url, this.env);
|
|
496
|
+
let parsed;
|
|
497
|
+
try {
|
|
498
|
+
parsed = new URL(url);
|
|
499
|
+
} catch {
|
|
500
|
+
throw new McpClientError("invalid_spec", "server URL is not valid");
|
|
501
|
+
}
|
|
502
|
+
if (parsed.username !== "" || parsed.password !== "") {
|
|
503
|
+
throw new McpClientError("invalid_spec", "server URL carries user-info; pass credentials in a header with ${ENV_VAR}");
|
|
504
|
+
}
|
|
505
|
+
if (parsed.protocol === "http:" && !LOOPBACK_HOSTS.has(parsed.hostname) && !this.allowInsecureHttp) {
|
|
506
|
+
throw new McpClientError("invalid_spec", "plain http is only allowed for localhost; use https");
|
|
507
|
+
}
|
|
508
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
509
|
+
throw new McpClientError("invalid_spec", "server URL must be http(s)");
|
|
510
|
+
}
|
|
511
|
+
this.url = parsed.toString();
|
|
512
|
+
this.headers = {};
|
|
513
|
+
for (const [key, value] of Object.entries(this.spec.headers ?? {})) this.headers[key] = expandEnv(value, this.env);
|
|
514
|
+
return Promise.resolve();
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
#headersFor(message) {
|
|
518
|
+
const headers = { ...this.headers, "content-type": "application/json", accept: "application/json, text/event-stream" };
|
|
519
|
+
const modern = modernVersionOf(message);
|
|
520
|
+
if (modern) {
|
|
521
|
+
headers["mcp-protocol-version"] = modern;
|
|
522
|
+
if (typeof message.method === "string") headers["mcp-method"] = message.method;
|
|
523
|
+
const params = isPlainObject(message.params) ? message.params : {};
|
|
524
|
+
if ((message.method === "tools/call" || message.method === "prompts/get") && typeof params.name === "string") headers["mcp-name"] = params.name;
|
|
525
|
+
if (message.method === "resources/read" && typeof params.uri === "string") headers["mcp-name"] = params.uri;
|
|
526
|
+
} else if (this.negotiatedVersion) {
|
|
527
|
+
headers["mcp-protocol-version"] = this.negotiatedVersion;
|
|
528
|
+
}
|
|
529
|
+
if (this.sessionId) headers["mcp-session-id"] = this.sessionId;
|
|
530
|
+
return headers;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
#deliver(message, pendingIds) {
|
|
534
|
+
if (Array.isArray(message)) {
|
|
535
|
+
for (const item of message) this.#deliver(item, pendingIds);
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
if (isResponse(message)) {
|
|
539
|
+
pendingIds?.delete(message.id);
|
|
540
|
+
if (this.initializeIds.has(message.id)) {
|
|
541
|
+
this.initializeIds.delete(message.id);
|
|
542
|
+
if (isPlainObject(message.result) && typeof message.result.protocolVersion === "string") {
|
|
543
|
+
this.negotiatedVersion = message.result.protocolVersion;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
this.onmessage?.(message);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
async #readText(response) {
|
|
551
|
+
const reader = response.body?.getReader();
|
|
552
|
+
if (!reader) return "";
|
|
553
|
+
const chunks = [];
|
|
554
|
+
let total = 0;
|
|
555
|
+
for (;;) {
|
|
556
|
+
const { done, value } = await reader.read();
|
|
557
|
+
if (done) break;
|
|
558
|
+
total += value.byteLength;
|
|
559
|
+
if (total > this.maxBytes) {
|
|
560
|
+
reader.cancel().catch(() => {});
|
|
561
|
+
throw new McpClientError("protocol", "server response exceeds the size limit");
|
|
562
|
+
}
|
|
563
|
+
chunks.push(value);
|
|
564
|
+
}
|
|
565
|
+
return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8");
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
async send(message) {
|
|
569
|
+
if (this.closed) throw new McpClientError("transport_closed", "the HTTP transport is closed");
|
|
570
|
+
if (isRequest(message) && message.method === "initialize") this.initializeIds.add(message.id);
|
|
571
|
+
const controller = new AbortController();
|
|
572
|
+
this.controllers.add(controller);
|
|
573
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
574
|
+
let response;
|
|
575
|
+
try {
|
|
576
|
+
response = await this.fetchImpl(this.url, {
|
|
577
|
+
method: "POST",
|
|
578
|
+
headers: this.#headersFor(message),
|
|
579
|
+
body: JSON.stringify(message),
|
|
580
|
+
redirect: "error",
|
|
581
|
+
signal: controller.signal,
|
|
582
|
+
});
|
|
583
|
+
} catch (error) {
|
|
584
|
+
clearTimeout(timer);
|
|
585
|
+
this.controllers.delete(controller);
|
|
586
|
+
if (controller.signal.aborted && !this.closed) throw new McpClientError("timeout", "no HTTP response from " + this.description + " within " + this.timeoutMs + " ms");
|
|
587
|
+
throw new McpClientError("unreachable", "could not reach " + this.description + " (" + clip(error?.cause?.code ?? error?.name ?? "fetch failed", 40) + ")");
|
|
588
|
+
}
|
|
589
|
+
const sid = response.headers.get("mcp-session-id");
|
|
590
|
+
if (sid && isRequest(message) && message.method === "initialize") this.sessionId = sid;
|
|
591
|
+
const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
|
|
592
|
+
const pendingIds = new Set(isRequest(message) ? [message.id] : []);
|
|
593
|
+
try {
|
|
594
|
+
if (response.status === 202 || response.status === 204) {
|
|
595
|
+
clearTimeout(timer);
|
|
596
|
+
await response.body?.cancel().catch(() => {});
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
if (response.ok && contentType.includes("text/event-stream")) {
|
|
600
|
+
// The stream may legitimately stay open (server notifications); the
|
|
601
|
+
// request-level timeout lives in McpClient, not here.
|
|
602
|
+
clearTimeout(timer);
|
|
603
|
+
this.#pump(response, controller, pendingIds, message);
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
const text = await this.#readText(response);
|
|
607
|
+
clearTimeout(timer);
|
|
608
|
+
let parsed = null;
|
|
609
|
+
try {
|
|
610
|
+
parsed = text === "" ? null : JSON.parse(text);
|
|
611
|
+
} catch {
|
|
612
|
+
parsed = null;
|
|
613
|
+
}
|
|
614
|
+
const isRpc = (value) => isPlainObject(value) && value.jsonrpc === "2.0";
|
|
615
|
+
if (parsed !== null && (isRpc(parsed) || (Array.isArray(parsed) && parsed.every(isRpc)))) {
|
|
616
|
+
this.#deliver(parsed, pendingIds);
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
if (!response.ok) {
|
|
620
|
+
const hint = response.status === 404 && this.sessionId ? " (session expired)" : "";
|
|
621
|
+
throw new McpClientError("http_status", "HTTP " + response.status + " from " + this.description + hint, { status: response.status });
|
|
622
|
+
}
|
|
623
|
+
if (isRequest(message)) throw new McpClientError("protocol", "server answered with a non-JSON-RPC body");
|
|
624
|
+
} finally {
|
|
625
|
+
if (!contentType.includes("text/event-stream")) this.controllers.delete(controller);
|
|
626
|
+
clearTimeout(timer);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
#pump(response, controller, pendingIds, message) {
|
|
631
|
+
readSse(response.body, (data) => {
|
|
632
|
+
let parsed;
|
|
633
|
+
try {
|
|
634
|
+
parsed = JSON.parse(data);
|
|
635
|
+
} catch {
|
|
636
|
+
this.onnoise?.("non_json_event");
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
this.#deliver(parsed, pendingIds);
|
|
640
|
+
}, { maxBytes: this.maxBytes })
|
|
641
|
+
.catch(() => {})
|
|
642
|
+
.finally(() => {
|
|
643
|
+
this.controllers.delete(controller);
|
|
644
|
+
if (!this.closed && pendingIds.size > 0 && isRequest(message)) {
|
|
645
|
+
// The stream ended without answering: answer with an error so the
|
|
646
|
+
// caller does not hang (a proxied host would otherwise wait forever).
|
|
647
|
+
this.onmessage?.({ jsonrpc: "2.0", id: message.id, error: { code: -32603, message: "upstream stream ended without a response" } });
|
|
648
|
+
}
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// Optional GET stream for server-initiated messages (legacy Streamable
|
|
653
|
+
// HTTP). Returns true when a stream was opened; a 405 means the server has
|
|
654
|
+
// none, which is allowed.
|
|
655
|
+
async openNotificationStream() {
|
|
656
|
+
if (this.closed) return false;
|
|
657
|
+
const controller = new AbortController();
|
|
658
|
+
this.controllers.add(controller);
|
|
659
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
660
|
+
try {
|
|
661
|
+
const headers = { ...this.headers, accept: "text/event-stream" };
|
|
662
|
+
if (this.negotiatedVersion) headers["mcp-protocol-version"] = this.negotiatedVersion;
|
|
663
|
+
if (this.sessionId) headers["mcp-session-id"] = this.sessionId;
|
|
664
|
+
const response = await this.fetchImpl(this.url, { method: "GET", headers, redirect: "error", signal: controller.signal });
|
|
665
|
+
clearTimeout(timer);
|
|
666
|
+
if (!response.ok || !(response.headers.get("content-type") ?? "").toLowerCase().includes("text/event-stream")) {
|
|
667
|
+
await response.body?.cancel().catch(() => {});
|
|
668
|
+
this.controllers.delete(controller);
|
|
669
|
+
return false;
|
|
670
|
+
}
|
|
671
|
+
this.#pump(response, controller, new Set(), null);
|
|
672
|
+
return true;
|
|
673
|
+
} catch {
|
|
674
|
+
clearTimeout(timer);
|
|
675
|
+
this.controllers.delete(controller);
|
|
676
|
+
return false;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
async close() {
|
|
681
|
+
if (this.closed) return;
|
|
682
|
+
this.closed = true;
|
|
683
|
+
for (const controller of this.controllers) controller.abort();
|
|
684
|
+
this.controllers.clear();
|
|
685
|
+
if (this.sessionId && this.url) {
|
|
686
|
+
const controller = new AbortController();
|
|
687
|
+
const timer = setTimeout(() => controller.abort(), 2_000);
|
|
688
|
+
try {
|
|
689
|
+
const headers = { ...this.headers, "mcp-session-id": this.sessionId };
|
|
690
|
+
if (this.negotiatedVersion) headers["mcp-protocol-version"] = this.negotiatedVersion;
|
|
691
|
+
const response = await this.fetchImpl(this.url, { method: "DELETE", headers, redirect: "error", signal: controller.signal });
|
|
692
|
+
await response.body?.cancel().catch(() => {});
|
|
693
|
+
} catch {
|
|
694
|
+
// best effort
|
|
695
|
+
} finally {
|
|
696
|
+
clearTimeout(timer);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
this.onclose?.({ code: null, signal: null });
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
export async function openTransport(specInput, options = {}) {
|
|
704
|
+
const spec = parseServerSpec(specInput);
|
|
705
|
+
const transport = spec.transport === "stdio" ? new StdioTransport(spec, options) : new HttpTransport(spec, options);
|
|
706
|
+
await transport.start();
|
|
707
|
+
return transport;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
// ---------------------------------------------------------------------------
|
|
711
|
+
// JSON-RPC client
|
|
712
|
+
// ---------------------------------------------------------------------------
|
|
713
|
+
|
|
714
|
+
export class McpClient {
|
|
715
|
+
constructor(transport, { timeoutMs = DEFAULT_TIMEOUT_MS, clientInfo = CLIENT_INFO, log = () => {}, meta } = {}) {
|
|
716
|
+
this.transport = transport;
|
|
717
|
+
this.timeoutMs = timeoutMs;
|
|
718
|
+
this.clientInfo = clientInfo;
|
|
719
|
+
this.log = log;
|
|
720
|
+
this.extraMeta = meta;
|
|
721
|
+
this.era = null;
|
|
722
|
+
this.protocolVersion = null;
|
|
723
|
+
this.serverInfo = null;
|
|
724
|
+
this.serverCapabilities = null;
|
|
725
|
+
this.idPrefix = "intentrax-" + randomBytes(6).toString("hex") + "-";
|
|
726
|
+
this.nextId = 1;
|
|
727
|
+
this.pending = new Map();
|
|
728
|
+
this.notificationHandlers = new Set();
|
|
729
|
+
this.closeInfo = null;
|
|
730
|
+
transport.onmessage = (message) => this.#dispatch(message);
|
|
731
|
+
transport.onclose = (info) => this.#closed(info);
|
|
732
|
+
transport.onnoise = (kind) => this.log("ignored " + kind.replace(/_/g, " ") + " from the server");
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
onNotification(handler) {
|
|
736
|
+
this.notificationHandlers.add(handler);
|
|
737
|
+
return () => this.notificationHandlers.delete(handler);
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
#closed(info) {
|
|
741
|
+
this.closeInfo = info ?? {};
|
|
742
|
+
const detail = info && info.code !== null && info.code !== undefined ? " (exit code " + info.code + ")" : info?.signal ? " (signal " + info.signal + ")" : "";
|
|
743
|
+
for (const { reject, timer, method } of this.pending.values()) {
|
|
744
|
+
clearTimeout(timer);
|
|
745
|
+
reject(new McpClientError("transport_closed", "server closed the connection before answering " + method + detail));
|
|
746
|
+
}
|
|
747
|
+
this.pending.clear();
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
#dispatch(message) {
|
|
751
|
+
if (Array.isArray(message)) {
|
|
752
|
+
for (const item of message) this.#dispatch(item);
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
if (isResponse(message)) {
|
|
756
|
+
const entry = this.pending.get(message.id);
|
|
757
|
+
if (!entry) return;
|
|
758
|
+
this.pending.delete(message.id);
|
|
759
|
+
clearTimeout(entry.timer);
|
|
760
|
+
if (Object.hasOwn(message, "error")) {
|
|
761
|
+
const error = isPlainObject(message.error) ? message.error : {};
|
|
762
|
+
entry.reject(new McpClientError("rpc_error", entry.method + " failed: " + (Number.isInteger(error.code) ? error.code + " " : "") + clip(error.message ?? "error"), { rpc: { code: error.code, message: clip(error.message ?? "") } }));
|
|
763
|
+
} else {
|
|
764
|
+
entry.resolve(message.result);
|
|
765
|
+
}
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
if (isRequest(message)) {
|
|
769
|
+
// Server -> client requests: answer ping, refuse everything else. This
|
|
770
|
+
// client offers no sampling, roots or elicitation.
|
|
771
|
+
const reply = message.method === "ping"
|
|
772
|
+
? { jsonrpc: "2.0", id: message.id, result: {} }
|
|
773
|
+
: { jsonrpc: "2.0", id: message.id, error: { code: METHOD_NOT_FOUND, message: "Method not found" } };
|
|
774
|
+
this.transport.send(reply).catch(() => {});
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
if (isPlainObject(message) && typeof message.method === "string") {
|
|
778
|
+
for (const handler of this.notificationHandlers) {
|
|
779
|
+
try {
|
|
780
|
+
handler(message);
|
|
781
|
+
} catch {
|
|
782
|
+
// a handler failure must not break the client
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
#withMeta(params, modern) {
|
|
789
|
+
const base = isPlainObject(params) ? { ...params } : {};
|
|
790
|
+
if (!modern) return base;
|
|
791
|
+
const meta = isPlainObject(base._meta) ? { ...base._meta } : {};
|
|
792
|
+
meta[META_PROTOCOL_VERSION] = MODERN_PROTOCOL_VERSION;
|
|
793
|
+
if (!isPlainObject(meta[META_CLIENT_CAPABILITIES])) meta[META_CLIENT_CAPABILITIES] = {};
|
|
794
|
+
if (!isPlainObject(meta[META_CLIENT_INFO])) meta[META_CLIENT_INFO] = { ...this.clientInfo };
|
|
795
|
+
if (isPlainObject(this.extraMeta)) Object.assign(meta, this.extraMeta);
|
|
796
|
+
base._meta = meta;
|
|
797
|
+
return base;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
request(method, params = {}, { timeoutMs = this.timeoutMs, modern = this.era === "modern" } = {}) {
|
|
801
|
+
if (this.closeInfo) return Promise.reject(new McpClientError("transport_closed", "server connection is closed"));
|
|
802
|
+
const id = this.idPrefix + this.nextId++;
|
|
803
|
+
const message = { jsonrpc: "2.0", id, method, params: this.#withMeta(params, modern) };
|
|
804
|
+
return new Promise((resolve, reject) => {
|
|
805
|
+
const timer = setTimeout(() => {
|
|
806
|
+
this.pending.delete(id);
|
|
807
|
+
reject(new McpClientError("timeout", method + " got no answer within " + timeoutMs + " ms"));
|
|
808
|
+
}, timeoutMs);
|
|
809
|
+
this.pending.set(id, { resolve, reject, timer, method });
|
|
810
|
+
this.transport.send(message).catch((error) => {
|
|
811
|
+
if (!this.pending.has(id)) return;
|
|
812
|
+
this.pending.delete(id);
|
|
813
|
+
clearTimeout(timer);
|
|
814
|
+
reject(error instanceof McpClientError ? error : new McpClientError("transport_closed", "could not send " + method));
|
|
815
|
+
});
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
async notify(method, params = undefined) {
|
|
820
|
+
const message = { jsonrpc: "2.0", method };
|
|
821
|
+
if (params !== undefined) message.params = params;
|
|
822
|
+
await this.transport.send(message);
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
async close() {
|
|
826
|
+
for (const { reject, timer, method } of this.pending.values()) {
|
|
827
|
+
clearTimeout(timer);
|
|
828
|
+
reject(new McpClientError("transport_closed", "client closed before " + method + " was answered"));
|
|
829
|
+
}
|
|
830
|
+
this.pending.clear();
|
|
831
|
+
await this.transport.close();
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
// ---------------------------------------------------------------------------
|
|
836
|
+
// Connect (2026-07-28 discover, legacy initialize fallback) and list tools
|
|
837
|
+
// ---------------------------------------------------------------------------
|
|
838
|
+
|
|
839
|
+
const DISCOVER_FALLBACK_CODES = new Set(["rpc_error", "timeout", "http_status", "transport_closed", "protocol"]);
|
|
840
|
+
|
|
841
|
+
// connect(server, options) -> McpClient with era ("modern" | "legacy"),
|
|
842
|
+
// protocolVersion, serverInfo and serverCapabilities set.
|
|
843
|
+
export async function connect(server, options = {}) {
|
|
844
|
+
const spec = parseServerSpec(server);
|
|
845
|
+
const versions = options.protocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS;
|
|
846
|
+
for (const version of versions) {
|
|
847
|
+
if (!SUPPORTED_PROTOCOL_VERSIONS.includes(version)) throw new McpClientError("invalid_spec", "unsupported protocol version " + clip(version, 20));
|
|
848
|
+
}
|
|
849
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
850
|
+
const discoverTimeoutMs = options.discoverTimeoutMs ?? Math.min(timeoutMs, DEFAULT_DISCOVER_TIMEOUT_MS);
|
|
851
|
+
const open = async () => new McpClient(await openTransport(spec, { ...options, timeoutMs }), { ...options, timeoutMs });
|
|
852
|
+
let client = await open();
|
|
853
|
+
try {
|
|
854
|
+
if (versions.includes(MODERN_PROTOCOL_VERSION)) {
|
|
855
|
+
try {
|
|
856
|
+
const result = await client.request("server/discover", {}, { timeoutMs: discoverTimeoutMs, modern: true });
|
|
857
|
+
if (isPlainObject(result) && Array.isArray(result.supportedVersions) && result.supportedVersions.includes(MODERN_PROTOCOL_VERSION)) {
|
|
858
|
+
client.era = "modern";
|
|
859
|
+
client.protocolVersion = MODERN_PROTOCOL_VERSION;
|
|
860
|
+
const info = isPlainObject(result._meta) ? result._meta[META_SERVER_INFO] : undefined;
|
|
861
|
+
client.serverInfo = isPlainObject(info) ? info : isPlainObject(result.serverInfo) ? result.serverInfo : null;
|
|
862
|
+
client.serverCapabilities = isPlainObject(result.capabilities) ? result.capabilities : null;
|
|
863
|
+
return client;
|
|
864
|
+
}
|
|
865
|
+
client.log("server/discover did not offer " + MODERN_PROTOCOL_VERSION + "; using initialize");
|
|
866
|
+
} catch (error) {
|
|
867
|
+
if (!(error instanceof McpClientError) || !DISCOVER_FALLBACK_CODES.has(error.code)) throw error;
|
|
868
|
+
client.log("server/discover unavailable (" + error.code + "); using initialize");
|
|
869
|
+
if (error.code === "transport_closed") {
|
|
870
|
+
// The process died on an unknown method: start it once more.
|
|
871
|
+
await client.close().catch(() => {});
|
|
872
|
+
client = await open();
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
const legacy = LEGACY_PROTOCOL_VERSIONS.filter((version) => versions.includes(version));
|
|
877
|
+
if (legacy.length === 0) throw new McpClientError("unsupported_version", "server does not support MCP " + MODERN_PROTOCOL_VERSION);
|
|
878
|
+
const result = await client.request("initialize", {
|
|
879
|
+
protocolVersion: legacy[0],
|
|
880
|
+
capabilities: {},
|
|
881
|
+
clientInfo: { ...client.clientInfo },
|
|
882
|
+
}, { modern: false });
|
|
883
|
+
if (!isPlainObject(result) || typeof result.protocolVersion !== "string") {
|
|
884
|
+
throw new McpClientError("protocol", "initialize result has no protocolVersion");
|
|
885
|
+
}
|
|
886
|
+
if (!legacy.includes(result.protocolVersion)) {
|
|
887
|
+
throw new McpClientError("unsupported_version", "server chose protocol version " + clip(result.protocolVersion, 20) + ", which this client does not support (supported: " + versions.join(", ") + ")");
|
|
888
|
+
}
|
|
889
|
+
client.era = "legacy";
|
|
890
|
+
client.protocolVersion = result.protocolVersion;
|
|
891
|
+
client.serverInfo = isPlainObject(result.serverInfo) ? result.serverInfo : null;
|
|
892
|
+
client.serverCapabilities = isPlainObject(result.capabilities) ? result.capabilities : null;
|
|
893
|
+
await client.notify("notifications/initialized");
|
|
894
|
+
return client;
|
|
895
|
+
} catch (error) {
|
|
896
|
+
await client.close().catch(() => {});
|
|
897
|
+
throw error;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// listAllTools(client) -> { tools, pages }. Follows every nextCursor. Anything
|
|
902
|
+
// short of a complete, well-formed list is an error: pinning or checking a
|
|
903
|
+
// partial list would let a server hide a tool on a later page.
|
|
904
|
+
export async function listAllTools(client, { maxPages = DEFAULT_MAX_PAGES, timeoutMs } = {}) {
|
|
905
|
+
const tools = [];
|
|
906
|
+
const seenCursors = new Set();
|
|
907
|
+
const names = new Set();
|
|
908
|
+
let cursor;
|
|
909
|
+
let pages = 0;
|
|
910
|
+
for (;;) {
|
|
911
|
+
pages += 1;
|
|
912
|
+
if (pages > maxPages) throw new McpClientError("pagination", "tools/list returned more than " + maxPages + " pages");
|
|
913
|
+
const params = cursor === undefined ? {} : { cursor };
|
|
914
|
+
let result;
|
|
915
|
+
try {
|
|
916
|
+
result = await client.request("tools/list", params, timeoutMs === undefined ? {} : { timeoutMs });
|
|
917
|
+
} catch (error) {
|
|
918
|
+
if (pages > 1 && error instanceof McpClientError) {
|
|
919
|
+
throw new McpClientError(error.code, "tools/list page " + pages + " failed, so the list is incomplete: " + error.message);
|
|
920
|
+
}
|
|
921
|
+
throw error;
|
|
922
|
+
}
|
|
923
|
+
if (!isPlainObject(result)) throw new McpClientError("protocol", "tools/list result is not an object");
|
|
924
|
+
if (result.resultType !== undefined && result.resultType !== "complete") {
|
|
925
|
+
throw new McpClientError("protocol", "tools/list result is not complete (resultType " + clip(String(result.resultType), 30) + ")");
|
|
926
|
+
}
|
|
927
|
+
if (!Array.isArray(result.tools)) throw new McpClientError("protocol", "tools/list result has no tools array");
|
|
928
|
+
for (const tool of result.tools) {
|
|
929
|
+
if (!isPlainObject(tool) || typeof tool.name !== "string" || tool.name === "") {
|
|
930
|
+
throw new McpClientError("protocol", "tools/list returned a tool without a name");
|
|
931
|
+
}
|
|
932
|
+
if (names.has(tool.name)) throw new McpClientError("protocol", "tools/list returned the tool name " + JSON.stringify(clip(tool.name, 64)) + " twice");
|
|
933
|
+
names.add(tool.name);
|
|
934
|
+
tools.push(tool);
|
|
935
|
+
}
|
|
936
|
+
const next = result.nextCursor;
|
|
937
|
+
if (next === undefined || next === null) break;
|
|
938
|
+
if (typeof next !== "string" || next === "") throw new McpClientError("pagination", "tools/list returned an invalid nextCursor");
|
|
939
|
+
if (seenCursors.has(next)) throw new McpClientError("pagination", "tools/list repeated a cursor (pagination loop)");
|
|
940
|
+
seenCursors.add(next);
|
|
941
|
+
cursor = next;
|
|
942
|
+
}
|
|
943
|
+
return { tools, pages };
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
// listServerTools(server, options) -> { tools, pages, era, protocolVersion, serverInfo }.
|
|
947
|
+
export async function listServerTools(server, options = {}) {
|
|
948
|
+
const client = await connect(server, options);
|
|
949
|
+
try {
|
|
950
|
+
const { tools, pages } = await listAllTools(client, options);
|
|
951
|
+
return { tools, pages, era: client.era, protocolVersion: client.protocolVersion, serverInfo: client.serverInfo };
|
|
952
|
+
} finally {
|
|
953
|
+
await client.close().catch(() => {});
|
|
954
|
+
}
|
|
955
|
+
}
|