Agentic coding CLIs stopped being a curiosity some time ago. The question now is which one you can trust with your repository — and "trust" here is a technical question, not a vibe. Can it read your code without rewriting files you did not ask it to touch? Can it run your test suite without phoning home? Can you script it in CI without handing it the keys to the machine? And when it does something, can you see exactly what it did?

Codex CLI 0.172.0 is OpenAI's answer to that checklist, and the timing matters. GPT-6.2 Sol and Astra landed in Codex on 2026-11-17 — Sol as the everyday coding model, Astra as the heavier one — and 0.172.0, released a week later, is the first version to ship with both models in the catalog, lazy startup for stdio MCP servers, and a fix so that resuming an exec session restores its sandbox permissions, working directory, and workspace roots. The pieces that make an agent safe to run unattended — sandboxing, approvals, project instructions, scripted execution — are all present, and all of them have defaults you should understand before you accept them.

This tutorial takes the tool apart in the order you will actually use it: install the pinned version, sign in, run a first interactive task, verify the sandbox with your own hands, teach it your project rules, give it extra tools, and finally script it. Every command, flag, and default below was checked against the shipped 0.172.0 binary or the official documentation on learn.chatgpt.com — and where the two disagreed, the binary wins and the disagreement is called out.

1. What you'll need#

  • Node.js 16 or later if you install through npm (the package declares node >= 16; a current LTS is the sane choice). The standalone binary needs no Node at all. This tutorial used Node v24.
  • A ChatGPT account or an OpenAI API key. Sign-in with ChatGPT works on Free, Go, Plus, Pro, Business, Enterprise, and Edu plans; GPT-6.2 Sol is rolling out to Plus, Pro, Business, Enterprise, and Edu users, while Free and Go users get GPT-6.2 Astra with weekly limits. With an API key, usage is billed to the API organization and project that owns the key.
  • A terminal and a project folder. Any small repository works for the first task — a scratch repo with a README and a few source files is ideal, because you will watch the agent edit it.
  • About 30 minutes, most of it reading the sandbox and configuration sections carefully. The install itself takes under two minutes. There is no cost to install or to run codex doctor; model usage is either covered by your ChatGPT plan's rate limits (credits first, if your plan includes them) or billed per token on an API key.

One decision to make up front: ChatGPT sign-in or API key? Sign in with ChatGPT if you already pay for a plan — it is the simplest path and keeps usage inside the plan's limits. Use an API key if you need Codex in scripts, CI, or a shared machine, or if you want usage billed to a specific organization and project. You can switch later with codex logout followed by codex login, or switch accounts with codex login and the Switch account option. The rest of this tutorial works identically either way.

2. Step 1: Install Codex CLI 0.172.0#

Pin the version. Codex ships frequently, and an unpinned npm install -g @openai/codex can silently move you to a newer release with different defaults. The changelog entry for 2026-11-24 gives the exact command:

npm install -g @openai/[email protected]

Verify the install before doing anything else:

codex --version
# codex-cli 0.172.0

If the version string says anything else, stop: you are reading the wrong binary. Two common traps: an older Codex installed by another package manager earlier in your PATH (on the machine used for this tutorial, /opt/hatch-image/bin/codex shadowed the npm install with a 0.164.0-alpha build), and npm failing to install the platform-specific optional dependency. If npm reports the install succeeded but codex fails to start, skip npm entirely and use the standalone binary from the release page — the musl build for Linux is a single 125 MB tarball that extracts to a self-contained executable:

curl -LO https://github.com/openai/codex/releases/download/rust-v0.172.0/codex-x86_64-unknown-linux-musl.tar.gz
tar -xzf codex-x86_64-unknown-linux-musl.tar.gz
./codex-x86_64-unknown-linux-musl --version
# codex-cli 0.172.0

