Skip to content

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

perf(mcp): engines reach OpenMausBot's own MCP servers by URL instead of a proxy process each (#6183)

Milind Sonib370d7f13392
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index 95d26c23ff..87142eed47 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -43,7 +43,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_JEV_API_KEY", "OMB_LAN", "OMB_LICENSE_KEY", "OMB_LINUX_GPU", "OMB_LIVE_PROVIDER", "OMB_LOCAL_VM_UPDATE_WAIT_MS",
"OMB_LOOPBACK_TRUST", "OMB_LOOP_GUARD", "OMB_LOOP_GUARD_STOP_AT", "OMB_META_API_KEY", "OMB_MODELGO_API_KEY", "OMB_NETLIFY_API_URL", "OMB_OPENAI_API_KEY",
"OMB_OPENAI_IMAGE_KEY", "OMB_OPENAI_LIVE_KEY", "OMB_OPENAI_LIVE_URL", "OMB_OPENROUTER_API_KEY",
- "OMB_OPENROUTER_DECIDER_KEY", "OMB_PERSON_FIRST_MS", "OMB_PHONE_PUSH", "OMB_PHONE_RELAY", "OMB_PHONE_RELAY_URL", "OMB_PHONE_SECRET_PUBLIC_KEY", "OMB_PORT", "OMB_SERVES_TUNNEL", "OMB_POSTIZ_API_KEY",
+ "OMB_OPENROUTER_DECIDER_KEY", "OMB_OWN_MCP_HTTP", "OMB_PERSON_FIRST_MS", "OMB_PHONE_PUSH", "OMB_PHONE_RELAY", "OMB_PHONE_RELAY_URL", "OMB_PHONE_SECRET_PUBLIC_KEY", "OMB_PORT", "OMB_SERVES_TUNNEL", "OMB_POSTIZ_API_KEY",
"OMB_POSTIZ_CLOUD_URL", "OMB_PROCESS_ID", "OMB_PUBLIC_IPV4", "OMB_PUBLIC_URL", "OMB_PUSH_CREDENTIAL", "OMB_QUOTA_SWITCH",
"OMB_REPLAY_TOOL_HISTORY", "OMB_ROOM_SESSIONS", "OMB_SAFETY_FLOOR", "OMB_SERVER_COMPILE_CACHE", "OMB_SERVER_NAME",
"OMB_SERVER_UPDATE_DIR",
diff --git a/server/drivers/acp/acp.test.ts b/server/drivers/acp/acp.test.ts
index 37afe09efa..1fc38ccb72 100644
--- a/server/drivers/acp/acp.test.ts
+++ b/server/drivers/acp/acp.test.ts
@@ -1213,6 +1213,9 @@ describe("ACP turns (fake CLI)", () => {
{ type: "http", name: "browser", url: `${harness}/api/internal/mcp-http/browser`, headers: [{ name: "authorization", value: "Bearer synthetic-browser-capability" }] },
{ name: "notes", command: process.execPath, args: ["/tmp/notes-mcp.js"], env: [] },
]);
+ // The agent reaches this server's loopback URL around any proxy it was given.
+ const { env } = JSON.parse(readFileSync(dump, "utf8")) as { env: Record<string, string> };
+ for (const name of ["NO_PROXY", "no_proxy"]) expect(env[name]!.split(",")).toEqual(expect.arrayContaining(["127.0.0.1", "localhost", "::1"]));
});
it.each([false, true])("mounts Data through the existing stdio transport unless excluded (excluded=%s)", async (excluded) => {
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index 17728519c4..ba995722ab 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -74,7 +74,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 { acpToolOutput, acpToolProgress } from "../tool-progress.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 { 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. */
@@ -988,7 +988,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: support.ownMcpOverHttp === true, engine: support.driverKind,
+ const mcpServers = acpMcpServers(turn, { http: loopbackUnproxied(env, support.ownMcpOverHttp === true || acpOwnMcpOverHttp(instanceId, support.mcpServersFromLaunch === true)), 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,
@@ -1175,7 +1175,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)
diff --git a/server/drivers/agents-mcp-env.ts b/server/drivers/agents-mcp-env.ts
index d3bc5d53f4..80ad7dbdab 100644
--- a/server/drivers/agents-mcp-env.ts
+++ b/server/drivers/agents-mcp-env.ts
@@ -1,7 +1,10 @@
import { TOOL_BRIDGE_ENV } from "./agents-bridge.ts";
import { TOOL_LIMIT_ENV } from "../tool-count-limit.ts";
+import { DEFER_TOOLS_ENV } from "./agents-claude-defer.ts";
/** The settings the harness gives the agents MCP server, and the only ones a request may carry over HTTP. */
export const AGENTS_MCP_ENV = ["OMB_BOT_ID", "OMB_THREAD_ID", "OMB_EXTERNAL_RUNTIME", "OMB_CHIEF_OF_STAFF",
"OMB_SKILL_AUTHORING_ENABLED", "OMB_MEMORY_ENABLED", "OMB_SHARED_COMPUTERS_ENABLED", "OMB_CLOUD_HOME", "OMB_VOICE_NOTES",
- "OMB_X_RESEARCH", "OMB_RESEARCH", "OMB_TEAM_PEOPLE", "OMB_MAUSBOT", "OMB_COMPUTER_SELECTION", "OMB_ROOM", "OMB_IMAGE_GENERATION", "OMB_MEETINGS", "OMB_APP_HOSTING", "OMB_TOOLS_OFF", TOOL_BRIDGE_ENV, TOOL_LIMIT_ENV] as const;
+ "OMB_X_RESEARCH", "OMB_RESEARCH", "OMB_TEAM_PEOPLE", "OMB_MAUSBOT", "OMB_COMPUTER_SELECTION", "OMB_ROOM", "OMB_IMAGE_GENERATION", "OMB_MEETINGS", "OMB_APP_HOSTING", "OMB_TOOLS_OFF", TOOL_BRIDGE_ENV, TOOL_LIMIT_ENV,
+ // Claude's deferred catalog: the URL form carries it as the stdio proxy's environment does.
+ DEFER_TOOLS_ENV] as const;
diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.ts
index 0436f4aeff..348731eff6 100644
--- a/server/drivers/claude.test.ts
+++ b/server/drivers/claude.test.ts
@@ -41,6 +41,7 @@ import { registerPathDir, resetPathCacheForTests } from "../env-path.ts";
import * as procs from "../procs.ts";
import * as localInject from "./local-inject.ts";
import { DEFER_TOOLS_ENV } from "./agents-claude-defer.ts";
+import { OWN_MCP_HTTP_ENV } from "./own-mcp-http.ts";
const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-claude-cli.ts");
const dumpedPid = (dump: string): number => JSON.parse(readFileSync(dump, "utf8")).pid;
@@ -542,6 +543,7 @@ describe("ClaudeDriver turns (fake CLI)", () => {
delete process.env.FAKE_CLAUDE_TEXT_HANG;
delete process.env.FAKE_CLAUDE_STEER_GRACE_SCALE;
delete process.env.FAKE_CLAUDE_STEER_SILENCE_SCALE;
+ vi.unstubAllEnvs();
delete process.env.ANTHROPIC_API_KEY;
delete process.env.XAI_API_KEY;
delete process.env.COMPOSIO_API_KEY;
@@ -1328,7 +1330,8 @@ describe("ClaudeDriver turns (fake CLI)", () => {
}
});
- it.each(["ask", "auto"] as const)("pre-allows the agents comms proxy while retaining native %s approval", async (approvalMode) => {
+ it.each([["ask", "0"], ["auto", "0"], ["ask", "1"], ["auto", "1"]] as const)("pre-allows the agents comms proxy while retaining native %s approval (OMB_OWN_MCP_HTTP=%s)", async (approvalMode, http) => {
+ vi.stubEnv(OWN_MCP_HTTP_ENV, http);
await create();
const dump = join(scratch, "dump.json");
process.env.FAKE_CLAUDE_DUMP = dump;
@@ -1348,11 +1351,19 @@ describe("ClaudeDriver turns (fake CLI)", () => {
await recorder.until((e) => e.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8"));
- expect(seen.mcpConfig.mcpServers.agents).toMatchObject({
- alwaysLoad: true,
- args: ["/fake/agents-proxy.js"],
- env: { OMB_BOT_ID: "b1", OMB_COMMS_TOKEN: "tok", [DEFER_TOOLS_ENV]: "1" },
- });
+ if (http === "1") {
+ // By URL: the same capability and settings as headers, and the loopback past any proxy the engine was given.
+ const agents = seen.mcpConfig.mcpServers.agents;
+ expect(agents).toMatchObject({ type: "http", alwaysLoad: true, url: "http://127.0.0.1:1/api/internal/mcp-http/agents", headers: { authorization: "Bearer tok" } });
+ expect(JSON.parse(Buffer.from(agents.headers["x-omb-agents-env"], "base64url").toString("utf8"))).toMatchObject({ OMB_BOT_ID: "b1", [DEFER_TOOLS_ENV]: "1" });
+ for (const name of ["NO_PROXY", "no_proxy"]) expect(seen.env[name].split(",")).toEqual(expect.arrayContaining(["127.0.0.1", "localhost", "::1"]));
+ } else {
+ expect(seen.mcpConfig.mcpServers.agents).toMatchObject({
+ alwaysLoad: true,
+ args: ["/fake/agents-proxy.js"],
+ env: { OMB_BOT_ID: "b1", OMB_COMMS_TOKEN: "tok", [DEFER_TOOLS_ENV]: "1" },
+ });
+ }
expect(seen.env.CLAUDE_CODE_DISABLE_CRON, "a deferred trigger must not lose to CronCreate").toBe("1");
expect(JSON.stringify(seen.argv)).not.toContain("tok");
const allowed = seen.argv[seen.argv.indexOf("--allowedTools") + 1];
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index 57e6211578..4eb1f095e4 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -18,7 +18,7 @@ import { botSettingsFor, folderSettingsEnv, withBotSettings } from "./claude-bot
import { claudeBilling, claudeCallUsage } from "./claude-billing.ts";
import { claudeAuthFailure, claudeAuthRecovery, claudeOAuthExpired } from "./claude-auth-recovery.ts"; import { AWS_CREDENTIAL_ENV_KEYS, bedrockResultError, withBedrockCredentialError } from "./claude-bedrock-aws.ts";
import { CLAUDE_MODEL_ID, STATIC_CLAUDE_MODELS, claudeModelExtras, currentEngineCatalog, endpointModelCatalog, withCliVersionGate } from "./claude-model-extras.ts";
-import { claudeAgentsMount, claudeToolSearchSetting } from "./claude-tool-search.ts"; import { claudeDisabledNativeSkillRules, unusableBuiltIns } from "./claude-unusable-tools.ts"; import { EMAIL_READ_TOOL_NAMES } from "../../shared/email.ts";
+import { claudeOwnMcpOverHttp, withLoopbackNoProxy } from "./own-mcp-http.ts"; import { claudeAgentsMount, claudeToolSearchSetting } from "./claude-tool-search.ts"; import { claudeDisabledNativeSkillRules, unusableBuiltIns } from "./claude-unusable-tools.ts"; import { EMAIL_READ_TOOL_NAMES } from "../../shared/email.ts";
import { claudeElicitations } from "./claude-elicitation.ts"; import { spawnContractDiff } from "./claude-spawn-contract.ts";
import { readCostHistory, recordCostState } from "./claude-cost-history.ts";
import { classifyResumeFailure, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts";
@@ -1072,11 +1072,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
}
if (turn.integrations?.localComputer) {
const local = turn.integrations.localComputer;
- mcpServers.computer = {
- command: local.command,
- args: local.args,
- env: local.env,
- };
+ mcpServers.computer = { command: local.command, args: local.args, env: local.env };
if (!controlsHost) allowed.push("mcp__computer");
}
const cwd = turn.cwd ?? homedir(), toolSearch = claudeToolSearchSetting(cwd, turnEnvironment);
@@ -1136,6 +1132,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (gated) mcpServers[name] = { ...gated, ...((mcpServers[name] as { alwaysLoad?: unknown })?.alwaysLoad === true ? { alwaysLoad: true } : {}) };
}
allowed.splice(0, allowed.length, ...allowed.filter((name) => Object.hasOwn(mcpServers, name.slice("mcp__".length).split("__")[0]!)));
+ const ownHttp = claudeOwnMcpOverHttp(mcpServers); // OpenMausBot's own servers by URL where that setting is on: no proxy process each
// Full access keeps ask_user: native bypass skips permission prompts, not questions.
let broker: Awaited<ReturnType<typeof createPermissionBroker>> | undefined;
const socketPath = permissionSocketPath(threadId, botId);
@@ -1147,7 +1144,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
allowed.push("mcp__ogb", ...gateQueryTools(mcpServers));
// A guest pre-allows only harness tools; anything else (the browser can open file:) asks.
if (turn.guestConfined) allowed.splice(0, allowed.length, ...allowed.filter((name) => name === "mcp__ogb" || name === "mcp__agents"));
- const env = withEndpointFolder(environment(config.endpointModels ? undefined : turnModel), config, () => retryState.delete(threadId)); env.PATH = turnEnvironment.PATH; // launch the copy this turn checked, not one a newer PATH finds
+ const env = withEndpointFolder(environment(config.endpointModels ? undefined : turnModel), config, () => retryState.delete(threadId)); if (ownHttp) withLoopbackNoProxy(env); env.PATH = turnEnvironment.PATH; // launch the copy this turn checked, not one a newer PATH finds
// The MCP config carries credentials and argv is readable via `ps`: a 0600 file, removed at settle.
let mcpConfigPath: string | null = null;
if (Object.keys(mcpServers).length) {
diff --git a/server/drivers/codex-mcp-mount.ts b/server/drivers/codex-mcp-mount.ts
index 9da805cd09..74e2eb0d4e 100644
--- a/server/drivers/codex-mcp-mount.ts
+++ b/server/drivers/codex-mcp-mount.ts
@@ -1,6 +1,8 @@
import type { McpServerSpec, StdioMcpSpec } from "../contracts.ts";
import { BOX_NO_PROXY_ENV, BOX_PROXY_ENV, botBox } from "../bot-box/box.ts";
import { tomlInlineTable } from "./codex-process.ts";
+import { ownMcpHttpEnabled, withLoopbackNoProxy } from "./own-mcp-http.ts";
+import { ownMcpOverHttp } from "./turn-mcp.ts";
/** Codex's default for one MCP server's tools (openai/codex#17843): "auto"
* runs without asking only tools the server marks read-only, "approve" runs
@@ -20,6 +22,7 @@ export function mountMcpServer(
forward: readonly string[] = [],
): void {
const prefix = `mcp_servers.${name}`;
+ if (mountOwnOverHttp(appServerArgs, env, prefix, server, approval, written)) return;
Object.assign(env, server.env);
for (const name of Object.keys(server.env)) written.add(name);
appServerArgs.push(
@@ -53,3 +56,22 @@ export function customServerEnvBox(
export function boxAdmittedEnv(custom: { box?: { allowEnv: string[] } }): Set<string> {
return new Set(botBox.enabled() ? custom.box?.allowEnv : []);
}
+
+/** One of OpenMausBot's own stdio proxies as Codex's streamable HTTP server, where that setting is on (own-mcp-http.ts):
+ * no proxy process. The token stays in Codex's environment under the name the proxy read it from, and argv names it only
+ * (`bearer_token_env_var`); the other headers (the agents server's settings, a tool limit) go as `http_headers`. Checked
+ * on codex-cli 0.50.0, 0.80.0, 0.117.0, 0.146.0 and 0.169.0. */
+function mountOwnOverHttp(appServerArgs: string[], env: Record<string, string | undefined>, prefix: string, server: StdioMcpSpec,
+ approval: McpApprovalMode, written: Set<string>): boolean {
+ const http = ownMcpHttpEnabled() ? ownMcpOverHttp({ name: prefix, command: server.command, args: server.args, env: server.env }) : null;
+ const tokenName = http && Object.keys(server.env).find((key) => http.headers.authorization === `Bearer ${server.env[key]}`);
+ if (!http || !tokenName) return false;
+ env[tokenName] = server.env[tokenName];
+ withLoopbackNoProxy(env);
+ written.add(tokenName);
+ const { authorization: _token, ...headers } = http.headers;
+ appServerArgs.push("-c", `${prefix}.url=${JSON.stringify(http.url)}`, "-c", `${prefix}.bearer_token_env_var=${JSON.stringify(tokenName)}`);
+ if (Object.keys(headers).length) appServerArgs.push("-c", `${prefix}.http_headers=${tomlInlineTable(headers)}`);
+ if (approval !== "prompt") appServerArgs.push("-c", `${prefix}.default_tools_approval_mode="${approval}"`);
+ return true;
+}
diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.ts
index 7b134f9689..fec7900415 100644
--- a/server/drivers/codex.test.ts
+++ b/server/drivers/codex.test.ts
@@ -2,7 +2,8 @@ import { createHash } from "node:crypto";
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
import { once } from "node:events";
import { spawn } from "node:child_process";
-import { createConnection } from "node:net";
+import { createConnection, type AddressInfo } from "node:net";
+import { createServer } from "node:http";
import { createInterface } from "node:readline";
import { tmpdir } from "node:os";
import { dirname, join, sep } from "node:path";
@@ -28,6 +29,10 @@ import { TEAM_TOOLS_FAILED } from "./team-tools.ts";
import { unsupportedCallsNotice } from "./codex-unsupported-calls.ts";
import { rebuiltSessionNotice } from "../resume-recovery.ts";
import { startFakeHttpMcp, type FakeHttpMcp } from "../testing/fake-http-mcp-server.ts";
+import { OWN_MCP_HTTP_ENV } from "./own-mcp-http.ts";
+import { ownMcpHttpRoutes } from "../routes/own-mcp-http.ts";
+import { json as sendJson, readBody } from "../harness/http.ts";
+import type { RequestAuth } from "../request-auth.ts";
import * as procs from "../procs.ts";
import { botBox } from "../bot-box/box.ts";
import { boxEnvironment } from "../bot-box/env.ts";
@@ -560,6 +565,7 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
delete process.env.FAKE_CODEX_RESOLVED_SANDBOX;
delete process.env.FAKE_CODEX_MCP_START;
delete process.env.FAKE_CODEX_MCP_HANDSHAKE;
+ vi.unstubAllEnvs();
delete process.env.FAKE_CODEX_STEER_ERROR;
delete process.env.FAKE_CODEX_STEER_ERROR_FILE;
delete process.env.FAKE_CODEX_STEER_HANG;
@@ -1944,7 +1950,8 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
expect(seen.env.HEALTH_REGION).toBe("eu");
});
- it.each(["ask", "auto"] as const)("pre-allows peer-agent comms without exposing its token in %s mode", async (approvalMode) => {
+ it.each([["ask", "0"], ["auto", "0"], ["ask", "1"], ["auto", "1"]] as const)("pre-allows peer-agent comms without exposing its token in %s mode (OMB_OWN_MCP_HTTP=%s)", async (approvalMode, http) => {
+ vi.stubEnv(OWN_MCP_HTTP_ENV, http);
await create();
const dump = join(scratch, "agents.json");
process.env.FAKE_CODEX_DUMP = dump;
@@ -1970,16 +1977,49 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
await recorder.until((event) => event.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8"));
- expect(seen.argv.join(" ")).toContain("mcp_servers.agents.command");
+ expect(seen.argv.join(" ")).toContain(http === "1" ? 'mcp_servers.agents.url="http://127.0.0.1:8799/api/internal/mcp-http/agents"' : "mcp_servers.agents.command");
expect(seen.argv).toContain('mcp_servers.agents.default_tools_approval_mode="approve"');
expect(seen.argv).toContain("mcp_servers.agents.tool_timeout_sec=960");
- expect(seen.argv.join(" ")).toContain("/tmp/agents-proxy.js");
+ if (http === "1") expect(seen.argv).toContain('mcp_servers.agents.bearer_token_env_var="OMB_COMMS_TOKEN"');
+ else expect(seen.argv.join(" ")).toContain("/tmp/agents-proxy.js");
expect(seen.argv.join(" ")).toContain("OMB_COMMS_TOKEN");
expect(seen.argv.join(" ")).not.toContain("peer-comms-secret");
expect(seen.env.OMB_COMMS_TOKEN).toBe("peer-comms-secret");
expect(instance.adapter.capabilities.agentsMcp).toBe(true);
});
+ it("with OMB_OWN_MCP_HTTP=1, starts the agents server by URL with the bot's settings and capability, the loopback out of any proxy", async () => {
+ vi.stubEnv(OWN_MCP_HTTP_ENV, "1");
+ const seenAuth: Array<string | undefined> = [];
+ const harness = createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
+ seenAuth.push(req.headers.authorization);
+ await ownMcpHttpRoutes({ req, res, url, path: url.pathname, method: req.method ?? "GET", auth: {} as RequestAuth, json: sendJson, readBody });
+ if (!res.headersSent) sendJson(res, 404, { error: "no such endpoint" });
+ });
+ await new Promise<void>((resolve) => harness.listen(0, "127.0.0.1", resolve));
+ try {
+ process.env.FAKE_CODEX_MCP_START = "1";
+ // Codex given a proxy for HTTP must reach this server's loopback URL around it.
+ await create({ environment: { NO_PROXY: "corp.internal" } });
+ const dump = join(scratch, "agents-http.json");
+ process.env.FAKE_CODEX_DUMP = dump;
+ await instance.adapter.sendTurn({ threadId: "t-agents-http", text: "go", integrations: { agents: { command: process.execPath, args: ["/tmp/agents-proxy.js"], env: {
+ ELECTRON_RUN_AS_NODE: "1", OMB_HARNESS_URL: `http://127.0.0.1:${(harness.address() as AddressInfo).port}`, OMB_BOT_ID: "captain", OMB_THREAD_ID: "t-agents-http",
+ OMB_COMMS_TOKEN: "peer-comms-secret", OMB_CHIEF_OF_STAFF: "1",
+ } } } });
+ expect(await recorder.until((event) => event.type === "turn.completed")).toMatchObject({ ok: true });
+ const seen = JSON.parse(readFileSync(dump, "utf8"));
+ expect(seen.mcpStartup.agents).toMatchObject({ status: "ready", tools: expect.arrayContaining(["coordinate_bots", "create_bot"]) });
+ expect(seenAuth.length).toBeGreaterThan(0);
+ expect(seenAuth.every((authorization) => authorization === "Bearer peer-comms-secret")).toBe(true);
+ expect(seen.env.NO_PROXY.split(",")).toEqual(["corp.internal", "127.0.0.1", "localhost", "::1"]);
+ expect(seen.argv.join(" ")).not.toContain("peer-comms-secret");
+ } finally {
+ await new Promise<void>((resolve) => harness.close(() => resolve()));
+ }
+ });
+
it.each(["ask", "auto"] as const)("pre-allows the built-in browser while preserving the native %s reviewer", async (approvalMode) => {
await create();
const dump = join(scratch, "browser.json");
diff --git a/server/drivers/own-mcp-http.test.ts b/server/drivers/own-mcp-http.test.ts
new file mode 100644
index 0000000000..d42a73171c
--- /dev/null
+++ b/server/drivers/own-mcp-http.test.ts
@@ -0,0 +1,105 @@
+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";
+
+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" } };
+const browser = { command: process.execPath, args: [SPAWNED_PROXIES.harnessMcp, "browser"], env: { OMB_HARNESS_URL: HARNESS, OMB_MCP_TOKEN_BROWSER: "browse", OMB_TOOL_LIMIT: "12" } };
+const ogb = { command: process.execPath, args: [SPAWNED_PROXIES.permission, "/tmp/perm.sock"], env: {}, alwaysLoad: true };
+const phone = { command: process.execPath, args: ["/app/phone-proxy.js"], env: { OMB_HARNESS_URL: HARNESS, OMB_PHONE_TOKEN: "p" } };
+const settings = (header: string) => JSON.parse(Buffer.from(header, "base64url").toString("utf8"));
+
+describe("the setting", () => {
+ it("is off unless OMB_OWN_MCP_HTTP=1, everywhere, and always off in the bot box", () => {
+ expect(ownMcpHttpEnabled({}, false)).toBe(false);
+ expect(ownMcpHttpEnabled({ OMB_CLOUD_ROLE: "home" }, false)).toBe(false);
+ expect(ownMcpHttpEnabled({ [OWN_MCP_HTTP_ENV]: "0" }, false)).toBe(false);
+ expect(ownMcpHttpEnabled({ [OWN_MCP_HTTP_ENV]: "true" }, false)).toBe(false);
+ expect(ownMcpHttpEnabled({ [OWN_MCP_HTTP_ENV]: "1" }, false)).toBe(true);
+ expect(ownMcpHttpEnabled({ [OWN_MCP_HTTP_ENV]: "1" }, true)).toBe(false);
+ });
+});
+
+describe("an engine set up to use a proxy", () => {
+ it("reaches this server's loopback URL directly: the loopback names join NO_PROXY and no_proxy, keeping what either held", () => {
+ const env: Record<string, string | undefined> = { HTTPS_PROXY: "http://proxy.internal:3128", NO_PROXY: "corp.internal, localhost", no_proxy: ".lan" };
+ withLoopbackNoProxy(env);
+ expect(env.NO_PROXY).toBe("corp.internal,localhost,.lan,127.0.0.1,::1");
+ expect(env.no_proxy).toBe(env.NO_PROXY);
+ withLoopbackNoProxy(env);
+ expect(env.NO_PROXY).toBe("corp.internal,localhost,.lan,127.0.0.1,::1");
+ const bare: Record<string, string | undefined> = {};
+ withLoopbackNoProxy(bare);
+ expect(bare).toEqual({ NO_PROXY: "127.0.0.1,localhost,::1", no_proxy: "127.0.0.1,localhost,::1" });
+ });
+
+ it("is left alone by an ACP engine that keeps the stdio form", () => {
+ const env: Record<string, string | undefined> = { NO_PROXY: "corp.internal" };
+ expect(loopbackUnproxied(env, false)).toBe(false);
+ expect(env).toEqual({ NO_PROXY: "corp.internal" });
+ expect(loopbackUnproxied(env, true)).toBe(true);
+ expect(env.NO_PROXY).toBe("corp.internal,127.0.0.1,localhost,::1");
+ });
+});
+
+describe("Claude's --mcp-config", () => {
+ it("gets OpenMausBot's own proxies by URL with their capability, settings, tool limit and alwaysLoad; nothing else changes", () => {
+ const servers: Record<string, unknown> = { agents: { ...agents, alwaysLoad: true }, browser, ogb, phone, mine: { command: "npx", args: ["my-server"] } };
+ expect(claudeOwnMcpOverHttp(servers, true)).toBe(true);
+ expect(servers.agents).toEqual({ type: "http", url: `${HARNESS}/api/internal/mcp-http/agents`, alwaysLoad: true,
+ headers: { authorization: "Bearer comms", "x-omb-agents-env": expect.any(String) } });
+ expect(settings((servers.agents as { headers: Record<string, string> }).headers["x-omb-agents-env"]!)).toEqual({ OMB_BOT_ID: "b1", OMB_THREAD_ID: "t1", OMB_AGENTS_DEFER_TOOLS: "1" });
+ expect(servers.browser).toEqual({ type: "http", url: `${HARNESS}/api/internal/mcp-http/browser`, headers: { authorization: "Bearer browse", "x-omb-tool-limit": "12" } });
+ expect(servers.ogb).toBe(ogb);
+ expect(servers.phone).toBe(phone);
+ expect(servers.mine).toEqual({ command: "npx", args: ["my-server"] });
+ });
+
+ it("is left as it is with the setting off", () => {
+ const servers: Record<string, unknown> = { agents, browser };
+ expect(claudeOwnMcpOverHttp(servers, false)).toBe(false);
+ expect(servers).toEqual({ agents, browser });
+ expect(claudeOwnMcpOverHttp({ phone }, true)).toBe(false);
+ });
+});
+
+describe("Codex's own servers", () => {
+ it("mount by URL with the token named, never written, in argv", () => {
+ vi.stubEnv(OWN_MCP_HTTP_ENV, "1");
+ try {
+ const args: string[] = [];
+ const env: Record<string, string | undefined> = { NO_PROXY: "corp.internal" };
+ mountMcpServer(args, env, "agents", agents, "approve");
+ const joined = args.join(" ");
+ expect(joined).toContain(`mcp_servers.agents.url="${HARNESS}/api/internal/mcp-http/agents"`);
+ expect(joined).toContain('mcp_servers.agents.bearer_token_env_var="OMB_COMMS_TOKEN"');
+ expect(joined).toContain('mcp_servers.agents.http_headers={ "x-omb-agents-env" = ');
+ expect(joined).toContain('mcp_servers.agents.default_tools_approval_mode="approve"');
+ expect(joined).not.toContain("comms");
+ expect(joined).not.toContain("command=");
+ expect(env.OMB_COMMS_TOKEN).toBe("comms");
+ expect([env.NO_PROXY, env.no_proxy]).toEqual(["corp.internal,127.0.0.1,localhost,::1", "corp.internal,127.0.0.1,localhost,::1"]);
+ const stdio: string[] = [];
+ const stdioEnv: Record<string, string | undefined> = {};
+ mountMcpServer(stdio, stdioEnv, "notes", { command: "npx", args: ["notes"], env: { KEY: "k" } });
+ expect(stdio.join(" ")).toContain('mcp_servers.notes.command="npx"');
+ expect(stdioEnv.NO_PROXY).toBeUndefined();
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+});
+
+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);
+ });
+});
diff --git a/server/drivers/own-mcp-http.ts b/server/drivers/own-mcp-http.ts
new file mode 100644
index 0000000000..040de4a982
--- /dev/null
+++ b/server/drivers/own-mcp-http.ts
@@ -0,0 +1,71 @@
+// OpenMausBot's own MCP servers (agents, browser, computer, data, email, device) reached by URL instead of a stdio proxy
+// process each: every engine process otherwise starts one Node helper per server, about 7 threads each, all counted
+// 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.
+import { botBox } from "../bot-box/box.ts";
+import { ownMcpOverHttp } from "./turn-mcp.ts";
+
+/** "1" turns the URL form on; off unless set, on every kind of server. */
+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). */
+export function ownMcpHttpEnabled(env: NodeJS.ProcessEnv = process.env, boxed: boolean = botBox.enabled()): boolean {
+ return !boxed && env[OWN_MCP_HTTP_ENV] === "1";
+}
+
+const LOOPBACK = ["127.0.0.1", "localhost", "::1"];
+
+/** An engine set up to use a proxy for HTTP (HTTPS_PROXY, ALL_PROXY) would send its calls to this server's loopback URL
+ * there too: the loopback names join NO_PROXY and no_proxy, both spellings, keeping whatever either held. */
+export function withLoopbackNoProxy(env: Record<string, string | undefined>): void {
+ const hosts = [env.NO_PROXY, env.no_proxy].flatMap((value) => (value ?? "").split(",")).map((host) => host.trim()).filter(Boolean);
+ env.NO_PROXY = env.no_proxy = [...new Set([...hosts, ...LOOPBACK])].join(",");
+}
+
+/** `http` as given; an engine that will reach this server by URL gets the loopback names in its NO_PROXY first. */
+export function loopbackUnproxied(env: Record<string, string | undefined>, http: boolean): boolean {
+ if (http) withLoopbackNoProxy(env);
+ return http;
+}
+
+type StdioMount = { command?: unknown; args?: unknown; env?: unknown; alwaysLoad?: unknown };
+
+/** One --mcp-config entry as Claude Code's HTTP form when it is one of OpenMausBot's own stdio proxies (Claude Code 1.0.60,
+ * 2.0.0, 2.1.257 and 2.1.325 checked: `type: "http"` with headers connects and lists tools), else null. `alwaysLoad` stays. */
+export function claudeOwnHttpMount(server: unknown): Record<string, unknown> | null {
+ const mount = server as StdioMount | null;
+ if (!mount || typeof mount.command !== "string" || !Array.isArray(mount.args) || !mount.env || typeof mount.env !== "object") return null;
+ const http = ownMcpOverHttp({ name: "", command: mount.command, args: mount.args.map(String), env: mount.env as Record<string, string> });
+ return http ? { type: "http", url: http.url, headers: http.headers, ...(mount.alwaysLoad === true ? { alwaysLoad: true } : {}) } : null;
+}
+
+/** Turns every one of OpenMausBot's own proxies in a Claude --mcp-config into its HTTP form, when the setting is on;
+ * true when any was. */
+export function claudeOwnMcpOverHttp(servers: Record<string, unknown>, enabled: boolean = ownMcpHttpEnabled()): boolean {
+ if (!enabled) return false;
+ let converted = false;
+ for (const [name, server] of Object.entries(servers)) {
+ const http = claudeOwnHttpMount(server);
+ if (http) { servers[name] = http; converted = true; }
+ }
+ 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>();
+
+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);
+}
+
+/** 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);
+}
diff --git a/server/routes/own-mcp-http.test.ts b/server/routes/own-mcp-http.test.ts
index aff1b98698..b760d12ba5 100644
--- a/server/routes/own-mcp-http.test.ts
+++ b/server/routes/own-mcp-http.test.ts
@@ -1,10 +1,12 @@
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
+import { Agent, fetch as undiciFetch } from "undici";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { json, readBody } from "../harness/http.ts";
import type { RequestAuth } from "../request-auth.ts";
-import { ownMcpHttpRoutes } from "./own-mcp-http.ts";
+import { createOwnMcpHttpRoutes, ownMcpHttpRoutes } from "./own-mcp-http.ts";
+import type { RouteHandler } from "./table.ts";
import { AGENTS_ENV_HEADER, OWN_MCP_HTTP_PATH } from "./own-mcp-http-path.ts";
import { TOOL_LIMIT_ENV, TOOL_LIMIT_HEADER } from "../tool-count-limit.ts";
@@ -12,12 +14,14 @@ import { TOOL_LIMIT_ENV, TOOL_LIMIT_HEADER } from "../tool-count-limit.ts";
const internalCalls: Array<{ path: string; authorization?: string; body?: unknown }> = [];
let server: Server;
let base: string;
+/** The route under test; a test may swap in one with shorter timings or smaller limits. */
+let routes: RouteHandler = ownMcpHttpRoutes;
beforeAll(async () => {
server = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://127.0.0.1");
if (url.pathname.startsWith(OWN_MCP_HTTP_PATH)) {
- await ownMcpHttpRoutes({ req, res, url, path: url.pathname, method: req.method ?? "GET", auth: {} as RequestAuth, json, readBody });
+ await routes({ req, res, url, path: url.pathname, method: req.method ?? "GET", auth: {} as RequestAuth, json, readBody });
return;
}
const body = req.method === "POST" ? await readBody(req) : undefined;
@@ -27,7 +31,10 @@ beforeAll(async () => {
const call = body as { method: string; params?: { name?: string } };
return json(res, 200, { result: call.method === "tools/list"
? { tools: [{ name: "agent_browser_open", inputSchema: { type: "object" } }] }
- : { content: [{ type: "text", text: `ran ${call.params?.name}` }] } });
+ : call.params?.name === "slow" || call.params?.name === "slower"
+ ? await new Promise((resolve) => setTimeout(() => resolve({ content: [{ type: "text", text: `ran ${call.params?.name}` }] }), call.params?.name === "slow" ? 600 : 2_500))
+ : call.params?.name === "large" ? { content: [{ type: "text", text: "x".repeat(2_000) }] }
+ : { content: [{ type: "text", text: `ran ${call.params?.name}` }] } });
}
if (url.pathname === "/api/internal/agents") return json(res, 200, { bots: [{ id: "w1", name: "W1", model: "m" }] });
return json(res, 404, { error: "no such endpoint" });
@@ -40,6 +47,13 @@ afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())));
const post = (kind: string, body: unknown, headers: Record<string, string> = { authorization: "Bearer turn-capability" }) =>
fetch(`${base}${OWN_MCP_HTTP_PATH}${kind}`, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...headers }, body: JSON.stringify(body) });
+/** A JSON body, or the replies of a server-sent event stream (one, or all of a batch's in id order). */
+async function read(response: { headers: { get(name: string): string | null }; text(): Promise<string> }): Promise<unknown> {
+ const text = await response.text();
+ if (!response.headers.get("content-type")?.startsWith("text/event-stream")) return JSON.parse(text);
+ const events = text.split("\n").filter((line) => line.startsWith("data: ")).map((line) => JSON.parse(line.slice(6)) as { id: number });
+ return events.length === 1 ? events[0] : events.sort((a, b) => a.id - b.id);
+}
const agentsHeaders = (settings: Record<string, string>) => ({ authorization: "Bearer turn-capability",
[AGENTS_ENV_HEADER]: Buffer.from(JSON.stringify(settings)).toString("base64url") });
@@ -52,16 +66,16 @@ describe("OpenMausBot's own MCP servers over HTTP", () => {
expect([notice.status, await notice.text()]).toEqual([202, ""]);
expect(await (await post("browser", { jsonrpc: "2.0", id: 2, method: "tools/list" })).json())
.toEqual({ jsonrpc: "2.0", id: 2, result: { tools: [{ name: "agent_browser_open", inputSchema: { type: "object" } }] } });
- const batch = await (await post("browser", [{ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "agent_browser_open", arguments: {} } },
- { jsonrpc: "2.0", id: 4, method: "ping" }])).json();
+ const batch = await read(await post("browser", [{ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "agent_browser_open", arguments: {} } },
+ { jsonrpc: "2.0", id: 4, method: "ping" }]));
expect(batch).toEqual([{ jsonrpc: "2.0", id: 3, result: { content: [{ type: "text", text: "ran agent_browser_open" }] } }, { jsonrpc: "2.0", id: 4, result: {} }]);
expect(internalCalls.filter((call) => call.path === "/api/internal/browser/mcp").every((call) => call.authorization === "Bearer turn-capability")).toBe(true);
});
it("refuses without a capability, passes a wrong one to the endpoint that refuses it, and offers no stream or unknown server", async () => {
expect((await post("browser", { jsonrpc: "2.0", id: 1, method: "tools/list" }, {})).status).toBe(401);
- const wrong = await (await post("browser", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "agent_browser_open" } },
- { authorization: "Bearer stolen" })).json();
+ const wrong = await read(await post("browser", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "agent_browser_open" } },
+ { authorization: "Bearer stolen" }));
expect(wrong).toMatchObject({ id: 1, result: { isError: true } });
expect((await fetch(`${base}${OWN_MCP_HTTP_PATH}browser`, { headers: { authorization: "Bearer turn-capability" } })).status).toBe(405);
expect((await post("shell", { jsonrpc: "2.0", id: 1, method: "tools/list" })).status).toBe(404);
@@ -76,8 +90,8 @@ describe("OpenMausBot's own MCP servers over HTTP", () => {
expect(worker).toContain("coordinate_bots");
expect(chief.length).toBeGreaterThan(worker.length);
internalCalls.length = 0;
- const call = await (await post("agents", { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "list_bots", arguments: {} } },
- agentsHeaders({ OMB_BOT_ID: "chief", OMB_THREAD_ID: "t1", OMB_HARNESS_URL: "http://203.0.113.9:1" }))).json();
+ const call = await read(await post("agents", { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "list_bots", arguments: {} } },
+ agentsHeaders({ OMB_BOT_ID: "chief", OMB_THREAD_ID: "t1", OMB_HARNESS_URL: "http://203.0.113.9:1" })));
expect(call).toMatchObject({ id: 2, result: { content: [{ type: "text", text: expect.stringContaining("W1") }] } });
expect(internalCalls).toEqual([
expect.objectContaining({ path: "/api/internal/agents?self=chief", authorization: "Bearer turn-capability" }),
@@ -85,6 +99,14 @@ describe("OpenMausBot's own MCP servers over HTTP", () => {
]);
});
+ it("keeps Claude's deferred catalog: the setting rides the agents server's settings header", async () => {
+ const tools = async (settings: Record<string, string>) =>
+ ((await (await post("agents", { jsonrpc: "2.0", id: 1, method: "tools/list" }, agentsHeaders(settings))).json()) as { result: { tools: Array<{ name: string; _meta?: Record<string, unknown> }> } }).result.tools;
+ const deferred = (list: Array<{ _meta?: Record<string, unknown> }>) => list.filter((tool) => tool._meta?.["anthropic/alwaysLoad"] === false).length;
+ expect(deferred(await tools({ OMB_BOT_ID: "w2", OMB_THREAD_ID: "t2" }))).toBe(0);
+ expect(deferred(await tools({ OMB_BOT_ID: "w2", OMB_THREAD_ID: "t2", OMB_AGENTS_DEFER_TOOLS: "1" }))).toBeGreaterThan(0);
+ });
+
it("lists no more of a server's tools than the turn's tool limit allows", async () => {
const limited = await (await post("browser", { jsonrpc: "2.0", id: 5, method: "tools/list" },
{ authorization: "Bearer turn-capability", [TOOL_LIMIT_HEADER]: "0" })).json();
@@ -96,3 +118,67 @@ describe("OpenMausBot's own MCP servers over HTTP", () => {
expect(await agents({ OMB_BOT_ID: "w2", OMB_THREAD_ID: "t2", [TOOL_LIMIT_ENV]: "3" })).toEqual(whole.slice(0, 3));
});
});
+
+describe("a long tool call, and the stdio proxy's limits", () => {
+ const capability = { "content-type": "application/json", authorization: "Bearer turn-capability" };
+ const slow = { jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: "slow", arguments: {} } };
+ const swap = async <T>(route: RouteHandler, run: () => Promise<T>): Promise<T> => {
+ routes = route;
+ try { return await run(); } finally { routes = ownMcpHttpRoutes; }
+ };
+
+ it("streams headers at once and keeps the connection busy, so a client that gives up on silence still gets its answer", async () => {
+ // An HTTP client that gives up after 300 ms without headers or bytes (undici checks about every half second), as
+ // Node's fetch does after 300 s; the call takes 2.5 s.
+ const impatient = new Agent({ headersTimeout: 300, bodyTimeout: 300 });
+ const slower = { ...slow, params: { name: "slower", arguments: {} } };
+ try {
+ await swap(createOwnMcpHttpRoutes({ keepaliveMs: 100 }), async () => {
+ const streamed = await undiciFetch(`${base}${OWN_MCP_HTTP_PATH}browser`, { method: "POST", dispatcher: impatient,
+ headers: { ...capability, accept: "application/json, text/event-stream" }, body: JSON.stringify(slower) });
+ expect(streamed.headers.get("content-type")).toBe("text/event-stream");
+ const text = await streamed.text();
+ expect(text).toContain(": keepalive");
+ expect(await read({ headers: streamed.headers, text: async () => text })).toEqual({ jsonrpc: "2.0", id: 7, result: { content: [{ type: "text", text: "ran slower" }] } });
+ // Without server-sent events the answer is one JSON body, sent when the call ends: too late for this client.
+ await expect(undiciFetch(`${base}${OWN_MCP_HTTP_PATH}browser`, { method: "POST", dispatcher: impatient,
+ headers: { ...capability, accept: "application/json" }, body: JSON.stringify(slower) })).rejects.toMatchObject({ cause: { code: "UND_ERR_HEADERS_TIMEOUT" } });
+ });
+ } finally {
+ await impatient.close();
+ }
+ });
+
+ it("answers a quick list as JSON even to a client that takes events", async () => {
+ const listed = await post("browser", { jsonrpc: "2.0", id: 8, method: "tools/list" });
+ expect(listed.headers.get("content-type")).toBe("application/json");
+ });
+
+ it("holds each capability to 16 requests in flight per server, a batch's included, as its stdio proxy does", async () => {
+ await swap(createOwnMcpHttpRoutes({ maxPending: 2 }), async () => {
+ const batch = [7, 8, 9].map((id) => ({ ...slow, id }));
+ const answered = await read(await post("browser", batch)) as Array<{ id: number; result: { isError?: boolean; content: Array<{ text: string }> } }>;
+ expect(answered.map((reply) => [reply.id, reply.result.content[0]!.text])).toEqual([[7, "ran slow"], [8, "ran slow"], [9, "Too many pending browser requests."]]);
+ // Another capability, another bot's turn, has its own.
+ const first = post("browser", [{ ...slow, id: 1 }, { ...slow, id: 2 }]);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ const other = await read(await post("browser", { ...slow, id: 3 }, { authorization: "Bearer another-turn" })) as { result: { content: Array<{ text: string }> } };
+ expect(other.result.content[0]!.text).not.toMatch(/Too many pending/);
+ const same = await read(await post("browser", { ...slow, id: 4 })) as { result: { content: Array<{ text: string }> } };
+ expect(same.result.content[0]!.text).toBe("Too many pending browser requests.");
+ await read(await first);
+ const after = await read(await post("browser", { ...slow, id: 5 })) as { result: { content: Array<{ text: string }> } };
+ expect(after.result.content[0]!.text).toBe("ran slow");
+ });
+ });
+
+ it("cuts an answer over the stdio proxy's output cap to a failure the bot can read, over a whole batch", async () => {
+ await swap(createOwnMcpHttpRoutes({ maxOutputBytes: 3_000 }), async () => {
+ const large = (id: number) => ({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "large", arguments: {} } });
+ const one = await read(await post("browser", large(1))) as { result: { isError?: boolean } };
+ expect(one.result.isError).toBeUndefined();
+ const two = await read(await post("browser", [large(1), large(2)])) as Array<{ id: number; result: { isError?: boolean; content: Array<{ text: string }> } }>;
+ expect(two.filter((reply) => reply.result.isError === true).map((reply) => reply.result.content[0]!.text)).toEqual(["The browser answer exceeded the size limit."]);
+ });
+ });
+});
diff --git a/server/routes/own-mcp-http.ts b/server/routes/own-mcp-http.ts
index 3ba29c5822..80ac6cd6d2 100644
--- a/server/routes/own-mcp-http.ts
+++ b/server/routes/own-mcp-http.ts
@@ -1,18 +1,24 @@
-// OpenMausBot's own MCP servers (agents, browser, computer, data, Email, phone) over MCP's Streamable HTTP transport, JSON
-// responses only, for engines that reach MCP servers by URL: one endpoint in this process instead of a stdio proxy
-// process per server in every session. The turn's capability rides the Authorization header, and the endpoints behind
-// these answers check it, as they check the stdio proxies'.
-import type { IncomingHttpHeaders } from "node:http";
+// OpenMausBot's own MCP servers (agents, browser, computer, data, Email, phone) over MCP's Streamable HTTP transport, for
+// engines that reach MCP servers by URL: one endpoint in this process instead of a stdio proxy process per server in
+// every session. The turn's capability rides the Authorization header, and the endpoints behind these answers check it,
+// as they check the stdio proxies'. Each capability gets the stdio proxy's limits: 16 requests in flight per server, and
+// no more than its output cap in one answer.
+import type { IncomingHttpHeaders, ServerResponse } from "node:http";
import { agentsMcp } from "../drivers/agents-mcp.ts";
import { AGENTS_MCP_ENV } from "../drivers/agents-mcp-env.ts";
import type { Json } from "../drivers/agents-client.ts";
-import { harnessMcpRequest, MAX_INPUT_BYTES, parseHarnessMcpKind } from "../harness-mcp-request.ts";
+import { failure, harnessMcpRequest, MAX_INPUT_BYTES, MAX_OUTPUT_BYTES, parseHarnessMcpKind, type RpcId } from "../harness-mcp-request.ts";
import { parseToolLimit, TOOL_LIMIT_HEADER } from "../tool-count-limit.ts";
import { PASS, type RouteContext, type RouteHandler } from "./table.ts";
import { AGENTS_ENV_HEADER, OWN_MCP_HTTP_PATH } from "./own-mcp-http-path.ts";
+/** As each stdio proxy allows (harness-mcp-proxy.ts). */
+const MAX_PENDING = 16;
+/** Well inside the 300 s an engine's HTTP client may wait between bytes, headers included (Node's fetch, undici). */
+const KEEPALIVE_MS = 15_000;
+
function agentsEnv(headers: IncomingHttpHeaders, token: string, harness: string): NodeJS.ProcessEnv {
let settings: Record<string, unknown> = {};
try {
@@ -25,36 +31,97 @@ function agentsEnv(headers: IncomingHttpHeaders, token: string, harness: string)
return env;
}
-export async function ownMcpHttpRoutes({ req, res, path, method, json, readBody }: RouteContext): ReturnType<RouteHandler> {
- if (!path.startsWith(OWN_MCP_HTTP_PATH)) return PASS;
- const name = path.slice(OWN_MCP_HTTP_PATH.length);
- const kind = name === "agents" ? "agents" : parseHarnessMcpKind(name);
- if (!kind) return json(res, 404, { error: "no such MCP server" });
- // No server-sent stream and no session to end: a client falls back to plain request and response.
- if (method !== "POST") {
- res.writeHead(405, { allow: "POST" });
- res.end();
- return;
- }
- const token = /^Bearer (\S+)$/.exec(req.headers.authorization ?? "")?.[1];
- if (!token) return json(res, 401, { error: "unauthorized" });
- const body = await readBody(req, MAX_INPUT_BYTES);
- const harness = `http://127.0.0.1:${req.socket.localPort}/`;
- const answer: (frame: Json) => Promise<unknown> = kind === "agents"
- ? agentsMcp(agentsEnv(req.headers, token, harness.slice(0, -1)))
- : (frame) => harnessMcpRequest(frame, { url: harness, token, kind, toolLimit: parseToolLimit(req.headers[TOOL_LIMIT_HEADER]) });
- const frames: Json[] = Array.isArray(body) ? body : [body];
- const replies = (await Promise.all(frames.map(async (frame) => {
- const reply = await answer(frame) as { result?: { protocolVersion?: unknown } } | undefined;
- // The version the client asked for: these servers answer the same way in every version.
- const asked = (frame?.params as { protocolVersion?: unknown } | undefined)?.protocolVersion;
- if (frame?.method === "initialize" && typeof asked === "string" && reply?.result) reply.result.protocolVersion = asked;
- return reply;
- }))).filter((reply) => reply !== undefined);
- if (!replies.length) {
- res.writeHead(202);
+type Frame = { id?: RpcId; method?: unknown; params?: unknown } | null;
+const isRequest = (frame: Frame) => frame !== null && typeof frame === "object" && Object.hasOwn(frame, "id");
+
+/** A tool call may run for minutes; a client that takes server-sent events gets its headers at once and a comment now and
+ * then, so its HTTP client never gives up waiting. Everything else is answered as one JSON body. */
+function streams(headers: IncomingHttpHeaders, frames: Frame[]): boolean {
+ return /\btext\/event-stream\b/.test(headers.accept ?? "") && frames.some((frame) => isRequest(frame) && frame!.method === "tools/call");
+}
+
+export function createOwnMcpHttpRoutes(options: { keepaliveMs?: number; maxPending?: number; maxOutputBytes?: number } = {}): RouteHandler {
+ const keepaliveMs = options.keepaliveMs ?? KEEPALIVE_MS;
+ const maxPending = options.maxPending ?? MAX_PENDING;
+ const maxOutputBytes = options.maxOutputBytes ?? MAX_OUTPUT_BYTES;
+ /** Requests in flight per server and capability: a bot's turn, as one stdio proxy serves. */
+ const pending = new Map<string, number>();
+
+ return async function ownMcpHttpRoutes({ req, res, path, method, json, readBody }: RouteContext): ReturnType<RouteHandler> {
+ if (!path.startsWith(OWN_MCP_HTTP_PATH)) return PASS;
+ const name = path.slice(OWN_MCP_HTTP_PATH.length);
+ const kind = name === "agents" ? "agents" : parseHarnessMcpKind(name);
+ if (!kind) return json(res, 404, { error: "no such MCP server" });
+ // No stream to open on its own and no session to end: a client falls back to request and response.
+ if (method !== "POST") {
+ res.writeHead(405, { allow: "POST" });
+ res.end();
+ return;
+ }
+ const token = /^Bearer (\S+)$/.exec(req.headers.authorization ?? "")?.[1];
+ if (!token) return json(res, 401, { error: "unauthorized" });
+ const body = await readBody(req, MAX_INPUT_BYTES);
+ const harness = `http://127.0.0.1:${req.socket.localPort}/`;
+ const answer: (frame: Json) => Promise<unknown> = kind === "agents"
+ ? agentsMcp(agentsEnv(req.headers, token, harness.slice(0, -1)))
+ : (frame) => harnessMcpRequest(frame, { url: harness, token, kind, toolLimit: parseToolLimit(req.headers[TOOL_LIMIT_HEADER]) });
+ const frames: Frame[] = Array.isArray(body) ? body : [body as Frame];
+ const key = `${kind}\0${token}`;
+
+ const run = async (frame: Frame): Promise<unknown> => {
+ const id = isRequest(frame) ? frame!.id ?? null : null;
+ if ((pending.get(key) ?? 0) >= maxPending) return isRequest(frame) ? failure(id, frame!.method, `Too many pending ${kind} requests.`) : undefined;
+ pending.set(key, (pending.get(key) ?? 0) + 1);
+ try {
+ const reply = await answer(frame as Json) as { result?: { protocolVersion?: unknown } } | undefined;
+ // The version the client asked for: these servers answer the same way in every version.
+ const asked = (frame?.params as { protocolVersion?: unknown } | undefined)?.protocolVersion;
+ if (frame?.method === "initialize" && typeof asked === "string" && reply?.result) reply.result.protocolVersion = asked;
+ return reply;
+ } catch (error) {
+ return isRequest(frame) ? failure(id, frame!.method, error instanceof Error ? error.message : String(error)) : undefined;
+ } finally {
+ const left = (pending.get(key) ?? 1) - 1;
+ if (left > 0) pending.set(key, left); else pending.delete(key);
+ }
+ };
+ // The stdio proxy's output cap, over the whole answer: a reply that would pass it becomes a failure the bot can read.
+ let sent = 0;
+ const capped = (frame: Frame, reply: unknown): unknown => {
+ if (reply === undefined) return undefined;
+ const size = Buffer.byteLength(JSON.stringify(reply));
+ const kept = sent + size > maxOutputBytes
+ ? failure(isRequest(frame) ? frame!.id ?? null : null, frame?.method, `The ${kind} answer exceeded the size limit.`) : reply;
+ sent += kept === reply ? size : Buffer.byteLength(JSON.stringify(kept));
+ return kept;
+ };
+
+ if (streams(req.headers, frames)) return stream(res, frames, run, capped, keepaliveMs);
+ const replies = (await Promise.all(frames.map(async (frame) => capped(frame, await run(frame))))).filter((reply) => reply !== undefined);
+ if (!replies.length) {
+ res.writeHead(202);
+ res.end();
+ return;
+ }
+ json(res, 200, Array.isArray(body) ? replies : replies[0]);
+ };
+}
+
+/** One server-sent event per reply as each finishes, with a comment line in between to keep the connection busy. */
+async function stream(res: ServerResponse, frames: Frame[], run: (frame: Frame) => Promise<unknown>, capped: (frame: Frame, reply: unknown) => unknown, keepaliveMs: number): Promise<void> {
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache, no-transform", connection: "keep-alive" });
+ res.flushHeaders();
+ const keepalive = setInterval(() => { if (!res.writableEnded) res.write(": keepalive\n\n"); }, keepaliveMs);
+ res.on("close", () => clearInterval(keepalive));
+ try {
+ await Promise.all(frames.map(async (frame) => {
+ const reply = capped(frame, await run(frame));
+ if (reply !== undefined && !res.writableEnded) res.write(`event: message\ndata: ${JSON.stringify(reply)}\n\n`);
+ }));
+ } finally {
+ clearInterval(keepalive);
res.end();
- return;
}
- json(res, 200, Array.isArray(body) ? replies : replies[0]);
}
+
+export const ownMcpHttpRoutes = createOwnMcpHttpRoutes();
diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.ts
index 7b6196ffbc..92ec8b5297 100755
--- a/server/testing/fake-acp-cli.ts
+++ b/server/testing/fake-acp-cli.ts
@@ -273,6 +273,8 @@ const dumpEnv = Object.fromEntries(
"PATH",
"HOME",
"USERPROFILE",
+ "NO_PROXY",
+ "no_proxy",
"PI_CODING_AGENT_SESSION_DIR",
"TEMP",
"TMP",
diff --git a/server/testing/fake-codex-app-server.ts b/server/testing/fake-codex-app-server.ts
index 45a2ecc86f..039dc194db 100755
--- a/server/testing/fake-codex-app-server.ts
+++ b/server/testing/fake-codex-app-server.ts
@@ -179,6 +179,10 @@ if (process.argv[2] === "exec") {
process.exit(0);
}
const calls: Array<{ method: string; params: unknown }> = [];
+/** A `-c` value as codex-cli reads it: JSON-compatible TOML, or an inline table of strings (`env`, `http_headers`). */
+const tomlValue = (raw: string): unknown => raw.startsWith("{")
+ ? Object.fromEntries([...raw.matchAll(/("(?:[^"\\]|\\.)*")\s*=\s*("(?:[^"\\]|\\.)*")/g)].map((pair) => [JSON.parse(pair[1]!), JSON.parse(pair[2]!)]))
+ : JSON.parse(raw);
const mcpOverrides: Record<string, Record<string, unknown>> = {};
for (let index = 0; process.env.FAKE_CODEX_MCP_OVERRIDES === "1" && index < process.argv.length; index++) {
if (process.argv[index - 1] === "-c" && process.argv[index]!.startsWith("mcp_servers=")) {
@@ -188,7 +192,7 @@ for (let index = 0; process.env.FAKE_CODEX_MCP_OVERRIDES === "1" && index < proc
continue;
}
const match = process.argv[index - 1] === "-c" ? /^mcp_servers\.([^.]+)\.([^.]+)=(.*)$/.exec(process.argv[index]!) : null;
- if (match) (mcpOverrides[match[1]!] ??= {})[match[2]!] = JSON.parse(match[3]!);
+ if (match) (mcpOverrides[match[1]!] ??= {})[match[2]!] = tomlValue(match[3]!);
}
// codex-cli 0.160 config/read reports every shell_environment_policy field, null when unset. A `-c
// shell_environment_policy.exclude=[…]` override replaces the list and drops the lower `filters` (0.160.1).
@@ -245,11 +249,7 @@ const mcpMounts = (): Record<string, Record<string, unknown>> => {
process.argv.forEach((arg, index) => {
const match = process.argv[index - 1] === "-c" ? /^mcp_servers\.([^.]+)\.([^.=]+)=(.*)$/.exec(arg) : null;
if (!match) return;
- const raw = match[3]!;
- const value = raw.startsWith("{")
- ? Object.fromEntries([...raw.matchAll(/("(?:[^"\\]|\\.)*")\s*=\s*("(?:[^"\\]|\\.)*")/g)].map((pair) => [JSON.parse(pair[1]!), JSON.parse(pair[2]!)]))
- : JSON.parse(raw);
- (mounts[match[1]!] ??= {})[match[2]!] = value;
+ (mounts[match[1]!] ??= {})[match[2]!] = tomlValue(match[3]!);
});
return mounts;
};
@@ -283,6 +283,7 @@ const startUrlMcp = async (mount: Record<string, unknown>, handshake: unknown):
const headers: Record<string, string> = { "content-type": "application/json", accept: "application/json, text/event-stream" };
if (typeof mount.bearer_token_env_var === "string") headers.authorization = `Bearer ${process.env[mount.bearer_token_env_var] ?? ""}`;
for (const [header, variable] of Object.entries((mount.env_http_headers ?? {}) as Record<string, string>)) headers[header] = process.env[variable] ?? "";
+ Object.assign(headers, mount.http_headers ?? {});
const post = async (frame: object) => {
const response = await fetch(mount.url as string, { method: "POST", headers, body: JSON.stringify({ jsonrpc: "2.0", ...frame }), signal: AbortSignal.timeout(20_000) });
const session = response.headers.get("mcp-session-id");
@@ -314,7 +315,8 @@ const announceMcpStartup = () => {
const report = (name: string, status: string, error: string | null = null) =>
out({ jsonrpc: "2.0", method: "mcpServer/startupStatus/updated", params: { threadId: null, name, status, error, failureReason: null } });
mcpPending = Object.entries(mcpMounts())
- .filter(([name, fields]) => "command" in fields && fields.enabled !== false && name !== process.env.FAKE_CODEX_MCP_FAILED)
+ // Every server it starts, by command or by URL (OpenMausBot's own, with OMB_OWN_MCP_HTTP=1).
+ .filter(([name, fields]) => ("command" in fields || "url" in fields) && fields.enabled !== false && name !== process.env.FAKE_CODEX_MCP_FAILED)
.map(([name]) => name);
for (const name of mcpPending) report(name, "starting");
const settle = (name: string) => {