Skip to content

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

perf(grok): Grok reaches OpenMausBot's own MCP servers by URL, no proxy process each

milind-soni4879396effa0
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index 62ef34c08b..d208b87ad2 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -1241,13 +1241,18 @@ provider outage. So on a Cloud home (`server/engine-memory.ts`):
server is -800 and Caddy -900, so the health check is the last to go, and
the root supervisor that restarts them is -1000, never picked. When memory
runs out the kernel takes a bot's process, never the workspace.
-- **OpenCode reaches OpenMausBot's own tools over HTTP.** The agents,
- browser, computer, Data, Email and phone servers are endpoints of this server
- (`/api/internal/mcp-http/<name>`, `server/routes/own-mcp-http.ts`) with the
- turn's capability in the Authorization header, instead of a Node proxy
- process each (about 20–30 MB PSS apiece) in every OpenCode session. A server
- behind a tool selection keeps its stdio gate; the person's own servers are
- unchanged.
+- **OpenCode, Cursor, omp and Grok reach OpenMausBot's own tools over HTTP.**
+ The agents, browser, computer, Data, Email and phone servers are endpoints of
+ this server (`/api/internal/mcp-http/<name>`, `server/routes/own-mcp-http.ts`)
+ with the turn's capability in the Authorization header, instead of a Node
+ proxy process each (about 20–30 MB PSS and 7 threads apiece, all counted
+ against the pids limit) in every session. Grok gets this in each session whose
+ `initialize` answer says `mcpCapabilities.http`; otherwise it keeps the stdio
+ proxies. In the bot box the engine reaches the endpoint the way its proxies
+ did, through the box's bridge to the harness gate. A server behind a tool
+ selection keeps its stdio gate; the person's own servers and the connected
+ apps' connector are unchanged. `OMB_OWN_MCP_HTTP=0` puts every engine back on
+ the stdio proxies.
- **The reason is said, in one line.** A turn whose engine was stopped for
memory, by the home or by the kernel (a SIGKILL while `/proc/vmstat`'s
`oom_kill` rose), ends with "Ran out of room, so I closed the browser to
diff --git a/scripts/control-omb.ts b/scripts/control-omb.ts
index 12dee9ef87..00a10f97b0 100644
--- a/scripts/control-omb.ts
+++ b/scripts/control-omb.ts
@@ -296,7 +296,7 @@ export async function launchVerificationServer(
enterprise?: { dir: string; licenseKey: string },
room?: { scripted: boolean },
/** Optional repository-owned fake providers for multi-engine setup checks. */
- extraProviders: Array<"codex" | "cline" | "copilot" | "customAcp" | "opencode" | "kimi"> = [],
+ extraProviders: Array<"codex" | "cline" | "copilot" | "customAcp" | "opencode" | "kimi" | "grok"> = [],
/** Programmatic tests only: an owned loopback Boat provider, never a live account. */
boatFixtureApi?: string,
/** Programmatic web UI qualification against the fixture's static server. */
@@ -343,6 +343,10 @@ export async function launchVerificationServer(
driver: "kimiAgent", displayName: "Verification Kimi",
config: { cli: fileURLToPath(new URL("../server/testing/fake-acp-cli.ts", import.meta.url)) },
} } : {}),
+ ...(extraProviders.includes("grok") ? { grok: {
+ driver: "grokAgent", displayName: "Verification Grok",
+ config: { cli: fileURLToPath(new URL("../server/testing/fake-acp-cli.ts", import.meta.url)), fullAuto: true },
+ } } : {}),
...(extraProviders.includes("codex") ? { codex: {
driver: "codex", displayName: "Verification Codex", config: { cli: fileURLToPath(new URL("../server/testing/fake-codex-app-server.ts", import.meta.url)) },
} } : {}),
diff --git a/server/drivers/acp/acp.test.ts b/server/drivers/acp/acp.test.ts
index 249cf098ae..a40fd9df62 100644
--- a/server/drivers/acp/acp.test.ts
+++ b/server/drivers/acp/acp.test.ts
@@ -1299,6 +1299,35 @@ describe("ACP turns (fake CLI)", () => {
for (const name of ["NO_PROXY", "no_proxy"]) expect(env[name]!.split(",")).toEqual(expect.arrayContaining(["127.0.0.1", "localhost", "::1"]));
});
+ it.each([
+ { advertised: "http", setting: undefined, form: "url" },
+ { advertised: undefined, setting: undefined, form: "stdio" },
+ { advertised: "http", setting: "0", form: "stdio" },
+ ])("gives Grok OpenMausBot's own servers by URL in its first session when its initialize says it takes them (advertised=$advertised, OMB_OWN_MCP_HTTP=$setting)", async ({ advertised, setting, form }) => {
+ if (advertised) process.env.FAKE_ACP_MCP_TRANSPORTS = advertised;
+ if (setting) vi.stubEnv("OMB_OWN_MCP_HTTP", setting);
+ try {
+ await create(GrokAgentDriver);
+ const dump = join(scratch, "grok-own-http.json");
+ process.env.FAKE_ACP_DUMP = dump;
+ const harness = "http://127.0.0.1:8799";
+ const browser = { command: process.execPath, args: ["/app/dist-server/harness-mcp-proxy.js", "browser"], env: { OMB_HARNESS_URL: harness, OMB_MCP_TOKEN_BROWSER: "synthetic-browser-capability" } };
+ const notes = { command: process.execPath, args: ["/tmp/notes-mcp.js"], env: {} };
+ await instance.adapter.sendTurn({ threadId: "t-grok-own-http", text: "go", integrations: { browser, custom: { notes } } });
+ expect(await recorder.until((event) => event.type === "turn.completed")).toMatchObject({ ok: true });
+ const sent = JSON.parse(readFileSync(`${dump}.mcp.json`, "utf8"));
+ expect(sent[1]).toEqual({ name: "notes", command: process.execPath, args: ["/tmp/notes-mcp.js"], env: [] });
+ expect(sent[0]).toEqual(form === "url"
+ ? { type: "http", name: "browser", url: `${harness}/api/internal/mcp-http/browser`, headers: [{ name: "authorization", value: "Bearer synthetic-browser-capability" }] }
+ : { name: "browser", command: process.execPath, args: browser.args, env: [{ name: "OMB_HARNESS_URL", value: harness }, { name: "OMB_MCP_TOKEN_BROWSER", value: "synthetic-browser-capability" }] });
+ const { env } = JSON.parse(readFileSync(dump, "utf8")) as { env: Record<string, string> };
+ if (setting !== "0") for (const name of ["NO_PROXY", "no_proxy"]) expect(env[name]!.split(",")).toEqual(expect.arrayContaining(["127.0.0.1", "localhost", "::1"]));
+ } finally {
+ delete process.env.FAKE_ACP_MCP_TRANSPORTS;
+ vi.unstubAllEnvs();
+ }
+ });
+
it.each([false, true])("mounts Data through the existing stdio transport unless excluded (excluded=%s)", async (excluded) => {
await create();
const dump = join(scratch, "data.json");
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index db1745539c..08a1b4be9f 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -76,7 +76,7 @@ import { startupFailureRecoverable } from "./startup-recovery.ts";
import { engineFailure, engineFailureKind } from "../engine-errors.ts";
import { acpRuntimeFailure, acpStopFailure } from "./failure-words.ts";
import { narrowsNativeTools, parseToolScope } from "../../../shared/tool-scope.ts";
-import { acpMcpServers, type AcpMcpServer } from "../turn-mcp.ts"; import { acpOwnMcpOverHttp, loopbackUnproxied, noteAcpMcpHttp } from "../own-mcp-http.ts"; import { acpToolOutput, acpToolProgress } from "../tool-progress.ts";
+import { acpMcpServers, type AcpMcpServer } from "../turn-mcp.ts"; import { acpOwnMcpTransport, acpSessionMcpServers, loopbackUnproxied } from "../own-mcp-http.ts"; import { acpToolOutput, acpToolProgress } from "../tool-progress.ts";
import { learnedToolCountLimit, mcpToolBudget, retryUnderToolLimit } from "../../tool-count-limit.ts"; import { instanceEnvNames } from "../../bot-box/env.ts";
/** Failures fixed on the provider account, not by retrying; the reporting process stays pooled. */
@@ -198,8 +198,8 @@ export interface AcpSupport extends AcpDriverHooks {
clientCapabilitiesMeta?: Record<string, unknown>;
/** Made once per process: rewrites a session/update before the turn reads it, or drops it by returning null. */
updateFilter?(): (update: Record<string, any>) => Record<string, any> | null; /** Rewrites a session/request_permission's params (its options and tool call) before the card is built. */ permissionRequest?(params: Record<string, any>): Record<string, any>;
- /** The agent reaches MCP servers by URL: OpenMausBot's own servers are this server's endpoints, no process each. */
- ownMcpOverHttp?: boolean;
+ /** OpenMausBot's own MCP servers as this server's endpoints, no process each: always, or in each session whose agent's `initialize` says it reaches MCP servers by URL. */
+ ownMcpOverHttp?: boolean | "advertised";
/** How many tools the agent lists of its own beside the MCP servers', counted against a provider's tool limit. */
engineTools?: number;
/** The agent's own debug log, read while a prompt is quiet: a new line proves it alive and `parse`
@@ -986,7 +986,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
}
const resolvedModel = support.resolveTurnModel?.(turn.model, env, catalog.models);
const toolLimitKey = JSON.stringify([instanceId, resolvedModel ?? null]);
- const mcpServers = acpMcpServers(turn, { http: loopbackUnproxied(env, support.ownMcpOverHttp === true || acpOwnMcpOverHttp(instanceId, support.mcpServersFromLaunch === true)), engine: support.driverKind,
+ const ownMcp = acpOwnMcpTransport(support), mcpServers = acpMcpServers(turn, { http: loopbackUnproxied(env, ownMcp !== "stdio") && ownMcp === "http", engine: support.driverKind,
toolBudget: mcpToolBudget(learnedToolCountLimit(toolLimitKey), support.engineTools ?? 32) });
support.applyTurnEnv?.(env, {
model: resolvedModel, requestedModel: turn.model, fullAuto: turnConfig.fullAuto === true, botId: turn.botId, cwd, toolScope: turn.toolScope,
@@ -1176,7 +1176,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
},
},
INIT_TIMEOUT,
- )); noteAcpMcpHttp(instanceId, session.initResult);
+ ));
}
if (!skipSubscriptionAuthForLocalInject(turn.model) && !session.authenticated) {
const methods: Array<{ id?: string }> = Array.isArray(session.initResult?.authMethods)
@@ -1222,7 +1222,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
try {
await request(
support.resumeMethod === "resume" ? "session/resume" : "session/load",
- { sessionId: cursor, cwd, mcpServers: support.mcpServersFromLaunch ? [] : mcpServers, ...selectionParams, ...support.sessionSetupParams?.(init) },
+ { sessionId: cursor, cwd, mcpServers: support.mcpServersFromLaunch ? [] : acpSessionMcpServers(mcpServers, ownMcp, init), ...selectionParams, ...support.sessionSetupParams?.(init) },
LOAD_SESSION_TIMEOUT,
(result) => {
if (result) {
@@ -1265,7 +1265,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
promptTurn = { ...turn, text: recovery.text };
rebuiltFromReplay = recovery.replayed;
}
- await request("session/new", { cwd, mcpServers: support.mcpServersFromLaunch ? [] : mcpServers, ...selectionParams, ...support.sessionSetupParams?.(init) }, NEW_SESSION_TIMEOUT, (result) => {
+ await request("session/new", { cwd, mcpServers: support.mcpServersFromLaunch ? [] : acpSessionMcpServers(mcpServers, ownMcp, init), ...selectionParams, ...support.sessionSetupParams?.(init) }, NEW_SESSION_TIMEOUT, (result) => {
session.sessionId = typeof result?.sessionId === "string" ? result.sessionId : null;
session.sessionKey = sessionKey;
receiveModelVariants(result, true);
diff --git a/server/drivers/acp/grok.ts b/server/drivers/acp/grok.ts
index 38a6505807..b642a3b9e2 100644
--- a/server/drivers/acp/grok.ts
+++ b/server/drivers/acp/grok.ts
@@ -441,6 +441,7 @@ const support: AcpSupport = {
effortLevels: ["low", "medium", "high"],
defaultCli: "grok",
nativeSource: "grok.acp",
+ ownMcpOverHttp: "advertised",
loginNote: "Grok is not signed in to your grok.com account — choose Sign in to Grok in engine setup",
// No Windows one-liner: the installer is a POSIX shell script.
diff --git a/server/drivers/own-mcp-http.test.ts b/server/drivers/own-mcp-http.test.ts
index d42a73171c..337dd32423 100644
--- a/server/drivers/own-mcp-http.test.ts
+++ b/server/drivers/own-mcp-http.test.ts
@@ -2,7 +2,8 @@ import { describe, expect, it, vi } from "vitest";
import { SPAWNED_PROXIES } from "../proxy-paths.ts";
import { mountMcpServer } from "./codex-mcp-mount.ts";
-import { acpOwnMcpOverHttp, claudeOwnMcpOverHttp, loopbackUnproxied, noteAcpMcpHttp, OWN_MCP_HTTP_ENV, ownMcpHttpEnabled, withLoopbackNoProxy } from "./own-mcp-http.ts";
+import { acpOwnMcpTransport, acpSessionMcpServers, claudeOwnMcpOverHttp, loopbackUnproxied, OWN_MCP_HTTP_ENV, ownMcpHttpEnabled, withLoopbackNoProxy } from "./own-mcp-http.ts";
+import type { AcpMcpServer } from "./turn-mcp.ts";
const HARNESS = "http://127.0.0.1:8799";
const agents = { command: process.execPath, args: [SPAWNED_PROXIES.agents], env: { OMB_HARNESS_URL: HARNESS, OMB_COMMS_TOKEN: "comms", OMB_BOT_ID: "b1", OMB_THREAD_ID: "t1", OMB_AGENTS_DEFER_TOOLS: "1", ELECTRON_RUN_AS_NODE: "1" } };
@@ -93,13 +94,37 @@ describe("Codex's own servers", () => {
});
describe("an ACP engine", () => {
- it("gets the URL form once its agent said it takes MCP servers by URL, and not when its servers come from its launcher", () => {
- expect(acpOwnMcpOverHttp("gemini-test", false, true)).toBe(false);
- noteAcpMcpHttp("gemini-test", { agentCapabilities: { mcpCapabilities: { http: true, sse: false } } });
- expect(acpOwnMcpOverHttp("gemini-test", false, true)).toBe(true);
- expect(acpOwnMcpOverHttp("gemini-test", true, true)).toBe(false);
- expect(acpOwnMcpOverHttp("gemini-test", false, false)).toBe(false);
- noteAcpMcpHttp("gemini-test", { agentCapabilities: {} });
- expect(acpOwnMcpOverHttp("gemini-test", false, true)).toBe(false);
+ it("takes the URL form by its driver's choice, by the setting outside the box, never with OMB_OWN_MCP_HTTP=0 or launcher-owned servers", () => {
+ expect(acpOwnMcpTransport({}, {}, false)).toBe("stdio");
+ expect(acpOwnMcpTransport({}, { [OWN_MCP_HTTP_ENV]: "1" }, false)).toBe("advertised");
+ expect(acpOwnMcpTransport({}, { [OWN_MCP_HTTP_ENV]: "1" }, true)).toBe("stdio");
+ for (const boxed of [false, true]) {
+ expect(acpOwnMcpTransport({ ownMcpOverHttp: "advertised" }, {}, boxed)).toBe("advertised");
+ expect(acpOwnMcpTransport({ ownMcpOverHttp: true }, {}, boxed)).toBe("http");
+ expect(acpOwnMcpTransport({ ownMcpOverHttp: "advertised" }, { [OWN_MCP_HTTP_ENV]: "0" }, boxed)).toBe("stdio");
+ expect(acpOwnMcpTransport({ ownMcpOverHttp: true }, { [OWN_MCP_HTTP_ENV]: "0" }, boxed)).toBe("stdio");
+ }
+ expect(acpOwnMcpTransport({ ownMcpOverHttp: "advertised", mcpServersFromLaunch: true }, {}, false)).toBe("stdio");
+ });
+
+ it("sends a session its own servers by URL only when that session's agent said it takes them, the person's as they were", () => {
+ const pairs = (record: Record<string, string>) => Object.entries(record).map(([name, value]) => ({ name, value }));
+ const servers: AcpMcpServer[] = [
+ { name: "agents", command: agents.command, args: agents.args, env: pairs(agents.env) },
+ { name: "browser", command: browser.command, args: browser.args, env: pairs(browser.env) },
+ { name: "notes", command: "npx", args: ["notes"], env: [] },
+ ];
+ const http = { agentCapabilities: { mcpCapabilities: { http: true, sse: false } } };
+ expect(acpSessionMcpServers(servers, "advertised", { agentCapabilities: {} })).toBe(servers);
+ expect(acpSessionMcpServers(servers, "advertised", { agentCapabilities: { mcpCapabilities: { http: "yes" } } })).toBe(servers);
+ expect(acpSessionMcpServers(servers, "stdio", http)).toBe(servers);
+ const sent = acpSessionMcpServers(servers, "advertised", http);
+ expect(sent.map((server) => "type" in server ? `${server.name}:${server.url}` : server.name)).toEqual([
+ `agents:${HARNESS}/api/internal/mcp-http/agents`, `browser:${HARNESS}/api/internal/mcp-http/browser`, "notes"]);
+ const own = sent[1] as Extract<AcpMcpServer, { type: "http" }>;
+ expect(own.headers).toEqual([{ name: "authorization", value: "Bearer browse" }, { name: "x-omb-tool-limit", value: "12" }]);
+ const agentsHeaders = Object.fromEntries((sent[0] as Extract<AcpMcpServer, { type: "http" }>).headers.map(({ name, value }) => [name, value]));
+ expect(agentsHeaders.authorization).toBe("Bearer comms");
+ expect(settings(Object.values(agentsHeaders).find((value) => value !== "Bearer comms")!)).toMatchObject({ OMB_BOT_ID: "b1", OMB_THREAD_ID: "t1" });
});
});
diff --git a/server/drivers/own-mcp-http.ts b/server/drivers/own-mcp-http.ts
index 040de4a982..8f3d260581 100644
--- a/server/drivers/own-mcp-http.ts
+++ b/server/drivers/own-mcp-http.ts
@@ -3,15 +3,18 @@
// against a container's pids limit. The URL form is the endpoint those proxies forward to (routes/own-mcp-http.ts), with
// the same capability token, so identity and permissions are the stdio form's. The permission prompt server (ogb, over the
// turn's broker socket), the Android phone tools (which run adb themselves) and the person's own servers stay as they are.
+// In the bot box with its own network, the engine reaches that endpoint as its stdio proxies do: 127.0.0.1 at the server's
+// port is the box's bridge to the harness gate (bot-box/harness-gate.ts), which passes /api/internal/ only, and the box
+// keeps loopback out of its egress proxy (NO_PROXY).
import { botBox } from "../bot-box/box.ts";
-import { ownMcpOverHttp } from "./turn-mcp.ts";
+import { acpOwnServersOverHttp, ownMcpOverHttp, type AcpMcpServer } from "./turn-mcp.ts";
-/** "1" turns the URL form on; off unless set, on every kind of server. */
+/** "1" turns the URL form on for every engine that can take it; "0" keeps every engine on stdio proxies, the ACP agents
+ * that take the URL form by default included. */
export const OWN_MCP_HTTP_ENV = "OMB_OWN_MCP_HTTP";
-/** Whether engines get OpenMausBot's own servers by URL: only with OMB_OWN_MCP_HTTP=1, and never while the bot box is on
- * (a boxed engine reaches this server only through the box's relays, which carry the stdio proxies' requests, not an
- * engine's own). */
+/** Whether Claude, Codex and the ACP agents that do not take the URL form by default get OpenMausBot's own servers by URL:
+ * only with OMB_OWN_MCP_HTTP=1, and not while the bot box is on, where their HTTP clients have not been checked. */
export function ownMcpHttpEnabled(env: NodeJS.ProcessEnv = process.env, boxed: boolean = botBox.enabled()): boolean {
return !boxed && env[OWN_MCP_HTTP_ENV] === "1";
}
@@ -54,18 +57,25 @@ export function claudeOwnMcpOverHttp(servers: Record<string, unknown>, enabled:
return converted;
}
-/** ACP engine instances whose agent said, in its `initialize` answer, that it reaches MCP servers by URL
- * (`agentCapabilities.mcpCapabilities.http`). The ACP spec lets a client send an `http` server only to such an agent. */
-const acpHttpAgents = new Set<string>();
+/** How an ACP engine's turn gets OpenMausBot's own servers: `http` in every session, `advertised` in a session whose agent
+ * said in its `initialize` answer that it reaches MCP servers by URL (`agentCapabilities.mcpCapabilities.http`; the ACP spec
+ * lets a client send an `http` server only to such an agent), else `stdio`. */
+export type AcpOwnMcpTransport = "http" | "advertised" | "stdio";
-export function noteAcpMcpHttp(instanceId: string, init: unknown): void {
- const http = (init as { agentCapabilities?: { mcpCapabilities?: { http?: unknown } } } | null | undefined)?.agentCapabilities?.mcpCapabilities?.http;
- if (http === true) acpHttpAgents.add(instanceId);
- else acpHttpAgents.delete(instanceId);
+export function acpOwnMcpTransport(support: { ownMcpOverHttp?: boolean | "advertised"; mcpServersFromLaunch?: boolean },
+ env: NodeJS.ProcessEnv = process.env, boxed: boolean = botBox.enabled()): AcpOwnMcpTransport {
+ if (support.mcpServersFromLaunch === true || env[OWN_MCP_HTTP_ENV] === "0") return "stdio";
+ if (support.ownMcpOverHttp === true) return "http";
+ if (support.ownMcpOverHttp === "advertised") return "advertised";
+ return ownMcpHttpEnabled(env, boxed) ? "advertised" : "stdio";
}
-/** An ACP engine gets OpenMausBot's own servers by URL once its agent has said it can take them (its first session starts
- * with the stdio form), unless its servers come from the launcher's own configuration. */
-export function acpOwnMcpOverHttp(instanceId: string, fromLaunch: boolean, enabled: boolean = ownMcpHttpEnabled()): boolean {
- return enabled && !fromLaunch && acpHttpAgents.has(instanceId);
+export function acpAgentTakesHttpMcp(init: unknown): boolean {
+ return (init as { agentCapabilities?: { mcpCapabilities?: { http?: unknown } } } | null | undefined)?.agentCapabilities?.mcpCapabilities?.http === true;
+}
+
+/** The servers a session/new or session/load sends: under `advertised`, OpenMausBot's own as this server's endpoints when
+ * the session's agent takes them. Deciding here, after `initialize`, lets an agent's first session use the URL form too. */
+export function acpSessionMcpServers(servers: AcpMcpServer[], transport: AcpOwnMcpTransport, init: unknown): AcpMcpServer[] {
+ return transport === "advertised" && acpAgentTakesHttpMcp(init) ? acpOwnServersOverHttp(servers) : servers;
}
diff --git a/server/drivers/turn-mcp.ts b/server/drivers/turn-mcp.ts
index 333c3fdb15..cd13bd6418 100644
--- a/server/drivers/turn-mcp.ts
+++ b/server/drivers/turn-mcp.ts
@@ -113,9 +113,17 @@ export function ownMcpOverHttp(server: TurnStdioMcpServer): { url: string; heade
* provider takes in all. */
export function acpMcpServers(turn: SendTurnInput, options: { http?: boolean; engine?: string; toolBudget?: number } = {}): AcpMcpServer[] {
const schemaProfile = toolSchemaProfileFor({ engine: options.engine })?.id;
- return turnStdioMcpServers(turn, { schemaProfile, toolBudget: options.toolBudget }).map((server) => {
- const own = options.http ? ownMcpOverHttp(server) : null;
- const pairs = (record: Record<string, string>) => Object.entries(record).map(([name, value]) => ({ name, value: String(value) }));
- return own ? { type: "http", name: server.name, url: own.url, headers: pairs(own.headers) } : { ...server, env: pairs(server.env) };
+ const servers: AcpMcpServer[] = turnStdioMcpServers(turn, { schemaProfile, toolBudget: options.toolBudget }).map((server) => ({ ...server, env: pairs(server.env) }));
+ return options.http ? acpOwnServersOverHttp(servers) : servers;
+}
+
+/** `servers` with each of OpenMausBot's own stdio proxies as its endpoint on this server; every other server as it was. */
+export function acpOwnServersOverHttp(servers: AcpMcpServer[]): AcpMcpServer[] {
+ return servers.map((server) => {
+ if (!("command" in server)) return server;
+ const own = ownMcpOverHttp({ ...server, env: Object.fromEntries(server.env.map(({ name, value }) => [name, value])) });
+ return own ? { type: "http", name: server.name, url: own.url, headers: pairs(own.headers) } : server;
});
}
+
+const pairs = (record: Record<string, string>): NameValue => Object.entries(record).map(([name, value]) => ({ name, value: String(value) }));
diff --git a/server/grok-own-mcp-http.e2e.test.ts b/server/grok-own-mcp-http.e2e.test.ts
new file mode 100644
index 0000000000..f59c017fae
--- /dev/null
+++ b/server/grok-own-mcp-http.e2e.test.ts
@@ -0,0 +1,78 @@
+import { readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+
+it("gives a Grok turn OpenMausBot's own tools by URL, no proxy process each, every one listed and callable", async () => {
+ const fixture = await launchVerificationServer({}, undefined, undefined, undefined, undefined, undefined, ["grok"]);
+ const { url, dataDir, logPath } = fixture.info;
+ const evidence: unknown[] = [{ fixture: fixture.info }];
+ const api = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(url + path, { method, headers: { "content-type": "application/json", origin: url },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(30_000) });
+ const result = await response.json() as any;
+ expect(response.status, `${method} ${path}: ${JSON.stringify(result)}`).toBe(200);
+ return result;
+ };
+ const cli = async (...args: string[]) => {
+ const result = await runControlOmb([...args, "--url", url]) as any;
+ evidence.push({ command: args, result });
+ return result;
+ };
+ const dump = join(dataDir, "grok-launch.json");
+ const calls = join(dataDir, "grok-calls.json");
+ const engine = (mode: string) => {
+ const wrapper = join(dataDir, `grok-${mode}.mjs`);
+ writeFileSync(wrapper, [
+ "#!/usr/bin/env node",
+ `process.env.FAKE_ACP_MODE = ${JSON.stringify(mode)};`,
+ 'process.env.FAKE_ACP_MCP_TRANSPORTS = "http";',
+ `process.env.FAKE_ACP_DUMP = ${JSON.stringify(dump)};`,
+ `process.env.FAKE_ACP_MCP_CALLS_FILE = ${JSON.stringify(calls)};`,
+ `await import(${JSON.stringify(new URL("./testing/fake-acp-cli.ts", import.meta.url).href)});`,
+ ].join("\n"), { mode: 0o700 });
+ return api("PATCH", "/api/instances/grok", { cli: wrapper });
+ };
+ try {
+ expect((await cli("doctor")).ok).toBe(true);
+ await engine("mcp-tools");
+ const bot = (await cli("new-bot", "--name", "Grok tools")).bot;
+ const threadId = bot.activeTaskId ?? bot.threadId;
+ await api("PATCH", `/api/bots/${bot.id}`, { modelSelection: { instanceId: "grok", model: "fake-model" } });
+ const turn = async (text: string) => {
+ await cli("send", "--bot", bot.id, "--task", threadId, "--text", text);
+ expect((await cli("wait", "--bot", bot.id, "--task", threadId, "--timeout", "40")).status).toBe("settled");
+ const messages = (await cli("messages", "--bot", bot.id, "--task", threadId)).messages as Array<{ role: string; text?: string }>;
+ return messages.filter((message) => message.role === "bot" && !message.text?.startsWith("[digest]")).at(-1)?.text ?? "";
+ };
+
+ const listed = await turn("List your tools.");
+ const sent = JSON.parse(readFileSync(`${dump}.mcp.json`, "utf8")) as Array<{ name: string; type?: string; url?: string; command?: string }>;
+ evidence.push({ sent: sent.map(({ name, type, url, command }) => ({ name, type, url, command })) });
+ const own = sent.filter((server) => server.type === "http");
+ // Every server this fixture's turn has is OpenMausBot's own, and none is a process.
+ expect(own.map((server) => server.name)).toEqual(expect.arrayContaining(["agents", "data"]));
+ expect(sent.filter((server) => server.command !== undefined)).toEqual([]);
+ for (const server of own) expect(server.url).toBe(`${url}/api/internal/mcp-http/${server.name}`);
+ const lists = Object.fromEntries(listed.trim().split("\n").map((line) => line.split(": ")).map(([name, tools]) => [name, tools!.split(",")]));
+ expect(Object.keys(lists).sort()).toEqual(own.map((server) => server.name).sort());
+ expect(lists.agents).toEqual(expect.arrayContaining(["list_bots"]));
+ expect(lists.data).toEqual(expect.arrayContaining(["data_sql"]));
+
+ await engine("mcp-calls");
+ writeFileSync(calls, JSON.stringify([
+ { server: "agents", name: "list_bots", arguments: {} },
+ { server: "data", name: "data_sql", arguments: { sql: "SELECT 41 + 1 AS answer", limit: 1 } },
+ ]));
+ const called = await turn("Call them.");
+ expect(called).toContain("list_bots: ");
+ expect(called).toMatch(/data_sql: .*42/s);
+ expect(JSON.parse(readFileSync(`${dump}.mcp.json`, "utf8")).every((server: { type?: string }) => server.type === "http")).toBe(true);
+ evidence.push({ called });
+ } finally {
+ const evidencePath = `${logPath}.grok-own-mcp.json`;
+ writeFileSync(evidencePath, JSON.stringify(evidence, null, 2));
+ console.info(JSON.stringify({ logPath, evidencePath }));
+ await fixture.close();
+ }
+}, 120_000);
diff --git a/server/routes/own-mcp-http.test.ts b/server/routes/own-mcp-http.test.ts
index b760d12ba5..bc9acec462 100644
--- a/server/routes/own-mcp-http.test.ts
+++ b/server/routes/own-mcp-http.test.ts
@@ -1,8 +1,12 @@
-import { createServer, type Server } from "node:http";
+import { mkdtempSync, rmSync } from "node:fs";
+import { createServer, request, type Server } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import type { AddressInfo } from "node:net";
import { Agent, fetch as undiciFetch } from "undici";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { openHarnessGate } from "../bot-box/harness-gate.ts";
import { json, readBody } from "../harness/http.ts";
import type { RequestAuth } from "../request-auth.ts";
import { createOwnMcpHttpRoutes, ownMcpHttpRoutes } from "./own-mcp-http.ts";
@@ -182,3 +186,32 @@ describe("a long tool call, and the stdio proxy's limits", () => {
});
});
});
+
+// The box's harness gate listens on a unix socket, which Windows refuses at a file path; the box runs only on Linux.
+describe.skipIf(process.platform === "win32")("an engine in the bot box", () => {
+ it("reaches these servers through the box's harness gate, as its stdio proxies reach the routes behind them", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-own-mcp-gate-"));
+ const gate = await openHarnessGate({ socketPath: join(dir, "harness.sock"), port: Number(new URL(base).port) });
+ const call = (path: string, body: unknown) => new Promise<{ status: number; text: string }>((resolve, reject) => {
+ const req = request({ socketPath: gate.socketPath, path, method: "POST", headers: { "content-type": "application/json",
+ accept: "application/json, text/event-stream", authorization: "Bearer turn-capability" } }, (res) => {
+ let text = "";
+ res.on("data", (chunk) => { text += chunk; });
+ res.on("end", () => resolve({ status: res.statusCode ?? 0, text }));
+ });
+ req.on("error", reject);
+ req.end(JSON.stringify(body));
+ });
+ try {
+ const listed = await call(`${OWN_MCP_HTTP_PATH}browser`, { jsonrpc: "2.0", id: 1, method: "tools/list" });
+ expect(JSON.parse(listed.text)).toMatchObject({ id: 1, result: { tools: [{ name: "agent_browser_open" }] } });
+ const called = await call(`${OWN_MCP_HTTP_PATH}browser`, { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "agent_browser_open", arguments: {} } });
+ expect(JSON.parse(called.text.split("\n").find((line) => line.startsWith("data: "))!.slice(6))).toEqual(
+ { jsonrpc: "2.0", id: 2, result: { content: [{ type: "text", text: "ran agent_browser_open" }] } });
+ expect((await call("/api/bots", {})).status).toBe(403);
+ } finally {
+ await gate.close();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.ts
index ea6285a25c..765c5ca814 100755
--- a/server/testing/fake-acp-cli.ts
+++ b/server/testing/fake-acp-cli.ts
@@ -37,6 +37,7 @@
// FAKE_ACP_LATE_UPDATE=1: a tool_call_update of the finished prompt arrives 50 ms after its answer)
// FAKE_ACP_GROK_NATIVE_MCP _x.ai/mcp/list reports these comma-separated native servers after the session's accepted ones
// FAKE_ACP_MCP_TRANSPORTS remote MCP transports advertised in initialize, e.g. "http,sse"
+// FAKE_ACP_MCP_HOLD=1 every session connects its MCP servers at once and keeps the stdio ones running, as Grok does
// FAKE_ACP_PERMISSION_OPTIONS JSON options override in permission mode
// FAKE_ACP_DUMP path for {argv, env}; with FAKE_ACP_MODES or FAKE_ACP_MODELS also <dump>.prompts.jsonl
// and <dump>.initialize.json for the initialize params
@@ -549,31 +550,46 @@ function offeredAgents(servers: AnyMcpEntry[]): McpEntry | null {
/** grok 1.0.25's initialize (`grok mcp doctor`) */
const GROK_MCP_HANDSHAKE = { protocolVersion: "2025-11-25", capabilities: { extensions: { "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] } } }, clientInfo: { name: "grok-shell", version: "1.0.25" } };
+/** An initialized client of a Streamable HTTP MCP server: one POST per frame, the answer read as JSON or as one event. */
+async function httpMcp(entry: AnyMcpEntry, handshake: unknown): Promise<(frame: object) => Promise<any>> {
+ const headers: Record<string, string> = { "content-type": "application/json", accept: "application/json, text/event-stream" };
+ for (const { name, value } of entry.headers ?? []) headers[name] = value;
+ const post = async (frame: object) => {
+ const response = await fetch(entry.url!, { method: "POST", headers, body: JSON.stringify({ jsonrpc: "2.0", ...frame }), signal: AbortSignal.timeout(20_000) });
+ const session = response.headers.get("mcp-session-id");
+ if (session) headers["mcp-session-id"] = session;
+ const text = await response.text();
+ const body = text.split("\n").find((line) => line.startsWith("data:"))?.slice(5) ?? text;
+ const parsed = body.trim() ? JSON.parse(body) : {};
+ if (!response.ok || parsed.error) throw new Error(`HTTP ${response.status} ${parsed.error?.message ?? ""}`.trim());
+ return parsed.result;
+ };
+ await post({ id: 1, method: "initialize", params: handshake });
+ await post({ method: "notifications/initialized" });
+ return post;
+}
+/** FAKE_ACP_MCP_HOLD=1: like Grok, each session's stdio MCP servers stay running once connected, until this process ends. */
+const heldMcp = new Set<ReturnType<typeof spawn>>();
+process.once("exit", () => { for (const child of heldMcp) child.kill(); });
+function holdSessionMcp(): void {
+ if (process.env.FAKE_ACP_MCP_HOLD !== "1") return;
+ for (const entry of sessionMcp) void listMcpTools(entry, GROK_MCP_HANDSHAKE).catch(() => {});
+}
+
async function listMcpTools(entry: AnyMcpEntry, handshake: unknown): Promise<string[]> {
const names = (result: any) => (result?.tools ?? []).map((tool: { name: string; inputSchema?: unknown }) =>
process.env.FAKE_ACP_MCP_SCHEMA_BYTES === "1" ? `${tool.name}=${JSON.stringify(tool.inputSchema ?? {}).length}` : tool.name);
if (typeof entry.url === "string") {
- const headers: Record<string, string> = { "content-type": "application/json", accept: "application/json, text/event-stream" };
- for (const { name, value } of entry.headers ?? []) headers[name] = value;
- const post = async (frame: object) => {
- const response = await fetch(entry.url!, { method: "POST", headers, body: JSON.stringify({ jsonrpc: "2.0", ...frame }), signal: AbortSignal.timeout(20_000) });
- const session = response.headers.get("mcp-session-id");
- if (session) headers["mcp-session-id"] = session;
- const text = await response.text();
- const body = text.split("\n").find((line) => line.startsWith("data:"))?.slice(5) ?? text;
- const parsed = body.trim() ? JSON.parse(body) : {};
- if (!response.ok || parsed.error) throw new Error(`HTTP ${response.status} ${parsed.error?.message ?? ""}`.trim());
- return parsed.result;
- };
- await post({ id: 1, method: "initialize", params: handshake });
- await post({ method: "notifications/initialized" });
+ const post = await httpMcp(entry, handshake);
return names(await post({ id: 2, method: "tools/list", params: {} }));
}
return new Promise((resolve, reject) => {
const env = { ...process.env };
for (const { name, value } of entry.env ?? []) env[name] = value;
const child = spawn(entry.command!, entry.args ?? [], { env, stdio: ["pipe", "pipe", "ignore"] });
- const finish = (error: Error | null, tools?: string[]) => { clearTimeout(timer); child.kill(); if (error) reject(error); else resolve(tools!); };
+ const hold = process.env.FAKE_ACP_MCP_HOLD === "1";
+ if (hold) heldMcp.add(child);
+ const finish = (error: Error | null, tools?: string[]) => { clearTimeout(timer); if (!hold || error) child.kill(); if (error) reject(error); else resolve(tools!); };
const timer = setTimeout(() => finish(new Error("mcp timeout")), 20_000);
child.on("error", (error) => finish(error));
const write = (frame: object) => child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...frame })}\n`);
@@ -657,6 +673,13 @@ function appendAntigravitySteps(sessionId: unknown): void {
}
}
+async function httpMcpCall(entry: AnyMcpEntry, name: string, args: Record<string, unknown>): Promise<string> {
+ const post = await httpMcp(entry, { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "fake-acp", version: "1" } });
+ const result = await post({ id: 2, method: "tools/call", params: { name, arguments: args } });
+ if (result?.isError) throw new Error(`Fixture MCP request failed: ${JSON.stringify(result)}`);
+ return String(result?.content?.[0]?.text ?? "");
+}
+
function driveMcp(entry: McpEntry, calls: Array<{ name: string | (() => string); args: (prev: string) => object }>, strict = false): Promise<string> {
return new Promise((resolve, reject) => {
const env = { ...process.env };
@@ -977,6 +1000,7 @@ function handle(msg: any) {
const offered = offeredAgents(servers);
agentsMcp = mode === "list-peers" ? agentsMcp ?? offered : offered;
sessionMcp = acceptedMcp(servers);
+ holdSessionMcp();
if (process.env.FAKE_ACP_DUMP) {
writeFileSync(`${process.env.FAKE_ACP_DUMP}.mcp.json`, JSON.stringify(servers, null, 2));
}
@@ -1050,7 +1074,7 @@ function handle(msg: any) {
if (process.env.FAKE_ACP_DUMP) {
writeFileSync(`${process.env.FAKE_ACP_DUMP}.mcp.json`, JSON.stringify(msg.params?.mcpServers ?? []));
}
- if (!cachedLiveLoad) sessionMcp = acceptedMcp(msg.params?.mcpServers ?? []);
+ if (!cachedLiveLoad) { sessionMcp = acceptedMcp(msg.params?.mcpServers ?? []); holdSessionMcp(); }
const opts = configOptions();
const mdls = sessionModels();
liveSession = typeof msg.params?.sessionId === "string" ? msg.params.sessionId : liveSession;
@@ -1547,8 +1571,8 @@ function handle(msg: any) {
void (async () => {
for (const call of calls) {
const server = sessionMcp.find((entry) => entry.name === call.server);
- if (!server?.command) throw new Error(`Fixture MCP server unavailable: ${call.server}`);
- const text = await driveMcp({ command: server.command, args: server.args, env: server.env },
+ if (!server?.command && !server?.url) throw new Error(`Fixture MCP server unavailable: ${call.server}`);
+ const text = server.url ? await httpMcpCall(server, call.name, call.arguments) : await driveMcp({ command: server.command!, args: server.args, env: server.env },
[{ name: call.name, args: () => call.arguments }], true);
out({ jsonrpc: "2.0", method: "session/update", params: { update: {
sessionUpdate: "agent_message_chunk", content: { text: `${call.name}: ${text}\n` },