Codex CLI Cheatsheet - Install, exec & Approvals
Codex CLI is OpenAI official open-source terminal coding agent (Rust) for developers driving GPT-family models to edit code, run tests, and manage approvals directly in a repo — and for CI engineers adopting AI codegen/review. Unlike cloud chat it adds fine-grained sandbox (read-only/workspace-write/full-access) and approval policies, plus headless codex exec --json for pipelines. This sheet covers install/login, non-interactive execution, and the sandbox trade-offs.
Typical Use Case
For engineers wiring AI coding capability into development and CI. The distinction to make first is between the interactive TUI, good for exploration and paired editing, and codex exec, the non-interactive mode that belongs in pipelines. Three areas matter most: structured output through --json, -o and --output-schema so scripts can consume results; the four combinations of sandbox and approval settings, chosen by risk level; and adding, removing and listing MCP servers so internal tools reach the model. Session handling is included too, because resuming or forking a prior thread beats restating the background every time.
Install & Auth 7
npm install -g @openai/codexbrew install --cask codexcodex --versioncodex logincodex login --with-api-keycodex login --device-authcodex logoutInteractive Mode 5
codexcodex "Explain this codebase"codex --search "Fix the login bug"codex -i ./screenshot.png "Implement this UI"codex --ossNon-interactive (codex exec) 5
codex exec "Fix the failing tests"echo "Refactor utils" | codex exec --osscodex exec --json "List all API endpoints"codex exec -o result.txt "Summarize the architecture"codex exec --output-schema '{...}' "Extract config"Session Management 5
codex resumecodex forkcodex applycodex --restorecodex --historyModel & Config 5
codex -m gpt-5.4 "Complex task"codex -p openai "Generate a component"codex -C /path/to/repocodex -ccodex completion bashSandbox & Approval 8
codex -s read-onlycodex -s workspace-writecodex -s danger-full-accesscodex -a untrustedcodex -a nevercodex --full-auto "Complete the implementation"codex --yolo "Emergency fix"codex --dangerously-bypass-approvals-and-sandboxMCP & Codex Cloud 7
codex mcp listcodex mcp add -- <args...>codex mcp add --url https://example.com/mcpcodex mcp get <name>codex mcp remove <name>codex cloud exec --env "task"codex cloud exec --env --attempts 3 "task"Interactive Slash Commands 12
/clear/compact/new/fork/diff/status/init/review/plan/model/permissions/exitParameter matrix
| Parameter | Effect | Example |
|---|---|---|
exec | Runs a one-off task in non-interactive mode (alias codex e). | codex exec "fix the failing test" |
--json | Emits JSONL for easy script parsing. | codex exec --json "list all API endpoints" |
-o <file> | Writes the final answer to a file. | codex exec -o result.txt "summarize the architecture" |
--output-schema <json> | Constrains output structure with a JSON Schema. | codex exec --output-schema '{}' "extract config" |
-m <model> | Specifies the model. | codex -m gpt-5.4-mini "complex task" |
-C <dir> | Sets the working root directory (--cd). | codex -C /path/to/repo |
-p <profile> | Loads a named config profile. | codex -p openai "generate a component" |
-c | Temporarily overrides a value in config.toml. | codex -c model_reasoning_effort="high" |
-s read-only | Read-only sandbox, the safest default. | codex -s read-only "audit dependencies" |
-s workspace-write | Sandbox can write the working directory. | codex --full-auto "finish the implementation" |
-a never | Never pops an approval prompt; suits read-only exploration. | codex -a never -s read-only |
--full-auto | Auto-approve: workspace-write + on-failure. | codex --full-auto "finish the implementation" |
--search | Enables live web search. | codex --search "fix the login bug" |
-i <img> | Attaches images (comma-separated for several). | codex -i ./shot.png "implement this UI" |
--oss | Uses a local open-source model (Ollama, etc.). | echo "refactor utils" | codex exec --oss |
mcp list / get / remove | Manages configured MCP servers. | codex mcp list |
mcp add --url <url> | Adds an HTTP-type MCP server. | codex mcp add --url https://example.com/mcp |
cloud exec --attempts <n> | Submits a Codex Cloud task with a retry count (1-4). | codex cloud exec --attempts 3 "task" |
Common pitfalls
SymptomAn automation script gets no model answer, only empty output or a blob of human-readable text.
CauseInteractive mode (TUI) prints answers to the terminal UI and leaves no structured exit for a non-human caller.
FixSwitch to codex exec --json and parse JSONL line by line; when you need plain text, use -o file to write it to a file and read that back.
SymptomThe task stalls midway waiting for confirmation, or dependency installs fail in an environment without network.
CauseThe default sandbox is read-only and the approval mode confirms each step; network access is disabled inside the sandbox.
FixRun --full-auto when you need to install dependencies; consider --yolo only in a trusted environment, and prefer -a never -s read-only for pure read-only research.
SymptomThe task only ever "talks" without doing — no file is modified.
CauseYou are in plan/read-only exploration mode or the sandbox is read-only, so write requests are refused outright.
FixExit read-only mode before running anything beyond /plan; during the execution phase switch to -s workspace-write or --full-auto.
SymptomYou have to restate the project background and coding conventions every time.
CauseThe session is stateless; the conventions were never written to disk.
FixWrite the project conventions into AGENTS.md at the repo root or under ~/.codex/, and Codex merges and loads them automatically.
SymptomLong sessions get slower and slower, burn tokens fast, and answer quality drops.
CauseThe conversation history keeps accumulating with no compaction.
FixSummarize and compact with /compact in-session, or reset with /clear; /status shows current usage first.
SymptomAn MCP server is attached but does not appear in the tool list.
CauseThe server config is missing, the name is misspelled, or the session needs reloading.
FixUse codex mcp list to confirm it is registered and codex mcp get <name> to inspect the config, then /new to start a fresh session and reload the tools.
SymptomFiles are changed but not under version control, and review is a mess.
CauseWorkspace changes were never taken through a git flow; /diff only shows the diff and does not commit.
FixUse /diff in-session to see the scope of changes, then commit yourself; you can also apply the latest diff as a git apply via codex apply.
Troubleshooting
1Confirm the install and login status.
codex --versionFirst confirm the CLI is on PATH and prints a version; in headless/SSH environments complete login with
codex login --device-auth.2Write the full answer of a one-off task to a file for review.
codex exec -o /tmp/result.txt "summarize the architecture"Read /tmp/result.txt afterwards to confirm the model actually produced content rather than failing silently.
3Make the output directly consumable by scripts.
codex exec --json "list all API endpoints"Output is JSONL; json.loads each line. In a pipeline, be careful not to mix in non-JSON banner text.
4Check whether the MCP server registered successfully.
codex mcp listEach listed name maps to one config; use
codex mcp get <name>to see the full parameters.5Minimal check of piped input plus a local model.
echo "refactor utils" | codex exec --ossThis verifies both the non-interactive input channel and local model connectivity — whichever step fails is immediately locatable.
6Generate a completion script to confirm subcommands and flags.
codex completion bashSource the emitted completion script into the current shell, then use Tab completion to confirm which subcommands and flags the installed version supports.
Command Examples
Run headless and emit JSON
codex exec --json "list all API endpoints in the project"
codex exec -o endpoints.txt "summarize the architecture"codex exec (alias codex e) is the de facto non-interactive standard; --json emits JSONL and -o saves the final answer to a file.
Output
{"findings":{"endpoint_count":23,"categories":[...]}}
(the final answer is also written to endpoints.txt; JSONL is easy for CI to parse)Fully auto-complete an implementation
codex --full-auto "add unit tests for the payment module; look at the existing test style before making changes"--full-auto by default equals a workspace-write sandbox + on-failure approval — safe and low-friction, the everyday default.
Output
(The model reads and writes the working directory on its own inside the network-disabled sandbox, exiting the sandbox to ask only when it needs the network to install dependencies.)
Explore a large repo read-only
codex -a never -s read-only "what is the build process and dependency topology of this project"Good for auditing, research, and understanding historical evolution; if you need to write files, switch back to workspace-write and add approval.
Output
(Read-only mode can read files across the whole system without making changes or popping confirmations.)
Add a stdio MCP server
codex mcp add -- npx -y @modelcontextprotocol/server-github
codex mcp listEverything after __ is passed to the server verbatim, letting the model call repository/tool interfaces directly in the session.
Output
Added MCP server "server-github" (stdio)
Common Pitfalls
- --dangerously-bypass-approvals-and-sandbox and --yolo skip all sandbox and approvals so the model can modify the system and run any command — only in isolated/throwaway environments.
- Only -a never + -s read-only is truly read-only; -a never alone can still let the model edit files in the working directory.
- Permission rules written into AGENTS.md make Codex follow team conventions by default but also lock in behavior — confirm impact before editing memory files.
- codex exec runs unattended with no human approvals, so side-effecting commands rely on the sandbox to bound scope (workspace-write), not on -a prompts.
Tips
- For non-interactive automation always use
codex exec+--jsonwith CI pipelines for codegen/review — Codex's signature use. - The default
--full-autoauto-approves inside a network-disabled sandbox: safe and hands-off; it only exits the sandbox to ask when it needs network (e.g. npm install). - Put project conventions in AGENTS.md (repo root or ~/.codex/); Codex merges and loads them automatically — more efficient than repeating them in prompts.
- For read-only exploration use
-a never -s read-only: no prompts yet full file read access, ideal for audits/research.
FAQ
What is the difference between codex exec and plain codex?
codex is the interactive TUI with a human in the loop; codex exec is non-interactive, takes one instruction, finishes and exits, which is what you want in scripts and CI. Add --json for JSONL output that programs can parse, -o result.txt to save the final answer, and --output-schema to constrain the shape with a JSON Schema. Never drive automation through the interactive mode.
How should I combine sandbox and approval modes safely?
The sandbox (-s) sets filesystem reach: read-only is safest, workspace-write allows edits in the current directory, danger-full-access removes all limits. Approval mode (-a) decides when it stops to ask: untrusted confirms each action, never never asks. For production prefer workspace-write with untrusted; for read-only exploration use read-only with never; only consider full access inside a container.
How do I resume a session or branch off from one?
codex resume picks up the previous session, while codex fork derives a new thread from it — the difference is that fork creates an independent branch and leaves the original intact. Inside a session, /fork clones the current conversation, /new starts a fresh conversation within the same session without clearing history, and /compact summarizes the conversation to free tokens while keeping context.
How do I use local open-source models with Codex CLI?
Add --oss, which routes to open-source models through a local runtime such as Ollama; combined with codex exec --oss it works without network access. Choose a model with -m, for example -m gpt-5.4 or -m gpt-5.4-mini. Local models are generally weaker than frontier ones, so keep online models for complex refactors.
How do I make Codex output conform to a JSON Schema?
codex exec --output-schema '...' "task" constrains the output structure with a JSON Schema, which is what you want when a downstream program must parse it. Add --json for line-delimited JSON or -o result.txt to write the final answer straight to a file. Schema constraints are far more reliable than asking for JSON in the prompt.
Official References
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Aug 5, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us