Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): stop Codex dying on mcp_servers overrides at startup (#88075)

Charles Vien2352f88853af
diff --git a/products/desktop/packages/agent/src/adapters/base-acp-agent.ts b/products/desktop/packages/agent/src/adapters/base-acp-agent.ts
index 88ef48c87073..d01e5ac8dcba 100644
--- a/products/desktop/packages/agent/src/adapters/base-acp-agent.ts
+++ b/products/desktop/packages/agent/src/adapters/base-acp-agent.ts
@@ -34,10 +34,9 @@ import {
} from "../gateway-models";
import { Logger } from "../utils/logger";
/**
- * Shared settings manager interface that both Claude's SettingsManager
- * and Codex's CodexSettingsManager implement. BaseAcpAgent only calls
- * dispose() on this; each adapter's Session type narrows it to the
- * concrete implementation.
+ * Shared settings manager interface that Claude's SettingsManager
+ * implements. BaseAcpAgent only calls dispose() on this; each adapter's
+ * Session type narrows it to the concrete implementation.
*/
export interface BaseSettingsManager {
dispose(): void;
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/settings.test.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/settings.test.ts
deleted file mode 100644
index 9dabe6c198c2..000000000000
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/settings.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-
-const readFileSync = vi.hoisted(() => vi.fn());
-vi.mock("node:fs", () => ({ readFileSync }));
-
-const { CodexSettingsManager } = await import("./settings");
-
-function serverNamesFor(toml: string): string[] {
- readFileSync.mockReturnValue(toml);
- return new CodexSettingsManager("/repo").getSettings().mcpServerNames.sort();
-}
-
-describe("CodexSettingsManager MCP server names", () => {
- // Regression: a `[mcp_servers.<name>.env]` table was treated as its own
- // server, so the spawn emitted `mcp_servers.<name>.env.enabled=false`, which
- // sets a boolean on codex's string-typed env map. codex-acp then rejected the
- // whole config, crashed the session, and the host silently ran Claude/Opus.
- it.each([
- {
- name: "collapses a nested sub-table to its parent server and dedupes",
- toml: [
- "[mcp_servers.node_repl]",
- 'command = "node"',
- "[mcp_servers.node_repl.env]",
- 'FOO = "bar"',
- "[mcp_servers.other]",
- 'command = "x"',
- ],
- expected: ["node_repl", "other"],
- },
- {
- name: "collapses a deeply nested sub-table to its parent server",
- toml: ["[mcp_servers.foo.bar.baz]", 'k = "v"'],
- expected: ["foo"],
- },
- {
- name: "keeps the inner name for a double-quoted dotted server key",
- toml: ['[mcp_servers."my.server"]', 'command = "x"'],
- expected: ["my.server"],
- },
- {
- name: "keeps the inner name for a single-quoted dotted server key",
- toml: ["[mcp_servers.'my.server']", 'command = "x"'],
- expected: ["my.server"],
- },
- {
- name: "returns no servers when none are declared",
- toml: ['model = "gpt-5.5"'],
- expected: [],
- },
- ])("$name", ({ toml, expected }) => {
- expect(serverNamesFor(toml.join("\n"))).toEqual(expected);
- });
-});
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/settings.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/settings.ts
deleted file mode 100644
index cfe8240e481b..000000000000
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/settings.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import * as fs from "node:fs";
-import * as os from "node:os";
-import * as path from "node:path";
-
-/**
- * Codex settings parsed from ~/.codex/config.toml and project-level config.
- *
- * Mirrors the shape of ClaudeCodeSettings so both adapters have a
- * consistent settings interface.
- */
-export interface CodexSettings {
- model?: string;
- personality?: string;
- modelReasoningEffort?: string;
- trustLevel?: string;
- // Names of every `[mcp_servers.<name>]` section declared in the user's config.toml
- mcpServerNames: string[];
-}
-
-/**
- * SettingsManager for Codex sessions.
- *
- * Reads from ~/.codex/config.toml (user-level) and respects
- * per-project trust configuration. Has the same public interface
- * as Claude's SettingsManager so both can satisfy BaseSession.
- */
-export class CodexSettingsManager {
- private cwd: string;
- private settings: CodexSettings = { mcpServerNames: [] };
-
- constructor(cwd: string) {
- this.cwd = cwd;
- this.loadSettings();
- }
-
- async initialize(): Promise<void> {
- // No-op: settings are loaded in the constructor. Kept async to
- // satisfy the BaseSettingsManager interface.
- }
-
- private getConfigPath(): string {
- return path.join(os.homedir(), ".codex", "config.toml");
- }
-
- private loadSettings(): void {
- const configPath = this.getConfigPath();
- try {
- const content = fs.readFileSync(configPath, "utf-8");
- this.settings = parseCodexToml(content, this.cwd);
- } catch {
- this.settings = { mcpServerNames: [] };
- }
- }
-
- getSettings(): CodexSettings {
- return this.settings;
- }
-
- getCwd(): string {
- return this.cwd;
- }
-
- async setCwd(cwd: string): Promise<void> {
- if (this.cwd === cwd) return;
- this.cwd = cwd;
- this.loadSettings();
- }
-
- dispose(): void {
- // No-op: no resources to release. Kept to satisfy the BaseSettingsManager interface.
- }
-}
-
-/**
- * Extracts the server name from a `mcp_servers.<name>...` section path, taking
- * only the first key segment. A nested table like `mcp_servers.foo.env`
- * describes the `env` field of server `foo`, not a separate server, so it must
- * collapse to `foo`. Treating it as its own server emits
- * `mcp_servers.foo.env.enabled=false`, which sets a boolean on the string-typed
- * env map and makes codex reject the whole config (it then crashes and the
- * host silently falls back to Claude). Quoted segments (`"a.b"`) keep their dots.
- */
-function firstMcpServerName(sectionPath: string): string | null {
- const trimmed = sectionPath.trim();
- if (!trimmed) return null;
- const quoted = trimmed.match(/^(["'])(.*?)\1/);
- if (quoted) return quoted[2] ?? null;
- const dotIndex = trimmed.indexOf(".");
- return dotIndex === -1 ? trimmed : trimmed.slice(0, dotIndex);
-}
-
-/**
- * Minimal TOML parser for codex config.toml.
- * Handles flat key=value pairs and [projects."path"] sections.
- * Does NOT handle full TOML spec — only what codex config uses.
- */
-function parseCodexToml(content: string, cwd: string): CodexSettings {
- const settings: CodexSettings = { mcpServerNames: [] };
- const mcpServerNames = new Set<string>();
- let currentSection = "";
-
- for (const line of content.split("\n")) {
- const trimmed = line.trim();
- if (!trimmed || trimmed.startsWith("#")) continue;
-
- // Section header: [projects."/some/path"] or [section]
- const sectionMatch = trimmed.match(/^\[(.+)\]$/);
- if (sectionMatch) {
- currentSection = sectionMatch[1] ?? "";
- if (currentSection.startsWith("mcp_servers.")) {
- const serverName = firstMcpServerName(
- currentSection.slice("mcp_servers.".length),
- );
- if (serverName) mcpServerNames.add(serverName);
- }
- continue;
- }
-
- // Key = value
- const kvMatch = trimmed.match(/^(\w+)\s*=\s*(.+)$/);
- if (!kvMatch) continue;
-
- const key = kvMatch[1];
- let value = kvMatch[2]?.trim() ?? "";
-
- // Strip quotes
- if (
- (value.startsWith('"') && value.endsWith('"')) ||
- (value.startsWith("'") && value.endsWith("'"))
- ) {
- value = value.slice(1, -1);
- }
-
- if (!currentSection) {
- // Top-level keys
- if (key === "model") settings.model = value;
- if (key === "personality") settings.personality = value;
- if (key === "model_reasoning_effort")
- settings.modelReasoningEffort = value;
- } else if (currentSection === `projects."${cwd}"`) {
- // Project-specific keys
- if (key === "trust_level") settings.trustLevel = value;
- }
- }
-
- settings.mcpServerNames = Array.from(mcpServerNames);
- return settings;
-}
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts
index 93d417e268c3..8bbc985b7eb6 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts
@@ -5,7 +5,6 @@ import type { Readable, Writable } from "node:stream";
import { applyContextWikiEnv } from "../../context-wiki";
import type { ContextWikiEnv, ProcessSpawnedCallback } from "../../types";
import { Logger } from "../../utils/logger";
-import { CodexSettingsManager } from "./settings";
/**
* Host-facing codex options passed through `createAcpConnection`'s
@@ -147,16 +146,6 @@ export function buildAppServerArgs(
);
}
- // Disable the user's ambient ~/.codex MCP servers so the adapter only exposes
- // MCP servers PostHog injects per-thread; otherwise codex fails connecting to them.
- for (const name of new CodexSettingsManager(
- options.cwd ?? process.cwd(),
- ).getSettings().mcpServerNames) {
- // codex's `-c` parser rejects quoted/special key segments; skip such names.
- if (!/^[A-Za-z0-9_-]+$/.test(name)) continue;
- args.push("-c", `mcp_servers.${name}.enabled=false`);
- }
-
if (options.apiBaseUrl) {
args.push("-c", `model_provider="posthog"`);
args.push("-c", `model_providers.posthog.name="PostHog Gateway"`);
diff --git a/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts b/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts
index ff5fd4ff96e0..9c7dfabdae78 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts
@@ -1,4 +1,4 @@
-import { existsSync, readFileSync } from "node:fs";
+import { existsSync, readFileSync, statSync } from "node:fs";
import { mkdir, mkdtemp, readlink, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -16,6 +16,7 @@ import {
cleanupCodexHome,
getCodexHomeDir,
prepareCodexHome,
+ stripMcpServers,
} from "./codex-home";
const noopLog = { debug() {}, info() {}, warn() {}, error() {} };
@@ -84,11 +85,21 @@ describe("prepareCodexHome", () => {
);
});
- it("copies the user's ~/.codex/config.toml when present", async () => {
+ it("copies the user's ~/.codex/config.toml without its mcp_servers tables", async () => {
const codexConfigDir = path.join(testHome.dir, ".codex");
await mkdir(codexConfigDir, { recursive: true });
const configPath = path.join(codexConfigDir, "config.toml");
- await writeFile(configPath, 'model = "gpt-5-codex"\n');
+ await writeFile(
+ configPath,
+ [
+ 'model = "gpt-5-codex"',
+ "[mcp_servers.mem0]",
+ 'url = "https://mcp.example.com/mcp/"',
+ '[projects."/repo"]',
+ 'trust_level = "trusted"',
+ "",
+ ].join("\n"),
+ );
const codexHome = await prepareCodexHome({
appDataPath,
@@ -99,10 +110,32 @@ describe("prepareCodexHome", () => {
const privateConfig = path.join(codexHome, "config.toml");
expect(readFileSync(privateConfig, "utf-8")).toBe(
- 'model = "gpt-5-codex"\n',
+ 'model = "gpt-5-codex"\n[projects."/repo"]\ntrust_level = "trusted"\n',
);
});
+ it.skipIf(process.platform === "win32")(
+ "writes the copied config so only its owner can read it",
+ async () => {
+ const codexConfigDir = path.join(testHome.dir, ".codex");
+ await mkdir(codexConfigDir, { recursive: true });
+ await writeFile(
+ path.join(codexConfigDir, "config.toml"),
+ 'model = "gpt-5-codex"\n',
+ );
+
+ const codexHome = await prepareCodexHome({
+ appDataPath,
+ taskRunId,
+ bundledSkillsDir,
+ log: noopLog,
+ });
+
+ const mode = statSync(path.join(codexHome, "config.toml")).mode & 0o777;
+ expect(mode).toBe(0o600);
+ },
+ );
+
it("rebuilds the skills dir, dropping stale links", async () => {
await createSkill(bundledSkillsDir, "first");
await prepareCodexHome({
@@ -189,3 +222,129 @@ describe("prepareCodexHome", () => {
expect(existsSync(path.join(outside, "precious", "SKILL.md"))).toBe(true);
});
});
+
+describe("stripMcpServers", () => {
+ it.each([
+ {
+ name: "drops a server table and its nested sub-tables",
+ toml: [
+ 'model = "gpt-5"',
+ "[mcp_servers.node_repl]",
+ 'command = "node"',
+ "[mcp_servers.node_repl.env]",
+ 'FOO = "bar"',
+ "[features]",
+ "memories = true",
+ ],
+ expected: ['model = "gpt-5"', "[features]", "memories = true"],
+ },
+ {
+ name: "drops the parent table with dotted keys",
+ toml: [
+ "[mcp_servers]",
+ 'mem0.url = "https://x/mcp"',
+ "[tui]",
+ "theme = 1",
+ ],
+ expected: ["[tui]", "theme = 1"],
+ },
+ {
+ name: "drops top-level inline and dotted keys",
+ toml: [
+ 'mcp_servers = { mem0 = { url = "https://x/mcp" } }',
+ 'mcp_servers.other.command = "x"',
+ 'model = "gpt-5"',
+ ],
+ expected: ['model = "gpt-5"'],
+ },
+ {
+ name: "drops quoted and array-of-table headers",
+ toml: [
+ '[mcp_servers."my.server"]',
+ 'command = "x"',
+ "[[mcp_servers.list]]",
+ 'command = "y"',
+ '[projects."/repo"]',
+ 'trust_level = "trusted"',
+ ],
+ expected: ['[projects."/repo"]', 'trust_level = "trusted"'],
+ },
+ {
+ name: "keeps keys that merely start with the prefix",
+ toml: ['mcp_servers_note = "keep"', "[mcp_servers_extra]", 'k = "v"'],
+ expected: ['mcp_servers_note = "keep"', "[mcp_servers_extra]", 'k = "v"'],
+ },
+ {
+ name: "keeps a dotted key inside another table",
+ toml: ["[tui]", 'mcp_servers.hint = "keep"'],
+ expected: ["[tui]", 'mcp_servers.hint = "keep"'],
+ },
+ {
+ name: "returns a config without mcp_servers unchanged",
+ toml: ['model = "gpt-5"', "[tui]", "theme = 1"],
+ expected: ['model = "gpt-5"', "[tui]", "theme = 1"],
+ },
+ {
+ name: "keeps a multiline string whose content looks like a header",
+ toml: [
+ 'notes = """',
+ "[mcp_servers.example]",
+ "how to add one",
+ '"""',
+ 'model = "gpt-5"',
+ ],
+ expected: [
+ 'notes = """',
+ "[mcp_servers.example]",
+ "how to add one",
+ '"""',
+ 'model = "gpt-5"',
+ ],
+ },
+ {
+ name: "keeps dropping a server table across a wrapped value",
+ toml: [
+ "[mcp_servers.docs]",
+ "args = [",
+ ' ["--flag"],',
+ "]",
+ 'instructions = """',
+ "[tui] is not a header here",
+ '"""',
+ "[tui]",
+ "theme = 1",
+ ],
+ expected: ["[tui]", "theme = 1"],
+ },
+ {
+ name: "drops a top-level key together with its wrapped value",
+ toml: [
+ "mcp_servers.docs.args = [",
+ ' "--flag",',
+ "]",
+ 'mcp_servers.docs.instructions = """',
+ "read me",
+ '"""',
+ 'model = "gpt-5"',
+ ],
+ expected: ['model = "gpt-5"'],
+ },
+ {
+ name: "keeps a bracket inside a quoted value from opening a table",
+ toml: ["[mcp_servers.docs]", 'command = "["', "[tui]", "theme = 1"],
+ expected: ["[tui]", "theme = 1"],
+ },
+ {
+ name: "keeps a quoted triple quote from opening a multiline string",
+ toml: [
+ "marker = \"'''\"",
+ "[mcp_servers.docs]",
+ 'command = "x"',
+ "[tui]",
+ ],
+ expected: ["marker = \"'''\"", "[tui]"],
+ },
+ ])("$name", ({ toml, expected }) => {
+ expect(stripMcpServers(toml.join("\n"))).toBe(expected.join("\n"));
+ });
+});
diff --git a/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts b/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts
index b83698cc1291..beec0f703eba 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts
@@ -47,7 +47,9 @@ export async function cleanupCodexHome(
* CODEX_HOME at this app-private dir we feed our skills through the former while
* the user's own Codex skills still load from the latter (it is keyed off
* `$HOME`, not `$CODEX_HOME`). The user's real `~/.codex/config.toml` is copied
- * in so their Codex configuration still applies without Windows symlink privileges.
+ * in so their Codex configuration still applies without Windows symlink
+ * privileges, minus its `mcp_servers` tables: PostHog sessions only get the MCP
+ * servers PostHog injects per thread (see {@link stripMcpServers}).
*
* Returns the CODEX_HOME path to hand to the spawned process.
*/
@@ -81,7 +83,12 @@ export async function prepareCodexHome(options: {
const userConfig = path.join(os.homedir(), ".codex", "config.toml");
if (fs.existsSync(userConfig)) {
try {
- await fs.promises.copyFile(userConfig, privateConfig);
+ const config = await fs.promises.readFile(userConfig, "utf-8");
+ // The copy can still carry provider headers and environment values, and
+ // it lands in a world-readable directory, so keep it to the owner.
+ await fs.promises.writeFile(privateConfig, stripMcpServers(config), {
+ mode: 0o600,
+ });
} catch (err) {
options.log.warn("Failed to copy codex config into codex home", {
error: err instanceof Error ? err.message : String(err),
@@ -91,3 +98,101 @@ export async function prepareCodexHome(options: {
return codexHome;
}
+
+const MCP_SERVERS_HEADER = /^\[\[?\s*mcp_servers\s*(?:[.\]])/;
+const MCP_SERVERS_KEY = /^mcp_servers\s*[.=]/;
+
+/**
+ * Drops every `mcp_servers` definition from a codex config.toml: `[mcp_servers]`
+ * and `[mcp_servers.<name>...]` tables with their bodies, and top-level
+ * `mcp_servers.<name>... = ...` / `mcp_servers = {...}` keys. Everything else is
+ * returned byte for byte.
+ *
+ * The user's own MCP servers must not run inside PostHog sessions (an
+ * unauthenticated or broken one stalls every thread), and disabling them by
+ * name with `-c mcp_servers.<name>.enabled=false` is worse than useless: a
+ * per-thread `mcp_servers` override discards those flags, and a name without a
+ * matching table in the loaded config yields a transport-less table that codex
+ * rejects at startup.
+ */
+export function stripMcpServers(toml: string): string {
+ const kept: string[] = [];
+ let inMcpTable = false;
+ let inTable = false;
+ let value: OpenValue = { fence: null, depth: 0 };
+ let dropRestOfValue = false;
+
+ for (const line of toml.split("\n")) {
+ // A line only carries structure when no value from an earlier line is still
+ // open. Otherwise it is content, and a `[mcp_servers` there is prose — reading
+ // it as a table header would hand codex a config it cannot parse.
+ const structural = value.fence === null && value.depth === 0;
+ const trimmed = line.trim();
+ if (structural && trimmed.startsWith("[")) {
+ inTable = true;
+ inMcpTable = MCP_SERVERS_HEADER.test(trimmed);
+ }
+ const drop: boolean = structural
+ ? inMcpTable || (!inTable && MCP_SERVERS_KEY.test(trimmed))
+ : inMcpTable || dropRestOfValue;
+
+ value = scanLine(line, value);
+ // A dropped key whose value wraps onto later lines takes the whole value.
+ dropRestOfValue = drop && (value.fence !== null || value.depth > 0);
+ if (!drop) kept.push(line);
+ }
+ return kept.join("\n");
+}
+
+/**
+ * A value left open at a line break: the multiline-string delimiter still to be
+ * closed, and how many `[` or `{` are still unclosed.
+ */
+interface OpenValue {
+ fence: string | null;
+ depth: number;
+}
+
+/** Returns the value left open at the end of `line`, given the one open at its start. */
+function scanLine(line: string, open: OpenValue): OpenValue {
+ let { fence, depth } = open;
+ for (let i = 0; i < line.length; i++) {
+ if (fence !== null) {
+ if (line.startsWith(fence, i)) {
+ fence = null;
+ i += 2;
+ }
+ continue;
+ }
+ if (line.startsWith('"""', i) || line.startsWith("'''", i)) {
+ fence = line.slice(i, i + 3);
+ i += 2;
+ } else if (line[i] === '"' || line[i] === "'") {
+ i = endOfString(line, i);
+ } else if (line[i] === "#") {
+ break; // A comment runs to the end of the line.
+ } else if (line[i] === "[" || line[i] === "{") {
+ depth += 1;
+ } else if (line[i] === "]" || line[i] === "}") {
+ depth = Math.max(0, depth - 1);
+ }
+ }
+ return { fence, depth };
+}
+
+/**
+ * Returns the index of the quote closing the single-line string that opens at
+ * `start`, or the end of the line when it is never closed.
+ */
+function endOfString(line: string, start: number): number {
+ const quote = line[start];
+ for (let i = start + 1; i < line.length; i++) {
+ // Only basic strings take backslash escapes; literal ones are verbatim.
+ if (quote === '"' && line[i] === "\\") {
+ i += 1;
+ continue;
+ }
+ if (line[i] === quote) return i;
+ }
+ return line.length;
+}