Codex MCP Server

An MCP server connecting Claude, Cursor, and other AI assistants to OpenAI Codex CLI · npm package @trishchuk/codex-mcp-tool · current release v2.6.0 · How I use it as an outside advisor to Claude Code →

npm ↗ GitHub ↗ Releases ↗ Docs ↗

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

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

ToolDescription
ask-codexExecute Codex CLI with files, models, sessions, and safety controls
batch-codexRun multiple atomic Codex tasks sequentially or concurrently
review-changesRun the native non-interactive Codex review command
do-actExecute, verify with a shell command, and retry fixes
image-genGenerate or edit images with Codex’s built-in image_gen tool
brainstormGenerate ideas with structured creative frameworks
list-sessionsView, delete, or clear MCP conversation mappings
list-skillsList skills visible from the selected workspace
healthDiagnose CLI installation, version, resolved path, and sessions
fetch-chunkRetrieve a chunk from cached change-mode output
pingTest the MCP connection
helpReturn current codex --help output
versionReport Codex CLI, Node.js, platform, and package versions
timeout-testExercise keepalive and timeout behavior

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"'
ParameterDescription
promptWhat to create, or what to change in an edit
editImageImage to edit; combine with preserve to list what must stay unchanged
referencesReference images with roles (identity, style, logo, layout, subject, or the default general); up to 5 images including editImage
useCase, assetTypeTask category (sets the polish level) and where the image will be used, e.g., “landing page hero”
style, composition, lighting, palette, materials, typography, avoidOptional prompt-spec fields, each rendered as a labeled line
textExact in-image text, rendered verbatim
aspectsquare, landscape (3:2), portrait (2:3), wide (16:9), tall (9:16), or W:H
transparentBackgroundAsk for an alpha background; check hasAlpha in the result
presetsphotoreal, portrait, likeness, product, thumbnail, no-text, exact-text, brand-style
enhanceLet the host model enrich generic prompts with composition/lighting detail (default true; never adds subjects or text)
variants1–4 images; each is a separate image_gen call (roughly 30–90 s each)
outputPath / overwriteCopy results into the project; an existing file is kept and the copy gets a -v2 suffix unless overwrite: true is set
model, reasoningEffort, timeoutHost 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:

ModelRecommendationMax reasoning
gpt-6.1-solLatest workhorse for coding and everyday work (needs CLI 0.159+)ultra
gpt-6-astraFrontier intelligence for the most demanding workultra
gpt-6-solPrevious-generation workhorseultra
gpt-6-lunaFast and affordable; easier, repeatable tasksmax
gpt-5.6-solOlder-generation workhorseultra
gpt-5.6-terraOlder balanced model for straightforward workultra
gpt-5.6-lunaOlder fast, efficient modelmax
gpt-5.5Legacy — Codex steers callers to gpt-5.6-solxhigh

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

VariablePurpose
CODEX_CLI_PATHAbsolute path to the codex executable (for GUI-launched clients with a minimal PATH)
CODEX_MCP_CWDOverride the working directory for all tool calls
CODEX_SESSION_TTL_MSSession TTL (default: 24h)
CODEX_MAX_SESSIONSMax sessions (default: 50)

Advanced Options

ParameterDescription
modelModel selection (omit to use config.toml)
sessionIdEnable conversation continuity
sandboxCompatibility automation: workspace-write + never
sandboxModeread-only, workspace-write, danger-full-access
approvalPolicyon-request or never
searchEnable web search
changeModeStructured OLD/NEW edits
addDirsAdditional writable directories
toolOutputTokenLimitCap response verbosity (100–10,000)
reasoningEffortlow, medium, high, xhigh, max, ultra (validated per model)
ossUse local OSS model provider
localProviderLocal provider: lmstudio or ollama
strictConfigFail on unknown Codex configuration keys
ephemeralDo not persist Codex session files
ignoreUserConfigIgnore $CODEX_HOME/config.toml
ignoreRulesIgnore execpolicy .rules files
imageAttach input image paths to the prompt (-i)
outputSchemaJSON Schema (file path or inline) the final answer must match
outputLastMessageWrite the final message to a file (-o)
responseModeclean (final answer) or full (complete log with thinking, tool calls, and agent activity)
personalitypragmatic or friendly
profile, configCodex config profile, and key=value overrides (an object is expanded into repeated -c flags)
enableFeatures, disableFeaturesToggle Codex feature flags (--enable / --disable)
skipGitRepoCheckAllow running outside a git repository
timeoutPer-call timeout in ms
yolo, bypassHookTrustDangerous: 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.

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

VersionChanges
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.2MCP tool annotations, structured output, argument completions, do-act, list-skills, responseMode.
v1.4–1.7Multi-turn sessions, list-sessions/health, structured errors, local OSS models via Ollama and LM Studio.

See the full notes in the CHANGELOG.


Further Reading