MCP Codex Worker
Provides an adapter to route model requests to OpenAI-compatible gateways, enabling cost savings by using cheaper models for code tasks.
Click on "Install 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., "@MCP Codex Workerfix the bug in utils.js and run tests"
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.
Stop spending premium context on bulk code work
Measured: 80% less premium context intake. ~$213-1068/mo saved.
Work type | Traditional | MCP Codex Worker | Cost |
Search code | LLM reads files |
| Free |
Explain code | Full agent loop |
| Low |
Fix bugs | Premium retries loop |
| Low |
Review code | Premium reads diff |
| Low |
See result | Full diff ingested |
| Compact |
Yeah# MCP Codex Worker
Stop spending premium Codex context on bulk code reading, patch loops, and giant diffs.
mcp-codex-worker lets Codex delegate the expensive part of a coding task to an async worker running on a cheaper OpenAI-compatible model gateway. Codex stays in charge, but it only receives the compact evidence it needs: changed files, checks, logs, and an optional trimmed diff.
Related MCP server: Jules MCP Server
Efficiency First
Most AI coding tools optimize the model call. This project optimizes the route.
The fast path is deliberately split:
searchhandles repo discovery with zero LLM calls.analyzeandreviewuse one cheap gateway call for read-only work.startmoves implementation loops into an async worker so Codex is not blocked by every file read, failed attempt, or test log.getandwaitreturn compact evidence instead of dumping the whole transcript back into the premium thread.
That routing discipline is the efficiency edge: Codex stays focused on planning and review while the worker absorbs the bulky middle.
The Simple Picture
Without this worker, Codex often pays to ingest everything:
Codex main thread
-> reads large files
-> runs repair loops
-> receives full diffs
-> burns premium contextWith this worker, Codex delegates the noisy middle:
flowchart LR
A["Codex<br/>planner and reviewer"] -->|"small MCP start request"| B["MCP Codex Worker"]
B -->|"launches"| C["Claude Code CLI<br/>background job"]
C -->|"Anthropic messages"| D["Local adapter"]
D -->|"OpenAI-compatible chat"| E["Cheap gateway model<br/>DeepSeek / OneAPI / New API"]
C -->|"git diff + checks"| B
B -->|"changed_files + checks<br/>optional diff"| APlain version:
Codex asks: "fix this, run tests"
Worker does: read files -> edit -> test -> summarize
Codex gets: files changed + checks passed + optional diffWhy It Exists
Codex is strongest when it coordinates, reviews, and decides. It is not always cost-effective to make the main Codex thread read huge files, run long repair loops, and ingest giant diffs.
This worker changes the shape of the bill:
Codex sends a compact
startrequest.Claude Code does the heavy local work in the background.
The local adapter routes model traffic to your cheaper backend.
Codex receives
changed_files,checks, logs, and an optional trimmed diff.
For large code-reading and patching tasks, this can cut the expensive main-thread token intake dramatically because Codex no longer has to ingest every intermediate file read and full patch body.
What Makes It Better Than "Just Use A Cheaper Model"
Cheap models alone are not enough. You still need routing, safety, result shape, and verification.
This project gives you the missing plumbing:
A Codex-native MCP interface, so delegation is one tool call.
A Claude Code execution loop, so the worker can actually edit and test.
A local Anthropic-to-OpenAI adapter, so Claude Code can use cheaper gateways.
Scope enforcement and check commands, so work is auditable.
Compact result payloads, so Codex does not swallow unnecessary tokens.
Metrics, fallback, retries, and optional worktree isolation for real operations.
Efficiency Comparison
Workflow | What usually happens | Efficiency gap | MCP Codex Worker path |
Direct premium-agent coding | The main agent reads files, retries fixes, sees every test log, and ingests large diffs. | Premium context becomes the workspace transcript. | Codex sends one small task; worker returns changed files, checks, logs, and optional diff. |
Generic cheaper-model wrapper | A cheaper model runs, but the main agent still needs bulky context and manual verification. | Lower model price, same noisy workflow. | Cheap gateway handles bulk tokens; scoped checks and compact results decide whether work is trustworthy. |
Full agent loop for read-only questions | Starting an edit-capable loop for summaries and discovery. | Slow startup and unnecessary write surface. |
|
Parallel implementation in one repo | Dirty worktrees collide and review payloads grow. | Coordination overhead eats the gain. | Optional worktree isolation plus scoped patch checks keep jobs separable. |
Highlights
Async MCP tools:
start,get,tail,wait,cancel.Read-only lite tools:
read_pack,analyze,diff_digest,history, anddraftkeep bulky reading/review/drafting out of the premium thread.Code review lite tool:
reviewchecks diffs/files through the cheap gateway.Zero-LLM repo discovery and mechanical work:
searchuses bounded local search, andapply_editshandles deterministic replacements without a model call.Worker-side command digesting:
shellcan run tests/builds/lint and return a compact failure digest. Non-zero command exits returnstatus:"failed"orstatus:"timeout"withfailure_kindandrequired_action; they are command outcomes, not tool transport errors.Receipt abnormal-output assessment: every receipt carries a deterministic accept/repair verdict and bounded repair guidance without default multi-model voting.
Runtime tool containment: the worker classifies tool errors, opens per-tool/per-error-class circuits, intercepts unhealthy routes, and uses deterministic fallbacks for
review/analyzewhen the LLM route is unhealthy.Reliability tiers and episode summaries:
startcan recordlite,standard,strict, orcriticalexpectations without blocking old callers; hard rejection happens only withblocking_policy:"enforce".Anthropic-to-OpenAI adapter: lets Claude Code talk to OpenAI-compatible gateways.
429 and 5xx retry handling with
Retry-Aftersupport.Optional
include_diff:falseto return onlychanged_filesandchecks.Deterministic verification layer: scope checks, command checks, result signals, and bounded auto-revise.
Cost telemetry: writes gateway token usage and worker tool-call categories to JSONL when
WORKER_METRICS_FILEis set.Optional fallback gateway when the primary provider fails.
Optional worktree isolation for parallel jobs inside one repository.
Secret redaction in logs and tool responses.
Use Cases
Use it when you want Codex to stay sharp instead of stuffed:
Task | Normal flow | Worker flow |
Fix a bug in a large repo | Codex reads many files and test outputs | Worker reads/edits/tests, Codex reviews compact result |
Summarize implementation details | Full agent loop may start |
|
Run repeated repair passes | Main thread absorbs every attempt | Worker handles loop and returns final evidence |
Parallel scoped edits | One dirty worktree gets tangled | Optional git worktree isolation keeps jobs apart |
Cost accounting | Claude Code cost may be misleading | Gateway token usage is written to JSONL |
Tool Surface
Tool | Purpose |
| Start an async Claude Code job in an allowed directory. Supports optional sequential |
| Read current job status and compact structured result; pass |
| Read a bounded redacted slice from an artifact referenced by a worker receipt. |
| Read recent worker logs. |
| Wait for completion without killing the job on timeout; pass |
| Kill a running job process tree. |
| Read-only cheap-model analysis for selected files or bounded globs. |
| Cheap-model review of a job diff/checks or selected files, returning a structured verdict. |
| Zero-LLM bounded repository search using |
| Zero-LLM context packer for selected paths; returns bounded symbol/keyword slices instead of whole files. |
| Summarize current git diff by file, hunk headers, and risk; optionally run cheap red-team review. |
| Run bounded worker-side commands with optional |
| Zero-LLM literal or regex replacements with replacement-count checks. |
| Bounded git log/blame timeline for file or line archaeology. |
| Draft commit messages, PR descriptions, changelog notes, or release notes from the current diff. |
Quick Start
npm install
npm run build
npm run test
npm run smokeCreate a local .env from .env.example or set environment variables in your shell. Never commit real keys.
setx ONEAPI_API_KEY "your-provider-key"
setx ONEAPI_BASE_URL "https://your-gateway.example.com/v1"
setx SANDBOX_ROOT "D:/workspaces"Then run:
npm run doctor
npm run doctor:networkCodex Desktop Config
Copy and adapt codex-mcp.example.toml into your Codex config.
[mcp_servers.codex_async_worker]
command = "node"
args = ["D:/path/to/mcp-codex-worker/dist/index.js"]
cwd = "D:/path/to/mcp-codex-worker"
startup_timeout_sec = 10
tool_timeout_sec = 3600
env = { SANDBOX_ROOT = "D:/workspaces", ONEAPI_BASE_URL = "https://your-gateway.example.com/v1", CLAUDE_MODEL = "deepseek-v4-flash", CLAUDE_CODE_MODEL = "sonnet", CLAUDE_PERMISSION_MODE = "acceptEdits", USE_OPENAI_ADAPTER = "1", WAIT_DEFAULT_MS = "1800000" }
env_vars = ["ONEAPI_API_KEY"]Example Job
{
"prompt": "Fix the failing tests with the smallest safe code change.",
"allowed_dirs": ["D:/workspaces/my-project"],
"model": "deepseek-v4-flash",
"permission_mode": "acceptEdits",
"include_diff": false,
"scoped_patch": {
"paths": ["src", "tests"],
"max_diff_bytes": 20000
},
"checks": [
{ "name": "unit tests", "command": "npm test", "timeout_ms": 600000 }
]
}Typical result:
{
"job_status": "completed",
"changed_files": ["src/a.ts", "tests/a.test.ts"],
"checks": ["scoped_patch: passed (src, tests)", "unit tests: passed"],
"diff": ""
}Use include_diff:false by default when Codex only needs to decide whether the job succeeded. Ask for the diff only when you actually need to review patch details.
Cost Controls
This project stacks several cost controls:
These controls reduce main-thread context, payload size, and accounting noise; they do not impose a spend ceiling on the worker LLM. Primary, fallback, and escalation models are chosen by capability and reliability configuration, not by price gates. WORKER_PRICE_* values are for reporting only and must not downgrade, block, or skip fallback/escalation usage.
include_diff:falsereduces high-cost Codex ingestion.DIFF_MAX_BYTEScaps patch payloads.INCLUDE_DIFF_DEFAULT=0makes omittedinclude_diffbehave likefalse.CHECK_OUTPUT_RESPONSE_MAXkeeps failed check output compact inget/waitresponses whiletailretains fuller logs.analyzeskips Claude Code for read-only summaries.searchhandles symbol/file discovery without any LLM call.reviewandWORKER_FAILURE_DIGEST=1move diff review and failure diagnosis to the cheaper gateway.read_pack,diff_digest,shell digest,apply_edits,history, anddraftmove the remaining high-token planning/review chores into worker lanes.WORKER_METRICS_FILErecords real gateway token usage plusevent=tool_callrows for zero-LLM worker calls.WORKER_ESCALATE_MODELupgrades only failed, difficult revise passes.WORKER_RELIABILITY_TIER,WORKER_BLOCKING_POLICY,WORKER_SEMANTIC_GATE, andWORKER_TOOL_BUDGETrecord reliability expectations and blocking risk. Defaults are observe-only to avoid surprise stalls.WORKER_ISOLATION=worktreeallows safe parallel work in one repo.Prompt-cache-friendly usage keeps stable instructions before dynamic task text.
Claude Code's own total_cost_usd may reflect Anthropic pricing, not your gateway pricing. Use WORKER_METRICS_FILE and provider prices for real accounting.
Cost-Saving Checklist
For best results:
Set
include_diff:falsefor delegated implementation tasks.Keep
scoped_patch.pathsnarrow.Add concrete
checksso the worker proves completion.Use
analyzefor read-only questions.Enable
WORKER_METRICS_FILEand compare token usage by route/model.Use
read_packinstead of full-file reads anddiff_digestinstead of full diff ingestion.Use
shellwithdigest:truefor tests/builds/lint so command output is summarized before Codex sees it.Keep
startbelow 30% of worker calls; use finer tools for search, reading, diff digestion, history, drafts, and mechanical edits.Treat receipt
abnormal.verdict !== "accept"as a repair signal before considering multi-model parallel review. Forshell, usefailure_kindandrequired_actionfirst; do not escalate to the main model just because the command exit code is non-zero.Use a fit-for-task default model and reserve
WORKER_ESCALATE_MODELfor difficult revise passes; do not downgrade primary, fallback, or escalation models because of cost.
Important Environment Variables
For less common stats, cache, reliability, and circuit-breaker settings, see Advanced Configuration.
Variable | Purpose |
| Root directory allowed for worker jobs and |
| Primary gateway URL. |
| Primary gateway key. Keep it out of git. |
| Real backend model used by the gateway. |
| Model name passed to Claude Code for local validation, usually |
|
|
| Worker concurrency limit, default |
| Maximum returned diff size. |
| Default for omitted |
| Per-check output cap for compact |
| Optional JSONL path for token usage metrics. |
| Optional USD-per-1M-token prices used by |
| Optional JSON model price overrides for |
| Set |
| Set |
| Optional cheaper model for |
| Optional disk cache directory for lite read-only tools; must be inside |
| TTL for lite disk cache entries, default |
| Set |
| Warn every N fallback calls; default |
| Gate threshold for total worker tool error rate; default |
| Gate threshold for each individual tool's error rate; default |
| Gate threshold for category-level tool error rate; default |
| Minimum sample count before category or single-tool error-rate gates apply; default |
| Runtime tool error-rate review interval while the MCP server is running; default |
| Review window for runtime tool error-rate control; default |
| How late a scheduled review can run before it is treated as overdue; default |
| Set |
| Active runtime containment switch; default enabled. Set |
| Rolling window for immediate circuit decisions; default |
| How long an opened circuit intercepts the unhealthy route; default |
| Minimum calls before generic per-tool error-rate circuits can open; default |
| Minimum errors before generic per-tool circuits can open; default |
| Minimum same-class errors before a per-error-class circuit can open; default |
| Comma-separated classes that open a circuit immediately; default |
| Optional persisted circuit state path. Defaults to |
| Maximum recent tool-control events persisted with circuit state; default |
| Minimum interval for non-error state snapshots; default |
| Best-effort state lock stale threshold; default |
| Optional stronger model for hard revise passes. |
| Default |
| How missing reliability gates behave: |
| Declared semantic-review expectation: |
| Optional advisory max tool-call budget recorded in metrics and reliability profile. |
| Set to |
| Optional fallback gateway. |
| Optional comma-separated fallback model pool, capped at 3 model candidates for bounded routing. Overrides |
Security Model
All job paths must resolve inside
SANDBOX_ROOT.scoped_patchrejects changes outside declared paths.bypassPermissionsis blocked unless explicitly enabled withALLOW_BYPASS_PERMISSIONS=1.Secrets are redacted from logs and tool responses.
.env, archives, logs,node_modules, anddistare gitignored.
See SECURITY.md for responsible disclosure and operational notes.
Validation
npm run build
npm run test
npm run smoke
npm run doctor:network
npm run skills:validate
npm run codex:audit -- --since-minutes=60
npm run codex:guarddoctor:network depends on your real gateway credentials. Build, test, and smoke should pass offline.
npm run codex:audit -- --since-minutes=60 checks recent worker metrics, receipt artifact coverage, the persisted AGENTS.md routing rules, fallback usage, and worker category evidence. It also prints the known blind spot: direct main-thread shell output, full-file reads, chat context, and pasted prompts are outside WORKER_METRICS_FILE.
npm run codex:guard runs the local Codex audit and then stats:gate.
npm run skills:validate checks the project-specific .claude/skills/ library used to preserve project doctrine for cheaper or lower-context worker sessions.
npm run stats reports gateway token usage, receipt byte/artifact usage, and a Worker Tool Audit. npm run stats:gate -- <metrics.jsonl> turns the same thresholds into hard gates with exit code 2 on failure. Category targets are: search 80%, context_pack 70%, command_digest 70%, diff_digest 60%, review 60%, mechanical_edit 50%, history 60%, draft 80%, analysis 60%, and start must stay at or below 30% of worker calls. Gate mode also fails if required categories have no audit evidence, overall tool error rate is 5% or higher, any single tool error rate is 3% or higher after the sample floor, fallback ratio exceeds 10%, large receipt payloads lack artifact refs, or diff_digest red-team coverage falls below 30%. Tool error rate is reserved for worker/tool execution failures; shell command failures are recorded as command_status with local repair guidance, and stale job ids or invalid caller inputs are recorded as rejected.
When the MCP server is running, it also reviews recent tool error rates every 3 hours by default. A threshold breach, or a review that runs later than WORKER_TOOL_REVIEW_GRACE_MS, enables escalation self-heal defaults for later start calls: reliability_tier=strict, blocking_policy=warn, semantic_gate=warn, auto_revise=true, and at least one revise pass. Explicit start arguments still win over these defaults.
Runtime containment is more aggressive than the 3-hour review. Every tool result updates an in-memory rolling window. Real tool execution errors are classified (upstream_404, upstream_error, shell_mismatch, search_timeout, timeout, missing_command, missing_path, permission_denied, dependency_missing, or unknown_failure). Repeated errors, or any immediate-class error, open a temporary circuit. While open, unhealthy routes are intercepted as rejected instead of producing more errors; review and analyze degrade to deterministic local evidence when possible. Open circuits and a bounded rolling-event snapshot are persisted to a state sidecar file and reloaded on MCP startup or the next tool-control decision, so restarts do not immediately forget an unhealthy route or a tool already close to its circuit threshold. To keep the hot path cheap, OK outcomes are snapshotted only after WORKER_TOOL_CIRCUIT_STATE_SAVE_MIN_MS; errors and circuit opens force a save. Shell command business failures still record command_status and do not count as tool errors. On Windows, PowerShell-shaped shell commands accidentally sent through cmd.exe are retried once through powershell -NoProfile -ExecutionPolicy Bypass -Command.
Additional redundancy that is already in place:
Gate redundancy:
codex:guardcombines recent routing audit evidence withstats:gate.Route redundancy:
review/analyzecan fall back to local deterministic evidence while LLM review routes are unhealthy.Shell redundancy: shell mismatch is retried once through the matching Windows shell before surfacing failure.
State redundancy: circuit state is atomically written with a temp file plus rename, protected by a best-effort lock, guarded by a checksum, and pruned on load. Corrupt, mismatched, or expired state is ignored and rewritten instead of crashing the MCP server.
Restart redundancy: a small rolling-event snapshot is restored with open circuits so a restart does not erase tools that are already near a circuit threshold.
Efficiency guardrail: state writes are bounded by event count and save interval; lock contention skips a snapshot instead of delaying the worker.
The routing contract tests lock the core money/safety invariants:
I3: no predictive classifier call before routing.
I5: identical read-only requests hit cache; primary failure plus fallback records one successful upstream.
I6: read-only tools do not write to the workspace.
The smoke test also verifies the current tool surface: analyze, apply_edits, cancel, diff_digest, draft, get, get_artifact_slice, history, read_pack, review, search, shell, start, tail, and wait.
When To Use It
Use this worker for:
long codebase reading tasks,
scoped code edits with tests,
repeated repair loops,
cheap model summaries,
background implementation while Codex continues planning/reviewing.
Keep the main Codex thread for high-level decisions, code review, final integration, and tasks that require your most capable model directly.
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Latest Blog Posts
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/sorryorc/mcp-codex-worker'
If you have feedback or need assistance with the MCP directory API, please join our Discord server