Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: keep custom Codex MCP mounts distinct and literal keys intact
Afloata0277e17ec94
diff --git a/server/drivers/codex-mcp-names.test.ts b/server/drivers/codex-mcp-names.test.tsindex 6fab4362b4..0dff21fa13 100644--- a/server/drivers/codex-mcp-names.test.ts+++ b/server/drivers/codex-mcp-names.test.ts@@ -2,7 +2,9 @@ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";-import { codexConfigMcp, codexConfigMcpServerNames, codexConfigRunsServer, mcpServerNamesInToml, mountedMcpServerName } from "./codex-mcp-names.ts";+import { codexConfigMcp, codexConfigMcpServerNames, codexConfigRunsServer, codexMcpDisableArgs, mcpServerNamesInToml, mountedMcpServerName } from "./codex-mcp-names.ts";++import { parseToml } from "../toml-lite.ts";const dirs: string[] = [];afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { force: true, recursive: true }); });@@ -104,3 +106,29 @@ describe("codexConfigRunsServer", () => {});});++describe("Codex literal MCP override keys", () => {+ it("disables literal dotted and quoted names without creating nested servers", () => {+ const names = new Set(["notes.prod", 'quoted"name', "ordinary"]);+ const args = codexMcpDisableArgs(names);+ expect(args).toHaveLength(2);+ expect(args[0]).toBe("-c");+ expect(parseToml(args[1]!).mcp_servers).toEqual({+ "notes.prod": { enabled: false },+ 'quoted"name': { enabled: false },+ ordinary: { enabled: false },+ });+ });++ it("keeps existing flat CLI overrides for ordinary names", () => {+ expect(codexMcpDisableArgs(new Set(["notes", "plain-name"]))).toEqual([+ "-c", "mcp_servers.notes.enabled=false", "-c", "mcp_servers.plain-name.enabled=false",+ ]);+ expect(codexMcpDisableArgs(new Set())).toEqual([]);+ });++ it.each(["notes.prod", "notes prod", 'notes"prod'])("gives %s a safe and unoccupied CLI mount name", (name) => {+ expect(mountedMcpServerName(name, new Set())).toBe("notes_prod");+ expect(mountedMcpServerName(name, new Set(["notes_prod", "notes_prod_openmausbot"]))).toBe("notes_prod_openmausbot2");+ });+});diff --git a/server/drivers/codex-mcp-names.ts b/server/drivers/codex-mcp-names.tsindex 4882007f7a..7b931d6057 100644--- a/server/drivers/codex-mcp-names.ts+++ b/server/drivers/codex-mcp-names.ts@@ -44,6 +44,15 @@ export function codexConfigMcp(env: Record<string, string | undefined>): CodexCoreturn { names: mcpServerNamesInToml(text), tables };}+/** Disable literal config keys before mounting per-turn servers. Codex splits CLI paths at every dot. */+export function codexMcpDisableArgs(names: ReadonlySet<string>): string[] {+ if ([...names].some((name) => !/^[A-Za-z0-9_-]+$/.test(name))) {+ const tables = [...names].map((name) => `${JSON.stringify(name)} = { enabled = false }`).join(", ");+ return ["-c", `mcp_servers={ ${tables} }`];+ }+ return [...names].flatMap((name) => ["-c", `mcp_servers.${name}.enabled=false`]);+}+export function codexConfigMcpServerNames(env: Record<string, string | undefined>): Set<string> {return codexConfigMcp(env).names;}@@ -72,8 +81,9 @@ export function codexConfigRunsServer(config: CodexConfigMcp, name: string, serv}export function mountedMcpServerName(name: string, taken: ReadonlySet<string>): string {- if (!taken.has(name)) return name;- let candidate = `${name}_openmausbot`;- for (let i = 2; taken.has(candidate); i++) candidate = `${name}_openmausbot${i}`;+ const safeName = name.replace(/[^A-Za-z0-9_-]/g, "_") || "mcp";+ if (!taken.has(safeName)) return safeName;+ let candidate = `${safeName}_openmausbot`;+ for (let i = 2; taken.has(candidate); i++) candidate = `${safeName}_openmausbot${i}`;return candidate;}diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.tsindex 748b284c55..8f304df550 100644--- a/server/drivers/codex.test.ts+++ b/server/drivers/codex.test.ts@@ -16,6 +16,7 @@ import { ChatGptPlanAuthController } from "./chatgpt-plan-auth.ts";import { recordEvents, type EventRecorder } from "../testing/events.ts";import { CodexDriver, codexNativeIncomingLogMessage, codexUpdateCommand } from "./codex.ts";import { codexCliOverrides } from "./codex-process.ts";+import { parseToml } from "../toml-lite.ts";import * as codexProcess from "./codex-process.ts";import { CODEX_SIGN_IN_EXPIRED, codexLimitFacts, codexNotSignedIn, codexSignInRefused, codexUserError } from "./codex-errors.ts";import { CODEX_USAGE_LIMIT_REACHED } from "../../shared/codex-usage-limit.ts";@@ -275,6 +276,51 @@ describe("CodexDriver turns (fake app-server)", () => {expect(restored.calls.find((call: { method: string }) => call.method === "thread/resume").params.config.mcp_servers.notes_openmausbot.default_tools_approval_mode).toBe("prompt");});+ it("keeps custom MCP mount names unique after an inline collision", async () => {+ const dump = join(scratch, "scope-inline-collision.json"); process.env.FAKE_CODEX_DUMP = dump;+ mkdirSync(join(scratch, ".codex"), { recursive: true });+ writeFileSync(join(scratch, ".codex/config.toml"), 'mcp_servers = { notes = { url = "https://example.test/ambient" } }');+ await create({ environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex"), FAKE_CODEX_MCP_OVERRIDES: "1" } });+ await instance.adapter.sendTurn({+ threadId: "scope-inline-collision", text: "Fixture",+ toolScope: { allow: ["native:*", "mcp:notes:read", "mcp:notes_openmausbot:read"] },+ integrations: { custom: {+ notes: { type: "http", url: "https://example.test/first", headers: {} },+ notes_openmausbot: { type: "http", url: "https://example.test/second", headers: {} },+ } },+ });+ await recorder.until((event) => event.type === "turn.completed");+ const seen = JSON.parse(readFileSync(dump, "utf8"));+ const selected = seen.calls.find((call: { method: string }) => call.method === "thread/start").params.config.mcp_servers;+ expect(Object.keys(selected)).toEqual(["notes_openmausbot", "notes_openmausbot_openmausbot"]);+ expect(Object.keys(seen.env).filter((name) => name.startsWith("OMB_GATE_CONFIG_"))).toHaveLength(2);+ expect(seen.calls.filter((call: { method: string }) => call.method === "turn/start")).toHaveLength(1);+ });++ it("keeps literal MCP server names intact in scoped CLI overrides", async () => {+ const dump = join(scratch, "scope-literal-name.json"); process.env.FAKE_CODEX_DUMP = dump;+ mkdirSync(join(scratch, ".codex"), { recursive: true });+ writeFileSync(join(scratch, ".codex/config.toml"), 'mcp_servers = { "notes.prod" = { url = "https://example.test/ambient" } }');+ await create({ environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex"), FAKE_CODEX_MCP_OVERRIDES: "1" } });+ await instance.adapter.sendTurn({+ threadId: "scope-literal-name", text: "Fixture",+ toolScope: { allow: ["native:*", "mcp:agents:*", "mcp:notes.prod:read"] },+ integrations: {+ agents: { command: "node", args: ["agents.js"], env: {} },+ custom: { "notes.prod": { type: "http", url: "https://example.test/private", headers: {} } },+ },+ });+ await recorder.until((event) => event.type === "turn.completed");+ const seen = JSON.parse(readFileSync(dump, "utf8"));+ const table = seen.argv.find((arg: string) => arg.startsWith("mcp_servers="));+ expect(parseToml(table).mcp_servers).toEqual({ "notes.prod": { enabled: false } });+ expect(seen.argv).not.toContain("mcp_servers.notes.prod.enabled=false");+ expect(seen.argv.indexOf(table)).toBeLessThan(seen.argv.findIndex((arg: string) => arg.startsWith("mcp_servers.agents.command=")));+ const selected = seen.calls.find((call: { method: string }) => call.method === "thread/start").params.config.mcp_servers;+ expect(Object.keys(selected)).toEqual(["agents", "notes_prod"]);+ expect(seen.calls.filter((call: { method: string }) => call.method === "turn/start")).toHaveLength(1);+ });+it("still mounts its own copy of a config.toml server when a tool selection switches config.toml's off", async () => {const dump = join(scratch, "scope-same.json"); process.env.FAKE_CODEX_DUMP = dump;mkdirSync(join(scratch, ".codex"), { recursive: true }); writeFileSync(join(scratch, ".codex/config.toml"), '[mcp_servers.notes]\nurl="https://example.test/notes"\n');diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex deae4dede4..54113a93a5 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -13,7 +13,7 @@ import { createHash } from "node:crypto";import { mkdirSync } from "node:fs";import { join } from "node:path";import { homedir } from "node:os";-import { codexConfigMcp, codexConfigRunsServer, mountedMcpServerName } from "./codex-mcp-names.ts";+import { codexConfigMcp, codexConfigRunsServer, codexMcpDisableArgs, mountedMcpServerName } from "./codex-mcp-names.ts";import { DATA_DIR, stripWorkspaceCredentialEnv } from "../config.ts";import { laterStartup, openStartupModelCatalog, unconfirmedModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";@@ -108,7 +108,7 @@ const renamedMcpServers = new Set<string>();function noteRenamedMcpServer(name: string, mountName: string): void {if (renamedMcpServers.has(name)) return;renamedMcpServers.add(name);- console.error(`codex: MCP server ${JSON.stringify(name)} is also declared in Codex's own config.toml — mounted as ${JSON.stringify(mountName)} for this bot so the two do not merge`);+ console.error(`codex: MCP server ${JSON.stringify(name)} is mounted as ${JSON.stringify(mountName)} for this bot to keep its CLI configuration distinct`);}interface CodexApprovalParams {@@ -551,6 +551,9 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {...(turn.toolScope === undefined && !authBridge ? [] : ["-c", "features.shell_snapshot=false"]),// A guest-driven turn: no shell, no file reads (-c wins over config files)....(turn.guestConfined ? GUEST_CONFINED_CODEX_ARGS : [])];+ const codexConfig = codexConfigMcp(env), declaredInCodexConfig = codexConfig.names;+ // A whole-table override preserves literal names and must precede the per-mount CLI overrides.+ if (turn.toolScope !== undefined) appServerArgs.push(...codexMcpDisableArgs(declaredInCodexConfig));const baseEnv = new Map(Object.entries(env).filter(([, value]) => value !== undefined));const mountedNames = new Set<string>();const selectedMcp = new Map<string, StdioMcpSpec>();@@ -606,12 +609,10 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {for (const name of ["data", "email", "device"] as const) if (turn.integrations?.[name]) mountSelected(name, name, turn.integrations[name]);// A `-c` override merges with a same-named server in config.toml, and stdio over url is// "invalid configuration" that kills the turn, so such a server mounts under its own name.- const codexConfig = codexConfigMcp(env), declaredInCodexConfig = codexConfig.names;- if (turn.toolScope !== undefined) {- for (const name of declaredInCodexConfig) appServerArgs.push("-c", `mcp_servers.${name}.enabled=false`);- }+ const takenMcpNames = new Set([...declaredInCodexConfig, ...selectedMcp.keys(), ...(turn.integrations?.phone ? ["openmausbot_phone"] : [])]);for (const [name, server] of Object.entries(turn.integrations?.custom ?? {}).filter(([name, server]) => turn.toolScope !== undefined || !codexConfigRunsServer(codexConfig, name, server))) {- const mountName = mountedMcpServerName(name, declaredInCodexConfig);+ const mountName = mountedMcpServerName(name, takenMcpNames);+ takenMcpNames.add(mountName);if (mountName !== name) noteRenamedMcpServer(name, mountName);mountSelected(name, mountName, server, "prompt", turn.toolScope === undefined && !("url" in server) ? boxProxyEnvNames() : []);}diff --git a/server/testing/fake-codex-app-server.ts b/server/testing/fake-codex-app-server.tsold mode 100755new mode 100644index 7dfc2a004f..97ed1a3e47--- a/server/testing/fake-codex-app-server.ts+++ b/server/testing/fake-codex-app-server.ts@@ -63,6 +63,8 @@import { spawn } from "node:child_process";import { appendFileSync, existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";+import { parseToml } from "../toml-lite.ts";+const mode = process.env.FAKE_CODEX_MODE ?? "happy";// Follow the spawning server down; on Windows ppid does not change after parent exit.@@ -175,6 +177,13 @@ if (process.argv[2] === "exec") {const calls: Array<{ method: string; params: unknown }> = [];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=")) {+ const tables = parseToml(process.argv[index]!).mcp_servers as Record<string, Record<string, unknown>>;+ // The real CLI replaces its accumulated override table before later dotted-path fields apply.+ for (const name of Object.keys(mcpOverrides)) delete mcpOverrides[name];+ Object.assign(mcpOverrides, tables);+ 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]!);}