MCPInstall

codex-cli-best-practice

Guide to mastering Codex CLI through subagents, skills, workflows, MCP servers, and agentic engineering patterns

Installs
245
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/reason-machines/codex-skills --skill codex-cli-best-practice
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads codex-cli-best-practice automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

codex-cli-best-practice

Skill by ara.so — Codex Skills collection.

A comprehensive guide and reference implementation for Codex CLI best practices, covering the journey from vibe coding to agentic engineering. This skill teaches you how to leverage Codex CLI's advanced features: subagents, skills, MCP servers, workflows, and configuration patterns.

What This Project Provides

codex-cli-best-practice is a reference repository that demonstrates:

  • Subagents: Custom TOML-configured agents for parallel orchestration
  • Skills: Reusable instruction packages with progressive disclosure
  • MCP Integration: Model Context Protocol servers for external tool access
  • Workflows: End-to-end patterns (Agent → Skill → Output)
  • Configuration: Layered TOML config system with profiles and approval policies
  • Hooks: Shell scripts that inject into the agentic loop
  • Memories: Cross-session memory pipeline for context retention

Installation

Prerequisites

  1. Install Codex CLI (requires Codex Pro subscription):

    # macOS
    brew install --cask codex-cli
    
    # Or download from https://developers.openai.com/codex/cli
    
  2. Clone this repository:

    git clone https://github.com/shanraisshan/codex-cli-best-practice.git
    cd codex-cli-best-practice
    
  3. Initialize Codex in your project:

    codex init
    

Key Concepts & Configuration

1. Subagents (.codex/agents/<name>.toml)

Subagents are custom agents with dedicated role configs. Example weather agent:

# .codex/agents/weather-agent.toml
[agents.weather-agent]
model = "gpt-5.4"
instructions = """
You are a weather data specialist. When asked:
1. Extract location and units from user request
2. Fetch current weather from Open-Meteo API
3. Return structured data for downstream skills
"""
temperature = 0.7
max_tokens = 2000

Invoke with:

codex
> @weather-agent Get Dubai weather in Celsius

Global agent settings in .codex/config.toml:

[agents]
max_threads = 4
max_depth = 3
job_max_runtime_seconds = 300

2. Skills (.agents/skills/<name>/SKILL.md)

Skills are reusable instruction packages. Required structure:

.agents/skills/weather-svg-creator/
├── SKILL.md              # Core instructions with YAML frontmatter
├── scripts/              # Helper scripts
│   └── create_svg.py
├── references/           # Documentation
│   └── svg-spec.md
└── assets/              # Templates, images
    └── template.svg

Example SKILL.md:

---
name: weather-svg-creator
description: Creates SVG weather cards from structured weather data
---

# Weather SVG Creator

You create beautiful SVG weather cards. When invoked:

1. Accept weather data (location, temp, condition, humidity)
2. Use scripts/create_svg.py to generate SVG
3. Output to specified path

## Usage Pattern

```python
# scripts/create_svg.py will be called with:
python scripts/create_svg.py \
  --location "Dubai" \
  --temp "32" \
  --condition "Sunny" \
  --output "weather.svg"

Invoke skills:
```bash
# Explicit
codex
> Use $weather-svg-creator to make a card for Dubai, 32°C, Sunny

# Implicit (by description match)
> Create an SVG weather card

3. MCP Servers (.codex/config.toml)

Connect external tools via Model Context Protocol:

# .codex/config.toml
[mcp_servers.filesystem]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-filesystem", "/Users/shan/projects"]
supports_parallel_tool_calls = true

[mcp_servers.github]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-github"]
env = { GITHUB_PERSONAL_ACCESS_TOKEN = "${GITHUB_TOKEN}" }

[mcp_servers.weather]
command = "python"
args = ["-m", "mcp_server_weather"]
working_directory = ".codex/mcp-servers/weather"

Manage MCP servers:

# List available servers
codex mcp list

# Add new server
codex mcp add weather

# Test server
codex mcp get weather

# OAuth login (for supported servers)
codex mcp login github

4. Orchestration Workflow (Agent → Skill)

The canonical pattern from this repo:

codex
> Fetch the current weather for Dubai in Celsius and create the SVG weather card output using the repo.

