Skip to content AI News: Mistral Large 4 is open weight: what you can run, and what it costs on the API →

Claude Code Subagents: How They Work, With 6 Agent Files to Copy

When Claude hands a codebase search to a subagent, the files it reads and the commands it runs stay out of your conversation, and only the summary comes back. The subagent runs in its own context window with its own system prompt, tool access and permissions. A custom one is a markdown file in .claude/agents/, and Claude decides when to call it from the file's description.

You don't have to write the file by hand. Paste a request like this into Claude Code and it writes one for you:

Create a project subagent in .claude/agents/ named api-contract-checker.
It compares changed route handlers against openapi.yaml and reports each
mismatch with file:line. Make it read-only (tools: Read, Grep, Glob) and
use Sonnet. Write the description so Claude uses it after any change
under src/routes/.

What a subagent sees when it starts

None of your conversation. A subagent doesn't see your history, the skills you've run or the files Claude already read. It starts with:

  • its own system prompt (the file's body) plus environment details like the working directory, without Claude Code's system prompt;
  • the task message Claude writes when it delegates;
  • your CLAUDE.md files, unless the file sets omitClaudeMd: true;
  • a git status snapshot;
  • the full text of any skill named in its skills field.

Your output style and Claude's auto memory stay behind. Since the task message is all it knows about your session, a rule that matters for this one job, like "skip the vendor/ folder", goes in your request to Claude, which passes it on.

A fork is the exception: it inherits the whole conversation, model and tools, so you can hand it a side task without re-explaining anything. You start one with /subtask followed by the task.

The built-in subagents

Claude Code ships six built-in agents and uses them without being asked:

AgentModelToolsClaude uses it for
ExploreYour session's model (Opus when your session runs Fable on a subscription or Console account)Read-only; Write and Edit deniedSearching and reading code without changing it
PlanInherits your session's modelRead-only; Write and Edit deniedResearch during plan mode
general-purposeCLAUDE_CODE_SUBAGENT_MODEL if set, otherwise your session'sEvery tool available to subagentsTasks that need both exploration and edits, or several dependent steps
claudeFollows the subagent model orderEvery tool available to subagentsA task no specialized agent fits; also the default for dispatched background sessions
statusline-setupSonnet—Running /statusline
claude-code-guideHaiku—Questions about Claude Code features

Explore and Plan skip your CLAUDE.md files and git status to stay fast, and they can't be resumed, because they return no agent ID.

Subagents, agent teams or parallel sessions?

Use subagents when Claude should delegate and collect the results inside one conversation. Anthropic lists five ways to run several tasks at once, and they differ in who coordinates:

ApproachWho coordinatesDo workers talk?Use it when
SubagentsClaude, inside your sessionThey report to the caller; ones Claude named can message each otherA side task would flood your conversation with search results or logs
Agent view (claude agents), research previewYou dispatch and check backSessions report only to youSeveral independent tasks you want to hand off and watch
Agent teams, experimental and off by defaultA lead session assigns and supervisesTeammates message each other directlyA project split into pieces that need discussion
Dynamic workflowsA script holds the planThe script cross-checks resultsA codebase-wide audit, a 500-file migration
Projects, public beta on Pro and MaxClaude, across threads over daysClaude shows you which threads need youWork that should keep running when your machine is off

Teams are the costly option: about 7x the tokens of a standard session when teammates run in plan mode. They also don't isolate teammates in worktrees, so give each teammate a different part of the code to own, such as the frontend, the backend or the tests. Start with subagents. Switch to a team when workers have to challenge each other's findings, like debugging with competing hypotheses.

With CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 set, a subagent Claude names launches as a teammate, so a team can form when you only asked for a subagent.

Where subagent files go

In .claude/agents/ for one project or ~/.claude/agents/ for all of them. Three other locations load too, and the higher one wins when two files share a name:

LocationScopePriority
Managed settingsYour organization1 (highest)
--agents CLI flagThe current session2
.claude/agents/The current project3
~/.claude/agents/All your projects4
A plugin's agents/ folderWherever the plugin is enabled5 (lowest)

Both folders are scanned recursively, so agents/review/security.md works, and the agent's identity comes from name alone. Edits load within a few seconds with no restart. The one case that needs a restart is the first file in an agents folder that didn't exist when the session began. Plugin subagents ignore hooks, mcpServers and permissionMode; copy the file into .claude/agents/ if you need them.

Every front-matter field

Only name and description are required. Field names are camelCase, like maxTurns, and Claude Code ignores one it doesn't recognize without reporting an error. To catch a typo, start claude --debug and search ~/.claude/debug/<session-id>.txt for does not recognize or apply. The log names up to five unknown fields and the likely intended one.

FieldWhat it does
nameUnique ID, up to 256 characters, no :
descriptionWhen Claude should delegate to it
toolsAllowlist, comma-separated or a YAML list; leave it out to inherit every tool available to subagents
disallowedToolsDenylist, applied before tools; Bash(git push *) here removes all of Bash
modelsonnet, opus, haiku, fable, a full ID like claude-opus-5-5, or inherit
permissionModedefault, acceptEdits, auto, dontAsk, bypassPermissions or plan
maxTurnsTurn cap; output returns marked partial and can be resumed
autoCompactWindowCompact earlier, from 100000 to 1000000 tokens, as a plain integer
skillsSkills whose full text loads at startup
mcpServersMCP servers for this subagent only, by name or defined inline
hooksHooks that run only while it's active
memoryA notes folder that survives sessions: user, project or local
backgroundtrue keeps it in the background even when Claude asks to wait for it; Claude-spawned subagents start there by default
omitClaudeMdtrue starts it without your CLAUDE.md files
effortlow, medium, high, xhigh or max, depending on the model
isolationworktree runs it in a temporary git worktree
colorred, blue, green, yellow, purple, orange, pink or cyan
initialPromptThe first user turn when the agent runs as the main session
experimentalA map; its cacheTtl key takes 5m or 1h

Claude Code resolves the model in this order: an alias Claude passes when it spawns the subagent, the file's model, the CLAUDE_CODE_SUBAGENT_MODEL variable, then your session's model.

Two fields do less than they look like they do. permissionMode is ignored when your session runs in auto, acceptEdits or bypassPermissions; the subagent takes your mode. And memory switches on Read, Write and Edit so the subagent can manage its notes, which gives a "read-only" reviewer write access. The hooks field uses the same events and matcher nesting as hooks in settings.json.

Six subagent files to copy

Save each one as a .md file in .claude/agents/. The description does the routing: Claude matches it against your request and the current context, and phrases like "use proactively" encourage it to delegate unprompted. Keep descriptions short. They sit in Claude's context every session, and past 15,000 tokens combined, Claude Code warns at startup.

1. Read-only diff reviewer

---
name: diff-reviewer
description: Reviews uncommitted changes for bugs, missing error handling and leaked secrets. Use proactively after code is written or modified, before a commit.
tools: Read, Grep, Glob, Bash
model: sonnet
color: blue
---
You review changes you didn't write. Start with `git status` and `git diff HEAD`.
Read each changed file in full before judging a hunk.
Report, in this order:
1. Bugs that change behavior, with file:line and a one-line fix.
2. Missing error handling or input validation on new code paths.
3. Secrets, keys or credentials added anywhere in the diff.
Skip style and naming. If nothing qualifies, reply "No blocking issues."
Never run a command that modifies files, branches or the git index.

The description asks for a review after every edit. With no Edit or Write it can't change files through those tools, but Bash runs anything, so add deny rules such as Bash(git push *) to permissions.deny. A Bash deny rule applies to subagents too.

2. Test runner on Haiku

---
name: test-runner
description: Runs the project's tests and reports only failures. Use when tests need running after a change, or when the user asks whether tests pass.
tools: Bash, Read, Grep, Glob
model: haiku
effort: low
maxTurns: 12
color: green
---
Find the test command in package.json, pyproject.toml or the Makefile, and run it.
If the full suite is slow, run only the tests for files listed by `git diff --name-only`.
Reply with:
- passed / failed / skipped counts
- for each failure: test name, assertion message, file:line
Don't fix code. Don't paste the full log.

The log stays in the subagent's context, and Haiku is the model suggested for simple subagent tasks.

3. Docs researcher

---
name: docs-researcher
description: Looks up how a third-party library, API or CLI flag works in its official docs and returns the answer with source URLs. Use for questions about external APIs, versions or config options.
tools: WebSearch, WebFetch, Read, Grep, Glob
model: haiku
omitClaudeMd: true
---
Answer the question you're given from official sources only: the vendor's docs, its GitHub repo or its changelog.
Give the URL you read each claim on.
Check the installed version in the lockfile (package-lock.json, poetry.lock, go.sum) and say which version the answer applies to.
If official sources don't answer it, say so. Don't guess.
Return at most 15 lines.

omitClaudeMd keeps your project rules out of a job that takes everything it needs from the delegation prompt. Swap haiku for sonnet if the answers come back thin.

4. Migration planner

---
name: migration-planner
description: Plans multi-file migrations (framework upgrades, API version changes, schema changes) before any code is touched. Use when the user asks to upgrade, migrate or replace a dependency across the codebase.
tools: Read, Grep, Glob
model: opus
effort: high
permissionMode: plan
---
You plan. You don't edit.
1. Find every call site of the API or module being replaced. Count them per directory.
2. Read the target version's migration guide or changelog if it's in the repo or node_modules.
3. Group the changes into steps that each leave the build passing.
4. For each step, list the files, the change, how to verify it and how to roll it back.
5. Flag anything that needs a human decision.
End with the total file count and the riskiest step.

Because permissionMode gives way to an auto or acceptEdits session, the read-only tools list is what keeps it from editing.

5. Refactor in a worktree

---
name: worktree-refactor
description: Carries out one mechanical multi-file refactor (rename, signature change, import path move) in an isolated git worktree. Use when a planned change touches many files and should stay out of the user's checkout.
tools: Read, Edit, Write, Bash, Grep, Glob
model: sonnet
isolation: worktree
maxTurns: 40
---
Apply exactly the change described in your task and nothing else.
After each group of files, run the type checker or build and fix what you broke.
When done, run the test suite once.
Reply with the branch name, the files changed and the final test result.
If a file needs a judgment call, leave it unchanged and list it.

Hand it the work after the planner, once the change is mechanical. The worktree branches from your default branch, not your current HEAD, so land what the refactor depends on in that branch first. A worktree with no changes is cleaned up on its own.

6. Explore on Haiku

---
name: Explore
description: Fast read-only codebase search. Use to find files, symbols and call sites, or to answer "where is X handled".
tools: Read, Grep, Glob
model: haiku
omitClaudeMd: true
---
Answer with file paths and line numbers.
Read only what the question needs. Don't summarize files you weren't asked about.

A project or user file named Explore overrides the built-in and keeps its own model, so this file moves exploration onto Haiku. Custom subagents load your CLAUDE.md files and the built-in doesn't; omitClaudeMd drops them here too. In ~/.claude/agents/ it covers every project; delete the file to get the built-in back.

How to call a subagent yourself

Name it, @-mention it, or run the whole session as it. Each step takes more of the choice away from Claude:

Use the diff-reviewer subagent on my last three commits
@"diff-reviewer (agent)" check the auth changes
claude --agent migration-planner
  • Plain words: Claude still decides whether to delegate.
  • @-mention: type @ and pick it, or type @agent-diff-reviewer. That subagent runs, and Claude writes its task prompt from your message.
  • --agent: the main thread takes on the agent's tools and model, and its body replaces Claude Code's system prompt. "agent": "diff-reviewer" in .claude/settings.json makes it the project default.
  • --agents '{...}': defines subagents as JSON for one session, handy in scripts.

To continue a finished one, say so: "Continue that review and check the authorization logic" resumes it with its full history. Run /tasks to see which model each running subagent is on.

Building your own app on the Agent SDK works the same way: subagents go in the agents option of query(), or in .claude/agents/ files.

Subagents Claude spawns from your conversation start in the background, so you can keep typing, and a permission prompt shows up in your session with the subagent's name on it. A background subagent keeps every MCP tool but only a fixed set of built-ins, Read, Grep, Glob, Bash, Edit, Write, WebFetch and WebSearch among them. Anything else in your tools list is dropped without an error.

What a subagent costs

A subagent saves context and spends usage. Its requests count toward the same usage limits as your main conversation, and its summary lands in your context when it's done. Three things set the bill:

On a Pro, Max, Team or Enterprise plan, /usage shows the share of recent usage that went to subagents. To force one model onto every subagent, Explore included, set CLAUDE_CODE_SUBAGENT_MODEL and CLAUDE_CODE_SUBAGENT_MODEL_FORCE=1 in the env block of your settings. More ways to keep a session cheap are in the Claude Code best practices.

When not to use a subagent

Skip it when the task needs your conversation. Stay in the main session for:

  • work with frequent back-and-forth or iterative refinement;
  • phases that share a lot of context, like planning, building and testing one feature;
  • a quick, targeted change;
  • anything where latency matters, since a fresh subagent has to gather context first.

Two lighter tools cover the edges. For a question about something already in the conversation, /btw answers with your full context, no tools, and nothing added to history. For a reusable procedure that should run with your context, write a Claude Code skill. A subagent pays off when the output is big and the answer is small. If its task message would need half your conversation pasted in, use a fork or do it in the main session.

When a subagent doesn't show up

  • Skipped file. Claude Code skips a file silently when it has no name, a name without a description, an opening --- that isn't line one, or YAML that doesn't parse.
  • Blocked by settings. An entry like Agent(Explore) in permissions.deny disables that subagent by name.

To give the diff reviewer a sharper task than "review my changes", pick one of the Claude Code prompts and @-mention the agent in front of it.

Sources

Weekly

New prompts in your inbox

One email a week: the best new prompts and one short guide. Confirm by email and get the free Prompt Cheat Sheet (PDF). Unsubscribe any time. Privacy policy