Claude Code9 min read

Claude Code Subagents: The Complete Guide to Building Custom AI Agent Teams (2026)

Learn how Claude Code subagents work and how to build your own — YAML frontmatter, tool restrictions, model selection, and real-world examples for 2026.

Claude Code Subagents: The Complete Guide to Building Custom AI Agent Teams (2026)

If you've used Claude Code for more than a few sessions, you've probably watched your context window fill up with test output, log dumps, or search results you never look at again. That's the exact problem subagents solve. Instead of every file read and every grep result living in your main conversation, a subagent does the messy work in its own isolated context and hands you back only what matters.

This guide walks through what subagents actually are, how the YAML configuration works, and how to build ones that make your Claude Code sessions faster, cheaper, and easier to follow — with copy-paste examples you can drop into your own projects today.

What Are Claude Code Subagents, and Why Do They Matter?

A subagent is a specialized AI assistant that runs in its own context window, with its own system prompt, its own tool access, and (optionally) its own model. When Claude Code encounters a task that matches a subagent's description, it delegates that task, waits for the subagent to finish, and only pulls the summary back into your main conversation.

This matters for four practical reasons:

  • Context preservation. A subagent that reads 40 files to find one function definition doesn't dump those 40 files into your conversation — you get the answer, not the search trail.
  • Enforced constraints. A documentation-writing subagent doesn't need Bash. A code-review subagent doesn't need Write. Restricting tools reduces the blast radius of anything going wrong.
  • Reusable configuration. Save a subagent once at ~/.claude/agents/ and it's available in every project on your machine.
  • Cost control. Route repetitive, low-complexity tasks (log triage, file search, simple summarization) to a cheaper, faster model like Haiku, and save your most capable model for the reasoning-heavy work.

Claude Code ships with a few built-in subagents you're already using without realizing it: Explore (fast, read-only codebase search, runs on Haiku), Plan (research during plan mode), and general-purpose (complex multi-step tasks with full tool access). Everything below is about building your own on top of that foundation.

How Subagent Files Work

Subagents are plain Markdown files with a YAML frontmatter block. There's no build step, no registry, no SDK call — Claude Code discovers them from disk the next time it starts a session.

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

The frontmatter above the --- fences configures the agent. Everything below becomes its system prompt, verbatim. That's the whole mental model.

Where to save subagent files

LocationScopeBest for
.claude/agents/Current projectTeam-shared agents specific to this codebase (commit to git)
~/.claude/agents/All your projectsPersonal agents you want everywhere
Plugin agents/ directoryWherever the plugin is enabledDistributed via a shared plugin

If two subagents share a name, Claude Code resolves the conflict by priority: managed org-wide settings first, then CLI-defined agents, then project-level, then user-level, then plugin-provided. Keep names unique within a scope — /doctor will flag same-scope duplicates.

The frontmatter fields that matter most

Only name and description are required. Everything else has sensible defaults:

  • tools — an allowlist of what the subagent can use. Omit it and the subagent inherits every tool available in the main conversation, including MCP tools.
  • disallowedTools — a denylist instead of an allowlist. Useful when you want "everything except Write and Edit" rather than enumerating every tool you do want.
  • modelsonnet, opus, haiku, fable, a full model ID like claude-sonnet-5, or inherit (the default). This is where cost control lives.
  • permissionModedefault, acceptEdits, dontAsk, bypassPermissions, or plan.
  • memoryuser, project, or local. Gives the subagent a persistent directory so it can accumulate knowledge (codebase patterns, recurring bugs) across sessions instead of starting from zero every time.
  • skills — preloads full skill content into the subagent's context at startup, rather than making it discover skills on the fly.

Building Your First Subagent: A Step-by-Step Example

Let's build a debugging subagent that can both diagnose and fix issues — a step up from a read-only reviewer because it needs Edit access.

1. Create the file at .claude/agents/debugger.md (project-scoped, so your whole team gets it):

markdown---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---

You are an expert debugger specializing in root cause analysis.

When invoked:
1. Capture the error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement a minimal fix
5. Verify the solution works

For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach

Focus on fixing the underlying issue, not the symptoms.

