Codex MCP
Wraps OpenAI Codex CLI to start and manage asynchronous coding agent sessions, including follow-ups, permission policies, sandbox modes, and session control.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Codex MCP start a Codex agent to fix failing tests with on-request approval and workspace-write sandbox"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
codex-mcp
MCP server that wraps OpenAI Codex — start coding agents, poll their progress, and manage permissions from any MCP client. Supports both app-server (full capability) and exec (fallback for codex variants without app-server) modes.
Features
4 tools, full capability —
codex,codex_reply,codex_session,codex_checkAsync non-blocking — sessions run in background, poll for results
Complete permission management — three-layer model: approval policy, sandbox isolation, async approval arbitration
Zero config — inherits your local
~/.codex/config.tomlautomaticallySession management — list, inspect, cancel, interrupt, fork sessions
Event streaming — cursor-based pagination with pin-protected event buffer
Static read-only resources —
codex-mcp:///server-info,codex-mcp:///compat-report,codex-mcp:///config,codex-mcp:///gotchas,codex-mcp:///quickstart,codex-mcp:///errors
Related MCP server: muster
Prerequisites
Node.js >= 18
OpenAI Codex CLI installed and configured (
codexin PATH)
Quick Start
npx (no install)
npx @leo000001/codex-mcpGlobal install
npm install -g @leo000001/codex-mcp
codex-mcpWindows shell wrapper (if needed)
pwsh -NoProfile -Command "npx -y @leo000001/codex-mcp"MCP Client Configuration
Add to your MCP client config (e.g. Claude Desktop, Cursor, etc.):
{
"mcpServers": {
"codex": {
"command": "npx",
"args": ["-y", "@leo000001/codex-mcp"]
}
}
}Claude Code
claude mcp add codex-mcp -- npx -y @leo000001/codex-mcpOr add to ~/.claude/settings.json:
{
"mcpServers": {
"codex-mcp": {
"command": "npx",
"args": ["-y", "@leo000001/codex-mcp"]
}
}
}STDIO Guard Modes
codex-mcp includes a startup preflight guard for stdout contamination risk.
CODEX_MCP_STDIO_MODE=auto(default): run with warnings when risk is elevatedCODEX_MCP_STDIO_MODE=strict: fail fast on blocking risks (e.g. TTY stdio), keep heuristic risks as warningsCODEX_MCP_STDIO_MODE=off: disable the preflight guard
Exec Fallback Mode
When the codex binary does not support app-server (e.g. internal variants like codex-internal), codex-mcp automatically falls back to codex exec --json mode.
Env Var | Default | Description |
|
| Name of the codex binary to use |
| auto-detect | Force |
Exec mode supports multi-turn context via codex exec resume. First turn uses codex exec, subsequent turns use codex exec resume <threadId>.
Exec mode limitations:
No approval/user-input interactions
threadFork/threadResumethrowEXEC_NOT_SUPPORTEDsandbox/profile/cwd/outputSchemaoverrides only apply on the first turn (exec resume does not support these flags)
Check codex-mcp:///server-info clientMode field to detect which mode is active.
Examples:
CODEX_MCP_STDIO_MODE=strict npx -y @leo000001/codex-mcp$env:CODEX_MCP_STDIO_MODE = "strict"; npx -y @leo000001/codex-mcpTools
codex — Start a new session
Start a Codex agent session asynchronously. Returns immediately with sessionId.
Parameter | Type | Required | Description |
| string | Yes | Task or question for the Codex agent |
| string | Yes | Approval policy: |
| string | Yes | Sandbox mode: |
| string | No | Reasoning effort: |
| string | No | Working directory. Default: server cwd |
| string | No | Model override. Default: from |
| string | No |
|
| object | No | Low-frequency options (see below) |
Parameter | Type | Description |
| string | Replace default instructions (thread-level) |
| string | Developer instructions (thread-level) |
| string | Personality: |
| string | Reasoning summary: |
| object | Override |
| boolean | Don't persist thread. Default: |
| object | JSON Schema for structured output |
| string[] | Local image paths (adds |
| number | Auto-decline timeout (ms) for pending approvals. Default: |
Returns: { sessionId, threadId, status: "running" | "idle", pollInterval }
{
"prompt": "Fix the failing tests in src/",
"approvalPolicy": "on-request",
"sandbox": "workspace-write",
"effort": "high",
"cwd": "/path/to/project",
"model": "o4-mini"
}Resources
If your MCP client supports resources, this server exposes a few read-only resources:
codex-mcp:///server-info(JSON): static server metadata (version/platform/runtime)codex-mcp:///compat-report(JSON): capability summary for cross-backend adapter compatibilitycodex-mcp:///config(Markdown): config mapping guide, including how to usecodex.advanced.configcodex-mcp:///gotchas(Markdown): practical limits/gotchascodex-mcp:///quickstart(Markdown): minimal workflow examplescodex-mcp:///errors(Markdown): error code catalog + recovery hints
codex_reply — Continue a session
Send a follow-up message to an existing session.
Parameter | Type | Required | Description |
| string | Yes | Session ID from |
| string | Yes | Follow-up message |
| string | No | Override model for this turn |
| string | No | Override approval policy |
| string | No | Override reasoning effort ( |
| string | No | Override reasoning summary ( |
| string | No | Override personality ( |
| string | No | Override sandbox ( |
| string | No | Override working directory |
| object | No | JSON Schema for structured output |
Returns: { sessionId, threadId, status: "running" | "idle", pollInterval }
{
"sessionId": "sess_abc123",
"prompt": "Now add error handling for the edge cases"
}codex_session — Manage sessions
List, inspect, cancel, interrupt, fork sessions, or clean background terminals.
Parameter | Type | Required | Description |
| string | Yes |
|
| string | For get/cancel/interrupt/fork/clean_background_terminals | Target session ID |
| boolean | No | Include |
Returns:
action="list"→{ sessions: PublicSessionInfo[] }action="get"→PublicSessionInfo(orSensitiveSessionInfowhenincludeSensitive=true)action="cancel"|"interrupt"→{ success: true, message }action="fork"→{ sessionId, threadId, status: "idle", pollInterval }action="clean_background_terminals"→{ success: true, message }
{ "action": "list" }
{ "action": "get", "sessionId": "sess_abc123", "includeSensitive": true }
{ "action": "cancel", "sessionId": "sess_abc123" }
{ "action": "interrupt", "sessionId": "sess_abc123" }
{ "action": "fork", "sessionId": "sess_abc123" }
{ "action": "clean_background_terminals", "sessionId": "sess_abc123" }codex_check — Poll events & respond
Query a running session for events, respond to approval requests, or answer user input.
Parameter | Type | Required | Description |
| string | Yes |
|
| string | Yes | Target session ID |
| number | No | Event cursor for incremental polling ( |
| number | No | Keep this small. |
| string | No | Response shaping mode: |
| object | No | Optional controls: |
| string | For respond_permission/user_input | Request ID from |
| string | For respond_permission | For command approvals: |
| string[] | For acceptWithExecpolicyAmendment | Exec policy amendment list (required when |
| string | No | Internal note on deny (not sent to app-server) |
| object | For respond_user_input | For |
Returns (poll and respond_*): { sessionId, status, pollInterval?, cursorResetTo?, events, nextCursor, actions?, result? }
{ "action": "poll", "sessionId": "sess_abc123", "cursor": 0 }
{
"action": "respond_permission",
"sessionId": "sess_abc123",
"requestId": "req_xyz",
"decision": "accept"
}
{
"action": "respond_user_input",
"sessionId": "sess_abc123",
"requestId": "req_abc",
"answers": { "question_id": { "answers": ["choice_1"] } }
}Event Polling Semantics
codex_check(action="poll") returns an append-only event stream with cursor pagination:
cursor: the first event id you want (use the previousnextCursor)nextCursor: pass this back on the next pollcursorResetTo: when present, older events were evicted; restart from this cursor to avoid gapsmaxEvents: max events returned per callIf
cursoris omitted, codex-mcp continues from that session's last consumed cursor.If
responseModeis omitted, codex-mcp usesminimal.pollOptions.includeEvents/includeActions/includeResultdefault totrue.pollOptions.maxBytesis optional and enforces best-effort payload truncation (truncated,truncatedFields).respond_*defaults to compact ACK (events: [], no cursor advance) unless you explicitly passmaxEvents.polldefaults tomaxEvents=1to keep payloads small; increase temporarily (for example10-20) when you need to catch up faster.If
pollis called withmaxEvents=0, codex-mcp treats it as1to avoid no-op polling loops.For
respond_*, prefermaxEvents=0instead of1:0keeps approval ACK minimal and avoids consuming/replaying stream events in the same call. Use1-5only when you explicitly need immediate events.For
poll, keep windows small to reduce payload spikes and context pressure.
Event types include output, progress, approval_request, approval_result, result, error.
Approvals/results/errors are pinned to reduce eviction risk.
Approvals & User Input
When the agent requests approval or user input, poll includes an actions[] list. Respond with:
respond_permission:decisionis one ofaccept,acceptForSession,decline,cancel.For command approvals,
acceptWithExecpolicyAmendmentis supported and requiresexecpolicy_amendment.
respond_user_input: sendanswerskeyed by the questionid.For command approvals,
actions[]may includecommandActionsandproposedExecpolicyAmendmentfor richer review UI.
Pending approvals auto-decline after advanced.approvalTimeoutMs.
Auth callback note: if app-server sends account/chatgptAuthTokens/refresh, codex-mcp returns JSON-RPC error -32000 because external ChatGPT token refresh is out of scope for this server.
Session Lifecycle & Cleanup
Sessions auto-clean up in the background:
idle> 30 minutes → cancelledrunning/waiting_approval> 4 hours → cancelledcancelled/error> 5 minutes → removed from memory
Error Model
Tools return errors as:
{ "content": [{ "type": "text", "text": "Error [CODE]: message" }], "isError": true }Common codes include INVALID_ARGUMENT, SESSION_NOT_FOUND, SESSION_BUSY, SESSION_NOT_RUNNING, REQUEST_NOT_FOUND, CANCELLED, INTERNAL.
Client compatibility notes
Tool responses follow
@modelcontextprotocol/sdk'sCallToolResultcontract:content(JSON text for wide compatibility), optionalstructuredContent(the canonical object), andisError.structuredContentis always object-shaped; when a tool returns a scalar/array, codex-mcp wraps it as{ "value": ... }. Claude Desktop and other clients tend to surface thecontenttext directly, which shows the raw JSON blob, so they should fall back tostructuredContentwhen they want typed data (Cursor already does this automatically whenever structured output is available).When an operation fails we set
isError: trueand returnError [CODE]: messagein thecontentarray instead of raising an MCP transport error. This keeps the STDIO channel healthy so Claude, Cursor, and other MCP clients stay connected even when a tool reports a problem.codex-mcpuses the MCP stdio transport (src/index.ts), so stdout is reserved for newline-delimited JSON and all diagnostics go to stderr. Anything else on stdout—including shell/profile banners (e.g., PowerShell's oh-my-posh warning) or CLI wrappers that print prompts—will break the MCP handshake for Claude/Cursor. Runpwsh -NoProfile, disable profile banners, or wrap the command so stdout stays quiet before piping it into the client.Windows command execution inside
codex app-servermay still inherit PowerShell profile side effects in some environments. This cannot be filtered by codex-mcp once emitted on stdout; if command turns are noisy or fail with profile errors, clean your PowerShell profile and preferapprovalPolicy="on-failure"/"never"to reduce approval churn.If Windows command output shows mojibake, enforce UTF-8 in the shell (
chcp 65001and$OutputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()).Startup guard behavior is controlled by
CODEX_MCP_STDIO_MODE(auto/strict/off). Usestrictin CI or hardened environments to fail fast on blocking contamination risks (while still surfacing heuristic risk warnings).Retryable transport/API interruptions are emitted as
progressevents withdata.method="codex-mcp/reconnect"andwillRetry=true, so clients can surface reconnect state without treating it as terminal failure.Approval/user-input flows rely on the
actions[]array returned bycodex_check(action="poll"). Claude and Cursor render approval buttons from this payload, so they need to poll atpollInterval, honourcursorResetTo, and reply withinapprovalTimeoutMsto avoid automatic declines.
Typical Workflow
1. codex(prompt="Fix bug X") → { sessionId, threadId, status: "running" }
2. codex_check(action="poll", ...) → events[], status, actions[]
3. codex_check(action="respond_permission", decision="accept") (if needed)
4. codex_check(action="poll", ...) → result when status="idle"
5. codex_reply(prompt="Also add tests") → new turn starts
6. codex_check(action="poll", ...) → poll until donePermission Model
Three layers of protection:
Layer | Mechanism | Options |
0 | Approval Policy |
|
1 | Sandbox |
|
2 | Async Approval | Command execution + file change approval via |
Architecture
Same-platform assumption: codex-mcp assumes the MCP client and server run on the same machine. All communication uses stdio (local IPC), child processes share the local filesystem and
~/.codex/config.toml, andcwdpaths refer to the local filesystem.
MCP Client ←stdio→ codex-mcp server ←stdio→ codex app-server ←→ Codex Agent (app-server mode)
MCP Client ←stdio→ codex-mcp server ←stdio→ codex exec --json ←→ Codex Agent (exec fallback)
(same machine, stdio transport)Each session spawns an independent child process. In app-server mode, it uses the JSON-RPC protocol over stdio. In exec fallback mode, it uses codex exec --json JSONL output with codex exec resume for multi-turn context.
Development
git clone https://github.com/xihuai18/codex-mcp.git
cd codex-mcp
npm install
npm run build
npm run typecheck
npm test
npm run check:stdio
npm run check:stdio:strictEnd-to-end local test plan (after installing/configuring in an MCP client):
Full guide (LLM operator handbook):
docs/E2E_LOCAL_TEST_PLAN.mdQuick English checklist: run
codex→ poll withcodex_check(action="poll")→ respond viarespond_permission/respond_user_inputifactions[]appears → continue polling untilstatusisidle/error/cancelled.
Project Policies
License
Available Tools
4 toolscodexStart Codex SessionBDestructive
Start session asynchronously and return { sessionId, threadId, status, pollInterval }. Use pollInterval as a minimum hint: running >=120000ms (increase for long tasks), waiting_approval ~=1000ms.
Inputs: prompt (required), sandbox (required), approvalPolicy (required), cwd, +4 more. Returns: error, status, isError, threadId, +2 more
codex_checkPoll & RespondA
Poll session for events or respond to approval/input requests.
POLLING FREQUENCY: Do NOT poll every turn. Codex tasks take minutes, not seconds.
Treat pollInterval as a minimum hint, not a fixed schedule.
"running": sleep at least 2 minutes between polls; increase for complex tasks. Do NOT high-frequency poll — it wastes tokens and provides no benefit.
"waiting_approval": poll about every 1000ms and respond quickly to actions[].
When status is "idle"/"error"/"cancelled": stop polling, the session is done.
Adapt interval based on task complexity and whether the previous poll returned new events.
poll: events since cursor. Default maxEvents=1.
respond_permission: approval decision. Default maxEvents=0 (compact ACK).
respond_user_input: user-input answers. Default maxEvents=0 (compact ACK).
events[].type is coarse-grained; details are in events[].data.method. cursor omitted => use session last cursor. cursorResetTo => reset and continue.
Inputs: action (required), sessionId (required), cursor, answers, +8 more. Returns: error, events, result, status, +9 more
codex_replyContinue Codex SessionADestructive
Continue existing session. Allowed in idle/error; otherwise SESSION_BUSY. Returns immediately. Use pollInterval as a minimum hint: running >=120000ms, waiting_approval ~=1000ms.
Inputs: prompt (required), sessionId (required), cwd, model, +6 more. Returns: error, status, isError, threadId, +2 more
codex_sessionManage SessionsBDestructive
Session actions: list, get, cancel, interrupt, fork, clean_background_terminals.
list: sessions in memory.
get: details. includeSensitive defaults to false; true adds threadId/cwd/profile/config.
cancel: terminal.
interrupt: stop current turn.
fork: clone current thread into a new session; source remains unchanged.
clean_background_terminals: ask app-server to clean stale background terminals for this thread.
Inputs: action (required), sessionId, includeSensitive. Returns: cwd, error, model, config, +16 more
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 4 tools
The four tools map to distinct lifecycle stages: start (codex), continue (codex_reply), manage (codex_session), and poll/respond (codex_check). There is minor overlap between codex_reply and codex_check's respond_user_input/respond_permission (both send input to a session), but the descriptions disambiguate by session state (idle/error vs waiting_approval).
All tools share the `codex_` prefix and snake_case style, giving a predictable namespace. The bare `codex` tool for starting a session is the only deviation (no verb like codex_start), which is a minor inconsistency rather than a real problem.
Four tools is a compact, well-scoped surface for an async session orchestrator, with each tool earning its place. However, codex_session hides six sub-actions (list/get/cancel/interrupt/fork/clean) and codex_check bundles poll plus two respond variants, so the effective surface is larger than the count suggests.
The full loop is covered: start a session, poll events, respond to approvals/input, continue turns, and cancel/interrupt/fork/manage sessions. Minor gaps exist—there is no explicit delete/archive action to remove sessions from memory and no dedicated result-retrieval beyond get details, but these are workaroundable.
Maintenance
Related MCP Connectors
Start and manage Reason cloud coding agents, projects and sessions from any MCP client.
A paid remote MCP for OpenAI Codex agent coordination MCP, built to return verdicts, receipts, usage
Hosted MCP memory and agent control plane for durable conversations, jobs, and operations.
Multi-tenant backend your coding agent configures over MCP: auth, RBAC, data, workflows, deploy.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables MCP clients to spawn and control Codex CLI and Claude Code sessions on the host machine, with session management and filesystem access.4MIT
- AlicenseBqualityBmaintenanceEnables launching and supervising local Codex and Claude Code agent sessions and one-shot tasks, exposing run, list, stop, and output operations over MCP with session-scoped permissions and sandbox controls.2138 npm1MIT
- FlicenseNot gradedqualityCmaintenanceEnables MCP clients such as Codex to asynchronously launch, monitor, steer, and control persistent CodeBuddy CLI sessions, including permission responses, interruption, recovery, and shutdown. It also provides model and account queries plus optional WebUI monitoring.-
- AlicenseBqualityBmaintenanceEnables MCP clients to spawn and control long-lived local coding-agent sessions, including turns, mid-turn steering, approvals, user prompts, status, cancellation, and opt-in live event streaming.17BSD Zero Clause