Guides

How to Write a Claude Code Subagent

Checked 2026-10-31

Loading poll...

A Claude Code subagent is a Markdown file with YAML frontmatter, saved in .claude/agents/. The frontmatter names it and says when to use it; the body is its system prompt. Claude hands it a task, it works in its own context window, and only a summary comes back. This guide writes one from scratch. Facts checked 31 October 2026.

What you will have at the end

  • A read-only code reviewer subagent, committed for your team
  • A clear rule for which tools and which model each subagent gets
  • A description that makes Claude delegate at the right moments
  • A hook that blocks a risky command for one subagent only
  • A short test routine

If you have not met the pieces around subagents yet, our best practices guide shows how they fit together. Our subagent directory lists ready-made files worth copying from.

What a subagent is, and what it is not

A subagent gets its own context window, its own tool list and its own system prompt. It receives your delegation message and a small amount of environment detail such as the working directory. It does not receive the Claude Code system prompt or your conversation history. That isolation is the whole point: noisy output stays out of your main session.

Main conversation

Subagent

Skill with context: fork

Sees your chat history

Yes

No

No

Own context window

No

Yes

Yes

System prompt

Claude Code default

Your file's body

Chosen agent type's

Tool limits

Session settings

Its tools list

Chosen agent type's

Best for

Back-and-forth work

Self-contained jobs with a summary

A repeatable task you trigger

Claude Code also ships built-in subagents. Explore is a fast read-only agent for searching a codebase, and Plan does read-only research during plan mode. Both start without your CLAUDE.md files and git status to keep research cheap. Other built-in and custom subagents load both unless you set omitClaudeMd.

When to write one, and when not to

The docs give a plain split.

Use the main conversation when the task needs frequent back-and-forth, when several phases share lots of context, when the change is small, or when latency matters. A fresh subagent has to gather context your main session already holds.

Use a subagent when the task produces verbose output you do not need in context, when you want hard tool restrictions, or when the work is self-contained and can return a summary.

Use a skill when you want a reusable prompt that runs inside the main conversation. For a question about something already in your chat, /btw sees your full context without spending a subagent. Our subagents vs skills comparison goes deeper.

A good first subagent is one you would otherwise do badly in the main chat: a reviewer who has not seen your reasoning, a test runner whose output is huge, or a research task that reads dozens of files.

Step 1: Choose the scope

Subagent files can live in several places. When two share a name, the higher-priority location wins.

Location

Scope

Priority

Managed settings

Whole organization

1 (highest)

--agents CLI flag

Current session

2

.claude/agents/

Current project

3

~/.claude/agents/

All your projects

4

A plugin's agents/ folder

Where the plugin is enabled

5 (lowest)

Project subagents belong in version control so the team can improve them together. Claude Code scans these folders recursively, so you can sort files into agents/review/ or agents/research/. The folder name does not affect identity, because identity comes only from the name field. When nested folders define the same name, the one closest to your working directory wins.

Step 2: Write the file

Only name and description are required. Here is the smallest useful file.

---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
---

You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.

Save it as .claude/agents/code-reviewer.md. Claude Code watches the folder and picks up changes in a few seconds. The exception is the first file in a new agents directory, which needs a restart, and folders added with --add-dir, which are not watched at all.

A few naming rules: name is up to 256 characters, cannot contain a colon (reserved for plugin identifiers like my-plugin:reviewer), and does not have to match the filename. Hooks receive the name as agent_type.

Step 3: Learn the frontmatter

Multi-word field names use camelCase here, unlike skills, which use hyphens. A field Claude Code does not recognize is ignored without an error.

Field

What it does

name, description

Required. The description tells Claude when to delegate

tools

Allowed tools. Omit it and the subagent inherits every tool available to subagents

disallowedTools

Removed from the inherited or listed set

model

sonnet, opus, haiku, fable, a full model ID, or inherit

permissionMode

