Welcome to Week 4! This week you'll learn about Sub-agents -
specialized AI assistants that Claude can delegate to. It's like having a whole team of experts,
each trained for specific tasks!
LESSON 1
What Are Sub-agents?
A sub-agent is a specialized AI assistant that Claude Code can call on for help
with specific tasks. Each sub-agent has its own expertise and operates in its own space.
🏥 Think of it like a hospital:
When you go to the hospital, there's a general doctor who sees you first. But if you need
heart surgery, they call in a heart specialist. If you need brain surgery, they call in a
brain specialist. Sub-agents work the same way - Claude is the general doctor, and sub-agents
are the specialists!
Key Features of Sub-agents
🧠
Separate Context
Each sub-agent has its own "brain" - doesn't clutter your main conversation
🎯
Specialized
Trained for specific tasks with custom instructions
♻️
Reusable
Use them again and again across different projects
🔒
Controlled Access
You decide what tools each agent can use
🔧 Real-World Examples
Code Reviewer Agent - Reviews your code for bugs and security issues
Debugger Agent - Investigates errors and finds fixes
Documentation Agent - Writes clear docs for your code
Test Writer Agent - Creates tests for your functions
Refactor Agent - Improves code structure and readability
LESSON 2
How Sub-agents Work
Sub-agents are defined in Markdown files with special YAML frontmatter. Let's break down the structure:
Where They Live
Sub-agents are stored in special folders:
Project-level:.claude/agents/ (for your team)
Personal:~/.claude/agents/ (just for you)
💡 Priority: Project-level agents take priority over personal ones.
This means your team's shared agents will be used first!
File Structure
Every sub-agent file has two parts:
# Example: .claude/agents/code-reviewer.md# PART 1: YAML Frontmatter (the settings)
---
name:code-reviewerdescription:Reviews code for quality, security, and best practices. Use when you need a second opinion on your code.tools:Read, Grep, Glob, Bashmodel:sonnet
---
# PART 2: System Prompt (the instructions)
You are an expert code reviewer. When reviewing code:
1. Check for security vulnerabilities
2. Look for potential bugs
3. Suggest performance improvements
4. Ensure code follows best practices
5. Verify proper error handling
Always provide specific, actionable feedback.
Understanding the Fields
Field
Required?
What It Does
name
Yes
Unique identifier (lowercase, hyphens only)
description
Yes
Tells Claude when to use this agent
tools
No
Which tools the agent can use (inherits all if not specified)
model
No
Which AI model to use (sonnet, opus, haiku)
⚠️ Important: The description field is CRITICAL!
Claude uses this to decide when to call the sub-agent. Make it clear and specific!
LESSON 3
Creating Your First Sub-agent
🎯 Let's Build a Debugger Agent!
We'll create a sub-agent that specializes in finding and fixing bugs.
Follow along step by step!
Method 1: Using /agents Command (Recommended)
claude>/agentsAgent Management================1. Create new agent2. Edit existing agent3. View all agents4. Delete an agentSelect: 1Agent name: debuggerDescription: Investigates errors, identifies root causes, and suggests fixes. Use when encountering bugs or unexpected behavior.Tools (comma-separated, or leave empty for all): Read, Edit, Bash, Grep, GlobModel (sonnet/opus/haiku/inherit): sonnet✓ Agent 'debugger' created at .claude/agents/debugger.md
Method 2: Create File Directly
Create a file at .claude/agents/debugger.md:
---
name: debugger
description: Investigates errors, identifies root causes, and suggests fixes. Use when encountering bugs or unexpected behavior.
tools: Read, Edit, Bash, Grep, Glob
model: sonnet
---
You are an expert debugger. Your job is to find and fix bugs efficiently.
## Your Process:
1. **Capture the error** - Get the exact error message and stack trace
2. **Reproduce the issue** - Understand when and how it occurs
3. **Isolate the problem** - Narrow down to the specific code causing issues
4. **Find root cause** - Not just the symptom, but the actual problem
5. **Apply minimal fix** - Fix only what's broken, don't change other things
6. **Verify the fix** - Make sure it actually solves the problem
## Important Rules:
- Always explain your reasoning
- Test your fixes before declaring victory
- Consider edge cases
- Document what you changed and why
You just created a specialized debugging assistant! Now whenever you have a bug,
Claude can call on this expert to help investigate and fix it.
LESSON 4
Invoking Sub-agents
There are two ways Claude uses sub-agents:
1. Automatic Delegation (Magic Mode! 🪄)
Claude automatically picks the right sub-agent based on what you ask. You don't need to
mention the agent at all!
claude> I'm getting a "TypeError: Cannot read property 'map' of undefined"
when I try to render my user list. Can you help me fix it?
Claude thinks: "This is a bug investigation task... I should use the debugger agent!"[Automatically delegates to debugger agent]Agent is investigating the error...
💡 Pro Tip: Add phrases like "use PROACTIVELY" in your description to encourage
Claude to automatically use the agent more often!
2. Explicit Invocation (You're in Control)
Mention the sub-agent directly when you want to be specific:
# Explicitly call the debugger agentclaude> Use the debugger subagent to investigate why my login
function isn't working. Here's the error: "Authentication failed"
# Explicitly call the code-reviewer agentclaude> Have the code-reviewer agent check my new payment
processing function for security issues.
# Chain multiple agentsclaude> First use the code-reviewer agent to check my code,
then use the debugger agent to fix any issues it finds.
What Happens Behind the Scenes
When a sub-agent is called:
Claude creates a separate conversation for the agent
The agent gets its own fresh context window
It follows its custom instructions (system prompt)
It uses only the tools you allowed
When done, it reports back to Claude
LESSON 5
More Sub-agent Examples
Example 1: Documentation Writer
---
name: doc-writer
description: Writes clear, comprehensive documentation for code. Use when you need README files, API docs, or code comments.
tools: Read, Write, Glob
model: sonnet
---
You are a technical documentation expert. Write documentation that is:
- Clear and easy to understand
- Well-organized with proper headings
- Includes code examples where helpful
- Suitable for developers of varying skill levels
Always include:
- Purpose/overview
- Installation/setup instructions
- Usage examples
- API reference (if applicable)
- Troubleshooting tips
Example 2: Test Writer
---
name: test-writer
description: Creates comprehensive test suites for functions and modules. Use when you need unit tests, integration tests, or test coverage.
tools: Read, Write, Bash
model: sonnet
---
You are a testing expert. When writing tests:
1. Cover the happy path (normal usage)
2. Test edge cases (empty inputs, max values, etc.)
3. Test error conditions
4. Use descriptive test names that explain what's being tested
5. Follow the project's existing test patterns
Use the appropriate testing framework for the project.
Example 3: Security Auditor
---
name: security-auditor
description: Audits code for security vulnerabilities and suggests fixes. Use PROACTIVELY when reviewing code that handles user input, authentication, or sensitive data.
tools: Read, Grep, Glob
model: opus
---
You are a security expert. Check for:
## Critical Vulnerabilities:
- SQL Injection
- Cross-Site Scripting (XSS)
- Command Injection
- Authentication bypasses
- Sensitive data exposure
## Best Practices:
- Input validation
- Output encoding
- Proper authentication
- Secure session management
- Error handling that doesn't leak info
Rate each finding by severity: CRITICAL, HIGH, MEDIUM, LOW
💡 Notice: The security-auditor uses model: opus - a more powerful
(and expensive) model. This makes sense for security-critical tasks where accuracy is crucial!
LESSON 6
Best Practices
✅ DO These Things
Keep agents focused - One specific task per agent
Write detailed descriptions - Include trigger keywords
Limit tool access - Only give tools they need
Use version control - Check agents into Git for team sharing
Test your agents - Make sure they work as expected
❌ DON'T Do These
Create "do everything" agents - Too broad = poor results
Skip the description - Claude won't know when to use it
Give unnecessary permissions - Security risk!
Forget to document - Your team won't know how to use them
⚠️ Limitation: Sub-agents CANNOT spawn other sub-agents.
This prevents infinite loops and keeps things manageable.
📝
Week 2 Key Takeaways
✅ Sub-agents are specialized AI assistants with separate contexts
✅ Stored in .claude/agents/ (project) or ~/.claude/agents/ (personal)
✅ Use /agents command to manage them
✅ Each agent has: name, description, tools (optional), model (optional)
✅ Claude automatically delegates OR you can explicitly invoke
✅ The description field is crucial - it tells Claude when to use the agent