The short version
- A Claude Code custom subagent is one Markdown file with a name, a description and a system prompt, saved in .claude/agents/ so the whole team can share it through version control.
- Each subagent runs in a fresh context with its own tool list and model, and only its result returns to your main conversation.
- Restrict tools with an allowlist, add a PreToolUse hook when you need finer rules, and route routine work to a cheaper model such as Haiku.
- Subagent requests count toward the same usage limits as your main conversation, so a subagent saves context, not plan usage, and each one spends tokens of its own.
- Keep subagents few and sharply described: Claude picks one by its description, and Claude Code warns at startup when custom descriptions together exceed 15,000 tokens.
On this page
How do you create a custom subagent in Claude Code? Write a Markdown file with a name, a description and a system prompt, and save it in .claude/agents/ (project) or ~/.claude/agents/ (all your projects). Claude then delegates matching tasks to it, in its own context window, with the tools and model you chose.
This guide covers where the files go, which fields matter, three working examples, how to cut cost, and the limits to know. Everything below comes from the Claude Code subagents documentation. Fields and version numbers change, so check that page against your installed version.
What is a Claude Code subagent?
A subagent is a specialised assistant that runs in its own context window with a custom system prompt, restricted tool access and independent permissions. When it finishes, its result comes back to your main conversation. That keeps verbose output such as search results, logs and file contents out of the context you are paying to carry.
Two facts matter for planning:
- A subagent starts fresh. It does not see your conversation history. It receives its own system prompt, the delegation message, your CLAUDE.md files (unless you set
omitClaudeMd) and git status. - Subagent requests count toward the same usage limits as your main conversation. A subagent saves context, not plan usage.
Claude Code also ships built-in subagents. Explore does fast, read-only codebase search, Plan does research while in plan mode, and general-purpose handles multi-step work with every tool available to subagents. You can block a specific one in settings with permissions.deny, for example Agent(Explore).
Where do subagent files go?
When two subagents share a name, the higher-priority location wins:
| Location | Scope | Priority |
|---|---|---|
| Managed settings | Organisation-wide | 1 (highest) |
--agents CLI flag | Current session | 2 |
.claude/agents/ | Current project | 3 |
~/.claude/agents/ | All your projects | 4 |
Plugin agents/ directory | Where the plugin is enabled | 5 (lowest) |
Claude Code scans these directories recursively, so subfolders are fine. Identity comes only from the name field, so keep names unique. Changes are detected within seconds, though files in directories added with --add-dir need a restart.
For a team, commit .claude/agents/ to the repository. The docs list "check into version control" among their best practices, and it is the simplest way to make every engineer's agent behave the same. To share across repositories, package subagents in a plugin. Plugin subagents ignore hooks, mcpServers and permissionMode, so put hooks in the plugin's own hooks instead.
How do you write a custom subagent?
Only name and description are required. Multi-word field names are camelCase, and unrecognised fields are ignored without an error, so a typo fails quietly. Run claude --debug and search the log for does not recognize or apply to find them.
The fields you will use most:
| Field | What it does |
|---|---|
description | Tells Claude when to delegate to this subagent |
tools | Allowlist of tools |
disallowedTools | Denylist, applied before tools |
model | sonnet, opus, haiku, fable, a full model ID, or inherit |
permissionMode | default, acceptEdits, auto, dontAsk, bypassPermissions or plan |
maxTurns | Turn limit; output is marked partial when it is reached |
skills | Skills whose full content is preloaded at startup |
hooks | Lifecycle hooks scoped to this subagent |
isolation | worktree runs it in a temporary git worktree |
memory | Persistent memory: user, project or local |
effort | low, medium, high, xhigh or max |
Example 1: a read-focused reviewer
---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---
You are a senior code reviewer ensuring high standards of code quality and security.
When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately
Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)This is shortened from the docs' example. Note the docs' own caveat: leaving out Edit and Write does not make the reviewer read-only, because it can still change files through Bash. If that matters, use a hook (Example 3).
Example 2: a debugger that may edit
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---
You are an expert debugger specializing in root cause analysis.
When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution worksThe difference from the reviewer is one word in tools: Edit. Give a subagent the narrowest list that lets it finish its job.
Example 3: block writes with a hook
When a tools list is too coarse, add a PreToolUse hook to the subagent. This definition allows Bash but runs a script before every command:
---
name: db-reader
description: Execute read-only database queries. Use when analyzing data or generating reports.
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
You are a database analyst with read-only access. Execute SELECT queries only.The script reads the hook's JSON from stdin and exits with code 2 to block:
#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
[ -z "$COMMAND" ] && exit 0
if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE|REPLACE|MERGE)\b' > /dev/null; then
echo "Blocked: Write operations not allowed. Use SELECT queries only." >&2
exit 2
fi
exit 0Run chmod +x on the script on macOS or Linux, or the hook fails instead of blocking. The docs call the hook a backstop: the prompt already tells the subagent to refuse writes, and the hook catches an attempt anyway. A keyword filter like this is crude, so treat it as a guard rail, not a security boundary.
How do you invoke a subagent?
- Automatically. Claude delegates by matching the task to each description. Phrases like "use proactively" in the description encourage it.
- By name in plain language:
Use the test-runner subagent to fix failing tests. - With an @-mention:
@"code-reviewer (agent)" look at the auth changes, or type@agent-<name>. - As the whole session:
claude --agent code-reviewer. To make it a project default, set"agent": "code-reviewer"in.claude/settings.json. The flag overrides the setting.
For one-off or scripted use, --agents takes JSON for the current session:
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'In non-interactive mode, --agents also accepts a path to a JSON file, for example claude -p --agents ./agents.json "Review my changes". The docs say the file form needs v2.1.281 or later, and an interactive session refuses a file path.
How do subagents affect cost?
Subagents are a context tool first. Used well they cut cost, because noisy work such as a long log read stays in the subagent and you carry only its result. Used carelessly they add cost: the docs warn that running many subagents that each return detailed results can consume significant context, and each subagent spends tokens of its own while it runs.
Practical levers from the docs:
- Pick the model per subagent. Claude Code uses the first of these that applies: the per-invocation model, then the
modelfield, then theCLAUDE_CODE_SUBAGENT_MODELenvironment variable, then the main conversation's model. Setmodel: haikuon routine search or log-reading agents. To force one model onto every subagent, setCLAUDE_CODE_SUBAGENT_MODELandCLAUDE_CODE_SUBAGENT_MODEL_FORCEto1(v2.1.257 or later). - Skip what the agent does not need.
omitClaudeMd: trueleaves out your CLAUDE.md files for a narrow helper. - Cap runaway work.
maxTurnsstops a subagent after a set number of turns. - Compact earlier for long readers.
autoCompactWindowtakes a token count of100000or more, written as a plain integer: write200000, not200k, which is read as 200 and ignored. It needs v2.1.296 or later. - Keep the results short. Ask the subagent in its system prompt to report only what the main conversation needs.
What are the limits?
- Subagents can spawn subagents. Nesting is on by default, up to three layers below the main conversation. Set
CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTHto change the limit, or to1to turn nesting off. - By default, 20 subagents can run at once.
CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTSchanges that. - When the combined descriptions of your custom subagents exceed 15,000 tokens, Claude Code shows a startup warning. Keep descriptions short and move detail into the system prompt.
- If the main conversation is in
bypassPermissions,acceptEditsor auto mode, the subagent uses that mode and ignores its ownpermissionMode. If the main conversation is in plan mode, the subagent stays in plan mode. Do not rely onpermissionModeas a fence. - Subagent transcripts are deleted after 30 days by default (the
cleanupPeriodDayssetting).
A related feature is the fork, a subagent that inherits the whole conversation so far. Because a fork's system prompt and tool definitions match its parent's, its first request reuses the parent's prompt cache, so it costs less than a fresh subagent when the task needs the same context. Fork mode is on by default from v2.1.302. You can start one yourself with /subtask followed by a task.
If subagents edit files in parallel, give them isolation: worktree so their edits land in a separate git worktree.
A short checklist for your team
- Start with two subagents, a reviewer and a debugger, not ten.
- Write each description so it singles out one job; overlapping descriptions make routing unpredictable.
- Give each the shortest tool list that works, and add a hook where Bash must be constrained.
- Set
modeldeliberately: cheaper for reading, stronger for judgement. - Commit
.claude/agents/and review changes to it like code. - Watch usage for a week before adding more.
Conclusion
Custom subagents are cheap to write and easy to share: one file, a sharp description, a short tool list and a deliberate model. They cut context, not plan usage, so measure before you multiply them.
Teams that run many Claude Code sessions at once meet the same trade-offs at larger scale. Atlas is built on Claude Code and gives each engineer its own session, written role and model and effort for that role; its own helpers that read files run on Haiku. Managing subagent definition files is not something Atlas does today; that is coming to Atlas, built in, so it needs no setup.
Questions people ask
Where do I put a custom subagent file in Claude Code?
Put it in .claude/agents/ in your project to share it with your team through version control, or in ~/.claude/agents/ for all your projects. Only name and description are required in the frontmatter.
Do Claude Code subagents save usage limits?
No. Subagent requests count toward the same usage limits as your main conversation, and each subagent spends tokens of its own. They save context in your main session, and you can lower cost by giving routine subagents a cheaper model such as Haiku.
How do I stop a subagent from changing files?
Leaving Edit and Write out of its tools list is not enough, because it can still change files through Bash. For a firmer rule, add a PreToolUse hook that exits with code 2 to block commands you do not allow, and treat it as a guard rail.
Can a subagent call another subagent?
Yes. Nesting is on by default, up to three layers below the main conversation. Set CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH to change the limit, or to 1 to turn nesting off.
How many subagents can run at once?
By default 20 subagents can run at once. You can change that with the CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS environment variable.
Sources
Researched and drafted with Claude, then checked against the sources above. Atlas is an independent product, not affiliated with Anthropic or OpenAI. Claude and Claude Code are trademarks of Anthropic; Codex is a product of OpenAI.