antigravity-codex-mcp
# antigravity-codex-mcp
English | [简体中文](./README.zh-CN.md)
Cross-platform [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server for orchestrating OpenAI [Codex CLI](https://github.com/openai/codex) sessions (`codex exec --json`, `resume`, `fork`, `review`) from **Antigravity** and MCP clients across **Windows and Linux**.
## Features
- **Dual Transport (`stdio` & Streamable HTTP `/mcp`)**:
- Zero-config local `stdio` transport for desktop IDE / CLI clients.
- Standard MCP **Streamable HTTP** (`/mcp`) with stateful sessions by default (idle TTL & `DELETE /mcp` cleanup) plus `--stateless` mode for intermittent connections and reverse proxies.
- **Secure-by-Default HTTP Guardrails**:
- **All** HTTP launches — including `127.0.0.1` (to protect reverse-proxy deployments) — require both **Bearer Token authentication** (`crypto.timingSafeEqual`) and **`--allowed-roots`** workspace allowlisting by default, and cap sandbox at `workspace-write`.
- Built-in `Host` and `Origin` validation against DNS rebinding, 4 MiB JSON body cap, `realpath` symlink-escape protection, and strict `resume`/`fork` origin validation (disabling `allow_unindexed` under `--allowed-roots`).
- Automatic child-process environment sanitization stripping `CODEX_MCP_AUTH_TOKEN`, `CODEX_MCP_AUTH_TOKEN_FILE`, and all `CODEX_MCP_*` variables before spawning Codex CLI.
- **Async Job Orchestration & Cross-Process Safety**:
- Bounded long-polling (`wait_seconds <= 55`) with replayable event cursors (`seq > cursor`) and truncation metadata.
- Cross-process atomic `session_id` locks (`O_CREAT | O_EXCL`) paired with unique `instance_id` heartbeat leases (preventing concurrent writes across windows/processes and avoiding bare PID-reuse false positives).
- Atomic per-job directory persistence with terminal job retention pruning and graceful `SIGINT`/`SIGTERM` process-tree shutdown (Windows `taskkill /T /F` & POSIX process groups `SIGTERM -> SIGKILL`).
- **JSON Schema Output Validation**: Validates structured final output with Ajv and returns field-level errors while preserving raw output.
- **Bundled Antigravity Plugin**: Includes a ready-to-install plugin (`antigravity-plugin/`) with manifest, icon, prefixed MCP config, and orchestration `SKILL.md`.
---
## Requirements
- **Node.js** `>= 20.0.0`
- **Codex CLI** (`codex`) installed and authenticated on the host machine
## Quick Start
### Build from Source
```bash
npm install
npm run typecheck
npm run build
npm test
```
### Mode 1: Local `stdio` (Desktop Antigravity / MCP Clients)
```json
{
"mcpServers": {
"antigravity-codex": {
"command": "node",
"args": ["/absolute/path/to/antigravity-codex-mcp/dist/index.js"],
"env": {
"CODEX_CLI_COMMAND": "codex"
}
}
}
}
```
Or install the bundled Antigravity plugin from [`antigravity-plugin/`](./antigravity-plugin/README.md).
### Mode 2: Streamable HTTP (Remote / Multi-Client over HTTPS)
Store a strong random token outside your workspaces (e.g. `chmod 600 /etc/codex-mcp/token` or `C:\ProgramData\codex-mcp\token`), then start the HTTP server behind an HTTPS reverse proxy:
```bash
node dist/index.js \
--transport http \
--host 127.0.0.1 \
--port 8765 \
--auth-token-file /etc/codex-mcp/token \
--allowed-roots /path/to/projects \
--allowed-hosts mcp.example.com
```
For clients behind reverse proxies or intermittent networks, add `--stateless` so requests do not depend on in-memory HTTP sessions (jobs and Codex sessions remain persisted on the server).
See [`docs/deployment.md`](./docs/deployment.md) for Caddy/Nginx HTTPS reverse-proxy templates, Linux `systemd` units, OS/container isolation guidance, and remote HTTP client setup.
---
## Exposed Tools (12)
| Tool | Description |
| :--- | :--- |
| `codex_run` | Start a new async Codex session (`codex exec --json`) with optional `model`, `reasoning_effort`, and bounded wait (`<= 55s`). |
| `codex_resume` | Resume an existing session by `session_id`, `job_id`, or `use_last: true` with strict identity verification, optional `reasoning_effort`, and cross-process session lock. |
| `codex_fork` | Fork an existing session (`session_id` or `job_id`) into a brand-new session with optional `reasoning_effort`. |
| `codex_review` | Run non-interactive code review (`uncommitted`, `base`, `commit` + optional `title`, or custom `prompt`) with optional `reasoning_effort`. |
| `codex_poll` | Bounded long-poll (default `wait_seconds = 55`, `wait_mode = "terminal"`, `include_events = false`) with replayable `cursor`, `events_count`, and truncation reporting. |
| `codex_result` | Fetch final structured result (returns `ready: false` without blocking while active). |
| `codex_cancel` | Cancel an active job process tree (atomic against completion, retryable on kill failure). |
| `codex_list_jobs` | List active and recent MCP jobs (newest first) for cross-window / reconnect `job_id` recovery. |
| `codex_list_workspaces` | List allowed workspace roots/subdirectories (or recent dirs in unrestricted `stdio`) with Git branch and dirty status. |
| `codex_list_sessions` | List merged local (`$CODEX_HOME/sessions`) and MCP sessions (`source="both"` matches both `local` and `mcp`). |
| `codex_get_session` | Inspect session metadata and recent user/assistant turns. |
| `codex_health` | One-shot preflight & health check: verifies Codex CLI, active `backend` (`cli` / `app-server`) and `app_server_state`, concurrency/policy caps, allowlisted default model/reasoning/profiles, cached models, and optional `cwd`/`model`/`reasoning_effort` readiness (`ready`, `errors`, `warnings`). |
---
## Security Threat Model & Boundaries
- **Trusted Single-Owner Positioning**: HTTP mode is designed for **trusted multi-client access by the same machine owner** (e.g., your own Windows and Linux workstations over HTTPS + Bearer token).
- **What `--allowed-roots` Protects**: `--allowed-roots` and `--max-sandbox` are **MCP control-plane guardrails**. They strictly constrain `cwd`, `images`, `codex_list_workspaces` candidates (pre-Git `realpath` check), session/job visibility, and `resume`/`fork` source + target directories (with `allow_unindexed` disabled).
- **What `--allowed-roots` Does NOT Guarantee**: Even under `workspace-write`, Codex CLI's OS sandbox may still permit reading files outside `cwd` depending on the host OS and Codex configuration. If you require strict filesystem read isolation for remote callers, run the MCP server under a **dedicated OS user account** with restrictive filesystem ACLs or inside a **container** mounting only the permitted project directories, and verify using a sentinel file outside the mounted directory (see [`docs/deployment.md`](./docs/deployment.md)).
- **Token Hygiene**: `CODEX_MCP_*` environment variables are stripped from all Codex child processes, and startup fails if `--auth-token-file` resides inside `--allowed-roots`. Always keep token files outside workspaces with OS-level read restrictions.
---
## CLI Flags & Environment Variables
Precedence: **CLI flags > Environment variables > Transport-aware defaults**.
| CLI Flag | Env Variable | Default (`stdio` / `http`) |
| :--- | :--- | :--- |
| `--transport <stdio\|http>` | `CODEX_MCP_TRANSPORT` | `stdio` |
| `--host <addr>` | `CODEX_MCP_HOST` | `127.0.0.1` |
| `--port <num>` | `CODEX_MCP_PORT` | `8765` |
| `--path <route>` | `CODEX_MCP_HTTP_PATH` | `/mcp` |
| `--stateless` | `CODEX_MCP_STATELESS` | `false` |
| `--session-ttl-sec <sec>` | `CODEX_MCP_SESSION_TTL_SEC` | `3600` |
| `--auth-token <token>` | `CODEX_MCP_AUTH_TOKEN` | unused / **required** |
| `--auth-token-file <path>` | `CODEX_MCP_AUTH_TOKEN_FILE` | unused / **required** (alt) |
| `--allow-unauthenticated-http` | `CODEX_MCP_ALLOW_UNAUTHENTICATED_HTTP` | `false` (loopback dev opt-in only) |
| `--allow-unauthenticated-network` | `CODEX_MCP_ALLOW_UNAUTHENTICATED_NETWORK` | `false` (dangerous opt-in) |
| `--allowed-hosts <csv>` | `CODEX_MCP_ALLOWED_HOSTS` | loopback + bind host |
| `--allowed-origins <csv>` | `CODEX_MCP_ALLOWED_ORIGINS` | loopback origins |
| `--allowed-roots <paths>` | `CODEX_MCP_ALLOWED_ROOTS` | unrestricted / **required** |
| `--allow-any-cwd` | `CODEX_MCP_ALLOW_ANY_CWD` | `false` (dev opt-in only) |
| `--max-sandbox <mode>` | `CODEX_MCP_MAX_SANDBOX` | unrestricted / `workspace-write` |
| `--max-concurrent-jobs <n>` | `CODEX_MCP_MAX_CONCURRENT_JOBS` | `4` |
| `--max-retained-jobs <n>` | `CODEX_MCP_MAX_RETAINED_JOBS` | `500` |
| `--codex-command <cmd>` | `CODEX_CLI_COMMAND` | `codex` |
| `--backend <cli\|app-server>` | `CODEX_MCP_BACKEND` | `cli` (`app-server` lazy-spawns persistent `codex app-server --stdio`; falls back to `cli` for differing per-call `profile` or `review`+`output_schema`) |
| `--default-profile <name>` | `CODEX_MCP_DEFAULT_PROFILE` | unset (no `-p` flag) |
| `--default-model <model>` | `CODEX_MCP_DEFAULT_MODEL` | unset (official Codex CLI default) |
| `--default-reasoning-effort <lvl>` | `CODEX_MCP_DEFAULT_REASONING_EFFORT` | unset (official Codex CLI default) |
| `--state-dir <dir>` | `CODEX_MCP_STATE_DIR` | `~/.codex-mcp-state` |
## License
[MIT](./LICENSE)
TDQS
Scored across 12 tools
Most tools target clearly distinct operations: run (new session), resume, fork, review, poll, result, cancel all have specific roles clarified by descriptions. Minor overlap exists between codex_list_sessions and codex_list_jobs (both enumerate session/job records, with sessions merging both sources) and between codex_resume and codex_fork (both accept session_id or job_id), but the descriptions draw the lines adequately.
All tools share a consistent `codex_` prefix with a predictable verb_noun convention (codex_run, codex_resume, codex_poll, codex_list_sessions, codex_get_session). A couple of names are noun-only (codex_health, codex_result) rather than verb-led, a minor deviation from the otherwise uniform pattern.
Twelve tools is well within the ideal range and each maps to a distinct facet of the async job/session lifecycle. The set is cleanly organized into job control (run/poll/result/cancel), session management (resume/fork/list/get), plus review, health, and workspace listing, so no tool feels redundant.
The surface covers the full async lifecycle (start, poll, result, cancel), session continuation (resume, fork, list, get), review, and environment introspection (health, workspaces). Minor gaps remain: no session/job cleanup or deletion, no way to change default config (only read it via health), and no content-based session search.