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): sanitize MCP server names for codex sessions (#84531)

Chris Volzer64f7fc1c24e4
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/mcp-config.test.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/mcp-config.test.ts
index 01c1196e2023..dd3d98036d3f 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/mcp-config.test.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/mcp-config.test.ts
@@ -1,6 +1,6 @@
import type { McpServer } from "@agentclientprotocol/sdk";
import { describe, expect, it } from "vitest";
-import { toCodexMcpServers } from "./mcp-config";
+import { codexKeyMatchesMcpServerName, toCodexMcpServers } from "./mcp-config";
describe("toCodexMcpServers", () => {
it("returns undefined for empty input", () => {
@@ -81,6 +81,49 @@ describe("toCodexMcpServers", () => {
});
});
+ // Codex rejects server names outside ^[a-zA-Z0-9_-]+$ and silently never
+ // starts the server, so MCP Store display names must be sanitized here.
+ it.each([
+ ["Google Calendar", "Google_Calendar"],
+ ["Linear (Jane Doe)", "Linear__Jane_Doe_"],
+ ])("sanitizes %j into a codex-valid server key", (name, expected) => {
+ const servers = [
+ { type: "http", name, url: "https://mcp.example/mcp" },
+ ] as unknown as McpServer[];
+
+ expect(toCodexMcpServers(servers)).toEqual({
+ [expected]: { url: "https://mcp.example/mcp" },
+ });
+ });
+
+ it("suffixes colliding sanitized names instead of dropping a server", () => {
+ const servers = [
+ { type: "http", name: "Notion (A)", url: "https://a.example/mcp" },
+ { type: "http", name: "Notion [A]", url: "https://b.example/mcp" },
+ ] as unknown as McpServer[];
+
+ expect(toCodexMcpServers(servers)).toEqual({
+ Notion__A_: { url: "https://a.example/mcp" },
+ Notion__A__2: { url: "https://b.example/mcp" },
+ });
+ });
+
+ // Consumers match codex-reported keys against raw names without seeing the
+ // assignment order, so the matcher must cover the suffixed collision form;
+ // missing it lets a relayed tool bypass its always-ask gate.
+ it.each([
+ ["My Slack", "My Slack", true],
+ ["My_Slack", "My Slack", true],
+ ["My_Slack_2", "My Slack", true],
+ ["My_Slack_10", "My Slack", true],
+ ["My_Slack2", "My Slack", false],
+ ["My_Slack_x", "My Slack", false],
+ ["My_Slack_", "My Slack", false],
+ ["Other_Server", "My Slack", false],
+ ])("codexKeyMatchesMcpServerName(%j, %j) is %s", (key, name, expected) => {
+ expect(codexKeyMatchesMcpServerName(key, name)).toBe(expected);
+ });
+
it("leaves PostHog exec unchanged when gating is not enabled", () => {
const servers = [
{
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/mcp-config.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/mcp-config.ts
index 36465825a2a7..9905bdd451ee 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/mcp-config.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/mcp-config.ts
@@ -1,5 +1,6 @@
import type { McpServer } from "@agentclientprotocol/sdk";
import { isPostHogExecDescriptor } from "../../posthog-exec-permission";
+import { sanitizeMcpServerName } from "../claude/mcp/tool-metadata";
interface CodexMcpServerToolConfig {
approval_mode: "prompt";
@@ -24,10 +25,56 @@ export type CodexMcpServerConfig =
http_headers?: Record<string, string>;
});
+/**
+ * Codex requires `mcp_servers` keys to match `^[a-zA-Z0-9_-]+$` and fails the
+ * offending server's startup otherwise (silently: the thread starts, the
+ * server's tools just never appear), so display names like "Google Calendar"
+ * or "Linear (Jane Doe)" from the MCP Store must be sanitized before keying
+ * the map. Reuses the Claude adapter's sanitizer so an installation produces
+ * the same `mcp__<server>__<tool>` keys under both adapters. A collision after
+ * sanitization gets a numeric suffix, because a plain map write would silently
+ * drop one of the colliding servers.
+ */
+export function codexMcpServerName(name: string): string {
+ return sanitizeMcpServerName(name) || "mcp-server";
+}
+
+function uniqueCodexMcpServerName(name: string, taken: Set<string>): string {
+ const base = codexMcpServerName(name);
+ let key = base;
+ for (let i = 2; taken.has(key); i++) {
+ key = `${base}_${i}`;
+ }
+ taken.add(key);
+ return key;
+}
+
+/**
+ * Whether a codex-reported server key can belong to the server named `name`.
+ * {@link toCodexMcpServers} registers `codexMcpServerName(name)` or, after a
+ * collision, that base plus `_<n>`, and the assignment depends on the order
+ * and content of the whole server list, which consumers of codex-reported
+ * keys (the relay always-ask gate) do not see. Accepting every form the
+ * assignment can produce keeps those consumers fail-closed: a false positive
+ * (two raw names that share a sanitized base) asks for approval, never
+ * skips it.
+ */
+export function codexKeyMatchesMcpServerName(
+ key: string,
+ name: string,
+): boolean {
+ if (key === name) return true;
+ const base = codexMcpServerName(name);
+ if (key === base) return true;
+ return key.startsWith(`${base}_`) && /^\d+$/.test(key.slice(base.length + 1));
+}
+
/**
* Translates the ACP `McpServer[]` into the shape Codex's app-server expects under
* `config.mcp_servers` — ACP encodes env/headers as `{ name, value }[]`, Codex
- * wants plain string maps. Returns undefined when there's nothing to inject.
+ * wants plain string maps, and keys must satisfy codex's server-name pattern
+ * (see {@link codexMcpServerName}). Returns undefined when there's nothing to
+ * inject.
*/
export function toCodexMcpServers(
servers: McpServer[] | undefined,
@@ -38,6 +85,7 @@ export function toCodexMcpServers(
}
const out: Record<string, CodexMcpServerConfig> = {};
+ const taken = new Set<string>();
for (const server of servers) {
// `approval_mode: "prompt"` makes codex ask before every exec call; the
// per-sub-tool regex filtering happens in the adapter's approval handlers,
@@ -49,7 +97,7 @@ export function toCodexMcpServers(
: {};
if ("command" in server && server.command) {
const env = pairsToRecord(server.env);
- out[server.name] = {
+ out[uniqueCodexMcpServerName(server.name, taken)] = {
command: server.command,
args: server.args ?? [],
...(env ? { env } : {}),
@@ -57,7 +105,7 @@ export function toCodexMcpServers(
};
} else if ("url" in server && server.url) {
const headers = pairsToRecord(server.headers);
- out[server.name] = {
+ out[uniqueCodexMcpServerName(server.name, taken)] = {
url: server.url,
...(headers ? { http_headers: headers } : {}),
...policy,
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index 59a03ca175c9..675273bb27a4 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -1699,6 +1699,30 @@ describe("AgentServer HTTP Mode", () => {
expect(relaySpy).toHaveBeenCalledOnce();
});
+ // Codex registers servers under sanitized keys (its name pattern rejects
+ // e.g. spaces) and suffixes collisions, so the always-ask gate must match
+ // both forms; missing the suffixed one auto-runs a relayed local tool.
+ it.each([["My_Slack"], ["My_Slack_2"]])(
+ "relays a codex tool call for a relayed server reported as %j",
+ async (reportedKey) => {
+ const testServer = exposeCloudClient(createServer());
+ testServer.config.relayMcpServers = ["My Slack"];
+ testServer.session = { hasDesktopConnected: true };
+ const relaySpy = vi
+ .spyOn(testServer, "relayPermissionToClient")
+ .mockResolvedValue({
+ outcome: { outcome: "selected", optionId: "allow_once" },
+ });
+
+ const { requestPermission } = testServer.createCloudClient(basePayload);
+ await requestPermission(
+ codexPermissionRequestFor(reportedKey, "send_message"),
+ );
+
+ expect(relaySpy).toHaveBeenCalledOnce();
+ },
+ );
+
it("denies a relayed-server tool call instead of auto-approving when no client is reachable", async () => {
const testServer = exposeCloudClient(createServer());
testServer.config.relayMcpServers = ["slack"];
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index b4fad19029e5..babfb0004155 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -49,6 +49,7 @@ import {
hydrateSessionJsonl,
} from "../adapters/claude/session/jsonl-hydration";
import type { GatewayEnv } from "../adapters/claude/session/options";
+import { codexKeyMatchesMcpServerName } from "../adapters/codex-app-server/mcp-config";
import { hasCodexThreadState } from "../adapters/codex-app-server/thread-state";
import {
type AgentErrorClassification,
@@ -4428,9 +4429,16 @@ ${commonInstructions}
// relayed tool auto-run in non-asking modes.
const mcpServerName =
this.readPermissionMcpDescriptor(params)?.server;
+ // Codex reports the key the adapter registered the server under:
+ // the raw name sanitized, plus a numeric suffix when another
+ // server's name sanitized to the same base. The matcher accepts
+ // every form the assignment can produce, because missing any of
+ // them loses the relayed server's always-ask guarantee.
if (
mcpServerName &&
- (this.config.relayMcpServers ?? []).includes(mcpServerName)
+ (this.config.relayMcpServers ?? []).some((name) =>
+ codexKeyMatchesMcpServerName(mcpServerName, name),
+ )
) {
if (mode !== "background" && this.hasReachableClient()) {
return this.relayPermissionToClient(params);
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.test.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.test.ts
index e03f5e1f9365..396d36c333ed 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.test.ts
@@ -1,4 +1,9 @@
-// @ts-expect-error jsdom ships no bundled types; only the test harness needs it
+// jsdom ships no types and this workspace does not install @types/jsdom, but
+// the posthog repo root does, and local runs pick it up through node_modules
+// traversal. The import is untyped only in workspace-only installs (CI), so an
+// expect-error directive would be "unused" locally; only a ts-ignore fits both.
+// biome-ignore lint/suspicious/noTsIgnore: the auto-fix (an expect-error directive) breaks repo-root installs (see above)
+// @ts-ignore
import { JSDOM } from "jsdom";
import { describe, expect, it, vi } from "vitest";
import { injectArtifactHtmlCommentBridge } from "./artifactHtmlCommentBridge";
@@ -248,7 +253,7 @@ describe("artifactHtmlCommentBridge", () => {
channel: CHANNEL,
type: "selection-dismissed",
},
- source: dom.window,
+ source: dom.window as unknown as MessageEventSource,
}),
);
top = 10;
@@ -268,7 +273,7 @@ describe("artifactHtmlCommentBridge", () => {
dom.window.dispatchEvent(
new dom.window.MessageEvent("message", {
data: { marker: BRIDGE_MARKER, channel: CHANNEL, ...data },
- source: dom.window,
+ source: dom.window as unknown as MessageEventSource,
}),
);
@@ -329,7 +334,7 @@ describe("artifactHtmlCommentBridge", () => {
type: "theme",
theme,
},
- source: dom.window,
+ source: dom.window as unknown as MessageEventSource,
}),
);
};