Skip to main content
Glama
codex-mcp-bridge

codex-mcp-bridge

by hampsterx

codex-mcp-bridge

npm version npm downloads CI License: MIT Node.js TypeScript MCP

MCP server that wraps Codex CLI as a subprocess, exposing code execution, web search, and structured output as Model Context Protocol tools.

Works with any MCP client: Claude Code, Gemini CLI, Cursor, Windsurf, VS Code, or any tool that speaks MCP.

Do you need this?

If you're in a terminal agent (Claude Code, Codex CLI, Gemini CLI) with shell access, call Codex CLI directly. It's faster, cheaper, and zero overhead:

# Review current branch vs main
codex review --base main

# Review uncommitted changes
codex review --uncommitted

# Review with custom focus
codex review --base main "Focus on security and error handling"

# From a worktree (run inside the worktree; `-C` is broken for `review`)
cd /path/to/worktree && codex review --base main

# General analysis
codex exec "Analyze src/utils/parse.ts for edge cases"

Use this MCP bridge instead when:

  • Your client has no shell access (Cursor, Windsurf, Claude Desktop, VS Code)

  • You need structured output with JSON Schema validation (Codex CLI's --json has known bugs)

  • You need partial response capture on timeout and automatic model fallback on quota exhaustion

  • You want subprocess isolation: explicit env allowlist, no shell escape, secret redaction on output, FIFO-queued concurrency (max 3 parallel spawns, configurable via CODEX_MAX_CONCURRENT)

  • You need multi-turn conversations via session resume (sessionId / resetSession, inspected via listSessions)

Worktree note: Codex CLI issue #9084 breaks codex -C /path review .... Run codex review from inside the worktree to avoid it.

Related MCP server: gemini-mcp-bridge

Quick Start

npx codex-mcp-bridge

Prerequisites

  • Codex CLI installed (npm i -g @openai/codex)

  • OPENAI_API_KEY environment variable set, or codex auth login completed

Claude Code

claude mcp add codex-bridge -- npx -y codex-mcp-bridge

Gemini CLI

Add to ~/.gemini/settings.json:

{
  "mcpServers": {
    "codex-bridge": {
      "command": "npx",
      "args": ["-y", "codex-mcp-bridge"]
    }
  }
}

Cursor / Windsurf / VS Code

Add to your MCP settings:

{
  "codex-bridge": {
    "command": "npx",
    "args": ["-y", "codex-mcp-bridge"],
    "env": {
      "OPENAI_API_KEY": "sk-..."
    }
  }
}

Tools

Tool

Description

codex

Execute prompts with file context, session resume, and sandbox control. Multi-turn conversations via session IDs. Use for free-form review prompts; see Code review with this CLI.

review

Native diff-aware Codex review via codex exec review --json. No caller prompt; supports uncommitted, base branch, and commit review modes.

search

Web search via codex --search. Returns synthesized answers with source URLs.

query

Lightweight text analysis. No repo context, no sessions. Runs in an isolated temp directory.

structured

JSON Schema validated output via Ajv. Data extraction, classification, or any task needing machine-parseable output.

ping

Health check with CLI version, capabilities, and concurrency diagnostics (activeCount, queueDepth).

mcpStatus

Report what Codex says about each MCP server it knows about: auth type, tool inventory, and whether it initialized. Optional diagnostic mode adds explicit failure states and error text.

listSessions

List active conversation sessions with metadata (turn count, model, timestamps).

codex

General-purpose execution. Supports multi-turn conversations via sessionId, sandbox levels (read-only, workspace-write, full-auto), and reasoning effort control. Pass resetSession: true to discard and start fresh. Use listSessions to inspect active sessions before resuming.

Key parameters: prompt (required), files, model, sessionId, sandbox, reasoningEffort, workingDirectory, timeout (default 60s).

Web search powered by OpenAI's native search infrastructure via Codex CLI's --search flag. Returns synthesized answers with source URLs.

Key parameters: query (required), model, workingDirectory, timeout (default 120s).

query

Lightweight, non-agentic text analysis. Spawns in an isolated temp directory so the bridge's repo context doesn't leak. Pass text to analyze in the context parameter. Supports reasoningEffort and maxResponseLength.

Key parameters: prompt (required), context, model, reasoningEffort, timeout (default 60s).

review

Thin wrapper around Codex CLI's native diff-aware review. The bridge passes the diff selector to codex exec review --json; upstream Codex owns the review prompt. Requires a real git repository via workingDirectory.

Key parameters: mode (required: uncommitted, base, or commit), workingDirectory (required), base (required for base mode), commit (required for commit mode), title, model, timeout (default 180s).

structured

Embeds a JSON Schema in the prompt and validates the response with Ajv. Returns clean JSON on success, validation errors on failure.

Key parameters: prompt (required), schema (required, JSON string), files, model, workingDirectory, timeout (default 60s).

ping

No parameters. Returns CLI version, auth status, model configuration, and concurrency diagnostics (activeCount, queueDepth).

mcpStatus

Reports per-server MCP state as Codex's own app-server protocol sees it. Unlike every other tool, it deliberately does not suppress Codex's MCP servers or harden the subprocess environment, because both would disable the thing being measured. It therefore boots the servers in ~/.codex/config.toml and is slower than a normal call. With diagnostics: true and a workingDirectory inside a trusted project, the thread it starts also boots that project's .codex/config.toml servers.

Key parameters: diagnostics (default false), workingDirectory, timeout (per-request, default 90s).

Mode

Cost

What you get

default

~6-9s

Inventory: auth type, tool names and counts, and initialized / unknown per server. Creates no thread and writes no session record.

diagnostics: true

~10-20s

Adds an explicit failed state and the error text naming the cause (expired OAuth grant, missing binary, remote refusal). Starts an ephemeral thread, which is never materialised on disk.

Reading the output:

  • unknown is not a failure. It means the inventory carried no server info and no explicit verdict was available. Only diagnostics: true can report failed.

  • A degraded warning means don't trust unknown. Slow calls have been observed reporting healthy servers as uninitialized, so the tool reports how long the underlying call took and flags the result when it was slow enough to be suspect.

  • builtIn marks a server Codex injects that is not in your config; configuredButUnreported marks one in your config that Codex never mentioned.

Example:

atlassian            failed       auth=oAuth  tools=0
    error: MCP client for `atlassian` failed to start: MCP startup failed: failed to
    refresh OAuth tokens for server atlassian: ... invalid_grant: Grant not found
codex_apps           initialized  auth=bearerToken  tools=117  (builtIn)
linear               initialized  auth=oAuth  tools=57
serena               initialized  auth=unsupported  tools=22

All tools attach execution metadata (_meta) with durationMs, model, fallbackUsed, and session info where applicable. See DESIGN.md for details.

Code review with this CLI

This bridge does not bundle reviewer prompts. There are three paths for code review:

Native upstream codex review

codex review --base main
codex review --uncommitted
codex review --base main "Focus on security and error handling"

Diff-aware review built into Codex CLI. No bridge involvement. Use this when your client has shell access.

Bridge review tool for native diff-aware review

{
  "tool": "review",
  "arguments": {
    "mode": "base",
    "base": "main",
    "workingDirectory": "/path/to/worktree"
  }
}

The bridge runs codex exec review --json from workingDirectory, captures the final review text, and returns review metadata such as threadId, event counts, and redacted command output. It does not accept a prompt.

Bridge codex tool with caller-supplied prompt

{
  "tool": "codex",
  "arguments": {
    "prompt": "<your review prompt + diff or file references>",
    "sandbox": "read-only"
  }
}

The bridge runs codex exec --sandbox read-only with the supplied prompt and returns stdout. Use this for free-form review prompts or review inputs that are not expressible as uncommitted, base, or commit diff selectors.

Representative review prompt

A starting point; adapt freely:

Review the following diff:

<diff content>

Look for:
- Bugs that would surface in production
- Missing error handling on user-supplied input
- Tests modified to silence failures rather than verify behaviour
- Security issues (injection, missing auth checks, secret leaks)

For each finding cite file:line, severity (high/medium/low), and a suggested fix.
Skip style/formatting; assume an autoformatter handles those.

The bridge has no opinion on prompt content. See ADR-001 for the rationale.

Configuration

Variable

Default

Description

CODEX_DEFAULT_MODEL

(CLI default)

Default model for all tools

CODEX_FALLBACK_MODEL

o3

Fallback on quota exhaustion (none to disable)

CODEX_CLI_PATH

codex

Path to CLI binary

CODEX_MAX_CONCURRENT

3

Max concurrent subprocess spawns

CODEX_MCP_SERVERS

(unset)

Control which Codex internal MCP servers stay enabled. See DESIGN.md.

CODEX_HOME

~/.codex

Root subprocesses authenticate from

Running the bridge against a second Codex account

CODEX_HOME is a complete identity switch: auth, config.toml, skills and thread history all live under the root, so a second root is a second install. Every tool call this bridge makes is machine traffic rather than a session someone is sitting in front of, which makes it a good candidate for a work or team seat while interactive codex keeps a personal one.

Set it in the server registration rather than the ambient shell, so the choice does not depend on which terminal launched the client:

{
  "mcpServers": {
    "codex": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "codex-mcp-bridge"],
      "env": {
        "CODEX_HOME": "/home/you/.codex-work",
        "CODEX_DEFAULT_MODEL": "gpt-5.6-sol"
      }
    }
  }
}