2. Restart your session so the file loads (subagents created via the /agents command activate immediately, but hand-edited files need a restart). 3. Invoke it three ways, in order of how much control you want:

text# Natural language — Claude decides whether to delegate
Have the debugger subagent look at why the auth tests are failing

# @-mention — guarantees this specific subagent runs
@"debugger (agent)" fix the failing auth tests

# Session-wide — the whole session becomes this agent
claude --agent debugger

The phrase "use proactively" in the description field is doing real work here — it's a signal Claude uses to decide whether to delegate to this subagent without being explicitly asked.

Restricting Tools and Controlling Cost

Two fields do most of the heavy lifting for safety and cost.

Read-only research agent — can't write or edit anything, no matter what it's asked to do:

yaml---
name: safe-researcher
description: Research agent with restricted capabilities
tools: Read, Grep, Glob, Bash
---

Inherit everything except file writes:

yaml---
name: no-writes
description: Inherits every tool except file writes
disallowedTools: Write, Edit
---

For cost, the model resolution order is: an environment variable override, then a per-invocation model parameter, then the subagent's own model frontmatter, then finally the main conversation's model. In practice, this means you can build a three-tier fleet — Haiku for high-volume grep/search work, Sonnet for the 80% of tasks that need real judgment, and your most capable model reserved for the handful of decisions that genuinely require deep reasoning. Teams running this pattern in production report 60–70% lower API spend compared to using one model for everything, without a noticeable quality drop on routine tasks.

yaml---
name: data-scientist
description: Data analysis expert for SQL queries and BigQuery operations. Use proactively for data analysis tasks.
tools: Bash, Read, Write
model: sonnet
---

Giving a Subagent Persistent Memory

By default, every subagent invocation starts from zero — no memory of what it found last time. The memory field changes that:

yaml---
name: code-reviewer
description: Reviews code for quality and best practices
memory: project
---

You are a code reviewer. As you review code, update your agent memory with
patterns, conventions, and recurring issues you discover.

With memory: project, the subagent gets a directory at .claude/agent-memory/code-reviewer/ that's shareable via version control — your whole team's reviewer agent gets smarter over time as it learns your codebase's actual conventions instead of generic best practices. Use memory: user for knowledge that should follow you across every project, or memory: local for project-specific learnings you don't want committed to git.

Common Patterns Worth Copying

Isolate high-volume operations. Test suites and log files are the classic case — delegate the run, get back only the failures:

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

Run parallel research. Independent investigations can run simultaneously instead of sequentially:

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

Chain subagents for multi-step workflows:

textUse the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them

One caution worth internalizing: subagent results return to your main conversation when they finish. Running many subagents that each report back in detail can undo the context savings you were chasing in the first place — keep the summaries tight.

Subagent vs. Main Conversation: When to Use Which

Use the main conversation when...Use a subagent when...
The task needs frequent back-and-forthThe task produces verbose output you don't need to see
Multiple phases share significant contextYou want to enforce specific tool restrictions
You're making a quick, targeted changeThe work is self-contained and can return a summary
Latency matters (subagents start with fresh context)You want to route it to a cheaper/faster model

Key Takeaways

  • Subagents are Markdown files with YAML frontmatter — no build tooling required, just save and (usually) restart.
  • Only name and description are required; tools, model, memory, and permissionMode are where the real customization happens.
  • Restrict tools aggressively. A subagent that can't Write can't cause a write-related incident.
  • Route repetitive, low-complexity work to a cheaper model and save your most capable one for genuine reasoning tasks — this is the single biggest lever for cost control.
  • Project-scoped agents (.claude/agents/) belong in version control so your whole team benefits from the same specialized reviewers, debuggers, and researchers.

Next Steps

Subagents are one small piece of the broader skill set that shows up on the Claude Certified Architect (CCA) exam — tool-use design, context management, and agentic architecture all get tested directly. If you're prepping for certification or just want to validate that you actually understand these concepts (not just copy-paste them), try a free practice quiz at AI for Anything and see where your gaps are before exam day.

Ready to Start Practicing?

300+ scenario-based practice questions covering all 5 CCA domains. Detailed explanations for every answer.

Free CCA Study Kit

Get domain cheat sheets, anti-pattern flashcards, and weekly exam tips. No spam, unsubscribe anytime.