DEV Community

UC Jung
UC Jung

Posted on

Chapter 4. How to Use — Sub Agents

4.1 What Is a Sub Agent?

A Sub Agent is a specialized AI assistant dedicated to handling specific tasks within a Claude Code session.

If the main Claude Code is the "general manager," Sub Agents are "team members," each with their own area of expertise.
Each Sub Agent operates with its own independent context window, dedicated system prompt, and restricted tool access.

┌──────────────────────────────────────────────┐
│  Main Claude Code Session (General Manager)  │
│                                              │
│  "Review this code"                          │
│      ↓ delegate                              │
│  ┌──────────────────────────────────┐        │
│  │  Sub Agent: code-reviewer        │        │
│  │  • Independent context window    │        │
│  │  • Read-only tools allowed       │        │
│  │  • Code review system prompt     │        │
│  └──────────────┬───────────────────┘        │
│                 ↓ return result              │
│  "Review complete: 3 improvements found"     │
└──────────────────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

4.2 Purpose and Role

Why Use Sub Agents?

Purpose Description
Context preservation Exploration and analysis results do not pollute the main conversation. Sub Agents return only a summary, keeping the main context clean
Specialization Role-specific system prompts for tasks like code review, test writing, and security analysis improve accuracy
Tool restriction Apply the principle of least privilege — e.g., grant only Read to review agents, and Write/Edit to implementation agents
Reusability A Sub Agent created once can be used across all projects (user scope)

Built-in Sub Agents

Claude Code includes built-in Sub Agents that are used automatically.

Name Tools Role
Explore Read-only Search and navigate the codebase. No file modifications
Plan Read-only Analyze the codebase before implementation in Plan Mode
General-purpose All tools Complex multi-step tasks (exploration + modification)
Bash Terminal Execute commands in a separate context

These built-in agents are delegated to automatically by Claude.
The user does not need to invoke them directly — they are selected automatically based on the nature of the task.


4.3 Setup and Verification

Method 1: /agents Command (Recommended)

> /agents
Enter fullscreen mode Exit fullscreen mode

From the interactive menu, you can:

  1. Select Create new agent
  2. Choose Personal (all projects) or Project (current project only)
  3. Select Generate with Claude → enter a description of the role
  4. Choose tool access scope (Read-only, all tools, etc.)
  5. Select a model (Sonnet, Opus, Haiku)
  6. Choose a background color → save

Example: Creating a Code Review Agent

> /agents
→ Create new agent
→ Personal
→ Generate with Claude
→ "An agent that analyzes code and suggests improvements from the perspective of readability, performance, and best practices"
→ Select Read-only tools
→ Sonnet
→ Save
Enter fullscreen mode Exit fullscreen mode

Method 2: Writing a Markdown File Directly

# Personal use (all projects)
mkdir -p ~/.claude/agents
nano ~/.claude/agents/code-reviewer.md

# Project use (current project only)
mkdir -p .claude/agents
nano .claude/agents/code-reviewer.md
Enter fullscreen mode Exit fullscreen mode

How to Verify

# List agents from CLI (outside a session)
claude agents

# List agents from within a session
> /agents
Enter fullscreen mode Exit fullscreen mode

How to Invoke

# Automatic delegation — Claude judges automatically based on the description
> Analyze the code quality of this project

# Explicit invocation — specify the agent by name
> Use the code-reviewer agent to review the src/api/ folder
Enter fullscreen mode Exit fullscreen mode

4.4 Sub Agent File Structure

A Sub Agent is composed of a YAML front matter + Markdown body.

File Example: .claude/agents/code-reviewer.md

---
name: code-reviewer
description: Analyzes code quality and suggests improvements from the perspectives of readability, performance, and security. Used when code review or quality analysis is requested.
tools: Read, Grep, Glob
model: sonnet
---

# Code Reviewer Agent

## Role
You are a senior software engineer dedicated to performing code reviews.

## Review Criteria
- Readability: variable names, function structure, comments
- Performance: unnecessary iteration, potential memory leaks
- Security: SQL injection, XSS, hardcoded secrets
- Best practices: adherence to project conventions

