Subagents: Isolation, Specialization, and Parallel Work
Subagents are specialized AI assistants that run in isolated contexts with scoped tools and custom prompts. Learn when to delegate tasks, the exact subagent file structure, and how discovery matching works.
Learning objectives
- Understand what subagents are and why you delegate to them instead of doing everything in one context
- Recognize the distinction between built-in, custom, and general-purpose subagents
- Learn the subagent file structure and discovery mechanism
- Identify use cases where subagent isolation, cost reduction, or parallelism provides real value
ToolDix original visual
Frame
Name the outcome and constraints.
Build
Try one bounded workflow.
Review
Keep evidence, revise, and share.
What a subagent is and why delegation matters
A subagent is a specialized AI assistant that your main agent can spawn to handle a focused subtask. Unlike your main conversation (where context accumulates across every file read, every command output, and every decision), a subagent runs in its own fresh context window with its own scoped tool set and custom instructions. When the subagent finishes, the main agent receives only the final summary—not all the intermediate files it read.
Think of subagents as workers: you (the main agent) describe what you want done, a worker (subagent) goes off and does it in isolation, and comes back with the result.
This solves three concrete problems:
-
Context preservation: When you read 30 files to understand an architecture, that context stays in the subagent and never pollutes your main conversation. Your main agent remains focused on implementation.
-
Cost reduction: A subagent can use a smaller, cheaper model (
haiku) while your main agent usesopus. The subagent explores and reports back; you only pay for what matters in the main thread. -
Parallelism: Multiple subagents can work simultaneously. Three code reviewers checking different aspects of a PR finish in parallel rather than sequentially.
The key constraint: subagents are one-way reporters. They work independently and report back to the main agent, but they cannot message each other directly or see each other's work. (For multi-agent teams that need to coordinate, see agent teams instead.)
Built-in vs. custom vs. general-purpose subagents
Claude Code provides three kinds of subagents:
| Type | Definition | When to use |
| :--- | :--- | :--- |
| Built-in | Bundled specialized subagents like Explore (research a topic) and Plan (draft a detailed plan) | Specific tactical tasks; no custom configuration needed |
| General-purpose | A fallback subagent Claude can invoke without explicit definition | Quick delegation without setup; good for one-off research |
| Custom | You define exactly what it does, which tools it can access, and its system prompt | Reusable specialists for your team (security reviewer, test runner, performance profiler) |
Custom subagents are the most powerful: you encode expertise once and reuse it across projects.
Subagent file structure and discovery
A custom subagent is defined as a markdown file with YAML frontmatter. Here is the exact structure:
.claude/agents/security-reviewer.md
---
name: security-reviewer
description: "Reviews code for security vulnerabilities and risky patterns. Examines authentication, data handling, and injection risks."
tools: Read, Grep, Glob
model: opus
---
You are a senior security engineer with 15 years of experience.
When reviewing code:
- Identify injection vulnerabilities (SQL, XSS, command injection)
- Check authentication and authorization logic
- Spot secrets or credentials in code
- Review cryptographic usage
- Assess data flow and sanitization
Report specific line numbers and severity ratings. Suggest fixes.
Frontmatter fields
| Field | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| name | string | Yes | Identifier for the subagent (kebab-case; must equal filename minus .md) |
| description | string | Yes | When and why Claude should use this subagent; used for automatic matching |
| tools | comma-separated string | No | Tools the subagent can access (e.g., Read, Grep, Glob, Bash). Omit for full access. |
| model | string | No | Model override (haiku, sonnet, opus). Defaults to main model. |
| background | boolean | No | If true, runs as a non-blocking background task. Defaults to false (foreground). |
The body (after ---) is the system prompt: custom instructions defining the subagent's expertise, behavior, and constraints.
Where subagents live
Custom subagents are discovered from:
- Project scope:
.claude/agents/in your repository (shared with your team via git) - User scope:
~/.claude/agents/(personal; only you can use them) - Plugin scope: Installed via plugins (if available)
Claude Code watches these directories and picks up new or edited files within a few seconds. A session restart is required only if you create a new agents/ directory for the first time.
How subagent discovery and invocation work
Automatic matching
Claude automatically decides whether to invoke a subagent based on your prompt and each subagent's description. The description is the key—it tells Claude when the subagent is useful.
A well-written description matches the language you use in your prompt:
Prompt: "Review this code for security issues"
Subagent description: "Reviews code for security vulnerabilities..."
→ Claude invokes the security-reviewer subagent
Vague descriptions lead to missed matches:
Prompt: "Review this code for security issues"
Subagent description: "A subagent" or "Code analysis"
→ Claude may not invoke it because the description is too generic
Explicit invocation
To guarantee a specific subagent is used, mention it by name:
Use the security-reviewer subagent to audit the authentication module.
This bypasses automatic matching and directly invokes the named subagent.
Worked example: Building a custom security-reviewer subagent
Here is a complete, production-ready example:
File: .claude/agents/security-reviewer.md
---
name: security-reviewer
description: "Expert code security reviewer. Identifies injection vulnerabilities, broken authentication, insecure data handling, and compliance risks."
tools: Read, Grep, Glob
model: opus
---
# Security Code Reviewer
You are a security engineer with expertise in OWASP Top 10, cryptography, and secure coding practices.
## Your role
Review provided code for security vulnerabilities. Focus on:
- **Injection** (SQL, XSS, command injection, LDAP, XML)
- **Broken Authentication** (session handling, password storage, token validation)
- **Sensitive Data Exposure** (encryption, hashing, logging)
- **Broken Access Control** (authorization checks, privilege escalation)
- **Security Misconfiguration** (defaults, exposed services, headers)
- **Insecure Dependencies** (known CVEs, outdated libraries)
## Reporting
For each finding:
1. State the vulnerability type (from OWASP Top 10)
2. Quote the vulnerable code (specific line or snippet)
3. Explain the risk (impact if exploited)
4. Suggest a fix or mitigation
5. Assign severity: Low, Medium, High, Critical
Only report real vulnerabilities. Do not report:
- Code style issues
- Performance concerns
- Non-security architectural choices
How to invoke it:
In your session, either:
Review the authentication module in src/auth/ for security issues
Claude sees "security" in your prompt and the security-reviewer description matches automatically.
Or explicitly:
Use the security-reviewer subagent to review src/auth/oauth.ts
What happens:
- Claude spawns the security-reviewer subagent in a fresh context
- The subagent receives only the tools you specified:
Read,Grep,Glob - It loads the system prompt and begins reviewing
- It reads the requested files, searches for patterns, and identifies issues
- It reports findings back to the main agent with specific line numbers and severity ratings
- The main agent receives the summary and continues the conversation
Cost and context impact:
- The main agent's context does NOT include all the files the subagent read
- The subagent uses
opus(expensive), but runs once, not repeatedly - Your main conversation stays clean for implementation work
When to use subagents vs. alternatives
| Situation | Subagent | Alternative | Why |
|---|---|---|---|
| Research a codebase, report findings; move on to implementation | Yes | Do it in main | Subagent isolates context bleed; you save tokens by not keeping all the research files in memory |
| Run tests and report results without editing code | Yes | Do it in main | Subagent with only Bash and Read stays focused; cannot accidentally edit code |
| Three reviewers checking different aspects of the same PR simultaneously | Yes | Sequential in main | Parallelism saves time; each reviewer runs independently and reports back |
| Simple, single-step task (rename a variable across 3 files) | No | Do it in main | Subagent overhead is not worth it for simple work |
| Your main agent needs the subagent's output to make the next decision | Foreground (default) | Background | Foreground blocks and returns results immediately; background is fire-and-forget |
Common mistake
Confusing subagents with smaller model choices. A subagent is not just "run this task with Haiku instead of Opus." Subagents are about isolation and focus: a subagent has its own context, its own tool set, and cannot pollute your main conversation with intermediate artifacts. Use subagents when the task genuinely benefits from isolation, not just to save a few tokens on a small model. And because subagents run in parallel, spawning three read-only subagents often costs less total tokens than running the same analysis sequentially in the main thread with full context.
Sources and license context
These references informed the lesson. ToolDix adds its own explanation, workflow, and practice rather than reproducing source material. Every link below leaves ToolDix and opens the publisher's own site in a new tab.
- Create custom subagents (opens code.claude.com in a new tab)External · code.claude.com (Anthropic terms apply)
- Subagents in the SDK (opens code.claude.com in a new tab)External · code.claude.com (Anthropic terms apply)
- Run agents in parallel (opens code.claude.com in a new tab)External · code.claude.com (Anthropic terms apply)
Keep going
Read these next on ToolDix.
Original lessons that build on what you just read.