Create Custom Subagents

Claude Code — Beginner-Friendly Teaching Edition
Big idea: A subagent is a specialized Claude worker with its own context, instructions, tool access, model, permissions, and optional memory. Use one when a side task would otherwise fill your main conversation with files, logs, search results, or other information you do not need to keep.

1. What Is a Subagent?

A subagent is a specialized AI assistant that handles a focused type of work. Claude Code can delegate a matching task to that worker. The subagent works in its own context window and then returns the useful result to the main conversation.

Main Claude session Delegate task Subagent context Focused work Summary returned
Simple mental model: Main Claude = project manager. Subagent = specialist brought in for one focused job.

2. Why Use Subagents?

  • Protect context: large searches, logs, tests, or documentation stay outside the main conversation.
  • Enforce constraints: give a worker only the tools it needs.
  • Specialize behavior: create agents for testing, code review, debugging, security, research, and more.
  • Reuse configuration: personal subagents can work across projects.
  • Control cost: route suitable work to a faster or cheaper model.
Good example: Instead of asking the main session to process thousands of lines of test output, delegate the test run and ask the subagent to return only failing tests and their important errors.

3. Subagents vs. Other Parallel Features

FeatureMain purpose
SubagentFocused delegated work inside a single Claude session.
Background session / agent viewRun independent Claude sessions and monitor them.
Agent teamCoordinate multiple Claude sessions that can communicate.
WorktreeIsolate file changes in separate Git checkouts.

A subagent is especially useful when you want the result of a side task, not all of the side task's intermediate context.

4. Built-in Subagents

Claude Code includes built-in subagents that Claude can use automatically when appropriate.

Built-in agentPurposeTypical access
ExploreSearch and analyze a codebase without changing it.Read-only tools.
PlanResearch the codebase while preparing a plan.Read-only tools.
General-purposeComplex multi-step work requiring exploration and action.Broad subagent tools.
Other helpersSpecial Claude Code tasks such as status-line setup or Claude Code feature questions.Depends on the agent.
Current documentation note: Explore now inherits the main conversation's model, with provider-specific limits described in the official documentation. Do not assume that Explore always runs on Haiku.

5. Create Your First Custom Subagent

Custom subagents are Markdown files with YAML frontmatter. The recommended current workflow is to ask Claude to create the file or create it manually. The older interactive /agents wizard was removed in Claude Code v2.1.198.

Ask Claude to create one

Create a personal code-improver subagent in ~/.claude/agents/
that scans files and suggests improvements for readability,
performance, and best practices. Make it read-only and use Sonnet.

Example file

---
name: code-improver
description: Scans files and suggests improvements for readability,
  performance, and best practices. Use after writing or modifying code.
tools: Read, Grep, Glob
model: sonnet
---

You are a code improvement specialist.
For each issue, explain the problem, show the current code,
and provide an improved version.
Important: The file is the agent's reusable definition. The frontmatter controls configuration; the Markdown body is the system prompt that tells the agent how to behave.

6. Where Do Subagents Live?

The file location determines the subagent's scope and priority.

LocationScopePriority
Managed settingsOrganization-wideHighest
--agents CLI flagCurrent session2
.claude/agents/Current project3
~/.claude/agents/All projects for the user4
Plugin agents/Where the plugin is enabledLowest

Project subagent

.claude/agents/code-reviewer.md

Best when the agent is specific to one repository and should be shared through version control.

Personal subagent

~/.claude/agents/code-reviewer.md

Best when you want the same agent available across your projects.

7. CLI-Defined Subagents

You can define subagents directly when launching Claude Code. These definitions exist only for that session, which makes them useful for experiments and automation.

claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  },
  "debugger": {
    "description": "Debugging specialist for errors and test failures.",
    "prompt": "Analyze errors, identify root causes, and provide fixes."
  }
}'

8. Use a Subagent as the Whole Session

The --agent option can start Claude Code with a subagent's system prompt, tool restrictions, and model as the main session configuration.

claude --agent code-reviewer

This is different from asking the main Claude session to delegate one task. Here, the selected subagent becomes the main session's agent identity.

9. Frontmatter: The Agent's Configuration

The most important fields include:

