Codex MCP Server
This MCP server connects Claude, Cursor, and other AI assistants to Codex CLI. It enables code analysis via @ file references, multi-turn conversations, sandboxed edits, structured change mode, native code review, and image generation through your ChatGPT login.
The server does not call the OpenAI API itself: it spawns codex exec (or codex review for reviews) as a child process, builds the command line for you, and parses the output back into MCP responses. Anything Codex CLI can reach — your ChatGPT plan, ~/.codex/config.toml, skills, local OSS models — is what the server can reach.
Features
- File Analysis — reference files with
@src/,@package.jsonsyntax - Multi-Turn Sessions — conversation continuity backed by native Codex threads
- Native Resume — uses
codex exec resumefor context preservation - Code Review —
review-changesruns Codex’s native non-interactive review on your git diff - Image Generation —
image-genrelays Codex’s built-inimage_gen; noOPENAI_API_KEYneeded - Local OSS Models — run with Ollama or LM Studio via
localProvider - Web Search — research capabilities with
search: true - Sandbox Mode — safe automation with explicit sandbox and approval policies
- Change Mode — structured OLD/NEW patch output for refactoring, paginated with
fetch-chunk - Brainstorming — divergent, convergent, SCAMPER, design thinking, and lateral thinking frameworks
- Image Inputs and Structured Output — attach images to
ask-codexwithimage, constrain the final answer with a JSON Schema viaoutputSchema - Skills —
list-skillsshows skills from.agents/skills/<name>/SKILL.md; invoke one in a prompt as$skill-name - Large Prompts — prompts over ~100 KB are sent over stdin instead of argv, so nothing is truncated
- Health Diagnostics — CLI version, resolved executable path, and session monitoring
- MCP Extras —
health,version,list-sessions,list-skills,batch-codex,do-act, andimage-genreturnstructuredContentalongside text; all tools carry MCP annotations, are exposed as MCP prompts, and get argument completions; long runs send a progress keepalive every 25 s - Cross-Platform — Windows, macOS, Linux fully supported
Quick Start
claude mcp add codex-cli -- npx -y @trishchuk/codex-mcp-tool
Prerequisites: Node.js 18+, Codex CLI 0.95.0 or newer, installed and authenticated (codex login). For the newest models, install the latest CLI: npm install -g @openai/codex@latest.
Configuration
{
"mcpServers": {
"codex-cli": {
"command": "npx",
"args": ["-y", "@trishchuk/codex-mcp-tool"]
}
}
}
Config locations: macOS: ~/Library/Application Support/Claude/claude_desktop_config.json | Windows: %APPDATA%\Claude\claude_desktop_config.json
The server is also listed in the official MCP Registry as io.github.x51xxx/codex-mcp-tool.
Usage Examples
// File analysis
'explain the architecture of @src/'
'analyze @package.json and list dependencies'
// With specific model
'use codex with model gpt-6.1-sol to analyze @algorithm.py'
// Multi-turn conversations
'ask codex sessionId:"my-project" prompt:"explain @src/"'
'ask codex sessionId:"my-project" prompt:"now add error handling"'
// Code review of the working tree
'use review-changes to review my uncommitted changes'
// Brainstorming
'brainstorm ways to optimize CI/CD using SCAMPER method'
// Sandbox mode
'use codex sandbox:true to create and run a Python script'
// Web search
'ask codex search:true prompt:"latest TypeScript 5.7 features"'
// Image generation
'image-gen prompt:"YouTube cover about AI coding agents" aspect:"wide" outputPath:"assets/cover.png"'
// Local OSS model (Ollama)
'ask codex localProvider:"ollama" model:"qwen3:8b" prompt:"explain @src/"'
Tools
| Tool | Description |
|---|---|
ask-codex | Execute Codex CLI with files, models, sessions, and safety controls |
batch-codex | Run multiple atomic Codex tasks sequentially or concurrently |
review-changes | Run the native non-interactive Codex review command |
do-act | Execute, verify with a shell command, and retry fixes |
image-gen | Generate or edit images with Codex’s built-in image_gen tool |
brainstorm | Generate ideas with structured creative frameworks |
list-sessions | View, delete, or clear MCP conversation mappings |
list-skills | List skills visible from the selected workspace |
health | Diagnose CLI installation, version, resolved path, and sessions |
fetch-chunk | Retrieve a chunk from cached change-mode output |
ping | Test the MCP connection |
help | Return current codex --help output |
version | Report Codex CLI, Node.js, platform, and package versions |
timeout-test | Exercise keepalive and timeout behavior |
review-changes— reviewsuncommittedchanges, a branch againstbase, or a singlecommit; an optionalpromptsets the review focus (it cannot be combined withuncommitted: true). The default timeout is 10 minutes, because a high-effort review runs its own verification commands. If the timeout is hit, the result says so explicitly instead of returning a half-written review as if it were complete.do-act— runs atask, then averifyshell command (expectedexitCode, owntimeout), and feeds failures back for up tomaxRetriesfix attempts (0–5, default 2). Runs inworkspace-writeby default.batch-codex— takes a list oftaskswith optionalpriority; setparallel: trueandconcurrency(1–10, default up to 4) to run them at once;stopOnErrordefaults totrue.
Image Generation
image-gen (added in v2.6.0) drives Codex’s built-in image_gen tool, so it uses your ChatGPT login and needs no OPENAI_API_KEY. That tool only accepts a prompt and reference image paths: Codex picks the image model and pixel size, and there are no size, quality, format or mask arguments. image-gen therefore puts all steering into a structured prompt — use case, asset type, style, composition, exact text, reference roles, edit invariants, aspect ratio, and presets — and tells the Codex host model to relay it instead of improvising.
// New image, 16:9, exact Cyrillic headline, copied into the project
'image-gen prompt:"YouTube cover about AI coding agents" aspect:"wide"
text:"АГЕНТИ БЕЗ ХАОСУ" presets:["thumbnail","exact-text"]
outputPath:"assets/cover.png"'
// Edit: change only the headline, keep everything else
'image-gen editImage:"assets/cover.png" prompt:"Replace the headline text"
text:"ЧАСТИНА 2" preserve:["people and background"]
outputPath:"assets/cover.png"'
| Parameter | Description |
|---|---|
prompt | What to create, or what to change in an edit |
editImage | Image to edit; combine with preserve to list what must stay unchanged |
references | Reference images with roles (identity, style, logo, layout, subject, or the default general); up to 5 images including editImage |
useCase, assetType | Task category (sets the polish level) and where the image will be used, e.g., “landing page hero” |
style, composition, lighting, palette, materials, typography, avoid | Optional prompt-spec fields, each rendered as a labeled line |
text | Exact in-image text, rendered verbatim |
aspect | square, landscape (3:2), portrait (2:3), wide (16:9), tall (9:16), or W:H |
transparentBackground | Ask for an alpha background; check hasAlpha in the result |
presets | photoreal, portrait, likeness, product, thumbnail, no-text, exact-text, brand-style |
enhance | Let the host model enrich generic prompts with composition/lighting detail (default true; never adds subjects or text) |
variants | 1–4 images; each is a separate image_gen call (roughly 30–90 s each) |
outputPath / overwrite | Copy results into the project; an existing file is kept and the copy gets a -v2 suffix unless overwrite: true is set |
model, reasoningEffort, timeout | Host model that relays the call (not the image model); effort defaults to low; timeout defaults to 10 minutes |
Codex saves images under $CODEX_HOME/generated_images/<thread id>/; the server finds them by the thread id that codex exec prints, so concurrent runs don’t pick up each other’s files. If the id is missing from the output, it falls back to a timestamp scan and adds a warning to the result. The result reports each file’s dimensions and alpha channel, so a transparent-background request that came back opaque is flagged.
Note: aspect ratio and transparency are requests in the prompt, not guarantees. Codex’s backend ignores an image model or size field entirely, so there is no way to pin a specific image model from an MCP call.
Models
By default, the model parameter is omitted, and Codex CLI applies the default model from your ~/.codex/config.toml (for example, model = "gpt-6.1-sol"). Pass model only when you need to override the configured default for a single call. The server no longer runs its own fallback chain: unknown names are passed through to Codex with a warning. Reasoning depth is calibrated per tool:
ask-codex— uses the Codex CLI default reasoning (medium). Increase it only when the task needs more planning or checking.brainstorm,do-act,review-changes— defaultreasoningEffort: "high"(creative ideation, act-check-fix loops, and code review benefit from deeper reasoning).image-gen— defaultreasoningEffort: "low", since the host model only relays a prepared image spec.
| Model | Recommendation | Max reasoning |
|---|---|---|
gpt-6.1-sol | Latest workhorse for coding and everyday work (needs CLI 0.159+) | ultra |
gpt-6-astra | Frontier intelligence for the most demanding work | ultra |
gpt-6-sol | Previous-generation workhorse | ultra |
gpt-6-luna | Fast and affordable; easier, repeatable tasks | max |
gpt-5.6-sol | Older-generation workhorse | ultra |
gpt-5.6-terra | Older balanced model for straightforward work | ultra |
gpt-5.6-luna | Older fast, efficient model | max |
gpt-5.5 | Legacy — Codex steers callers to gpt-5.6-sol | xhigh |
Reasoning effort is validated per model before Codex is spawned, so asking gpt-5.5 for ultra fails immediately with a clear message instead of a 400 from the API. ultra may delegate work to subagents; most tasks should remain on medium or high.
Use concrete slugs. The bare moving aliases gpt-6 and gpt-5.6 are rejected by the API with HTTP 400, as are the withdrawn gpt-5.4 and gpt-5.4-mini. gpt-6.1-sol is rejected by Codex CLI 0.157.x with the same 400 an unknown slug gets — upgrade the CLI rather than drop the model.
Key Features
Session Management
Multi-turn conversations with workspace isolation. Each sessionId is mapped to a native Codex thread and resumed with codex exec resume, so the model keeps its own context rather than a replayed transcript:
{ "prompt": "analyze code", "sessionId": "my-session" }
{ "prompt": "continue from here", "sessionId": "my-session" }
{ "prompt": "start fresh", "sessionId": "my-session", "resetSession": true }
A sessionId is global to the running server process, not per project: reusing the same id in a second workspace resumes the first workspace’s thread, so give each project its own ids. Session mappings live in memory and are lost when the server restarts. ephemeral: true cannot be combined with sessionId, since an ephemeral run leaves nothing to resume.
Local OSS Models
Run with local Ollama or LM Studio instead of OpenAI:
// Ollama
{ "prompt": "analyze @src/", "localProvider": "ollama", "model": "qwen3:8b" }
// LM Studio
{ "prompt": "analyze @src/", "localProvider": "lmstudio", "model": "my-model" }
// Auto-select provider
{ "prompt": "analyze @src/", "oss": true }
Requirements: Ollama or LM Studio running locally with a model that supports tool calling (e.g., qwen3:8b). OSS runs default to --sandbox workspace-write when no sandbox is given, and local model names are passed through as-is.
Working Directory
The directory Codex runs in is resolved in this order: explicit workingDir (or its alias cd) → CODEX_MCP_CWD → PWD → INIT_CWD → inferred from @path references → process.cwd(). Only the @path step walks up to the nearest project root (package.json, .git, Cargo.toml, …); the others are used as given.
Environment Variables
| Variable | Purpose |
|---|---|
CODEX_CLI_PATH | Absolute path to the codex executable (for GUI-launched clients with a minimal PATH) |
CODEX_MCP_CWD | Override the working directory for all tool calls |
CODEX_SESSION_TTL_MS | Session TTL (default: 24h) |
CODEX_MAX_SESSIONS | Max sessions (default: 50) |
Advanced Options
| Parameter | Description |
|---|---|
model | Model selection (omit to use config.toml) |
sessionId | Enable conversation continuity |
sandbox | Compatibility automation: workspace-write + never |
sandboxMode | read-only, workspace-write, danger-full-access |
approvalPolicy | on-request or never |
search | Enable web search |
changeMode | Structured OLD/NEW edits |
addDirs | Additional writable directories |
toolOutputTokenLimit | Cap response verbosity (100–10,000) |
reasoningEffort | low, medium, high, xhigh, max, ultra (validated per model) |
oss | Use local OSS model provider |
localProvider | Local provider: lmstudio or ollama |
strictConfig | Fail on unknown Codex configuration keys |
ephemeral | Do not persist Codex session files |
ignoreUserConfig | Ignore $CODEX_HOME/config.toml |
ignoreRules | Ignore execpolicy .rules files |
image | Attach input image paths to the prompt (-i) |
outputSchema | JSON Schema (file path or inline) the final answer must match |
outputLastMessage | Write the final message to a file (-o) |
responseMode | clean (final answer) or full (complete log with thinking, tool calls, and agent activity) |
personality | pragmatic or friendly |
profile, config | Codex config profile, and key=value overrides (an object is expanded into repeated -c flags) |
enableFeatures, disableFeatures | Toggle Codex feature flags (--enable / --disable) |
skipGitRepoCheck | Allow running outside a git repository |
timeout | Per-call timeout in ms |
yolo, bypassHookTrust | Dangerous: bypass approvals and sandbox, or hook trust checks. Use only in an isolated environment |
CLI Compatibility
Requires Codex CLI 0.95.0 or newer; v2.6.0 was validated end-to-end against Codex CLI 0.159.2. On an older CLI the server stops with an explicit upgrade message. Earlier versions silently dropped flags the CLI didn’t know, which produced runs that looked successful while ignoring half the request.
-a/--ask-for-approvalaccepts onlyon-requestandnever.untrustedwas removed upstream in 0.153.x and now fails at argument parsing, so it is gone from the tool schemas too.--full-autoand approval policyon-failurewere removed by Codex CLI. MCPsandbox: true/fullAuto: trueremain compatibility aliases for--sandbox workspace-write --ask-for-approval never; they do not bypass the sandbox.- Flag position matters.
-m,-s/--sandbox,-a/--ask-for-approval,--search,-C,--add-dirare accepted only before theexecsubcommand;--oss,--local-provider,--ephemeral,--skip-git-repo-check,--output-schema,-o,--ignore-user-config,--ignore-rulesonly after it. The command builder encodes this order. - Native
--searchis used without the deprecatedweb_search_requestfeature.
Troubleshooting
codex --version # Check CLI version
codex login # Authenticate
which codex # Path to pin in CODEX_CLI_PATH
Use the health tool for diagnostics: 'use health verbose:true'. It reports the detected CLI version, whether the minimum version is met, and which executable was resolved and how.
“codex not found” from a desktop app
MCP clients launched from a GUI (Dock, Finder, Start menu) inherit a minimal PATH that excludes Homebrew, nvm, and Volta directories, so codex may work in a terminal but not from the app. The server searches those locations automatically and also extends the child’s PATH, because codex itself starts with #!/usr/bin/env node. If it still can’t find the CLI, pin it:
{
"mcpServers": {
"codex-cli": {
"command": "npx",
"args": ["-y", "@trishchuk/codex-mcp-tool"],
"env": { "CODEX_CLI_PATH": "/opt/homebrew/bin/codex" }
}
}
}
A missing working directory and a missing binary used to produce the same spawn ENOENT; the server now checks the directory first and reports which of the two is wrong.
HTTP 400 on a model name
Either the slug is a moving alias or withdrawn model (see Models), or your CLI is older than the model. Upgrade with npm install -g @openai/codex@latest and retry before changing the model.
Release History
| Version | Changes |
|---|---|
| v2.6.0 Sep 2026 | Model list synced with Codex CLI 0.159.2: added gpt-6.1-sol, gpt-6-sol, gpt-6-luna. New image-gen tool. Breaking: dropped gpt-5.4-mini (now HTTP 400). |
| v2.5.0 Sep 2026 | Codex CLI 0.153.4 compatibility; added gpt-6-astra. Minimum CLI 0.95.0 enforced instead of silently dropping flags; CODEX_CLI_PATH and clear bad-cwd/missing-binary errors; large prompts over stdin; per-model reasoning validation; timeouts no longer reported as success. Breaking: dropped gpt-5.4, the gpt-5.6 alias, and the untrusted approval policy. |
| v2.4.0 Jul 2026 | Codex CLI 0.144.3 audit; GPT-5.6 Sol/Terra/Luna, max/ultra reasoning, strictConfig/ephemeral/ignoreUserConfig/ignoreRules, native-only search, safe handling of the removed --full-auto and on-failure. |
| v2.3.0 May 2026 | Model choice deferred to config.toml; per-tool reasoning defaults; retired GPT-5.1/5.2/5.3 Codex models removed. |
| v2.0–2.2 | MCP tool annotations, structured output, argument completions, do-act, list-skills, responseMode. |
| v1.4–1.7 | Multi-turn sessions, list-sessions/health, structured errors, local OSS models via Ollama and LM Studio. |
See the full notes in the CHANGELOG.