Claude Code subagents: files, frontmatter, tools and complete examples
Introduction
A subagent is a separate worker with its own context window, its
own system prompt, its own tool list and its own model. Claude starts
one when a side task would flood the main conversation with search
results, logs or file contents, and the subagent returns only the
summary. You get three wins at once: the main context stays clean,
constraints are enforced by tool lists instead of polite requests, and
cheap models can carry cheap work.
The typical split mirrors the role model:
cheap triage and research on small
models, standard implementation in the main session, and a strict
Opus reviewer that never edits.
Writing the files is the easy part; this page covers the fields,
limits and failure modes that decide whether the roles actually run.
Where subagents live
A subagent is a Markdown file with YAML frontmatter. Location decides who gets it and who wins on a name clash:
| Location | Scope | Priority |
|---|---|---|
| .claude/agents/ | This project, committed for the team | 3 |
| ~/.claude/agents/ | All your projects | 4 |
| --agents CLI flag | Current session only, JSON on the command line | 2 |
| Managed settings | Organization-wide, deployed by administrators | 1 |
| Plugin agents/ | Wherever the plugin is enabled | 5 |
Project and user directories are scanned recursively, so organize files into folders such as agents/review/; the subdirectory does not change the id, because the frontmatter name is the identity. Keep names unique inside one directory: two files with the same name load only one of them, in filesystem order. Across nested project directories the definition closest to the working directory wins. Directories added with --add-dir or /add-dir also contribute their .claude/agents/ files for that session.
File anatomy
Frontmatter configures the worker; the Markdown body becomes its system prompt. Only name and description are required. Example file .claude/agents/code-reviewer.md:
mkdir -p .claude/agents
vi .claude/agents/code-reviewer.md
--- name: code-reviewer description: Reviews changes for correctness, security and missing tests. Use after every code change. tools: Read, Grep, Glob model: opus color: red --- You are a strict reviewer. Report findings in severity order, each with file and line, then a verdict: ship, fix first, or block. Never edit files.
Fields that matter in practice:
- name: unique id, up to 256 characters, no colon (reserved for plugin-scoped names). The filename does not have to match.
- description: when Claude should delegate here. This is the trigger, so write the occasion, not the personality: Use after every code change beats Helps with code.
- tools / disallowedTools: allowlist or denylist, comma-separated or YAML list. Omit tools to inherit every tool available to subagents.
- model: alias (opus, sonnet, haiku, fable), a full id such as claude-opus-5-5, or inherit.
- permissionMode: default, acceptEdits, auto, dontAsk, bypassPermissions or plan. Leave unset to follow the main session.
- maxTurns: cap on agentic turns; the partial result comes back marked and can be resumed.
- skills: skills to preload into the subagent context at startup; unlisted skills stay reachable through the Skill tool.
- memory: user, project or local enables persistent notes for this subagent across sessions.
- isolation: worktree runs the subagent in a temporary git worktree, an isolated copy of the repository, cleaned up automatically when it makes no changes.
- omitClaudeMd: set to true to start without the user, project and local CLAUDE.md files; useful for workers that take everything from the delegation prompt.
- background: spawned subagents run in the background by default; false makes the parent wait.
- mcpServers and hooks: server access and lifecycle hooks scoped to this subagent; both are ignored for plugin-provided agents.
A misspelled field is ignored without an error, which is the most common silent failure. Run claude --debug and search the debug log for does not recognize or apply when a field seems to do nothing.
How they are invoked
Claude reads the subagent descriptions and delegates automatically when
a task matches. You can also ask explicitly:
Use the code-reviewer subagent on my staged changes.
Under the hood the main session calls the Agent tool (named Task before
v2.1.63); the transcript shows a row for the subagent and its task.
Subagents work inside the current session. They can spawn their own
subagents while the depth limit allows; at the limit the Agent tool is
removed from that worker. Running subagents and the model each one uses
are listed by /tasks. A finished subagent can
be resumed for follow-up instead of re-running the task from scratch.
- Restart after the first file. When an agents directory did not exist at session start, restart Claude Code to pick up the first file.
- Restart after --add-dir edits. Agent files in added directories are not watched; restart to reload them.
- Live edits elsewhere. Files under ~/.claude/agents/ and .claude/agents/ are watched, so later edits apply within seconds.
Tools and limits
The tool list is the real contract. A read-only reviewer that cannot edit, write or run shell cannot damage the repository, no matter what the prompt says. This one can only read and search, file .claude/agents/safe-researcher.md:
vi .claude/agents/safe-researcher.md
--- name: safe-researcher description: Research agent with restricted capabilities tools: Read, Grep, Glob ---
The denylist form inherits everything except the listed tools, which is convenient but wider, file .claude/agents/no-writes.md:
vi .claude/agents/no-writes.md
--- name: no-writes description: Inherits the available tools except file writes disallowedTools: Write, Edit ---
Filters apply before your list: a few tools never reach a subagent
(AskUserQuestion,
EnterPlanMode, ScheduleWakeup,
WaitForMcpServers, Workflow,
EndConversation), and background subagents keep
only a working subset of built-ins — Read, Grep, Glob, LSP, Bash,
Edit, Write, WebFetch, WebSearch, TodoWrite, Skill and a few more. The
same definition can therefore resolve to different tools in the
foreground and the background. If nothing resolves at all, the subagent
refuses to launch with an error naming the entries.
MCP access follows the same idea. List whole servers in
disallowedTools
(mcp__github) to withhold them, or define
servers inline in mcpServers so their tools
exist only inside the subagent and cost no context in the parent. An
inline server from a project agent file loads only after you trust the
folder.
Models and cost
Route by task weight. Subagent requests count toward the same usage limits as the main conversation, so a research worker on a cheap model pays for itself while the expensive model stays on the final verdict.
| Work | Model field | Why |
|---|---|---|
| Search, triage, summaries | haiku | Fast and cheap; read-only tools. |
| Implementation, tests | sonnet or inherited session model | Balanced quality for routine edits. |
| Review, architecture, hard bugs | opus or claude-opus-5-5 | Top reasoning for the last ten percent. |
| Same as the main session | inherit | No routing decision when the session model already fits. |
Resolution order: a per-invocation model parameter, then the frontmatter model, then the CLAUDE_CODE_SUBAGENT_MODEL environment variable, then the main conversation model. Set the variable together with CLAUDE_CODE_SUBAGENT_MODEL_FORCE=1 to put every subagent on one model. A model excluded by your organization allowlist is substituted, and Claude Code shows a warning naming the requested and the actual model; /tasks shows the model a running subagent uses. The optional effort field tunes reasoning depth per subagent.
Five complete subagents
Files you can drop into .claude/agents/ today. They map to the role model from Building AI agents: read-only review, test execution, debugging, cheap research and a coordinator with an explicit spawn allowlist.
Example 1 — Opus reviewer, read-only. The final gate on staged diffs; no edit tool by design:
vi .claude/agents/code-reviewer.md
--- name: code-reviewer description: Reviews staged changes for correctness, security and missing tests. Use after every code change. tools: Read, Grep, Glob model: opus maxTurns: 12 --- Review the staged diff. Report findings in severity order with file and line. Check for missing validation, secrets and missing tests. Verdict: ship, fix first, or block. Do not edit files.
Example 2 — Sonnet test runner. Owns the test loop so failures and logs never flood the main context:
vi .claude/agents/test-runner.md
--- name: test-runner description: Runs the test suite and fixes failing tests. Use after implementation changes. tools: Read, Edit, Bash model: sonnet --- Run the narrowest test command for the change, then the full suite. On failure, quote the failing assertion, fix only the test or the code under test, and rerun. Stop after three attempts and report.
Example 3 — inherited debugger. Hard bugs get the session model, more turns and every tool:
vi .claude/agents/debugger.md
--- name: debugger description: Root-cause analysis for crashes and test failures. Use when an error resists a quick fix. model: inherit maxTurns: 20 color: orange --- Trace the error to the first wrong assumption before proposing a fix. Show the evidence chain, then apply the smallest fix and verify it.
Example 4 — Haiku researcher. Cheap read-only exploration for questions that need many files:
vi .claude/agents/safe-researcher.md
--- name: safe-researcher description: Read-only research over the codebase. Use for "where is" and "how does" questions. tools: Read, Grep, Glob model: haiku --- Answer with file paths and short quotes. Do not edit anything. State clearly when the codebase does not contain the answer.
Example 5 — coordinator with a spawn allowlist. As the main session agent it may spawn only the named children; the type list is ignored inside a subagent definition:
vi .claude/agents/coordinator.md
--- name: coordinator description: Coordinates work across specialized agents tools: Agent(worker, researcher), Read, Bash --- Plan the work in three bullets, delegate each step to worker or researcher, then merge the results into one report.
That is the subagent half of the loop. Prompts, skills and commands come from the skills guide; the tool side of MCP servers is in MCP.
Context, memory and isolation
- Own window. A subagent loads its system prompt, basic environment details and the tools it can use; it does not see the main conversation unless the prompt carries the needed context.
- CLAUDE.md. Custom subagents load the user, project and local CLAUDE.md files unless omitClaudeMd: true. The built-in Explore and Plan agents start without them for speed.
- Auto memory. The main conversation auto memory is not loaded into subagents; the memory field gives a subagent its own directory instead.
- Skills. Preload with the skills field; the full content loads at startup, not only the description.
- Worktree isolation. isolation: worktree copies the repository into a temporary git worktree; git commands that would touch the main checkout are blocked.
- Background runs. Spawned subagents run in the background by default; a parent can keep working and collect results later, or wait with background: false.
Evals before opinions
Eight fixed tasks with checkable outcomes beat any demo. Starter suite for the five examples above:
- code-reviewer x2: a planted missing input validation, a diff with a hardcoded key. Each must produce file, line and a block verdict, and must not edit.
- test-runner x2: one genuinely failing test and one flaky timing test. Both must end with a rerun result, not a guess.
- debugger x1: an off-by-one bug hidden behind a passing suite. Must show the evidence chain before the fix.
- safe-researcher x2: a real answer with paths, and a question the codebase cannot answer. The second must say so instead of inventing files.
- coordinator x1: a two-step task. Must return two child results and one merged report, and must not spawn anything outside the allowlist.
Run the suite on every prompt, tool or model change and keep the history. A two-point drop after an improvement is normal. When a role fails, the trace usually shows the cause: a vague description, a tool list that is too narrow, or a model too small for the job.
With OpenCode in one repo
Claude Code and OpenCode can share one checkout without stepping on each other, because they read different agent directories but overlap on skills: OpenCode also reads .claude/skills/, so that directory is the common home for shared procedures. Agent files stay separate: .claude/agents/ here, .opencode/agents/ there.
repo/ ├── AGENTS.md shared instructions ├── .claude/skills/ read by both tools ├── .claude/agents/ Claude Code subagents ├── .opencode/agents/ OpenCode agents └── .opencode/skills/ extra OpenCode skills
The worked scenario — triage in one tool, build in the other, review back in the first — is in Building AI agents, with the OpenCode file details in OpenCode agents.
Troubleshooting
- File skipped silently. Causes: no name (treated as documentation), opening --- not on the first line, a name starting with - or containing :, a name without description, or YAML that does not parse. Run claude --debug for the reason.
- Subagent not found after creating it. The agents directory did not exist at session start; restart once.
- Refuses to launch, names tool entries. Nothing in tools resolved to an available tool. Fix spelling or drop the field to inherit.
- Model ignored. The requested model is excluded by an allowlist or unavailable on the provider; the startup warning and /tasks name the substitution.
- Too many descriptions. When custom descriptions pass about 15,000 tokens combined, startup warns. Shorten descriptions and move detail into each system prompt, which loads only when the subagent runs.
- Wrong tools in the background. Background subagents keep a reduced built-in set. Test the role in the foreground first, then check /tasks.
Article author: Arthur Isaev