Building Your First Sub-Agent: A Practical Guide to Claude Code
I spent weeks using Claude Code before I realized my context window was a mess. I’d ask Claude to research something, and boom—half my context is filled with file contents and grep results. Then I’d try to ask a follow-up question and Claude would forget what we were doing.
Sub-agents fixed this for me. They’re basically specialized AI assistants that handle specific tasks in their own isolated context. Your main conversation stays clean, and you get better results.
Today I’m going to show you how to build a code reviewer sub-agent. It’ll automatically check your code for security issues and common mistakes. Once you see how this works, you’ll probably want to build a dozen more.
What Makes Sub-Agents Different
The main Claude agent can do anything, which is great until it’s not. Sub-agents are different:
- They have their own context windows, so research doesn’t pollute your main conversation
- You write custom prompts for each one (make it security-focused, or overly critical, or whatever)
- You control which tools they can use (read-only for reviewers, full access for implementers)
- They can run in parallel
I think of them like having a team instead of one person doing everything.
Setting This Up
You need Claude Code installed and a git repo to work with. That’s it. If you’re not familiar with YAML or markdown frontmatter, don’t worry—I’ll explain when we get there.
Creating the Agent File
Sub-agents are just markdown files in .claude/agents/. Create that directory first:
mkdir -p .claude/agents
Now create a file for your code reviewer:
touch .claude/agents/code-reviewer.md
The filename matters—it’s how you’ll reference this agent. You’ll call it by name: code-reviewer.
Configuring Your Sub-Agent
Open that file and add this at the top:
---
name: code-reviewer
description: 'Expert code reviewer. Use PROACTIVELY after writing code to check security, style, and best practices.'
tools: Read, Grep, Glob, Bash
model: sonnet
---
This section between the --- marks is called frontmatter. It’s just metadata—think of it as the sub-agent’s ID card. It uses YAML format, which is just key: value pairs.
Here’s what each field does:
- name: How you reference this sub-agent
- description: Tells the main Claude agent when to use this. The word “PROACTIVELY” is important—it encourages automatic use
- tools: Which tools this agent can access. I’m restricting this to read-only operations plus git commands. You could give it access to everything, but I don’t want a reviewer accidentally modifying code
- model: Which Claude model to use. Options are
sonnet,opus,haiku, orinherit(uses whatever model the main agent is using)
Writing the System Prompt
Below that frontmatter, you write the actual instructions. This is where you define how the sub-agent behaves. The prompt can be as detailed or as simple as you want.
Here’s what I use:
---
name: code-reviewer
description: 'Expert code reviewer. Use PROACTIVELY after writing code to check security, style, and best practices.'
tools: Read, Grep, Glob, Bash
model: sonnet
---
You are a senior software engineer with 15+ years of experience in code review, security auditing, and best practices enforcement.
## Your Mission
When invoked, perform a thorough code review focusing on:
1. **Security vulnerabilities**
- SQL injection risks
- XSS vulnerabilities
- Command injection possibilities
- Insecure authentication/authorization
- Exposed secrets or credentials
- OWASP Top 10 issues
2. **Code quality**
- Proper error handling
- Edge case coverage
- Code duplication
- Overly complex logic
- Missing null/undefined checks
3. **Best practices**
- Consistent naming conventions
- Proper function/variable scope
- Performance concerns
- Memory leaks or resource cleanup
- Framework-specific best practices
## Review Process
1. Run `git diff HEAD` to see recent changes
2. Identify modified files and focus your review on changed code
3. Read the full context of modified functions/classes
4. Check for security vulnerabilities FIRST
5. Then assess code quality and best practices
6. Provide specific, actionable feedback with line numbers
## Output Format
Structure your review as:
### 🔴 Critical Issues (Fix Immediately)
- [file:line] Description of security vulnerability or breaking issue
### 🟡 Warnings (Should Fix)
- [file:line] Description of code quality concern
### 🟢 Suggestions (Nice to Have)
- [file:line] Description of improvement opportunity
### ✅ Positive Feedback
- Call out well-written code or good practices
## Important Guidelines
- Be **honest and critical** — false positives are better than missed vulnerabilities
- Reference specific lines using `filename:line_number` format
- Explain _why_ something is a problem, not just _what_ the problem is
- If you're unsure, say so and explain your reasoning
- Don't be overly pedantic about style if the code follows the project's existing patterns
Quick recap of the file structure:
- Lines 1-6: Frontmatter (the config)
- Everything after: System prompt (the instructions)
Save that as .claude/agents/code-reviewer.md.
Testing It Out
Start a Claude Code session and make a small code change. Then just ask:
Use the code-reviewer agent to review my recent changes
The sub-agent will run git diff, read your changes, and give you feedback. It works in isolation, so your main conversation history stays clean.
If you want it to run automatically whenever you (or Claude) write code, update the description:
description: 'Expert code reviewer. Use PROACTIVELY and AUTOMATICALLY after the main agent writes or modifies code files.'
Now Claude will invoke the reviewer without you asking.
What the Output Looks Like
Here’s an example of what you might get:
### 🔴 Critical Issues
- [src/api/users.js:45] SQL injection vulnerability
Query concatenates user input directly: `SELECT * FROM users WHERE id = ${userId}`
Use parameterized queries instead
### 🟡 Warnings
- [src/api/users.js:67] Missing error handling
Database query can throw but isn't wrapped in try/catch
### 🟢 Suggestions
- [src/api/users.js:23] Consider extracting validation logic
The validation code could be reusable across other endpoints
### ✅ Positive Feedback
- Good use of async/await throughout
- Clear variable naming makes code self-documenting
Honestly, the critical feedback is the most valuable part. I’ve caught actual SQL injection risks this way.
Things I Learned the Hard Way
Don’t give every sub-agent full tool access. I made this mistake early on. A documentation reviewer doesn’t need write permissions. Restrict tools to prevent accidents.
Generic prompts produce generic results. “Review this code” won’t cut it. Be specific about what you want checked. Mention your stack. If you’re writing React, say that in the prompt.
Sub-agents can’t see your main conversation. They’re completely isolated. If context matters, you need to include it in the system prompt or pass it when you invoke the agent.
The description field matters more than you think. This is what tells Claude’s main agent when to use your sub-agent. Be explicit. Vague descriptions mean the agent won’t get used.
Other Sub-Agents Worth Building
Once you have this working, you’ll probably want more. Some ideas:
- Documentation Reviewer — Checks docs for broken links, outdated examples, inconsistent formatting
- Test Generator — Writes unit tests for your code (honestly this one has saved me hours)
- Security Auditor — Deep security analysis with threat modeling
- Performance Analyzer — Profiles code and suggests optimizations
I have about eight sub-agents now. Each one handles a specific thing, and it’s way better than having one agent try to do everything.
Project vs. User Level
One last thing: you can create sub-agents in two places.
- Project level:
.claude/agents/in your repo — these are project-specific - User level:
~/.claude/agents/in your home directory — these work across all projects
I keep my code reviewer at the user level since I want it everywhere. Project-specific stuff (like a docs reviewer that knows your API structure) goes in the repo.
If you have the same sub-agent name in both places, the project-level one takes precedence.
Final Thoughts
Sub-agents changed how I use Claude Code. Instead of one AI trying to do everything, I have a team of specialized agents. The code reviewer we built here is just the start.
Think about your workflow. What tasks do you do repeatedly? What would benefit from a second pair of eyes? Build a sub-agent for it.
Start simple. One agent. Get it working. Then build more.
Further Reading
- Claude Code Sub-Agents Documentation
- Claude Agent SDK Documentation
- Awesome Claude Code Sub-Agents — Community collection