Three things to know before you do:

  • Log in as that root first, since a root is only as usable as its credentials: CODEX_HOME=/home/you/.codex-work codex login (or codex login --with-api-key). Check it with CODEX_HOME=/home/you/.codex-work codex login status.

  • A JSON env block has no conditional. If that root loses its login, every subprocess the bridge spawns targets it anyway, with no fallback to the default root the way a shell wrapper could offer one.

  • Set CODEX_DEFAULT_MODEL alongside it. The bridge resolves config.toml from CODEX_HOME, so a freshly created root has none and the model drops to the CLI default. That absence also makes most of CODEX_MCP_SERVERS inert: with nothing configured there is nothing to disable, nothing to inherit and no name to enable, which is what the default setting wants anyway. The one mode it does not disarm is a raw TOML override (a value starting { or [), which is passed straight through as -c mcp_servers=... and never reads config.toml.

Choosing a Codex MCP server

You need...

Consider

Structured output, model fallback, concurrency management, session resume

This bridge

Session threading with conversationId, callback URI forwarding

@tuannvm/codex-mcp-server

Structured patch output with approval policies

cexll/codex-mcp-server

Minimal codex exec wrapper with parallel subagents

codex-as-mcp

Native Codex MCP (experimental, no wrapper needed)

codex mcp serve (docs)

Performance

Codex CLI has minimal startup overhead (<100ms), so wall time is dominated by model inference.

Scenario

Typical time

Trivial prompt

9-12s

Web search

~17s

Default timeouts (60-300s) are comfortable for typical workloads.

Bridge family

Two MCP servers, same architecture, different underlying CLIs. Each wraps a terminal agent as a subprocess and exposes it as MCP tools. Pick the one that matches your model provider, or run both for cross-model workflows.

codex-mcp-bridge

claude-mcp-bridge

CLI

Codex CLI

Claude Code

Provider

OpenAI

Anthropic

Tools

codex, review, search, query, structured, ping, listSessions

query, review, search, structured, ping, listSessions

Code review

review tool wrapping native codex exec review --json, or codex tool with caller-supplied prompt

review tool with caller-supplied prompt and hardened isolation defaults

Structured output

Ajv validation

Native --json-schema

Session resume

Session IDs with multi-turn

Native --resume

Budget caps

Not supported

Native --max-budget-usd

Effort control

reasoningEffort (low/medium/high)

--effort low/medium/high/max

Cold start

<100ms (inference dominates)

~1-2s

Auth

OPENAI_API_KEY

claude login (subscription) or ANTHROPIC_API_KEY

Cost

Pay-per-token

Subscription (included) or API credits

Concurrency

3 (configurable)

3 (configurable)

Model fallback

Auto-retry with fallback model

Auto-retry with fallback model

Both share: subprocess env isolation, path sandboxing, output redaction (secret stripping), FIFO concurrency queue, MCP tool annotations, _meta response metadata, progress heartbeats.

Development

npm install
npm run build        # Compile TypeScript
npm run dev          # Watch mode
npm test             # Run tests
npm run lint         # ESLint
npm run typecheck    # tsc --noEmit

Further reading

  • DESIGN.md - Architecture, MCP server control grammar, sessions, output parsing, response metadata

  • SECURITY.md - Environment isolation, path sandboxing, output redaction, resource limits

  • CHANGELOG.md - Release history

License

MIT

Available Tools

8 tools
codexCodex CLIA
Destructive

Execute a prompt via Codex CLI. Codex is an AI coding agent that can generate, analyze, refactor, and explain code with full project context (reads AGENTS.md/CODEX.md automatically).

Capabilities: code generation and refactoring, code analysis and explanation, file reading and modification (when sandbox allows), git operations and terminal commands, multi-turn conversations via sessionId.

When to use a different tool:

  • For analysis of text you already have (plans, docs, opinions), inline it directly in the prompt rather than passing file paths. The files parameter triggers full file I/O and increases timeout pressure.

Tips:

  • Set workingDirectory to the target repo for project-aware responses.

  • Use sandbox "read-only" (default) for analysis, "full-auto" for code changes.

  • Break complex tasks into focused prompts rather than one large request.

  • Resume multi-turn conversations with sessionId (returned in previous response metadata).

  • Include relevant files via the files parameter for targeted context (text and images supported).

  • Set reasoningEffort to control depth: "none" for trivial, "minimal" for lightweight, "low"/"medium" for routine, "high"/"xhigh" for deep analysis.

Inputs: prompt (required), files, model, sandbox, +6 more.

listSessionsList SessionsA
Read-onlyIdempotent

List active Codex conversation sessions. Returns session metadata for orchestration (no prompts or responses, just IDs and timing). Use to check available sessions before resuming with the codex tool's sessionId parameter.

Inputs: no named parameters.

mcpStatusMCP Server StatusA
Read-only

Report what Codex's own app-server says about each MCP server it knows about: auth type, tool inventory, and whether the server initialized.

Unlike the other tools, this one deliberately does NOT suppress Codex's MCP servers — suppressing them would disable the thing being measured — so it is slower than a normal call and boots the servers named in ~/.codex/config.toml.

Two modes:

  • Default (~6-9s): inventory only. Reports each server as "initialized" or "unknown". Creates no thread and writes no session record.

  • diagnostics: true (~10-20s): starts an ephemeral thread to collect startup notifications, which are the only source of an explicit "failed" state and the error text naming the cause (expired OAuth grant, missing binary, remote refusal).

Reading the output:

  • "unknown" is not a failure. It means the inventory carried no server info and no explicit verdict was available. Only diagnostics mode can report "failed".

  • A "degraded" warning means the underlying call was slow enough that healthy servers have been observed reporting as uninitialized. Treat "unknown" as unproven when it appears.

  • Servers marked "builtIn" are injected by Codex and are not in your config.toml. Servers marked "configuredButUnreported" are in your config.toml but absent from Codex's inventory.

Inputs: timeout, diagnostics, workingDirectory.

pingHealth CheckA
Read-onlyIdempotent

Health check: verifies Codex CLI is installed and authenticated, reports versions and capabilities.

Inputs: no named parameters.

queryQuick QueryA
Read-only

Lightweight query for analysis or opinions on text you already have. No file reading, no repo exploration, no session state. Pass text in the context parameter. For code execution or file operations, use the codex tool instead.

Use cases: reviewing a plan, critiquing a draft, comparing approaches, answering questions about provided text, generating summaries.

Tips:

  • Pass the text to analyze in the context parameter, not as file paths.

  • Set reasoningEffort to control depth: "none" for trivial, "minimal" for lightweight, "low"/"medium" for routine, "high"/"xhigh" for thorough analysis.

  • Use maxResponseLength to control verbosity.

Inputs: prompt (required), model, context, timeout, +2 more.

reviewNative Code ReviewA
Destructive

Run Codex CLI's native diff-aware review via codex exec review --json. The bridge does not accept or bundle a review prompt; upstream Codex owns the reviewer instructions.

Use for MCP clients that cannot run shell commands but need native Codex review of uncommitted changes, a base branch diff, or a single commit.

Tips:

  • Set workingDirectory to the target git repository.

  • Choose mode "uncommitted", "base", or "commit".

  • Use the codex tool with sandbox "read-only" for free-form review prompts.

Inputs: mode (required), workingDirectory (required), base, model, +3 more.

structuredStructured OutputA
Read-only

Generate a JSON response conforming to a provided JSON Schema. Use for data extraction, classification, or any task needing machine-parseable output.

Inputs: prompt (required), schema (required), files, model, +2 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.1/5.0

    Scored across 8 tools

    Disambiguation4/5

    Each tool has a distinct purpose, though codex/query and ping/mcpStatus have some overlap. Descriptions draw clear boundaries, but an agent could still confuse the general-purpose codex tool with its specialized variants like query or review.

    Naming Consistency2/5

    Naming follows no consistent pattern: listSessions and mcpStatus use camelCase, while the rest are single lowercase verbs or nouns (codex, search, query, ping, review, structured). Some are verbs, some nouns, and one is an adjective, making the set feel inconsistent.

    Tool Count5/5

    8 tools is appropriate for the bridge's scope, covering core execution plus specialized helpers without bloat. It sits comfortably within the typical 3-15 range and each tool earns its place.

    Completeness4/5

    The server covers core prompt execution, lightweight text analysis, web search, structured output, native review, session listing, and health/status checks. Minor gaps like session deletion or explicit file operations remain, but codex's own capabilities fill those holes.

    Maintenance

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Wraps OpenAI Codex CLI as an MCP server, exposing 8 Codex tools (exec, review, skill list, skill run, status, poll, list jobs, kill) as named tools for use with pi or codex.
      1,488 npm
      ISC
    • F
      license
      A
      quality
      D
      maintenance
      An MCP server that brings Parallel web search and URL extraction to Codex and other Model Context Protocol clients.
      2
      43 npm
      -