## Output Format
For each issue:
1. File path and line number
2. Current code
3. Description of the problem
4. Suggested improved code
Enter fullscreen mode Exit fullscreen mode

YAML Front Matter Fields

Field Required Description
name Agent identifier (alphanumeric, hyphens allowed)
description Explains when to use this agent. Claude reads this description to decide whether to delegate automatically
tools List of allowed tools. If omitted, all tools from the main session are inherited
model Model to use (sonnet, opus, haiku). Default: the main session model

Tool Restriction Examples

# Read-only (for review and analysis)
tools: Read, Grep, Glob

# Code modification allowed (for implementation)
tools: Read, Write, Edit, Bash, Grep, Glob

# Inherit all tools (omit the field entirely)
# Do not include the tools field at all
Enter fullscreen mode Exit fullscreen mode

Scope by Storage Location

~/.claude/agents/             ← Personal: available across all projects
.claude/agents/               ← Project: available only in this project
                                 (commit to Git to share with the team)
Enter fullscreen mode Exit fullscreen mode

If a Sub Agent with the same name exists in both locations, the project-level agent takes precedence.

Full File Structure Example

my-project/
├── .claude/
│   ├── agents/                    ← Project Sub Agents
│   │   ├── code-reviewer.md
│   │   ├── test-writer.md
│   │   └── security-auditor.md
│   ├── settings.json              ← Project settings (hooks, permissions)
│   └── commands/                  ← Slash commands
├── CLAUDE.md                      ← Project memory
└── .mcp.json                      ← MCP server config (shared with team)

~/.claude/
├── agents/                        ← Personal Sub Agents (all projects)
│   └── general-assistant.md
├── CLAUDE.md                      ← Global memory (personal)
└── settings.json                  ← Personal global settings
Enter fullscreen mode Exit fullscreen mode

4.5 Sub Agent vs MCP — Key Differences

Category Sub Agent MCP Server
Identity A specialized Claude instance A connection to an external tool or service
How it works Claude performs tasks in an independent context An external process provides tool functionality
Context Its own context window (separate from the main session) Shares and consumes the main context window
Config format Markdown file (YAML + prompt) JSON config (command, args, env)
Storage location .claude/agents/ .claude.json or .mcp.json
How it is invoked Claude delegates automatically or by name Claude calls it as a tool
What it can do AI reasoning tasks: code analysis, review, implementation, test writing, etc. External system integration: DB queries, GitHub PRs, browser automation, etc.
Cost Consumes separate tokens (independent context) Consumes context proportional to tool descriptions
Relationship Can use MCP tools Operates independently of Sub Agents

When to Use Which?

"Automatically create a GitHub PR"              → MCP (github server)
"Review this code"                              → Sub Agent (code-reviewer)
"Query user data from the DB"                   → MCP (postgresql server)
"Write test code"                               → Sub Agent (test-writer)
"Find a function by symbol"                     → MCP (serena server)
"Analyze security vulnerabilities"              → Sub Agent (security-auditor)
Enter fullscreen mode Exit fullscreen mode

Key distinction: MCP is a tool for connecting to external systems; Sub Agents are AI instances that perform work in specialized roles.
The two are not substitutes — they are meant to be combined.
Example: a security-auditor Sub Agent uses the Serena MCP's find_symbol tool to trace vulnerable functions.


4.6 Quick Reference

# ── Sub Agent Management ─────────────────────────────
> /agents                              # Create, view, edit, delete (in session)
claude agents                          # List agents (CLI)

# ── File Locations ───────────────────────────────────
~/.claude/agents/                      # Personal (all projects)
.claude/agents/                        # Project (team-shareable)

# ── Invocation ───────────────────────────────────────
> Analyze using the code-reviewer agent     # Explicit invocation
> Review this code                          # Automatic delegation (description matching)

# ── File Format ──────────────────────────────────────
# .claude/agents/my-agent.md
---
name: my-agent
description: Describe when to use this agent
tools: Read, Grep, Glob            # Omit to inherit all tools
model: sonnet                      # sonnet / opus / haiku
---
System prompt content (Markdown)
Enter fullscreen mode Exit fullscreen mode

Reference: https://code.claude.com/docs/en/sub-agents

Top comments (0)