Skip to content

Commit f3a653f

Browse files
fix(client): kill process tree on StdioClientTransport.close() (modelcontextprotocol#2023)
StdioClientTransport.close() called ChildProcess.kill(), which only signals the direct child. Wrapper commands (npx/uvx/python -m/shells) fork the real MCP server as a grandchild, so the server was left orphaned; on Windows kill() does not terminate the tree at all. Spawn the child detached on POSIX so it leads its own process group, and add killProcessTree() so the existing SIGTERM -> 2s grace -> SIGKILL escalation signals the whole tree: process.kill(-pid) for the group (falling back to a pgrep -P descendant walk), and taskkill /T /F on Windows. Escalation now also checks signalCode, so a server that exits on SIGTERM does not trigger a redundant SIGKILL (and descendant walk) on the common path. Closes modelcontextprotocol#2023 Assisted-by: Claude Code (Anthropic, Opus 4.x) Co-Authored-By: Claude <[email protected]>
1 parent 199a28e commit f3a653f

3 files changed

Lines changed: 290 additions & 12 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
'@modelcontextprotocol/client': patch
3+
---
4+
5+
Fix `StdioClientTransport.close()` leaving MCP server processes alive when the command is a wrapper (npx/uvx/python -m, shell scripts) that forks the real server as a grandchild — `ChildProcess.kill()` only signalled the direct child.
6+
7+
The child is now spawned in its own process group on POSIX, and the existing SIGTERM→2s grace→SIGKILL escalation in `close()` now signals the whole tree: `process.kill(-pid)` on POSIX (with a best-effort `pgrep -P` descendant-walk fallback), and `taskkill /T` (soft) escalating to `taskkill /T /F` on Windows. A server that exits on SIGTERM no longer triggers a redundant SIGKILL.
8+
9+
Note: spawning detached means the child no longer shares the parent's controlling terminal, so terminal SIGINT (Ctrl+C) is not auto-forwarded to it; the transport tears the tree down in `close()`.

‎packages/client/src/client/stdio.ts‎

Lines changed: 114 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { ChildProcess, IOType } from 'node:child_process';
2+
import { spawnSync } from 'node:child_process';
23
import process from 'node:process';
34
import type { Stream } from 'node:stream';
45
import { PassThrough } from 'node:stream';
@@ -135,6 +136,15 @@ export class StdioClientTransport implements Transport {
135136
},
136137
stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'],
137138
shell: false,
139+
// On POSIX, run the child as the leader of its own process group (pgid === pid)
140+
// so that wrapper commands (npx/uvx/python -m/shells) and the real server they
141+
// fork can be terminated together as a tree in close(). We keep stdio wired and do
142+
// NOT call unref(): the transport still owns the child's lifecycle. Skipped on
143+
// Windows, where `detached` opens a new console window instead.
144+
// Tradeoff: a detached child no longer shares the parent's controlling terminal,
145+
// so terminal SIGINT (Ctrl+C) is not auto-delivered to it, and an abrupt parent
146+
// death that skips close() can orphan the tree.
147+
detached: process.platform !== 'win32',
138148
windowsHide: process.platform === 'win32',
139149
cwd: this._serverParams.cwd
140150
});
@@ -235,22 +245,20 @@ export class StdioClientTransport implements Transport {
235245

236246
await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);
237247

238-
if (processToClose.exitCode === null) {
239-
try {
240-
processToClose.kill('SIGTERM');
241-
} catch {
242-
// ignore
243-
}
248+
// `exitCode` stays null both before exit AND after death-by-signal (where
249+
// `signalCode` is set instead). Only escalate while the process is genuinely
250+
// still running, so a server that terminates on SIGTERM does not trigger a
251+
// pointless SIGKILL — and its descendant-tree walk — on the common close path.
252+
const stillRunning = () => processToClose.exitCode === null && processToClose.signalCode === null;
253+
254+
if (stillRunning()) {
255+
killProcessTree(processToClose, 'SIGTERM');
244256

245257
await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);
246258
}
247259

248-
if (processToClose.exitCode === null) {
249-
try {
250-
processToClose.kill('SIGKILL');
251-
} catch {
252-
// ignore
253-
}
260+
if (stillRunning()) {
261+
killProcessTree(processToClose, 'SIGKILL');
254262
}
255263
}
256264

