Codex CLI no OpenAI key: use your own key
TL;DR: codex asks for an OpenAI account when it finds no key. The CLI reads its provider from ~/.codex/config.toml and keeps credentials in ~/.codex/auth.json — export the two variables below and it runs without an OpenAI account.
export OPENAI_BASE_URL="https://api.codegateway.dev/v1"
export OPENAI_API_KEY=sk-cg-…
codex login --skip
codex "What does this repo do?"No OpenAI key — or no foreign card? Get one here and paste it into the export above.
Codex CLI 451: unsupported region error
TL;DR: HTTP 451 (unsupported region) means the request was refused for your region — not a problem with your key or quota. Point the CLI at the /v1 endpoint below and retry the same command.
export OPENAI_BASE_URL="https://api.codegateway.dev/v1"
export OPENAI_API_KEY=sk-cg-…
codex login --skip
codex "What does this repo do?"No OpenAI key — or no foreign card? Get one here and paste it into the export above.
Codex CLI 401 unauthorized: missing key or base_url path
TL;DR: A 401 = missing key in this shell; a 451 = wrong endpoint. Export the key again in the active shell, and keep the /v1 path on the base URL.
export OPENAI_BASE_URL="https://api.codegateway.dev/v1"
export OPENAI_API_KEY=sk-cg-…
codex login --skip
codex "What does this repo do?"No OpenAI key — or no foreign card? Get one here and paste it into the export above.
Codex CLI timeout: requests hang or time out
TL;DR: Retry once, then check the endpoint URL and the key in the active shell — the same three lines below clear the two common causes.
export OPENAI_BASE_URL="https://api.codegateway.dev/v1"
export OPENAI_API_KEY=sk-cg-…
codex login --skip
codex "What does this repo do?"No OpenAI key — or no foreign card? Get one here and paste it into the export above. Full triage: connection timeout fixes.
One command installs the CLI, but the setup that actually decides whether Codex works is `config.toml`. This guide covers all three install paths (npm, winget, brew), the config.toml keys that matter, how to point Codex at an OpenAI-compatible endpoint with your own key, and the three errors that stop a first run — so you go from install to a working first task in one sitting.
No official OpenAI key — or you'd rather not bind a foreign card? Get one here and paste it straight into config.toml.
Related guides: pricing and key cost · project rules with AGENTS.md · MCP server setup · connection timeout fixes · CodeGateway compliance matrix
⚠️ Unofficial community guide. For official docs see platform.openai.com. Need a stable API proxy for Codex? → CodeGateway Codex Hub
Table of contents
- Why Codex CLI matters in 2026
- Codex CLI install (npm / winget on Windows / macOS)
- Configure Codex: config.toml base_url, model, reasoning effort
- The model picker
- Reasoning effort
- Subagents
- MCP servers
- Hooks and auto-review
- Codex Cloud
- Screenshots and image input
- Computer use
- When codex says "451: unsupported region"
- Codex CLI vs Claude Code
- FAQ
Codex CLI install (npm / winget on Windows / macOS)
TL;DR: Install Codex CLI with npm install -g @openai/codex on any platform, or winget install OpenAI.Codex on Windows, then verify with codex --version.
The detailed commands are in the npm & winget install section; the file layout and provider fields are in the config.toml reference.
Quick links: a one-click config.toml starter on the setup page, the Codex CLI docs page for the full config reference, and the “451: unsupported region” section below if install reports that error.
Codex CLI ships as an npm package, with macOS / Linux / Windows (PowerShell + WSL) installers.
# Option A — npm (works everywhere with Node 18+)
npm install -g @openai/codex
# Option B — Homebrew (macOS)
brew install openai/tap/codex
# Option C — winget (Windows)
winget install OpenAI.CodexFirst run:
codex login
# Opens browser → ChatGPT/OpenAI account → returns access token
codex "What does this repo do?"A few practical notes from the field:
- Codex stores credentials at
~/.codex/auth.json. Keep that file out of dotfile repos. - The CLI auto-detects your project's package manager, lockfile, and test runner — you don't need a
.codexconfig to start. - If
codex logintimes out (common behind corporate proxies), setOPENAI_API_KEYdirectly and skip the OAuth flow.
Finished installing? Bookmark two internal guides: Codex CLI install and config error troubleshooting covers auth.json, config.toml and MCP failures (including 451 region errors); the tier pricing guide explains per-model cost after install. Still choosing an agent? Codex CLI vs Claude Code.
Configure Codex: config.toml base_url, model, reasoning effort
If you cannot get an OpenAI API key — no supported payment method in your region, or an account that never clears review — Codex CLI does not have to go without. CodeGateway issues an OpenAI-compatible key, and the CLI points at it the same way it points at OpenAI: export OPENAI_BASE_URL=https://api.codegateway.dev/v1 and put the CodeGateway key in the OPENAI_API_KEY slot. Your prompts, MCP servers and AGENTS.md all keep working unchanged. Sign up at CodeGateway, create a pay-as-you-go key, and paste it in as your provider key; billing is per token with no monthly minimum. Rates are published on the pay-as-you-go API pricing page, so you can estimate a month's spend before you commit.
Confirm with codex --version, then set the model and gateway URL in ~/.codex/config.toml. The config.toml reference below lists the exact keys. If you would rather not hand-write that file, the config generator fills in the model, the provider and the base URL in ~/.codex/config.toml, so the key stays in your environment.The project rules Codex loads alongside this config are covered in AGENTS.md load order and 32 KiB cap.
Verify your first Codex CLI call
TL;DR: Run codex "What does this repo do?" and check the request in your usage log. A 401 = missing key in this shell; a 451 = wrong endpoint.
中文速览:Codex CLI 怎么装、怎么配,451 与 unsupported_country_region_territory 怎么处理
Codex CLI 装三条命令,按系统挑一条:Windows 用 winget install OpenAI.Codex,macOS / Linux 用 npm install -g @openai/codex(Node 18+)。npm install -g 报 EACCES、或装完提示 command not found,都是全局目录权限与 PATH 的问题,见本页 FAQ。
配置都在 ~/.codex/config.toml,首次运行后生成:model 选模型;[model_providers.<name>] 段写 base_url 与 env_key(也可用 OPENAI_BASE_URL / OPENAI_API_KEY 环境变量);MCP 写成 [mcp_servers.<name>] 表(command + args)。
两类地区报错要分清。451: unsupported region 是 OpenAI 按地区拒绝请求,要改指兼容端点(provider 段 + base_url + env_key)。unsupported_country_region_territory 是上游出口对本次请求的瞬态拒绝,HTTP 503 带 Retry-After:请几秒后重试;若持续失败,请改用其他服务商的模型。
没有官方 Key,也不想绑定海外信用卡 —— 直接在这里拿一个。注册并创建 API Key
首次调用一般三步:注册 → 建 Key(sk-cg-…,明文只显示一次,系统只存哈希)→ 粘进上面那两行配置 → 发一条消息。
常见问题
Q:codex cli install 用什么命令?
A:三选一——Windows 用 winget install OpenAI.Codex;macOS / Linux 用 npm install -g @openai/codex(Node 18 及以上);macOS 用 brew install openai/tap/codex。装完用 codex --version 确认。
Q:codex cli winget 装不上怎么办?
A:先确认 PowerShell 里 winget 是否可用(系统缺 App Installer 时需要升级,或改走 npm 路线)。走 npm 路线若报 EACCES,说明 npm 全局目录归 root 所有:换 nvm / fnm 管理 Node,或 npm config set prefix ~/.npm-global 并把 ~/.npm-global/bin 加进 PATH。
Q:装好 Codex CLI 之后怎么指向自己的 API 端点?
A:在 ~/.codex/config.toml 的 [model_providers.<name>] 段写 base_url 与 env_key 并导出对应变量,或直接设 OPENAI_BASE_URL 与 OPENAI_API_KEY 两个环境变量。指向 CodeGateway 时 base_url 用 https://api.codegateway.dev/v1。
Q:Codex CLI 报 451 unsupported region 怎么处理?
A:451 是 OpenAI 按地区拒绝请求,不是 config.toml 写错,重跑 codex login 也无效。把 CLI 指向 OpenAI 兼容端点(provider 段写 base_url + env_key)后开新会话,prompt、MCP 服务器与 AGENTS.md 照旧可用。
Q:unsupported_country_region_territory 报错是什么意思?
A:上游出口对本次请求的瞬态拒绝,HTTP 503 并带 Retry-After。这通常是上游出口的瞬态拒绝,也可能是该服务商不服务你的客户端所在地区。请几秒后重试;若持续失败,请改用其他服务商的模型。
Why Codex CLI matters in 2026
When OpenAI relaunched Codex in mid-2025 it was, frankly, a slimmer version of Claude Code with a nicer install story. That stopped being true sometime around the GPT-5.5 release on 2026-04-23, when OpenAI made Codex the default surface for the new model and shipped a stack of features that closed the agentic-coding gap: subagents, MCP, auto-review, hooks, remote cloud tasks, and image input — all wired together in a single CLI.
Today the headline numbers (from OpenAI's own dev keynote and the Codex changelog):
- 4 million weekly active developers on Codex across CLI / IDE / ChatGPT / Codex Cloud
- GPT-5.5 routed by default, with GPT-5.3-Codex as an agentic-coding-tuned snapshot, GPT-5.4-mini for fast subagent work, and GPT-5.3-Codex-Spark for sub-second latency
- Chat Completions API is deprecated inside Codex — every new feature ships on the Responses API
Whether you prefer Codex over Claude Code is a separate question (see the comparison at the end). What's no longer defensible is dismissing Codex as "just an OpenAI wrapper" — in 2026 it is a peer.
The model picker
codex lets you switch models mid-session with /model. The 2026 line-up:
Model | Best for | Typical latency | Notes |
|---|---|---|---|
GPT-5.5 | General work, implementation, refactors, debugging | 8–25 s/turn | Default since 2026-04-23 — frontier coding model, lowest token output of the family |
GPT-5.4 | Flagship "professional work" model; fallback when 5.5 is still rolling out | 8–20 s/turn | GA. Combines GPT-5.3-Codex coding strength with stronger reasoning and tool use |
GPT-5.4-mini | Subagents, responsive coding, anything cost/latency sensitive | 3–8 s/turn | GA. The model to wire into subagents — cheap, fast, capable enough |
GPT-5.3-Codex | Long-running agentic loops, multi-file refactors, eval runs | 12–40 s/turn | Snapshot model, Responses API only. Powers GPT-5.4 internally |
GPT-5.3-Codex-Spark | Inline completion, "feels like an IDE" workflows | < 1 s/turn (1000+ tokens/s) | Research preview, ChatGPT Pro only. Text-only; capability < GPT-5.5 but near-instant |
GPT-5.2 | Hard debugging that benefits from deeper deliberation | 15–35 s/turn | Previous-generation, still available. Useful as a fresh second-opinion model |
A rough rule of thumb after a few weeks of dogfooding:
- Default to GPT-5.5. Frontier model since 2026-04-23, strictly better than GPT-5.4 on most coding tasks.
- Wire GPT-5.4-mini into your subagents. Lower cost + lower latency makes it the sweet spot for the child agents the parent spawns.
- Reach for GPT-5.3-Codex when handing the agent a multi-hour autonomous task — purpose-tuned snapshot for sustained agentic loops.
- Pin Codex-Spark for
codex --watchstyle inline edits where latency dominates UX (ChatGPT Pro account required). - Fall back to GPT-5.2 for the kind of deep-debugging task that benefits from a second model with deliberative reasoning.
OpenAI's published benchmark claim is that GPT-5.5 produces ~72% fewer output tokens than Claude Opus 4.7 on the same coding task. We measured something similar in our own internal harness over two weeks: median output 41% smaller, p95 output 68% smaller. That partially neutralises Opus's per-token price advantage and is one reason routing layers like Cursor and Cline increasingly pick GPT-5.5 by default.
Reasoning effort
Independent of model, every Responses-API call accepts a reasoning_effort parameter:
low— fast, minimal chain-of-thought. Use for simple edits, formatting, lint fixes.medium— balanced. The default forcodexinteractive sessions.high— for complex agentic tasks. Slower, more accurate.xhigh— research-grade. Token budget can be 10×+ medium. Use for eval runs and the hardest async work.
In the CLI you can override per-turn:
codex --reasoning xhigh "Find every place in the repo that mutates user state without a lock and propose a fix."Or for a whole session:
codex
> /reasoning high
> Now refactor the billing module to use the new pricing types.Practical tip: xhigh is wonderful in eval scripts and miserable in interactive sessions. Don't leave it on.
Subagents
The 2026 Codex CLI ships a native subagent primitive. From inside a codex session:
> /spawn "audit the test suite for flaky tests and report which ones share a fixture"
> /spawn "look up the latest stripe API for subscription updates and write a migration plan"
> /spawn "review the diff against our coding-standards.md and list violations"Each spawn launches an independent agent with its own context window. Results stream back into the parent session. This is the single most useful 2026 addition for anyone running large refactors — a parent agent can fan out work, gather structured reports, and decide what to act on without burning its own context on intermediate exploration.
A worked example — finding tech debt across a Django monorepo:
codex
> /spawn "list every file under apps/billing that imports from apps.legacy and write the import graph to /tmp/legacy-graph.txt"
> /spawn "grep for raw SQL strings that bypass the ORM in apps/billing and apps/payments, output to /tmp/raw-sql.txt"
> /spawn "for each test that takes more than 5 seconds, output test name + likely cause, write to /tmp/slow-tests.txt"
> Now read all three reports and propose a 3-week migration plan we can take to engineering review.Three subagents fan out in parallel, the parent consumes the three files, then plans against the consolidated picture. Total wall-clock time on our test repo: 6 minutes 12 seconds. The equivalent single-session run took 18 minutes and timed out twice.
MCP servers
Codex CLI is a first-class Model Context Protocol client. The 2026 release added an MCP submenu in the composer and /mcp install <name> shortcuts that match the syntax of Claude Code and Cursor.
Wire up a server:
# Add an MCP server from a published registry
codex mcp install github
# Add a custom server pointing at a local binary
codex mcp add notion --command "/usr/local/bin/notion-mcp"
# List active servers
codex mcp listInside a session:
> /mcp connect github
> Find the open PRs in our repo touching apps/billing and summarise the review status.Codex routes the tool calls through the configured MCP server, returns structured results, and (depending on reasoning_effort) decides whether to act on them or ask the user. The mental model is identical to Claude Code MCP, the syntax is identical, and most servers built for one client work in the other without changes.
Hooks and auto-review
Hooks in Codex CLI let you fire shell commands on lifecycle events: pre-commit, post-edit, pre-push, pre-spawn. The config lives at .codex/hooks.toml in the project root:
[[hooks]]
event = "pre-commit"
command = "pnpm run lint:fix"
description = "Auto-fix lint before any Codex-driven commit"
[[hooks]]
event = "post-edit"
command = "pnpm test -- --findRelatedTests $CODEX_EDITED_FILES"
description = "Run related tests after every edit"Auto-review is a separate but related feature. Setting auto_review = true in .codex/config.toml spawns a second Codex agent — using a different model snapshot if you want — to review every diff before it gets staged or pushed.
[auto_review]
enabled = true
reviewer_model = "gpt-5.4"
block_on_severity = "high"The reviewer reads the diff, your coding-standards.md (if present), and any project-local conventions, then either approves silently or blocks with a structured report. Practical experience: leaving this on catches roughly 1 in 8 commits that would have introduced a regression. The cost is non-trivial (every commit eats a Pro-level inference) but for shared codebases it pays back fast.
Codex Cloud
For long-running tasks that you don't want to hold open on your laptop:
codex cloud launch "Migrate the entire test suite from jest to vitest. Diff back when done."
# → Returns a task URL you can monitor in browser or via `codex cloud status <id>`
codex cloud status fc-7a2b
# → Streams logs, shows partial diff
codex cloud apply fc-7a2b
# → Applies the final diff to your local working treeThree things to know:
- Codex Cloud tasks run on OpenAI-provisioned VMs with isolated sandboxes. Your repo is mirrored at launch; nothing else on disk is visible.
- The default environment matches your local language/runtime (detected from lockfiles). For custom toolchains, ship a
.codex/cloud-env.yaml. - You can chain Cloud tasks into
codex execfor scripted workflows — useful for nightly maintenance runs.
This is the feature that pushed our infra team from "Codex is OK" to "we keep four nightly Codex Cloud jobs running" — refactors that used to need a dedicated half-day now happen overnight.
Screenshots and image input
Codex CLI 2026 accepts image attachments inline:
codex --image ~/Desktop/figma-export.png "Build a React component that matches this layout. Match Tailwind class names used elsewhere in the repo."In an interactive session:
> /attach ~/screenshots/error-modal.png
> Why is the alignment off? The CSS is in components/ui/Modal.tsx.Codex passes the image to the vision-capable GPT-5.5 inference and reads it alongside the text prompt. We've used this for three workflows:
- Design-to-code: paste a Figma export, get a first-cut React/Vue/Svelte implementation that matches existing repo conventions.
- Bug screenshots: attach the broken state, point Codex at the file, ask for the fix.
- Whiteboard photos: surprisingly good at parsing hand-drawn system diagrams into Mermaid syntax.
Quality is good but not magic. Expect to iterate; treat the first pass as a starting structure.
Computer use
GPT-5.5 ships computer-use as a first-class Responses-API primitive — the model can drive a sandboxed browser, click buttons, fill forms, read pages, and report back. In Codex CLI:
codex compute "Log in to the GitHub admin for whitedit/code-gateway with the saved session, find the PR #1230 review thread, copy any unresolved comments to /tmp/pr-1230-tasks.md"Computer use runs inside an OpenAI-managed isolated browser. Sessions are persisted (optionally) and you can scope which sites the agent can navigate to via a deny-list in .codex/computer-use.toml. It is not a replacement for Playwright in your test pipeline, but for ad-hoc "go and do this in a web UI" tasks it removes the need to context-switch.
When codex says "451: unsupported region"
A subset of users see HTTP 451: unsupported_country_region_territory when calling OpenAI from certain regions or transit networks. That comes from the upstream/compliance side — not your key or your quota. Retry first to check whether it is transient (the gateway answers upstream transient rejections with 503 + Retry-After, and the SDK retries automatically); only then switch model or egress. A gateway gives you a reachable API endpoint and unified billing; it does not change upstream region decisions.
CodeGateway exposes the Responses API at https://api.codegateway.dev/v1/responses with the same payload schema as OpenAI's endpoint. To redirect Codex CLI:
# Either set the env var
export OPENAI_BASE_URL="https://api.codegateway.dev/v1"
# Or pin it per-session
codex --base-url https://api.codegateway.dev/v1 "Refactor the auth module."Authentication uses the same OPENAI_API_KEY slot — populate it with a CodeGateway key generated at the dashboard. New accounts get a starting credit after binding a card (current amount on the signup/pricing page), billed per token at OpenAI's published rates with a flat 1.07× markup. See tier pricing details.
Three details that catch first-time users:
- Codex's OAuth flow (
codex login) does not work via a proxy — use the API-key path instead. codex cloudtasks run server-side on OpenAI infrastructure; the base-URL override applies only to your local CLI calls.- Streaming responses (SSE) are fully supported — no fallback to polling.
Codex CLI vs Claude Code
A quick comparison after extended use of both in 2026 (full deep-dive: Claude Code vs Gemini CLI covers the third option, and we'll publish a four-way Codex/Claude/Cursor/Gemini hub soon):
Dimension | Codex CLI (GPT-5.5) | Claude Code (Opus 4) |
|---|---|---|
Default model output verbosity | ~40 % shorter on coding tasks | More verbose, more explanatory |
Subagent primitive | Native, native UI in TUI | Native via |
MCP support | First-class, registry-backed | First-class, registry-backed |
Hooks | Lifecycle hooks via TOML | Lifecycle hooks via JSON |
Auto-review | Built-in, configurable reviewer model | Available via subagent pattern, more setup |
Remote cloud tasks | Codex Cloud (built-in) | Not built-in |
Image input | Yes, inline attach | Yes, inline attach |
Computer use | Yes (Responses API) | Yes (Computer Use API) |
Restricted-region access | Needs proxy (e.g. CodeGateway) | Needs proxy (e.g. CodeGateway) |
Pricing | Per-token, tiered | Per-token, no tier |
The honest summary: in May 2026, neither is strictly better. Codex wins on terseness, remote cloud, and OpenAI ecosystem tie-ins. Claude Code wins on architectural reasoning, longer multi-turn coherence, and a more mature plugin/MCP ecosystem. Most teams we've talked to who run both keep them for different jobs rather than picking one.
No official key? Wire up CodeGateway in 3 minutes
The config above needs a working API key. If you have no Anthropic / OpenAI official key — or you'd rather not put a foreign card on file — get one here: Generate your config →. The page defaults to the OpenCode config; for Claude Code / Codex CLI / Claude Desktop, use the in-page 'Generate a config for other clients' link, then copy and paste. Register to top up — cards accepted.
FAQ
Q: Is GPT-5.5 the right default? When should I switch? For most interactive coding work, yes. Switch to gpt-5.3-codex for long-running agent loops you'll leave unsupervised, to GPT-5.4-mini for subagent fanout, and to Codex-Spark when latency dominates UX (inline edits, --watch mode; ChatGPT Pro account required).
Q: Do hooks slow down every command? Only the hooks you wire up. A pre-commit hook running pnpm lint:fix adds maybe 2–4 seconds. A post-edit hook running the full test suite is a bad idea — use --findRelatedTests.
Q: Can subagents share context with the parent? No, by design. Each subagent gets a fresh window. Pass data through files in /tmp or via structured stdout — the parent re-reads what it needs.
Q: Does the Responses API support function calling / tools the same way Chat Completions did? Yes, and more. Tools, web search, file search, code interpreter, computer use, and remote MCP are all unified under one primitive. The migration is mostly mechanical for existing tool-using code.
*Q: What about older snapshots like `gpt-5.2-codex` or `gpt-5.1-codex-?** OpenAI removed them from the /model picker on 2026-04-07. The current picker (ChatGPT sign-in) is gpt-5.5, gpt-5.4, gpt-5.4-mini, gpt-5.3-codex, gpt-5.2, plus gpt-5.3-codex-spark for Pro. New work should target gpt-5.5 or gpt-5.3-codex`.
Q: Is Codex Cloud secure for proprietary code? OpenAI's enterprise terms cover Codex Cloud usage under the same SOC 2 / data-processing addendum as the API. For regulated workloads, talk to OpenAI's enterprise team about data residency before piping production code through it.
Q: How does CodeGateway billing differ from OpenAI direct? OpenAI's published per-token price × a flat 1.07× markup. New accounts get a starting credit after binding a card (current amount on the signup/pricing page). Payment via Stripe. See the billing guide. For the full multiplier table, see how CodeGateway bills.
Q: Can I use Codex CLI without OAuth? Yes. Set OPENAI_API_KEY directly, skip codex login. Most useful in CI environments and behind corporate proxies that block OAuth flows.
Q: I get `unsupported parameter: 'reasoning.summary' is not supported with the 'gpt-5.3-codex-spark' model` — what do I do? It means the request sends the `reasoning.summary` parameter to `gpt-5.3-codex-spark`, which doesn't support it (Spark is the low-latency snapshot, and its config can't be copied verbatim from `gpt-5.3-codex`). Fix: remove `reasoning.summary` (or the whole `reasoning` block if it only sets summary) from the request; use `reasoning.effort` instead on models that support it, or switch to `gpt-5.5` / `gpt-5.3-codex` when you need reasoning control. In Codex CLI this is usually a stale config or a plugin that injects the parameter for every model — pin it per model.
Q: How do I install Codex CLI? Run npm install -g @openai/codex on Node 18+ (macOS, Linux, Windows); winget install openai.codex and Homebrew also work. Then codex login to authenticate — on headless Linux use OPENAI_API_KEY instead of OAuth.
Q: Where is the Codex CLI config file? ~/.codex/config.toml (credentials live separately at ~/.codex/auth.json). Use config.toml to pin the model, set approval policy, and register MCP servers.
Q: Can I point Codex CLI at a custom API endpoint? Yes — set the base URL (for example https://api.codegateway.dev/v1) in ~/.codex/config.toml. If you see 451 unsupported region, follow the fix section above.
Q:Why does npm install -g @openai/codex fail with EACCES or "command not found"?
EACCES means npm's global prefix is owned by root: install Node through nvm or fnm, or run npm config set prefix ~/.npm-global and add ~/.npm-global/bin to PATH. If the install succeeds but the shell still reports command not found, the PATH was not refreshed - reopen the terminal and check which codex. Also confirm node -v is 18 or newer; older Node versions fail during install.
Q:How do I fix the Codex CLI "451 Unsupported Region" error?
A 451 is OpenAI rejecting requests from your region. It is not a typo in config.toml and re-running codex login will not clear it. Point the CLI at an OpenAI-compatible endpoint instead: declare a [model_providers.codegateway] entry in ~/.codex/config.toml with base_url and env_key, export that key, then start a new session with codex. Prompts, MCP servers and AGENTS.md keep working unchanged; the gateway section above has the exact values.
Q:How do I add an MCP server to Codex CLI?
Add an [mcp_servers.<name>] table to ~/.codex/config.toml with command and args (use url for a remote server), restart Codex, then confirm the server loaded with /mcp inside the session. Project-scoped overrides belong in .codex/config.toml inside the repository; a server that is not registered there is never started.
Where does Codex CLI keep its configuration?
TL;DR: Codex CLI reads model, provider, base URL and approval policy from ~/.codex/config.toml (Windows: %USERPROFILE%\.codex\config.toml); credentials stay in ~/.codex/auth.json.
Everything lives in config.toml: model, provider/base URL, approval policy and MCP servers. The model picker and MCP sections above are the field-by-field reference — or grab a working starter file from the setup page.
Using Claude Desktop rather than a terminal agent? Its config file has a different shape: claude_desktop_config.json apikey 与 base_url 怎么配.
Can I run Codex CLI without an OpenAI API key or credit card?
TL;DR: Set OPENAI_BASE_URL=https://api.codegateway.dev/v1 and OPENAI_API_KEY=sk-cg-… in the shell, then run codex login --skip; any OpenAI-compatible gateway works without an OpenAI account.
Yes. Codex CLI speaks the OpenAI Responses protocol, so any OpenAI-compatible gateway works: grab an API key from the setup page, put the gateway base URL and key in config.toml, and the CLI runs unchanged — this is also the standard fix for the “451: unsupported region” error.
The same custom endpoint in Claude Desktop goes through Developer Mode: Claude Desktop Developer Mode 的 base URL 设置.
Q: What is the difference between npm, winget and brew for installing the Codex CLI?
A: All three install the same CLI; only the package manager differs. `npm install -g @openai/codex` works on any platform with Node.js, `winget install -e --id OpenAI.Codex` is the Windows path, and `brew install codex` is the macOS/Linux path. If the command runs but the binary is not found afterwards, that is a PATH problem, not an install problem.
Q: Which config.toml keys decide whether the first run works?
A: Four: `model`, `model_provider`, and the provider's `base_url` and `env_key`. `model` picks the model, `model_provider` selects the provider block, `base_url` points at the endpoint, and `env_key` names the environment variable that holds your API key. Everything else in config.toml is optional.
Related resources
- Claude Code vs Gemini CLI: 2026 Comparison — third option in the agentic-coding-CLI space
- Quick Setup: Claude Code in 5 minutes — companion guide for the Anthropic side of the stack
- Tier Pricing Explained — how the multiplier works
- Error Troubleshooting — 451, 429, 529, timeout edge cases
- Codex CLI vs Claude Code — focused two-way comparison
External references
- OpenAI Codex CLI documentation
- GPT-5.5 model card
- Codex models reference
- Codex changelog
- Responses API guide
