Skip to content

Commit 6077dd0

Browse files
committed
adding SIGTERM kill first, only then SIGKILL
1 parent 0b86517 commit 6077dd0

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-4
lines changed

src/client/stdio.ts

+26-1
Original file line numberDiff line numberDiff line change
@@ -192,9 +192,34 @@ export class StdioClientTransport implements Transport {
192192
}
193193
}
194194

195+
private gracefullyExitProcess(): void {
196+
const pid = this.pid;
197+
198+
if (!pid) {
199+
return;
200+
}
201+
202+
// Killing after 3 seconds to ensure the process has time to exit gracefully.
203+
setTimeout(() => {
204+
try {
205+
process.kill(pid, "SIGKILL");
206+
207+
} catch (err) {
208+
if (typeof err === "object" && err !== null && "code" in err && err.code === "ESRCH") {
209+
// Ignoring ESRCH error, which means the process is already dead.
210+
return;
211+
}
212+
213+
console.warn(`Failed to kill process ${pid}: ${err}`);
214+
}
215+
}, 3000);
216+
217+
process.kill(pid, "SIGINT");
218+
}
219+
195220
async close(): Promise<void> {
196221
this._abortController.abort();
197-
process.kill(this._process!.pid!, 'SIGKILL');
222+
this.gracefullyExitProcess();
198223
this._process = undefined;
199224
this._readBuffer.clear();
200225
}

src/integration-tests/process-cleanup.test.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { Client } from "../client/index.js";
55
import { StdioClientTransport } from "../client/stdio.js";
66

77
describe("Process cleanup", () => {
8-
jest.setTimeout(5000); // 5 second timeout
8+
jest.setTimeout(10 * 1000); // 10 second timeout
99

1010
it("server should exit cleanly after closing transport", async () => {
1111
const server = new Server(
@@ -56,7 +56,7 @@ describe("Process cleanup", () => {
5656
const pid = transport.pid;
5757

5858
await client.close();
59-
await new Promise(resolve => setTimeout(resolve, 1000));
59+
await new Promise(resolve => setTimeout(resolve, 5000));
6060

6161
expect(isProcessRunning(pid!)).toBe(false);
6262
});

src/integration-tests/server-that-hangs.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { StdioServerTransport } from "../../dist/esm/server/stdio.js";
66
const transport = new StdioServerTransport();
77

88
const server = new McpServer({
9-
name: "test-stdio-server",
9+
name: "server-that-hangs",
1010
version: "1.0.0"
1111
});
1212

0 commit comments

Comments
 (0)