Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions .changeset/stdio-sigterm-exit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@modelcontextprotocol/server-filesystem": patch
"@modelcontextprotocol/server-sequential-thinking": patch
---

Exit on `SIGINT` and `SIGTERM` over stdio as well as Streamable HTTP, so `docker stop` ends the container at once instead of killing it at the timeout (#5611).
71 changes: 36 additions & 35 deletions docs/quality-gate.md

Large diffs are not rendered by default.

23 changes: 15 additions & 8 deletions scripts/image-smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@
// (#5485): after a write and that stop, the graph's directory holds the
// graph and nothing else, so no lock or temporary save file was left.
//
// `cleanStop` is in the table, not read from the image's `STOPSIGNAL`: the
// regression worth catching is that line being dropped, which would also drop
// a check derived from it. The other five images do not stop on their own
// today (#5611), so nothing is asserted of them.
// `cleanStop` is in the table, not read from the image's `STOPSIGNAL` or its
// init process: the regression worth catching is that line being dropped,
// which would also drop a check derived from it. Every image sets it since
// #5611; the script tests require it of every entry, so a new image gains the
// check with its entry.
//
// Which images it builds is decided from the files changed since the base,
// as the interface diff decides which servers to diff: a server's own
Expand Down Expand Up @@ -107,6 +108,7 @@ export const IMAGES = [
// It refuses to start without an allowed directory; the image has /tmp.
args: ["/tmp"],
tool: "list_allowed_directories",
cleanStop: true,
},
{
name: "memory",
Expand All @@ -126,10 +128,15 @@ export const IMAGES = [
},
leaves: { dir: "/data", files: ["memory.jsonl"] },
},
{ name: "sequentialthinking", language: "ts", tool: "sequentialthinking" },
{ name: "fetch", language: "py", tool: "fetch" },
{ name: "git", language: "py", tool: "git_status" },
{ name: "time", language: "py", tool: "get_current_time" },
{
name: "sequentialthinking",
language: "ts",
tool: "sequentialthinking",
cleanStop: true,
},
{ name: "fetch", language: "py", tool: "fetch", cleanStop: true },
{ name: "git", language: "py", tool: "git_status", cleanStop: true },
{ name: "time", language: "py", tool: "get_current_time", cleanStop: true },
];

/** Files whose change selects every image: this tooling itself. */
Expand Down
23 changes: 8 additions & 15 deletions scripts/image-smoke.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -76,21 +76,12 @@ test("findUnlistedImages names a Dockerfile the table lacks", (t) => {
assert.deepEqual(findUnlistedImages(src), ["newserver"]);
});