default, acceptEdits, auto, dontAsk, bypassPermissions, plan

maxTurns

Stops after this many agentic turns; output is marked partial

skills

Skills whose full content is injected at startup

mcpServers

Servers by name, or inline definitions, scoped to this subagent

hooks

Lifecycle hooks that run while this subagent runs

memory

user, project or local persistent memory

isolation

worktree to work in a temporary git worktree

background

true to always run in the background

effort

low through max, depending on the model

Plugin subagents ignore permissionMode, mcpServers and hooks. If a field seems to do nothing, run claude --debug and search the log for does not recognize or apply.

Step 4: Write a description Claude acts on

Claude decides to delegate by reading the description, so write it as a trigger, not a label. "Reviews code" is a label. The docs' own reviewer example reads: "Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code."

Two phrases do real work there. "Proactively" invites Claude to delegate without being asked. "Use immediately after writing or modifying code" names the moment. You can also invoke a subagent explicitly by naming it in your request, or with an @-mention, when you do not want to rely on automatic delegation.

Step 5: Write the system prompt

The body is all the subagent knows about its job, so make it a short brief. Say who it is, what it does first, what to look for, and what shape the answer takes. This is the docs' reviewer, trimmed.

---
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

Review checklist:
- Code is clear and readable
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage

Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)

Note what the tools line does. Edit and Write are absent, so this reviewer cannot change a file even if its prompt drifts. It keeps Bash so it can run git diff. Whether that is acceptable depends on your permission rules, since the subagent inherits the parent conversation's permissions.

Because the subagent has no chat history, put anything it must know in the prompt or in files it can read. If it needs project rules, it gets your CLAUDE.md automatically, unless you set omitClaudeMd: true because the delegation message carries everything.

Step 6: Choose the model and effort

Models are a cost lever. A reviewer that reads a diff does not always need your most capable model. Set model: haiku or sonnet for read-heavy work and keep inherit when quality of judgment matters.

Two facts from the docs help planning. A user or project subagent named Explore overrides the built-in and keeps its own model field, so a file with model: haiku makes exploration cheaper. And an environment variable can force one model onto every subagent, which is useful when you want a single bill line. Price differences between models are on our Claude models page.

effort works the same way: set low for lookups and a higher level where reasoning matters. The levels available depend on the model.

Step 7: Limit what it can do

There are two ways to restrict a subagent, and they combine.

Allow list. tools: Read, Grep, Glob means exactly those tools. Omit the line and the subagent inherits everything available to subagents, which is rarely what you want for a reviewer.

Deny list. disallowedTools removes tools from whatever the subagent would otherwise get. Note that an entry with a specifier, such as Bash(git push *), still removes the whole tool, so use it for tools you want gone, not for fine-grained command rules.

For command-level rules use a hook. The docs show a database reader that allows SELECT and blocks writes. The hook runs only while that subagent runs.

---
name: db-reader
description: Execute read-only database queries
tools: Bash
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate-readonly-query.sh"
---
#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|ALTER|TRUNCATE)\b' > /dev/null; then
  echo "Blocked: write operations not allowed. Use SELECT queries only." >&2
  exit 2
fi
exit 0

Exit code 2 blocks the call and sends the stderr text back as feedback. Make the script executable with chmod +x. Our hooks guide explains the exit codes. A regex over a command is a guard against mistakes, not a security boundary, so pair it with a database user that truly has read-only rights.

Step 8: Give it skills, servers or memory

Three fields extend what a subagent knows or can reach.

  • `skills` injects the full content of named skills at startup. This is the inverse of a skill with context: fork: here the subagent's body is the system prompt and skills are reference material. A subagent can still call unlisted skills through the Skill tool. See our skill-writing guide.
  • `mcpServers` gives the subagent a server by name, or an inline definition. Scoping an MCP server to one subagent keeps its tool descriptions out of your main context. Our MCP install guide covers setup.
  • `memory` with user, project or local lets the subagent keep notes across sessions. Use project for knowledge about this codebase that should be shared in version control, and local for notes you do not want committed.

