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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Use [OpenAI Codex](https://github.com/openai/codex) from [Agent Client Protocol]
- Typed warnings and errors through the opt-in [AIR session failure extension](docs/air-extensions.md#session-failure).
- All AIR extensions, capabilities, and `_meta` keys: [AIR extensions](docs/air-extensions.md).
- A per-turn [agent file-change report](docs/air-extensions.md#agent-file-change-report) after capability negotiation.
- Client-provided MCP servers over command-based stdio config and HTTP transport.
- Client-provided MCP servers over stdio, HTTP, or the existing ACP connection ([MCP-over-ACP](docs/mcp-over-acp.md)).
- Slash commands: `/status`, `/mcp` (with `/mcp reconnect`), `/skills`, `/goal`, `/review`, `/review-branch`, `/review-commit`, `/compact`, and `/logout`, as well as configured skills.

## Installation
Expand Down
39 changes: 39 additions & 0 deletions docs/mcp-over-acp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# MCP-over-ACP

A client can serve MCP tools over its existing ACP connection. Check `agentCapabilities.mcpCapabilities.acp: true`
on ACP v1 or `capabilities.session.mcp.acp: {}` on v2. Register the server on that connection **before**
sending a session setup request: Codex can discover tools before the request returns.

```json
{
"cwd": "/workspace",
"mcpServers": [
{"type": "acp", "name": "project-tools", "serverId": "project-tools:7a72"}
]
}
```

`name` is the server name in Codex. `serverId` is the provider's opaque registration ID; sessions on the same
connection can share it. The same declaration works on new, resume, fork, and v1 load. The usual rules for
[name conflicts, startup failures, and `/mcp` status](mcp-startup-await-timeout.md) apply.

Codex speaks HTTP to the ACP SDK's authenticated loopback bridge. The client does not need an HTTP listener.
Each operation arrives at the client as an `mcp/message` request with the `serverId`, a fresh logical `requestId`,
and the MCP method and parameters. Return `{ "result": ... }` or `{ "error": ... }` for the MCP outcome;
outer ACP errors indicate binding failures. Request-scoped `mcp/message` notifications go back to Codex.
The listener closes with the ACP connection, not with an individual session.

Codex starts with `server/discover`. Include the [discovery result](https://modelcontextprotocol.io/specification/2026-07-28/server/discover)
cache fields: for example, `ttlMs: 0` and `cacheScope: "private"` for an uncached result.
The bridge uses the ACP SDK defaults: 64 concurrent HTTP requests per connection, 1 MiB per request body,
and 1 MiB of buffered stream output for a slow reader.

Only `type: "acp"` servers must support MCP **2026-07-28**; the bridge does not accept legacy `initialize`.
You can use legacy stdio and HTTP servers alongside them. Codex's `mcp_2026_07_28` setting applies to
the whole thread, so Codex may try `server/discover` on ordinary HTTP servers too. A legacy server that
answers `Method not found` can then use `initialize`; an unresponsive discovery request may fail instead.
Threads without a bridged server keep their existing MCP setting. The adapter checks the running
Codex binary's feature list at initialization. If it cannot confirm `mcp_2026_07_28` support
(for example with an older `CODEX_PATH`), it does not advertise the ACP transport.

See the [MCP-over-ACP draft](https://agentclientprotocol.com/rfds/mcp-over-acp.md) for the wire contract.
16 changes: 12 additions & 4 deletions src/AcpAgentRouter.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import * as acp from "@agentclientprotocol/sdk/unstable";
import * as acpV2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
import {McpOverAcpHttpBridge} from "@agentclientprotocol/sdk/experimental/mcp-http";
import {z} from "zod";
import type {CodexAcpServer} from "./CodexAcpServer";
import {type AcpClientConnection, AcpV2Connection} from "./ACPSessionConnection";
import type {McpOverAcpToHttp} from "./McpServerConfig";
import packageJson from "../package.json";
import {AcpResponseDelivery} from "./AcpResponseDelivery";
import {isAbsoluteProtocolPath} from "./PathUtils";
Expand Down Expand Up @@ -63,12 +65,14 @@ const hooksTrustParamsParser = z.object({
hooks: z.array(z.object({key: z.string().min(1), currentHash: z.string().min(1)})).min(1),
});

type CreateAgent = (connection: AcpClientConnection | AcpV2Connection, toHttp: McpOverAcpToHttp) => CodexAcpServer;

/**
* Builds the ACP router. It picks the v1 or v2 handler chain from the first `initialize`
* request, and only the selected chain's `onConnect` runs for the connection.
*/
export function createAcpAgentRouter(
createAgent: (connection: AcpClientConnection | AcpV2Connection) => CodexAcpServer,
createAgent: CreateAgent,
): Pick<acpV2.AgentProtocolRouter, "connect"> {
return {
connect(stream, options) {
Expand All @@ -81,9 +85,11 @@ export function createAcpAgentRouter(
}

function createRouter(
createAgent: (connection: AcpClientConnection | AcpV2Connection) => CodexAcpServer,
createAgent: CreateAgent,
responses: AcpResponseDelivery,
): acpV2.AgentProtocolRouter {
const mcp = new acp.McpOverAcpCaller();
const bridge = new McpOverAcpHttpBridge(mcp);
let codexAcpServer: CodexAcpServer | null = null;
const getAgent = (params?: {sessionId?: unknown}): CodexAcpServer => {
if (!codexAcpServer) {
Expand Down Expand Up @@ -183,7 +189,8 @@ function createRouter(
};

const v1Agent = acp.agent({name: packageJson.name})
.onConnect((connection) => attachAgent(createAgent(connection.client), connection.signal))
.onConnect(({client, signal}) => attachAgent(createAgent(client, server => bridge.toHttp(client, server)), signal))
.onNotification(acp.methods.agent.mcp.message, mcp.handleNotification)
.onRequest(acp.methods.agent.initialize, (ctx) => initialize(ctx.requestId, () => getAgent().initialize(ctx.params)))
.onRequest(acp.methods.agent.session.new, (ctx) => createdSetup(ctx.requestId, () => getAgentForPaths(ctx.params).newSession(ctx.params)))
.onRequest(acp.methods.agent.session.load, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgentForPaths(ctx.params).loadSession(ctx.params), ctx.signal))
Expand Down Expand Up @@ -218,7 +225,8 @@ function createRouter(
.onRequest(SESSION_LIST_UNSUBSCRIBE_METHOD, sessionListSubscriptionParamsParser, (ctx) => getAgent().sessionIndex.unsubscribeList(ctx.params));

const v2Agent = acpV2.agent({name: packageJson.name})
.onConnect((connection) => attachAgent(createAgent(new AcpV2Connection(connection.client)), connection.signal))
.onConnect(({client, signal}) => attachAgent(createAgent(new AcpV2Connection(client), server => bridge.toHttp(client, server)), signal))
.onNotification(acpV2.methods.agent.mcp.message, mcp.handleNotification)
.onRequest(acpV2.methods.agent.initialize, (ctx) => initialize(ctx.requestId, () => getAgent().initializeV2(ctx.params)))
// No `session/load`: v2 folds it into `session/resume` with `replayFrom`.
.onRequest(acpV2.methods.agent.session.new, (ctx) => createdSetup(ctx.requestId, () => getAgentForPaths(ctx.params).newSessionV2(ctx.params)))
Expand Down
57 changes: 43 additions & 14 deletions src/CodexAcpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import {isDeepStrictEqual} from "node:util";
import {logger} from "./Logger";
import {isAccountReadAuthFailureError, isAccountReadUnavailableError} from "./CodexThreadErrors";
import {listedSessionTitle, normalizeSessionTitle} from "./SessionTitle";
import {type AcpMcpServer, type WithAcpMcpServers, normalizeMcpServers, toCodexMcpServerConfig} from "./McpServerConfig";
import {type AcpMcpServer, type McpOverAcpToHttp, type WithAcpMcpServers, normalizeMcpServers, toCodexMcpServerConfig} from "./McpServerConfig";
import type {
AccountUpdatedNotification,
ApprovalsReviewer,
Expand Down Expand Up @@ -92,7 +92,7 @@ import {
narrowToListedModels,
} from "./GatewayModelDiscovery";
import {findSupportedEffort} from "./ModelConfigOption";
import {type ProviderStartupConfig, configOverride, NO_PROVIDER_STARTUP_CONFIG} from "./CodexConfigOverride";
import {type ProviderStartupConfig, configOverride, expandConfigTables, NO_PROVIDER_STARTUP_CONFIG} from "./CodexConfigOverride";
import {disableUnsupportedSkills, withoutUnsupportedSkills} from "./UnsupportedSkills";
export type {SessionMetadata, SessionMetadataWithThread} from "./SessionMetadata";
/** A null turn marks unavailable outcome metadata, not a failed turn. */
Expand Down Expand Up @@ -123,6 +123,7 @@ type ResumedThread = {
export const CUSTOM_GATEWAY_PROVIDER_ID = "custom-gateway";
export const OPENAI_PROVIDER_ID = "openai";
const DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1";
const STATELESS_MCP_FEATURE = "mcp_2026_07_28";

/**
* The url-mode variant of the ACP `elicitation/create` request params.
Expand Down Expand Up @@ -177,9 +178,14 @@ export class CodexAcpClient {
private readonly subagents: CodexSubagentSubscriptions;
private skillExtraRoots: string[] = [];
private configPath: string | null = null;
private verifiedMcpBridge?: McpOverAcpToHttp;


constructor(codexClient: CodexAppServerClient, codexConfig?: JsonObject, modelProvider?: string) {
constructor(
codexClient: CodexAppServerClient,
codexConfig?: JsonObject,
modelProvider?: string,
private readonly mcpOverAcpToHttp?: McpOverAcpToHttp,
) {
this.codexClient = codexClient;
this.config = codexConfig ?? {};
this.modelProvider = modelProvider ?? null;
Expand All @@ -192,12 +198,16 @@ export class CodexAcpClient {
return this.codexClient;
}

get supportsMcpOverAcp(): boolean {
return this.verifiedMcpBridge !== undefined;
}

/**
* A client of the same configuration for another app-server: the same config and model provider. The routing
* that the agent set at runtime (gateway auth, `providers/set`) is copied by {@link adoptRoutingFrom}.
*/
withAppServer(codexClient: CodexAppServerClient): CodexAcpClient {
const client = new CodexAcpClient(codexClient, this.config, this.modelProvider ?? undefined);
const client = new CodexAcpClient(codexClient, this.config, this.modelProvider ?? undefined, this.mcpOverAcpToHttp);
client.adoptRoutingFrom(this);
return client;
}
Expand Down Expand Up @@ -227,6 +237,18 @@ export class CodexAcpClient {
}
});
this.configPath = response?.codexHome ?? null;
// A CODEX_PATH binary may support HTTP but not stateless MCP. Don't offer a bridge it can't use.
if (this.mcpOverAcpToHttp) {
try {
if (await this.codexClient.hasExperimentalFeature(STATELESS_MCP_FEATURE)) {
this.verifiedMcpBridge = this.mcpOverAcpToHttp;
}
} catch (error) {
if (this.codexClient.connectionLoss.lost) throw error;
// Older app-servers need not implement the feature catalog to serve other transports.
logger.log("Could not verify MCP-over-ACP support", {error: String(error)});
}
}
this.isInitialized = true;
}

Expand Down Expand Up @@ -1155,8 +1177,9 @@ export class CodexAcpClient {
apiType: activeProvider.apiType,
baseUrl: activeProvider.baseUrl,
});
const overrides = mcpServers.length ? expandConfigTables(this.config, "mcp_servers", "features") : this.config;
const mergedConfig = {
...disableUnsupportedSkills(forceGitRootTurnDiffPaths(mergeGatewayConfig(this.config, this.gatewayConfig))),
...disableUnsupportedSkills(forceGitRootTurnDiffPaths(mergeGatewayConfig(overrides, this.gatewayConfig))),
projects: Object.fromEntries(sessionRoots.map(root => [root, {
trust_level: "trusted",
}])),
Expand All @@ -1176,11 +1199,13 @@ export class CodexAcpClient {
return {config: configWithWorkspaceRoots, skippedMcpServers: [], ...permissionProfileMetadata};
}

const requestedServers = normalizeMcpServers(mcpServers).map(server => ({name: server.name, server}));
// config/read sees Codex's layers, but not the per-thread overrides from CODEX_CONFIG.
const localServers = overrides["mcp_servers"];
const requestedServers = normalizeMcpServers(mcpServers, this.verifiedMcpBridge);
let serversToConfigure = requestedServers;
if (shouldDeduplicateMcpConflicts()) {
// Prevents Codex from deep-merging incompatible field types, such as url and stdio schemas.
const existingNames = this.getConfigMcpServerNames(effectiveConfig);
const existingNames = this.getConfigMcpServerNames(effectiveConfig, localServers);
serversToConfigure = requestedServers.filter(mcp => !existingNames.has(mcp.name));
}
const skippedMcpServers = requestedServers
Expand All @@ -1196,26 +1221,30 @@ export class CodexAcpClient {
return {config: configWithWorkspaceRoots, skippedMcpServers, ...permissionProfileMetadata};
}

const configs = await Promise.all(serversToConfigure.map(async server =>
[server.name, await toCodexMcpServerConfig(server)] as const));
const features = configWithWorkspaceRoots["features"];
return {
config: {
...configWithWorkspaceRoots,
"mcp_servers": Object.fromEntries(serversToConfigure.map(mcp => [mcp.name, toCodexMcpServerConfig(mcp.server)])),
// Without modern discovery Codex sends `initialize`, which the ACP bridge does not accept.
...(serversToConfigure.some(server => server.type === "acp") && {
features: {...(isJsonObject(features) ? features : {}), [STATELESS_MCP_FEATURE]: true},
}),
mcp_servers: {...(isJsonObject(localServers) ? localServers : {}), ...Object.fromEntries(configs)},
},
skippedMcpServers,
...permissionProfileMetadata,
};
}

private getConfigMcpServerNames(response: ConfigReadResponse): Set<string> {
private getConfigMcpServerNames(response: ConfigReadResponse, localServers: JsonValue | undefined): Set<string> {
const effectiveMcpServers = response?.config?.["mcp_servers"];
const configLayers = response?.layers ?? [];
const layerMcpServers = configLayers.map(layer => {
return isJsonObject(layer.config) ? layer.config["mcp_servers"] : undefined;
});
const configuredMcpServers = [effectiveMcpServers, ...layerMcpServers].filter(isJsonObject);
if (configuredMcpServers.length === 0) {
return new Set();
}
const configuredMcpServers = [localServers, effectiveMcpServers, ...layerMcpServers].filter(isJsonObject);
return new Set(configuredMcpServers.flatMap(server => Object.keys(server)));
}

Expand Down
3 changes: 2 additions & 1 deletion src/CodexAcpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -854,7 +854,7 @@ export class CodexAcpServer {
},
sessionCapabilities,
mcpCapabilities: {
acp: false,
acp: this.codexAcpClient.supportsMcpOverAcp,
http: true,
sse: false
},
Expand Down Expand Up @@ -911,6 +911,7 @@ export class CodexAcpServer {
mcp: {
stdio: {},
http: {},
...(this.codexAcpClient.supportsMcpOverAcp && {acp: {}}),
},
delete: {},
additionalDirectories: {},
Expand Down
14 changes: 14 additions & 0 deletions src/CodexAppServerClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type {
ConfigReadResponse,
ConfigBatchWriteParams,
ConfigWriteResponse,
ExperimentalFeatureListResponse,
GetAccountParams,
GetAccountRateLimitsResponse,
GetAccountResponse,
Expand Down Expand Up @@ -877,6 +878,19 @@ export class CodexAppServerClient {
return await this.sendRequest({ method: "mcpServerStatus/list", params });
}

/** Whether this binary implements a feature, regardless of its default enablement. */
async hasExperimentalFeature(name: string): Promise<boolean> {
let cursor: string | null = null;
do {
const page: ExperimentalFeatureListResponse = await this.sendRequest({
method: "experimentalFeature/list", params: {cursor, limit: 256},
});
if (page.data.some(feature => feature.name === name && feature.stage !== "removed")) return true;
cursor = page.nextCursor ?? null;
} while (cursor !== null);
return false;
}

async mcpServerReload(): Promise<McpServerRefreshResponse> {
return await this.sendRequest({ method: "config/mcpServer/reload", params: undefined });
}
Expand Down
26 changes: 26 additions & 0 deletions src/CodexConfigOverride.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,36 @@
import type {JsonValue} from "./app-server/serde_json/JsonValue";
import type {JsonObject} from "./CodexAcpClient";

/** A Codex `-c key=value` override, the value written as TOML. */
export function configOverride(key: string, value: JsonValue | undefined): string[] {
return ["-c", `${key}=${toToml(value)}`];
}

/**
* Fold dotted overrides into the tables the adapter is about to edit. Codex applies thread overrides
* from an unordered map: sending both `mcp_servers` and `mcp_servers.x.url` could pair a URL with
* the wrong credentials. More specific keys win; do not mutate the config shared by other threads.
*/
export function expandConfigTables(config: JsonObject, ...tables: string[]): JsonObject {
const paths = Object.keys(config).filter(key => tables.some(table => key.startsWith(`${table}.`))).sort();
if (paths.length === 0) return config;
const result = {...config};
for (const path of paths) {
const parts = path.split(".");
const field = parts.pop()!;
let parent = result;
for (const part of parts) {
const existing = parent[part];
// Server and header names are data, including names such as "__proto__".
parent = parent[part] = Object.assign(Object.create(null),
existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {});
}
parent[field] = result[path];
delete result[path];
}
return result;
}

// JSON strings, numbers, booleans, and arrays are already valid TOML; only objects need `key = value` syntax.
function toToml(value: JsonValue | undefined): string {
if (Array.isArray(value)) return `[${value.map(toToml).join(", ")}]`;
Expand Down
6 changes: 5 additions & 1 deletion src/CodexJsonRpcConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,11 @@ export function startCodexConnection(
export function attachLogs(proc: ChildProcessWithoutNullStreams) {
const originalWrite = proc.stdin.write.bind(proc.stdin);
proc.stdin.write = (chunk: any, encoding?: any, callback?: any): boolean => {
if (logger.enabled) logger.log(`[IN] ${chunk.toString()}`);
if (logger.enabled) {
// The writer sends one complete JSON message. Keep MCP endpoint credentials out of its trace.
const line = chunk.toString().replace(/("Authorization"\s*:\s*")Bearer [^"]+"/gi, '$1Bearer [REDACTED]"');
logger.log(`[IN] ${line}`);
}
return originalWrite(chunk, encoding, callback);
};

Expand Down
Loading
Loading