Codex Mcp Bridge

io.github.hampsterx由 GitHub 帳號 hampsterx 發布v0.9.1更新於 Oct 24, 2026

Wraps Codex CLI as MCP tools: codex, review, query, search, structured, ping, listSessions.

概覽

AI 產生的概覽

把 Codex CLI 包裝成 MCP 工具,讓助理能執行 Codex 提示、程式碼審查、網頁搜尋,以及符合 JSON Schema 的結構化輸出。

可以做什麼
將 Codex CLI 以子程序方式啟動並公開為工具:codex 用於帶檔案脈絡、工作階段續用、沙箱層級與推理強度設定的通用提示;review 用於對未提交變更、基準分支或某次提交進行原生差異感知審查;search 用於回傳來源網址的網頁搜尋;query 用於在隔離的暫存目錄中做輕量文字分析;structured 用於經 JSON Schema 驗證的輸出;另有 ping、mcpStatus 與 listSessions 診斷工具。回應會附上執行中繼資料,例如耗時、模型與是否使用備援模型。
適用情境
當你的 MCP 用戶端沒有 shell 存取權(Cursor、Windsurf、Claude Desktop、VS Code),但仍想借助 Codex 做分析與審查時適用;也適合需要結構描述驗證輸出、逾時部分擷取、配額用盡時自動切換備援模型,或多輪工作階段的場景。若用戶端本身就有 shell,直接呼叫 Codex CLI 更快也更省。
執行需求
需要本機 Node.js 執行環境(npx codex-mcp-bridge),並安裝 Codex CLI(例如透過 npm)。需要 OpenAI 憑證:環境變數 OPENAI_API_KEY,或已完成 codex auth login。選用環境變數:CODEX_CLI_PATH、CODEX_DEFAULT_MODEL、CODEX_FALLBACK_MODEL、CODEX_MAX_CONCURRENT、CODEX_MCP_SERVERS。僅支援桌面端;模型呼叫與網頁搜尋需要網路連線。
安裝前請注意
codex 工具支援包含 workspace-write 與 full-auto 在內的沙箱層級,會讓底層代理修改檔案;除非確實要寫入,否則建議使用 read-only。它會以你的 OpenAI 憑證執行 Codex 子程序,因此提示內容與檔案脈絡會傳送給 OpenAI。mcpStatus 工具刻意不抑制 Codex 已設定的 MCP 伺服器,也不強化子程序環境,因此會啟動 ~/.codex/config.toml 中的伺服器。採依 token 計費。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Codex Mcp Bridge,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

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:

bash
# Review current branch vs maincodex review --base main
# Review uncommitted changescodex review --uncommitted
# Review with custom focuscodex 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 analysiscodex 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.

Quick Start

bash
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

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

Gemini CLI

Add to ~/.gemini/settings.json:

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

Cursor / Windsurf / VS Code

Add to your MCP settings:

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

Tools

ToolDescription
codexExecute 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.
reviewNative diff-aware Codex review via codex exec review --json. No caller prompt; supports uncommitted, base branch, and commit review modes.
searchWeb search via codex --search. Returns synthesized answers with source URLs.
queryLightweight text analysis. No repo context, no sessions. Runs in an isolated temp directory.
structuredJSON Schema validated output via Ajv. Data extraction, classification, or any task needing machine-parseable output.
pingHealth check with CLI version, capabilities, and concurrency diagnostics (activeCount, queueDepth).
mcpStatusReport 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.
listSessionsList 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).

search

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).

ModeCostWhat you get
default~6-9sInventory: auth type, tool names and counts, and initialized / unknown per server. Creates no thread and writes no session record.
diagnostics: true~10-20sAdds 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:

text
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 foundcodex_apps           initialized  auth=bearerToken  tools=117  (builtIn)linear               initialized  auth=oAuth  tools=57serena               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

bash
codex review --base maincodex review --uncommittedcodex 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

jsonc
{  "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

jsonc
{  "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:

text
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

VariableDefaultDescription
CODEX_DEFAULT_MODEL(CLI default)Default model for all tools
CODEX_FALLBACK_MODELo3Fallback on quota exhaustion (none to disable)
CODEX_CLI_PATHcodexPath to CLI binary
CODEX_MAX_CONCURRENT3Max concurrent subprocess spawns
CODEX_MCP_SERVERS(unset)Control which Codex internal MCP servers stay enabled. See DESIGN.md.
CODEX_HOME~/.codexRoot 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:

jsonc
{  "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 resumeThis bridge
Session threading with conversationId, callback URI forwarding@tuannvm/codex-mcp-server
Structured patch output with approval policiescexll/codex-mcp-server
Minimal codex exec wrapper with parallel subagentscodex-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.

ScenarioTypical time
Trivial prompt9-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-bridgeclaude-mcp-bridge
CLICodex CLIClaude Code
ProviderOpenAIAnthropic
Toolscodex, review, search, query, structured, ping, listSessionsquery, review, search, structured, ping, listSessions
Code reviewreview tool wrapping native codex exec review --json, or codex tool with caller-supplied promptreview tool with caller-supplied prompt and hardened isolation defaults
Structured outputAjv validationNative --json-schema
Session resumeSession IDs with multi-turnNative --resume
Budget capsNot supportedNative --max-budget-usd
Effort controlreasoningEffort (low/medium/high)--effort low/medium/high/max
Cold start<100ms (inference dominates)~1-2s
AuthOPENAI_API_KEYclaude login (subscription) or ANTHROPIC_API_KEY
CostPay-per-tokenSubscription (included) or API credits
Concurrency3 (configurable)3 (configurable)
Model fallbackAuto-retry with fallback modelAuto-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

bash
npm installnpm run build        # Compile TypeScriptnpm run dev          # Watch modenpm test             # Run testsnpm run lint         # ESLintnpm 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

來源:README.md,提交 bb14fad

工具

0
SourceWeft 尚未在沙箱中啟動過該軟體包,因此其工具未知。

版本歷史

1
  1. v0.9.1最新Sep 16, 2026

評分

已滿足適用檢查項的 50%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分

    請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。

  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分