What happens:

  1. @weather-agent fetches data from Open-Meteo
  2. Returns structured JSON: {"location": "Dubai", "temp": 32, "condition": "Clear"}
  3. Codex matches $weather-svg-creator skill by description
  4. Skill runs scripts/create_svg.py with data
  5. SVG output saved and displayed

5. Configuration Layers

# .codex/config.toml
[features]
memories = true           # Cross-session memory
codex_hooks = true       # Enable hooks
fast_mode = false        # 1.5x speed mode

[approval_policy]
edits_outside_cwd = "prompt"
deletions = "prompt"
shell_commands = "auto_approve_safe"

[sandbox]
enabled = true
include_patterns = ["src/**", "tests/**"]
exclude_patterns = ["*.pyc", "__pycache__/**"]

[model]
default = "gpt-5.4"
review_model = "gpt-5.4-large-context"
temperature = 0.7

[memories]
max_tokens = 10000
collection_interval_seconds = 300

# Developer instructions (always included)
developer_instructions = """
Follow repo conventions:
- Use type hints in Python
- Run pytest before committing
- Update AGENTS.md for architectural changes
"""

6. Hooks (.codex/hooks.json)

Inject shell scripts into the agentic loop:

{
  "hooks": {
    "before_edit": {
      "script": ".codex/hooks/lint-check.sh",
      "description": "Run linter before edits"
    },
    "after_shell": {
      "script": ".codex/hooks/log-command.sh",
      "description": "Log all shell commands"
    },
    "before_commit": {
      "script": ".codex/hooks/run-tests.sh",
      "description": "Run test suite"
    }
  }
}

Hook script example:

#!/bin/bash
# .codex/hooks/lint-check.sh

# Codex provides context via env vars:
# CODEX_HOOK_FILES, CODEX_HOOK_CONTEXT

for file in $CODEX_HOOK_FILES; do
  if [[ $file == *.py ]]; then
    ruff check "$file" || exit 1
  fi
done

exit 0

7. Plugins & Marketplace

Install plugin marketplaces:

# Add GitHub marketplace
codex plugin marketplace add github:openai/codex-plugins

# Add local marketplace
codex plugin marketplace add ~/my-plugins

# Browse installed plugins
codex
> /plugins

# Install specific plugin
codex plugin install security-scanner

Create a plugin (.codex-plugin/plugin.json):

{
  "name": "my-workflow-plugin",
  "version": "1.0.0",
  "description": "Custom workflow automation",
  "skills": ["skills/planner", "skills/executor"],
  "mcp_servers": {
    "custom-api": {
      "command": "node",
      "args": ["mcp-server.js"]
    }
  }
}

8. Memories (Cross-Session Context)

Enable in config:

[features]
memories = true

[memories]
max_tokens = 10000
collection_interval_seconds = 300

Control via TUI:

codex
> /memories use      # Enable for this session
> /memories reset    # Clear all memories

Memories are user-scoped, not project-scoped.

Common Workflows

Create a New Subagent

codex
> Create a subagent called @api-designer that specializes in REST API design. 
  It should use gpt-5.4-large-context and follow OpenAPI 3.0 standards.
  Save to .codex/agents/api-designer.toml

Create a New Skill

codex
> Use the $skill-creator to make a new skill called database-migrator.
  It should help write Alembic migrations for SQLAlchemy models.
  Include example migration scripts.

Set Up MCP Server for Custom Tool

# .codex/mcp-servers/weather/server.py
from mcp.server import Server
from mcp.server.stdio import stdio_server

app = Server("weather-mcp")

@app.tool()
async def get_weather(location: str, units: str = "celsius"):
    """Fetch current weather for a location."""
    # Integration with Open-Meteo API
    import httpx
    async with httpx.AsyncClient() as client:
        response = await client.get(
            "https://api.open-meteo.com/v1/forecast",
            params={
                "latitude": ...,
                "longitude": ...,
                "current_weather": "true",
                "temperature_unit": units
            }
        )
        return response.json()

if __name__ == "__main__":
    stdio_server(app)

Add to config:

[mcp_servers.weather]
command = "python"
args = [".codex/mcp-servers/weather/server.py"]

Implement Agent → Skill Workflow

  1. Create the agent:
# .codex/agents/data-fetcher.toml
[agents.data-fetcher]
model = "gpt-5.4"
instructions = "Fetch data from APIs and return structured JSON"
  1. Create the skill:
# .agents/skills/data-visualizer/SKILL.md
---
name: data-visualizer
description: Creates charts from JSON data
---

Accept JSON data and create matplotlib/plotly visualizations.
  1. Invoke:
codex
> @data-fetcher get GitHub stars for shanraisshan/codex-cli-best-practice, 
  then $data-visualizer create a trend chart

Enable Fast Mode

codex
> /fast on         # Enable 1.5x speed (2x credits)
> /fast status     # Check current mode
> /fast off        # Disable

Or in config:

[model]
service_tier = "fast"  # Always use fast mode

Code Review Workflow

# Review uncommitted changes
codex
> /review

# Review specific branch
> /review main..feature-branch

# Review with custom instructions
> /review --instructions "Focus on security and performance"

Configure review model:

[model]
review_model = "gpt-5.4-large-context"

Slash Commands Reference

CommandDescription
/planCreate execution plan before acting
/fast on|off|statusToggle fast mode (1.5x speed)
/forkCreate parallel session branch
/review [ref]Code review for changes/branch
/statusShow session info and token usage
/mcpManage MCP servers
/agent <name>Switch to specific subagent
/appsManage connected applications
/modelChange model for session
/permissionsManage approval policies
/skillsBrowse and invoke skills
/pluginsBrowse plugin marketplace
/memories use|resetControl memory system

Environment Variables

# Required
export OPENAI_API_KEY="sk-..."  # Codex Pro API key

# Optional
export CODEX_HOME="$HOME/.codex"  # Config directory
export GITHUB_TOKEN="ghp_..."     # For GitHub MCP server
export ANTHROPIC_API_KEY="sk-..." # For Claude models (if configured)

Troubleshooting

Subagent Not Found

Issue: @my-agent not recognized

Solution:

# Check agent config exists
ls .codex/agents/my-agent.toml

# Verify TOML syntax
codex config validate

# Restart codex session
codex
> /exit
codex

Skill Not Triggering

Issue: Skill not invoked implicitly

Solution:

  • Use explicit invoke: $skill-name
  • Check skill description is specific enough
  • Verify SKILL.md has valid YAML frontmatter
  • Check .agents/skills/ directory structure

MCP Server Connection Failed

Issue: MCP server 'xyz' not responding

Solution:

# Test server directly
codex mcp get xyz

# Check server logs
cat ~/.codex/logs/mcp-xyz.log

# Verify command and args in config.toml
# Ensure env vars are set (use ${VAR} syntax)

# Restart server
codex mcp remove xyz
codex mcp add xyz

Hooks Not Running

Issue: Hooks defined but not executing

Solution:

