Claude Code subagents: when to use them and how to write your own

Claude Code subagents: when to use them and how to write your own

Claude Code subagents are separate Claude instances that the main session hands a task to; each runs in its own context window with its own system prompt, tools and permissions, and returns only a summary. This guide covers the built-in subagents, when delegation helps, how to write custom agents and the settings that control them.

In shortTL;DR
  • A subagent starts with a fresh context, does one job and returns a summary, which keeps search results and logs out of your main conversation.
  • Claude Code ships built-in subagents such as Explore (read-only search), Plan and general-purpose; you rarely need to call them by name.
  • Custom subagents are Markdown files with YAML front matter in .claude/agents/ (project) or ~/.claude/agents/ (personal); only name and description are required.
  • The description decides when Claude delegates, so write it as a routing rule, and restrict tools to what the job needs.
  • Use subagents for isolated, verbose or parallel work; keep tightly coupled edits in the main session.

What are Claude Code subagents?

Claude Code subagents are specialized helpers that the main Claude Code session delegates work to. Each one runs in its own context window with a custom system prompt, its own tool access and its own permissions. It does the job and hands back a summary, so the verbose middle part (file contents, search hits, test logs) never lands in your main conversation.

The Claude Code subagents documentation describes three things you get from that separation:

  • Context isolation. A subagent starts fresh. It does not see your conversation history, only its system prompt, the task message Claude wrote for it, your CLAUDE.md files and a snapshot of git status.
  • Tool and permission limits. You can give a reviewer read-only tools, or let a debugger edit but not browse the web.
  • A different model per job. A file search can run on a fast, cheap model while the main session uses a stronger one.

Subagents live inside one Claude Code session. If you want several fully independent sessions working on different branches, that is a different setup, covered in our guide to git worktrees for parallel agents.

Which subagents come built in?

Claude Code ships several built-in subagents and uses them on its own. You mostly notice them as "Explore" or "Plan" steps in the transcript.

Built-in subagentToolsWhat it is for
ExploreRead-only (no Write or Edit)Fast file discovery and codebase search, at a thoroughness level Claude picks
PlanRead-onlyResearch while you are in plan mode
general-purposeAll tools available to subagentsMulti-step tasks that need both exploration and changes
claude-code-guideNot specifiedAnswering questions about Claude Code itself
statusline-setupNot specifiedRuns when you use /statusline

A few behaviors worth knowing:

  • Explore and Plan skip CLAUDE.md and the git status snapshot to stay fast, and they are one-shot (they cannot be resumed).
  • If you create your own subagent named Explore, it overrides the built-in one.
  • You can turn off a built-in agent by adding Agent(Explore) to permissions.deny in settings.

When should you use a subagent?

Use a subagent when a piece of work is self-contained, produces a lot of intermediate output, or can run in parallel with other work. Keep work in the main session when each step depends closely on the previous one or when you want to watch and steer every edit.

Good fits:

  • Codebase research. "Find every place we read the STRIPE_KEY env var and how it is validated." The subagent reads 40 files; you get a list of five locations.
  • Running and triaging tests. A test subagent runs the suite, reads the failure output and reports the three real failures with likely causes.
  • Independent reviews. A reviewer with a fresh context looks at the diff without the main session's assumptions about why the code is right.
  • Parallel investigation. Three subagents each check one hypothesis for a bug at the same time.

Poor fits:

  • One coherent change across a few files. Splitting it means each subagent lacks the full picture, and the main session spends effort stitching results back together.
  • Tasks where you need the reasoning, not only the result. You only see the summary, so if you need to follow how a conclusion was reached, keep the work in the main thread.
  • Small tasks. Spinning up a subagent for a two-line edit adds overhead and tokens.

The same trade-offs apply to agent systems in general; our explainer on multi-agent systems covers when splitting work helps and when coordination costs win.

How do you create a custom subagent?

A custom subagent is a Markdown file with YAML front matter. The front matter configures it, and the Markdown body becomes its system prompt. Put project agents in .claude/agents/ (commit them so your team shares them) and personal ones in ~/.claude/agents/.

Step by step:

  1. Create the folder: mkdir -p .claude/agents.
  2. Add a file such as .claude/agents/test-runner.md.
  3. Write the front matter with at least name and description.
  4. Write the system prompt in the body: role, steps, output format.
  5. Test it with an explicit request. If Claude does not pick it up, start a new session.
