Guide to creating and utilizing specialized AI assistants
Sub-agents are specialized AI assistants designed to handle specific tasks. They have their own separate context window from the main Claude Code session and perform tasks independently.
Think of sub-agents as "assistants to your AI assistant."
When you assign a large project to Claude Code (the main assistant), Claude Code autonomously delegates subtasks to secondary assistants (sub-agents). For example, if you say "Find bugs in this project," the main assistant might tell a sub-agent "You check the frontend folder," while it examines the backend folder itself.
If you're a first-time user, you don't need to set up sub-agents yourself. Claude Code automatically utilizes sub-agents when it determines they are needed.
A context window is the amount of conversation content an AI can remember at once. It's similar to a person's short-term memory.
As conversations grow longer, the AI may forget earlier content. By using sub-agents, each task uses its own memory space, preserving the main conversation's memory.
Claude Code comes with 5 built-in sub-agents by default.
| Field | Details |
|---|---|
| Model | Claude Haiku 4.5 |
| Purpose | Read-only codebase exploration |
| Permissions | File reading and searching only (no modifications) |
| Features | Quickly understand code structure at low cost |
The main agent automatically uses this when analyzing codebase structure or locating specific files.
| Field | Details |
|---|---|
| Model | Same as the main model |
| Purpose | Conduct research in plan mode |
| Permissions | Read-only |
| Features | Exploration for building execution plans |
Activated when entering plan mode via the /plan command or Shift+Tab.
| Field | Details |
|---|---|
| Model | Same as the main model |
| Purpose | Handle complex multi-step tasks |
| Permissions | Full tool access |
| Features | Perform large tasks in an independent context |
Used when the main agent delegates complex subtasks at its own discretion.
| Field | Details |
|---|---|
| Model | Same as the main model |
| Purpose | Execute commands in a separate context |
| Permissions | Bash command execution |
| Features | Isolate long-running commands |
| Field | Details |
|---|---|
| Model | Claude Haiku 4.5 |
| Purpose | Answer questions about Claude Code features |
| Permissions | Read-only |
| Features | A helper that guides Claude Code usage |
The easiest method is to use the /agents command.
Custom sub-agents are created as markdown files in your project's .claude/agents/ folder. Write the agent's role and rules in the markdown file, and Claude Code will call on that specialist when needed.
/agents
An interactive interface appears where you can configure the name, description, tools, instructions, and more step by step.
Define sub-agents by creating Markdown files in the .claude/agents/ directory.
.claude/agents/
code-reviewer.md
test-writer.md
doc-generator.md
Each file consists of YAML frontmatter and a Markdown body.
---
name: "Code Reviewer"
description: "A specialized reviewer that examines code quality, security, and performance"
tools:
- Read
- Grep
- Glob
- Bash(eslint)
- Bash(npm test)
model: claude-sonnet-4-6
maxTurns: 30
---
# Code Review Guidelines
You are a code review expert. Review code based on the following criteria:
## Review Items
1. **Code quality**: Readability, naming conventions, duplicate code
2. **Security**: SQL injection, XSS, authentication bypass vulnerabilities
3. **Performance**: Unnecessary computations, N+1 queries, memory leaks
4. **Testing**: Test coverage, edge cases
5. **Type safety**: TypeScript strict mode compliance
## Output Format
Classify each issue by severity and report:
- CRITICAL: Requires immediate fix
- WARNING: Improvement recommended
- INFO: For reference| Field | Type | Description |
|---|---|---|
| name | string | Agent display name |
| description | string | Agent role description |
| tools | string[] | List of available tools |
| model | string | Claude model to use |
| permissionMode | string | Permission mode (default, plan, bypassPermissions) |
| maxTurns | number | Maximum execution turns |
| memory | string | Persistent memory scope (user, project, local) |
| background | boolean | Whether to run in the background |
| isolation | string | Isolation mode (worktree) |
| hooks | object | Agent-specific Hook settings |
| skills | string[] | List of skills to reference |
| mcpServers | object | Agent-specific MCP server settings |
Setting the memory field on a sub-agent allows it to retain information across sessions.
| Scope | Storage Location | Sharing Scope |
|---|---|---|
| user | ~/.claude/ | All projects for the user |
| project | .claude/ | All users in the project |
| local | .claude/local/ | Current user, current project |
---
name: "Learning Assistant"
description: "An assistant that remembers the user's learning progress"
memory: user
---
Remembers the user's learning progress and preferences, and guides the
next lesson based on content learned in previous sessions.Agents with memory retain conversation content and learning results from previous sessions, maintaining a continuous workflow.
When agents with the same name are defined in multiple locations, the following priority order applies:
1. CLI (--agents option) ← Highest
2. Project (.claude/agents/)
3. User (~/.claude/agents/)
4. Plugins ← Lowest
Project agents take priority over user agents. Temporary agents passed via CLI have the highest priority.
The standard execution mode. The main session waits until the agent completes its task.
# Invoke an agent in conversation
"Review the src/ directory with the code reviewer agent"
Set background: true to run the agent in the background. The main session can continue with other tasks.
---
name: "Test Runner"
background: true
tools:
- Bash(npm test)
- Read
---
Runs tests in the background and reports the results.Multiple sub-agents can be run simultaneously. Claude Code automatically determines when to execute them in parallel.
"Review the frontend and backend directories simultaneously"
Pass the output of one agent as input to another agent.
"First find issues with the code analysis agent, then pass the results to the refactoring agent"
Setting isolation: worktree makes the agent work in a separate Git worktree.
---
name: "Experimental Refactoring"
description: "Safely attempt large-scale refactoring"
isolation: worktree
tools:
- Read
- Write
- Edit
- Bash
model: claude-opus-4-6
maxTurns: 50
---
Performs refactoring in a separate worktree.
Since it does not affect the main branch, you can experiment safely.
If the results are satisfactory, you can merge them into the main branch.You can define agents directly from the CLI using the --agents option. This is useful for one-time use without creating files.
# Define a temporary agent in JSON format
claude --agents '[{
"name": "Quick Reviewer",
"description": "Fast code review",
"tools": ["Read", "Grep"],
"model": "claude-haiku-4-5",
"maxTurns": 10
}]' -p "Check the code quality of the src/ directory"# Automated code review in CI/CD
claude --agents '[{
"name": "ci-reviewer",
"tools": ["Read", "Grep", "Glob", "Bash(eslint)"],
"model": "claude-sonnet-4-6"
}]' -p "Review the code quality of changed files and write a report"
# Automate specific tasks in scripts
claude --agents '[{
"name": "migrator",
"tools": ["Read", "Write", "Edit", "Bash"],
"model": "claude-opus-4-6",
"maxTurns": 50
}]' -p "Convert all React class components to functional components"To prohibit the use of a specific agent, configure permissions deny.
{
"permissions": {
"deny": [
"agent:dangerous-agent"
]
}
}You can also restrict an agent's use of specific tools.
{
"permissions": {
"deny": [
"Bash(rm -rf)",
"Write(*.env)"
]
}
}---
name: "Test Writer"
description: "Automatically generates test code by analyzing source code"
tools:
- Read
- Write
- Glob
- Bash(npm test)
- Bash(npx vitest)
model: claude-sonnet-4-6
maxTurns: 30
---
# Test Writing Guide
Analyzes source code and writes unit tests.
## Rules
- Use the Vitest framework
- Structure with describe/it pattern
- Include edge cases and error cases
- At least 3 test cases per function
- Use mocks minimally---
name: "Documentation Assistant"
description: "Generates API documentation and comments by analyzing code"
tools:
- Read
- Write
- Glob
- Grep
model: claude-haiku-4-5
maxTurns: 20
memory: project
---
# Documentation Guidelines
Analyzes code to generate TSDoc/JSDoc comments and API documentation.
## Rules
- Add TSDoc comments to all exported functions
- Include parameter and return value descriptions
- Include usage example code
- Provide both Korean and EnglishWhen using sub-agents, the most important thing is choosing the right model for the task. Using high-performance models for every task will cause costs to increase rapidly.
| Task Type | Haiku 4.5 | Sonnet 4.6 | Opus 4.6 | Recommended Model |
|---|---|---|---|---|
| Code review (1 time) (5-10 files) | ~$0.01 | ~$0.05 | ~$0.30 | Sonnet |
| Codebase exploration (grep/glob) | ~$0.005 | ~$0.02 | ~$0.15 | Haiku |
| Unit test writing (1 function) | ~$0.01 | ~$0.04 | ~$0.25 | Sonnet |
| Bug fix (single file) | ~$0.01 | ~$0.05 | ~$0.30 | Sonnet |
| Large-scale refactoring (20+ files) | ~$0.05 | ~$0.20 | ~$1.50 | Opus |
| Documentation generation (API docs) | ~$0.008 | ~$0.03 | ~$0.20 | Haiku |
| Lint/format check | ~$0.003 | ~$0.01 | ~$0.08 | Haiku |
Note: The costs above are rough estimates. Actual costs vary depending on codebase size, number of files, and number of conversation turns.
Use Haiku for read-only tasks: Tasks that don't modify files, such as code exploration, searching, and structure analysis, are well-served by Haiku.
Mix models: Setting the main agent to Sonnet and exploration sub-agents to Haiku can significantly reduce costs.
Set maxTurns appropriately: This prevents agents from running indefinitely. Generally, 10 turns is suitable for exploration tasks and 20-30 turns for modification tasks.
Limit sub-agent tools to the minimum necessary: Allowing only required tools prevents unnecessary tool invocations.
Monitor costs: Use the /cost command to check the cumulative cost of the current session.
---
# Cost-optimized sub-agent configuration example
name: "Economical Code Explorer"
description: "Explore the codebase at low cost"
tools:
- Read # Only allow file reading
- Grep # Only allow text search
- Glob # Only allow file pattern search
model: claude-haiku-4-5 # Most affordable model
maxTurns: 10 # Limited to a maximum of 10 turns
---
Explores the codebase and provides summaries only. Does not modify files.When a sub-agent doesn't behave as expected, here's how to diagnose and resolve issues.
Claude Code displays the execution status of sub-agents in real time. You can monitor activity using the following methods:
# Check current session status (including running sub-agents)
# Enter /status in interactive mode
/status
# Check cost and token usage
/cost
# Check agent list and status
/agentsThis occurs when the sub-agent file cannot be found.
Error: Agent "code-reviewer" not found
Cause and Solution:
.claude/agents/ directory.md (not .txt or .mdx)name field in the file's YAML frontmatter is correctThis occurs when a sub-agent attempts to use a tool that is not allowed.
Error: Tool "Bash" is not permitted for agent "read-only-agent"
Cause and Solution:
tools fieldsettings.json under permissions.denyThis occurs when a sub-agent reaches its maxTurns limit.
Error: Agent reached maximum turns (10)
Cause and Solution:
maxTurns value (e.g., to 20 or 30)Cause and Solution:
Write and Edit from the tools field to restrict it to read-onlypermissionMode: "plan" to require approval before modificationsWhen problems occur, check the following in order:
.claude/agents/agent-name.mdRead, Write, Edit, Bash, Glob, Grep (case-sensitive)claude-opus-4-6, claude-sonnet-4-6, claude-haiku-4-5settings.jsonclaude --versionBy effectively utilizing sub-agents, you can automate repetitive tasks and efficiently distribute complex work.