Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(mcp): revalidate the stdio server's lifecycle, and give the PID record durable identity (#3364)

Mr. Make64caaf37237
diff --git a/v3/@claude-flow/cli/__tests__/mcp-stdio-no-sibling-kill.test.ts b/v3/@claude-flow/cli/__tests__/mcp-stdio-no-sibling-kill.test.ts
index 99f939f70f..4cd59551c7 100644
--- a/v3/@claude-flow/cli/__tests__/mcp-stdio-no-sibling-kill.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mcp-stdio-no-sibling-kill.test.ts
@@ -18,6 +18,17 @@
// 2. MCPServerManager β€” a stdio server neither refuses to start over, nor
// overwrites, nor removes, nor health-checks the PID file of another
// server. The fix keys on transport, so it covers every route above.
+//
+// Review round 2 (@ruvnet, 2026-09-20). The first round kept a one-way
+// "has served stdio" flag so a second stop() could not delete another
+// server's record, and that flag outlived the server it described: after
+// start -> stop, status still said running and health still said healthy.
+// The flag is now the manager's live lifecycle, and the PID record carries
+// durable instance identity (host, OS, Linux PID namespace and kernel boot,
+// and the owner's process start time) instead of a bare PID. Blocks 3-6
+// below cover the four things that review asked for: start -> stop ->
+// independent status/health denial, concurrent ownership, PID reuse and
+// non-owned processes, and the Windows lifecycle.
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { spawn, type ChildProcess } from 'node:child_process';
@@ -85,6 +96,36 @@ afterAll(() => {
});
const siblingAlive = () => sibling.exitCode === null && sibling.signalCode === null;
+// The two Linux identity fields, read exactly as src/mcp-server.ts reads them,
+// so `record()` below builds a record this host would accept. Both are
+// undefined off Linux, where JSON.stringify drops them β€” and the manager
+// compares undefined to undefined, so the record still matches.
+const readOrUndefined = (read: () => string): string | undefined => {
+ try {
+ return read();
+ } catch {
+ return undefined;
+ }
+};
+const PID_NAMESPACE = readOrUndefined(() => fs.readlinkSync('/proc/self/ns/pid'));
+const BOOT_ID = readOrUndefined(() =>
+ fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim()
+);
+
+/** A PID record as src/mcp-server.ts writes it: bare PID, then the identity. */
+const record = (pid: number, identity: Record<string, unknown> = {}): string =>
+ `${pid}\n${JSON.stringify({
+ v: 1,
+ pid,
+ host: os.hostname(),
+ platform: process.platform,
+ pidns: PID_NAMESPACE,
+ boot: BOOT_ID,
+ transport: 'http',
+ port: 3000,
+ ...identity,
+ })}\n`;
+
describe('mcp start: stdio never kills a recorded server (#3364)', () => {
const start = mcpCommand.subcommands!.find((command) => command.name === 'start')!;
const run = (flags: Record<string, unknown>) =>
@@ -129,38 +170,57 @@ describe('mcp start: stdio never kills a recorded server (#3364)', () => {
});
});
-describe('MCPServerManager: stdio servers stay out of the PID file (#3364)', () => {
- type Manager = import('../src/mcp-server.js').MCPServerManager;
- let MCPServerManager: typeof import('../src/mcp-server.js').MCPServerManager;
- let dir: string;
- let pidFile: string;
+type Manager = import('../src/mcp-server.js').MCPServerManager;
+
+/**
+ * Per-test harness for the real MCPServerManager: a throwaway PID-file
+ * directory, stubbed transports (the stdin hooks and the http listener are out
+ * of scope), and managers that are stopped and cleaned up afterwards.
+ */
+function useManagerHarness() {
const managers: Manager[] = [];
const originalCwdEnv = process.env.CLAUDE_FLOW_CWD;
+ const h = {
+ MCPServerManager: undefined as unknown as typeof import('../src/mcp-server.js').MCPServerManager,
+ dir: '',
+ pidFile: '',
+ create(transport: 'stdio' | 'http', pidFile = h.pidFile): Manager {
+ const manager = new h.MCPServerManager({ transport, pidFile, port: 1 });
+ managers.push(manager);
+ return manager;
+ },
+ };
beforeAll(async () => {
- ({ MCPServerManager } = await vi.importActual<typeof import('../src/mcp-server.js')>('../src/mcp-server.js'));
+ ({ MCPServerManager: h.MCPServerManager } =
+ await vi.importActual<typeof import('../src/mcp-server.js')>('../src/mcp-server.js'));
});
beforeEach(() => {
- dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-stdio-pidfile-'));
- pidFile = path.join(dir, 'claude-flow-mcp.pid');
+ h.dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-stdio-pidfile-'));
+ h.pidFile = path.join(h.dir, 'claude-flow-mcp.pid');
// removePidFile() also unlinks a legacy <CLAUDE_FLOW_CWD>/.claude-flow/mcp-server.pid.
- process.env.CLAUDE_FLOW_CWD = dir;
- // The transports themselves (stdin hooks, http listener) are out of scope.
- vi.spyOn(MCPServerManager.prototype as any, 'startStdioServer').mockResolvedValue(undefined);
- vi.spyOn(MCPServerManager.prototype as any, 'startHttpServer').mockResolvedValue(undefined);
+ process.env.CLAUDE_FLOW_CWD = h.dir;
+ vi.spyOn(h.MCPServerManager.prototype as any, 'startStdioServer').mockResolvedValue(undefined);
+ vi.spyOn(h.MCPServerManager.prototype as any, 'startHttpServer').mockResolvedValue(undefined);
});
afterEach(async () => {
for (const manager of managers.splice(0)) await manager.stop().catch(() => {});
vi.restoreAllMocks();
if (originalCwdEnv === undefined) delete process.env.CLAUDE_FLOW_CWD;
else process.env.CLAUDE_FLOW_CWD = originalCwdEnv;
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(h.dir, { recursive: true, force: true });
+ });
+
+ return h;
+}
+
+describe('MCPServerManager: stdio servers stay out of the PID file (#3364)', () => {
+ const h = useManagerHarness();
+ const create = (transport: 'stdio' | 'http') => h.create(transport);
+ let pidFile: string;
+ beforeEach(() => {
+ pidFile = h.pidFile;
});
- const create = (transport: 'stdio' | 'http') => {
- const manager = new MCPServerManager({ transport, pidFile, port: 1 });
- managers.push(manager);
- return manager;
- };
it('starts while another live server is recorded, and never overwrites or removes its PID file', async () => {
fs.writeFileSync(pidFile, String(sibling.pid));
@@ -170,8 +230,9 @@ describe('MCPServerManager: stdio servers stay out of the PID file (#3364)', ()
expect(status).toMatchObject({ running: true, pid: process.pid, transport: 'stdio' });
expect(fs.readFileSync(pidFile, 'utf8')).toBe(String(sibling.pid));
- // Twice: the "I served stdio" flag has to outlive the first stop(), or the
- // second one reads the other server's live record and deletes it.
+ // Twice: the second stop() must not read the other server's live record
+ // and delete it. It no longer can, because after the first stop() this
+ // manager reports itself not running and stop() returns straight away.
await manager.stop();
await manager.stop();
expect(fs.readFileSync(pidFile, 'utf8')).toBe(String(sibling.pid));
@@ -198,3 +259,249 @@ describe('MCPServerManager: stdio servers stay out of the PID file (#3364)', ()
expect(fs.readFileSync(pidFile, 'utf8')).toBe(String(sibling.pid));
});
});
+
+// ---------------------------------------------------------------------------
+// Review round 2, ask 1: start -> stop -> independent status/health denial.
+// ---------------------------------------------------------------------------
+describe('MCPServerManager lifecycle: a stopped server denies status and health (#3364)', () => {
+ const h = useManagerHarness();
+
+ it('start -> stop -> the manager denies both status and health', async () => {
+ // Another server is recorded throughout, so "denied" has to mean "I am not
+ // running", not "I read the file and found nothing".
+ fs.writeFileSync(h.pidFile, String(sibling.pid));
+ const manager = h.create('stdio');
+
+ await expect(manager.start()).resolves.toMatchObject({ running: true, pid: process.pid });
+ await expect(manager.checkHealth()).resolves.toEqual({ healthy: true });
+
+ await manager.stop();
+
+ // The round-1 flag was one-way, so both of these still said "yes".
+ await expect(manager.getStatus()).resolves.toEqual({ running: false });
+ await expect(manager.checkHealth()).resolves.toEqual({ healthy: false, error: 'Server stopped' });
+ // ...and it stays denied however many times it is asked.
+ await expect(manager.getStatus()).resolves.toEqual({ running: false });
+ await expect(manager.checkHealth()).resolves.toEqual({ healthy: false, error: 'Server stopped' });
+ // ...without ever having touched the other server.
+ expect(fs.readFileSync(h.pidFile, 'utf8')).toBe(String(sibling.pid));
+ expect(siblingAlive()).toBe(true);
+ });
+
+ it('start -> stop -> the module-level query behind `mcp status` / `mcp health` is denied', async () => {
+ // getMCPServerStatus() and mcp health both go through getServerManager(),
+ // the module singleton, so this is the query path as the commands run it.
+ // A fresh module instance keeps that singleton out of the other tests.
+ vi.resetModules();
+ const mod = await vi.importActual<typeof import('../src/mcp-server.js')>('../src/mcp-server.js');
+ vi.spyOn(mod.MCPServerManager.prototype as any, 'startStdioServer').mockResolvedValue(undefined);
+
+ await mod.startMCPServer({ transport: 'stdio', pidFile: h.pidFile });
+ await expect(mod.getMCPServerStatus()).resolves.toMatchObject({ running: true });
+
+ await mod.stopMCPServer();
+
+ await expect(mod.getMCPServerStatus()).resolves.toEqual({ running: false });
+ await expect(mod.getServerManager().checkHealth()).resolves.toMatchObject({ healthy: false });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Review round 2, ask 2: concurrent ownership.
+// ---------------------------------------------------------------------------
+describe('MCPServerManager: concurrent ownership of the PID slot (#3364)', () => {
+ const h = useManagerHarness();
+
+ it('two stdio servers run side by side: each answers for itself, neither touches the record', async () => {
+ fs.writeFileSync(h.pidFile, String(sibling.pid)); // a live recorded server
+ const a = h.create('stdio');
+ const b = h.create('stdio');
+
+ await a.start();
+ await b.start();
+ await expect(a.getStatus()).resolves.toMatchObject({ running: true });
+ await expect(b.getStatus()).resolves.toMatchObject({ running: true });
+
+ await a.stop();
+
+ await expect(a.getStatus()).resolves.toEqual({ running: false });
+ await expect(a.checkHealth()).resolves.toMatchObject({ healthy: false });
+ // B is untouched by A's lifecycle β€” one stdio server stopping says nothing
+ // about the next one.
+ await expect(b.getStatus()).resolves.toMatchObject({ running: true });
+ await expect(b.checkHealth()).resolves.toEqual({ healthy: true });
+
+ await b.stop();
+ await expect(b.getStatus()).resolves.toEqual({ running: false });
+ expect(fs.readFileSync(h.pidFile, 'utf8')).toBe(String(sibling.pid));
+ expect(siblingAlive()).toBe(true);
+ });
+
+ it('a server retracts only its own record: once the slot has changed hands, stop() leaves it alone', async () => {
+ const manager = h.create('http');
+ await manager.start();
+ expect(fs.readFileSync(h.pidFile, 'utf8').split('\n')[0]).toBe(String(process.pid));
+
+ // Our record is replaced while we run: another server claimed the slot.
+ const theirs = record(sibling.pid!);
+ fs.writeFileSync(h.pidFile, theirs);
+
+ await manager.stop();
+
+ expect(fs.readFileSync(h.pidFile, 'utf8')).toBe(theirs);
+ expect(siblingAlive()).toBe(true);
+ });
+
+ it("the record's first line is still a bare PID, so every existing reader keeps working", async () => {
+ await h.create('http').start();
+ const raw = fs.readFileSync(h.pidFile, 'utf8');
+
+ // An older ruflo's readPidFile(): parseInt stops at the newline.
+ expect(parseInt(raw.trim(), 10)).toBe(process.pid);
+ // v3/scripts/start-mcp.sh's `head -n 1`.
+ expect(raw.split('\n')[0]).toBe(String(process.pid));
+ expect(JSON.parse(raw.split('\n')[1])).toMatchObject({
+ v: 1,
+ pid: process.pid,
+ host: os.hostname(),
+ platform: process.platform,
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Review round 2, ask 3: PID reuse and non-owned processes.
+// ---------------------------------------------------------------------------
+describe('MCPServerManager: a PID is liveness evidence, not identity (#3364)', () => {
+ const h = useManagerHarness();
+
+ it('a recorded PID whose owner has been replaced is not the recorded server', async () => {
+ // The same live node process, recorded as having started at a different
+ // moment β€” which is exactly what PID reuse looks like from here.
+ fs.writeFileSync(h.pidFile, record(sibling.pid!, { start: 'Thu Jan 1 00:00:00 1970' }));
+
+ await expect(h.create('stdio').getStatus()).resolves.toEqual({ running: false });
+ expect(siblingAlive()).toBe(true); // never signalled, never adopted
+ expect(fs.existsSync(h.pidFile)).toBe(false); // cleaned up as stale
+
+ // ...so the slot is free and a new port-bound server starts over it.
+ await expect(h.create('http').start()).resolves.toMatchObject({ running: true });
+ });
+
+ it('a record from another host, kernel boot or PID namespace is never believed', async () => {
+ for (const foreign of [
+ { host: 'some-other-host' },
+ { boot: 'ffffffff-ffff-ffff-ffff-ffffffffffff' },
+ { pidns: 'pid:[4026531111]' },
+ ]) {
+ fs.writeFileSync(h.pidFile, record(sibling.pid!, foreign));
+ await expect(h.create('stdio').getStatus()).resolves.toEqual({ running: false });
+ expect(siblingAlive()).toBe(true);
+ }
+ });
+
+ it('an identity line that names a different PID is ignored, not applied to this one', async () => {
+ // A half-overwritten record: line 1 replaced, line 2 left behind. The
+ // identity says nothing about the PID now on line 1, so the record falls
+ // back to PID-only β€” believed here, because the sibling really is alive.
+ fs.writeFileSync(
+ h.pidFile,
+ `${sibling.pid}\n${JSON.stringify(JSON.parse(record(999999999, { start: 'Thu Jan 1 00:00:00 1970' }).split('\n')[1]))}\n`
+ );
+ await expect(h.create('stdio').getStatus()).resolves.toMatchObject({
+ running: true,
+ pid: sibling.pid,
+ });
+ });
+
+ it('pins ADR-071: a live process that is not one of ours is not the recorded server', async () => {
+ // Pre-existing guard (isProcessRunning's process-name check), pinned here
+ // because it is the other half of non-owned-process protection and a
+ // bare-integer record β€” an older ruflo's β€” has nothing else to go on.
+ const stranger = spawn('/bin/sleep', ['60'], { stdio: 'ignore' });
+ try {
+ await vi.waitFor(() => expect(stranger.pid).toBeDefined());
+ fs.writeFileSync(h.pidFile, String(stranger.pid));
+ await expect(h.create('stdio').getStatus()).resolves.toEqual({ running: false });
+ expect(stranger.exitCode).toBe(null); // not signalled
+ } finally {
+ stranger.kill('SIGKILL');
+ }
+ });
+
+ it('the query `mcp start` reads denies a PID-reused record, so its --force SIGKILL is unreachable', async () => {
+ // commands/mcp.ts only ever kills `(await getMCPServerStatus()).pid`. With
+ // no live owned server there is no pid, so the kill branch cannot run.
+ const originalTmp = process.env.TMPDIR;
+ process.env.TMPDIR = h.dir; // the default pidFile is os.tmpdir()/claude-flow-mcp.pid
+ try {
+ vi.resetModules();
+ const mod = await vi.importActual<typeof import('../src/mcp-server.js')>('../src/mcp-server.js');
+ fs.writeFileSync(h.pidFile, record(sibling.pid!, { start: 'Thu Jan 1 00:00:00 1970' }));
+
+ const status = await mod.getMCPServerStatus();
+ expect(status.running).toBe(false);
+ expect(status.pid).toBeUndefined();
+ expect(siblingAlive()).toBe(true);
+ } finally {
+ if (originalTmp === undefined) delete process.env.TMPDIR;
+ else process.env.TMPDIR = originalTmp;
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Review round 2, ask 4: Windows lifecycle.
+//
+// There is no Windows host here, so these run the Windows-shaped inputs on
+// this one; nothing below is a measurement on Windows. What Windows does with
+// `process.kill(pid, 0)` is taken from libuv's source, not from a run:
+// src/win/process.c `uv_kill` answers signal 0 by opening the process and
+// calling GetExitCodeProcess, returning UV_ESRCH when it is gone, and
+// src/win/error.c:158 maps ERROR_ACCESS_DENIED to UV_EPERM. Node surfaces both
+// as a throw from process.kill, so isProcessRunning() answers false for either
+// β€” including for a live process owned by another user, where POSIX answers
+// EPERM and therefore true.
+// ---------------------------------------------------------------------------
+describe('MCPServerManager: Windows lifecycle, derived not measured (#3364)', () => {
+ const h = useManagerHarness();
+
+ it('a record written on Windows is not believed on this host', async () => {
+ fs.writeFileSync(h.pidFile, record(sibling.pid!, { platform: 'win32' }));
+ await expect(h.create('stdio').getStatus()).resolves.toEqual({ running: false });
+ expect(siblingAlive()).toBe(true);
+ });
+
+ it('a record with no start token β€” what Windows writes β€” keeps exactly the evidence used today', async () => {
+ // processStartToken() has neither /proc nor ps on Windows and returns
+ // undefined, so the record carries no start time and liveness falls back
+ // to isProcessRunning(). That must neither call every record stale...
+ fs.writeFileSync(h.pidFile, record(sibling.pid!));
+ await expect(h.create('stdio').getStatus()).resolves.toMatchObject({
+ running: true,
+ pid: sibling.pid,
+ });
+
+ // ...nor stop cleaning up a dead one.
+ fs.writeFileSync(h.pidFile, record(999999999));
+ await expect(h.create('stdio').getStatus()).resolves.toEqual({ running: false });
+ });
+
+ it('the start -> stop denial is in-process state: no record, no process probe, no platform', async () => {
+ // The stdio lifecycle never reads the PID file, never signals a PID and
+ // never asks the OS anything, so it behaves identically on every platform.
+ // Pointed at an unwritable path to prove it: if any of that were involved,
+ // this would not get through start().
+ const unusable = path.join(h.dir, 'no-such-directory', 'claude-flow-mcp.pid');
+ const manager = h.create('stdio', unusable);
+
+ await expect(manager.start()).resolves.toMatchObject({ running: true, pid: process.pid });
+ await expect(manager.checkHealth()).resolves.toEqual({ healthy: true });
+
+ await manager.stop();
+
+ await expect(manager.getStatus()).resolves.toEqual({ running: false });
+ await expect(manager.checkHealth()).resolves.toMatchObject({ healthy: false });
+ expect(fs.existsSync(path.dirname(unusable))).toBe(false);
+ });
+});
diff --git a/v3/@claude-flow/cli/src/mcp-server.ts b/v3/@claude-flow/cli/src/mcp-server.ts
index f606930353..2db7ab4479 100644
--- a/v3/@claude-flow/cli/src/mcp-server.ts
+++ b/v3/@claude-flow/cli/src/mcp-server.ts
@@ -70,6 +70,102 @@ export interface MCPServerStatus {
};
}
+/**
+ * Durable identity of the instance that wrote the PID record (#3364).
+ *
+ * A PID is liveness evidence, not identity. The number only means anything in
+ * the PID namespace that issued it, and the OS hands it out again once the
+ * process is reaped, so `kill -0` alone cannot tell "the server we recorded"
+ * from "whatever now holds that number". The record therefore carries what
+ * stays true for one instance β€” host, OS, Linux PID namespace and kernel boot,
+ * and the owner's own process start time β€” and a recorded PID is believed only
+ * while all of it still matches. Same identity model as #3363 for the policy
+ * lock (`src/services/policy-runtime.ts`), which compares the lock's bytes
+ * rather than a stat triple for the same reason.
+ */
+interface PidFileIdentity {
+ v: 1;
+ pid: number;
+ host: string;
+ platform: string;
+ pidns?: string;
+ boot?: string;
+ start?: string;
+ transport?: string;
+ port?: number;
+ startedAt?: string;
+}
+
+interface PidFileRecord {
+ pid: number;
+ raw: string;
+ identity?: PidFileIdentity;
+}
+
+/**
+ * Linux PID namespace of this process, e.g. `pid:[4026531836]`; undefined on
+ * other platforms or without /proc. A PID from another namespace (a container,
+ * a `bwrap --unshare-pid` sandbox) names a different process here.
+ */
+const PID_NAMESPACE = ((): string | undefined => {
+ try {
+ return fs.readlinkSync('/proc/self/ns/pid');
+ } catch {
+ return undefined;
+ }
+})();
+
+/**
+ * Linux boot id: one uuid per kernel boot, shared by every process on that
+ * kernel and readable inside containers. `host` is only a name, and many
+ * distributions keep /tmp across a reboot β€” ADR-071 already names
+ * `/tmp/claude-flow-mcp.pid` as machine-wide on Linux β€” so without this a
+ * record written before the machine came back up looks exactly like a live one.
+ */
+const BOOT_ID = ((): string | undefined => {
+ try {
+ return fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
+ } catch {
+ return undefined;
+ }
+})();
+
+/**
+ * A token that changes when a PID is handed to a different process: the
+ * owner's start time.
+ *
+ * Linux reports it in /proc/<pid>/stat field 22 as clock ticks since boot,
+ * which is durable together with BOOT_ID above. Elsewhere `ps -o lstart=`
+ * reports an absolute wall-clock time, durable on its own. Returns undefined
+ * where neither exists β€” on Windows, so PID reuse stays unqualified there,
+ * exactly as isProcessRunning()'s process-name check already is.
+ */
+function processStartToken(pid: number): string | undefined {
+ if (!Number.isInteger(pid) || pid <= 0) return undefined;
+ // DA-CRIT-3: validate the PID numerically and pass it as an argv entry,
+ // never interpolated into a shell string.
+ const safePid = String(Math.floor(pid));
+ try {
+ // `pid (comm) state ppid ...` β€” comm is parenthesised and may itself
+ // contain spaces and parentheses, so parse after the last ')'.
+ const stat = fs.readFileSync(`/proc/${safePid}/stat`, 'utf8');
+ const afterComm = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
+ const starttime = afterComm[19];
+ if (starttime && /^\d+$/.test(starttime)) return starttime;
+ } catch {
+ // Not Linux, or no /proc β€” fall through to ps.
+ }
+ try {
+ const lstart = execFileSync('ps', ['-p', safePid, '-o', 'lstart='], {
+ encoding: 'utf8',
+ timeout: 1000,
+ }).trim();
+ return lstart || undefined;
+ } catch {
+ return undefined;
+ }
+}
+
/**
* Default configuration
*/
@@ -160,8 +256,21 @@ export class MCPServerManager extends EventEmitter {
private startTime?: Date;
private healthCheckInterval?: NodeJS.Timeout;
private mcpServers: Array<{ stop(): Promise<void> }> = [];
- /** True once this manager has served stdio; such a server stays out of the PID file (#3364). */
- private servedStdio = false;
+ /**
+ * This manager's own lifecycle (#3364). A stdio server keeps no PID record,
+ * so nothing on disk can answer "is this manager running?" β€” only the
+ * manager can. `idle` is a manager that has never started, and only there
+ * does the #2934 fallback in getStatus() ("assume a client-launched stdio
+ * server") apply; `stopped` is a handle on a server that is gone, and it
+ * says so rather than reporting whatever PID the shared file happens to hold.
+ */
+ private lifecycle: 'idle' | 'running' | 'stopped' = 'idle';
+ /**
+ * The exact bytes this manager wrote to the PID file, while they are still
+ * there (#3364). stop() retracts the record only while it is byte for byte
+ * the one we wrote: the slot may have changed hands in between.
+ */
+ private ownedRecord: string | null = null;
constructor(options: MCPServerOptions = {}) {
super();
@@ -187,16 +296,26 @@ export class MCPServerManager extends EventEmitter {
// project), so a stdio server never claims that slot, and never refuses to
// start over β€” or clears β€” a live server's record. ADR-071 made this
// singleton safe against self-detection and PID reuse; a stdio server has
- // no business claiming it at all.
+ // no business claiming it at all. What it does instead is track its own
+ // lifecycle, because for a server that leaves no record that is the only
+ // evidence there is.
const usesPidFile = this.options.transport !== 'stdio';
- // Check if already running (skip if status reports our own PID β€”
- // getStatus() returns running=true for the current process in stdio mode
- // even before the server is actually started)
+ // Refuse to start a second port-bound server over a live one. The record
+ // is read directly rather than through getStatus(), whose #2934 fallback
+ // answers about this process, not about the recorded server β€” and whose
+ // own PID would otherwise have to be filtered out again here.
if (usesPidFile) {
- const status = await this.getStatus();
- if (status.running && status.pid !== process.pid) {
- throw new Error(`MCP Server already running (PID: ${status.pid})`);
+ const record = await this.readPidRecord();
+ if (record && this.recordedServerIsLive(record)) {
+ if (record.pid !== process.pid) {
+ throw new Error(`MCP Server already running (PID: ${record.pid})`);
+ }
+ } else if (record) {
+ // Stale record β€” a dead PID, a PID since handed to another process, or
+ // an identity from another host, kernel boot or PID namespace. Cleaned
+ // up here, as the getStatus() call this replaced used to do.
+ await this.removePidFile();
}
}
@@ -209,17 +328,17 @@ export class MCPServerManager extends EventEmitter {
if (this.options.transport === 'stdio') {
// For stdio transport, spawn the server process
await this.startStdioServer();
- this.servedStdio = true;
} else {
// For HTTP/WebSocket, start in-process server
await this.startHttpServer();
}
+ this.lifecycle = 'running';
const duration = performance.now() - startTime;
- // Write PID file
+ // Write PID file, and remember the bytes so stop() retracts only ours
if (usesPidFile) {
- await this.writePidFile();
+ this.ownedRecord = await this.writePidFile();
}
// Start health check monitoring
@@ -286,13 +405,19 @@ export class MCPServerManager extends EventEmitter {
await Promise.all(servers.map((server) => server.stop()));
}
- // Remove PID file (a stdio server never wrote it; any record belongs to
- // another server, so the flag stays set β€” a second stop() must not
- // delete that server's record either)
- if (!this.servedStdio) {
+ // #3364: retract the record only if this manager wrote it, and only
+ // while it is still ours byte for byte β€” another server may have taken
+ // the slot. A live stdio server wrote nothing, so it has nothing to
+ // retract; a manager that never started β€” the one `mcp stop` builds β€”
+ // still clears the recorded server, exactly as before.
+ if (this.ownedRecord !== null) {
+ await this.removePidFile(this.ownedRecord);
+ } else if (this.lifecycle !== 'running' || this.options.transport !== 'stdio') {
await this.removePidFile();
}
+ this.lifecycle = 'stopped';
+ this.ownedRecord = null;
this.startTime = undefined;
this.emit('stopped');
} catch (error) {
@@ -305,11 +430,30 @@ export class MCPServerManager extends EventEmitter {
* Get server status
*/
async getStatus(): Promise<MCPServerStatus> {
- // Check PID file (a manager that serves stdio reports itself: a recorded
- // PID belongs to some other server, #3364)
- const pid = this.servedStdio ? null : await this.readPidFile();
+ // #3364: this manager's own lifecycle is the authority on this manager.
+ // While it is serving stdio it IS the server β€” it never wrote a record, so
+ // a recorded PID belongs to somebody else. Once it has stopped it is not
+ // running, whatever the record says. The marker is live lifecycle, not a
+ // one-way "has served stdio" flag that survives the server it described.
+ if (this.lifecycle === 'running' && this.options.transport === 'stdio') {
+ return {
+ running: true,
+ pid: process.pid,
+ transport: 'stdio',
+ startedAt: this.startTime?.toISOString(),
+ uptime: this.startTime
+ ? Math.floor((Date.now() - this.startTime.getTime()) / 1000)
+ : undefined,
+ };
+ }
+ if (this.lifecycle === 'stopped') {
+ return { running: false };
+ }
+
+ // Check PID file
+ const record = await this.readPidRecord();
- if (!pid) {
+ if (!record) {
// No PID file found. Detect if we are running in stdio mode
// (e.g., launched by Claude Code via `claude mcp add`).
const isStdio = !process.stdin.isTTY;
@@ -328,10 +472,8 @@ export class MCPServerManager extends EventEmitter {
return { running: false };
}
- // Check if process is running
- const isRunning = this.isProcessRunning(pid);
-
- if (!isRunning) {
+ // Check that the recorded server is still the instance the record names
+ if (!this.recordedServerIsLive(record)) {
// Clean up stale PID file
await this.removePidFile();
return { running: false };
@@ -340,7 +482,7 @@ export class MCPServerManager extends EventEmitter {
// Build status
const status: MCPServerStatus = {
running: true,
- pid,
+ pid: record.pid,
transport: this.options.transport,
host: this.options.host,
port: this.options.port,
@@ -367,19 +509,23 @@ export class MCPServerManager extends EventEmitter {
metrics?: Record<string, number>;
}> {
if (this.options.transport === 'stdio') {
- // #3364: a manager that serves stdio is the server, so it is healthy by
- // definition. Without this it would read the PID file it deliberately
- // never wrote and report another server's health (or, every 30s from
- // startHealthMonitoring(), clear that server's stale record).
- if (this.servedStdio) {
+ // #3364: while this manager is serving stdio it IS the server, so it is
+ // healthy by definition and must not read β€” or, from the 30s monitor in
+ // startHealthMonitoring(), clear β€” the record it deliberately never
+ // wrote. Once it has stopped it is not healthy either: it is a handle on
+ // a dead server, not a window onto whatever PID the shared file holds.
+ if (this.lifecycle === 'running') {
return { healthy: true };
}
- // For stdio, check if process is running
- const pid = await this.readPidFile();
- if (pid === null) {
+ if (this.lifecycle === 'stopped') {
+ return { healthy: false, error: 'Server stopped' };
+ }
+ // For stdio, check if the recorded process is running
+ const record = await this.readPidRecord();
+ if (record === null) {
return { healthy: false, error: 'No PID file found' };
}
- if (!this.isProcessRunning(pid)) {
+ if (!this.recordedServerIsLive(record)) {
// Clean up stale PID file
await this.removePidFile();
return { healthy: false, error: 'Process not running (cleaned up stale PID)' };
@@ -877,34 +1023,117 @@ export class MCPServerManager extends EventEmitter {
}
/**
- * Write PID file
+ * Write the PID record.
+ *
+ * Line 1 is the bare PID, byte for byte what this file has always held, so
+ * every existing reader keeps working: an older ruflo's
+ * `parseInt(content.trim(), 10)` stops at the newline, and
+ * `v3/scripts/start-mcp.sh` reads the first line. Line 2 is the durable
+ * identity of the instance that wrote it (#3364). Returns the bytes written,
+ * which stop() uses to retract only its own record.
*/
- private async writePidFile(): Promise<void> {
+ private async writePidFile(): Promise<string> {
const pid = this.process?.pid || process.pid;
- await fs.promises.writeFile(this.options.pidFile, String(pid), 'utf8');
+ const identity: PidFileIdentity = {
+ v: 1,
+ pid,
+ host: os.hostname(),
+ platform: process.platform,
+ pidns: PID_NAMESPACE,
+ boot: BOOT_ID,
+ start: processStartToken(pid),
+ transport: this.options.transport,
+ port: this.options.port,
+ startedAt: (this.startTime ?? new Date()).toISOString(),
+ };
+ const record = `${pid}\n${JSON.stringify(identity)}\n`;
+ await fs.promises.writeFile(this.options.pidFile, record, 'utf8');
+ return record;
}
/**
- * Read PID file
+ * Read the PID record.
+ *
+ * A bare-integer file β€” an older ruflo, `start-mcp.sh --daemon`, or a
+ * hand-written one β€” parses to a record with no identity, which keeps
+ * exactly the old behaviour: the PID is checked for liveness and nothing
+ * more. An identity line is only believed for the PID it names.
*/
- private async readPidFile(): Promise<number | null> {
+ private async readPidRecord(): Promise<PidFileRecord | null> {
try {
- const content = await fs.promises.readFile(this.options.pidFile, 'utf8');
- const pid = parseInt(content.trim(), 10);
- return isNaN(pid) ? null : pid;
+ const raw = await fs.promises.readFile(this.options.pidFile, 'utf8');
+ const newline = raw.indexOf('\n');
+ const pid = parseInt((newline === -1 ? raw : raw.slice(0, newline)).trim(), 10);
+ if (!Number.isInteger(pid) || pid <= 0) return null;
+
+ let identity: PidFileIdentity | undefined;
+ const rest = newline === -1 ? '' : raw.slice(newline + 1).trim();
+ if (rest) {
+ try {
+ const parsed = JSON.parse(rest) as PidFileIdentity | null;
+ if (parsed && parsed.v === 1 && parsed.pid === pid) identity = parsed;
+ } catch {
+ // Truncated, or a second line we don't recognise β€” PID only.
+ }
+ }
+ return { pid, raw, identity };
} catch {
return null;
}
}
/**
- * Remove PID file
+ * Is the recorded server still the instance the record names? (#3364)
+ *
+ * `kill -0`, and isProcessRunning()'s process-name check on top of it, only
+ * answer "something with this number is alive". Durable identity answers
+ * "it is still the one we wrote down":
+ * - another host, OS, kernel boot or PID namespace issues its own PIDs, so
+ * the number says nothing here. On Linux this is the ordinary stale case,
+ * because /tmp commonly survives a reboot;
+ * - within one boot the OS reuses a PID once the process is reaped, and the
+ * owner's start time is what tells the two apart.
+ * Where the start time cannot be read β€” Windows β€” the answer falls back to
+ * isProcessRunning(), i.e. exactly the evidence used today.
*/
- private async removePidFile(): Promise<void> {
- try {
- await fs.promises.unlink(this.options.pidFile);
- } catch {
- // Ignore errors
+ private recordedServerIsLive(record: PidFileRecord): boolean {
+ const { pid, identity } = record;
+ if (identity) {
+ if (
+ identity.host !== os.hostname() ||
+ identity.platform !== process.platform ||
+ identity.pidns !== PID_NAMESPACE ||
+ identity.boot !== BOOT_ID
+ ) {
+ return false;
+ }
+ if (identity.start !== undefined) {
+ const start = processStartToken(pid);
+ if (start !== undefined && start !== identity.start) return false;
+ }
+ }
+ return this.isProcessRunning(pid);
+ }
+
+ /**
+ * Remove PID file. With `ownedRecord`, only while the file still holds
+ * exactly those bytes: the slot may have changed hands (#3364).
+ */
+ private async removePidFile(ownedRecord?: string): Promise<void> {
+ let ours = true;
+ if (ownedRecord !== undefined) {
+ try {
+ ours = (await fs.promises.readFile(this.options.pidFile, 'utf8')) === ownedRecord;
+ } catch {
+ ours = false; // Already gone
+ }
+ }
+ if (ours) {
+ try {
+ await fs.promises.unlink(this.options.pidFile);
+ } catch {
+ // Ignore errors
+ }
}
// Also clean up legacy PID file location from older versions
try {
diff --git a/v3/scripts/start-mcp.sh b/v3/scripts/start-mcp.sh
index c2c7f5155a..2114da4da6 100755
--- a/v3/scripts/start-mcp.sh
+++ b/v3/scripts/start-mcp.sh
@@ -96,10 +96,13 @@ EOF
}
# Check if server is running
+# #3364: the CLI writes the bare PID on line 1 and a durable identity record
+# on line 2, so read the first line only. A file this script wrote itself is a
+# single line and reads the same way.
is_running() {
if [ -f "$PID_FILE" ]; then
local pid
- pid=$(cat "$PID_FILE")
+ pid=$(head -n 1 "$PID_FILE")
if kill -0 "$pid" 2>/dev/null; then
return 0
fi
@@ -110,7 +113,7 @@ is_running() {
# Get server PID
get_pid() {
if [ -f "$PID_FILE" ]; then
- cat "$PID_FILE"
+ head -n 1 "$PID_FILE"
fi
}