pi-mcp-extension 1.16.5 → 1.16.6
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 +2 -1
- package/package.json +1 -1
- package/src/connect-policy.ts +35 -1
- package/src/mcp-client.ts +7 -1
- package/src/stdio-exit-guard.ts +349 -0
- package/src/stdio-process.ts +80 -29
package/README.md
CHANGED
|
@@ -351,7 +351,8 @@ Recent output:
|
|
|
351
351
|
|
|
352
352
|
### OAuth startup, headless/SSH, and concurrency behavior
|
|
353
353
|
|
|
354
|
-
- **
|
|
354
|
+
- **Authorization by Pi mode**: TUI and RPC (`--mode rpc`) support interactive OAuth authorization. In RPC mode, Pi sends `extension_ui_request` (`select` / `input`) events that the RPC host must answer or cancel via `extension_ui_response` (`{"value": "..."}` or `{"cancelled": true}`). Print (`-p` / `--print`) and JSON (`--mode json`) cannot show interactive dialogs and fail promptly when browser authorization is required.
|
|
355
|
+
- **Serialized OAuth dialogs in RPC**: An unanswered startup prompt holds the interactive authorization queue for subsequent OAuth flows until the RPC host answers or cancels the dialog, or stops that server with `/mcp:stop <name>`; non-OAuth servers and OAuth servers with valid stored tokens can connect without waiting.
|
|
355
356
|
- **Startup prompt for eager OAuth servers**: Silent startup and background reconnects never open a browser unprompted or trigger Dynamic Client Registration when no client credentials are stored. When an `eager` OAuth server needs interactive authorization at startup in an interactive Pi session, Pi presents a sequential `<name> needs authorization` prompt (`Authorize now` / `Not now`). Choosing `Authorize now` runs the interactive OAuth flow; choosing `Not now` leaves the server stopped, shows a `run /mcp:auth <name>` footer hint, and remembers the decline for the rest of the session.
|
|
356
357
|
- **Headless and SSH support**: While authorization is pending, Pi displays the authorization URL and offers `Retry: open browser again`, `Paste redirect URL`, and `Cancel authentication`. On remote/SSH or headless machines, open the URL locally and either forward the callback port (`ssh -L <port>:127.0.0.1:<port>`) or paste the browser's final `http://127.0.0.1:<port>/callback?code=...&state=...` redirect URL into `Paste redirect URL`. Only `https:` (or loopback `http:`) authorization URLs are passed to the system browser opener.
|
|
357
358
|
- **Coordinated connects and cross-process locks**: Concurrent connect requests join an in-flight attempt, while `--reset` supersedes a normal connect and shares one pending reset. Cross-process interactive flows are serialized per server via `<agent dir>/mcp-auth/<hash>.json.lock` with a 30s heartbeat and automatic reclamation of locks from dead local PIDs or stale heartbeats (>90s), while allowing silent token refreshes to persist rotated tokens.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-mcp-extension",
|
|
3
|
-
"version": "1.16.
|
|
3
|
+
"version": "1.16.6",
|
|
4
4
|
"description": "Full-featured, lightweight MCP extension for the Pi coding agent: stdio, SSE & Streamable HTTP transports, OAuth 2.1 (PKCE + DCR), lazy/eager lifecycles — minimal dependencies, zero bloat.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
package/src/connect-policy.ts
CHANGED
|
@@ -351,6 +351,40 @@ export interface ClassifyConnectFailureInput {
|
|
|
351
351
|
serverName?: string;
|
|
352
352
|
}
|
|
353
353
|
|
|
354
|
+
/**
|
|
355
|
+
* Local OS spawn errnos on `stdio` that cannot succeed on retry without user intervention
|
|
356
|
+
* (missing binary/cwd, missing execute permission, invalid binary format, or bad path type).
|
|
357
|
+
*/
|
|
358
|
+
const NON_RETRYABLE_STDIO_SPAWN_CODES = new Set([
|
|
359
|
+
"ENOENT",
|
|
360
|
+
"EACCES",
|
|
361
|
+
"ENOEXEC",
|
|
362
|
+
"ENOTDIR",
|
|
363
|
+
"EISDIR",
|
|
364
|
+
]);
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Whether `error` is a deterministic local OS spawn failure on `stdio` that cannot
|
|
368
|
+
* succeed on retry without user intervention.
|
|
369
|
+
*/
|
|
370
|
+
export function isNonRetryableStdioSpawnError(
|
|
371
|
+
transport: TransportType,
|
|
372
|
+
error: unknown,
|
|
373
|
+
): boolean {
|
|
374
|
+
if (transport !== "stdio" || typeof error !== "object" || error === null) {
|
|
375
|
+
return false;
|
|
376
|
+
}
|
|
377
|
+
const code = (error as { code?: unknown }).code;
|
|
378
|
+
return typeof code === "string" && NON_RETRYABLE_STDIO_SPAWN_CODES.has(code);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function isFastFailConnectError(input: ClassifyConnectFailureInput, error: Error): boolean {
|
|
382
|
+
if (error instanceof McpError) {
|
|
383
|
+
return error.code === "protocol" || error.code === "config";
|
|
384
|
+
}
|
|
385
|
+
return isNonRetryableStdioSpawnError(input.transport, input.error);
|
|
386
|
+
}
|
|
387
|
+
|
|
354
388
|
function classifyOAuthFailure(
|
|
355
389
|
input: ClassifyConnectFailureInput,
|
|
356
390
|
error: Error,
|
|
@@ -387,7 +421,7 @@ function classifyPreRetryFailure(
|
|
|
387
421
|
const oauthAction = classifyOAuthFailure(input, error);
|
|
388
422
|
if (oauthAction) return oauthAction;
|
|
389
423
|
|
|
390
|
-
if (
|
|
424
|
+
if (isFastFailConnectError(input, error)) {
|
|
391
425
|
return { kind: "fail", error };
|
|
392
426
|
}
|
|
393
427
|
|
package/src/mcp-client.ts
CHANGED
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
21
|
import { basename } from "node:path";
|
|
22
|
+
import { getStdioSpawnError } from "./stdio-process.js";
|
|
22
23
|
import { pathToFileURL } from "node:url";
|
|
23
24
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
24
25
|
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
@@ -188,7 +189,12 @@ export async function connectClientWithTimeout(
|
|
|
188
189
|
try {
|
|
189
190
|
await Promise.race([connectPromise, guard.outcome]);
|
|
190
191
|
} catch (err) {
|
|
191
|
-
rethrowNormalizedConnectError(
|
|
192
|
+
rethrowNormalizedConnectError(
|
|
193
|
+
getStdioSpawnError(transport) ?? err,
|
|
194
|
+
signal,
|
|
195
|
+
serverName,
|
|
196
|
+
timeoutMs,
|
|
197
|
+
);
|
|
192
198
|
} finally {
|
|
193
199
|
guard.dispose();
|
|
194
200
|
}
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Synchronous process-level `SIGINT` / `exit` safety net for live stdio child trees.
|
|
3
|
+
*
|
|
4
|
+
* In headless Pi modes (`--mode rpc`, `--mode json`, `--print`), Pi binds graceful
|
|
5
|
+
* shutdown only to `SIGTERM` and `SIGHUP`. When `SIGINT` arrives with no active host
|
|
6
|
+
* handler, Node exits via default `SIGINT` disposition without firing `session_shutdown`.
|
|
7
|
+
* This module tracks live stdio root PIDs and terminates their process trees synchronously
|
|
8
|
+
* when unhandled `SIGINT` or unexpected `exit` fires, while yielding to active host
|
|
9
|
+
* handlers (such as interactive TUI `Ctrl+Z` suspend) and ignoring passive `signal-exit`
|
|
10
|
+
* wrappers.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
14
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
15
|
+
|
|
16
|
+
const MAX_DESCENDANTS = 256;
|
|
17
|
+
const PS_SYNC_TIMEOUT_MS = 250;
|
|
18
|
+
const TASKKILL_TIMEOUT_MS = 500;
|
|
19
|
+
const SIGNAL_EXIT_V4_SYMBOL = Symbol.for("signal-exit emitter");
|
|
20
|
+
|
|
21
|
+
export interface SignalExitProcess {
|
|
22
|
+
pid: number;
|
|
23
|
+
on(event: "SIGINT", listener: () => void): unknown;
|
|
24
|
+
on(event: "exit", listener: (code: number) => void): unknown;
|
|
25
|
+
off(event: "SIGINT", listener: () => void): unknown;
|
|
26
|
+
off(event: "exit", listener: (code: number) => void): unknown;
|
|
27
|
+
listenerCount(event: "SIGINT" | "exit"): number;
|
|
28
|
+
kill(pid: number, signal?: NodeJS.Signals | number): boolean;
|
|
29
|
+
exit(code?: number): never;
|
|
30
|
+
__signal_exit_emitter__?: unknown;
|
|
31
|
+
[key: symbol]: unknown;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface SyncTreeTerminationDeps {
|
|
35
|
+
platform: NodeJS.Platform;
|
|
36
|
+
kill: (pid: number, signal?: NodeJS.Signals | number) => void | boolean;
|
|
37
|
+
spawnSync: typeof spawnSync;
|
|
38
|
+
listDescendantPidsSync: (pid: number) => number[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface StdioExitGuardDeps {
|
|
42
|
+
proc: SignalExitProcess;
|
|
43
|
+
globalScope?: unknown;
|
|
44
|
+
terminatePidTreeSync: (pid: number) => void;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function readPositiveCount(holder: unknown): number {
|
|
48
|
+
const count = (holder as { count?: unknown } | undefined)?.count;
|
|
49
|
+
return typeof count === "number" && Number.isInteger(count) && count > 0 ? count : 0;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function resolveGlobalScope(proc: unknown, globalScope?: unknown): unknown {
|
|
53
|
+
if (globalScope !== undefined) return globalScope;
|
|
54
|
+
return proc === process ? globalThis : undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Count passive `signal-exit` v3/v4 `SIGINT` listeners attached to `proc`.
|
|
59
|
+
*
|
|
60
|
+
* WHY: Pi 1.3.0 bundles `signal-exit` v3 (via `proper-lockfile`), which stores its emitter on
|
|
61
|
+
* `process.__signal_exit_emitter__`, while `signal-exit` v4 stores its emitter on
|
|
62
|
+
* `globalThis[Symbol.for("signal-exit emitter")]`. Both register passive `SIGINT` listeners
|
|
63
|
+
* that only act when `listeners.length === count`. Subtracting those passive wrappers lets our
|
|
64
|
+
* guard detect whether an active host handler (such as Pi TUI's `Ctrl+Z` `ignoreSigint`) owns
|
|
65
|
+
* `SIGINT` without deadlocking in headless `rpc`/`json`/`print` modes.
|
|
66
|
+
*/
|
|
67
|
+
export function countPassiveSigintListeners(proc: unknown, globalScope?: unknown): number {
|
|
68
|
+
if (!proc || typeof proc !== "object") return 0;
|
|
69
|
+
const v3 = (proc as { __signal_exit_emitter__?: unknown }).__signal_exit_emitter__;
|
|
70
|
+
const scope = resolveGlobalScope(proc, globalScope);
|
|
71
|
+
const v4 =
|
|
72
|
+
scope && typeof scope === "object"
|
|
73
|
+
? (scope as Record<symbol, unknown>)[SIGNAL_EXIT_V4_SYMBOL]
|
|
74
|
+
: undefined;
|
|
75
|
+
return readPositiveCount(v3) + readPositiveCount(v4);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Index `ps -A -o pid=,ppid=` output as a parent PID → child PIDs map. */
|
|
79
|
+
export function indexProcessTable(stdout: string): Map<number, number[]> {
|
|
80
|
+
const childrenOf = new Map<number, number[]>();
|
|
81
|
+
for (const line of stdout.split("\n")) {
|
|
82
|
+
const match = /^\s*(\d+)\s+(\d+)\s*$/.exec(line);
|
|
83
|
+
if (!match) continue;
|
|
84
|
+
const childPid = Number(match[1]);
|
|
85
|
+
const parentPid = Number(match[2]);
|
|
86
|
+
const siblings = childrenOf.get(parentPid);
|
|
87
|
+
if (siblings) {
|
|
88
|
+
siblings.push(childPid);
|
|
89
|
+
} else {
|
|
90
|
+
childrenOf.set(parentPid, [childPid]);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return childrenOf;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function readTaskIdsSync(taskDir: string): string[] {
|
|
97
|
+
try {
|
|
98
|
+
return readdirSync(taskDir);
|
|
99
|
+
} catch {
|
|
100
|
+
// WHY: Best-effort sync /proc walk during signal/exit; a child can exit before its task dir is read.
|
|
101
|
+
return [];
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function readChildrenFileSync(path: string): string {
|
|
106
|
+
try {
|
|
107
|
+
return readFileSync(path, "utf8");
|
|
108
|
+
} catch {
|
|
109
|
+
// WHY: Best-effort sync /proc walk during signal/exit; a thread or process can exit mid-walk.
|
|
110
|
+
return "";
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function readProcChildrenSync(pid: number): number[] {
|
|
115
|
+
const taskDir = `/proc/${pid}/task`;
|
|
116
|
+
const tids = readTaskIdsSync(taskDir);
|
|
117
|
+
const children: number[] = [];
|
|
118
|
+
for (const tid of tids) {
|
|
119
|
+
const raw = readChildrenFileSync(`${taskDir}/${tid}/children`);
|
|
120
|
+
for (const token of raw.split(/\s+/)) {
|
|
121
|
+
const childPid = Number(token);
|
|
122
|
+
if (token && Number.isInteger(childPid) && childPid > 0) {
|
|
123
|
+
children.push(childPid);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return children;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function readPsProcessTableSync(): Map<number, number[]> {
|
|
131
|
+
try {
|
|
132
|
+
const stdout = execFileSync("ps", ["-A", "-o", "pid=,ppid="], {
|
|
133
|
+
encoding: "utf8",
|
|
134
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
135
|
+
timeout: PS_SYNC_TIMEOUT_MS,
|
|
136
|
+
});
|
|
137
|
+
return indexProcessTable(stdout);
|
|
138
|
+
} catch {
|
|
139
|
+
// WHY: Best-effort sync discovery during signal/exit; cache an empty table so one missing or
|
|
140
|
+
// slow `ps` does not stall remaining roots, which still receive SIGTERM directly.
|
|
141
|
+
return new Map();
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function createSyncChildReader(platform: NodeJS.Platform = process.platform): (pid: number) => number[] {
|
|
146
|
+
if (platform === "linux") return readProcChildrenSync;
|
|
147
|
+
if (platform === "win32") return () => [];
|
|
148
|
+
let table: Map<number, number[]> | null = null;
|
|
149
|
+
return (pid: number): number[] => {
|
|
150
|
+
table ??= readPsProcessTableSync();
|
|
151
|
+
return table.get(pid) ?? [];
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function readChildrenSafe(pid: number, readChildren: (pid: number) => number[]): number[] {
|
|
156
|
+
try {
|
|
157
|
+
return readChildren(pid);
|
|
158
|
+
} catch {
|
|
159
|
+
// WHY: Best-effort sync discovery during signal/exit; one exited child must not abort sibling discovery.
|
|
160
|
+
return [];
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function walkDescendantsSync(pid: number, readChildren: (pid: number) => number[]): number[] {
|
|
165
|
+
const descendants: number[] = [];
|
|
166
|
+
const seen = new Set<number>([pid]);
|
|
167
|
+
const pending = [...readChildrenSafe(pid, readChildren)];
|
|
168
|
+
while (pending.length > 0 && descendants.length < MAX_DESCENDANTS) {
|
|
169
|
+
const next = pending.shift();
|
|
170
|
+
if (next === undefined || seen.has(next)) continue;
|
|
171
|
+
seen.add(next);
|
|
172
|
+
descendants.push(next);
|
|
173
|
+
pending.push(...readChildrenSafe(next, readChildren));
|
|
174
|
+
}
|
|
175
|
+
return descendants;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Synchronously snapshot descendant PIDs of `pid`, deepest generation first.
|
|
180
|
+
* Used during `SIGINT` / `exit` cleanup where async awaits cannot run.
|
|
181
|
+
*/
|
|
182
|
+
export function listDescendantPidsSync(
|
|
183
|
+
pid: number,
|
|
184
|
+
readChildren?: (pid: number) => number[],
|
|
185
|
+
platform: NodeJS.Platform = process.platform,
|
|
186
|
+
): number[] {
|
|
187
|
+
const reader = readChildren ?? createSyncChildReader(platform);
|
|
188
|
+
return walkDescendantsSync(pid, reader).reverse();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function trySignalSync(
|
|
192
|
+
pid: number,
|
|
193
|
+
signal: NodeJS.Signals,
|
|
194
|
+
kill: SyncTreeTerminationDeps["kill"],
|
|
195
|
+
): void {
|
|
196
|
+
try {
|
|
197
|
+
kill(pid, signal);
|
|
198
|
+
} catch {
|
|
199
|
+
// WHY: Best-effort teardown during SIGINT/exit; ESRCH/EPERM must not abort sibling cleanup.
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function killWindowsTreeSync(
|
|
204
|
+
pid: number,
|
|
205
|
+
runSpawnSync: typeof spawnSync,
|
|
206
|
+
kill: SyncTreeTerminationDeps["kill"],
|
|
207
|
+
): void {
|
|
208
|
+
try {
|
|
209
|
+
const result = runSpawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], {
|
|
210
|
+
stdio: "ignore",
|
|
211
|
+
windowsHide: true,
|
|
212
|
+
timeout: TASKKILL_TIMEOUT_MS,
|
|
213
|
+
});
|
|
214
|
+
if (!result.error) return;
|
|
215
|
+
} catch {
|
|
216
|
+
// WHY: Fall back to signalling the root PID if taskkill cannot be spawned.
|
|
217
|
+
}
|
|
218
|
+
trySignalSync(pid, "SIGTERM", kill);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Synchronously signal a stdio child process tree (`SIGTERM` deepest-first on POSIX,
|
|
223
|
+
* `taskkill /T /F` with `SIGTERM` fallback on Windows).
|
|
224
|
+
*/
|
|
225
|
+
export function terminatePidTreeSync(
|
|
226
|
+
pid: number,
|
|
227
|
+
deps?: Partial<SyncTreeTerminationDeps>,
|
|
228
|
+
): void {
|
|
229
|
+
const platform = deps?.platform ?? process.platform;
|
|
230
|
+
const kill = deps?.kill ?? ((target, signal) => process.kill(target, signal));
|
|
231
|
+
if (platform === "win32") {
|
|
232
|
+
killWindowsTreeSync(pid, deps?.spawnSync ?? spawnSync, kill);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
const listDescendants =
|
|
236
|
+
deps?.listDescendantPidsSync ??
|
|
237
|
+
((root: number) => listDescendantPidsSync(root, undefined, platform));
|
|
238
|
+
const targets = [...listDescendants(pid), pid];
|
|
239
|
+
for (const target of targets) {
|
|
240
|
+
trySignalSync(target, "SIGTERM", kill);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function isValidPositivePid(pid: number | null | undefined): pid is number {
|
|
245
|
+
return typeof pid === "number" && Number.isInteger(pid) && pid > 0;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Reference-counted process-level `SIGINT` / `exit` safety net for live stdio root PIDs.
|
|
250
|
+
*
|
|
251
|
+
* Listeners are attached only while at least one live stdio PID is tracked, and detached
|
|
252
|
+
* immediately when the last PID stops or exits so tests and `/reload` leak no listeners.
|
|
253
|
+
*/
|
|
254
|
+
export class StdioExitGuard {
|
|
255
|
+
private readonly pids = new Set<number>();
|
|
256
|
+
private readonly proc: SignalExitProcess;
|
|
257
|
+
private readonly globalScope: unknown;
|
|
258
|
+
private readonly customKillTreeSync: ((pid: number) => void) | undefined;
|
|
259
|
+
private attached = false;
|
|
260
|
+
|
|
261
|
+
private readonly onSigint = (): void => {
|
|
262
|
+
// WHY: Yield whenever Pi (e.g. interactive-mode handleCtrlZ's ignoreSigint) or another
|
|
263
|
+
// active listener owns SIGINT; ignore passive signal-exit wrappers so headless rpc/json/print
|
|
264
|
+
// modes do not deadlock when both listeners are present.
|
|
265
|
+
const otherActive =
|
|
266
|
+
this.proc.listenerCount("SIGINT") -
|
|
267
|
+
1 -
|
|
268
|
+
countPassiveSigintListeners(this.proc, this.globalScope);
|
|
269
|
+
if (otherActive > 0) return;
|
|
270
|
+
this.terminateAll();
|
|
271
|
+
this.reRaiseSigint();
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
private readonly onExit = (): void => {
|
|
275
|
+
this.terminateAll();
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
constructor(deps?: Partial<StdioExitGuardDeps>) {
|
|
279
|
+
this.proc = deps?.proc ?? (process as unknown as SignalExitProcess);
|
|
280
|
+
this.globalScope =
|
|
281
|
+
deps && "globalScope" in deps
|
|
282
|
+
? deps.globalScope
|
|
283
|
+
: resolveGlobalScope(this.proc);
|
|
284
|
+
this.customKillTreeSync = deps?.terminatePidTreeSync;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
track(pid: number): void {
|
|
288
|
+
if (!isValidPositivePid(pid)) return;
|
|
289
|
+
this.pids.add(pid);
|
|
290
|
+
this.syncListeners();
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
untrack(pid: number | null | undefined): void {
|
|
294
|
+
if (!isValidPositivePid(pid)) return;
|
|
295
|
+
this.pids.delete(pid);
|
|
296
|
+
this.syncListeners();
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
trackedCount(): number {
|
|
300
|
+
return this.pids.size;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
dispose(): void {
|
|
304
|
+
this.pids.clear();
|
|
305
|
+
this.syncListeners();
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
private syncListeners(): void {
|
|
309
|
+
if (this.pids.size > 0 && !this.attached) {
|
|
310
|
+
this.proc.on("SIGINT", this.onSigint);
|
|
311
|
+
this.proc.on("exit", this.onExit);
|
|
312
|
+
this.attached = true;
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
if (this.pids.size === 0 && this.attached) {
|
|
316
|
+
this.proc.off("SIGINT", this.onSigint);
|
|
317
|
+
this.proc.off("exit", this.onExit);
|
|
318
|
+
this.attached = false;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
private terminateAll(): void {
|
|
323
|
+
const snapshot = [...this.pids];
|
|
324
|
+
this.pids.clear();
|
|
325
|
+
this.syncListeners();
|
|
326
|
+
if (this.customKillTreeSync) {
|
|
327
|
+
for (const pid of snapshot) {
|
|
328
|
+
this.customKillTreeSync(pid);
|
|
329
|
+
}
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
// WHY: Share one sync child reader across every tracked root so macOS/BSD teardown runs
|
|
333
|
+
// at most one bounded `ps` snapshot even when several stdio servers are running.
|
|
334
|
+
const reader = createSyncChildReader();
|
|
335
|
+
const listDescendants = (root: number): number[] => listDescendantPidsSync(root, reader);
|
|
336
|
+
for (const pid of snapshot) {
|
|
337
|
+
terminatePidTreeSync(pid, { listDescendantPidsSync: listDescendants });
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
private reRaiseSigint(): void {
|
|
342
|
+
try {
|
|
343
|
+
this.proc.kill(this.proc.pid, "SIGINT");
|
|
344
|
+
} catch {
|
|
345
|
+
// WHY: Fallback when self-SIGINT is unsupported or refused in a restricted environment.
|
|
346
|
+
this.proc.exit(130);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
package/src/stdio-process.ts
CHANGED
|
@@ -8,15 +8,20 @@
|
|
|
8
8
|
* cleanup with injectable process/timer dependencies.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
import { execFile } from "node:child_process";
|
|
11
|
+
import { ChildProcess, execFile } from "node:child_process";
|
|
12
12
|
import { readFile, readdir } from "node:fs/promises";
|
|
13
13
|
import { StringDecoder } from "node:string_decoder";
|
|
14
14
|
import { promisify } from "node:util";
|
|
15
|
-
import type { ChildProcess } from "node:child_process";
|
|
16
15
|
import type { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
16
|
+
import { isNonRetryableStdioSpawnError } from "./connect-policy.js";
|
|
17
|
+
import { indexProcessTable, StdioExitGuard } from "./stdio-exit-guard.js";
|
|
18
|
+
|
|
19
|
+
export { indexProcessTable } from "./stdio-exit-guard.js";
|
|
17
20
|
|
|
18
21
|
const execFileAsync = promisify(execFile);
|
|
19
22
|
|
|
23
|
+
const defaultStdioExitGuard = new StdioExitGuard();
|
|
24
|
+
|
|
20
25
|
// ─── Line Splitting ───────────────────────────────────────────────────────────
|
|
21
26
|
|
|
22
27
|
export interface LineSplitter {
|
|
@@ -88,6 +93,7 @@ export const POST_CLOSE_FLUSH_DELAY_MS = 100;
|
|
|
88
93
|
interface StdioChildRecord {
|
|
89
94
|
process: ChildProcess;
|
|
90
95
|
closed: boolean;
|
|
96
|
+
trackedPid?: number | undefined;
|
|
91
97
|
/** Flush the buffered partial stderr line before the pipe is destroyed. */
|
|
92
98
|
flushStderr(): void;
|
|
93
99
|
}
|
|
@@ -100,6 +106,38 @@ interface StdioChildRecord {
|
|
|
100
106
|
* keeps both reachable without pinning a closed transport in memory.
|
|
101
107
|
*/
|
|
102
108
|
const childRecords = new WeakMap<object, StdioChildRecord>();
|
|
109
|
+
const stdioSpawnErrors = new WeakMap<object, Error>();
|
|
110
|
+
const spawnErrorObservedProcs = new WeakSet<object>();
|
|
111
|
+
|
|
112
|
+
function attachSpawnErrorCapture(
|
|
113
|
+
transport: object,
|
|
114
|
+
proc: ChildProcess | undefined,
|
|
115
|
+
): void {
|
|
116
|
+
if (!proc || typeof proc.once !== "function" || spawnErrorObservedProcs.has(proc)) {
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
spawnErrorObservedProcs.add(proc);
|
|
120
|
+
proc.once("error", (err: unknown) => {
|
|
121
|
+
if (err instanceof Error && isNonRetryableStdioSpawnError("stdio", err)) {
|
|
122
|
+
stdioSpawnErrors.set(transport, err);
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Return any deterministic non-retryable stdio spawn error captured on `transport`'s child process.
|
|
129
|
+
*
|
|
130
|
+
* WHY: On Windows, `StdioClientTransport.start()` uses `cross-spawn`, which wraps
|
|
131
|
+
* non-`.exe`/`.com` commands (like `uvx` or `missing-pi-mcp-executable-335`) in
|
|
132
|
+
* `cmd.exe /d /s /c "..."`. Because `cmd.exe` spawns, `transport.start()` resolves on
|
|
133
|
+
* `'spawn'` and `Client.connect()` sends `initialize`; when `cmd.exe` exits with status 1,
|
|
134
|
+
* `cross-spawn` hooks `'exit'` and emits `'error'` (`ENOENT`) on the `ChildProcess`
|
|
135
|
+
* asynchronously right before `'close'` causes SDK `Protocol._onclose()` to reject
|
|
136
|
+
* `initialize` with `McpError(-32000, "MCP error -32000: Connection closed")`.
|
|
137
|
+
*/
|
|
138
|
+
export function getStdioSpawnError(transport: object | null | undefined): Error | undefined {
|
|
139
|
+
return transport ? stdioSpawnErrors.get(transport) : undefined;
|
|
140
|
+
}
|
|
103
141
|
|
|
104
142
|
/** A transport whose child stderr can be wired and whose `close()` can be wrapped. */
|
|
105
143
|
interface StderrCarrier {
|
|
@@ -176,6 +214,43 @@ export function instrumentStderr(
|
|
|
176
214
|
return flush;
|
|
177
215
|
}
|
|
178
216
|
|
|
217
|
+
function isLiveChildProcess(
|
|
218
|
+
proc: ChildProcess | undefined,
|
|
219
|
+
): proc is ChildProcess & { pid: number } {
|
|
220
|
+
if (!(proc instanceof ChildProcess)) {
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
return (
|
|
224
|
+
asPositivePid(proc.pid) !== null &&
|
|
225
|
+
proc.exitCode === null &&
|
|
226
|
+
proc.signalCode === null
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function registerChildRecord(
|
|
231
|
+
transport: StdioClientTransport,
|
|
232
|
+
proc: ChildProcess,
|
|
233
|
+
flushStderr: (() => void) | null,
|
|
234
|
+
): void {
|
|
235
|
+
attachSpawnErrorCapture(transport, proc);
|
|
236
|
+
const trackedPid = isLiveChildProcess(proc) ? proc.pid : undefined;
|
|
237
|
+
const record: StdioChildRecord = {
|
|
238
|
+
process: proc,
|
|
239
|
+
closed: false,
|
|
240
|
+
trackedPid,
|
|
241
|
+
flushStderr: () => flushStderr?.(),
|
|
242
|
+
};
|
|
243
|
+
if (trackedPid !== undefined) {
|
|
244
|
+
defaultStdioExitGuard.track(trackedPid);
|
|
245
|
+
proc.once("exit", () => defaultStdioExitGuard.untrack(trackedPid));
|
|
246
|
+
}
|
|
247
|
+
proc.once?.("close", () => {
|
|
248
|
+
record.closed = true;
|
|
249
|
+
defaultStdioExitGuard.untrack(trackedPid);
|
|
250
|
+
});
|
|
251
|
+
childRecords.set(transport, record);
|
|
252
|
+
}
|
|
253
|
+
|
|
179
254
|
export interface InstrumentStdioTransportOptions {
|
|
180
255
|
onPid(pid: number): void;
|
|
181
256
|
onStderrLine(line: string): void;
|
|
@@ -200,17 +275,10 @@ export function instrumentStdioTransport(
|
|
|
200
275
|
const flushStderr = instrumentStderr(transport, onStderrLine);
|
|
201
276
|
|
|
202
277
|
const recordProcess = (proc: ChildProcess | undefined): void => {
|
|
278
|
+
attachSpawnErrorCapture(transport, proc);
|
|
203
279
|
if (!proc?.pid) return;
|
|
204
280
|
if (!childRecords.has(transport)) {
|
|
205
|
-
|
|
206
|
-
process: proc,
|
|
207
|
-
closed: false,
|
|
208
|
-
flushStderr: () => flushStderr?.(),
|
|
209
|
-
};
|
|
210
|
-
proc.once?.("close", () => {
|
|
211
|
-
record.closed = true;
|
|
212
|
-
});
|
|
213
|
-
childRecords.set(transport, record);
|
|
281
|
+
registerChildRecord(transport, proc, flushStderr);
|
|
214
282
|
}
|
|
215
283
|
onPid(proc.pid);
|
|
216
284
|
};
|
|
@@ -285,6 +353,7 @@ export function destroyStdioStreams(transport: object | null | undefined): void
|
|
|
285
353
|
const record = childRecords.get(transport);
|
|
286
354
|
if (!record) return;
|
|
287
355
|
childRecords.delete(transport);
|
|
356
|
+
defaultStdioExitGuard.untrack(record.trackedPid);
|
|
288
357
|
// WHY: Flush the buffered partial stderr line first. Destroying our read end keeps the
|
|
289
358
|
// SDK's PassThrough from ever emitting 'end', so without this a forced teardown drops the
|
|
290
359
|
// server's last words (the buffered remainder of a line with no trailing newline).
|
|
@@ -348,24 +417,6 @@ async function readPsProcessTable(): Promise<Map<number, number[]>> {
|
|
|
348
417
|
return indexProcessTable(stdout);
|
|
349
418
|
}
|
|
350
419
|
|
|
351
|
-
/** Index `ps -A -o pid=,ppid=` output as a parent PID → child PIDs map. */
|
|
352
|
-
export function indexProcessTable(stdout: string): Map<number, number[]> {
|
|
353
|
-
const childrenOf = new Map<number, number[]>();
|
|
354
|
-
for (const line of stdout.split("\n")) {
|
|
355
|
-
const match = /^\s*(\d+)\s+(\d+)\s*$/.exec(line);
|
|
356
|
-
if (!match) continue;
|
|
357
|
-
const childPid = Number(match[1]);
|
|
358
|
-
const parentPid = Number(match[2]);
|
|
359
|
-
const siblings = childrenOf.get(parentPid);
|
|
360
|
-
if (siblings) {
|
|
361
|
-
siblings.push(childPid);
|
|
362
|
-
} else {
|
|
363
|
-
childrenOf.set(parentPid, [childPid]);
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
return childrenOf;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
420
|
function createPlatformChildReader(): (pid: number) => Promise<number[]> {
|
|
370
421
|
if (process.platform === "linux") return readProcChildren;
|
|
371
422
|
if (process.platform === "win32") {
|