Step 9: Run it in the foreground or background

Subagents that Claude spawns from the main conversation start in the background by default, so you keep working while they run. A background subagent runs with a narrower tool set. If the work needs a tool outside that set, ask Claude to wait for it, or run it in the foreground. Setting background: true in the file keeps a subagent in the background even when Claude asks to wait.

Two limits to know. By default 20 running subagents is the cap per session, and the next spawn fails with Concurrent subagent limit reached. Subagents can also spawn their own subagents, up to three layers below the main conversation. Both limits have environment variables if you need to change them.

To isolate file changes, set isolation: worktree. The subagent works in a temporary git worktree, and Claude Code removes it if the subagent made no changes. Claude Code also checks that its commands stay inside the worktree.

Common patterns

The docs name three patterns, and each maps to a file you can write today.

Pattern

Use it for

Tools

Isolate high-volume operations

Test runs, log scans, doc fetches

Bash, Read

Run parallel research

Several independent questions at once

Read, Grep, Glob

Chain subagents

Reviewer finds issues, fixer repairs them

Differs per step

The first is the easiest win. A test runner subagent can run a long suite, read thousands of lines of output, and return a five-line summary. That output never enters your main context.

For the chain pattern, keep each subagent's job narrow, and let the main conversation pass results between them. A reviewer that cannot edit, followed by a fixer that can, is easy to reason about and easy to audit.

Test it

  1. Ask Claude to do something the description covers and watch whether it delegates. If it does not, make the description more specific about the moment.
  2. Ask for it by name to confirm the file loads. If the file is missing from the list, check that the front matter parses and the folder is one Claude Code scans.
  3. Try something the tool list forbids, such as asking the reviewer to fix a bug. A read-only subagent should say it cannot edit.
  4. For a hook-protected subagent, send a command the hook should block and read the feedback.

Finished subagents appear in the panel and the task list, so you can read what each one did.

Our take

Treat subagents as a context-saving and permission-limiting device, not as a way to sound organized. Each one costs tokens and starts cold. We would write a subagent only when one of three things is true: the output is noisy, the tool list needs to be tighter than the main session, or you want a reviewer that did not write the code.

A tight tool list is the strongest reason. The prompt says what you hope happens, while the tools line decides what can happen. Put the read-only guarantee in tools, not in a sentence saying "do not edit files".

Commit project subagents so the team reviews them like code. Keep personal ones in ~/.claude/agents/.

Checklist

  • The file is in .claude/agents/ or ~/.claude/agents/
  • name is unique and has no colon
  • The description names the moment to delegate
  • tools is an explicit list for anything that should not edit
  • The prompt states first steps, checks and output shape
  • The model matches the work, not the default
  • A hook guards any command-level rule
  • You tested both delegation and a forbidden action

Related pages

Questions

Where do I put a subagent file?

In .claude/agents/ for one project, or ~/.claude/agents/ for all your projects. Claude Code watches both folders and picks up edits within a few seconds, except when you create the first file in a brand new agents folder, which needs a restart.

Which fields are required?

Only name and description. The body below the frontmatter becomes the subagent's system prompt.

Can a subagent change files?

Only if its tools allow it. If you omit tools it inherits every tool available to subagents. List tools such as Read, Grep and Glob to make it read-only.

How is a subagent different from a skill?

A skill is instructions that run in your main conversation unless you add context: fork. A subagent is a separate worker with its own context window, tool list and system prompt.

Loading poll...

Sources

  1. code.claude.com/docs/en/sub-agents
  2. code.claude.com/docs/en/skills
  3. code.claude.com/docs/en/hooks-guide

Part of the Wbcom Designs family

The all-in-one WordPress community stack

Also ours: wbcomdesigns.comvapvarun.combrndle.com