test("an image that declares a stop signal is checked for a clean stop", () => {
test("every image is checked for a clean stop", () => {
// The table, not the Dockerfile, decides what is asserted, so a deleted
// STOPSIGNAL cannot delete the check with it. This pins the other
// direction: an image that gains a STOPSIGNAL gains the check in the same
// change. Today that is `everything` and `memory`; the rest are #5611.
const declared = IMAGES.filter((image) =>
/^STOPSIGNAL\s/m.test(
readFileSync(
path.join(repoRoot, "src", image.name, "Dockerfile"),
"utf8",
),
),
).map((image) => image.name);
assert.deepEqual(declared, ["everything", "memory"]);
for (const name of declared) assert.equal(byName(name).cleanStop, true, name);
// STOPSIGNAL or init process cannot delete the check with it. Since #5611
// every image stops on its own, so every entry, a new one included, must
// ask for the check.
for (const image of IMAGES) assert.equal(image.cleanStop, true, image.name);
});

test("parseArgs reads every flag, in either spelling", () => {
Expand Down Expand Up @@ -382,9 +373,11 @@ test("checkImage fails a build that reports no image ID", async () => {
});

test("checkImage does not stop-check an image the table does not say stops", async () => {
// Every listed image says it stops (#5611), so the entry is made up.
const { docker, ran } = fakeDocker();
const { connect } = fakeSession({ tools: ["get_current_time"] });
await checkImage(byName("time"), { docker, connect, ...quiet });
const image = { ...byName("time"), cleanStop: false };
await checkImage(image, { docker, connect, ...quiet });
assert.deepEqual(ran(), ["build", "rm"]);
});

Expand Down
11 changes: 10 additions & 1 deletion src/fetch/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ RUN --mount=type=cache,target=/root/.cache/uv \

FROM python:3.12-slim-bookworm

# tini runs as PID 1 and the server as its child (#5611). PID 1 gets no default
# signal disposition, so the server, which installs no SIGTERM handler, would
# drop `docker stop`'s signal and be killed at the timeout. Under tini the
# signal reaches it with its default action and the container ends at once
# (exit 143). A handler in the server is not enough on stdio: the SDK reads
# stdin in a worker thread that a signal cannot interrupt.
RUN apt-get update && apt-get install -y --no-install-recommends tini \
&& rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY --from=uv /python /python
Expand All @@ -46,4 +55,4 @@ USER 999:999
# Place executables in the environment at the front of the path
ENV PATH="/app/.venv/bin:$PATH"

ENTRYPOINT ["mcp-server-fetch"]
ENTRYPOINT ["/usr/bin/tini", "--", "mcp-server-fetch"]
83 changes: 82 additions & 1 deletion src/filesystem/__tests__/bin-smoke.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
// and serves a tool. Everything else runs in-process, so this only guards the
// entry-point wiring that in-process tests cannot reach (the isEntryPoint
// guard and process stdio). It needs `dist/`, which `npm run validate` builds
// before testing; a bare `npm test` on a clean checkout skips it.
// before testing; a bare `npm test` on a clean checkout skips it. It also
// checks the bin exits on SIGTERM, which only a real process can show (#5611).

import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { createRequire } from "node:module";
import fs from "node:fs/promises";
Expand All @@ -20,6 +22,68 @@ const packageJson = createRequire(import.meta.url)("../package.json") as {
version: string;
};

/** How long the SIGTERM probe may take, from spawn to exit. */
const SIGTERM_DEADLINE_MS = 4_000;

/**
* Spawn the bin over stdio, wait for its answer to `initialize`, send it
* SIGTERM, and resolve with how it exited. Waiting on an answer rather than
* a startup line on stderr makes sure the signal handlers, installed once
* startup returns, are in place. Outside a container SIGTERM's default
* action would kill it (`signal: "SIGTERM"`, no code), so exit code 0 shows
* its own handler ran: the one that ends it as PID 1 in its Docker image,
* where that default action does not apply (#5611).
*/
function exitOnSigterm(
args: string[],
env?: NodeJS.ProcessEnv,
): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, args, {
env: { ...process.env, ...env },
stdio: ["pipe", "pipe", "pipe"],
});
child.stderr.resume();
child.stdout.once("data", () => child.kill("SIGTERM"));
child.stdin.write(
JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: {
protocolVersion: "2025-11-25",
capabilities: {},
clientInfo: { name: "sigterm-smoke", version: "0.0.0" },
},
}) + "\n",
);
// Under Vitest's 5 s test timeout, so a server that hangs is killed and
// reaped here rather than left running with its pipes open.
let timedOut = false;
const deadline = setTimeout(() => {
timedOut = true;
child.kill("SIGKILL");
}, SIGTERM_DEADLINE_MS);
child.on("error", (error) => {
clearTimeout(deadline);
child.kill("SIGKILL");
reject(error);
});
child.on("close", (code, signal) => {
clearTimeout(deadline);
if (timedOut) {
reject(
new Error(
`no exit within ${SIGTERM_DEADLINE_MS} ms of starting; killed`,
),
);
} else {
resolve({ code, signal });
}
});
});
}