macOS users have two more options from the project README: the installer script (curl -fsSL https://chatgpt.com/codex/install.sh | sh) or Homebrew (brew install --cask codex). Windows users run the PowerShell installer (irm https://chatgpt.com/codex/install.ps1 | iex). Whichever route you take, the verification is the same: codex --version must print codex-cli 0.172.0.

While you are here, print the help and skim it. The CLI is bigger than it looks — the subcommands include exec, review, login, mcp, plugin, app-server, remote-control, completion, update, doctor, sandbox, apply, resume, queue, archive, fork, and cloud. You will use five of them in this tutorial; the rest are for the day you want Codex to review a diff, resume a session, or run as a background server.

codex --help

3. Step 2: Sign in#

Codex supports exactly two authentication methods: sign in with ChatGPT, or sign in with an API key. Run codex login and choose:

codex login

Choosing ChatGPT sign-in opens a browser prompt: sign in and approve Codex. If you prefer not to leave the terminal, codex login --with-chatgpt does the same flow without a browser, and codex auth login is a newer alias for the same command. For an API key, use codex login --with-api-key — you can pipe a key straight in, though typing it at the prompt is safer than leaving it in shell history:

printenv OPENAI_API_KEY | codex login --with-api-key

Check what you are signed in as, and clear credentials when you are done:

codex login status
codex logout

For scripts and CI, do not sign in interactively at all. Export CODEX_API_KEY in the job environment instead. The docs are explicit on this point: do not set OPENAI_API_KEY at the job level, because the agent's shell commands can see it — and if both variables are set, Codex uses CODEX_API_KEY. That one variable name is the difference between a key the agent can spend and a key the agent's subprocesses can steal:

export CODEX_API_KEY="sk-..."
codex exec --sandbox read-only --skip-git-repo-check --json "Summarize this repo in three bullets"

Only use an API key issued by OpenAI, from platform.openai.com/api-keys. Keys from anywhere else are not supported, and a key pasted into a chat log or a shared script is a key you should rotate.

4. Step 3: Your first interactive session#

Change into your project folder and run codex with no arguments. The terminal UI opens full-screen: a prompt at the bottom, a workspace panel, and a status line showing the model and the sandbox mode. This is what the 0.172.0 splash looks like — Sol at high reasoning effort, a diff preview, and a benchmark table, all inside the terminal:

The official Codex 0.172.0 terminal splash: OpenAI Codex v0.172.0, GPT-6.2-Sol high, a code diff, and a benchmark table
The official Codex 0.172.0 splash screen, from the openai/codex repository (Apache-2.0). The status line shows the model and reasoning effort for the session.

Give it a small, verifiable task — something with an observable result, not an open-ended question. A good first task reads like a work order: what to do, where, and how to check it.

cd ~/projects/my-app
codex
Add a HEALTHCHECK section to README.md documenting the /health
endpoint: what it returns, what status codes mean, and an example
curl command. Then run the project's test suite and report the result.
Do not change any source files.

Watch what happens before you approve anything. Codex narrates its plan, reads the files it needs, and then shows you each proposed action — the command, its reason, and its arguments — before it runs. That approval prompt is the whole safety model in miniature, and it is worth reading carefully the first few times: the command is what it will execute, the reason is why it thinks it needs to, and the arguments are the blast radius.

Three slash commands run the session. /model switches models mid-session — use it to try Astra on a hard task without restarting. /sandbox shows the current sandbox mode and network status. /mcp lists the connected MCP servers (Step 7). And if you know the model you want before you start, pass it on the command line instead of relying on the catalog default:

codex --model gpt-6.2-sol
codex -m gpt-6.2-astra

Sol is the default catalog selection since 0.171.0 and the model the docs' examples select, but the docs stop short of naming it as the CLI's shipped default — pinning it explicitly costs nothing and removes the ambiguity. To make the choice permanent, set it in ~/.codex/config.toml (Step 7 covers the file):

model = "gpt-6.2-sol"

When the task is done, read the diff before you accept it. Codex shows you every change it made; accepting a diff you have not read is how an agent's plausible-looking edit becomes your bug. Use codex review from the command line later if you want the agent to review a set of changes on its own.

5. Step 4: Understand the sandbox and approvals#

This is the section most tutorials skip, and it is the one that matters most. Codex has three sandbox modes, and the default is not the strictest one:

  • read-only — the agent can only read files and run read-only commands. Nothing is written, nothing is executed that changes state.
  • workspace-write (the default for interactive sessions) — the agent can read and write files inside the workspace. Commands cannot write outside the workspace or access the network.
  • danger-full-access — the agent can read and write anywhere, execute commands, and access the network. This disables the sandbox entirely and automatically sets the approval policy to never.

The enforcement is done by the operating system, not by asking the model nicely. On macOS, Codex uses Apple's Seatbelt; on Linux, bubblewrap (bwrap) plus seccomp; Windows uses a native Windows sandbox, and WSL uses the Linux sandbox inside WSL2. (One correction to a claim that circulates about this tool: the docs do not say Linux uses Landlock. Landlock appears only as an alias of the codex sandbox subcommand, which lets you inspect or reproduce the sandbox environment.) The sandbox also applies to nested agent subprocesses — a sub-agent the main agent spawns does not escape it — but it does not apply to browser use or to MCP servers, which run outside it.

Verify the sandbox yourself instead of taking the docs' word for it. The codex sandbox subcommand runs any command inside the sandboxed environment, so you can probe it directly. Run these two probes from a terminal — no sign-in, no model call, no risk:

# Network: blocked inside the sandbox, open outside it
codex sandbox curl -s -o /dev/null -w "%{http_code}\n" https://example.com
# 000
curl -s -o /dev/null -w "%{http_code}\n" https://example.com
# 200
# Writes: blocked even inside the working directory in the bare sandbox
codex sandbox touch /tmp/probe.txt
# touch: cannot touch '/tmp/probe.txt': Read-only file system

The 000 from curl means the connection never left the machine; the 200 outside proves the network itself is fine. Read-only and workspace-write both deny network access — including local connections such as localhost — unless a command is explicitly allowlisted (the docs name npm, cargo, and git as the usual allowlist candidates). If your workflow needs the agent to run npm install or fetch a dependency, that is the moment to configure a network allowlist for that command, not the moment to reach for danger-full-access.

Approvals are the second half of the safety model, and there are only two policies in 0.172.0:

  • on-request (the default) — Codex asks for approval when an action falls outside the current sandbox or is risky. The prompt shows the command, its reason, and its arguments. Approving with "always" saves a rule to config.toml so the same action is not asked again.
  • never — Codex never asks. Use it only in a trusted environment, such as an isolated container. It requires danger-full-access.

The old untrusted policy was removed in 0.122.0 — if your configuration still uses it, remove it. Approvals persist only for the current session; after a restart, the request appears again unless you saved an approval rule. In the terminal UI these map to three visible modes: Read-only, Auto (the default — workspace-write plus on-request), and Full access (danger-full-access plus never). The flags to control all of this from the command line are -s/--sandbox and -a/--ask-for-approval:

# A locked-down session: read-only sandbox, approvals on request
codex -s read-only

# The escape hatch — only ever in an isolated container
codex --dangerously-bypass-approvals-and-sandbox

That last flag does exactly what its name says. If you find yourself typing it on your working machine because a task is awkward, stop: the awkwardness is the sandbox doing its job, and the fix is a narrower permission (an allowlisted command, an extra directory with --add-dir, a saved approval rule), not removing the sandbox.

6. Step 5: Teach it your project with AGENTS.md#

An agent with no project context guesses. AGENTS.md is the file that stops the guessing: a Markdown document that defines how Codex behaves in a project — the technology stack, the repository structure, the workflow, the commands, the style guide, and the conventions. It is loaded at the start of every session, and it is the main source of project-specific instructions Codex follows across sessions.

Codex searches for AGENTS.md in a strict precedence order, nearest file winning: the current working directory, then any parent directory, then the root of the Git repository, then the home directory (~/.codex/AGENTS.md). It also loads .codex/AGENTS.md from the project root as a fallback if no other file is found, and nested AGENTS.md files apply to their subdirectories, merged with the parent's instructions. Put project rules in the repo root and personal defaults — your shell, your editor — in the global file.

A good AGENTS.md is short and focused: role and behavior, coding standards, the commands that verify a change, and the lines the agent must not cross. The docs' own example structure, adapted for a small project, looks like this:

# Project instructions

You are working on a TypeScript service. Use npm, not yarn or pnpm.

## Commands
- Build: `npm run build`
- Test: `npm test`
- Lint: `npm run lint`

## Verification rules
- Run all verification steps when making changes: build, test, and lint.
- Run tests before creating a PR.
- Do not commit unless the user asks.
- If tests fail, fix them before submitting.

## Rules
- Never edit files under `migrations/` by hand.
- Never add dependencies without asking first.

Keep it short and include only instructions that apply to the project — the docs warn against adding instructions for a single task or repeating the prompt. A bloated AGENTS.md is worse than a short one: every line is context the model reads on every turn, and contradictory instructions are resolved in the model's favor, not yours. You can also point Codex at additional instruction files with agents.instruction_files in config.toml, or disable project-doc loading entirely with --no-project-doc or agents.load_project_doc = false when you want a clean session.

7. Step 6: Script it with codex exec#

The interactive UI is for working with the agent. codex exec is for putting it to work on its own: it takes a prompt, works through the task, and exits with the final message. It is the mode for scripts, CI, and any tool that calls Codex as a component rather than a conversation.

The defaults change when you switch modes, and the change is deliberate. By default, codex exec runs with a read-only sandbox and on-request approval, and it prints only the final message. A scripted agent that can write files and approve its own actions by default would be a liability; exec makes you opt into each capability explicitly. The shape of a run looks like this:

A four-stage workflow diagram: prompt, agent, sandbox shield, verified diff
One exec run: a prompt goes in, the agent works inside the sandbox, and a verified diff comes out. AI-generated illustration for AI Frontier Post.
# Read-only by default: safe for a first scripted run
codex exec --sandbox read-only --skip-git-repo-check \
  "Summarize this repository in three bullets: what it does, how to run it, how to test it"

When you run it, exec prints a session header — the version, the working directory, the model, the provider, the approval policy, the sandbox mode, and a session id — then works the task and exits. The exit code is part of the contract: codex exec exits non-zero if the task fails, so a script can branch on it. And note that exec is not a shell: it does not run your prompt as a command, it sends the prompt to Codex as a task.

The prompt can come from an argument or from standard input. A hyphen reads the prompt from stdin, and exec also reads additional context from stdin, so you can pipe file contents straight into a run:

# Prompt from stdin
echo "Fix the failing tests" | codex exec -

# Prompt from a file, with file contents as context
codex exec "$(cat prompt.txt)"
cat failing-test.log | codex exec --skip-git-repo-check "Explain why this test fails and propose a fix"

Use --skip-git-repo-check whenever you run outside a Git repository — without it, exec refuses to start in a non-repo directory. -C/--cd sets the working directory for the run.

For machine-readable output, add --json. It returns the thread id, token usage, and the final message as JSON, which is how you chain exec into other tools:

codex exec --json "List the three most complex files in this repo and why" \
  | jq -r '.thread_id'

Two more output flags complete the picture. -o/--output-last-message writes the final message to a file instead of printing it, and --output-schema takes a JSON Schema file and validates the final message against it — it requires --json. Together they turn an agent run into a typed step in a pipeline:

codex exec --json --output-last-message review.md \
  --output-schema schema.json \
  "Review this PR diff and return a JSON object with a verdict and a list of issues"

Sessions are saved to ~/.codex/sessions/, and you can resume one later. codex exec resume <session_id> picks up where a run left off, and --last resumes the most recent session. In 0.172.0, resuming also restores the saved sandbox permissions, working directory, and workspace roots unless you explicitly override them — before this release, a resumed session could silently come back with different permissions than the one you approved:

codex exec resume --last
codex resume --last

For an unattended run — a nightly job, a CI step — the docs' pattern is workspace-write plus never asking, so nothing blocks waiting for a human who is not there:

codex exec --sandbox workspace-write --ask-for-approval never \
  "Run the test suite, fix any failures, and write a summary to TEST-REPORT.md"

Run that only where you mean it: a workspace the agent can write to, with no secrets in reach, and with the output reviewed before it goes anywhere. The approval policy never is designed for trusted, isolated environments, and a CI runner with a checked-out repository and no credentials is exactly that environment. Your laptop is not.

8. Step 7: Give it tools with MCP servers#

Codex on its own can read files, run commands, and call the model. MCP servers extend that: they plug external tools into the agent over the Model Context Protocol, via stdio, HTTP, or SSE, with OAuth or bearer-token auth. A documentation server lets the agent fetch current API references instead of guessing them; a database server lets it query real data; a project-management server lets it read your tickets.

Servers are defined in ~/.codex/config.toml under [mcp_servers.<name>]. The docs' example wires up Context7, a documentation lookup server, as a stdio process launched through npx:

[mcp_servers.context7]
command = "npx"
args = ["-y", "@upstash/context7-mcp"]
env_vars = ["LOCAL_TOKEN"]
[mcp_servers.context7.env]
MY_ENV_VAR = "MY_ENV_VALUE"

Two details in that block are easy to get wrong. env_vars lists the environment variable names the server is allowed to access — it is a permission list, not a place to put secrets. The actual values go in the [mcp_servers.<name>.env] table. And the npx -y invocation runs the server without installing it, which keeps your global packages clean at the cost of a download on first use.

You can also add a server from the command line, which writes the same configuration for you:

codex mcp add context7 -- npx -y @upstash/context7-mcp
codex mcp list
codex mcp get context7
codex mcp test context7
codex mcp remove context7

codex mcp add also accepts a registry URL if the server is published in an MCP registry, and codex mcp login <server> starts the OAuth flow for servers that need it. Inside the terminal UI, /mcp shows the connected servers and /mcp login starts the login flow. On the machine used for this tutorial, codex mcp list showed three servers already configured — a CAD tool server, a planning inbox, and a file server — all enabled, which is the shape of a real working setup: a small number of servers, each with one clear job.

One 0.172.0 change matters here. Optional stdio MCP servers with cached tool lists now start on their first tool call by default, instead of at session startup — lazy startup, in other words. Sessions open faster and servers you never call never consume a process. If a server is slow to wake, startup_timeout_sec in its configuration controls how long Codex waits. And remember the sandbox caveat from Step 4: MCP servers run outside the sandbox. A server with filesystem or network access is a hole in the sandbox exactly as wide as that server's own permissions, so add servers the way you would add dependencies — one at a time, from sources you trust.

9. Step 8: Check its health with codex doctor#

When something is wrong — a login that will not stick, a sandbox that behaves oddly, a version mismatch — codex doctor is the first command to run. It checks the environment, the configuration, the sandbox, the MCP servers, and connectivity, and prints a report with a pass/fail line for each. Run it now, while everything is working, so you know what a healthy report looks like:

codex doctor

On a fresh machine with no sign-in yet, the report is honest about what is missing:

Codex Doctor v0.172.0 · linux-x86_64

Notes
   ✗ auth         no Codex credentials were found - Run codex login
                  or provide an API key through a supported auth env var.
   ⚠ websocket    Responses WebSocket failed; HTTPS fallback may still work

Configuration
  ✓ config       loaded
      model                    <default> · openai
      MCP servers              2
      configured TUI mode      fullscreen
  ✓ sandbox      restricted fs + restricted network · approval OnRequest

Updates
  ✓ updates      update configuration is locally consistent
      latest version           0.172.0
      latest version status    current version is not older

Three lines in that report are worth reading every time. The auth line tells you whether any credentials exist at all — on a machine you just signed in on, it should pass. The sandbox line confirms the enforcement mode (restricted fs + restricted network) and the approval policy (OnRequest) for the current configuration, so a bad config.toml edit shows up here before it shows up in a ruined repository. And the updates line tells you whether a newer version exists — codex update installs it when you are ready. Run doctor with --json if you want the report in a form a script can parse.

10. Which approach should you use?#

Codex now comes in four shapes, and the right one depends on what you are doing, not on which is newest:

  • The terminal UI (codex) is for working with the agent: exploring a codebase, iterating on a feature, reviewing diffs as they are proposed. You are present, you approve, you read the diff. This is the default, and for most developers it should stay the default.
  • codex exec is for running the agent without you: a script, a CI step, a nightly job, a tool that calls Codex and consumes its output. Read-only sandbox by default, structured output on request, non-zero exit on failure. Use it whenever the prompt is fixed and the output feeds something else.
  • Codex Web is for delegating a task and walking away: start a task in the browser, let it run in the cloud, review the result later. It suits long, self-contained work — a migration, a test-writing sweep — where you do not need the agent on your machine at all.
  • The IDE extension is for the smallest loop: a question about the file you are already looking at, a fix for the function under your cursor. It trades the terminal's full control for zero context switching.

A practical rule: if you are at the keyboard and the task is open-ended, use the terminal UI. If the task is repeatable and the output is consumed by a machine, use exec. If the task is long and you do not need to watch it, use the web app. And whichever surface you choose, the safety model is the same — sandbox, approvals, AGENTS.md — so learning it once, here, carries across all four.

11. The takeaway#

Codex CLI 0.172.0 is not a new model with a new wrapper. It is a complete working environment for an agent: GPT-6.2 Sol as the everyday model, a sandbox enforced by the operating system, approvals that ask before the risky action, project instructions that persist across sessions, MCP servers for tools the agent does not have, and a scriptable mode that turns the whole thing into a pipeline step. The install takes two minutes. The part that takes thirty is understanding the defaults — and the defaults are the point: workspace-write, on-request approval, read-only exec, and a sandbox you can verify with a single curl.

Start with the terminal UI and a small task. Read the approval prompts. Write an AGENTS.md for one project and watch how much less the agent guesses. Then, when you trust the pattern, script one repeatable job with codex exec and a JSON schema — and keep the approval policy at never strictly inside the isolated environments it was designed for. The agent is only as safe as the boundaries you set, and in 0.172.0, every boundary is yours to set.