# Enable in config
[features]
codex_hooks = true
# Make scripts executable
chmod +x .codex/hooks/*.sh

# Test hook directly
.codex/hooks/my-hook.sh

Memory Not Persisting

Issue: Context lost between sessions

Solution:

codex
> /memories use  # Enable for this thread

# Check feature flag
# In .codex/config.toml:
[features]
memories = true

Approval Policy Too Restrictive

Issue: Every action requires approval

Solution:

[approval_policy]
shell_commands = "auto_approve_safe"  # Auto-approve safe commands
edits_outside_cwd = "auto_approve"    # Less restrictive
network_access = "auto_approve"       # For MCP servers

# Or use profiles
[profiles.dev]
approval_policy.shell_commands = "auto_approve_safe"

Best Practices

  1. Start with /plan: Let Codex create execution plans for complex tasks
  2. Use AGENTS.md: Document project structure and conventions
  3. Namespace subagents: Use descriptive names like @api-designer not @api
  4. Scope skills narrowly: One skill = one clear responsibility
  5. Test MCP servers: Use codex mcp get to verify before adding to workflow
  6. Layer configs: Use profiles for different environments (dev, prod)
  7. Enable hooks selectively: Start with after_shell for logging
  8. Review approval policy: Balance security and automation
  9. Use memories sparingly: Enable only for long-running projects
  10. Document workflows: Create .md files showing Agent → Skill patterns

Resources

FAQ

What does the codex-cli-best-practice skill do?

Guide to mastering Codex CLI through subagents, skills, workflows, MCP servers, and agentic engineering patterns

How do I install codex-cli-best-practice?

Run npx skills add https://github.com/reason-machines/codex-skills --skill codex-cli-best-practice in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/codex-cli-best-practice/ (personal) or .claude/skills/codex-cli-best-practice/ (project).

Which AI agents can use codex-cli-best-practice?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is codex-cli-best-practice safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains codex-cli-best-practice?

It is published by reason-machines in reason-machines/codex-skills. It has 245 recorded installs.

More from reason-machines/codex-skills

View all →

academic-research-skills-codex

reason-machines/codex-skills

Open the skill to read its SKILL.md instructions.

codexplusplus-launcher

reason-machines/codex-skills

Open the skill to read its SKILL.md instructions.

282 installs

codex-plugin-claude-code

reason-machines/codex-skills

Open the skill to read its SKILL.md instructions.

273 installs

awesome-codex-skills-curator

reason-machines/codex-skills

Open the skill to read its SKILL.md instructions.

270 installs

codex-plusplus-tweak-system

reason-machines/codex-skills

Open the skill to read its SKILL.md instructions.

270 installs

awesome-codex-subagents

reason-machines/codex-skills

Open the skill to read its SKILL.md instructions.

AI & Agents268 installs

Popular ai & agents skills

View category →

google-agents-cli-publish

google/agents-cli

This skill should be used when the user wants to "publish an agent", "publish my ADK agent", "register an agent with Gemini", "publish to Gemini" (formerly Gemini Enterprise), or needs guidance on the agents-cli publish gemini command. Also use when the user wants to "manage agents in Agent Registry", "list/update/delete registered agents", or "register an MCP server". Covers ADK vs A2A registration modes, programmatic and interactive usage, flag reference, auto-detection from deployment metadata, Agent Registry fleet management, and troubleshooting. Part of the agents-cli skills suite. Do NOT use for deployment (use google-agents-cli-deploy).

AI & Agents513.9K installs

google-agents-cli-eval

google/agents-cli

This skill should be used when the user wants to "run an evaluation", "evaluate my agent", "evaluate my ADK agent", "write an eval dataset", "analyze eval failures", "compare eval results", "optimize agent", or needs guidance on the Gemini platform eval methodology and the Quality Flywheel. Covers eval metrics, dataset schema, LLM-as-judge scoring, and common failure causes. Applies to any agents-cli project, whatever framework the agent is written in. Do NOT use for agent API code patterns (ADK: use google-agents-cli-adk-code), deployment (use google-agents-cli-deploy), or project scaffolding (use google-agents-cli-scaffold).

AI & Agents513.5K installs

skill-creator

anthropics/skills

Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.

OfficialAI & Agents416.4K installs

codex-pet

prime-skills/runcomfy-agent-skills

Codex Pet generator on RunComfy. Build a Codex-compatible Codex Pet spritesheet.webp + pet.json from a single reference image, drop it into ${CODEXHOME:-$HOME/.codex}/pets/ / and Codex picks it up as a custom Codex Pet next to the 8 built-ins. This skill produces the exact Codex Pet atlas Codex expects (1536x1872 PNG/WebP, 8 cols x 9 rows, 192x208 cells, 9 animation states — idle, running-right, running-left, waving, jumping, failed, waiting, running, review). Calls OpenAI GPT Image 2 edit ONCE via the local RunComfy CLI as runcomfy run openai/gpt-image-2/edit to produce a canonical Codex Pet pose, then assembles all 9 animation rows programmatically with ImageMagick micro-transforms — no Codex Pro, no $imagegen, no OPENAIAPIKEY required, only RUNCOMFYTOKEN. Triggers on "codex pet", "create codex pet", "make codex pet", "hatch codex pet", "/hatch image", "desktop pet codex", "codex pets", "spritesheet.webp", or any explicit ask to build a custom pet for OpenAI Codex.

AI & Agents402.1K installs

full-output-enforcement

leonxlnx/taste-skill

Overrides default LLM truncation behavior. Enforces complete code generation, bans placeholder patterns, and handles token-limit splits cleanly. Apply to any task requiring exhaustive, unabridged output.

AI & Agents401K installs

executing-plans

obra/superpowers

Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available

AI & Agents245.7K installs