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.

AI CLI·54 commands·Last updated 2026-08-05
codexcodex-cliopenaiaicliagentCoding Agent

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/codex
Install globally via npm (all platforms)
brew install --cask codex
Install on macOS via Homebrew
codex --version
Verify install and show version
codex login
Browser OAuth sign-in to ChatGPT
codex login --with-api-key
Read API key from stdin to log in
codex login --device-auth
Headless/SSH device-code login
codex logout
Sign out

Interactive Mode 5

codex
Start an interactive TUI session
codex "Explain this codebase"
Start the TUI with an initial prompt
codex --search "Fix the login bug"
Enable live web search
codex -i ./screenshot.png "Implement this UI"
Attach an image (comma-separate multiple)
codex --oss
Use a local open-source model (Ollama, etc.)

Non-interactive (codex exec) 5

codex exec "Fix the failing tests"
Non-interactive automation mode (alias codex e)
echo "Refactor utils" | codex exec --oss
Pipe input + local model
codex exec --json "List all API endpoints"
Output JSONL for scripting
codex exec -o result.txt "Summarize the architecture"
Save the final response to a file
codex exec --output-schema '{...}' "Extract config"
Constrain output with a JSON Schema

Session Management 5

codex resume
Resume the previous session
codex fork
Fork the previous session into a new thread
codex apply
Apply the latest diff as git apply (alias codex a)
codex --restore
Restore the previous session (some versions)
codex --history
Browse past session history

Model & Config 5

codex -m gpt-5.4 "Complex task"
Set the model (e.g. gpt-5.4 / gpt-5.4-mini)
codex -p openai "Generate a component"
Load a named config profile
codex -C /path/to/repo
Set the working root directory (--cd)
codex -c
Override config.toml values
codex completion bash
Generate bash completion script

Sandbox & Approval 8

codex -s read-only
Sandbox read-only (default, safest)
codex -s workspace-write
Sandbox can write the working directory
codex -s danger-full-access
Full access (use cautiously in containers)
codex -a untrusted
Prompt for untrusted actions (default)
codex -a never
Never approve (for read-only exploration)
codex --full-auto "Complete the implementation"
Auto-approve: workspace-write + on-failure
codex --yolo "Emergency fix"
Skip all sandbox and approvals (dangerous)
codex --dangerously-bypass-approvals-and-sandbox
Fully bypass sandbox and approvals (in containers)

MCP & Codex Cloud 7

codex mcp list
List configured MCP servers
codex mcp add -- <args...>
Add a stdio MCP server
codex mcp add --url https://example.com/mcp
Add an HTTP MCP server
codex mcp get <name>
Show server configuration
codex mcp remove <name>
Remove a server
codex cloud exec --env "task"
Submit a task to Codex Cloud
codex cloud exec --env --attempts 3 "task"
Submit a task with retry attempts (1-4)

Interactive Slash Commands 12

/clear
Reset UI and conversation
/compact
Summarize conversation to free tokens
/new
Start a fresh conversation in the same session
/fork
Clone current conversation into a new thread
/diff
Show git diff including untracked files
/status
Show session config and token usage
/init
Generate an AGENTS.md project scaffold
/review
Code review of working-tree changes
/plan
Switch to plan (read-only) mode
/model
Choose model and reasoning effort
/permissions
Set what Codex can do without asking
/exit
Quit Codex CLI

Parameter matrix

ParameterEffectExample
execRuns a one-off task in non-interactive mode (alias codex e).codex exec "fix the failing test"
--jsonEmits 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"
-cTemporarily overrides a value in config.toml.codex -c model_reasoning_effort="high"
-s read-onlyRead-only sandbox, the safest default.codex -s read-only "audit dependencies"
-s workspace-writeSandbox can write the working directory.codex --full-auto "finish the implementation"
-a neverNever pops an approval prompt; suits read-only exploration.codex -a never -s read-only
--full-autoAuto-approve: workspace-write + on-failure.codex --full-auto "finish the implementation"
--searchEnables live web search.codex --search "fix the login bug"
-i <img>Attaches images (comma-separated for several).codex -i ./shot.png "implement this UI"
--ossUses a local open-source model (Ollama, etc.).echo "refactor utils" | codex exec --oss
mcp list / get / removeManages 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

  1. 1Confirm the install and login status.

    codex --version

    First confirm the CLI is on PATH and prints a version; in headless/SSH environments complete login with codex login --device-auth.

  2. 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.

  3. 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.

  4. 4Check whether the MCP server registered successfully.

    codex mcp list

    Each listed name maps to one config; use codex mcp get <name> to see the full parameters.

  5. 5Minimal check of piped input plus a local model.

    echo "refactor utils" | codex exec --oss

    This verifies both the non-interactive input channel and local model connectivity — whichever step fails is immediately locatable.

  6. 6Generate a completion script to confirm subcommands and flags.

    codex completion bash

    Source 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 list

Everything 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 + --json with CI pipelines for codegen/review — Codex's signature use.
  • The default --full-auto auto-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