Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 23 additions & 5 deletions src/CodexAcpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ export class CodexAcpClient {
approvalPolicy: null,
sandbox: null,
baseInstructions: null,
config: this.createSessionConfig(request.cwd, request.mcpServers ?? []),
config: await this.createSessionConfig(request.cwd, request.mcpServers ?? []),
cwd: request.cwd,
developerInstructions: null,
model: null,
Expand All @@ -228,7 +228,7 @@ export class CodexAcpClient {
approvalPolicy: null,
sandbox: null,
baseInstructions: null,
config: this.createSessionConfig(request.cwd, request.mcpServers ?? []),
config: await this.createSessionConfig(request.cwd, request.mcpServers ?? []),
cwd: request.cwd,
developerInstructions: null,
model: null,
Expand All @@ -250,7 +250,7 @@ export class CodexAcpClient {
await this.refreshSkills(request.cwd, request._meta);

const response = await this.codexClient.threadStart({
config: this.createSessionConfig(request.cwd, request.mcpServers),
config: await this.createSessionConfig(request.cwd, request.mcpServers),
modelProvider: this.getModelProvider(),
model: null,
cwd: request.cwd,
Expand Down Expand Up @@ -282,7 +282,7 @@ export class CodexAcpClient {
return this.codexClient.getMcpServerStartupVersion();
}

private createSessionConfig(projectPath: string, mcpServers: Array<McpServer>): JsonObject {
private async createSessionConfig(projectPath: string, mcpServers: Array<McpServer>): Promise<JsonObject> {
const mergedConfig = {
...mergeGatewayConfig(this.config, this.gatewayConfig),
projects: {
Expand All @@ -294,10 +294,28 @@ export class CodexAcpClient {
if (mcpServers.length === 0) {
return mergedConfig;
}

// Deduplicates new servers against existing config to prevent Codex from deep-merging
// incompatible field types (e.g., mixing url and stdio schemas).
const existingNames = await this.getConfigMcpServerNames(projectPath);
const uniqueServers = mcpServers.filter(mcp => !existingNames.has(mcp.name));
if (uniqueServers.length === 0) {
return mergedConfig;
}

return {
...mergedConfig,
"mcp_servers": Object.fromEntries(mcpServers.map(mcp => [mcp.name, this.createMcpSeverConfig(mcp)]))
"mcp_servers": Object.fromEntries(uniqueServers.map(mcp => [mcp.name, this.createMcpSeverConfig(mcp)])),
};
}

private async getConfigMcpServerNames(projectPath: string): Promise<Set<string>> {
const response = await this.codexClient.configRead({ includeLayers: true, cwd: projectPath });
const mcpServers = response?.config?.["mcp_servers"];
if (!mcpServers || typeof mcpServers !== "object" || Array.isArray(mcpServers)) {
return new Set();
}
return new Set(Object.keys(mcpServers));
}

getModelProvider(): string | null {
Expand Down
69 changes: 69 additions & 0 deletions src/__tests__/CodexACPAgent/mcp-config-merge.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// noinspection ES6RedundantAwait

import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import path from "node:path";
import fs from "node:fs";
import os from "node:os";
import type {McpServerStdio} from "@agentclientprotocol/sdk";
import {startCodexConnection} from "../../CodexJsonRpcConnection";
import {createBaseTestFixture, removeDirectoryWithRetry, type TestFixture} from "../acp-test-utils";

describe('MCP config merge across global config and ACP request', { timeout: 40_000 }, () => {

let codexHome: string;
let fixture: TestFixture;

beforeEach(() => {
vi.clearAllMocks();

const configToml = `
[mcp_servers.shared-mcp]
url = "https://example.com/mcp"
`;
codexHome = fs.mkdtempSync(path.join(os.tmpdir(), "codex-acp-mcp-merge-"));
fs.writeFileSync(path.join(codexHome, "config.toml"), configToml, "utf8");

const codexConnection = startCodexConnection(undefined, {
...process.env,
CODEX_HOME: codexHome,
});

fixture = createBaseTestFixture({
connection: codexConnection.connection,
getExitCode: () => codexConnection.process.exitCode,
});
});

afterEach(() => {
removeDirectoryWithRetry(codexHome);
});

it('should preserve the global url-based MCP when ACP passes a command-type MCP with the same name', async () => {
const codexAcpAgent = fixture.getCodexAcpAgent();
await codexAcpAgent.initialize({protocolVersion: 1});

fixture.getCodexAcpClient().authRequired = vi.fn().mockResolvedValue(false);

const conflictingMcp: McpServerStdio = {
name: "shared-mcp",
command: "./node_modules/.bin/mcp-hello-world",
args: ["example"],
env: [{name: "example", value: "example"}],
};

const newSessionResponse = await codexAcpAgent.newSession({
cwd: "",
mcpServers: [conflictingMcp],
});
fixture.clearAcpConnectionDump();

await codexAcpAgent.prompt({
sessionId: newSessionResponse.sessionId,
prompt: [{type: "text", text: "/mcp"}],
});

const transportDump = fixture.getAcpConnectionDump([]);
expect(transportDump).contain("Configured MCP servers:");
expect(transportDump).contain("- shared-mcp");
});
});
Loading