Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix: discard obsolete MCP startup health checks

Afloatc1cbca070fe9
diff --git a/server/mcp-health.test.ts b/server/mcp-health.test.ts
index 620c32712b..4ecd0f5780 100644
--- a/server/mcp-health.test.ts
+++ b/server/mcp-health.test.ts
@@ -1,4 +1,4 @@
-import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
@@ -98,4 +98,101 @@ describe("checking that command servers start", () => {
await health.prepare("paul", ["notes"]);
expect(starts).toEqual(["notes:paul", "notes:paul"]);
});
+
+ it("checks an edited server while its previous check is still pending", async () => {
+ const { deps, servers, told } = fixture({ servers: { notes } });
+ let finishOld!: (value: { ok: false; error: string }) => void;
+ const started: StdioMcpSpec[] = [];
+ const health = createMcpHealth({ ...deps, start: async (_name, server) => {
+ started.push(server);
+ return started.length === 1
+ ? new Promise<{ ok: false; error: string }>((resolve) => { finishOld = resolve; })
+ : { ok: true };
+ } });
+ const old = health.prepare("iris", ["notes"]);
+ servers.notes = { ...notes, args: ["-y", "@x/notes-mcp@2"] };
+ health.changed("notes");
+ const current = health.prepare("iris", ["notes"]);
+ expect(started).toHaveLength(2);
+ await current;
+ finishOld({ ok: false, error: "the old command failed" });
+ await old;
+ await health.settled();
+ expect(health.usable("iris", servers)).toEqual(servers);
+ expect(health.off("iris", ["notes"])).toEqual([]);
+ expect(told).toEqual([]);
+ const restarted = createMcpHealth(deps);
+ expect(restarted.usable("iris", servers)).toEqual(servers);
+ expect(JSON.parse(readFileSync(deps.file, "utf8")).notes.checks["*"].ok).toBe(true);
+ });
+
+ it("restarts a pending check even when the command specification is unchanged", async () => {
+ const { deps, told } = fixture({ servers: { notes } });
+ let finishOld!: (value: { ok: false; error: string }) => void;
+ let calls = 0;
+ const health = createMcpHealth({ ...deps, start: async () => ++calls === 1
+ ? new Promise<{ ok: false; error: string }>((resolve) => { finishOld = resolve; })
+ : { ok: true } });
+ const old = health.prepare("iris", ["notes"]);
+ health.changed("notes");
+ const current = health.prepare("iris", ["notes"]);
+ expect(calls).toBe(2);
+ await current;
+ finishOld({ ok: false, error: "the replaced process failed" });
+ await old;
+ await health.settled();
+ expect(health.usable("iris", { notes })).toEqual({ notes });
+ expect(told).toEqual([]);
+ });
+
+ it("does not stamp a pending result with a script's later file identity", async () => {
+ const { deps, servers, told } = fixture({ servers: {} });
+ const script = join(deps.file, "..", "server.mjs");
+ writeFileSync(script, "old");
+ servers.notes = { command: process.execPath, args: [script], env: {} };
+ let finishOld!: (value: { ok: false; error: string }) => void;
+ let calls = 0;
+ const health = createMcpHealth({ ...deps, start: async () => ++calls === 1
+ ? new Promise<{ ok: false; error: string }>((resolve) => { finishOld = resolve; })
+ : { ok: true } });
+ const old = health.prepare("iris", ["notes"]);
+ writeFileSync(script, "new script content");
+ finishOld({ ok: false, error: "old script failed" });
+ await old;
+ expect(health.off("iris", ["notes"])).toEqual([]);
+ expect(told).toEqual([]);
+ await health.prepare("iris", ["notes"]);
+ expect(calls).toBe(2);
+ expect(health.usable("iris", servers)).toEqual(servers);
+ });
+
+ it("keeps a replacement's failure when the obsolete check later succeeds", async () => {
+ const { deps, servers, told } = fixture({ servers: { notes } });
+ let finishOld!: (value: { ok: true }) => void;
+ let calls = 0;
+ const health = createMcpHealth({ ...deps, start: async () => ++calls === 1
+ ? new Promise<{ ok: true }>((resolve) => { finishOld = resolve; })
+ : { ok: false, error: "replacement cannot start" } });
+ const old = health.prepare("iris", ["notes"]);
+ servers.notes = { ...notes, args: ["replacement"] };
+ await health.prepare("iris", ["notes"]);
+ finishOld({ ok: true });
+ await old;
+ expect(health.usable("iris", servers)).toEqual({});
+ expect(health.off("iris", ["notes"])).toEqual([{ name: "notes", error: "replacement cannot start" }]);
+ expect(told).toHaveLength(1);
+ });
+
+ it("discards a removed server's pending failure without saving or notifying", async () => {
+ const { deps, servers, told } = fixture({ servers: { notes } });
+ let finish!: (value: { ok: false; error: string }) => void;
+ const health = createMcpHealth({ ...deps, start: async () => new Promise<{ ok: false; error: string }>((resolve) => { finish = resolve; }) });
+ const pending = health.prepare("iris", ["notes"]);
+ delete servers.notes;
+ health.changed("notes");
+ finish({ ok: false, error: "removed server failed" });
+ await pending;
+ expect(JSON.parse(readFileSync(deps.file, "utf8"))).toEqual({});
+ expect(told).toEqual([]);
+ });
});
diff --git a/server/mcp-health.ts b/server/mcp-health.ts
index dc549f4127..86ce586d67 100644
--- a/server/mcp-health.ts
+++ b/server/mcp-health.ts
@@ -57,6 +57,7 @@ export function createMcpHealth(deps: McpHealthDeps) {
try { state = JSON.parse(readFileSync(deps.file, "utf8")) as Record<string, ServerHealth>; } catch {}
const save = () => { try { writeFileAtomic(deps.file, JSON.stringify(state), { mode: 0o600 }); } catch (error) { console.warn("[mcp] could not save server checks:", error); } };
const running = new Map<string, Promise<void>>();
+ const generations = new Map<string, number>();
const waiting: Array<() => void> = [];
let active = 0;
const slot = async <T,>(work: () => Promise<T>): Promise<T> => {
@@ -72,8 +73,9 @@ export function createMcpHealth(deps: McpHealthDeps) {
};
const due = (check: McpStartCheck | undefined) => !check || now() - check.at >= (check.ok ? RECHECK_STARTED_MS : RECHECK_FAILED_MS);
- const record = (name: string, server: CommandServer, botId: string, result: { ok: true } | { ok: false; error: string }) => {
- const key = startKey(server);
+ const record = (name: string, server: CommandServer, botId: string, key: string, generation: number, result: { ok: true } | { ok: false; error: string }) => {
+ const current = deps.servers()[name];
+ if (!current || (generations.get(name) ?? 0) !== generation || current.bot !== server.bot || startKey(current) !== key) return;
const health = state[name]?.key === key && state[name]!.checks ? state[name]! : (state[name] = { key, checks: {} });
health.checks[standsFor(server, botId)] = result.ok ? { ok: true, at: now() } : { ok: false, at: now(), error: result.error };
const tell = !result.ok && health.told !== key;
@@ -85,12 +87,14 @@ export function createMcpHealth(deps: McpHealthDeps) {
};
const check = (name: string, server: CommandServer, botId: string): Promise<void> => {
- const id = `${name}\u0000${standsFor(server, botId)}`;
+ const key = startKey(server);
+ const generation = generations.get(name) ?? 0;
+ const id = `${name}\u0000${standsFor(server, botId)}\u0000${key}\u0000${generation}`;
const pending = running.get(id);
if (pending) return pending;
const work = slot(() => deps.start(name, server, botId))
.catch((error: unknown) => ({ ok: false as const, error: error instanceof Error ? error.message : String(error) }))
- .then((result) => record(name, server, botId, result))
+ .then((result) => record(name, server, botId, key, generation, result))
.finally(() => running.delete(id));
running.set(id, work);
return work;
@@ -144,6 +148,7 @@ export function createMcpHealth(deps: McpHealthDeps) {
},
/** A server was added, changed or turned on: checked again now. */
changed(name: string): void {
+ generations.set(name, (generations.get(name) ?? 0) + 1);
delete state[name];
save();
checkUsers(name, true);