Subagents enable delegation of complex tasks to specialized agents that operate autonomously without user interaction, returning their final output to the main conversation.
Project-level subagents override user-level when names conflict.
Subagents run in isolated contexts and return their final output to the main conversation. They:
- ✅ Can use tools like Read, Write, Edit, Bash, Grep, Glob
- ✅ Can access MCP servers and other non-interactive tools
- ❌ Cannot use AskUserQuestion or any tool requiring user interaction
- ❌ Cannot present options or wait for user input
- ❌ User never sees subagent's intermediate steps
The main conversation sees only the subagent's final report/output.
Use main chat for:
- Gathering requirements from user (AskUserQuestion)
- Presenting options or decisions to user
- Any task requiring user confirmation/input
- Work where user needs visibility into progress
Use subagents for:
- Research tasks (API documentation lookup, code analysis)
- Code generation based on pre-defined requirements
- Analysis and reporting (security review, test coverage)
- Context-heavy operations that don't need user interaction
Example workflow pattern:
Main Chat: Ask user for requirements (AskUserQuestion)
↓
Subagent: Research API and create documentation (no user interaction)
↓
Main Chat: Review research with user, confirm approach
↓
Subagent: Generate code based on confirmed plan
↓
Main Chat: Present results, handle testing/deployment
---
name: security-reviewer
description: Reviews code for security vulnerabilities
tools: Read, Grep, Glob, Bash
model: sonnet
---
<role>
You are a senior code reviewer specializing in security.
</role>
<focus_areas>
- SQL injection vulnerabilities
- XSS attack vectors
- Authentication/authorization issues
- Sensitive data exposure
</focus_areas>
<workflow>
1. Read the modified files
2. Identify security risks
3. Provide specific remediation steps
4. Rate severity (Critical/High/Medium/Low)
</workflow>
❌ Bad: "You are a helpful assistant that helps with code"
✅ Good: "You are a React component refactoring specialist. Analyze components for hooks best practices, performance anti-patterns, and accessibility issues."
<role> - Who the subagent is and what it does
<constraints> - Hard rules (NEVER/MUST/ALWAYS)
<focus_areas> - What to prioritize
<workflow> - Step-by-step process
<output_format> - How to structure deliverables
<success_criteria> - Completion criteria
<validation> - How to verify work
Medium subagents (multi-step process):
- Add workflow steps, output_format, success_criteria
- Example: api-researcher, documentation-generator
Complex subagents (research + generation + validation):
- Add all tags as appropriate including validation, examples
- Example: mcp-api-researcher, comprehensive-auditor
Keep markdown formatting WITHIN content (bold, italic, lists, code blocks, links).
For XML structure principles and token efficiency details, see @skills/create-agent-skills/references/use-xml-tags.md - the same principles apply to subagents.
> Use the code-reviewer subagent to check my recent changes
> Have the test-writer subagent create tests for the new API endpoints
Subagent usage and configuration: references/subagents.md
- File format and configuration
- Model selection (Sonnet 4.5 + Haiku 4.5 orchestration)
- Tool security and least privilege
- Prompt caching optimization
- Complete examples
Writing effective prompts: references/writing-subagent-prompts.md
- Core principles and XML structure
- Description field optimization for routing
- Extended thinking for complex reasoning
- Security constraints and strong modal verbs
- Success criteria definition
Advanced topics:
Evaluation and testing: references/evaluation-and-testing.md
- Evaluation metrics (task completion, tool correctness, robustness)
- Testing strategies (offline, simulation, online monitoring)
- Evaluation-driven development
- G-Eval for custom criteria
Error handling and recovery: references/error-handling-and-recovery.md
- Common failure modes and causes
- Recovery strategies (graceful degradation, retry, circuit breakers)
- Structured communication and observability
- Anti-patterns to avoid
Context management: references/context-management.md
- Memory architecture (STM, LTM, working memory)
- Context strategies (summarization, sliding window, scratchpads)
- Managing long-running tasks
- Prompt caching interaction
Orchestration patterns: references/orchestration-patterns.md
- Sequential, parallel, hierarchical, coordinator patterns
- Sonnet + Haiku orchestration for cost/performance
- Multi-agent coordination
- Pattern selection guidance
Debugging and troubleshooting: references/debugging-agents.md
- Logging, tracing, and correlation IDs
- Common failure types (hallucinations, format errors, tool misuse)
- Diagnostic procedures
- Continuous monitoring
- Valid YAML frontmatter (name matches file, description includes triggers)
- Clear role definition in system prompt
- Appropriate tool restrictions (least privilege)
- XML-structured system prompt with role, approach, and constraints
- Description field optimized for automatic routing
- Successfully tested on representative tasks
- Model selection appropriate for task complexity (Sonnet for reasoning, Haiku for simple tasks)
1---2name: create-subagents3description: Expert guidance for creating, building, and using Claude Code subagents and the Task tool. Use when working with subagents, setting up agent configurations, understanding how agents work, or using the Task tool to launch specialized agents.4---5
6<objective>
7Subagents are specialized Claude instances that run in isolated contexts with focused roles and limited tool access. This skill teaches you how to create effective subagents, write strong system prompts, configure tool access, and orchestrate multi-agent workflows using the Task tool.
8
9Subagents enable delegation of complex tasks to specialized agents that operate autonomously without user interaction, returning their final output to the main conversation.
10</objective>
11
12<quick_start>
13<workflow>
141. Run `/agents` command
152. Select "Create New Agent"
163. Choose project-level (`.claude/agents/`) or user-level (`~/.claude/agents/`)
174. Define the subagent:
18 - **name**: lowercase-with-hyphens
19 - **description**: When should this subagent be used?
20 - **tools**: Optional comma-separated list (inherits all if omitted)
21 - **model**: Optional (`sonnet`, `opus`, `haiku`, or `inherit`)
225. Write the system prompt (the subagent's instructions)
23</workflow>
24
25<example>
26```markdown
27---
28name: code-reviewer
29description: Expert code reviewer. Use proactively after code changes to review for quality, security, and best practices.
30tools: Read, Grep, Glob, Bash
31model: sonnet
32---
33
34<role>
35You are a senior code reviewer focused on quality, security, and best practices.
36</role>
37
38<focus_areas>
39- Code quality and maintainability
40- Security vulnerabilities
41- Performance issues
42- Best practices adherence
43</focus_areas>
44
45<output_format>
46Provide specific, actionable feedback with file:line references.
47</output_format>
48```
49</example>
50</quick_start>
51
52<file_structure>
53| Type | Location | Scope | Priority |
54|------|----------|-------|----------|
55| **Project** | `.claude/agents/` | Current project only | Highest |
56| **User** | `~/.claude/agents/` | All projects | Lower |
57| **Plugin** | Plugin's `agents/` dir | All projects | Lowest |
58
59Project-level subagents override user-level when names conflict.
60</file_structure>
61
62<configuration>
63<field name="name">
64- Lowercase letters and hyphens only
65- Must be unique
66</field>
67
68<field name="description">
69- Natural language description of purpose
70- Include when Claude should invoke this subagent
71- Used for automatic subagent selection
72</field>
73
74<field name="tools">
75- Comma-separated list: `Read, Write, Edit, Bash, Grep`
76- If omitted: inherits all tools from main thread
77- Use `/agents` interface to see all available tools
78</field>
79
80<field name="model">
81- `sonnet`, `opus`, `haiku`, or `inherit`
82- `inherit`: uses same model as main conversation
83- If omitted: defaults to configured subagent model (usually sonnet)
84</field>
85</configuration>
86
87<execution_model>
88<critical_constraint>
89**Subagents are black boxes that cannot interact with users.**
90
91Subagents run in isolated contexts and return their final output to the main conversation. They:
92- ✅ Can use tools like Read, Write, Edit, Bash, Grep, Glob
93- ✅ Can access MCP servers and other non-interactive tools
94- ❌ **Cannot use AskUserQuestion** or any tool requiring user interaction
95- ❌ **Cannot present options or wait for user input**
96- ❌ **User never sees subagent's intermediate steps**
97
98The main conversation sees only the subagent's final report/output.
99</critical_constraint>
100
101<workflow_design>
102**Designing workflows with subagents:**
103
104Use **main chat** for:
105- Gathering requirements from user (AskUserQuestion)
106- Presenting options or decisions to user
107- Any task requiring user confirmation/input
108- Work where user needs visibility into progress
109
110Use **subagents** for:
111- Research tasks (API documentation lookup, code analysis)
112- Code generation based on pre-defined requirements
113- Analysis and reporting (security review, test coverage)
114- Context-heavy operations that don't need user interaction
115
116**Example workflow pattern:**
117```
118Main Chat: Ask user for requirements (AskUserQuestion)
119 ↓
120Subagent: Research API and create documentation (no user interaction)
121 ↓
122Main Chat: Review research with user, confirm approach
123 ↓
124Subagent: Generate code based on confirmed plan
125 ↓
126Main Chat: Present results, handle testing/deployment
127```
128</workflow_design>
129</execution_model>
130
131<system_prompt_guidelines>
132<principle name="be_specific">
133Clearly define the subagent's role, capabilities, and constraints.
134</principle>
135
136<principle name="use_pure_xml_structure">
137Structure the system prompt with pure XML tags. Remove ALL markdown headings from the body.
138
139```markdown
140---
141name: security-reviewer
142description: Reviews code for security vulnerabilities
143tools: Read, Grep, Glob, Bash
144model: sonnet
145---
146
147<role>
148You are a senior code reviewer specializing in security.
149</role>
150
151<focus_areas>
152- SQL injection vulnerabilities
153- XSS attack vectors
154- Authentication/authorization issues
155- Sensitive data exposure
156</focus_areas>
157
158<workflow>
1591. Read the modified files
1602. Identify security risks
1613. Provide specific remediation steps
1624. Rate severity (Critical/High/Medium/Low)
163</workflow>
164```
165</principle>
166
167<principle name="task_specific">
168Tailor instructions to the specific task domain. Don't create generic "helper" subagents.
169
170❌ Bad: "You are a helpful assistant that helps with code"
171✅ Good: "You are a React component refactoring specialist. Analyze components for hooks best practices, performance anti-patterns, and accessibility issues."
172</principle>
173</system_prompt_guidelines>
174
175<subagent_xml_structure>
176Subagent.md files are system prompts consumed only by Claude. Like skills and slash commands, they should use pure XML structure for optimal parsing and token efficiency.
177
178<recommended_tags>
179Common tags for subagent structure:
180
181- `<role>` - Who the subagent is and what it does
182- `<constraints>` - Hard rules (NEVER/MUST/ALWAYS)
183- `<focus_areas>` - What to prioritize
184- `<workflow>` - Step-by-step process
185- `<output_format>` - How to structure deliverables
186- `<success_criteria>` - Completion criteria
187- `<validation>` - How to verify work
188</recommended_tags>
189
190<intelligence_rules>
191**Simple subagents** (single focused task):
192- Use role + constraints + workflow minimum
193- Example: code-reviewer, test-runner
194
195**Medium subagents** (multi-step process):
196- Add workflow steps, output_format, success_criteria
197- Example: api-researcher, documentation-generator
198
199**Complex subagents** (research + generation + validation):
200- Add all tags as appropriate including validation, examples
201- Example: mcp-api-researcher, comprehensive-auditor
202</intelligence_rules>
203
204<critical_rule>
205**Remove ALL markdown headings (##, ###) from subagent body.** Use semantic XML tags instead.
206
207Keep markdown formatting WITHIN content (bold, italic, lists, code blocks, links).
208
209For XML structure principles and token efficiency details, see @skills/create-agent-skills/references/use-xml-tags.md - the same principles apply to subagents.
210</critical_rule>
211</subagent_xml_structure>
212
213<invocation>
214<automatic>
215Claude automatically selects subagents based on the `description` field when it matches the current task.
216</automatic>
217
218<explicit>
219You can explicitly invoke a subagent:
220
221```
222> Use the code-reviewer subagent to check my recent changes
223```
224
225```
226> Have the test-writer subagent create tests for the new API endpoints
227```
228</explicit>
229</invocation>
230
231<management>
232<using_agents_command>
233Run `/agents` for an interactive interface to:
234- View all available subagents
235- Create new subagents
236- Edit existing subagents
237- Delete custom subagents
238</using_agents_command>
239
240<manual_editing>
241You can also edit subagent files directly:
242- Project: `.claude/agents/subagent-name.md`
243- User: `~/.claude/agents/subagent-name.md`
244</manual_editing>
245</management>
246
247<reference>
248**Core references**:
249
250**Subagent usage and configuration**: [references/subagents.md](references/subagents.md)
251- File format and configuration
252- Model selection (Sonnet 4.5 + Haiku 4.5 orchestration)
253- Tool security and least privilege
254- Prompt caching optimization
255- Complete examples
256
257**Writing effective prompts**: [references/writing-subagent-prompts.md](references/writing-subagent-prompts.md)
258- Core principles and XML structure
259- Description field optimization for routing
260- Extended thinking for complex reasoning
261- Security constraints and strong modal verbs
262- Success criteria definition
263
264**Advanced topics**:
265
266**Evaluation and testing**: [references/evaluation-and-testing.md](references/evaluation-and-testing.md)
267- Evaluation metrics (task completion, tool correctness, robustness)
268- Testing strategies (offline, simulation, online monitoring)
269- Evaluation-driven development
270- G-Eval for custom criteria
271
272**Error handling and recovery**: [references/error-handling-and-recovery.md](references/error-handling-and-recovery.md)
273- Common failure modes and causes
274- Recovery strategies (graceful degradation, retry, circuit breakers)
275- Structured communication and observability
276- Anti-patterns to avoid
277
278**Context management**: [references/context-management.md](references/context-management.md)
279- Memory architecture (STM, LTM, working memory)
280- Context strategies (summarization, sliding window, scratchpads)
281- Managing long-running tasks
282- Prompt caching interaction
283
284**Orchestration patterns**: [references/orchestration-patterns.md](references/orchestration-patterns.md)
285- Sequential, parallel, hierarchical, coordinator patterns
286- Sonnet + Haiku orchestration for cost/performance
287- Multi-agent coordination
288- Pattern selection guidance
289
290**Debugging and troubleshooting**: [references/debugging-agents.md](references/debugging-agents.md)
291- Logging, tracing, and correlation IDs
292- Common failure types (hallucinations, format errors, tool misuse)
293- Diagnostic procedures
294- Continuous monitoring
295</reference>
296
297<success_criteria>
298A well-configured subagent has:
299
300- Valid YAML frontmatter (name matches file, description includes triggers)
301- Clear role definition in system prompt
302- Appropriate tool restrictions (least privilege)
303- XML-structured system prompt with role, approach, and constraints
304- Description field optimized for automatic routing
305- Successfully tested on representative tasks
306- Model selection appropriate for task complexity (Sonnet for reasoning, Haiku for simple tasks)
307</success_criteria>