.claude/agents/test-runner.md
---name: test-runnerdescription: Runs tests and diagnoses failures. Use proactively after code changes and whenever the user asks to run or fix tests.tools: Read, Grep, Glob, Bashmodel: haiku---You run this project's tests and explain failures. You never edit files.When invoked:1. Run only the test files related to the changed code (see CLAUDE.md for commands).2. For each failure, read the failing test and the code under test.3. Report, for each failure: test name, the assertion that failed, the most likely   cause in one sentence, and the file and line to look at.Keep the report under 200 words. Do not paste full stack traces.

You can also ask Claude to write the file for you, for example: "Create a project subagent in .claude/agents/ that reviews database migrations for missing indexes and unsafe locks. Make it read-only and use Sonnet." Then edit what it produces.

For a one-off session, you can pass agents as JSON instead of files with the --agents flag. That is handy for testing a definition before you commit it.

Which frontmatter fields matter?

Only name and description are required, but tools and model are the two you should set on almost every subagent. The docs warn that field names are camelCase and unrecognized fields are silently ignored, so a typo fails quietly.

FieldWhat it does
nameUnique identifier, used for explicit calls
descriptionTells Claude when to delegate to this agent
toolsAllowlist of tools; omit it and the agent inherits all subagent tools
disallowedToolsDenylist, for example mcp__github to block a whole MCP server
modelhaiku, sonnet, opus, fable, a full model ID, or inherit
permissionModeFor example plan for read-only behavior or acceptEdits
skillsSkills preloaded into the subagent's context
mcpServersMCP servers available to this agent only
hooksPreToolUse, PostToolUse or Stop hooks scoped to this agent
memoryuser, project or local for a persistent memory folder
maxTurnsHard cap on agentic turns
isolationworktree runs the agent in a temporary git worktree
omitClaudeMdSkip CLAUDE.md files for this agent

Two fields deserve extra care:

  • description is a routing rule. Claude reads every subagent description to decide where a task goes, and the docs mention a combined budget of 15,000 tokens for these descriptions. Say what the agent does and when to use it. Phrases like "Use proactively after code changes" make automatic delegation more likely.
  • tools is your main safety control. A reviewer does not need Edit or Write. A research agent may not need Bash. Fewer tools also keep the agent focused.
Tip

For rules that a prompt cannot guarantee, add a hook. The docs show a db-reader subagent with a PreToolUse hook that runs a script on every Bash command and blocks SQL writes by exiting with code 2. See our guide to Claude Code hooks for how hook exit codes work.

How do you invoke a subagent?

Claude delegates automatically when a request matches a subagent's description. You can also call one explicitly in three ways:

  • By name in plain language: "Use the test-runner subagent to check the billing tests."
  • With an @-mention: type @ and pick the agent from the list, or write @agent-test-runner.
  • As the whole session: claude --agent code-reviewer runs the entire session with that agent's prompt, tools and model. Setting "agent": "code-reviewer" in .claude/settings.json makes it the default for the project.

The /agents command behavior has changed across versions; in recent versions it points you to edit the agent folders directly or ask Claude to do it.

Foreground, background and forks

Recent Claude Code versions start subagents in the background by default, so you can keep talking to the main session while they work. Background subagents surface their permission prompts in your main session. If you prefer Claude to wait for each result, the docs describe setting CLAUDE_CODE_FORK_SUBAGENT=0.

Claude can also start a fork: a subagent that inherits the full conversation instead of a fresh context. Because a fork shares the main session's system prompt and tools, its first request reuses the parent's prompt cache, which makes it cheaper than a fresh subagent when the task needs the same context.

Three subagents worth copying

These three cover most of what teams use subagents for. Adjust the commands to your project.

