Skip to content

Ensuring stdio transport closure despite server hanging. Fixing #271 #314

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/client/stdio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,13 @@ export class StdioClientTransport implements Transport {
return this._process?.stderr ?? null;
}

/**
* The process id of the child process, if it has been started.
*/
get pid(): number | undefined {
return this._process?.pid;
}

private processReadBuffer() {
while (true) {
try {
Expand All @@ -185,8 +192,34 @@ export class StdioClientTransport implements Transport {
}
}

private gracefullyExitProcess(): void {
const pid = this.pid;

if (!pid) {
return;
}

// Killing after 3 seconds to ensure the process has time to exit gracefully.
setTimeout(() => {
try {
process.kill(pid, "SIGKILL");

} catch (err) {
if (typeof err === "object" && err !== null && "code" in err && err.code === "ESRCH") {
// Ignoring ESRCH error, which means the process is already dead.
return;
}

console.warn(`Failed to kill process ${pid}: ${err}`);
}
}, 3000);

process.kill(pid, "SIGINT");
}

async close(): Promise<void> {
this._abortController.abort();
this.gracefullyExitProcess();
this._process = undefined;
this._readBuffer.clear();
}
Expand Down
41 changes: 38 additions & 3 deletions src/integration-tests/process-cleanup.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { execSync } from "node:child_process";
import { Server } from "../server/index.js";
import { StdioServerTransport } from "../server/stdio.js";
import { Client } from "../client/index.js";
import { StdioClientTransport } from "../client/stdio.js";

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

it("should exit cleanly after closing transport", async () => {
it("server should exit cleanly after closing transport", async () => {
const server = new Server(
{
name: "test-server",
Expand All @@ -25,4 +28,36 @@ describe("Process cleanup", () => {
// The test runner will fail if the process hangs
expect(true).toBe(true);
});
});

it("client should exit cleanly after closing transport", async () => {
const isProcessRunning = (pid: number) => {
try {
execSync(`ps -p ${pid}`, { stdio: 'ignore' });
return true;

/* eslint-disable @typescript-eslint/no-unused-vars */
} catch (error) {
return false;
}
}

const client = new Client({
name: "test-client",
version: "1.0.0",
});

const transport = new StdioClientTransport({
command: "node",
args: ["server-that-hangs.js"],
cwd: __dirname
});

await client.connect(transport);
const pid = transport.pid;

await client.close();
await new Promise(resolve => setTimeout(resolve, 5000));

expect(isProcessRunning(pid!)).toBe(false);
});
});
21 changes: 21 additions & 0 deletions src/integration-tests/server-that-hangs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { setTimeout } from 'node:timers'
import process from 'node:process'
import { McpServer } from "../../dist/esm/server/mcp.js";
import { StdioServerTransport } from "../../dist/esm/server/stdio.js";

const transport = new StdioServerTransport();

const server = new McpServer({
name: "server-that-hangs",
version: "1.0.0"
});

await server.connect(transport);

const doNotExitImmediately = async () => {
setTimeout(() => process.exit(0), 30 * 1000);
};

process.stdin.on('close', doNotExitImmediately);
process.on('SIGINT', doNotExitImmediately);
process.on('SIGTERM', doNotExitImmediately);