FieldPurpose
nameUnique identifier for the subagent.
descriptionTells Claude when the subagent should be used.
toolsControls which tools the subagent can use.
disallowedToolsRemoves specific tools from its available set.
modelSelects the model, such as sonnet, opus, haiku, fable, or inherit.
permissionModeControls how permissions work for the subagent.
skillsPreloads selected skills into the subagent's context.
memoryEnables persistent memory for the subagent.
hooksDefines lifecycle hooks for the subagent.
mcpServersProvides MCP servers specifically to the subagent.
isolationCan isolate subagent work in a worktree.

10. Write a Good Description

Claude uses the description field to decide when automatic delegation makes sense. Make it clear, specific, and short.

Weak description

Helps with code.

Better description

Reviews TypeScript changes for security, error handling,
and project conventions. Use after modifying API or authentication code.
Context warning: Subagent descriptions are loaded when Claude decides what to delegate. If the combined descriptions become very large, they consume valuable context. Put detailed instructions in the agent's system prompt instead.

11. Control the Model

The model field controls which model a subagent uses.

model: haiku

or:

model: sonnet

or:

model: opus

or:

model: inherit

Use a faster model for simple searches or classification when appropriate. Use a stronger model for complex reasoning or implementation.

12. Restrict Tools

A powerful advantage of subagents is that you can restrict what they are allowed to do. A read-only reviewer can be prevented from editing files.

---
name: reviewer
description: Review code without changing files.
tools: Read, Grep, Glob
model: sonnet
---

Review the code and report problems.
Do not modify any files.
Principle: Give a subagent the smallest tool set that is sufficient for its job.

13. Permission Modes

The permissionMode field controls the subagent's permission behavior.

ModeMeaning
defaultManual mode; prompts for permission.
acceptEditsAutomatically accepts file edits and common filesystem commands in allowed paths.
autoUses Auto mode's background classifier.
dontAskAutomatically denies permission prompts.
bypassPermissionsSkips permission prompts; use with caution.
planRead-only plan mode.
Security: bypassPermissions can allow operations without approval. Do not use it casually, especially on untrusted projects or sensitive environments.

14. Preload Skills

Use the skills field when a subagent needs specific domain knowledge at startup.

---
name: api-developer
description: Implement API endpoints using team conventions.
skills:
  - api-conventions
  - error-handling-patterns
---

Implement API endpoints following the preloaded conventions.

This is useful when the agent repeatedly needs the same instructions and patterns.

15. Persistent Memory

A subagent can have persistent memory so it can accumulate useful knowledge across conversations. For example, it can remember recurring codebase patterns or common issues.

Use memory when: the agent is a long-lived specialist whose learned information remains useful over time. Avoid persistent memory for tasks where every run should start clean.

16. MCP Servers for a Subagent

A subagent can receive MCP servers that are scoped specifically to it. This keeps those tool descriptions and external integrations out of the main conversation when they are not needed there.

---
name: browser-tester
description: Tests features in a real browser.
mcpServers:
  - playwright:
      type: stdio
      command: npx
      args: ["-y", "@playwright/mcp@latest"]
  - github
---

Use Playwright to navigate, screenshot,
and interact with the browser.
Mental model: MCP gives the subagent extra capabilities, while the parent conversation does not automatically receive those tool descriptions.

17. Hooks for Subagents

Hooks can run at important points in a subagent's lifecycle. Common events include PreToolUse, PostToolUse, and Stop.

---
name: code-reviewer
description: Review code with automatic validation.
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate-command.sh $TOOL_INPUT"
  PostToolUse:
    - matcher: "Edit|Write"
      hooks:
        - type: command
          command: "./scripts/run-linter.sh"
---

Project-level settings.json can also react to SubagentStart and SubagentStop events.

18. Automatic Delegation

Claude decides whether to delegate based on your request, the subagent's description, and the current context. You can encourage proactive delegation by including wording such as “Use proactively” in the description.

Your request Current context Agent descriptions Delegation decision Subagent runs

19. Invoke a Subagent Explicitly

There are three useful levels of control.

Level 1 — Natural language

Use the test-runner subagent to fix the failing tests.