@@ -272,3 +280,97 @@ export class StdioClientTransport implements Transport {
272280
});
273281
}
274282
}
283+
284+
/**
285+
* Terminate a child process together with any descendants it spawned.
286+
*
287+
* {@link StdioClientTransport} frequently launches wrapper commands (`npx`, `uvx`,
288+
* `python -m`, shell scripts) that fork the real MCP server as a grandchild.
289+
* {@link ChildProcess.kill} only signals the direct child, leaving the server
290+
* orphaned; this helper signals the whole tree instead.
291+
*
292+
* - On POSIX the child is spawned `detached`, so it leads its own process group
293+
* (`pgid === pid`); signalling the negative pid reaches every member of the group.
294+
* If the group signal fails we fall back to a best-effort `pgrep -P` descendant walk
295+
* (which can miss descendants already reparented away from an exited leader), then the
296+
* direct child.
297+
* - On Windows there is no process-group primitive, so we shell out to `taskkill /T`,
298+
* which terminates the pid and its entire child tree. The graceful pass (SIGTERM) uses a
299+
* soft taskkill and the SIGKILL pass adds `/F`, mirroring the POSIX escalation.
300+
*/
301+
function killProcessTree(proc: ChildProcess, signal: NodeJS.Signals): void {
302+
const pid = proc.pid;
303+
if (pid === undefined) {
304+
return;
305+
}
306+
307+
if (process.platform === 'win32') {
308+
// Windows has no process-group primitive and Node's kill() cannot deliver POSIX
309+
// signals there, so shell out to taskkill /T (whole tree). Map the graceful pass
310+
// (SIGTERM) to a soft taskkill and reserve /F for the SIGKILL pass, mirroring the
311+
// POSIX SIGTERM -> grace -> SIGKILL escalation. `timeout` bounds a hung taskkill.
312+
const force = signal === 'SIGKILL';
313+
const args = force ? ['/T', '/F', '/PID', String(pid)] : ['/T', '/PID', String(pid)];
314+
const result = spawnSync('taskkill', args, { windowsHide: true, timeout: 2000 });
315+
// Only fall back to a direct kill on the force pass. A soft taskkill legitimately
316+
// fails for a console process with no window to receive the close request; killing
317+
// just the direct child there would orphan the tree, so we let close() escalate to
318+
// the SIGKILL pass instead.
319+
if (force && (result.error || result.status !== 0)) {
320+
killPid(proc, signal);
321+
}
322+
return;
323+
}
324+
325+
try {
326+
// A negative pid signals the entire process group led by the detached child.
327+
process.kill(-pid, signal);
328+
return;
329+
} catch {
330+
// Group signalling failed (e.g. the child was never a group leader, or the
331+
// group is already gone); fall back to walking the descendant tree explicitly.
332+
}
333+
334+
for (const descendant of collectDescendantPids(pid)) {
335+
try {
336+
process.kill(descendant, signal);
337+
} catch {
338+
// ignore processes that already exited
339+
}
340+
}
341+
342+
killPid(proc, signal);
343+
}
344+
345+
/**
346+
* Signal a single child process, swallowing errors (e.g. it already exited).
347+
*/
348+
function killPid(proc: ChildProcess, signal: NodeJS.Signals): void {
349+
try {
350+
proc.kill(signal);
351+
} catch {
352+
// ignore
353+
}
354+
}
355+
356+
/**
357+
* Depth-first enumeration of a process's descendant pids via `pgrep -P`, ordered
358+
* deepest-first so children are signalled before their parents.
359+
*/
360+
function collectDescendantPids(pid: number): number[] {
361+
// `timeout` bounds a hung pgrep so close() can't block forever.
362+
const result = spawnSync('pgrep', ['-P', String(pid)], { encoding: 'utf8', timeout: 2000 });
363+
if (result.status !== 0 || typeof result.stdout !== 'string') {
364+
return [];
365+
}
366+
367+
const descendants: number[] = [];
368+
for (const line of result.stdout.split('\n')) {
369+
const childPid = Number.parseInt(line.trim(), 10);
370+
if (!Number.isInteger(childPid) || childPid <= 0) {
371+
continue;
372+
}
373+
descendants.push(...collectDescendantPids(childPid), childPid);
374+
}
375+
return descendants;
376+
}
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
2+
import { tmpdir } from 'node:os';
3+
import { join } from 'node:path';
4+
5+
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
6+
7+
import { StdioClientTransport } from '../../src/client/stdio';
8+
9+
/**
10+
* Regression test for issue #2023: StdioClientTransport.close() must kill the whole
11+
* process tree, not just the direct child. Wrapper commands (npx/uvx/python -m) fork
12+
* the real server as a grandchild; closing the transport must not orphan it.
13+
*
14+
* The wrapper child here spawns a long-sleeping grandchild, writes the grandchild's
15+
* pid to a marker file, then parks on stdin (so it behaves like a live MCP server and
16+
* the transport's stdio stays wired). After close(), the grandchild must be gone.
17+
*/
18+
19+
// These commands signal child processes by pid; that machinery is POSIX/Windows-specific
20+
// but the assertion (`process.kill(pid, 0)` throws once the process is gone) is portable.
21+
const isWindows = process.platform === 'win32';
22+
23+
// Wrapper script: fork a detached grandchild that sleeps, record its pid, then read stdin
24+
// forever so the wrapper stays alive until the transport closes it.
25+
const WRAPPER_SCRIPT = `
26+
const { spawn } = require('node:child_process');
27+
const { writeFileSync } = require('node:fs');
28+
const markerFile = process.env.MARKER_FILE;
29+
30+
// Grandchild: sleep far longer than the test so it can only die by being killed.
31+
const grandchild = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 600000)'], {
32+
detached: false,
33+
stdio: 'ignore'
34+
});
35+
36+
writeFileSync(markerFile, String(grandchild.pid));
37+
38+
// Keep the wrapper alive by holding stdin open; never resolve on its own.
39+
process.stdin.resume();
40+
setTimeout(() => {}, 600000);
41+
`;
42+
43+
function isAlive(pid: number): boolean {
44+
try {
45+
// Signal 0 performs error checking without actually sending a signal.
46+
process.kill(pid, 0);
47+
return true;
48+
} catch (err) {
49+
// ESRCH => no such process. EPERM => exists but not ours (treat as alive).
50+
return (err as NodeJS.ErrnoException).code === 'EPERM';
51+
}
52+
}
53+
54+
async function waitForDead(pid: number, timeoutMs = 5000): Promise<boolean> {
55+
const deadline = Date.now() + timeoutMs;
56+
while (Date.now() < deadline) {
57+
if (!isAlive(pid)) {
58+
return true;
59+
}
60+
await new Promise(resolve => setTimeout(resolve, 50));
61+
}
62+
return !isAlive(pid);
63+
}
64+
65+
describe.skipIf(isWindows)('StdioClientTransport.close() kills the process tree (POSIX)', () => {
66+
let tmpDir: string;
67+
68+
beforeEach(() => {
69+
tmpDir = mkdtempSync(join(tmpdir(), 'mcp-stdio-tree-'));
70+
});
71+
72+
afterEach(() => {
73+
rmSync(tmpDir, { recursive: true, force: true });
74+
});
75+
76+
test('grandchild process is terminated when the transport is closed', async () => {
77+
const markerFile = join(tmpDir, 'grandchild.pid');
78+
79+
const transport = new StdioClientTransport({
80+
command: process.execPath,
81+
args: ['-e', WRAPPER_SCRIPT],
82+
env: { MARKER_FILE: markerFile }
83+
});
84+
transport.onerror = () => {
85+
// The wrapper does not speak MCP; ignore protocol read noise.
86+
};
87+
88+
await transport.start();
89+
90+
// Wait for the wrapper to record its grandchild's pid.
91+
let grandchildPid: number | undefined;
92+
const deadline = Date.now() + 5000;
93+
while (Date.now() < deadline) {
94+
try {
95+
const contents = readFileSync(markerFile, 'utf8').trim();
96+
if (contents) {
97+
grandchildPid = Number.parseInt(contents, 10);
98+
break;
99+
}
100+
} catch {
101+
// marker not written yet
102+
}
103+
await new Promise(resolve => setTimeout(resolve, 25));
104+
}
105+
106+
expect(grandchildPid).toBeDefined();
107+
expect(Number.isInteger(grandchildPid)).toBe(true);
108+
expect(isAlive(grandchildPid!)).toBe(true);
109+
110+
await transport.close();
111+
112+
// The grandchild must be reaped along with the wrapper.
113+
const dead = await waitForDead(grandchildPid!);
114+
expect(dead).toBe(true);
115+
expect(() => process.kill(grandchildPid!, 0)).toThrow(/ESRCH/);
116+
}, 20000);
117+
});
118+
119+
describe.runIf(isWindows)('StdioClientTransport.close() kills the process tree (Windows)', () => {
120+
let tmpDir: string;
121+
122+
beforeEach(() => {
123+
tmpDir = mkdtempSync(join(tmpdir(), 'mcp-stdio-tree-'));
124+
});
125+
126+
afterEach(() => {
127+
rmSync(tmpDir, { recursive: true, force: true });
128+
});
129+
130+
test('grandchild process is terminated when the transport is closed', async () => {
131+
const markerFile = join(tmpDir, 'grandchild.pid');
132+
133+
const transport = new StdioClientTransport({
134+
command: process.execPath,
135+
args: ['-e', WRAPPER_SCRIPT],
136+
env: { MARKER_FILE: markerFile }
137+
});
138+
transport.onerror = () => {
139+
// The wrapper does not speak MCP; ignore protocol read noise.
140+
};
141+
142+
await transport.start();
143+
144+
let grandchildPid: number | undefined;
145+
const deadline = Date.now() + 5000;
146+
while (Date.now() < deadline) {
147+
try {
148+
const contents = readFileSync(markerFile, 'utf8').trim();
149+
if (contents) {
150+
grandchildPid = Number.parseInt(contents, 10);
151+
break;
152+
}
153+
} catch {
154+
// marker not written yet
155+
}
156+
await new Promise(resolve => setTimeout(resolve, 25));
157+
}
158+
159+
expect(grandchildPid).toBeDefined();
160+
expect(isAlive(grandchildPid!)).toBe(true);
161+
162+
await transport.close();
163+
164+
const dead = await waitForDead(grandchildPid!);
165+
expect(dead).toBe(true);
166+
}, 20000);
167+
});

0 commit comments

Comments
 (0)