Custom Coding Subagents: Build Specialized AI Helpers for Claude Code and Codex CLI

Every AI coding tool in 2026 — Claude Code, Codex CLI, Gemini CLI, Cursor, Copilot — supports subagents. They all solve the same problem: your main coding session’s context window is precious, and mixing file search, code review, and test generation in one conversation pollutes it fast.
Subagents get their own context window, tool set, and system prompt. They run in parallel. Only their final output comes back to you. The result: cleaner sessions, faster parallel work, and specialized agents you reuse across projects.
This guide walks through the two most popular implementations — Claude Code (markdown agent files) and Codex CLI (TOML agent configs) — with production-ready templates you can copy today.
Why subagents matter for production work
Three scenarios where subagents save real time:
- PR review automation — Spawn a read-only security auditor while you keep working. It analyzes the diff independently and returns a structured report.
- Test generation at scale — Delegate test writing for 10 files to parallel subagents. Each handles one module. They don’t share context, so no cross-contamination.
- Codebase exploration — “Find all usages of this deprecated API and assess the migration effort.” An explorer subagent traces the call graph while your main session stays clean.
Simon Willison documented subagents as a core pattern across all major coding agents by March 2026 [1]. The pattern is mature. The question now is how to configure them well.
Claude Code subagents: markdown-based
Claude Code defines subagents as markdown files with YAML frontmatter [2]. Place them in .claude/agents/ (per-project) or ~/.claude/agents/ (your machine). Each file is one agent.
Anatomy of a Claude Code agent file
---
name: code-reviewer
description: Use proactively when staging a feature branch for PR review. Focuses on correctness, security, and test coverage gaps.
model: sonnet
tools: Read, Grep, Glob
---
You are a senior code reviewer. When invoked, do the following in order:
1. Identify files changed on the current branch.
2. Read each changed file and its tests.
3. Flag specific issues by file and line: correctness, security, performance, readability.
4. Suggest concrete fixes, not vague advice.
Output format: a Markdown report grouped by file, with severity tags (BLOCKER, MAJOR, NIT).
Do not modify files — read-only by design.
Fields: name (required), description (required — Claude uses this to decide when to auto-delegate), model (optional — haiku, sonnet, opus, or inherit), tools (optional allowlist), disallowedTools (optional denylist).
Production-ready Claude Code templates
Security auditor — read-only, Opus-grade reasoning, narrow scope:
---
name: security-auditor
description: Use before merging any PR that touches auth, payment, data access, or dependency files.
model: opus
tools: Read, Grep, Glob
---
Audit for OWASP Top 10 vulnerabilities:
- SQL/NoSQL injection, XSS, CSRF
- Broken authentication or session management
- Secrets or credentials in code
- Insecure direct object references
- Dependency vulnerabilities (check lock files)
Rate each finding: CRITICAL, HIGH, MEDIUM, LOW.
Include CWE identifiers. If no issues, say so explicitly.
Test generator — has write access but restricted to test files:
---
name: test-writer
description: Use when adding unit or integration tests for a module. Generates tests matching the existing test framework and patterns.
model: sonnet
tools: Read, Write, Bash, Glob, Grep
---
1. Read the target module and existing test files for style reference.
2. Generate tests covering: happy path, error cases, edge cases.
3. Run the tests with `npm test -- --bail` or equivalent.
4. Fix any failures iteratively, up to 3 attempts.
5. Report coverage delta.
Match the project's existing test framework (vitest, jest, pytest, etc.).
Codebase explorer — cheapest model, fast, stateless:
---
name: scout
description: Fast codebase exploration when you need to trace a code path, find usages, or gather evidence without modifying anything.
model: haiku
tools: Read, Grep, Glob
---
You are a codebase reconnaissance agent. Stay in exploration mode.
- Trace execution paths and cite files with exact paths.
- Prefer targeted grep over broad directory scans.
- Summarize findings concisely — the orchestrating agent will synthesize.
Invoking Claude Code subagents
| Method | Example | Reliability |
|---|---|---|
| Automatic | Just ask “Review this PR” — Claude picks the right agent | Good with clear descriptions |
| @-mention | @code-reviewer analyse the auth module |
Guaranteed delegation |
| Background | Ctrl+B to run concurrently | Great for parallel work |
Agent Teams (Claude Code’s multi-agent orchestration) take this further — multiple agents coordinate autonomously with one acting as team lead [3].
Codex CLI subagents: TOML-based
Codex CLI defines custom agents as TOML files. Place them in ~/.codex/agents/ (personal) or .codex/agents/ (project). Each .toml file defines exactly one agent [4].
Anatomy of a Codex CLI agent file
name = "reviewer"
description = "PR reviewer focused on correctness, security, and missing tests."
model = "gpt-5.4"
model_reasoning_effort = "high"
sandbox_mode = "read-only"
nickname_candidates = ["Athena", "Ada"]
developer_instructions = """
Review code like an owner.
Prioritise correctness, security regressions, and test coverage gaps.
Lead with concrete findings including file paths and line numbers.
Never modify files — your job is analysis, not implementation.
If you find no issues, say so explicitly rather than inventing nitpicks.
"""
Required fields: name, description, developer_instructions. Optional: model, model_reasoning_effort, sandbox_mode, mcp_servers, skills.config.
Production-ready Codex CLI templates
Security auditor with MCP server binding:
name = "security_auditor"
description = "Scans code changes for security vulnerabilities and dependency risks."
model = "gpt-5.5"
model_reasoning_effort = "high"
sandbox_mode = "read-only"
developer_instructions = """
Focus exclusively on security concerns:
- Injection vulnerabilities (SQL, XSS, command injection)
- Authentication and authorisation flaws
- Secrets or credentials in code or configuration
- Dependency vulnerabilities via the security MCP server
- Insecure defaults and missing input validation
Rate each finding: CRITICAL, HIGH, MEDIUM, or LOW.
Include CWE identifiers where applicable.
"""
[mcp_servers.security-advisory]
command = "npx"
args = ["-y", "@security-tools/advisory-mcp-server"]
Lightweight explorer — cheap model for high-volume scans:
name = "scout"
description = "Fast read-only explorer for tracing execution paths and gathering evidence."
model = "gpt-5.3-codex-spark"
model_reasoning_effort = "medium"
sandbox_mode = "read-only"
developer_instructions = """
Stay in exploration mode.
Trace execution paths, cite files and symbols with exact paths.
Prefer targeted search over broad directory scans.
Summarise findings concisely — the orchestrator will synthesise.
"""
Test writer — workspace write access, wider tooling:
name = "test_writer"
description = "Generates and runs tests for specified modules. Writes to test files only."
model = "gpt-5.4"
model_reasoning_effort = "medium"
sandbox_mode = "workspace-write"
developer_instructions = """
Write tests for the specified module matching the project's existing test framework.
Cover: happy path, error cases, edge cases, and integration scenarios.
Run the test suite after writing to verify. Fix failures iteratively up to 3 attempts.
Report which tests were added and the coverage delta.
"""
Codex CLI global agent settings
In your .codex/config.toml:
[agents]
max_threads = 6 # Max concurrent subagents (default: 6)
max_depth = 1 # Nesting limit — keep at 1 to prevent recursive fan-out
Codex CLI subagents inherit the parent’s sandbox policy, but you can override sandbox_mode per-agent (read-only, workspace-write, danger-full-access) [4].
Side-by-side comparison
| Feature | Claude Code | Codex CLI |
|---|---|---|
| Agent file format | Markdown + YAML frontmatter | TOML |
| Location | .claude/agents/ or ~/.claude/agents/ |
.codex/agents/ or ~/.codex/agents/ |
| Model assignment | model: field (haiku/sonnet/opus/inherit) |
model field (any OpenAI model ID) |
| Tool restriction | tools: allowlist + disallowedTools: denylist |
sandbox_mode (3 levels) |
| MCP server binding | Yes (mcpServers field) |
Yes (mcp_servers table) |
| Max agents concurrent | No hard limit (practical: 3-5) | Configurable via max_threads (default: 6) |
| Nesting depth | Cannot spawn subagents | Configurable via max_depth (default: 1) |
| Background execution | Yes (Ctrl+B, background: true) |
Yes (non-interactive) |
| Invocation methods | Automatic, @-mention, explicit prompt | Explicit prompt, named reference |
| Required fields | name, description | name, description, developer_instructions |
When to use which
- Claude Code — Better for team-shared subagents. Markdown files are human-readable without a parser. The automatic delegation (Claude picks based on description) works well when your agent descriptions are clear.
- Codex CLI — Better for CI/CD pipelines. TOML files with
sandbox_modegive you granular permission control. Per-agent model assignment (including cheapcodex-sparkmodels) lets you optimize cost at scale. - Both — Start with a security auditor and a test writer. Those two subagents save the most time per setup investment. Add a cheap explorer agent once the pattern proves itself.
Both tools support three built-in agent types (explorer/worker/default in Codex; explore/plan/general in Claude) but the real value comes from custom agents tailored to your team’s stack and standards [5].
Deployment checklist
Before committing subagent definitions to your repo:
- Subagent files are in the right scope directory (project vs user)
-
descriptionis specific enough for automatic delegation -
sandbox_modeortoolsrestriction aligns with the agent’s purpose - Subagents are tested with at least one real invocation
- Codex global
max_depthis set to 1 (prevents runaway nesting) - Claude subagents do NOT include
Agentin their tools array (no recursion) - Agent definitions are committed to VCS (not just local)
Bottom line
Subagents are the single highest-leverage productivity improvement in AI coding tools right now. They keep your main session focused, let you parallelize work, and encode team standards as reusable agent definitions. Setting up three — security auditor, test writer, and explorer — takes 15 minutes and pays back immediately on the next PR.
[1] Simon Willison, “Use subagents and custom agents in Codex”, March 2026 — https://simonwillison.net/2026/Mar/16/codex-subagents/
[2] Anthropic, “Subagents in the SDK — Claude Code Docs” — https://code.claude.com/docs/en/agent-sdk/subagents
[3] Turing College, “Claude Agent Teams Explained: AI for Complex Projects (2026 Guide)” — https://www.turingcollege.com/blog/claude-agent-teams-explained
[4] OpenAI, “Subagents — Codex | OpenAI Developers” — https://developers.openai.com/codex/subagents
[5] Simon Willison, “Agentic Engineering Patterns: Subagents” — https://simonwillison.net/guides/agentic-engineering-patterns/subagents/
← Back to all posts

