Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(mcp): identify chat startup failures and keep initialize uncancelled
skygunner0888baa43282
diff --git a/server/drivers/chat-host-computer.test.ts b/server/drivers/chat-host-computer.test.tsindex ad16354c0a..8932b18e98 100644--- a/server/drivers/chat-host-computer.test.ts+++ b/server/drivers/chat-host-computer.test.ts@@ -163,7 +163,7 @@ describe("this desktop's own computer in a chat turn", () => {const session = await mount(computer(driver, { MODE: "silent" }).server, 150, 600, "c-lost", lines);expect(names(session)).toEqual(["computer_write"]);const result = await session.execute("computer_write", { value: "z" }, controller.signal);- expect(result).toMatchObject({ ok: false, text: expect.stringContaining("did not start this time (MCP startup timed out)") });+ expect(result).toMatchObject({ ok: false, text: expect.stringContaining("did not start this time (MCP startup timed out (server \"computer\"") });expect(() => session.validate("computer_write", { value: "z" })).not.toThrow();await vi.waitFor(() => expect(lines).toEqual([expect.objectContaining({ text: { key: "chat.notice.computerToolsDidNotStart", params: { why: "chat.notice.part.computerToolsTookTooLong" } } })]));});diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex 90d5390219..1c1b3dac2e 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -19,15 +19,16 @@ import { wideSchema } from "../testing/oversized-tool-schema.ts";import { schemaBytes, toolSchemaProfile } from "../tool-schema-profile.ts";const killProbe = vi.hoisted(() => ({ override: false, stopped: false, budgets: [] as number[] }));-const spawned = vi.hoisted(() => [] as Array<{ owner?: string; opts: { env?: NodeJS.ProcessEnv; box?: unknown } }>);+const spawned = vi.hoisted(() => [] as Array<{ owner?: string; opts: { env?: NodeJS.ProcessEnv; box?: unknown }; stdin: ReturnType<typeof import("../procs.ts").spawnCli>["stdin"] }>);vi.mock("../procs.ts", async (importOriginal) => {const actual = await importOriginal<typeof import("../procs.ts")>();return {...actual,// Always runs the real kill for cleanup; the override only forces the verdict and records the budget.spawnCli: (...args: Parameters<typeof actual.spawnCli>) => {- spawned.push({ owner: args[3], opts: args[2] });- return actual.spawnCli(...args);+ const child = actual.spawnCli(...args);+ spawned.push({ owner: args[3], opts: args[2], stdin: child.stdin });+ return child;},killCliTree: (child: Parameters<typeof actual.killCliTree>[0], budget = 5_000) => {killProbe.budgets.push(budget);@@ -77,7 +78,9 @@ function fixture(body = "", toolSchema: Record<string, unknown> = schema) {const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1);const message = JSON.parse(line);calls.push(message);- writeFileSync(receipt, JSON.stringify({pid:process.pid,path:process.env.PATH,omb:Object.fromEntries(Object.entries(process.env).filter(([name]) => name.startsWith("OMB_"))),calls}));+ if (message.method !== "notifications/cancelled") {+ writeFileSync(receipt, JSON.stringify({pid:process.pid,path:process.env.PATH,omb:Object.fromEntries(Object.entries(process.env).filter(([name]) => name.startsWith("OMB_"))),calls}));+ }${body}if (message.method === "initialize") reply(message, {protocolVersion:"2024-11-05",capabilities:{tools:{}}});else if (message.method === "tools/list") reply(message, {tools:[{name:"write",description:"Fixture write",inputSchema:schema}]});@@ -489,11 +492,19 @@ describe("Chat MCP session", () => {});// tools/list needs a budget that outlasts the child's own start, or the overrun would land in initialize.- it.each([["initialize", 150], ["tools/list", 2_500]] as const)("reports an overrun in %s as a startup timeout, not as a request whose outcome is uncertain", async (method, budget) => {+ it.each([["initialize", 1_000], ["tools/list", 2_500]] as const)("reports an overrun in %s as a startup timeout, not as a request whose outcome is uncertain", async (method, budget) => {const f = fixture(`if (message.method === "${method}") { return; }`);- const client = new ChatMcpClient(f.server);- await expect(client.tools(f.controller.signal, undefined, budget)).rejects.toThrow(/^MCP startup timed out$/);- await client.close();+ const client = new ChatMcpClient(f.server, false, true, "audit");+ const id = method === "initialize" ? 1 : 2;+ const write = vi.spyOn(spawned.at(-1)!.stdin!, "write");+ try {+ await expect(client.tools(f.controller.signal, undefined, budget)).rejects.toThrow(new RegExp(+ `^MCP startup timed out.*"audit".*${method}.*request ${id}.*startup budget ${budget}ms.*request budget \\d+ms.*pipe write completed.*matching response absent.*request elapsed \\d+ms.*cleanup confirmed in \\d+ms`,+ ));+ const cancels = write.mock.calls.map(([chunk]) => JSON.parse(String(chunk))).filter((frame) => frame.method === "notifications/cancelled");+ expect(cancels.map((frame) => frame.params.requestId)).toEqual(method === "initialize" ? [] : [id]);+ expect(alive(f.read().pid)).toBe(false);+ } finally { write.mockRestore(); await client.close(); }});});@@ -589,7 +600,7 @@ describe("Chat MCP session", () => {const session = await mountChatTools({ composio: refused.server, custom: { ready: ready.server } }, ready.controller.signal);sessions.push(session);expect(session.definitions.map((definition) => definition.function.name)).toEqual(["ready_write"]);- expect(session.skipped).toEqual([{ server: "composio", reason: expect.stringContaining("MCP request failed") }]);+ expect(session.skipped).toEqual([{ server: "composio", reason: expect.stringContaining('MCP server refused the startup request (server "composio", tools/list request 2') }]);expect(warn).toHaveBeenCalledWith(expect.stringContaining(`"composio"`));await vi.waitFor(() => expect(alive(refused.read().pid)).toBe(false));expect(alive(ready.read().pid)).toBe(true);@@ -778,20 +789,60 @@ describe("Chat MCP session", () => {receipt = JSON.parse(readFileSync(f.receipt, "utf8"));expect(receipt.helper).toBeGreaterThan(0);}, { timeout: 10_000 });+ const write = vi.spyOn(spawned.at(-1)!.stdin!, "write");f.controller.abort();await rejected;+ const notifications = write.mock.calls.map(([chunk]) => JSON.parse(String(chunk)));+ if (method === "initialize") expect(notifications).toEqual([]);+ else expect(notifications).toEqual([expect.objectContaining({ method: "notifications/cancelled", params: expect.objectContaining({ requestId: method === "tools/list" ? 2 : 3 }) })]);+ write.mockRestore();expect(alive(receipt.pid)).toBe(false);expect(alive(receipt.helper)).toBe(false);});});describe("Chat MCP shutdown verdict", () => {+ it.each(["initialize", "tools/list"])("closes a pending %s wait with only eligible cancellation", async (method) => {+ const f = fixture(`if (message.method === "${method}") continue;`);+ const client = new ChatMcpClient(f.server);+ const pending = expect(client.call(method, {}, f.controller.signal, 5_000)).rejects.toThrow("MCP session closed");+ try {+ await vi.waitFor(() => expect(f.read().calls.some((call) => call.method === method)).toBe(true));+ const write = vi.spyOn(spawned.at(-1)!.stdin!, "write");+ try {+ await client.close();+ await pending;+ const frames = write.mock.calls.map(([chunk]) => JSON.parse(String(chunk)));+ expect(frames).toEqual(method === "initialize" ? [] : [expect.objectContaining({ method: "notifications/cancelled" })]);+ expect(alive(f.read().pid)).toBe(false);+ } finally { write.mockRestore(); }+ } finally { await client.close(); }+ });+afterEach(() => {killProbe.override = false;killProbe.stopped = false;killProbe.budgets.length = 0;});+ it("preserves a startup refusal through unconfirmed cleanup without upstream error text", async () => {+ const f = fixture(`if (message.method === "tools/list") {+ process.stderr.write("private stderr fixture\\n");+ send({jsonrpc:"2.0",id:message.id,error:{code:-32602,message:"private upstream fixture"}});+ continue;+ }`);+ killProbe.override = true;+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ try {+ const session = await f.mount();+ expect(session.skipped).toEqual([{ server: "audit", reason: expect.stringMatching(+ /MCP server refused the startup request.*server "audit".*tools\/list request 2.*matching response received.*cleanup unconfirmed in \d+ms/,+ ) }]);+ expect(session.skipped[0]!.reason).not.toMatch(/private|-32602/);+ expect(alive(f.read().pid)).toBe(false);+ } finally { warn.mockRestore(); }+ });+it("a slow shutdown resolves close when no call was in flight", async () => {const f = fixture();const session = await f.mount();diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex a751745f8e..167a0800bf 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -154,12 +154,16 @@ export class ChatMcpClient {private closed = false;private closing?: Promise<void>;private failure?: string;+ private cleanup?: { elapsed: number; stopped: boolean };+ private listed = false;private stderrTail = "";private readonly configured: string[];- private pending = new Map<number, { method: string; resolve(value: unknown): void; reject(error: Error): void }>();+ private readonly label: string;+ private pending = new Map<number, { method: string; cancel(): void; resolve(value: unknown): void; reject(error: Error, matched?: boolean): void }>();/** `configured`: a server the person set up, whose own environment passes the bot box as theirs. */- constructor(server: Server, computerUse = false, configured = false) {+ constructor(server: Server, computerUse = false, configured = false, label = "computer") {+ this.label = label;this.frameBytes = computerUse ? 32 * 1024 * 1024 : FRAME_BYTES;this.configured = Object.values(server.env).filter((value) => value.length >= 6);try {@@ -175,7 +179,7 @@ export class ChatMcpClient {this.child.on("error", () => this.fail(new Error("MCP server could not start; check its command and installation")));// "close" follows the last of its output, so what it said on the way out is read first; a helper still holding stderr doesn't hold this up.this.child.on("exit", () => {- const stop = () => this.fail(new Error(`MCP server exited before the session closed.${this.lastWords()}`));+ const stop = () => this.fail(new Error(`MCP server exited before the session closed.${this.listed ? this.lastWords() : ""}`));this.child.once("close", stop);setTimeout(stop, 200).unref();});@@ -202,15 +206,19 @@ export class ChatMcpClient {close(): Promise<void> {if (this.closing) return this.closing;+ const started = performance.now();+ const inFlight = [...this.pending.values()].some((entry) => entry.method === "tools/call");+ for (const entry of this.pending.values()) {+ entry.cancel();+ entry.reject(new Error("MCP session closed"));+ }this.closed = true;- // Read before the pending rejections below: only a call still in flight at entry is genuinely uncertain.- const inFlight = this.pending.size > 0;- for (const entry of this.pending.values()) entry.reject(new Error("MCP session closed"));this.pending.clear();this.buffer = "";// Windows reaps the tree via taskkill /T, which can exceed shorter budgets on a loaded machine;// elsewhere the budget is the TERM grace before KILL, not a verdict race, so it stays short.- this.closing = killCliTree(this.child, process.platform === "win32" ? 15_000 : 5_000).then((stopped) => {+ this.closing = killCliTree(this.child, process.platform === "win32" ? 15_000 : 5_000).catch(() => false).then((stopped) => {+ this.cleanup = { elapsed: Math.round(performance.now() - started), stopped };if (stopped) return;if (!inFlight) {console.warn("chat-mcp: shutdown could not be confirmed within its budget; no call was in flight, so the turn outcome is unaffected");@@ -221,11 +229,11 @@ export class ChatMcpClient {return this.closing;}- private write(frame: unknown): void {+ private write(frame: unknown, callback?: (error?: Error | null) => void): void {if (this.closed || !this.child.stdin.writable || this.child.stdin.destroyed) throw new Error("MCP session closed");const encoded = JSON.stringify(frame) + "\n";if (Buffer.byteLength(encoded) > this.frameBytes) throw new Error("MCP request exceeds the frame limit");- this.child.stdin.write(encoded);+ this.child.stdin.write(encoded, callback);}private onData(chunk: string): void {@@ -253,59 +261,80 @@ export class ChatMcpClient {const entry = this.pending.get(message.id);if (!entry) continue;this.pending.delete(message.id);- if ("error" in message) entry.reject(new McpRequestRefused(mcpRefusalText(entry.method, message.error)));- else if (!("result" in message)) entry.reject(new Error("MCP response has no result"));+ if ("error" in message) entry.reject(new McpRequestRefused(mcpRefusalText(entry.method, message.error)), true);+ else if (!("result" in message)) entry.reject(new Error("MCP response has no result"), true);else entry.resolve(message.result);}if (Buffer.byteLength(this.buffer) > this.frameBytes) this.fail(new Error("MCP response exceeds the frame limit"));}- async call(method: string, params: unknown, signal: AbortSignal, timeout: number, keepOnRefusal = false, timedOut = REQUEST_TIMED_OUT): Promise<unknown> {- if (signal.aborted) { await this.close(); throw aborted(); }- if (this.closed) throw new Error(this.failure ?? "MCP session closed");+ async call(method: string, params: unknown, signal: AbortSignal, timeout: number, keepOnRefusal = false, startupMs?: number): Promise<unknown> {const id = this.nextId++;+ const started = performance.now();+ const timedOut = startupMs === undefined ? REQUEST_TIMED_OUT : STARTUP_TIMED_OUT;+ let writeState = "not attempted";+ let matched = false;try {+ if (signal.aborted) throw aborted();+ if (this.closed) throw new Error(this.failure ?? "MCP session closed");+ if (timeout <= 0) throw new Error(timedOut);return await new Promise((resolve, reject) => {const finish = (error?: Error, value?: unknown) => {clearTimeout(timer);- signal.removeEventListener("abort", cancel);+ signal.removeEventListener("abort", onAbort);this.pending.delete(id);if (error) reject(error); else resolve(value);};const cancel = () => {+ // MCP cancellation excludes initialize, including when its wait times out or the transport closes.+ if (method === "initialize" || writeState === "failed" || writeState === "not attempted") return;try { this.write({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: id, reason: "Cancelled" } }); }catch {}- finish(aborted());};- const timer = setTimeout(() => finish(new Error(timedOut)), timeout);+ const onAbort = () => { cancel(); finish(aborted()); };+ const timer = setTimeout(() => { cancel(); finish(new Error(timedOut)); }, timeout);timer.unref();- signal.addEventListener("abort", cancel, { once: true });- this.pending.set(id, { method, resolve: (value) => finish(undefined, value), reject: (error) => finish(error) });- try { this.write({ jsonrpc: "2.0", id, method, params }); }- catch { finish(new Error("MCP request could not be sent")); }+ signal.addEventListener("abort", onAbort, { once: true });+ this.pending.set(id, { method, cancel, resolve: (value) => finish(undefined, value), reject: (error, received = false) => {+ matched = received;+ finish(error);+ } });+ try {+ writeState = "pending";+ this.write({ jsonrpc: "2.0", id, method, params }, (error) => { writeState = error ? "failed" : "completed"; });+ } catch {+ writeState = "failed";+ finish(new Error("MCP request could not be sent"));+ }});} catch (error) {- if (!(keepOnRefusal && error instanceof McpRequestRefused)) await this.close();- throw error;+ if (keepOnRefusal && error instanceof McpRequestRefused) throw error;+ const elapsed = Math.round(performance.now() - started);+ const atFailure = writeState;+ await this.close().catch(() => {});+ if (startupMs === undefined || !(error instanceof Error)) throw error;+ const { elapsed: cleanupMs, stopped } = this.cleanup!;+ const reason = error instanceof McpRequestRefused ? "MCP server refused the startup request" : error.message;+ throw new Error(`${reason} (server ${JSON.stringify(this.label)}, ${method} request ${id}, ` ++ `startup budget ${startupMs}ms, request budget ${timeout}ms, pipe write ${atFailure}, ` ++ `matching response ${matched ? "received" : "absent"}, request elapsed ${elapsed}ms, ` ++ `cleanup ${stopped ? "confirmed" : "unconfirmed"} in ${cleanupMs}ms)`);}}async tools(signal: AbortSignal, include: (tool: unknown) => boolean = () => true, startupMs = STARTUP_MS, observer?: AppObserver): Promise<unknown[]> {- const deadline = Date.now() + startupMs;- const remaining = () => {- if (Date.now() >= deadline) throw new Error(STARTUP_TIMED_OUT);- return deadline - Date.now();- };+ const deadline = performance.now() + startupMs;+ const remaining = () => Math.max(0, Math.ceil(deadline - performance.now()));const handshake = { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "openmausbot-chat", version: "1" } };let initialized: unknown;if (observer?.mount.extension) {- try { initialized = await this.call("initialize", withUiExtension(handshake), signal, remaining(), true, STARTUP_TIMED_OUT); }+ try { initialized = await this.call("initialize", withUiExtension(handshake), signal, remaining(), true, startupMs); }catch (error) {if (!(error instanceof McpRequestRefused)) throw error;- initialized = await this.call("initialize", handshake, signal, remaining(), false, STARTUP_TIMED_OUT);+ initialized = await this.call("initialize", handshake, signal, remaining(), false, startupMs);}} else {- initialized = await this.call("initialize", handshake, signal, remaining(), false, STARTUP_TIMED_OUT);+ initialized = await this.call("initialize", handshake, signal, remaining(), false, startupMs);}if (!object(initialized)) throw new Error("MCP initialization returned an invalid result");observer?.initialized(initialized);@@ -315,12 +344,15 @@ export class ChatMcpClient {const cursors = new Set<string>();let cursor: string | undefined;for (let page = 0; page < MAX_PAGES; page += 1) {- const result = await this.call("tools/list", cursor ? { cursor } : {}, signal, remaining(), false, STARTUP_TIMED_OUT);+ const result = await this.call("tools/list", cursor ? { cursor } : {}, signal, remaining(), false, startupMs);if (!object(result) || !Array.isArray(result.tools)) throw new Error("MCP tools/list returned an invalid result");observer?.listed(result);tools.push(...result.tools.filter((tool) => modelVisible(tool) && include(tool)));if (tools.length > SERVER_TOOLS_MAX) throw new Error(`MCP server offers more than ${SERVER_TOOLS_MAX} tools`);- if (result.nextCursor === undefined) return tools;+ if (result.nextCursor === undefined) {+ this.listed = true;+ return tools;+ }if (typeof result.nextCursor !== "string" || !result.nextCursor || cursors.has(result.nextCursor)) throw new Error("MCP tools/list returned an invalid pagination cursor");cursors.add(result.nextCursor);cursor = result.nextCursor;@@ -769,7 +801,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]// Concurrent starts, consumed in config order so names and collision suffixes stay stable.const mounts = servers.map(async ([name, descriptor], index): Promise<Mounted> => {if (signal.aborted || closed) throw aborted();- const client = new ChatMcpClient(descriptor, computerUse, index >= builtIns);+ const client = new ChatMcpClient(descriptor, computerUse, index >= builtIns, name);clients.push(client);started.set(name, client);startedAt[index] = client;diff --git a/server/mcp-http.test.ts b/server/mcp-http.test.tsindex 83cb43acfe..eefbbeebc4 100644--- a/server/mcp-http.test.ts+++ b/server/mcp-http.test.ts@@ -10,6 +10,28 @@ afterEach(async () => {await fake?.close(); fake = undefined;});+describe("request cancellation", () => {+ it.each(["initialize", "tools/list", "tools/call"])("cancels an HTTP wait for %s with only eligible notifications", async (method) => {+ const frames: unknown[] = [];+ client = new RemoteMcpClient({ type: "http", url: "https://fixture.example/mcp", headers: {} }, { fetch: async (_url, init) => {+ const frame = JSON.parse(String(init?.body));+ frames.push(frame);+ if (frame.method === "notifications/cancelled") return new Response(null, { status: 202 });+ return new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener("abort", () => reject(new Error("cancelled locally")), { once: true });+ });+ } });+ const controller = new AbortController();+ const request = client.request(method, {}, controller.signal);+ controller.abort();+ await expect(request).rejects.toThrow("cancelled locally");+ expect(frames).toEqual([+ { jsonrpc: "2.0", method, id: 1, params: {} },+ ...(method === "initialize" ? [] : [{ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: 1, reason: "Request cancelled" } }]),+ ]);+ });+});+describe("a server's own requests to the client", () => {it("does not charge earlier SSE replies against a later request's byte limit", async () => {fake = await startFakeHttpMcp({ transport: "sse", tools: [{ name: "still_available" }] });diff --git a/server/mcp-http.ts b/server/mcp-http.tsindex 7270ea3a2a..e6f55c8eb1 100644--- a/server/mcp-http.ts+++ b/server/mcp-http.ts@@ -261,7 +261,7 @@ export class RemoteMcpClient {const onAbort = () => {void this.notify("notifications/cancelled", { requestId: id, reason: "Request cancelled" }, AbortSignal.timeout(2_000)).catch(() => {});};- signal.addEventListener("abort", onAbort, { once: true });+ if (method !== "initialize") signal.addEventListener("abort", onAbort, { once: true });const reply = this.target.type === "sse" ? this.sseRequest(id, frame, signal) : this.streamableRequest(id, frame, signal);return reply.finally(() => signal.removeEventListener("abort", onAbort));}