Skip to content

Commit 40a33be

Browse files
authored
refactor: cleanup signal listeners and auto-remove handlers (#4)
Replace global setMaxListeners(0) with explicit SIGINT/SIGTERM listener management: - use process.once in createServer() - remove handlers on httpServer close in setupCleanupHandlers()
1 parent e4a1a33 commit 40a33be

2 files changed

Lines changed: 10 additions & 2 deletions

File tree

src/server.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,12 @@ export function createServer(): Server {
3232
setupToolHandlers(server);
3333

3434
server.onerror = (error) => console.error("[MCP Error]", error);
35-
process.on("SIGINT", async () => {
35+
// Graceful shutdown on Ctrl-C, remove listener afterwards to prevent leaks
36+
const sigintHandler = async () => {
3637
await server.close();
3738
process.exit(0);
38-
});
39+
};
40+
process.once("SIGINT", sigintHandler);
3941

4042
return server;
4143
}

src/utils/httpServer.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,18 @@ function setupCleanupHandlers(
7979

8080
httpServer.close(() => {
8181
console.log("Server closed");
82+
// exit after cleanup
8283
process.exit(0);
8384
});
8485
};
8586

87+
// Attach signal handlers and remove them on server close to avoid leaks
8688
process.on("SIGINT", cleanup);
8789
process.on("SIGTERM", cleanup);
90+
httpServer.once("close", () => {
91+
process.removeListener("SIGINT", cleanup);
92+
process.removeListener("SIGTERM", cleanup);
93+
});
8894
}
8995

9096
/**

0 commit comments

Comments
 (0)