Claude decides whether to delegate.

Level 2 — @-mention

@"code-reviewer (agent)" review the authentication changes.

This explicitly selects the subagent for that task.

Level 3 — Session-wide

claude --agent code-reviewer

The entire session runs using that agent configuration.

20. Foreground vs. Background

A subagent can run in the foreground or background.

ForegroundBackground
Main conversation waits for the result.Main conversation can continue while the worker runs.
Useful for dependent tasks.Useful for independent or long-running work.
Result returns directly.Status/result can be checked while it runs.

21. High-Volume Operations

One of the strongest use cases is isolating operations that generate a lot of output. Examples include test suites, documentation searches, and large log files.

Use a subagent to run the test suite and report
only the failing tests with their error messages.

The detailed output remains in the subagent context, while the main conversation receives the useful summary.

22. Run Parallel Research

Independent investigations can be delegated to multiple subagents at the same time.

Research the authentication, database, and API modules
in parallel using separate subagents.

Each worker explores one area, and Claude combines the findings. This works best when the research paths do not depend on one another.

Running many subagents that each return detailed results can itself consume significant main-session context. Ask for concise summaries when possible.

23. Chain Subagents

Subagents can be used sequentially when one specialist's result becomes the next specialist's input.

Use the code-reviewer subagent to find performance issues,
then use the optimizer subagent to fix them.
ReviewerFind issuesPass findings OptimizerApply fixes

24. When NOT to Use a Subagent

Stay in the main conversation when:

  • The task needs frequent back-and-forth.
  • Planning, implementation, and testing share a lot of context.
  • The change is small and targeted.
  • Latency is critical and the worker would need to rebuild context.

Consider a Skill instead when you want reusable instructions that run in the main conversation context.

Useful shortcut: If the question is about something already present in your conversation and does not need tool access, /btw can be better than starting a subagent.

25. Subagent Context

A normal subagent gets its own context window rather than automatically receiving every detail of the parent conversation. This separation is one of the main reasons subagents save context.

If a subagent needs specific information, give it the relevant files, task description, or instructions rather than assuming it knows everything the main conversation knows.

26. Forked Subagents

A forked subagent starts from the current conversation context instead of starting completely fresh. This is useful when the new worker needs the discussion that has already happened.

Difference: Named subagent = focused worker with its own context. Fork = a new path that can inherit the current conversation context.

27. Worktrees for Subagent Isolation

When a subagent needs to make code changes and you want those changes isolated, worktree isolation can be used. This gives the worker a separate Git checkout.

---
name: refactorer
description: Apply a large mechanical refactor safely.
isolation: worktree
---

Apply the refactor, run tests,
and report the changed files.

This is especially useful when several workers may edit overlapping areas.

28. Let Subagents Spawn Subagents

The documentation supports configuring whether a subagent can spawn its own subagents. This creates a hierarchy of workers.

Use carefully: Nested delegation can multiply complexity, context usage, and cost. Only allow it when the workflow genuinely benefits from another level of specialization.

29. Concurrent Subagent Limits

Claude Code limits how many subagents can run concurrently. When the limit is reached, additional work waits until capacity becomes available.

The practical lesson is simple: parallelism has a capacity and cost. More workers do not automatically mean faster results.

30. Subagent Output Scanning

Claude Code scans subagent final reports before returning them to the main conversation. This helps distinguish text that imitates Claude Code system messages or permission-setting instructions from actual conversation structure.

Important: Output scanning is not a security substitute. Tool calls caused by returned text still go through normal permissions and sandboxing. Restrict what the subagent can access in the first place.

31. Resume a Subagent

A subagent can be resumed when you want to continue work using its existing context rather than starting a new worker. This is useful for long-running investigations or multi-step specialist work.

32. Auto-Compaction

Long-running subagents can compact their context when necessary. The purpose is the same general idea as normal Claude context management: keep important information while reducing redundant history.

33. Common Patterns

PatternExample
High-volume isolationRun tests and return only failures.
Parallel researchResearch auth, database, and API independently.
ChainingReviewer finds issues → optimizer fixes them.
Specialized reviewerSecurity agent checks authentication changes.
Read-only explorationExplore agent maps an unfamiliar codebase.
Isolated implementationRefactorer works in a worktree.

