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
5 changes: 5 additions & 0 deletions .changeset/memory-http-lock-cleanup.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@modelcontextprotocol/server-memory": patch
---

Remove the memory file lock when the server is stopped while serving Streamable HTTP: a write still in flight at shutdown no longer leaves its lock behind for the next writer, and a second SIGINT or SIGTERM exits at once instead of waiting for the listener to close.
78 changes: 77 additions & 1 deletion src/memory/__tests__/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
// across requests, and a 2026-07-28 listen stream across clients.

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { connect as connectTcp } from "node:net";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import {
Client,
StreamableHTTPClientTransport,
Expand All @@ -18,7 +22,12 @@ import {
startHttpServer,
type RunningHttpServer,
} from "../http.js";
import { parseTransport, RESOURCE_URI, run } from "../index.js";
import {
parseTransport,
releaseHeldLocks,
RESOURCE_URI,
run,
} from "../index.js";
import { call, makeTempGraph } from "./helpers.js";

const alice = { name: "Alice", entityType: "person", observations: [] };
Expand Down Expand Up @@ -277,6 +286,73 @@ describe("run", () => {
await expect(fetch(url)).rejects.toThrow();
});

it("exits at once on a second signal, with that signal's status (#5595)", async () => {
const running = await run(["--transport=streamable-http"]);
const close = running.close;
// A shutdown that never finishes, as when a request is still in flight.
running.close = vi.fn().mockReturnValue(new Promise<void>(() => {}));
added("SIGINT")[0]("SIGINT");
expect(process.exit).not.toHaveBeenCalled();
added("SIGTERM")[0]("SIGTERM");
expect(process.exit).toHaveBeenLastCalledWith(143);
added("SIGINT")[0]("SIGINT");
expect(process.exit).toHaveBeenLastCalledWith(130);
expect(running.close).toHaveBeenCalledTimes(1);
await close();
});

it("registers the lock cleanup for the process's exit (#5595)", async () => {
const running = await run(["--transport=streamable-http"]);
expect(process.listeners("exit")).toContain(releaseHeldLocks);
await running.close();
});

// A real signal, sent to a real server process that is serving Streamable
// HTTP and holds the lock mid-write. Windows has no SIGTERM to deliver:
// process.kill() there ends the process outright, so no handler can run.
it.skipIf(process.platform === "win32")(
"removes a lock held mid-write when SIGTERM stops the HTTP server (#5595)",
async () => {
const lockPath = `${graph.filePath}.lock`;
const distIndex = pathToFileURL(
path.join(
path.dirname(fileURLToPath(import.meta.url)),
"..",
"dist",
"index.js",
),
).href;
const script = `
const { run, withFileLock } = await import(${JSON.stringify(distIndex)});
await run(["--transport", "streamable-http"]);
await withFileLock(${JSON.stringify(lockPath)}, () => {
console.log("held");
return new Promise(() => {});
});
`;
const child = spawn(
process.execPath,
["--input-type=module", "-e", script],
{ stdio: ["ignore", "pipe", "ignore"], env: process.env },
);
const exited = new Promise<number | null>((resolve) =>
child.on("exit", (code) => resolve(code)),
);
await new Promise<void>((resolve, reject) => {
child.stdout.on("data", (data: Buffer) => {
if (data.toString().includes("held")) resolve();
});
child.on("exit", () => reject(new Error("exited before holding")));
});
expect(existsSync(lockPath)).toBe(true);

child.kill("SIGTERM");

expect(await exited).toBe(0);
expect(existsSync(lockPath)).toBe(false);
},
);

it("reports a shutdown that fails and exits non-zero", async () => {
const running = await run(["--transport=streamable-http"]);
const close = running.close;
Expand Down
48 changes: 36 additions & 12 deletions src/memory/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,8 +436,22 @@ export function releaseHeldLocks(): void {
// signal's number.
const SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 } as const;

let exitLockCleanupInstalled = false;
let lockCleanupInstalled = false;

// Release held locks when the process exits normally or through
// process.exit(), by the `exit` event. Installed once, however the server is
// started. It covers a signal only when something turns that signal into a
// process.exit(): installLockCleanup() does for stdio, and run() does for
// Streamable HTTP, whose signals first close the listener (#5595).
export function installExitLockCleanup(): void {
if (exitLockCleanupInstalled) {
return;
}
exitLockCleanupInstalled = true;
process.on("exit", releaseHeldLocks);
}

// Release held locks however the server process ends (#5485): on a normal
// exit or process.exit() through the `exit` event, and on SIGINT or SIGTERM,
// whose default action would end the process without emitting `exit`. A
Expand All @@ -449,7 +463,7 @@ export function installLockCleanup(): void {
return;
}
lockCleanupInstalled = true;
process.on("exit", releaseHeldLocks);
installExitLockCleanup();
for (const [signal, code] of Object.entries(SIGNAL_EXIT_CODES)) {
process.on(signal, () => process.exit(code));
}
Expand Down Expand Up @@ -1781,7 +1795,10 @@ 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.
// stops, exiting the process, on SIGINT or SIGTERM. Closing the listener does
// not wait for a tool call that is mid-write, so the exit that follows still
// goes through the lock cleanup (#5595); a second signal does not wait for
// the close either, and exits with the status the signal's default would give.
export async function run(
args: string[] = process.argv.slice(2),
): Promise<{ close: () => Promise<void> }> {
Expand All @@ -1799,17 +1816,24 @@ export async function run(
console.error(
`Knowledge Graph MCP Server running on Streamable HTTP at ${running.url}`,
);
const stop = () => {
running.close().then(
() => process.exit(0),
(error: unknown) => {
console.error("Error shutting down:", error);
process.exit(1);
},
);
installExitLockCleanup();
let stopping = false;
const stop = (signal: keyof typeof SIGNAL_EXIT_CODES) => {
if (stopping) {
process.exit(SIGNAL_EXIT_CODES[signal]);
} else {
stopping = true;
running.close().then(
() => process.exit(0),
(error: unknown) => {
console.error("Error shutting down:", error);
process.exit(1);
},
);
}
};
process.once("SIGINT", stop);
process.once("SIGTERM", stop);
process.on("SIGINT", () => stop("SIGINT"));
process.on("SIGTERM", () => stop("SIGTERM"));
return running;
}

Expand Down
Loading