Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Train E2: MCP start checks that time out three times running count as not starting; the first request does not wait
milind-sonic887e11abbfa
diff --git a/server/drivers/chat-host-computer.test.ts b/server/drivers/chat-host-computer.test.tsindex 38e7879dda..ad16354c0a 100644--- a/server/drivers/chat-host-computer.test.ts+++ b/server/drivers/chat-host-computer.test.ts@@ -5,7 +5,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { randomUUID } from "node:crypto";import { joinLateChatTools, mountChatTools, type ChatToolDefinition, type ChatToolSession } from "./chat-mcp-tools.ts";import type { SendTurnInput } from "../contracts.ts";-import { startFakeHttpMcp } from "../testing/fake-http-mcp-server.ts";import { HOST_COMPUTER_READY, HOST_COMPUTER_STAND_IN, hostComputerKey, hostComputerStartupMs } from "./chat-host-computer.ts";const FAKE = `@@ -171,36 +170,30 @@ describe("this desktop's own computer in a chat turn", () => {it("in a background start, keeps its stand-in while a slower server joins, then lists its own tools beside both", async () => {// A driver that failed before gets the short wait, so the turn goes on with the stand-in well inside the other- // servers' startup budget. The notes server is a URL one, whose own start budget is longer than the turn's, so it- // is the one still starting when the bound passes and joins after the mount.+ // servers' startup budget, and the gated server can join after the mount.const driver = `background-${randomUUID()}`;await mount(computer(driver, { MODE: "exit" }).server, 5_000, 20_000);const starting = computer(driver, { DELAY_MS: "2500" });+ const gate = join(dirs[0]!, `gate-${randomUUID()}`);const plain = (env: Record<string, string> = {}) => ({ command: process.execPath, args: [script], env: { ANSWERED: join(dirs[0]!, `answered-${randomUUID()}`), ...env } });- const notes = await startFakeHttpMcp({- tools: [{ name: "write", description: "Write", inputSchema: { type: "object", properties: { value: { type: "string" } }, required: ["value"], additionalProperties: false } }],- toolsDelayMs: 6_000,- callResult: (params) => ({ content: [{ type: "text", text: `recorded:${String((params as { arguments?: { value?: unknown } }).arguments?.value)}` }] }),- });const ask: ChatToolDefinition = { type: "function", function: { name: "ask_user", description: "Ask", parameters: { type: "object" } } };const settled: string[] = [];- try {- const session = await mountChatTools({ localComputer: starting.server, agents: plain(), custom: { notes: { type: "http", url: notes.url, headers: {} } } } as SendTurnInput["integrations"],- controller.signal, true, undefined, undefined, undefined, undefined, undefined, undefined,- { startupMs: 5_000, hostComputerMs: 20_000, background: true, onSettled: (server) => settled.push(server) });- sessions.push(session);- expect(names(session)).toEqual(["agents_write", HOST_COMPUTER_STAND_IN]);- expect(settled).not.toContain("notes");- session.definitions.push(ask);-- await vi.waitFor(() => expect(settled).toContain("notes"), { timeout: 10_000, interval: 20 });- expect(await joinLateChatTools(session, [ask])).toEqual([]);- expect(names(session)).toEqual(["agents_write", HOST_COMPUTER_STAND_IN, "notes_write", "ask_user"]);-- await expect(session.execute(HOST_COMPUTER_STAND_IN, {}, controller.signal)).resolves.toEqual({ ok: true, text: HOST_COMPUTER_READY });- expect(names(session)).toEqual(["agents_write", "computer_write", "notes_write", "ask_user"]);- await expect(session.execute("notes_write", { value: "n" }, controller.signal)).resolves.toMatchObject({ ok: true, text: "recorded:n" });- expect(await joinLateChatTools(session, [ask]), "nothing left to join").toBeUndefined();- } finally { await notes.close(); }+ const session = await mountChatTools({ localComputer: starting.server, agents: plain(), custom: { notes: plain({ GATE: gate }) } } as SendTurnInput["integrations"],+ controller.signal, true, undefined, undefined, undefined, undefined, undefined, undefined,+ { startupMs: 5_000, hostComputerMs: 20_000, background: true, onSettled: (server) => settled.push(server) });+ sessions.push(session);+ expect(names(session)).toEqual(["agents_write", HOST_COMPUTER_STAND_IN]);+ expect(settled).not.toContain("notes");+ session.definitions.push(ask);++ writeFileSync(gate, "");+ await vi.waitFor(() => expect(settled).toContain("notes"), { timeout: 10_000, interval: 20 });+ expect(await joinLateChatTools(session, [ask])).toEqual([]);+ expect(names(session)).toEqual(["agents_write", HOST_COMPUTER_STAND_IN, "notes_write", "ask_user"]);++ await expect(session.execute(HOST_COMPUTER_STAND_IN, {}, controller.signal)).resolves.toEqual({ ok: true, text: HOST_COMPUTER_READY });+ expect(names(session)).toEqual(["agents_write", "computer_write", "notes_write", "ask_user"]);+ await expect(session.execute("notes_write", { value: "n" }, controller.signal)).resolves.toMatchObject({ ok: true, text: "recorded:n" });+ expect(await joinLateChatTools(session, [ask]), "nothing left to join").toBeUndefined();}, 30_000);});diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex 5053e2abdc..90d5390219 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -1543,8 +1543,8 @@ describe("Chat MCP tool limit, fairly shared", () => {describe("Chat MCP servers starting in the background", () => {const slowStart = (ms: number) => `if (message.method === "initialize") { setTimeout(() => reply(message, {protocolVersion:"2024-11-05",capabilities:{tools:{}}}), ${ms}); continue; }`;const ask: ChatToolDefinition = { type: "function", function: { name: "ask_user", description: "Ask", parameters: { type: "object" } } };- const background = async (integrations: SendTurnInput["integrations"], signal: AbortSignal, toolLimit?: number, onSettled?: (server: string) => void, options: { startupMs?: number } = {}) => {- const session = await mountChatTools(integrations, signal, false, undefined, undefined, undefined, undefined, undefined, toolLimit, { background: true, ...(onSettled ? { onSettled } : {}), ...options });+ const background = async (integrations: SendTurnInput["integrations"], signal: AbortSignal, toolLimit?: number, onSettled?: (server: string) => void) => {+ const session = await mountChatTools(integrations, signal, false, undefined, undefined, undefined, undefined, undefined, toolLimit, { background: true, ...(onSettled ? { onSettled } : {}) });sessions.push(session);return session;};@@ -1577,43 +1577,31 @@ describe("Chat MCP servers starting in the background", () => {return lines;};- it("waits for a configured server that starts within the budget, and lists its tools from the first request", async () => {+ it("starts the turn once the agents server is up, and lists a slow server's tools when it joins", async () => {const agents = fixture();const slow = fixture(slowStart(1_500));+ const startedAt = Date.now();const session = await background({ agents: agents.server, custom: { slow: slow.server } }, agents.controller.signal);+ expect(Date.now() - startedAt).toBeLessThan(1_500);session.definitions.push(ask);+ expect(names(session)).toEqual(["agents_write", "ask_user"]);+ expect(await joined(session)).toEqual([]);expect(names(session)).toEqual(["agents_write", "slow_write", "ask_user"]);await expect(session.execute("slow_write", { value: "late" }, agents.controller.signal)).resolves.toMatchObject({ ok: true, text: "recorded:late" });expect(await session.join()).toBeUndefined();});- it("skips a configured server that fails within the wait, saying so before the model runs", async () => {+ it("says when a server that was still starting is skipped", async () => {const warn = vi.spyOn(console, "warn").mockImplementation(() => {});const agents = fixture();const late = fixture(`if (message.method === "tools/list") { setTimeout(() => reply(message, {tools:"invalid"}), 800); continue; }`);const session = await background({ agents: agents.server, custom: { late: late.server } }, agents.controller.signal);- expect(chatToolNotices(session)).toEqual([expect.stringMatching(/^MCP server "late" was skipped for this turn: .*invalid result/)]);+ expect(session.skipped).toEqual([]);+ expect(await joined(session)).toEqual([expect.stringMatching(/^MCP server "late" was skipped for this turn: .*invalid result/)]);expect(names(session)).toEqual(["agents_write"]);- expect(await session.join()).toBeUndefined();warn.mockRestore();});- it("says when a configured server is still starting past the budget, and lists its tools when it joins", async () => {- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});- const agents = fixture();- // A URL server's own start budget is longer than a turn's, so it is still starting when the bound passes.- const late = await startFakeHttpMcp({ tools: whopLikeCatalog(2), toolsDelayMs: 1_200 });- try {- const session = await mountChatTools({ agents: agents.server, custom: { late: { type: "http", url: late.url, headers: {} } } },- agents.controller.signal, false, undefined, undefined, undefined, undefined, undefined, undefined, { background: true, startupMs: 800 });- sessions.push(session);- expect(chatToolNotices(session)).toEqual(['MCP server "late" was skipped for this turn: still starting; its tools may be missing from this turn\'s first reply.']);- expect(names(session)).toEqual(["agents_write"]);- await joined(session);- expect(names(session).some((name) => name.startsWith("late_"))).toBe(true);- } finally { await late.close(); warn.mockRestore(); }- });-it("keeps a listed tool's name when a server joining later would have taken it", async () => {const configured = fixture();// Up once the session has the configured server's tools, so those are listed from the start; the built-in starts after.@@ -1635,42 +1623,39 @@ describe("Chat MCP servers starting in the background", () => {const notes = catalog(syntheticToolNames("note", 10));const gates = settledGates("notes");const agents = catalog(["write"], gates.files);- // Named like the tool search and reached through it, it joins after the first round and takes _2 names: a URL- // server's own start budget is longer than the turn's, so it is the one still starting when the bound passes.- const late = await startFakeHttpMcp({ tools: [{ name: "call_tool", description: "Runs a tool", inputSchema: { type: "object" } }], toolsDelayMs: 1_200 });+ // Named like the tool search and offering the tool its call tool is listed as, it joins after the first round.+ const go = gate();+ const late = catalog(["call_tool"], [go]);const controller = new AbortController();controllers.push(controller);- try {- const session = await background({ agents: agents.server, custom: { notes: notes.server, mcp: { type: "http", url: late.url, headers: {} } } }, controller.signal, 8, gates.onSettled, { startupMs: 800 });- expect(names(session)).toEqual(["agents_write", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);- await joined(session);- expect(names(session)).toEqual(["agents_write", "mcp_search_tools_2", "mcp_describe_tool_2", "mcp_call_tool_2", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);- await expect(session.execute("mcp_call_tool", { name: "notes_note_1", arguments: {} }, controller.signal)).resolves.toEqual({ ok: true, text: "ran note_1" });- await expect(session.execute("mcp_call_tool_2", { name: "call_tool", arguments: {} }, controller.signal)).resolves.toMatchObject({ ok: true, text: "remote execution recorded" });- } finally { await late.close(); }+ const session = await background({ agents: agents.server, custom: { notes: notes.server, mcp: late.server } }, controller.signal, 8, gates.onSettled);+ expect(names(session)).toEqual(["agents_write", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);+ writeFileSync(go, "");+ await joined(session);+ expect(names(session)).toEqual(["agents_write", "mcp_call_tool_2", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);+ await expect(session.execute("mcp_call_tool", { name: "notes_note_1", arguments: {} }, controller.signal)).resolves.toEqual({ ok: true, text: "ran note_1" });});it("keeps a searched tool's name when a listed server joins the tool search later", async () => {// "x" is listed and "x_a" searched; then "y" joins and takes the room "x" had, so "x" is searched too, before "x_a",- // and its "a_b" reads as "x_a_b_2", beside the "x_a_b" the searched "b" of "x_a" already has. "y" is a URL server,- // whose own start budget is longer than the turn's, so it is the one still starting when the bound passes.- const listed = catalog(["a_b", "p_1", "q_1", "r_1"]);+ // and its "a_b" reads as "x_a_b", the name the searched "b" of "x_a" already has.+ const listed = catalog(["a_b", "p_1"]);const searched = catalog(["b", ...syntheticToolNames("c", 5)]);const gates = settledGates("x", "x_a");const agents = catalog(["write"], gates.files);- const late = await startFakeHttpMcp({ tools: [{ name: "call_tool", description: "Runs a tool", inputSchema: { type: "object" } }], toolsDelayMs: 1_200 });+ const go = gate();+ const late = catalog(["write"], [go]);const controller = new AbortController();controllers.push(controller);- try {- const session = await background({ agents: agents.server, custom: { x: listed.server, x_a: searched.server, y: { type: "http", url: late.url, headers: {} } } }, controller.signal, 9, gates.onSettled, { startupMs: 800 });- expect(names(session)).toEqual(["agents_write", "x_a_b", "x_p_1", "x_q_1", "x_r_1", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);- const call = (name: string) => session.execute("mcp_call_tool", { name, arguments: {} }, controller.signal);- await expect(call("x_a_b")).resolves.toEqual({ ok: true, text: "ran b" });- await joined(session);- expect(names(session)).toEqual(["agents_write", "y_search_tools", "y_describe_tool", "y_call_tool", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);- await expect(call("x_a_b")).resolves.toEqual({ ok: true, text: "ran b" });- await expect(call("x_a_b_2")).resolves.toEqual({ ok: true, text: "ran a_b" });- } finally { await late.close(); }+ const session = await background({ agents: agents.server, custom: { x: listed.server, x_a: searched.server, y: late.server } }, controller.signal, 7, gates.onSettled);+ expect(names(session)).toEqual(["agents_write", "x_a_b", "x_p_1", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);+ const call = (name: string) => session.execute("mcp_call_tool", { name, arguments: {} }, controller.signal);+ await expect(call("x_a_b")).resolves.toEqual({ ok: true, text: "ran b" });+ writeFileSync(go, "");+ await joined(session);+ expect(names(session)).toEqual(["agents_write", "y_write", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);+ await expect(call("x_a_b")).resolves.toEqual({ ok: true, text: "ran b" });+ await expect(call("x_a_b_2")).resolves.toEqual({ ok: true, text: "ran a_b" });});it("waits for every server without the agents server, or when not started in the background", async () => {diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex 5a09392047..a751745f8e 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -82,8 +82,6 @@ const WINDOWS_BUILT_IN_STARTUP_MS = 20_000;/** A turn can't run without the agents server, so a slow computer (an older Intel Mac) gets this long for it everywhere. */const AGENTS_STARTUP_MS = 20_000;const STARTUP_TIMED_OUT = "MCP startup timed out";-/** A configured server still starting when a background turn's bounded wait ends: it keeps starting for a later round. */-const STILL_STARTING = "still starting; its tools may be missing from this turn's first reply.";const REQUEST_TIMED_OUT = "MCP request timed out; execution outcome may be uncertain";/** How much of a server's stderr is kept, and how much of its last line is ever shown. */const STDERR_TAIL_CHARS = 4_000, STDERR_LINE_CHARS = 300;@@ -103,9 +101,8 @@ export function agentsStartupMs(env: Record<string, string | undefined> = proces/** `startupMs` replaces every command server's startup budget (mcpStartupMs, agentsStartupMs), `hostComputerMs` hostComputerStartupMs. `notice` hears, for the person,* that this computer's tools did not start, worded once per `conversation`. With `background` and the agents server, setup- * waits for the built-ins a turn acts through (agents, a computer, the browser) and, within the built-ins' startup budget,- * the configured servers too; one still starting past that is listed by `join` once started. `onSettled` hears each- * server's name once it has listed its tools or failed. */+ * waits only for the built-ins a turn acts through (agents, a computer, the browser); the rest are listed by `join` once+ * started. `onSettled` hears each server's name once it has listed its tools or failed. */export interface ChatToolMountOptions {startupMs?: number;hostComputerMs?: number;@@ -770,7 +767,6 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]try {if (signal.aborted) throw aborted();// Concurrent starts, consumed in config order so names and collision suffixes stay stable.- const mountedAt = Date.now();const mounts = servers.map(async ([name, descriptor], index): Promise<Mounted> => {if (signal.aborted || closed) throw aborted();const client = new ChatMcpClient(descriptor, computerUse, index >= builtIns);@@ -806,20 +802,6 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]};const waitAll = !options.background || !servers.some(([, descriptor]) => descriptor === agentsServer);await Promise.all(settled.filter((_, index) => waitAll || waited(index)));- // In the background, the first request waits for the configured servers' first mounts too, within the startup budget- // a built-in gets: one that starts in time has its tools listed from the first request, and one still starting past- // that keeps starting for a later round (join), said here so its tools' absence is not silent.- const late = waitAll ? [] : settled.flatMap((mount, index) => index >= builtIns && !waited(index) ? [{ mount, index }] : []);- if (late.length) {- const atBound = new Promise<false>((resolve) => { setTimeout(() => resolve(false), Math.max(0, mountedAt + startupMs - Date.now())).unref(); });- const made = await Promise.all(late.map(({ mount }) => Promise.race([mount.then(() => true as const), atBound])));- for (const [at, { index }] of late.entries()) {- if (made[at]) continue;- const name = servers[index]![0];- skipped.push({ server: name, reason: STILL_STARTING });- console.warn(`chat-mcp: configured MCP server "${name}" is still starting; its tools may be missing from this turn's first reply`);- }- }await absorb();await layout(toolLimit);if (signal.aborted || closed) throw aborted();diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.tsindex 48b6d9d4df..961c63b1b4 100644--- a/server/drivers/openai-chat-tools.test.ts+++ b/server/drivers/openai-chat-tools.test.ts@@ -1537,34 +1537,38 @@ describe("a turn with the person's Windows computer, the built-in browser and threturn { ...others, agents: catalog(syntheticToolNames("agent", agents), { after: names.map((name) => join(gates, name)) }) };};- it("sends the first request past the startup budget with a notice, and lists the late server's tools from the next round", async () => {- // A URL server's own start budget is longer than the turn's, so the turn goes on without it past the budget, saying- // so, and has its tools in hand before the next round.+ it("sends the first request without waiting for a slow server, and lists its tools from the next round", async () => {+ // The slow server cannot start until the first request has arrived: a turn that waited for it would give up on it+ // first, so its tools could never be listed in the next round, however slow the runner.+ const gate = mkdtempSync(join(tmpdir(), "omb-chat-tools-slow-"));+ cleanups.push(() => removeTempDir(gate));+ const go = join(gate, "go");let settledBeforeFirst: boolean | null = null;- const notes = await startFakeHttpMcp({ tools: [{ name: "note", description: "Note", inputSchema: { type: "object" } }], toolsDelayMs: 9_500 });+ const notes = catalog(["note"], { after: [go] });const f = await fixture(async (_body, response, round) => {if (round > 1) return answer(response);settledBeforeFirst = mountSettled.servers.has("notes");+ writeFileSync(go, "");// The turn has the slow server's tools in hand before the next round.await settledServer("notes");sse(response, [chunk({ tool_calls: [toolCall("agents_agent_1", "{}")] }, "tool_calls")]);});- try {- await f.start({ integrations: { agents: catalog(syntheticToolNames("agent", 1)), custom: { notes: { type: "http", url: notes.url, headers: {} } } } });- expect(await f.recorder.until((event) => event.type === "turn.completed", 40_000)).toMatchObject({ ok: true });- expect(settledBeforeFirst).toBe(false);- expect(f.requests.map((request) => request.tools!.map((tool) => tool.function.name))).toEqual([["agents_agent_1", "ask_user"], ["agents_agent_1", "notes_note", "ask_user"]]);- expect(f.recorder.events.filter((event) => event.type === "runtime.notice" || event.type === "runtime.error")).toEqual([- expect.objectContaining({ type: "runtime.notice", message: 'MCP server "notes" was skipped for this turn: still starting; its tools may be missing from this turn\'s first reply.' }),- ]);- } finally { await notes.close(); }- }, 30_000);+ await f.start({ integrations: { agents: catalog(syntheticToolNames("agent", 1)), custom: { notes } } });+ expect(await f.completed()).toMatchObject({ ok: true });+ expect(settledBeforeFirst).toBe(false);+ expect(f.requests.map((request) => request.tools!.map((tool) => tool.function.name))).toEqual([["agents_agent_1", "ask_user"], ["agents_agent_1", "notes_note", "ask_user"]]);+ expect(f.recorder.events.filter((event) => event.type === "runtime.notice" || event.type === "runtime.error")).toEqual([]);+ });it("lists fewer tools when servers that joined after a tool call go past the provider's limit", async () => {- const notes = await startFakeHttpMcp({ tools: syntheticToolNames("note", 5).map((name) => ({ name, description: "Note", inputSchema: { type: "object" } })), toolsDelayMs: 9_500 });+ const gate = mkdtempSync(join(tmpdir(), "omb-chat-tools-gate-"));+ cleanups.push(() => removeTempDir(gate));+ const go = join(gate, "go");+ const notes = catalog(syntheticToolNames("note", 5), { after: [go] });const f = await fixture(async (body, response) => {if (!body.messages.some((message) => message.role === "tool")) {// The slow server starts, and the turn has its tools in hand, before the next round.+ writeFileSync(go, "");await settledServer("notes");return sse(response, [chunk({ tool_calls: [toolCall("agents_agent_1", "{}")] }, "tool_calls")]);}@@ -1575,16 +1579,16 @@ describe("a turn with the person's Windows computer, the built-in browser and thconst warn = console.warn;console.warn = () => {};try {- await f.start({ integrations: { agents: catalog(syntheticToolNames("agent", 1)), custom: { notes: { type: "http", url: notes.url, headers: {} } } } });- expect(await f.recorder.until((event) => event.type === "turn.completed", 40_000)).toMatchObject({ ok: true });- } finally { await notes.close(); console.warn = warn; }+ await f.start({ integrations: { agents: catalog(syntheticToolNames("agent", 1)), custom: { notes } } });+ expect(await f.completed()).toMatchObject({ ok: true });+ } finally { console.warn = warn; }expect(f.requests.map((request) => request.tools!.map((tool) => tool.function.name))).toEqual([["agents_agent_1", "ask_user"],["agents_agent_1", ...syntheticToolNames("notes_note", 5), "ask_user"],["agents_agent_1", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool", "ask_user"],]);expect(f.recorder.events.some((event) => event.type === "runtime.error")).toBe(false);- }, 30_000);+ });it("sends at most 128 tools, ask_user and every agents tool among them", async () => {const f = await fixture((_body, response) => answer(response));diff --git a/server/mcp-health.test.ts b/server/mcp-health.test.tsindex b88124a9e2..6028edd3b9 100644--- a/server/mcp-health.test.ts+++ b/server/mcp-health.test.ts@@ -86,6 +86,22 @@ describe("checking that command servers start", () => {expect(again.usable("paul", servers), "kept across a restart").toEqual(servers);});+ it("counts a server whose check runs out of time three times in a row as not starting", async () => {+ const { deps, servers, told, tick } = fixture({ servers: { notes } });+ const health = createMcpHealth({ ...deps, start: async () => ({ ok: false, error: "The server did not answer in time.", timeout: true }) });+ for (let round = 0; round < 2; round += 1) {+ await health.prepare("paul", ["notes"]);+ await health.settled();+ expect(health.usable("paul", servers)).toEqual(servers);+ tick(60_000);+ }+ await health.prepare("paul", ["notes"]);+ await health.settled();+ expect(health.usable("paul", servers)).toEqual({});+ expect(health.off("paul", ["notes"])).toEqual([{ name: "notes", error: "The server did not answer in time." }]);+ expect(told).toHaveLength(1);+ });+it("names the bot whose own server does not start", async () => {const { health, told } = fixture({ startsFor: (name) => name !== "blender" });await health.prepare("iris", ["blender"]);diff --git a/server/mcp-health.ts b/server/mcp-health.tsindex e86c7b7428..f52e410357 100644--- a/server/mcp-health.ts+++ b/server/mcp-health.ts@@ -16,11 +16,13 @@ import type { McpServerSpec, StdioMcpSpec } from "./contracts.ts";export const RECHECK_FAILED_MS = 30 * 60_000;export const RECHECK_STARTED_MS = 6 * 60 * 60_000;export const RECHECK_TIMEOUT_MS = 60_000;+/** Checks that ran out of time in a row before the server counts as not starting: one that hangs is not tried for ever. */+export const TIMEOUTS_FOR_A_VERDICT = 3;const CHECKS_AT_ONCE = 2;/** The check of a server that is no bot's own. */const EVERY_BOT = "*";-export interface McpStartCheck { ok: boolean; at: number; error?: string; timeout?: true }+export interface McpStartCheck { ok: boolean; at: number; error?: string; timeout?: true; timeouts?: number }interface ServerHealth { key: string; checks: Record<string, McpStartCheck>; told?: string }type Bot = { id: string; name: string };type CommandServer = StdioMcpSpec & { bot?: string };@@ -76,17 +78,21 @@ export function createMcpHealth(deps: McpHealthDeps) {const health = state[name];return health && health.key === startKey(server) ? health.checks?.[standsFor(server, botId)] : undefined;};- /** A check that ran out of time proves nothing: the server is not said to be off and is not left out of turns. */- const provenFailure = (check: McpStartCheck | undefined): boolean => !!check && !check.ok && check.timeout !== true;+ /** A check that ran out of time proves nothing, until it has done so TIMEOUTS_FOR_A_VERDICT times in a row: till then+ * the server is not said to be off and is not left out of turns. */+ const provenFailure = (check: McpStartCheck | undefined): boolean =>+ !!check && !check.ok && (check.timeout !== true || (check.timeouts ?? 1) >= TIMEOUTS_FOR_A_VERDICT);const due = (check: McpStartCheck | undefined) =>- !check || now() - check.at >= (check.ok ? RECHECK_STARTED_MS : check.timeout ? RECHECK_TIMEOUT_MS : RECHECK_FAILED_MS);+ !check || now() - check.at >= (check.ok ? RECHECK_STARTED_MS : check.timeout && !provenFailure(check) ? RECHECK_TIMEOUT_MS : RECHECK_FAILED_MS);const record = (name: string, server: CommandServer, botId: string, key: string, generation: number, result: { ok: true } | { ok: false; error: string; timeout?: true }) => {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: {} });+ const prior = health.checks[standsFor(server, botId)];+ const timeouts = (prior?.timeout ? prior.timeouts ?? 1 : 0) + 1;health.checks[standsFor(server, botId)] = result.ok ? { ok: true, at: now() }- : { ok: false, at: now(), error: result.error, ...(result.timeout ? { timeout: true } : {}) };+ : { ok: false, at: now(), error: result.error, ...(result.timeout ? { timeout: true, timeouts } : {}) };const tell = provenFailure(health.checks[standsFor(server, botId)]) && health.told !== key;if (tell) health.told = key;save();