34. Troubleshooting

My subagent is not discovered

Check that the Markdown file starts with YAML frontmatter, has a valid name and description, and is stored in a supported agents directory. If you create a new agents directory while Claude Code is already running, restarting the session may be necessary.

Duplicate names

Keep names unique within the relevant directory tree. For nested project agents, the definition closest to the working directory takes precedence.

Invalid frontmatter

Claude Code skips files with missing required fields, invalid YAML, or invalid names. Use --debug to inspect debug information. Current documentation also describes claude plugin validate for checking an agents directory.

35. Security Best Practices

  • Give agents only the tools they need.
  • Use read-only tools for reviewers whenever possible.
  • Be cautious with bypassPermissions.
  • Review MCP servers exposed to specialized agents.
  • Use worktrees when code isolation is important.
  • Do not put secrets into agent prompts or committed agent files.
  • Remember that output scanning does not replace permission controls.

36. Common Beginner Mistakes

  1. Making one giant “do everything” subagent.
  2. Writing a vague description that gives Claude no delegation signal.
  3. Giving a read-only reviewer unnecessary write or shell access.
  4. Putting detailed instructions into description instead of the system prompt.
  5. Creating too many agents and increasing context overhead.
  6. Using a subagent for a tiny task that is faster in the main conversation.
  7. Forgetting that subagents have their own context.
  8. Assuming a subagent automatically knows all parent-session decisions.
  9. Running too many parallel agents without considering token cost and rate limits.
  10. Confusing subagents with worktrees or agent teams.

37. Best-Practice Checklist

  • Give each subagent one clear responsibility.
  • Keep description short and specific.
  • Put detailed behavior in the system prompt.
  • Restrict tools to the minimum required.
  • Choose the model according to task complexity.
  • Use project scope for team-shared agents.
  • Use user scope for personal reusable agents.
  • Use skills for reusable domain knowledge.
  • Use hooks for enforced lifecycle checks.
  • Use worktree isolation when file changes need separation.
  • Ask for concise results when many agents run in parallel.

38. Interview / Revision Questions

  1. What is a Claude Code subagent?
  2. Why does a subagent help with context management?
  3. What are the built-in Explore, Plan, and General-purpose agents used for?
  4. Where should a project-specific subagent be stored?
  5. Where should a personal subagent be stored?
  6. What does the description field control?
  7. What is the difference between tools and disallowedTools?
  8. What does the model field do?
  9. What are the main permission modes?
  10. How do you preload a Skill into a subagent?
  11. How can an MCP server be scoped to one subagent?
  12. What is the difference between automatic delegation and @-mention invocation?
  13. When should you use a subagent instead of the main conversation?
  14. What is a forked subagent?
  15. Why would you use worktree isolation for a subagent?

39. Practice — Build Your Own Subagent

  1. Create .claude/agents/ in a test project.
  2. Create code-reviewer.md.
  3. Add a clear name and description.
  4. Give it only Read, Grep, and Glob.
  5. Choose a model appropriate for code review.
  6. Write a system prompt that tells it to report problems without modifying files.
  7. Ask Claude to use the reviewer on a recent change.
  8. Check the returned summary.
  9. Then create a second agent for running tests.
  10. Compare how much cleaner your main conversation becomes.

40. Quick Memory Map

Subagent = specialist Own context Custom prompt Tool restrictions Model selection Permissions Skills MCP Hooks Memory Worktree isolation

41. Final Takeaway

One-sentence rule:
Use a Claude Code subagent when a focused task can be handled independently and you want the specialist's useful result without filling your main conversation with all of its intermediate work.
Subagent
   ↓
Own context + focused instructions
   ↓
Limited tools / selected model
   ↓
Specialized work
   ↓
Concise result
   ↓
Main Claude continues
Source: Claude Code official documentation — “Create custom subagents”. This teaching edition follows the current documentation's terminology, structure, configuration model, built-in agents, scope and priority rules, frontmatter, models, tools, permissions, skills, MCP, hooks, delegation, background execution, parallel research, chaining, context management, forks, worktree isolation, troubleshooting, and examples.