describe("the built bin", () => {
it.skipIf(!existsSync(distIndexPath))(
"boots over stdio and serves a tool",
Expand Down Expand Up @@ -51,4 +115,21 @@ describe("the built bin", () => {
}
},
);

// Windows has no SIGTERM to deliver: process.kill() there ends the process
// outright, so no handler can run.
it.skipIf(!existsSync(distIndexPath) || process.platform === "win32")(
"exits 0 on SIGTERM over stdio",
async () => {
const dir = await makeTempDir("mcp-fs-sigterm-");
try {
await expect(exitOnSigterm([distIndexPath, dir])).resolves.toEqual({
code: 0,
signal: null,
});
} finally {
await fs.rm(dir, { recursive: true, force: true });
}
},
);
});
5 changes: 3 additions & 2 deletions src/filesystem/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -343,8 +343,9 @@ export function isEntryPoint(
if (isEntryPoint(process.argv[1], import.meta.url)) {
main().then(
(running) => {
// Streamable HTTP keeps the process up on its port; stop it cleanly.
if (!("handler" in running)) return;
// Stop cleanly on either transport. As PID 1 in its Docker image the
// process gets no default signal disposition, so without these a
// `docker stop` is dropped and the container is killed (#5611).
const stop = () => {
running.close().then(
() => process.exit(0),
Expand Down
11 changes: 9 additions & 2 deletions src/git/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,19 @@ RUN --mount=type=cache,target=/root/.cache/uv \

FROM python:3.12-slim-bookworm

# tini runs as PID 1 and the server as its child (#5611). PID 1 gets no default
# signal disposition, so the server, which installs no SIGTERM handler, would
# drop `docker stop`'s signal and be killed at the timeout. Under tini the
# signal reaches it with its default action and the container ends at once
# (exit 143). A handler in the server is not enough on stdio: the SDK reads
# stdin in a worker thread that a signal cannot interrupt.
#
# `safe.directory '*'`: a bind-mounted repository shows up owned by whatever UID
# the host or Docker Desktop maps it to, rarely the unprivileged `app` user the
# server runs as, so git's ownership check would refuse every repository the
# container is given (#4741). The only repositories the container sees are the
# ones its user chose to mount, which is the trust that check stands in for.
RUN apt-get update && apt-get install -y git git-lfs && rm -rf /var/lib/apt/lists/* \
RUN apt-get update && apt-get install -y git git-lfs tini && rm -rf /var/lib/apt/lists/* \
&& git lfs install --system \
&& git config --system --add safe.directory '*'

Expand All @@ -58,4 +65,4 @@ ENV PATH="/app/.venv/bin:$PATH"
# when running the container, bind-mount the host directory holding the Git
# repositories it may use; add --repository with an in-container path to confine
# it to one of them
ENTRYPOINT ["mcp-server-git"]
ENTRYPOINT ["/usr/bin/tini", "--", "mcp-server-git"]
76 changes: 76 additions & 0 deletions src/sequentialthinking/__tests__/stdio-smoke.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
// behavior is tested in-process elsewhere; this only proves the published
// entry point starts and serves the same server. It needs a build, so it is
// skipped when dist/ is absent (`npm run validate` builds before testing).
// It also checks the bin exits on SIGTERM, which only a real process can
// show (#5611).

import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { spawn } from "node:child_process";
import { createRequire } from "node:module";
import { existsSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";
import { tmpdir } from "node:os";
Expand All @@ -22,6 +25,68 @@ const packageRoot = path.join(
);
const distIndexPath = path.join(packageRoot, "dist", "index.js");

/** How long the SIGTERM probe may take, from spawn to exit. */
const SIGTERM_DEADLINE_MS = 4_000;

/**
* Spawn the bin over stdio, wait for its answer to `initialize`, send it
* SIGTERM, and resolve with how it exited. Waiting on an answer rather than
* a startup line on stderr makes sure the signal handlers, installed once
* startup returns, are in place. Outside a container SIGTERM's default
* action would kill it (`signal: "SIGTERM"`, no code), so exit code 0 shows
* its own handler ran: the one that ends it as PID 1 in its Docker image,
* where that default action does not apply (#5611).
*/
function exitOnSigterm(
args: string[],
env?: NodeJS.ProcessEnv,
): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, args, {
env: { ...process.env, ...env },
stdio: ["pipe", "pipe", "pipe"],
});
child.stderr.resume();
child.stdout.once("data", () => child.kill("SIGTERM"));
child.stdin.write(
JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: {
protocolVersion: "2025-11-25",
capabilities: {},
clientInfo: { name: "sigterm-smoke", version: "0.0.0" },
},
}) + "\n",
);
// Under Vitest's 5 s test timeout, so a server that hangs is killed and
// reaped here rather than left running with its pipes open.
let timedOut = false;
const deadline = setTimeout(() => {
timedOut = true;
child.kill("SIGKILL");
}, SIGTERM_DEADLINE_MS);
child.on("error", (error) => {
clearTimeout(deadline);
child.kill("SIGKILL");
reject(error);
});
child.on("close", (code, signal) => {
clearTimeout(deadline);
if (timedOut) {
reject(
new Error(
`no exit within ${SIGTERM_DEADLINE_MS} ms of starting; killed`,
),
);
} else {
resolve({ code, signal });
}
});
});
}

describe.skipIf(!existsSync(distIndexPath))("stdio binary smoke", () => {
let dir: string;

Expand Down Expand Up @@ -80,4 +145,15 @@ describe.skipIf(!existsSync(distIndexPath))("stdio binary smoke", () => {
symlinkSync(distIndexPath, link);
await smoke(link);
});

// Windows has no SIGTERM to deliver: process.kill() there ends the process
// outright, so no handler can run.
it.skipIf(process.platform === "win32")(
"exits 0 on SIGTERM over stdio",
async () => {
await expect(
exitOnSigterm([distIndexPath], { DISABLE_THOUGHT_LOGGING: "true" }),
).resolves.toEqual({ code: 0, signal: null });
},
);
});
22 changes: 14 additions & 8 deletions src/sequentialthinking/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,20 +225,26 @@ export function parseTransport(args: string[]): TransportName {

/**
* Start the server on the transport `args` names, and hand back how to stop
* it. Streamable HTTP listens on `HOST`:`PORT` (loopback:3001 by default) and
* also stops, exiting the process, on SIGINT or SIGTERM.
* it. Streamable HTTP listens on `HOST`:`PORT` (loopback:3001 by default).
* Either transport also stops, exiting the process, on SIGINT or SIGTERM: as
* PID 1 in its Docker image the process gets no default signal disposition,
* so without these a `docker stop` is dropped and the container is killed
* (#5611).
*/
export async function run(
args: string[] = process.argv.slice(2),
): Promise<{ close: () => Promise<void> }> {
let running: { close: () => Promise<void> };
if (parseTransport(args) === "stdio") {
return main();
running = main();
} else {
const { httpEndpoint, startHttpServer } = await import("./http.js");
const http = await startHttpServer(httpEndpoint());
console.error(
`Sequential Thinking MCP Server running on Streamable HTTP at ${http.url}`,
);
running = http;
}
const { httpEndpoint, startHttpServer } = await import("./http.js");
const running = await startHttpServer(httpEndpoint());
console.error(
`Sequential Thinking MCP Server running on Streamable HTTP at ${running.url}`,
);
const stop = () => {
running.close().then(
() => process.exit(0),
Expand Down
Loading