@jangmanj/pi-mcp-ext 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +93 -2
- package/package.json +52 -4
- package/src/client.ts +582 -0
- package/src/config.ts +135 -0
- package/src/events.ts +826 -0
- package/src/index.ts +1546 -0
- package/src/tasks.ts +110 -0
- package/src/transport-http.ts +144 -0
- package/src/transport-stdio.ts +644 -0
- package/src/types.ts +574 -0
|
@@ -0,0 +1,644 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import type { ChildProcessWithoutNullStreams } from "node:child_process";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { StringDecoder } from "node:string_decoder";
|
|
6
|
+
import {
|
|
7
|
+
isErrorResponse,
|
|
8
|
+
isNotification,
|
|
9
|
+
isResponse,
|
|
10
|
+
McpRpcError,
|
|
11
|
+
McpTransportError,
|
|
12
|
+
subscriptionIdOf,
|
|
13
|
+
} from "./types.ts";
|
|
14
|
+
import type {
|
|
15
|
+
JSONRPCNotification,
|
|
16
|
+
JSONRPCRequest,
|
|
17
|
+
JSONRPCResponse,
|
|
18
|
+
JSONRPCResultResponse,
|
|
19
|
+
Mcp2026Transport,
|
|
20
|
+
OpenStreamHandle,
|
|
21
|
+
RequestId,
|
|
22
|
+
ResolvedStdioServer,
|
|
23
|
+
TransportRequestOptions,
|
|
24
|
+
} from "./types.ts";
|
|
25
|
+
|
|
26
|
+
const STDERR_TAIL_LIMIT = 2_000;
|
|
27
|
+
const SHUTDOWN_WAIT_MS = 1_500;
|
|
28
|
+
const SIGKILL_WAIT_MS = 500;
|
|
29
|
+
const EXIT_DRAIN_MS = 50;
|
|
30
|
+
|
|
31
|
+
interface PendingRequest {
|
|
32
|
+
readonly id: RequestId;
|
|
33
|
+
readonly progressToken: RequestId;
|
|
34
|
+
readonly timeoutMs: number | undefined;
|
|
35
|
+
readonly onNotification: ((msg: JSONRPCNotification) => void) | undefined;
|
|
36
|
+
timer: ReturnType<typeof setTimeout> | undefined;
|
|
37
|
+
cleanupAbort: (() => void) | undefined;
|
|
38
|
+
resetTimer: () => void;
|
|
39
|
+
resolve: (res: JSONRPCResponse) => void;
|
|
40
|
+
reject: (err: McpTransportError) => void;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface ActiveStream {
|
|
44
|
+
readonly id: RequestId;
|
|
45
|
+
readonly onNotification: (msg: JSONRPCNotification) => void;
|
|
46
|
+
cleanupAbort: (() => void) | undefined;
|
|
47
|
+
resolveDone: (res: JSONRPCResultResponse | undefined) => void;
|
|
48
|
+
rejectDone: (err: Error) => void;
|
|
49
|
+
settled: boolean;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function expandHome(value: string): string {
|
|
53
|
+
if (value === "~") return homedir();
|
|
54
|
+
if (value.startsWith("~/") || value.startsWith("~\\")) {
|
|
55
|
+
return join(homedir(), value.slice(2));
|
|
56
|
+
}
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function abortReasonText(signal: AbortSignal, fallback: string): string {
|
|
61
|
+
const reason: unknown = signal.reason;
|
|
62
|
+
if (typeof reason === "string" && reason.length > 0) return reason;
|
|
63
|
+
if (reason instanceof Error && reason.message.length > 0) return reason.message;
|
|
64
|
+
return fallback;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function extractProgressToken(msg: JSONRPCRequest): RequestId {
|
|
68
|
+
const metaToken = msg.params?._meta?.["progressToken"];
|
|
69
|
+
if (typeof metaToken === "string" || typeof metaToken === "number") return metaToken;
|
|
70
|
+
const paramToken = msg.params?.["progressToken"];
|
|
71
|
+
if (typeof paramToken === "string" || typeof paramToken === "number") return paramToken;
|
|
72
|
+
return msg.id;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function waitOrTimeout(done: Promise<void>, ms: number): Promise<void> {
|
|
76
|
+
return new Promise<void>((resolveWait) => {
|
|
77
|
+
const timer = setTimeout(() => {
|
|
78
|
+
resolveWait();
|
|
79
|
+
}, ms);
|
|
80
|
+
void done.then(() => {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
resolveWait();
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function signalProcessGroup(child: ChildProcessWithoutNullStreams, signal: NodeJS.Signals): void {
|
|
88
|
+
if (child.pid !== undefined && process.platform !== "win32") {
|
|
89
|
+
try {
|
|
90
|
+
process.kill(-child.pid, signal);
|
|
91
|
+
return;
|
|
92
|
+
} catch {
|
|
93
|
+
// Fall back to direct child kill when group signalling is unavailable.
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
child.kill(signal);
|
|
98
|
+
} catch {
|
|
99
|
+
// Process has already exited.
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function createStdioTransport(
|
|
104
|
+
server: ResolvedStdioServer,
|
|
105
|
+
opts: { cwd: string; resolveValue?: (v: string) => string },
|
|
106
|
+
): Promise<Mcp2026Transport> {
|
|
107
|
+
const resolveValue = opts.resolveValue ?? ((v: string) => v);
|
|
108
|
+
const resolvedEnv: Record<string, string> = {};
|
|
109
|
+
for (const [key, rawValue] of Object.entries(server.env)) {
|
|
110
|
+
resolvedEnv[key] = resolveValue(rawValue);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const command = expandHome(server.command);
|
|
114
|
+
const args = server.args.map(expandHome);
|
|
115
|
+
const cwd = resolve(opts.cwd, expandHome(server.cwd ?? "."));
|
|
116
|
+
|
|
117
|
+
const child = spawn(command, args, {
|
|
118
|
+
cwd,
|
|
119
|
+
env: { ...process.env, ...resolvedEnv },
|
|
120
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
121
|
+
shell: false,
|
|
122
|
+
detached: process.platform !== "win32",
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
const stdoutDecoder = new StringDecoder("utf8");
|
|
126
|
+
const stderrDecoder = new StringDecoder("utf8");
|
|
127
|
+
let stdoutBuffer = "";
|
|
128
|
+
let stderrTail = "";
|
|
129
|
+
|
|
130
|
+
const requests = new Map<RequestId, PendingRequest>();
|
|
131
|
+
const streams = new Map<RequestId, ActiveStream>();
|
|
132
|
+
const unexpectedCloseListeners = new Set<(err?: Error) => void>();
|
|
133
|
+
|
|
134
|
+
let closing = false;
|
|
135
|
+
let childExited = false;
|
|
136
|
+
let terminatedHandled = false;
|
|
137
|
+
let exitCode: number | null = null;
|
|
138
|
+
let exitSignal: NodeJS.Signals | null = null;
|
|
139
|
+
let spawnError: Error | undefined;
|
|
140
|
+
let unexpectedExitError: Error | undefined;
|
|
141
|
+
let exitDrainTimer: ReturnType<typeof setTimeout> | undefined;
|
|
142
|
+
let closePromise: Promise<void> | undefined;
|
|
143
|
+
|
|
144
|
+
let resolveChildExited!: () => void;
|
|
145
|
+
const childExitedPromise = new Promise<void>((res) => {
|
|
146
|
+
resolveChildExited = res;
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
function appendStderr(text: string): void {
|
|
150
|
+
if (text.length === 0) return;
|
|
151
|
+
stderrTail += text;
|
|
152
|
+
if (stderrTail.length > STDERR_TAIL_LIMIT) {
|
|
153
|
+
stderrTail = stderrTail.slice(-STDERR_TAIL_LIMIT);
|
|
154
|
+
const first = stderrTail.charCodeAt(0);
|
|
155
|
+
if (first >= 0xdc00 && first <= 0xdfff) {
|
|
156
|
+
stderrTail = stderrTail.slice(1);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function formatWithStderr(prefix: string): string {
|
|
162
|
+
const trimmed = stderrTail.trim();
|
|
163
|
+
return trimmed.length > 0 ? `${prefix}: ${trimmed}` : prefix;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function closedErrorMessage(): string {
|
|
167
|
+
if (closing) {
|
|
168
|
+
return formatWithStderr(`MCP stdio server "${server.name}" closed`);
|
|
169
|
+
}
|
|
170
|
+
if (spawnError) {
|
|
171
|
+
return formatWithStderr(`MCP stdio server "${server.name}" error: ${spawnError.message}`);
|
|
172
|
+
}
|
|
173
|
+
const detail =
|
|
174
|
+
exitSignal !== null
|
|
175
|
+
? `signal ${exitSignal}`
|
|
176
|
+
: exitCode !== null
|
|
177
|
+
? `code ${exitCode}`
|
|
178
|
+
: "closed";
|
|
179
|
+
return formatWithStderr(`MCP stdio server "${server.name}" exited (${detail})`);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function serializeFrame(msg: JSONRPCRequest | JSONRPCNotification): string {
|
|
183
|
+
const json = JSON.stringify(msg);
|
|
184
|
+
if (json === undefined || json.includes("\n") || json.includes("\r")) {
|
|
185
|
+
throw new McpTransportError("protocol", "Serialized stdio JSON-RPC message must not contain raw CR or LF");
|
|
186
|
+
}
|
|
187
|
+
return `${json}\n`;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function writeFrame(msg: JSONRPCRequest | JSONRPCNotification): Promise<void> {
|
|
191
|
+
if (closing || childExited || terminatedHandled || child.stdin.destroyed || !child.stdin.writable) {
|
|
192
|
+
return Promise.reject(new McpTransportError("closed", closedErrorMessage()));
|
|
193
|
+
}
|
|
194
|
+
let frame: string;
|
|
195
|
+
try {
|
|
196
|
+
frame = serializeFrame(msg);
|
|
197
|
+
} catch (err) {
|
|
198
|
+
return Promise.reject(
|
|
199
|
+
err instanceof McpTransportError
|
|
200
|
+
? err
|
|
201
|
+
: new McpTransportError("protocol", err instanceof Error ? err.message : String(err)),
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
return new Promise<void>((resolveWrite, rejectWrite) => {
|
|
205
|
+
let settled = false;
|
|
206
|
+
const onExit = (): void => {
|
|
207
|
+
if (settled) return;
|
|
208
|
+
settled = true;
|
|
209
|
+
rejectWrite(new McpTransportError("closed", closedErrorMessage()));
|
|
210
|
+
};
|
|
211
|
+
void childExitedPromise.then(onExit);
|
|
212
|
+
child.stdin.write(frame, "utf8", (err) => {
|
|
213
|
+
if (settled) return;
|
|
214
|
+
settled = true;
|
|
215
|
+
if (err) {
|
|
216
|
+
rejectWrite(new McpTransportError("closed", formatWithStderr(`MCP stdio write failed: ${err.message}`)));
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
resolveWrite();
|
|
220
|
+
});
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function sendCancelled(requestId: RequestId, reason?: string): Promise<void> {
|
|
225
|
+
if (closing || childExited || terminatedHandled || child.stdin.destroyed || !child.stdin.writable) {
|
|
226
|
+
return Promise.resolve();
|
|
227
|
+
}
|
|
228
|
+
const params: Record<string, unknown> =
|
|
229
|
+
reason !== undefined ? { requestId, reason } : { requestId };
|
|
230
|
+
const notification: JSONRPCNotification = {
|
|
231
|
+
jsonrpc: "2.0",
|
|
232
|
+
method: "notifications/cancelled",
|
|
233
|
+
params,
|
|
234
|
+
};
|
|
235
|
+
return writeFrame(notification).catch(() => {});
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function findPendingByProgressToken(token: RequestId): PendingRequest | undefined {
|
|
239
|
+
for (const entry of requests.values()) {
|
|
240
|
+
if (entry.progressToken === token) return entry;
|
|
241
|
+
}
|
|
242
|
+
return undefined;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function handleMessage(msg: unknown): void {
|
|
246
|
+
if (isResponse(msg)) {
|
|
247
|
+
const id = msg.id;
|
|
248
|
+
if (typeof id !== "string" && typeof id !== "number") return;
|
|
249
|
+
|
|
250
|
+
const pending = requests.get(id);
|
|
251
|
+
if (pending) {
|
|
252
|
+
requests.delete(id);
|
|
253
|
+
if (pending.timer !== undefined) clearTimeout(pending.timer);
|
|
254
|
+
pending.cleanupAbort?.();
|
|
255
|
+
pending.resolve(msg);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const stream = streams.get(id);
|
|
260
|
+
if (stream && !stream.settled) {
|
|
261
|
+
stream.settled = true;
|
|
262
|
+
streams.delete(id);
|
|
263
|
+
stream.cleanupAbort?.();
|
|
264
|
+
if (isErrorResponse(msg)) {
|
|
265
|
+
stream.rejectDone(new McpRpcError(msg.error));
|
|
266
|
+
} else {
|
|
267
|
+
stream.resolveDone(msg);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (isNotification(msg)) {
|
|
274
|
+
if (msg.method === "notifications/progress") {
|
|
275
|
+
const token = msg.params?.["progressToken"];
|
|
276
|
+
if (typeof token === "string" || typeof token === "number") {
|
|
277
|
+
const pending = findPendingByProgressToken(token);
|
|
278
|
+
if (pending) {
|
|
279
|
+
pending.resetTimer();
|
|
280
|
+
pending.onNotification?.(msg);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const subId = subscriptionIdOf(msg);
|
|
287
|
+
if (subId !== undefined) {
|
|
288
|
+
const stream = streams.get(subId);
|
|
289
|
+
if (stream && !stream.settled) {
|
|
290
|
+
stream.onNotification(msg);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function handleLine(rawLine: string): void {
|
|
297
|
+
const trimmed = rawLine.trim();
|
|
298
|
+
if (trimmed.length === 0) return;
|
|
299
|
+
let parsed: unknown;
|
|
300
|
+
try {
|
|
301
|
+
parsed = JSON.parse(rawLine);
|
|
302
|
+
} catch {
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
handleMessage(parsed);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function drainStdout(flush: boolean): void {
|
|
309
|
+
let newlineIndex = stdoutBuffer.indexOf("\n");
|
|
310
|
+
while (newlineIndex !== -1) {
|
|
311
|
+
let line = stdoutBuffer.slice(0, newlineIndex);
|
|
312
|
+
stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1);
|
|
313
|
+
if (line.endsWith("\r")) line = line.slice(0, -1);
|
|
314
|
+
if (line.length > 0) {
|
|
315
|
+
handleLine(line);
|
|
316
|
+
}
|
|
317
|
+
newlineIndex = stdoutBuffer.indexOf("\n");
|
|
318
|
+
}
|
|
319
|
+
if (flush && stdoutBuffer.length > 0) {
|
|
320
|
+
let line = stdoutBuffer;
|
|
321
|
+
stdoutBuffer = "";
|
|
322
|
+
if (line.endsWith("\r")) line = line.slice(0, -1);
|
|
323
|
+
if (line.length > 0) {
|
|
324
|
+
handleLine(line);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function settleAllInFlight(err: McpTransportError): void {
|
|
330
|
+
const pendingEntries = [...requests.values()];
|
|
331
|
+
requests.clear();
|
|
332
|
+
for (const entry of pendingEntries) {
|
|
333
|
+
if (entry.timer !== undefined) clearTimeout(entry.timer);
|
|
334
|
+
entry.cleanupAbort?.();
|
|
335
|
+
entry.reject(err);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const activeStreams = [...streams.values()];
|
|
339
|
+
streams.clear();
|
|
340
|
+
for (const stream of activeStreams) {
|
|
341
|
+
if (!stream.settled) {
|
|
342
|
+
stream.settled = true;
|
|
343
|
+
stream.cleanupAbort?.();
|
|
344
|
+
stream.resolveDone(undefined);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function finalizeTermination(): void {
|
|
350
|
+
if (terminatedHandled) return;
|
|
351
|
+
terminatedHandled = true;
|
|
352
|
+
if (exitDrainTimer !== undefined) {
|
|
353
|
+
clearTimeout(exitDrainTimer);
|
|
354
|
+
exitDrainTimer = undefined;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
stdoutBuffer += stdoutDecoder.end();
|
|
358
|
+
drainStdout(true);
|
|
359
|
+
appendStderr(stderrDecoder.end());
|
|
360
|
+
|
|
361
|
+
const err = new McpTransportError("closed", closedErrorMessage());
|
|
362
|
+
settleAllInFlight(err);
|
|
363
|
+
|
|
364
|
+
if (!closing) {
|
|
365
|
+
unexpectedExitError = err;
|
|
366
|
+
for (const listener of [...unexpectedCloseListeners]) {
|
|
367
|
+
listener(err);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
child.stdin.on("error", () => {
|
|
373
|
+
// Handled per-write and on process exit.
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
child.stdout.on("data", (chunk: Buffer) => {
|
|
377
|
+
stdoutBuffer += stdoutDecoder.write(chunk);
|
|
378
|
+
drainStdout(false);
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
child.stdout.on("end", () => {
|
|
382
|
+
stdoutBuffer += stdoutDecoder.end();
|
|
383
|
+
drainStdout(true);
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
child.stderr.on("data", (chunk: Buffer) => {
|
|
387
|
+
appendStderr(stderrDecoder.write(chunk));
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
child.stderr.on("end", () => {
|
|
391
|
+
appendStderr(stderrDecoder.end());
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
await new Promise<void>((resolveSpawn, rejectSpawn) => {
|
|
395
|
+
let settled = false;
|
|
396
|
+
|
|
397
|
+
child.once("spawn", () => {
|
|
398
|
+
if (settled) return;
|
|
399
|
+
settled = true;
|
|
400
|
+
resolveSpawn();
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
child.on("error", (err: Error) => {
|
|
404
|
+
spawnError = err;
|
|
405
|
+
if (!settled) {
|
|
406
|
+
settled = true;
|
|
407
|
+
childExited = true;
|
|
408
|
+
resolveChildExited();
|
|
409
|
+
terminatedHandled = true;
|
|
410
|
+
rejectSpawn(
|
|
411
|
+
new McpTransportError(
|
|
412
|
+
"closed",
|
|
413
|
+
formatWithStderr(`Failed to spawn MCP stdio server "${server.name}": ${err.message}`),
|
|
414
|
+
),
|
|
415
|
+
);
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
if (!terminatedHandled) {
|
|
419
|
+
finalizeTermination();
|
|
420
|
+
}
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
child.once("exit", (code, signal) => {
|
|
424
|
+
exitCode = code;
|
|
425
|
+
exitSignal = signal;
|
|
426
|
+
childExited = true;
|
|
427
|
+
resolveChildExited();
|
|
428
|
+
if (!terminatedHandled && exitDrainTimer === undefined) {
|
|
429
|
+
exitDrainTimer = setTimeout(() => {
|
|
430
|
+
finalizeTermination();
|
|
431
|
+
}, EXIT_DRAIN_MS);
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
child.once("close", (code, signal) => {
|
|
436
|
+
if (exitCode === null) exitCode = code;
|
|
437
|
+
if (exitSignal === null) exitSignal = signal;
|
|
438
|
+
if (!childExited) {
|
|
439
|
+
childExited = true;
|
|
440
|
+
resolveChildExited();
|
|
441
|
+
}
|
|
442
|
+
finalizeTermination();
|
|
443
|
+
});
|
|
444
|
+
});
|
|
445
|
+
|
|
446
|
+
return {
|
|
447
|
+
kind: "stdio",
|
|
448
|
+
|
|
449
|
+
request(msg: JSONRPCRequest, reqOpts?: TransportRequestOptions): Promise<JSONRPCResponse> {
|
|
450
|
+
if (closing || childExited || terminatedHandled) {
|
|
451
|
+
return Promise.reject(new McpTransportError("closed", closedErrorMessage()));
|
|
452
|
+
}
|
|
453
|
+
const signal = reqOpts?.signal;
|
|
454
|
+
if (signal?.aborted) {
|
|
455
|
+
return Promise.reject(new McpTransportError("aborted", abortReasonText(signal, "Request aborted")));
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const timeoutMs = reqOpts?.timeoutMs;
|
|
459
|
+
const progressToken = extractProgressToken(msg);
|
|
460
|
+
|
|
461
|
+
return new Promise<JSONRPCResponse>((resolveReq, rejectReq) => {
|
|
462
|
+
const entry: PendingRequest = {
|
|
463
|
+
id: msg.id,
|
|
464
|
+
progressToken,
|
|
465
|
+
timeoutMs,
|
|
466
|
+
onNotification: reqOpts?.onNotification,
|
|
467
|
+
timer: undefined,
|
|
468
|
+
cleanupAbort: undefined,
|
|
469
|
+
resetTimer: () => {
|
|
470
|
+
if (timeoutMs === undefined) return;
|
|
471
|
+
if (entry.timer !== undefined) clearTimeout(entry.timer);
|
|
472
|
+
entry.timer = setTimeout(() => {
|
|
473
|
+
if (!requests.delete(msg.id)) return;
|
|
474
|
+
entry.cleanupAbort?.();
|
|
475
|
+
const reason = `Request ${String(msg.id)} timed out after ${timeoutMs}ms`;
|
|
476
|
+
void sendCancelled(msg.id, reason);
|
|
477
|
+
rejectReq(new McpTransportError("timeout", formatWithStderr(reason)));
|
|
478
|
+
}, timeoutMs);
|
|
479
|
+
},
|
|
480
|
+
resolve: resolveReq,
|
|
481
|
+
reject: rejectReq,
|
|
482
|
+
};
|
|
483
|
+
|
|
484
|
+
if (signal) {
|
|
485
|
+
const onAbort = (): void => {
|
|
486
|
+
if (!requests.delete(msg.id)) return;
|
|
487
|
+
if (entry.timer !== undefined) clearTimeout(entry.timer);
|
|
488
|
+
const reason = abortReasonText(signal, "Request aborted");
|
|
489
|
+
void sendCancelled(msg.id, reason);
|
|
490
|
+
rejectReq(new McpTransportError("aborted", reason));
|
|
491
|
+
};
|
|
492
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
493
|
+
entry.cleanupAbort = () => {
|
|
494
|
+
signal.removeEventListener("abort", onAbort);
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
entry.resetTimer();
|
|
499
|
+
requests.set(msg.id, entry);
|
|
500
|
+
|
|
501
|
+
void writeFrame(msg).catch((err: unknown) => {
|
|
502
|
+
if (!requests.delete(msg.id)) return;
|
|
503
|
+
if (entry.timer !== undefined) clearTimeout(entry.timer);
|
|
504
|
+
entry.cleanupAbort?.();
|
|
505
|
+
rejectReq(
|
|
506
|
+
err instanceof McpTransportError
|
|
507
|
+
? err
|
|
508
|
+
: new McpTransportError("closed", err instanceof Error ? err.message : String(err)),
|
|
509
|
+
);
|
|
510
|
+
});
|
|
511
|
+
});
|
|
512
|
+
},
|
|
513
|
+
|
|
514
|
+
async openStream(
|
|
515
|
+
msg: JSONRPCRequest,
|
|
516
|
+
onNotification: (msg: JSONRPCNotification) => void,
|
|
517
|
+
streamOpts?: { signal?: AbortSignal; headers?: Record<string, string> },
|
|
518
|
+
): Promise<OpenStreamHandle> {
|
|
519
|
+
if (closing || childExited || terminatedHandled) {
|
|
520
|
+
throw new McpTransportError("closed", closedErrorMessage());
|
|
521
|
+
}
|
|
522
|
+
const signal = streamOpts?.signal;
|
|
523
|
+
if (signal?.aborted) {
|
|
524
|
+
throw new McpTransportError("aborted", abortReasonText(signal, "Stream aborted"));
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
let resolveDone!: (res: JSONRPCResultResponse | undefined) => void;
|
|
528
|
+
let rejectDone!: (err: Error) => void;
|
|
529
|
+
const done = new Promise<JSONRPCResultResponse | undefined>((res, rej) => {
|
|
530
|
+
resolveDone = res;
|
|
531
|
+
rejectDone = rej;
|
|
532
|
+
});
|
|
533
|
+
done.catch(() => {});
|
|
534
|
+
|
|
535
|
+
const stream: ActiveStream = {
|
|
536
|
+
id: msg.id,
|
|
537
|
+
onNotification,
|
|
538
|
+
cleanupAbort: undefined,
|
|
539
|
+
resolveDone,
|
|
540
|
+
rejectDone,
|
|
541
|
+
settled: false,
|
|
542
|
+
};
|
|
543
|
+
|
|
544
|
+
const cancel = async (reason?: string): Promise<void> => {
|
|
545
|
+
if (stream.settled) return;
|
|
546
|
+
stream.settled = true;
|
|
547
|
+
streams.delete(msg.id);
|
|
548
|
+
stream.cleanupAbort?.();
|
|
549
|
+
stream.resolveDone(undefined);
|
|
550
|
+
await sendCancelled(msg.id, reason);
|
|
551
|
+
};
|
|
552
|
+
|
|
553
|
+
if (signal) {
|
|
554
|
+
const onAbort = (): void => {
|
|
555
|
+
void cancel(abortReasonText(signal, "Stream aborted"));
|
|
556
|
+
};
|
|
557
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
558
|
+
stream.cleanupAbort = () => {
|
|
559
|
+
signal.removeEventListener("abort", onAbort);
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
streams.set(msg.id, stream);
|
|
564
|
+
|
|
565
|
+
try {
|
|
566
|
+
await writeFrame(msg);
|
|
567
|
+
} catch (err) {
|
|
568
|
+
if (!stream.settled) {
|
|
569
|
+
stream.settled = true;
|
|
570
|
+
streams.delete(msg.id);
|
|
571
|
+
stream.cleanupAbort?.();
|
|
572
|
+
stream.resolveDone(undefined);
|
|
573
|
+
}
|
|
574
|
+
throw err instanceof McpTransportError
|
|
575
|
+
? err
|
|
576
|
+
: new McpTransportError("closed", err instanceof Error ? err.message : String(err));
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
if (signal?.aborted) {
|
|
580
|
+
const reason = abortReasonText(signal, "Stream aborted");
|
|
581
|
+
await cancel(reason);
|
|
582
|
+
throw new McpTransportError("aborted", reason);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
return {
|
|
586
|
+
requestId: msg.id,
|
|
587
|
+
done,
|
|
588
|
+
cancel,
|
|
589
|
+
};
|
|
590
|
+
},
|
|
591
|
+
|
|
592
|
+
onUnexpectedClose(listener: (err?: Error) => void): () => void {
|
|
593
|
+
let active = true;
|
|
594
|
+
unexpectedCloseListeners.add(listener);
|
|
595
|
+
if (unexpectedExitError !== undefined && !closing) {
|
|
596
|
+
const err = unexpectedExitError;
|
|
597
|
+
queueMicrotask(() => {
|
|
598
|
+
if (active && !closing) {
|
|
599
|
+
listener(err);
|
|
600
|
+
}
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
return () => {
|
|
604
|
+
active = false;
|
|
605
|
+
unexpectedCloseListeners.delete(listener);
|
|
606
|
+
};
|
|
607
|
+
},
|
|
608
|
+
|
|
609
|
+
close(): Promise<void> {
|
|
610
|
+
if (closePromise) return closePromise;
|
|
611
|
+
closing = true;
|
|
612
|
+
|
|
613
|
+
closePromise = (async () => {
|
|
614
|
+
settleAllInFlight(new McpTransportError("closed", closedErrorMessage()));
|
|
615
|
+
|
|
616
|
+
if (!childExited) {
|
|
617
|
+
try {
|
|
618
|
+
child.stdin.end();
|
|
619
|
+
} catch {
|
|
620
|
+
// Ignore stdin close errors.
|
|
621
|
+
}
|
|
622
|
+
await waitOrTimeout(childExitedPromise, SHUTDOWN_WAIT_MS);
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
if (!childExited) {
|
|
626
|
+
signalProcessGroup(child, "SIGTERM");
|
|
627
|
+
await waitOrTimeout(childExitedPromise, SHUTDOWN_WAIT_MS);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
if (!childExited) {
|
|
631
|
+
signalProcessGroup(child, "SIGKILL");
|
|
632
|
+
await waitOrTimeout(childExitedPromise, SIGKILL_WAIT_MS);
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
finalizeTermination();
|
|
636
|
+
child.stdin.destroy();
|
|
637
|
+
child.stdout.destroy();
|
|
638
|
+
child.stderr.destroy();
|
|
639
|
+
})();
|
|
640
|
+
|
|
641
|
+
return closePromise;
|
|
642
|
+
},
|
|
643
|
+
};
|
|
644
|
+
}
|