.claude/agents/code-reviewer.md
---name: code-reviewerdescription: Reviews the current diff for bugs, security issues and missing tests. Use proactively after writing or modifying code, before committing.tools: Read, Grep, Glob, Bashmodel: inherit---You are a senior reviewer. Run `git diff` and review only the changed code.Report findings in three groups: must fix, should fix, consider.For each finding give the file and line, the problem, and a concrete fix.Check for: unhandled errors, unvalidated input, secrets in code, missing testsfor new branches, and changes that break existing callers.Do not comment on formatting; the formatter handles it.
.claude/agents/researcher.md
---name: researcherdescription: Answers questions about how this codebase works by reading code. Use for "where is", "how does", and "what calls" questions.tools: Read, Grep, Globmodel: haiku---Answer the question by reading code. Cite file paths and line numbers for everyclaim. If you are unsure, say what you checked and what is still unknown.Keep the answer under 250 words.
.claude/agents/migration-checker.md
---name: migration-checkerdescription: Reviews new database migrations for unsafe locks, missing indexes and irreversible changes. Use when a migration file is added or edited.tools: Read, Grep, Globmodel: sonnet---Review each new migration. Flag: table rewrites on large tables, missingindexes on new foreign keys, dropped columns still referenced in code, andmigrations with no down step. End with a one-line verdict: safe, needschanges, or needs a human.

The reviewer pairs well with an automated review step in CI; our article on AI code review covers what AI reviewers catch and what they miss.

Common mistakes with subagents

Most subagent problems come from vague descriptions, too many tools, or using delegation where it adds nothing.

  • Generic descriptions. "Helps with code" never routes correctly. Name the trigger: which files, which requests, which moment.
  • Inherited everything. Omitting tools gives the agent every tool. Decide explicitly.
  • No output format. Without one, a subagent's summary can be as long as the work it was meant to absorb. Ask for a short, structured report.
  • Expecting shared memory. The subagent does not see your conversation. Put what it needs in the task message, CLAUDE.md or the agent's prompt.
  • Overlapping agents. Two agents with similar descriptions make delegation unpredictable. Merge them or sharpen the boundary.
  • Delegating tightly coupled work. If step two needs every detail of step one, keep both in the main session.

How to start with subagents today

Start small and add agents only when you notice a repeated need:

  1. Watch a few sessions and note where the main context fills with search results or logs.
  2. Write one read-only agent for that job (research or test triage) with tools and model set.
  3. Give it a routing description with a clear trigger and an output limit.
  4. Commit it to .claude/agents/ so your team gets the same behavior.
  5. Add a reviewer agent next, and a hook if any rule must hold no matter what.

Subagents make long sessions practical, and long sessions are where a closed laptop becomes the bottleneck. If you want Claude Code and its subagents to keep working overnight on your own Claude account, Orkio runs them on an always-on cloud box that you check from your phone. If you are new to the tool itself, start with the Claude Code tutorial and a solid CLAUDE.md.

Frequently asked questions

What is the difference between a subagent and a skill in Claude Code?

A skill is a set of instructions and files that loads into the current conversation when relevant. A subagent is a separate Claude instance with its own context window, tools and permissions that returns a summary. Use a skill to teach the main session how to do something, and a subagent to do a self-contained job without filling the main context.

Do subagents cost more tokens?

Each subagent builds its own context, so a task split across several subagents usually consumes more tokens in total than doing it in one session. The trade is that your main conversation stays small and focused. Routing simple subagents such as search or test runs to a cheaper model like Haiku offsets part of the cost.

Can a Claude Code subagent start its own subagents?

Yes. According to the Claude Code docs, subagents can spawn further subagents by default, up to three levels below the main conversation. You can lower that limit with the CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH environment variable, or leave Agent out of a subagent's tools list to stop it from spawning.

Do subagents read my CLAUDE.md?

Custom subagents receive your CLAUDE.md files in their starting context, along with their own system prompt and the task message. The built-in Explore and Plan agents skip CLAUDE.md, and you can make a custom subagent skip it with the omitClaudeMd field.

How many subagents can run at once?

The Claude Code docs say up to 20 subagents can run concurrently by default, configurable with CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS. In practice you hit usage limits and review capacity long before that, so a handful of parallel subagents is a more useful working number.

SOURCES

  1. Claude Code docs: Create custom subagents
  2. Claude Code docs: Hooks reference
  3. Claude Code docs: Prompt caching
  • #claude code
  • #subagents
  • #ai agents
  • #ai coding
Orkio team

The team building Orkio. We write about putting AI to work: coding agents that run overnight, always-on boxes and pull requests ready by morning.

Keep reading

All posts

07:06 · YOU MERGED #128

Go to sleep. Wake up to pull requests.

Start for $19 a month
© 2026 Orkio · Hosted in Europe TürkçeStatus