CDX-201a · Module 2

Environment Variables & Secrets

3 min read

Codex sessions run in the context of your shell environment, which means environment variables are available to commands Codex executes. This is both powerful and dangerous. Powerful because Codex can run your build tools, test suites, and deployment scripts that depend on environment configuration. Dangerous because a poorly scoped session can expose secrets to the model through command output.

MCP server configurations in config.toml support an env block where you can set environment variables specifically for that MCP server. This is the right way to provide API keys to MCPs — scoped to the server that needs them, not leaked into the global environment. Never put secrets directly in AGENTS.md. Use environment variables referenced by name, and let the shell or .env file provide the actual values.

# MCP-scoped environment variables
[mcp.github]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-github"]
env = { GITHUB_TOKEN = "${GITHUB_TOKEN}" }

[mcp.postgres]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-postgres"]
env = { DATABASE_URL = "${DATABASE_URL}" }

# Never do this:
# env = { GITHUB_TOKEN = "ghp_actualSecretHere1234567890" }
  1. Audit your environment Run `env | grep -i key\|secret\|token\|password` to see what sensitive values are in your current shell. Consider which ones Codex actually needs.
  2. Scope MCP secrets Move API keys from your shell profile into MCP-scoped env blocks in config.toml. Each server gets only the secrets it needs.
  3. Use .env.codex Create a minimal .env file with only the variables Codex sessions need. Source it explicitly before launching Codex instead of inheriting your full development environment.