Skip to content

Commit 8d89c33

Browse files
committed
fix: kill process tree on StdioClientTransport.close()
close() only signaled the direct child PID, leaving descendants (e.g. from npx/uvx wrappers) running as orphans. - Spawn with detached: true on Unix so the child leads its own process group - Use process.kill(-pid) to kill the entire group on Unix - Use taskkill /T /F on Windows for tree kill - Fall back to direct ChildProcess.kill() if group kill fails Closes modelcontextprotocol#2023
1 parent 2c0c481 commit 8d89c33

2 files changed

Lines changed: 174 additions & 6 deletions

File tree

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

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { ChildProcess, IOType } from 'node:child_process';
2+
import { execFile } from 'node:child_process';
23
import process from 'node:process';
34
import type { Stream } from 'node:stream';
45
import { PassThrough } from 'node:stream';
@@ -85,6 +86,39 @@ export function getDefaultEnvironment(): Record<string, string> {
8586
return env;
8687
}
8788

89+
/**
90+
* Kill a process and all its descendants.
91+
*
92+
* - Unix: kills the process group via negative PID (requires the child to have
93+
* been spawned with `detached: true` so it leads its own process group).
94+
* - Windows: uses `taskkill /T /F` to kill the process tree.
95+
*
96+
* Falls back to direct `ChildProcess.kill()` if the tree-wide signal fails
97+
* (e.g. the process already exited).
98+
*/
99+
function killProcessTree(childProcess: ChildProcess, signal: NodeJS.Signals = 'SIGTERM'): void {
100+
const pid = childProcess.pid;
101+
if (pid === undefined) {
102+
childProcess.kill(signal);
103+
return;
104+
}
105+
106+
if (process.platform === 'win32') {
107+
try {
108+
execFile('taskkill', ['/T', '/F', '/PID', pid.toString()], { windowsHide: true });
109+
} catch {
110+
childProcess.kill(signal);
111+
}
112+
} else {
113+
try {
114+
process.kill(-pid, signal);
115+
} catch {
116+
// Process group may already be gone; fall back to direct kill.
117+
childProcess.kill(signal);
118+
}
119+
}
120+
}
121+
88122
/**
89123
* Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout.
90124
*
@@ -126,6 +160,7 @@ export class StdioClientTransport implements Transport {
126160
},
127161
stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'],
128162
shell: false,
163+
detached: process.platform !== 'win32',
129164
windowsHide: process.platform === 'win32',
130165
cwd: this._serverParams.cwd
131166
});
@@ -223,7 +258,7 @@ export class StdioClientTransport implements Transport {
223258

224259
if (processToClose.exitCode === null) {
225260
try {
226-
processToClose.kill('SIGTERM');
261+
killProcessTree(processToClose, 'SIGTERM');
227262
} catch {
228263
// ignore
229264
}
@@ -233,7 +268,7 @@ export class StdioClientTransport implements Transport {
233268

234269
if (processToClose.exitCode === null) {
235270
try {
236-
processToClose.kill('SIGKILL');
271+
killProcessTree(processToClose, 'SIGKILL');
237272
} catch {
238273
// ignore
239274
}

‎packages/client/test/client/stdio.test.ts‎

Lines changed: 137 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,42 @@
11
import type { JSONRPCMessage } from '@modelcontextprotocol/core';
2+
import { execSync } from 'node:child_process';
23

34
import type { StdioServerParameters } from '../../src/client/stdio.js';
45
import { StdioClientTransport } from '../../src/client/stdio.js';
56

6-
// Configure default server parameters based on OS
7-
// Uses 'more' command for Windows and 'tee' command for Unix/Linux
8-
const getDefaultServerParameters = (): StdioServerParameters => {
7+
const isUnix = process.platform !== 'win32';
8+
9+
function getDefaultServerParameters(): StdioServerParameters {
910
if (process.platform === 'win32') {
1011
return { command: 'more' };
1112
}
1213
return { command: '/usr/bin/tee' };
13-
};
14+
}
15+
16+
function isProcessAlive(pid: number): boolean {
17+
try {
18+
process.kill(pid, 0);
19+
return true;
20+
} catch {
21+
return false;
22+
}
23+
}
24+
25+
function getChildPids(parentPid: number): number[] {
26+
return execSync(`pgrep -P ${parentPid} 2>/dev/null || true`, { encoding: 'utf-8' }).trim().split('\n').filter(Boolean).map(Number);
27+
}
28+
29+
function getAllDescendantPids(rootPid: number): number[] {
30+
const result: number[] = [];
31+
const queue = [rootPid];
32+
while (queue.length > 0) {
33+
const pid = queue.shift()!;
34+
const children = getChildPids(pid);
35+
result.push(...children);
36+
queue.push(...children);
37+
}
38+
return result;
39+
}
1440

1541
const serverParameters = getDefaultServerParameters();
1642

@@ -77,3 +103,110 @@ test('should return child process pid', async () => {
77103
await client.close();
78104
expect(client.pid).toBeNull();
79105
});
106+
107+
test.skipIf(!isUnix)('should kill child process tree on close', async () => {
108+
const client = new StdioClientTransport({
109+
command: '/bin/sh',
110+
args: ['-c', 'sleep 300 & wait']
111+
});
112+
113+
await client.start();
114+
const parentPid = client.pid!;
115+
expect(parentPid).not.toBeNull();
116+
117+
const grandchildPids = getChildPids(parentPid);
118+
expect(grandchildPids.length).toBeGreaterThan(0);
119+
120+
await client.close();
121+
122+
expect(isProcessAlive(parentPid)).toBe(false);
123+
for (const gPid of grandchildPids) {
124+
expect(isProcessAlive(gPid)).toBe(false);
125+
}
126+
});
127+
128+
test.skipIf(!isUnix)('should kill multiple grandchildren on close', async () => {
129+
const client = new StdioClientTransport({
130+
command: '/bin/sh',
131+
args: ['-c', 'sleep 301 & sleep 302 & sleep 303 & wait']
132+
});
133+
134+
await client.start();
135+
const parentPid = client.pid!;
136+
137+
const grandchildPids = getChildPids(parentPid);
138+
expect(grandchildPids.length).toBe(3);
139+
140+
await client.close();
141+
142+
expect(isProcessAlive(parentPid)).toBe(false);
143+
for (const gPid of grandchildPids) {
144+
expect(isProcessAlive(gPid)).toBe(false);
145+
}
146+
});
147+
148+
test.skipIf(!isUnix)('should kill a 3-level deep process tree on close', async () => {
149+
const client = new StdioClientTransport({
150+
command: '/bin/sh',
151+
args: ['-c', '/bin/sh -c "sleep 304 & wait" & wait']
152+
});
153+
154+
await client.start();
155+
const rootPid = client.pid!;
156+
157+
// Give the nested shell time to spawn its children
158+
await new Promise(resolve => setTimeout(resolve, 500));
159+
160+
const allDescendants = getAllDescendantPids(rootPid);
161+
expect(allDescendants.length).toBeGreaterThanOrEqual(2);
162+
163+
await client.close();
164+
165+
expect(isProcessAlive(rootPid)).toBe(false);
166+
for (const pid of allDescendants) {
167+
expect(isProcessAlive(pid)).toBe(false);
168+
}
169+
});
170+
171+
test.skipIf(!isUnix)('should fire onclose callback when killing process tree', async () => {
172+
const client = new StdioClientTransport({
173+
command: '/bin/sh',
174+
args: ['-c', 'sleep 305 & wait']
175+
});
176+
177+
let didClose = false;
178+
client.onclose = () => {
179+
didClose = true;
180+
};
181+
182+
await client.start();
183+
await client.close();
184+
185+
expect(didClose).toBe(true);
186+
});
187+
188+
test('should not throw when closing an already-exited process', async () => {
189+
const client = new StdioClientTransport(
190+
isUnix ? { command: '/bin/sh', args: ['-c', 'exit 0'] } : { command: 'cmd.exe', args: ['/c', 'exit 0'] }
191+
);
192+
193+
await client.start();
194+
195+
// Wait for the process to exit on its own
196+
await new Promise(resolve => setTimeout(resolve, 500));
197+
198+
await expect(client.close()).resolves.toBeUndefined();
199+
});
200+
201+
test('should not throw when close is called twice', async () => {
202+
const client = new StdioClientTransport(serverParameters);
203+
204+
await client.start();
205+
await client.close();
206+
await expect(client.close()).resolves.toBeUndefined();
207+
});
208+
209+
test('should not throw when close is called without start', async () => {
210+
const client = new StdioClientTransport(serverParameters);
211+
await expect(client.close()).resolves.toBeUndefined();
212+
});

0 commit comments

Comments
 (0)