Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
MCP: the first model request waits for custom servers within the startup budget, a probe timeout is no verdict, and Grok's readiness cap matches the shared budget
skygunnere375e704e802
diff --git a/server/drivers/acp/grok-mcp-ready.test.ts b/server/drivers/acp/grok-mcp-ready.test.tsnew file mode 100644index 0000000000..1dc7ce0dd1--- /dev/null+++ b/server/drivers/acp/grok-mcp-ready.test.ts@@ -0,0 +1,47 @@+// Grok's readiness wait for the tool selection's MCP catalog: it ends on Grok's own confirmation, pacing on the+// shared budget, not on a wall clock shorter than a server's own start.+import { describe, expect, it, vi } from "vitest";++import type { SendTurnInput } from "../../contracts.ts";+import { GROK_SUPPORT } from "./grok.ts";++// Grok's readiness loop paces on timers/promises, which fake timers cannot reach: tie it to the faked global clock.+vi.mock("node:timers/promises", async (importOriginal) => ({+ ...(await importOriginal<typeof import("node:timers/promises")>()),+ setTimeout: (ms: number, value?: unknown) => new Promise((resolve) => { globalThis.setTimeout(() => resolve(value), ms); }),+}));++describe("Grok confirms its selected MCP catalog", () => {+ it("keeps waiting while Grok reports progress past the old cap, and accepts the catalog when it resolves", async () => {+ vi.useFakeTimers();+ try {+ let polls = 0;+ const request = async (method: string) => {+ if (method !== "_x.ai/mcp/list") return {};+ polls += 1;+ const resolved = polls > 220;+ return { result: { servers: [{ name: "notes", session: { enabled: true, status: resolved ? "ready" : "starting" } }], sessionMcpResolved: resolved } };+ };+ const turn = { toolScope: { allow: ["mcp:notes:*"] }, integrations: { custom: { notes: { command: "notes" } } } } as unknown as SendTurnInput;+ const run = GROK_SUPPORT.configureSession!({ request, sessionId: "s", turn, sessionModels: [], currentModelId: undefined, configOptions: [], effortApplied: () => {} } as unknown as Parameters<NonNullable<typeof GROK_SUPPORT.configureSession>>[0]);+ let outcome: string | undefined;+ void run.then(() => { outcome = "confirmed"; }, (error: Error) => { outcome = error.message; });+ for (let step = 0; step < 400 && outcome === undefined; step += 1) await vi.advanceTimersByTimeAsync(100);+ expect(polls, "it was still resolving when the old ten-second cap had passed").toBeGreaterThan(220);+ expect(outcome).toBe("confirmed");+ } finally { vi.useRealTimers(); }+ });++ it("ends the turn when the confirmation never comes, even past a catalog that answers", async () => {+ vi.useFakeTimers();+ try {+ const request = async () => ({ result: { servers: [], sessionMcpResolved: false } });+ const turn = { toolScope: { allow: ["mcp:notes:*"] }, integrations: { custom: { notes: { command: "notes" } } } } as unknown as SendTurnInput;+ const run = GROK_SUPPORT.configureSession!({ request, sessionId: "s", turn, sessionModels: [], currentModelId: undefined, configOptions: [], effortApplied: () => {} } as unknown as Parameters<NonNullable<typeof GROK_SUPPORT.configureSession>>[0]);+ let outcome: string | undefined;+ void run.then(() => { outcome = "confirmed"; }, (error: Error) => { outcome = error.message; });+ for (let step = 0; step < 700 && outcome === undefined; step += 1) await vi.advanceTimersByTimeAsync(100);+ expect(outcome).toBe("Grok did not confirm its selected MCP catalog in time. No prompt was sent.");+ } finally { vi.useRealTimers(); }+ });+});diff --git a/server/drivers/acp/grok.ts b/server/drivers/acp/grok.tsindex ddd34a7080..70758f7d2f 100644--- a/server/drivers/acp/grok.ts+++ b/server/drivers/acp/grok.ts@@ -19,6 +19,7 @@ import type { AcpPromptSteer } from "./steer.ts";import { bundledEngineCatalog } from "../../model-manifest/bundled.ts";import { currentEngineCatalog } from "../../model-manifest/manifest.ts";import { ENGINE_MODEL_ID } from "../../model-manifest/schema.ts";+import { REMOTE_MCP_STARTUP_MS } from "../../mcp-http.ts";import type { AcpQuestionRequest } from "./question-requests.ts";import { allowsTool, canUseMcpServer, narrowsNativeTools, parseToolScope } from "../../../shared/tool-scope.ts";import { OWN_APPS_SERVER } from "../../../shared/own-apps.ts";@@ -497,7 +498,7 @@ export function grokPermissionRequest(params: Record<string, any>): Record<strin};}-const support: AcpSupport = {+export const GROK_SUPPORT: AcpSupport = {driverKind: "grokAgent",questionRequests: {"_x.ai/ask_user_question": GROK_ASK_USER_QUESTION,@@ -556,7 +557,7 @@ const support: AcpSupport = {const resolved = ensureGrokInjectSlug(model, env);return resolved !== "default" && SLUG.test(resolved) ? resolved : undefined;},- spawnContractArgs: (config, turn) => grokContractArgs(support.spawnArgs(config, turn), turn),+ spawnContractArgs: (config, turn) => grokContractArgs(GROK_SUPPORT.spawnArgs(config, turn), turn),loadReplayQuietMs: (turn) => narrowsNativeTools(turn.toolScope) ? undefined : GROK_LOAD_REPLAY_QUIET_MS,permissionRequest: grokPermissionRequest,@@ -578,7 +579,9 @@ const support: AcpSupport = {...(turn.integrations?.data ? ["data"] : []), ...(turn.integrations?.email ? ["email"] : []), ...(turn.integrations?.device ? ["device"] : []),...Object.keys(turn.integrations?.custom ?? {}),].filter((name) => canUseMcpServer(turn.toolScope, name)));- const deadline = Date.now() + 10_000;+ // Grok bounds a server that never comes up with its own startup_timeout_sec; this only bounds the confirmation, no+ // shorter than the wait a remote MCP server gets elsewhere.+ const deadline = Date.now() + REMOTE_MCP_STARTUP_MS;for (;;) {const reply = await request("_x.ai/mcp/list", { sessionId, cache: true }, 10_000);const catalog = reply?.result;@@ -653,4 +656,4 @@ const support: AcpSupport = {buildPromptText: (turn) => (turn.system ? `${turn.system}\n\n${turn.text}` : turn.text),};-export const GrokAgentDriver = createAcpDriver(support);+export const GrokAgentDriver = createAcpDriver(GROK_SUPPORT);diff --git a/server/drivers/chat-host-computer.test.ts b/server/drivers/chat-host-computer.test.tsindex aa63dcdd51..829e768b6f 100644--- a/server/drivers/chat-host-computer.test.ts+++ b/server/drivers/chat-host-computer.test.ts@@ -5,6 +5,7 @@ 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 = `@@ -160,30 +161,36 @@ 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, and the gated server can join after the mount.+ // 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.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[] = [];- 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();+ 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(); }}, 30_000);});diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex 90d5390219..5053e2abdc 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) => {- const session = await mountChatTools(integrations, signal, false, undefined, undefined, undefined, undefined, undefined, toolLimit, { background: true, ...(onSettled ? { onSettled } : {}) });+ 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 });sessions.push(session);return session;};@@ -1577,31 +1577,43 @@ describe("Chat MCP servers starting in the background", () => {return lines;};- it("starts the turn once the agents server is up, and lists a slow server's tools when it joins", async () => {+ it("waits for a configured server that starts within the budget, and lists its tools from the first request", 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("says when a server that was still starting is skipped", async () => {+ it("skips a configured server that fails within the wait, saying so before the model runs", 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(session.skipped).toEqual([]);- expect(await joined(session)).toEqual([expect.stringMatching(/^MCP server "late" was skipped for this turn: .*invalid result/)]);+ expect(chatToolNotices(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.@@ -1623,39 +1635,42 @@ 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 offering the tool its call tool is listed as, it joins after the first round.- const go = gate();- const late = catalog(["call_tool"], [go]);+ // 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 });const controller = new AbortController();controllers.push(controller);- 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" });+ 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(); }});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", the name the searched "b" of "x_a" already has.- const listed = catalog(["a_b", "p_1"]);+ // 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"]);const searched = catalog(["b", ...syntheticToolNames("c", 5)]);const gates = settledGates("x", "x_a");const agents = catalog(["write"], gates.files);- const go = gate();- const late = catalog(["write"], [go]);+ const late = await startFakeHttpMcp({ tools: [{ name: "call_tool", description: "Runs a tool", inputSchema: { type: "object" } }], toolsDelayMs: 1_200 });const controller = new AbortController();controllers.push(controller);- 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" });+ 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(); }});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 a752018fbd..75517aa1e2 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -82,6 +82,8 @@ 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;@@ -101,8 +103,9 @@ 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 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. */+ * 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. */export interface ChatToolMountOptions {startupMs?: number;hostComputerMs?: number;@@ -767,6 +770,7 @@ 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);@@ -802,6 +806,20 @@ 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 961c63b1b4..48b6d9d4df 100644--- a/server/drivers/openai-chat-tools.test.ts+++ b/server/drivers/openai-chat-tools.test.ts@@ -1537,38 +1537,34 @@ 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 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");+ 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.let settledBeforeFirst: boolean | null = null;- const notes = catalog(["note"], { after: [go] });+ const notes = await startFakeHttpMcp({ tools: [{ name: "note", description: "Note", inputSchema: { type: "object" } }], toolsDelayMs: 9_500 });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")]);});- 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([]);- });+ 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);it("lists fewer tools when servers that joined after a tool call go past the provider's limit", async () => {- 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 notes = await startFakeHttpMcp({ tools: syntheticToolNames("note", 5).map((name) => ({ name, description: "Note", inputSchema: { type: "object" } })), toolsDelayMs: 9_500 });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")]);}@@ -1579,16 +1575,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 } } });- expect(await f.completed()).toMatchObject({ ok: true });- } finally { console.warn = warn; }+ 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; }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/host/mcp-servers-host.test.ts b/server/host/mcp-servers-host.test.tsindex 7b5c4eebea..3b9abd9375 100644--- a/server/host/mcp-servers-host.test.ts+++ b/server/host/mcp-servers-host.test.ts@@ -11,6 +11,7 @@ import { providerToolAllowKey } from "../provider-tool-allow.ts";import { VaultStore } from "../vault-store.ts";import { createMcpKeys } from "../vault/mcp-keys.ts";import { claimedNotice, createMcpServersHost, startCheckTimeout } from "./mcp-servers-host.ts";+import * as probeModule from "../mcp-probe.ts";import type { BrokerPath } from "../bot-box/broker-probe.ts";import { notMcpError, type UrlAnswer } from "./mcp-url-checks.ts";@@ -127,6 +128,30 @@ it("says it in one plain line per bot", () => {expect(claimedNotice("Iris", ["blender"])).toBe("The Blender tool only works for Iris, so it's off for your other bots.");});+it("a start check that only runs out of time is no verdict: the server stays in turns and is not announced", async () => {+ const data = mkdtempSync(join(tmpdir(), "omb-mcp-host-timeout-"));+ dirs.push(data);+ const cfg = { mcpServers: { notes: { command: "npx", args: ["-y", "@x/notes-mcp"], enabled: true } } } as AppConfig;+ const told: Array<{ text: string; about: string }> = [];+ const host = createMcpServersHost({+ dataDir: data,+ cfg: () => cfg,+ persist: (next) => { cfg.mcpServers = next; },+ bots: () => [IRIS],+ startsServers: () => true,+ boxed: () => true,+ policy: (servers) => servers,+ tell: (text, about) => told.push({ text, about: about.id }),+ });+ const probe = vi.spyOn(probeModule, "probeMcpServer").mockResolvedValue({ ok: false, error: "The server did not answer in time.", reason: "timeout" });+ try {+ await host.prepare(IRIS);+ expect(Object.keys(host.mounted(IRIS)), "a timed-out probe is not a failed start").toEqual(["notes"]);+ expect(host.off(IRIS)).toEqual([]);+ expect(told).toEqual([]);+ } finally { probe.mockRestore(); }+});+it("tests a command server as its bot's turns start it, from that bot's own folder, and any other as any bot's", () => {const { host, data } = setup();expect(host.probeAs({})).toEqual({});diff --git a/server/host/mcp-servers-host.ts b/server/host/mcp-servers-host.tsindex 4aa9c24da6..7a27d7c879 100644--- a/server/host/mcp-servers-host.ts+++ b/server/host/mcp-servers-host.ts@@ -127,7 +127,7 @@ export function createMcpServersHost(deps: McpServersHostDeps) {const keyedStart = deps.keys ? deps.keys.resolve(name, server) : { ok: true as const, server };if (!keyedStart.ok) return { ok: false, error: keyedStart.why };const result = await probeMcpServer({ ...keyedStart.server, enabled: true }, startCheckTimeout(server.command), undefined, { asBot: asBot(botId) });- return result.ok ? { ok: true } : { ok: false, error: result.error };+ return result.ok ? { ok: true } : { ok: false, error: result.error, ...(result.reason === "timeout" ? { timeout: true as const } : {}) };});const checks = createMcpHealth({file: join(deps.dataDir, "mcp-health.json"),diff --git a/server/mcp-health.test.ts b/server/mcp-health.test.tsindex 4ecd0f5780..b88124a9e2 100644--- a/server/mcp-health.test.ts+++ b/server/mcp-health.test.ts@@ -62,6 +62,30 @@ describe("checking that command servers start", () => {expect(JSON.parse(readFileSync(deps.file, "utf8")).notes.told).toBeTruthy();});+ it("treats a check that ran out of time as no verdict: the server stays in turns, is not said to be off, and is tried again soon", async () => {+ const { deps, servers, told, tick } = fixture({ servers: { notes } });+ const starts: string[] = [];+ const health = createMcpHealth({ ...deps, start: async (name, _server, botId) => {+ starts.push(`${name}:${botId}`);+ return { ok: false, error: "The server did not answer in time.", timeout: true };+ } });+ await health.prepare("paul", ["notes"]);+ expect(health.usable("paul", servers), "a timed-out probe is not a failed start").toEqual(servers);+ expect(health.off("paul", ["notes"])).toEqual([]);+ expect(health.offFor("notes")).toEqual([]);+ expect(told).toEqual([]);+ expect(JSON.parse(readFileSync(deps.file, "utf8")).notes.checks["*"], "recorded, with why it is no verdict").toMatchObject({ ok: false, timeout: true });+ tick(60_000 - 1);+ await health.prepare("paul", ["notes"]);+ expect(starts).toEqual(["notes:paul"]);+ tick(1);+ await health.prepare("paul", ["notes"]);+ expect(starts, "tried again after a minute, not half an hour").toEqual(["notes:paul", "notes:paul"]);+ await health.settled();+ const again = createMcpHealth(deps);+ expect(again.usable("paul", servers), "kept across a restart").toEqual(servers);+ });+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 86ce586d67..e86c7b7428 100644--- a/server/mcp-health.ts+++ b/server/mcp-health.ts@@ -1,7 +1,9 @@// Whether each command MCP server starts, started the way a bot's AI would start it. One that does not start is left// out of turns (an engine that mounts it anyway fails it on every session, and Claude Code then repeats the failure-// under every tool search), the person hears about it once, and it is tried again on its own. A bot's own server is-// checked for that bot; any other server starts the same for every bot on this computer, so one check stands for all.+// under every tool search), the person hears about it once, and it is tried again on its own. A check that only ran out+// of time is no verdict: the server stays in turns, nothing is said, and the check is tried again soon. A bot's own+// server is checked for that bot; any other server starts the same for every bot on this computer, so one check stands+// for all.import { createHash } from "node:crypto";import { readFileSync, statSync } from "node:fs";import { isAbsolute } from "node:path";@@ -9,14 +11,16 @@ import { isAbsolute } from "node:path";import { writeFileAtomic } from "./atomic.ts";import type { McpServerSpec, StdioMcpSpec } from "./contracts.ts";-/** A server that did not start is tried again after this long; one that started is trusted this long. */+/** A server that did not start is tried again after this long; one that started is trusted this long; a check that ran+ * out of time is tried again after this long. */export const RECHECK_FAILED_MS = 30 * 60_000;export const RECHECK_STARTED_MS = 6 * 60 * 60_000;+export const RECHECK_TIMEOUT_MS = 60_000;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 }+export interface McpStartCheck { ok: boolean; at: number; error?: string; timeout?: true }interface ServerHealth { key: string; checks: Record<string, McpStartCheck>; told?: string }type Bot = { id: string; name: string };type CommandServer = StdioMcpSpec & { bot?: string };@@ -27,8 +31,9 @@ export interface McpHealthDeps {servers(): Record<string, CommandServer>;/** The bots whose turns start `name`. */users(name: string): Bot[];- /** Starts the server as `botId`'s AI would and lists its tools. */- start(name: string, server: StdioMcpSpec, botId: string): Promise<{ ok: true } | { ok: false; error: string }>;+ /** Starts the server as `botId`'s AI would and lists its tools. `timeout: true`: the check ran out of time, which is+ * no verdict about the server. */+ start(name: string, server: StdioMcpSpec, botId: string): Promise<{ ok: true } | { ok: false; error: string; timeout?: true }>;/** Says it to the person, once. */tell(text: string, about: Bot): void;now?(): number;@@ -71,14 +76,18 @@ export function createMcpHealth(deps: McpHealthDeps) {const health = state[name];return health && health.key === startKey(server) ? health.checks?.[standsFor(server, botId)] : undefined;};- const due = (check: McpStartCheck | undefined) => !check || now() - check.at >= (check.ok ? RECHECK_STARTED_MS : RECHECK_FAILED_MS);+ /** 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;+ const due = (check: McpStartCheck | undefined) =>+ !check || now() - check.at >= (check.ok ? RECHECK_STARTED_MS : check.timeout ? 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 }) => {+ 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: {} });- 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;+ health.checks[standsFor(server, botId)] = result.ok ? { ok: true, at: now() }+ : { ok: false, at: now(), error: result.error, ...(result.timeout ? { timeout: true } : {}) };+ const tell = provenFailure(health.checks[standsFor(server, botId)]) && health.told !== key;if (tell) health.told = key;save();if (!tell) return;@@ -126,20 +135,20 @@ export function createMcpHealth(deps: McpHealthDeps) {/** `mounted` without the command servers that did not start. */usable<T extends McpServerSpec>(botId: string, mounted: Record<string, T>): Record<string, T> {const servers = deps.servers();- return Object.fromEntries(Object.entries(mounted).filter(([name]) => !servers[name] || checkOf(name, servers[name], botId)?.ok !== false));+ return Object.fromEntries(Object.entries(mounted).filter(([name]) => !servers[name] || !provenFailure(checkOf(name, servers[name], botId))));},/** Which of `names` are left out of this bot's turns, with why. */off(botId: string, names: readonly string[]): Array<{ name: string; error: string }> {const servers = deps.servers();return names.flatMap((name) => {const last = servers[name] ? checkOf(name, servers[name], botId) : undefined;- return last && !last.ok ? [{ name, error: last.error ?? "It did not start." }] : [];+ return provenFailure(last) ? [{ name, error: last!.error ?? "It did not start." }] : [];});},/** Who a server is off for, by bot id. */offFor(name: string): string[] {const server = deps.servers()[name];- return server ? deps.users(name).filter((bot) => checkOf(name, server, bot.id)?.ok === false).map((bot) => bot.id) : [];+ return server ? deps.users(name).filter((bot) => provenFailure(checkOf(name, server, bot.id))).map((bot) => bot.id) : [];},/** The bot's AI reported these did not connect: each is checked again now. */engineFailed(botId: string, names: readonly string[]): void {