A subagent is a second Claude with one job. It gets its own context window, its own system prompt and its own tool list. It does the work and hands back a summary, so your main thread stays clean.
Use one when a side task would flood your conversation with output you won't read again. Or when the job should have fewer tools than you do, like a reviewer that can't edit code.
What is a Claude Code subagent?
A Claude Code subagent is a markdown file with YAML frontmatter, saved in .claude/agents/. The frontmatter sets its name, when to use it and which tools it gets. The body is its system prompt.
What makes it different from just asking Claude:
- Own context window. It starts fresh. It doesn't see your conversation.
- Own system prompt. Its markdown body replaces the Claude Code system prompt.
- Own tools. You can give it three tools, or one MCP server, and nothing else.
- Only the summary comes back. It can read 40 files. You get the answer.
Subagents count toward the same usage limits as your main conversation. Isolation saves context, not tokens.
Where subagent files live
| Location | Scope |
|---|---|
.claude/agents/ | This project. Commit it |
~/.claude/agents/ | You, in every project |
A plugin's agents/ folder | Wherever the plugin is on |
The --agents CLI flag (JSON) | One session |
| Managed settings | The whole organization |
When two share a name, managed wins, then the CLI flag, then project, then user, then plugin. Folders are scanned recursively, so you can group agents in subfolders.
Copy this: a minimal subagent
A generic starter, not from the generator. Save it as .claude/agents/test-runner.md:
---
name: test-runner
description: Runs the test suite and reports only the failures. Use after code changes, or when the user asks why tests fail.
tools: Read, Grep, Glob, Bash
model: haiku
---
You run tests and report failures. You never edit files.
1. Find the test script in package.json and run it once.
2. For each failure, give the test name, the file and line, and the first error line.
3. Read the failing test and the code under test. Say the likely cause in one sentence.
4. If everything passes, say so in one line.
Never paste the full log. Never rerun tests hoping they pass.
Then ask "use the test-runner subagent to check my last change". Or let Claude pick it, since the description says when.
The frontmatter fields
Only name and description are required.
| Field | What it does |
|---|---|
name | Unique id, like pr-reviewer. No : and no leading - |
description | When Claude should hand work to it. Keep it short |
tools | The tools it gets. Leave it out and it inherits every tool |
disallowedTools | Tools to remove from what it would get |
model | sonnet, opus, haiku, inherit, or a full model ID |
permissionMode | default, acceptEdits, plan and others |
skills | Skills loaded into its context at start |
mcpServers | MCP servers it can use, by name or defined inline |
hooks | Hooks that run only while it is active |
memory | user, project or local, for notes that persist across sessions |
maxTurns | Stop after this many turns |
isolation | worktree runs it in a temporary git worktree |
tools takes MCP servers too. mcp__neon means every tool from the Neon MCP server.
How Claude picks a subagent
- Automatically. Claude reads every subagent's description and delegates when a task matches. Put "use proactively" in the description to nudge it.
- By name. "Use the pr-reviewer subagent on this branch." Claude still decides.
- With an @-mention.
@agent-pr-reviewerguarantees that subagent runs. - For a whole session.
claude --agent pr-reviewerruns the session as that agent.
Claude Code also has built-in subagents. Explore and Plan are read-only and skip CLAUDE.md for speed. general-purpose gets every tool.
Real example: a read-only database inspector
This is db-inspector, which the Neon battery adds to a generated repo. The first part, quoted as generated:
---
description: Read-only Neon Postgres inspector. Explains schema, data shape and query plans. Runs SELECT and EXPLAIN only, and refuses every statement that writes or changes schema.
name: db-inspector
tools:
- Read
- Grep
- Glob
- Bash
- mcp__neon
---
You inspect the Neon Postgres database behind my-app and report what you
find. You never change it. Not the data, not the schema, not the settings, not
the branches.
## Refusal contract
This is not a preference you weigh against the user's request. It is the
definition of your job.
**You may run exactly two kinds of statement:**
1. `select ...` (including `with ... select`, `select` on `information_schema`, `pg_catalog`, `pg_stat_*`)
2. `explain ...` and `explain (analyze false, buffers false, format text) ...`
**You must refuse everything else**, including but not limited to: `insert`,
`update`, `delete`, `merge`, `truncate`, `copy ... from`, `create`, `alter`,
`drop`, `comment on`, `grant`, `revoke`, `vacuum`, `analyze`, `reindex`,
`refresh materialized view`, `call`, `do`, `set` (other than a read-only
`set local statement_timeout`), `begin`/`commit`, `select ... for update`,
`select pg_terminate_backend(...)`, and any function whose purpose is to write.
**`explain analyze` is a write.** It executes the statement. Refuse it for
anything but a bare `select`, and prefer plain `explain` even then.
**Neon control-plane operations are also writes.** You do not create, delete,
reset or restore branches; you do not change compute settings; you do not rotate
credentials. `neonctl branches list` and `neonctl projects list` are fine.
When you refuse, say so in one sentence, name the statement you will not run, and
offer the read-only alternative or the migration file the change belongs in. Do
not write the migration yourself unless the user asks for it as a file - and even
then you produce a file, you do not apply it.
First 43 of 117 lines of .claude/agents/db-inspector.md.
Look at what carries the weight:
- The tool list.
Read,Grep,Glob,Bashand the Neon MCP server. NoEdit, noWrite. - A refusal contract. Exactly two kinds of statement are allowed. Everything else is named and refused. It even calls
explain analyzea write, because it runs the query. - The read-only MCP server.
.mcp.jsonopens Neon with?readonly=true.
Be honest about the gap. It still has Bash, so only its prompt stands between it and a write through psql. The guard-neon-sql hook blocks DDL and unqualified deletes, not insert or update. Defense in depth means stacking all three, and knowing which one is only a request.
Real example: a PR reviewer that cites your rules
pr-reviewer ships in every generated repo. It reviews against the rules the repo already wrote down, not its own taste:
---
description: Reviews a diff against this repo's rules before it becomes a PR. Convention-aware, blocking on correctness and security, advisory on taste.
name: pr-reviewer
tools:
- Read
- Grep
- Glob
- Bash
---
You are the PR reviewer for this repository. You review a change *against the
rules this repo has already written down*, not against your own preferences.
A reviewer who invents new standards mid-review is worse than no reviewer.
## Before you read a single line of the diff
1. Read every file in `.claude/rules/`. These are the standards. If the diff
violates one, cite the rule id in your finding.
2. Read `CLAUDE.md` for the project's own conventions and `DESIGN.md` if the
diff touches `src/components/**` or `src/app/**`.
3. Skim `docs/solutions/` for docs whose tags overlap the changed paths. If a
solution doc already documents the correct pattern and the diff does
something else, that is a finding, and you link the doc.
4. Get the diff: `git diff main...HEAD` (or the range you were given). Read the
whole thing before commenting on any of it.
## What you review, in priority order
1. **Correctness.** Does it do what it claims? Walk the unhappy paths: empty
list, null session, provider timeout, duplicate webhook, concurrent request,
`undefined` from an indexed read (`noUncheckedIndexedAccess` is on).
2. **Security.** Secrets in code or logs, missing authorisation check in the
handler that does the work, unvalidated input crossing a boundary, raw SQL
interpolation, `NEXT_PUBLIC_` misuse, unverified webhook signature, PII in
breadcrumbs. Cross-check against `.claude/rules/security.md`.
3. **Server/client boundary.** A `"use client"` file that pulls in server-only
code or a private env var. A page marked client for one interactive leaf.
4. **Data and migrations.** Migration ordering, backwards compatibility with the
currently deployed revision, missing index on a new lookup path, N+1 queries.
5. **Tests.** Does the change carry the tests `.claude/rules/testing.md`
requires? For a bug fix, is there a test that would have failed before?
6. **Rule compliance.** Naming, exports, imports, error handling, comments.
7. **Clarity.** Only after all of the above. Suggest, do not demand.
## How you verify
You may run read-only and check commands: `git diff`, `git log`, `grep`,
`bun run typecheck`, `bun run lint`, `bun run test`. Report what you ran
and what it said. If you did not run something, do not imply that you did.
First 49 of 89 lines of .claude/agents/pr-reviewer.md.
It reads .claude/rules/ before the diff, so every finding can cite a rule id. It can run checks (typecheck, lint, test) but its prompt bans any command that writes, installs, migrates or deploys. The rest of the file sets a fixed output: verdict, blocking, non-blocking, missing tests, verified.
All 7 subagents in a generated Next.js repo
The Indie SaaS preset ships these:
db-inspector: Read-only Neon Postgres inspector. Explains schema, data shape and query plans. Runs SELECT and EXPLAIN only, and refuses every statement that writes or changes schema.designer: Owns the Daylight design system and its shadcn bridge. The only agent allowed to introduce a new visual pattern or a new token. Refuses to ship a raw colour or a single-mode change.documentarian: Keeps README, CLAUDE.md, DESIGN.md, docs/onboard.md and docs/solutions/ true to the code. Writes solution docs from work that just landed.pr-reviewer: Reviews a diff against this repo's rules before it becomes a PR. Convention-aware, blocking on correctness and security, advisory on taste.product-analyst: Read-only product analyst. Answers questions about user behaviour from the event catalogue and the PostHog project, and says plainly when the instrumentation cannot answer them.security-auditor: Audits the repo or a diff for leaked secrets, broken auth boundaries, injection, unsafe dependencies and unsafe deploy configuration.system-manager: Maintains the .claude agentic layer itself, rules, skills, agents, hooks, settings. Adds a rule when a correction repeats.
Four come with the stack in every repo: pr-reviewer, security-auditor, documentarian and system-manager. Every design adds designer. Neon adds db-inspector. PostHog adds product-analyst, which gets Read, Grep, Glob and the PostHog MCP server, and nothing else. It can answer questions about your events. It can't change them.
system-manager is the one that keeps the setup alive. It owns .claude/ itself. When you correct an agent on the same thing twice, it turns the correction into a rule.
Tool lists are the real boundary
A prompt that says "never edit files" is a request. A tool list without Edit and Write is a fact.
- Leave out
toolsand the subagent gets every tool available to subagents. That is the default, and it is rarely what you want. - Give read-only roles read-only tools.
Read, Grep, Globcovers most reviewers and analysts. disallowedTools: Bash(git push *)removes all of Bash, not just that command. To block one command and keep Bash, use apermissions.denyrule or a hook.- Hooks still apply. Your
PreToolUseandPostToolUsehooks fire on a subagent's tool calls too, with itsagent_typein the payload. A guard onrm -rfcovers every agent. See Claude Code hooks.
Subagents vs skills
| Subagent | Skill | |
|---|---|---|
| What it is | A separate worker | Instructions, a workflow or reference |
| Context | Its own window | Loads into yours |
| What comes back | A summary | Everything stays in your thread |
| Tools | Its own list | Yours, plus any allowed-tools |
| Best for | Reading a lot, parallel work, restricted roles | Procedures and reference |
They combine. A subagent's skills: field preloads skills into it. A skill with context: fork runs inside a subagent. In the generated repo, the /security-audit skill runs its pass through the security-auditor subagent. Details in Claude Code skills.
When to use a subagent, and when not to
Use one when:
- The task produces a lot of output you won't reference again: test logs, search results, big files.
- The role needs fewer tools than the main thread.
- The work is self-contained and a summary is enough.
- You want parallel research, like three modules at once.
Skip it when:
- You need back-and-forth to refine the result.
- Planning, building and testing share a lot of context.
- It is a quick, targeted edit. A fresh subagent has to rebuild context first.
Claude Code subagents best practices
- One job each. "Reviews diffs" beats "helps with code quality".
- Explicit tools, always. Start from the smallest list that does the job.
- A description that says when. It is the routing signal. Keep it short.
- Say what it never does. Edit, commit, push, install, migrate. Put it in writing.
- Fix the output format. A verdict line, then findings, then what it checked.
- Point it at your rules. A reviewer that reads
.claude/rules/first gives findings you can act on. - Pick a model on purpose. A cheap model for search and test runs. A strong one for review.
- Commit
.claude/agents/. The team should get the same specialists.
Common mistakes
- No
toolsfield. The "read-only" agent can edit everything. - Trusting the prompt alone. Back read-only roles with tool lists and hooks.
- Vague descriptions. Claude either never picks it or picks it for everything.
- Expecting it to know the conversation. A regular subagent starts fresh. It gets its own prompt, the task Claude writes for it,
CLAUDE.md, git status and any skills inskills:. Put what it needs in the task. - A subagent for a two-line fix. You pay for a fresh start and gain nothing.
- Broken frontmatter. A file with a
namebut nodescriptionis skipped. So is a name with:in it.
Get these subagents in your repo
The generator writes the subagents for your picks into .claude/agents/, next to the rules, skills and hooks they rely on. Build a repo in the builder, start from Indie SaaS, or run:
npm create agentic-boilerplate@latest my-app
The agentic layer docs explain how agents fit with the rest. The Claude Code setup for Next.js puts the whole thing on one page.
FAQ
What is a Claude Code subagent?
A subagent is a specialized Claude defined in a markdown file in .claude/agents/. It runs in its own context window with its own system prompt and tools, and returns only a summary to the main conversation.
Where do I put custom Claude Code agents?
Project subagents go in .claude/agents/, one markdown file each, and get committed. Personal ones go in ~/.claude/agents/ and work in every project.
What is the difference between Claude Code agents and skills?
A skill is instructions that load into your current conversation. A subagent is a separate worker with its own context and tool list that hands back a summary. A subagent can preload skills, and a skill can run in a subagent with context: fork.
How do I make Claude use a specific subagent?
@-mention it, like @agent-pr-reviewer. That guarantees it runs. Naming it in plain words also works, but Claude decides.
Does a subagent see my conversation?
No. A regular subagent starts with its own system prompt, the task Claude writes for it, CLAUDE.md and git status. Forks are the exception: they inherit the whole conversation.
What tools does a subagent get by default?
Every tool available to subagents, if you leave out the tools field. Set tools explicitly for any role that should not edit, run commands or call MCP servers.
Sources
Tool behavior is from the official docs, checked on October 4, 2026. Tools change. The docs win.
Keep reading
- CLAUDE.md template for Next.js, from a real repoA CLAUDE.md template for Next.js you can copy, a real one from a generated repo, where the file goes, what belongs in it, and the mistakes that get it ignored.
- AGENTS.md examples, from a real Next.js repoWhat AGENTS.md is, a template to copy, real root and nested AGENTS.md files from a generated Next.js repo, and how Codex, Cursor and Claude Code load them.
- CLAUDE.md vs AGENTS.md: which one you needCLAUDE.md is for Claude Code. AGENTS.md is the shared file Codex, Cursor and others read. Which tool reads what, and how to run both without them drifting.
- Cursor rules for Next.js, with real .mdc examplesHow Cursor rules work: the .mdc format, globs, alwaysApply and the four rule types, plus real Next.js rules from a generated repo that you can copy.