OpenAI Codex CLI Complete Guide 2026: Terminal AI Coding Assistant from Installation to Production-Grade Configuration
OpenAI Codex CLI is a terminal-based AI coding assistant launched by OpenAI in mid-2025. It brings powerful code generation capabilities directly into the command-line environment. As the core product competing against Anthropic's Claude Code, Codex CLI has quickly become an essential tool in developers' toolkits for 2026, thanks to its open-source and free nature, sandbox security model, MCP protocol integration, and flexible Profile configuration system.
What Is Codex CLI?
More Than Just "ChatGPT in the Terminal"
Many developers who first encounter Codex CLI simply think of it as "ChatGPT running in the terminal." But that view seriously underestimates its design depth. Codex CLI is a complete interactive Code Agent. It doesn't just understand natural language instructions—it can also:
- Read project context: Automatically analyze the file structure, dependencies, and code style of the current directory
- Execute multi-step tasks: Form a complete workflow from requirements analysis to code implementation to test verification
- Sandbox isolation: Use three-tier sandbox modes and four-level approval policies to ensure AI operations won't damage your system
- Session persistence: Support session recovery, fork experiments, and history tracking so you never lose work progress
Core Architecture Design
Codex CLI is built with Rust and uses a modular architecture:
codex-cli/
├── core/ # Core engine: model calls, context management
├── sandbox/ # Sandbox layer: filesystem isolation, command execution limits
├── mcp/ # MCP protocol integration: external tool connections
├── config/ # Configuration system: Profile management, alias resolution
└── ui/ # Interactive interface: TUI, slash command parsing
This design keeps Codex CLI lightweight while providing enterprise-grade security and extensibility. Compared to traditional IDE plugins, its advantages include:
- No editor binding: Whether you prefer Vim, Emacs, or VS Code, you can use it seamlessly in the terminal
- Remote-friendly: Runs smoothly on SSH-connected servers or inside Docker containers
- Low resource usage: The Rust-built binary starts fast and uses far less memory than Electron apps
Installation and Basic Configuration
Four Installation Methods
1. npm Install (Recommended for Most Users)
npm install -g @openai/codex
This is the most universal installation method, suitable for macOS, Linux, and Windows (WSL2). After installation, run codex --version to confirm success.
2. Homebrew Install (Preferred for macOS Users)
brew install --cask codex
Homebrew installation automatically handles dependencies and PATH configuration. Upgrading is as simple as brew upgrade codex.
3. Binary Download
Visit GitHub Releases to download precompiled binaries for your platform:
- macOS Apple Silicon:
codex-macos-arm64 - macOS Intel:
codex-macos-x86_64 - Linux x86_64:
codex-linux-x86_64 - Linux ARM64:
codex-linux-arm64 - Windows:
codex-windows-x86_64.exe
After downloading, grant execute permission and move to a PATH directory:
chmod +x codex-linux-x86_64
sudo mv codex-linux-x86_64 /usr/local/bin/codex
4. WSL2 Install (For Windows Users)
Native Windows support is still being improved. We recommend installing via WSL2 (Windows Subsystem for Linux):
# Inside WSL2 Ubuntu
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
npm install -g @openai/codex
Authentication: ChatGPT Subscription vs API Key
Codex CLI supports two authentication methods, each suited for different scenarios:
ChatGPT Subscription Login (Best for Individual Users)
If you have a ChatGPT Plus, Pro, Team, Edu, or Enterprise subscription, you can log in directly through your browser:
codex login
This opens your default browser. After completing OAuth authorization, the token is saved automatically. Perks for subscribers:
- Plus users: $5/month free API credit (30-day rolling)
- Pro users: $50/month free API credit (30-day rolling)
Usage beyond the free credit is billed at standard API pricing.
API Key Environment Variable (Best for Teams/Automation)
For team collaboration or CI/CD integration, we recommend using an API Key:
export OPENAI_API_KEY="sk-proj-xxxxxxxxxxxxxxxxxxxxxxxx"
Add this line to ~/.bashrc or ~/.zshrc to make it permanent. You can create and manage API Keys on the OpenAI Platform.
Security tip: Never hardcode API Keys in code repositories. Use .env files or a secrets management service instead.
System Requirements and Pre-flight Checks
Before installing, make sure your system meets these requirements:
| Component | Minimum Version | Recommended Version |
|---|---|---|
| Node.js | 18.x | 20.x LTS |
| npm | 9.x | 10.x |
| Git | 2.x | 2.40+ |
| OS | macOS 12+/Ubuntu 20.04+/WSL2 | Latest stable |
Run these commands to check prerequisites:
node --version # Should output v18.x or higher
npm --version # Should output 9.x or higher
git --version # Should output git version 2.x
If your Node.js version is too low, visit the Node.js official site to download and install the latest LTS release.
Three Operation Modes Explained
Codex CLI offers three operation modes, each corresponding to a different level of automation and security:
suggest Mode (Safest)
codex --mode suggest
In suggest mode, Codex only provides code suggestions and explanations. It will not automatically modify any files. You need to manually copy the suggested code and apply it to your project.
Use cases: - Learning a new framework and wanting to understand the reasoning behind each step - Reviewing sensitive code changes that require manual confirmation - First-time Codex users getting familiar with its output style
Example:
$ codex --mode suggest
> Create a React Todo component
[CODEx] I suggest creating the following file structure:
- src/components/TodoList.jsx
- src/components/TodoItem.jsx
- src/hooks/useTodos.js
Here is the content for TodoList.jsx:
[code block...]
You can manually create these files, or switch to auto-edit mode to let me write them automatically.
auto-edit Mode (Balanced)
codex --mode auto-edit
auto-edit is the default mode. Codex automatically edits files but requests confirmation before executing commands that may have side effects (like rm or git push).
Use cases: - Daily development workflows - Needing AI to iterate code quickly while retaining approval rights for critical operations - Refactoring medium-complexity projects
Example:
[CODEx] I will create src/components/TodoList.jsx... ✓
[CODEx] I will create src/components/TodoItem.jsx... ✓
[CODEx] I need to run npm install react-icons. Continue? [Y/n]
full-auto Mode (Fastest)
codex --mode full-auto
In full-auto mode, Codex executes everything automatically, including file edits and command runs, without any confirmation. This is the most efficient but also the riskiest mode.
Use cases: - Isolated development environments (e.g., Docker containers) - When you fully trust Codex's judgment and want maximum efficiency - Batch code generation tasks
Warning: Before using full-auto in production, be sure to configure sandbox mode to limit its permission scope.
Deep Dive into the Sandbox Security Model ⭐ Key Differentiator
The sandbox is Codex CLI's core security mechanism. It isolates filesystem and command execution permissions to prevent AI mistakes or malicious behavior from damaging your system. Understanding the sandbox model is key to using Codex in production.
Comparing Three Sandbox Modes
Codex offers three-tier sandbox modes, specified via the --sandbox parameter:
| Mode | Filesystem Permissions | Command Execution | Use Case |
|---|---|---|---|
read-only |
Read-only; no writes allowed | Allows read-only commands (ls, cat, grep) | Code review, document analysis |
workspace-write |
Write allowed only in current project directory | Allows normal commands; blocks system-level operations | Daily development (recommended) |
danger-full-access |
Full read/write access | Allows all commands | Isolated environments, experimental tasks |
Default mode: workspace-write, balancing security and convenience.
read-only Mode in Action
codex --sandbox read-only
> Analyze this project's architecture
[CODEx] Reading src/ directory structure...
[CODEx] Found the following modules:
- auth/ (authentication)
- api/ (REST API)
- components/ (UI components)
Since I'm in read-only mode, I cannot modify files. To refactor, please switch to workspace-write mode.
workspace-write Mode (Recommended)
codex --sandbox workspace-write
> Refactor the auth module, add JWT refresh tokens
[CODEx] I will modify src/auth/token.js... ✓
[CODEx] I will create src/auth/refresh.js... ✓
[CODEx] Running tests to verify changes... ✓
In this mode, Codex can only modify files within the current working directory and its subdirectories. It cannot access system directories like /etc or /usr.
danger-full-access Mode (Use with Caution)
codex --sandbox danger-full-access
> Clean up all node_modules directories
[CODEx] Warning: This operation will delete multiple directories. Confirm? [Y/n]
Only use in these scenarios: - Temporary environments inside Docker containers - Dedicated sandbox virtual machines - When you fully trust Codex's judgment and have backed up important data
Four-Level Approval Policy Granularity
Beyond sandbox modes, Codex provides fine-grained command approval policies controlled via the --ask-for-approval parameter:
| Policy | Behavior | Use Case |
|---|---|---|
untrusted |
Only untrusted commands require approval (default) | Daily development |
on-failure |
Request approval only when a command fails | Debugging scenarios |
on-request |
Approve only when Codex explicitly requests | High trust in AI |
never |
Never request approval | Used with sandbox |
Definition of untrusted commands:
- Network operations (curl, wget)
- Package management (npm install, pip install)
- Version control (git push, git reset --hard)
- System configuration (sudo, chmod)
Combination Examples
# Safest combo: read-only sandbox + strict approval
codex --sandbox read-only --ask-for-approval untrusted
# Efficient combo: workspace write + approve on failure
codex --sandbox workspace-write --ask-for-approval on-failure
# Fully automatic combo: dangerous sandbox + never approve (isolated environments only)
codex --sandbox danger-full-access --ask-for-approval never
The Essential Difference Between --full-auto and --yolo
Many users confuse --mode full-auto with the --yolo parameter. They operate at different levels:
--mode full-auto: Controls whether Codex needs user confirmation for code edits--yolo: Skips all approval prompts for command execution (equivalent to--ask-for-approval never)
# These two commands have the same effect
codex --mode full-auto --yolo
codex --mode full-auto --ask-for-approval never
Naming origin: "Yolo" comes from the popular phrase "You Only Live Once." In tech communities, it often means "execute without considering consequences." OpenAI uses this humorous name to remind users: this mode carries risks, so use it cautiously.
Security Best Practices for Production Environments
When using Codex CLI in production, follow these security guidelines:
- Default to
workspace-writesandbox: Restrict AI to modifying only current project files - Enable Git integration: Auto-commit every AI modification for easy rollback
- Regularly review Transcripts: Codex records all interactions and operation logs
- Manually execute sensitive operations: Don't hand over critical steps like database migrations or production deployments to AI
- Use Profiles to isolate environments: Configure different security policies for different projects
# Production project config example
codex --profile production --sandbox workspace-write --ask-for-approval untrusted
# Experimental project config example
codex --profile experimental --sandbox danger-full-access --yolo
All 24 Slash Commands Explained ⭐ Key Differentiator
Codex CLI provides 24 slash commands covering session control, model switching, permission management, file operations, and more. Mastering these commands significantly boosts productivity.
Session Control (/new, /resume, /fork, /compact)
/new - Start a New Session
/new
Clears the current context and starts a fresh conversation. Useful when switching tasks or clearing historical interference.
/resume - Restore a Previous Session
/resume
Opens an interactive session selector listing all historical sessions, with filtering by date and directory. See the "Session Recovery" section below for details.
/fork - Fork an Experiment
/fork
Creates a copy of the current session. Try different solutions in the new branch without affecting the main session. Great for:
- Comparing multiple implementation approaches
- Experimental refactoring that can be easily discarded if it fails
- Parallel exploration of different architectural designs
> /fork
[CODEx] Created session branch fork-2026-06-07-14-30
> Try replacing Context API with Redux
[CODEx] In the branch, I will refactor state management...
/compact - Compress Context
/compact
When session history becomes too long and token usage spikes, use /compact to compress the context. It retains key information and clears redundant conversations, effectively reducing costs for subsequent calls.
Model and Style (/model, /personality, /plan)
/model - Switch Models
/model gpt-5
Switch the model in use at runtime. Available models include:
gpt-5.3-codex(default, optimized for code)gpt-5(general flagship model)o4-mini(lightweight reasoning model, lower cost)
> /model o4-mini
[CODEx] Switched to o4-mini model. This model is suitable for simple tasks. It has weaker reasoning ability but lower cost.
/personality - Adjust AI Personality
/personality concise
Adjust Codex's response style:
concise: Brief and direct, minimal explanationverbose: Detailed explanations, great for learningprofessional: Formal tone, suitable for documentationfriendly: Casual and friendly, good for daily chat
/plan - Generate an Execution Plan
/plan
Ask Codex to output a detailed execution plan before implementing. Ideal for complex tasks, helping you spot potential issues early.
> /plan
> Refactor the entire auth module, add OAuth2 support
[CODEx] Execution plan:
1. Analyze existing auth/ directory structure
2. Design OAuth2 flow (Authorization Code Grant)
3. Create oauth2/ submodule
4. Modify login endpoint to support both traditional passwords and OAuth2
5. Update test cases
6. Generate migration documentation
Start execution? [Y/n]
Permissions and Status (/permissions, /status, /debug-config)
/permissions - View Current Permissions
/permissions
Displays the current sandbox mode and approval policy configuration.
> /permissions
[CODEx] Current permission config:
- Sandbox: workspace-write
- Approval Policy: untrusted
- Yolo Mode: disabled
/status - View Session Status
/status
Shows detailed session information, including:
- Model and reasoning level in use
- Token usage statistics
- Session duration
- Number of operations executed
> /status
[CODEx] Session status:
- Model: gpt-5.3-codex (reasoning: high)
- Tokens: 12,450 input / 3,200 output
- Duration: 45 minutes
- Operations: 23 file edits, 8 commands executed
/debug-config - Diagnose Configuration Loading Chain
/debug-config
This is the ultimate tool for troubleshooting configuration issues. It shows how Codex loads configuration files, including:
- Global config path (
~/.codex/config.toml) - Project config path (
.codex/config.toml) - Environment variable overrides
- Profile activation status
- Final effective configuration values
> /debug-config
[CODEx] Configuration loading chain:
1. Global config: /home/user/.codex/config.toml ✓
2. Project config: /path/to/project/.codex/config.toml ✓
3. Environment variables: OPENAI_API_KEY set ✓
4. Active Profile: production
5. Final Config:
- model: gpt-5.3-codex
- sandbox_mode: workspace-write
- approval_policy: untrusted
Files and Tools (/mention, /diff, /review, /mcp)
/mention - Reference a Specific File
/mention src/auth/token.js
Force Codex to focus on a specific file, even if it's not in the current context. Useful for locating key files in large projects.
/diff - View Change Diffs
/diff
Shows the diff of all file changes since the session started. Helps you review whether AI modifications match your expectations.
/review - Code Review
/review
Ask Codex to review recent code changes, pointing out potential issues, performance bottlenecks, and security risks.
> /review
[CODEx] Code review report:
✓ Strengths:
- Correctly uses async/await for async operations
- Added comprehensive error handling
⚠ Suggestions for improvement:
- token.js line 45: Missing input validation, could lead to injection attacks
- refresh.js line 12: HttpOnly flag not set, XSS risk present
🔴 Critical issues:
- Hardcoded JWT secret; should use environment variables
/mcp - Manage MCP Servers
/mcp list
Lists configured Model Context Protocol (MCP) servers. MCP allows Codex to connect to external tools like GitHub, databases, and monitoring platforms. See the "MCP Protocol Integration" section below for details.
Other Useful Commands
| Command | Function |
|---|---|
/init |
Initialize project config, create .codex/config.toml |
/feedback |
Send feedback to OpenAI |
/logout |
Log out and clear authentication tokens |
/quit |
Exit Codex CLI |
/statusline |
Customize terminal status bar display |
/ps |
View background-running tasks |
/apps |
Manage integrated applications |
Session Recovery: Never Lose Work Progress Again ⭐ Key Differentiator
Session recovery is one of Codex CLI's most underrated features. In traditional terminal tools, closing the terminal means losing all context. Codex achieves session persistence and flexible recovery through its Transcripts mechanism.
Four Recovery Methods
1. Interactive Selector (Recommended)
codex resume
Opens an interactive interface listing all historical sessions, supporting:
- Sorting by date
- Filtering by directory
- Keyword search
- Session summary preview
$ codex resume
Select a session to restore:
1. [2026-06-07 14:30] refactor auth module (12 ops)
2. [2026-06-07 10:15] create React todo app (8 ops)
3. [2026-06-06 16:45] debug API endpoint (5 ops)
> 1
[CODEx] Restored session: refactor auth module
2. Restore the Most Recent Session
codex resume --last
Quickly restores the most recently used session without interactive selection. Ideal for continuing work after an interruption.
3. Restore a Specific Session
codex resume <SESSION_ID>
Precisely restore a session by its ID. You can find the session ID in the /status command output or in the Transcripts directory.
codex resume sess_abc123def456
4. Cross-Directory Restore All Sessions
codex resume --all
Lists historical sessions across all directories. Useful when switching between multiple projects.
What Gets Preserved During Recovery?
When restoring a session, Codex rebuilds the following state:
- Conversation history: All previous Q&A records
- File context: List of files read and modified
- Model configuration: Model and reasoning level in use
- Sandbox permissions: Current security configuration
- Unfinished tasks: If a multi-step task was in progress, it continues from the breakpoint
What is NOT preserved: - Temporary variables or unsaved intermediate results - Execution state of external commands (e.g., running servers)
Practical Use Case Examples
Scenario 1: Continue After Interruption
# Morning: start refactoring the auth module
$ codex
> Refactor auth module, add JWT refresh tokens
[CODEx] Analyzing existing code...
# Suddenly need to attend a meeting, Ctrl+C to exit
# Afternoon: come back and resume directly
$ codex resume --last
[CODEx] Session restored. Last time we analyzed auth/token.js. Next, I will create refresh.js...
Scenario 2: Compare Multiple Approaches
# Main session: using Context API
$ codex
> Implement state management
[CODEx] I will use Context API...
# Fork experiment: try Redux
> /fork
[CODEx] Branch created. Now trying Redux approach...
# After comparison, decide to keep the main session and discard the branch
Scenario 3: Incremental Development of Long-Term Projects
# Day 1: Set up project skeleton
$ codex
> Create Next.js project structure
[CODEx] Done...
# Day 2: Resume session, continue development
$ codex resume --last
[CODEx] Welcome back. Yesterday we created the project structure. Today, let's continue implementing page components...
Production-Grade Configuration ⭐ Key Differentiator
Codex CLI's configuration system is highly flexible, supporting global config, project config, and Profile-based multi-scenario configuration. Proper configuration significantly improves both productivity and security.
Alias Configuration: One Command for Startup Parameters
For commonly used startup parameter combinations, you can simplify commands with shell aliases:
# ~/.bashrc or ~/.zshrc
alias codex-safe='codex --sandbox read-only --ask-for-approval untrusted'
alias codex-dev='codex --sandbox workspace-write --mode auto-edit'
alias codex-yolo='codex --sandbox danger-full-access --yolo'
Then use:
codex-safe # Safe review mode
codex-dev # Daily development mode
codex-yolo # Experimental mode (use with caution!)
Profile Multi-Scenario Configuration (More Elegant Solution)
Aliases are simple but lack flexibility. Codex's Profile system lets you define multiple scenarios in a config file and switch with a single --profile parameter.
Configuration File Structure
The global config file is at ~/.codex/config.toml. The project config file is at .codex/config.toml.
# ~/.codex/config.toml
# Default configuration
model = "gpt-5.3-codex"
model_reasoning_effort = "high"
web_search = "live"
sandbox_mode = "workspace-write"
approval_policy = "untrusted"
# Profile: Code Review (read-only, strict approval)
[profiles.review]
sandbox_mode = "read-only"
approval_policy = "untrusted"
model_reasoning_effort = "medium"
# Profile: Quick Prototype (lightweight model, low cost)
[profiles.quick]
model = "o4-mini"
model_reasoning_effort = "low"
web_search = "disabled"
sandbox_mode = "workspace-write"
# Profile: Production (security first)
[profiles.production]
sandbox_mode = "workspace-write"
approval_policy = "on-failure"
model = "gpt-5.3-codex"
model_reasoning_effort = "high"
# Profile: Experimental (fully automatic, high risk)
[profiles.experimental]
sandbox_mode = "danger-full-access"
approval_policy = "never"
model = "gpt-5.3-codex"
model_reasoning_effort = "high"
Using Profiles
# Code review scenario
codex --profile review
# Quick prototype scenario
codex --profile quick
# Production project
codex --profile production
# Experimental project
codex --profile experimental
Project-Level Config Override
Create .codex/config.toml in the project root to override global config:
# my-project/.codex/config.toml
# This project enforces read-only sandbox
sandbox_mode = "read-only"
# This project disables web search
web_search = "disabled"
Codex's config loading priority: Project Config > Profile Config > Global Config > Defaults.
debug-config to Diagnose Configuration Loading Chain
When config isn't taking effect as expected, use /debug-config to diagnose:
> /debug-config
[CODEx] Configuration loading chain:
1. Global config: /home/user/.codex/config.toml ✓
- model: gpt-5.3-codex
- sandbox_mode: workspace-write
2. Project config: /path/to/project/.codex/config.toml ✓
- sandbox_mode: read-only (overrides global config)
3. Active Profile: review
- approval_policy: untrusted
4. Environment variables:
- OPENAI_API_KEY: set ✓
- CODEX_MODEL: not set
5. Final Config:
- model: gpt-5.3-codex (from global config)
- sandbox_mode: read-only (from project config, higher priority)
- approval_policy: untrusted (from Profile)
This output clearly shows the source of each config value, helping you quickly pinpoint issues.
Model Switching and Reasoning Levels
Default Model: gpt-5.3-codex
Codex CLI defaults to the gpt-5.3-codex model, a variant specifically optimized by OpenAI for code generation. Its features include:
- Strong code understanding: Deep knowledge of multiple programming languages and frameworks
- Large context window: Supports analysis of long files and complex project structures
- High reasoning efficiency: Reasoning paths optimized for code tasks
Runtime Model Switching
Switch models via the /model command or config file:
# Switch to general flagship model
/model gpt-5
# Switch to lightweight model
/model o4-mini
Model use cases:
| Model | Use Case | Cost |
|---|---|---|
gpt-5.3-codex |
Complex code generation, refactoring, debugging | High |
gpt-5 |
General tasks, documentation, architecture design | High |
o4-mini |
Simple tasks, quick prototypes, low-cost scenarios | Low |
Reasoning Level Strategy (high/medium/low)
Reasoning Effort controls how deeply the model thinks before generating a response:
| Level | Behavior | Use Case | Token Usage |
|---|---|---|---|
high |
Deep analysis, multi-step reasoning | Complex algorithms, architecture design, tricky bugs | High |
medium |
Balanced speed and quality | Daily development, routine refactoring | Medium |
low |
Fast response, shallow reasoning | Simple tasks, syntax fixes, template generation | Low |
Set in config file:
model_reasoning_effort = "high" # or "medium", "low"
Switch at runtime:
> /reasoning high
[CODEx] Switched to high reasoning level. Subsequent responses will involve deeper analysis.
Cost Optimization: Save Half Your Tokens in a Month
Using models and reasoning levels wisely can significantly reduce costs:
-
Use o4-mini + low reasoning for simple tasks:
bash codex --profile quick # Uses o4-mini + low -
Reserve gpt-5.3-codex + high reasoning for complex tasks:
bash codex --profile production # Uses gpt-5.3-codex + high -
Regularly use /compact to compress context: Clears redundant conversation history
-
Leverage ChatGPT subscription credits: Plus/Pro users' free credits are used first
-
Avoid unnecessary web searches: Set
web_search = "disabled"to reduce extra calls
Estimated savings:
- Shifting 50% of simple tasks from gpt-5.3-codex + high to o4-mini + low saves about 60-70% in token costs
- Combined with subscription credits, individual users can keep monthly costs within $10-20
MCP Protocol Integration: Connecting External Tools
Model Context Protocol (MCP) is an open protocol proposed by Anthropic that allows AI assistants to connect to external tools and data sources. Through MCP integration, Codex CLI can access GitHub, databases, monitoring platforms, and other external resources, greatly expanding its capabilities.
What Is MCP?
MCP's core idea: AI assistants shouldn't be limited to their own knowledge—they should access real-time data from external systems. Through MCP servers, Codex can:
- Read GitHub repository Issues and Pull Requests
- Query PostgreSQL database records
- Fetch Sentry error logs
- Access Slack channel messages
Configuring GitHub/Sentry/Database MCP Servers
Configure MCP servers in ~/.codex/config.toml:
[mcp_servers]
# GitHub MCP server
github = { command = "npx", args = ["-y", "@modelcontextprotocol/server-github"] }
# PostgreSQL MCP server
postgres = { command = "npx", args = ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"] }
# Sentry MCP server
sentry = { command = "npx", args = ["-y", "@modelcontextprotocol/server-sentry"] }
# Filesystem MCP server (extends sandbox capabilities)
filesystem = { command = "npx", args = ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"] }
In Practice: Extending Codex with MCP
Scenario 1: Analyze a GitHub Issue
codex --mcp github
> Analyze recent bug reports in repo:openai/codex
[CODEx] Querying via GitHub MCP...
[CODEx] Found 5 recent bug reports:
1. #123: Session restore fails on Windows
2. #124: Sandbox permission leak in workspace-write mode
3. ...
I will analyze issue #123 in detail...
Scenario 2: Query a Database
codex --mcp postgres
> Query recently registered users from the users table
[CODEx] Executing query via PostgreSQL MCP...
[CODEx] Results:
- user_id: 1001, email: alice@example.com, created_at: 2026-06-07
- user_id: 1002, email: bob@example.com, created_at: 2026-06-06
Scenario 3: Troubleshoot Sentry Errors
codex --mcp sentry
> Analyze critical errors from the last 24 hours
[CODEx] Querying via Sentry MCP...
[CODEx] Found 3 critical errors:
1. TypeError: Cannot read property 'token' of undefined (auth/token.js:45)
2. ...
Suggested fix: Add null checks before accessing the token property...
Viewing and Managing MCP Servers
# List configured MCP servers
/mcp list
# Enable/disable specific servers
/mcp enable github
/mcp disable postgres
# Check server status
/mcp status
Codex CLI vs Claude Code: Comprehensive Comparison
Both Codex CLI and Claude Code are leading terminal AI coding assistants. Each has its strengths and weaknesses. Here's a comprehensive comparison:
Feature Comparison Table
| Dimension | Claude Code | Codex CLI |
|---|---|---|
| Custom Config | Supports status bar, prompts, output styles | Profile multi-scenario config, fine-grained reasoning control |
| Visual Context | Supports image input | Supports Ctrl+V image paste |
| Session Management | Session recovery, background tasks | /resume, /fork, Transcripts logging |
| Security | Built-in security review | Three-tier sandbox + four-level approval granularity |
| Special Modes | Vim mode | --yolo fully automatic (dangerous mode) |
| MCP Integration | Native support | Integrated via config file |
| Open Source | Closed source | Open source (Apache 2.0) |
| Model Selection | Claude models only | gpt-5.3-codex, gpt-5, o4-mini |
| Community Ecosystem | Anthropic official support | GitHub 39K+ Stars, active community |
Pricing Comparison
| Item | Claude Code | Codex CLI |
|---|---|---|
| Tool itself | Free | Free (open source) |
| Subscription fee | Claude Pro $20/month | No fixed monthly fee |
| API fees | Included in Pro subscription | Billed per API usage |
| Free credit | Pro subscription unlimited use | Plus: $5/month, Pro: $50/month |
| Overage billing | None (Pro unlimited) | Per OpenAI API pricing |
Cost estimates: - Light users (1-2 hours/day): Codex CLI ~$5-15/month (using subscription credits), Claude Pro $20 - Medium users (3-5 hours/day): Codex CLI ~$20-50/month, Claude Pro $20 - Heavy users (6+ hours/day): Codex CLI ~$50-150+/month, Claude Pro $20
How to Choose?
Choose Codex CLI if: - You prefer open-source tools and transparent configuration systems - You need fine-grained control over model selection and reasoning levels - Your projects involve frequent model switching (e.g., lightweight models for simple tasks) - You value sandbox security and session recovery features - You're budget-conscious and want to reduce costs via subscription credits
Choose Claude Code if: - You're already a Claude Pro subscriber - You prefer a mature, stable product experience - You don't need frequent model switching - You value Anthropic's official support and ecosystem integration
Hybrid strategy: Many developers install both tools and choose based on the scenario: - Daily development with Claude Code (stable, hassle-free) - Complex refactoring with Codex CLI (multi-model, fine-grained control) - Cost-sensitive tasks with Codex CLI (leverage subscription credits)
Frequently Asked Questions
"command not found" Error After Installation
Cause: The npm global install directory is not in your PATH.
Solution:
# Find where codex is installed
which codex
# If not found, check npm global directory
npm config get prefix
# Add that directory's bin subdirectory to PATH
echo 'export PATH=$(npm config get prefix)/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
Node.js Version Too Low
Cause: Codex CLI requires Node.js 18.x or higher.
Solution:
# Check current version
node --version
# If below 18.x, upgrade to LTS
# macOS
brew install node@20
# Ubuntu
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
# Using nvm (recommended)
nvm install 20
nvm use 20
Invalid API Key
Cause: API Key format error, expired, or insufficient permissions.
Solution:
1. Confirm API Key format: should start with sk-proj- or sk-
2. Check Key status on OpenAI Platform
3. Confirm your account has sufficient balance or subscription credits
4. Re-export the environment variable:
bash
export OPENAI_API_KEY="sk-proj-your-correct-key"
How to Use Codex CLI in China?
Network issues: Codex CLI needs to access the OpenAI API. Direct connections from China may be unstable.
Solutions:
1. Use a proxy: Configure HTTP_PROXY environment variable
bash
export HTTP_PROXY=http://your-proxy:port
export HTTPS_PROXY=http://your-proxy:port
2. Use a relay service: Some cloud providers offer API relay services
3. Local model deployment: Combine with local model tools like Ollama (requires modifying Codex config)
Account issues: Registering an OpenAI account may require an overseas phone number or email.
Payment issues: ChatGPT subscriptions require an international credit card or gift card.
How to Handle Git Warnings?
Symptom: Git-related warnings appear when running Codex.
Cause: Git is not installed or user info is not configured.
Solution:
# Install Git
# macOS
brew install git
# Ubuntu
sudo apt install git
# Configure user info
git config --global user.name "Your Name"
git config --global user.email "your@email.com"
# Initialize repo (if in a project directory)
git init
Summary and Quick Start in Three Steps
OpenAI Codex CLI represents the latest direction in terminal AI coding assistants. It's not just a code generation tool—it's a complete development platform integrating security sandboxes, session management, MCP integration, and production-grade configuration.
Core Value Recap
- Security first: Three-tier sandbox modes + four-level approval policies ensure controllable AI operations
- Flexible configuration: Profile system supports one-click switching between multiple scenarios
- Session persistence: /resume and /fork ensure work progress is never lost
- Ecosystem expansion: MCP protocol connects GitHub, databases, and other external tools
- Cost optimization: Multi-model selection + reasoning level control for on-demand usage
Quick Start in Three Steps
Step 1: Install and Authenticate
npm install -g @openai/codex
codex login # Or use API Key
Step 2: Choose a Security Mode
# Recommended for beginners: safe review mode
codex --sandbox read-only
# Daily development: workspace write mode
codex --sandbox workspace-write
Step 3: Start Your First Task
codex
> Create a simple Express.js API with a GET /health endpoint
[CODEx] I will create the following files:
- package.json
- server.js
- routes/health.js
Executing... ✓
Next Steps and Learning Resources
- Official docs: developers.openai.com/codex
- GitHub repo: github.com/openai/codex
- IDE integration guide: developers.openai.com/codex/ide
- API pricing details: openai.com/api/pricing
- Community discussion: GitHub Issues and Reddit r/OpenAI
Whether you're a seasoned developer or new to AI programming, Codex CLI can significantly enhance your workflow. Start today and let AI become your pair programming partner right in your terminal!
Related reading: - Aider Complete Guide 2026: Open-Source AI Pair Programming in the Terminal - Claude Code CLI Complete Guide 2026 - OpenCode CLI In-Depth Review 2026