How to Create Custom Agents in Claude Code
Custom agents let you build specialized AI assistants for specific tasks. Create a code reviewer, a debugger, or a data analyst—each with its own context, tools, and behavior.
Custom agents in Claude Code are specialized AI assistants you define with a simple Markdown file — each gets its own instructions, tool access, and context window, and Claude delegates tasks to the right one automatically. You can create a code reviewer, a debugger, a data analyst, or any other role tailored to your workflow.
This guide walks you through creating custom agents step by step, from a basic configuration to advanced setups with restricted permissions and model selection. Each agent runs independently so its work stays out of your main conversation, keeping things fast and focused.
What Are Custom Agents?
Custom agents (officially called "subagents") are specialized AI assistants that handle specific types of tasks. Each one has:
- Its own context window: Keeps exploration separate from your main conversation
- Custom system prompt: Instructions that define how the agent behaves
- Specific tool access: Control which tools the agent can use
- Independent permissions: Set different permission levels per agent
- Optional model selection: Use Haiku 4.5 for fast tasks, Opus 4.6 for complex reasoning, or Sonnet 4.5 for a balanced approach
When you ask Claude something like "review this code for security issues," it checks if any agent matches that description. If your code-reviewer agent says it handles security reviews, Claude delegates the task automatically.
Key benefit: Agents preserve your main conversation context. When an agent runs tests or explores a codebase, all that verbose output stays in the agent's context. Only the summary returns to you.
Built-in Agents You Already Have
Claude Code comes with several built-in agents that it uses automatically:
| Agent | Purpose | Model |
|---|---|---|
Explore |
Read-only codebase search and analysis | Haiku (fast) |
Plan |
Research during plan mode | Inherited |
General-purpose |
Complex multi-step tasks | Inherited |
The Explore agent is particularly useful. When Claude needs to search your codebase without making changes, it delegates to Explore. This keeps the search results out of your main conversation, preserving context for actual work.
How to Create Your First Agent
The fastest way to create an agent is with the /agents command. Here's the complete process:
Step 1: Open the agents interface
In Claude Code, run /agents. This opens an interactive menu showing all available agents.
Step 2: Create a new agent
Select Create new agent, then choose where to save it:
- User-level: Saves to
~/.claude/agents/— available in all your projects - Project-level: Saves to
.claude/agents/— shared with your team via git
Step 3: Generate with Claude or write manually
Select Generate with Claude and describe what you want:
A code review agent that checks for security issues,
performance problems, and best practices. It should
explain each issue and show how to fix it.
Claude generates the system prompt and configuration. Press e to edit it if needed.
Step 4: Select tools
Choose which tools the agent can use. For a read-only reviewer, select only Read-only tools. The agent won't be able to modify files.
Step 5: Choose a model
Pick the AI model for this agent:
- Sonnet (Claude Sonnet 4.5): Balanced speed and capability (recommended for most agents)
- Haiku (Claude Haiku 4.5): Fastest and cheapest—great for simple, frequent tasks like linting or formatting checks
- Opus (Claude Opus 4.6): Most capable—use for complex reasoning, architectural reviews, and multi-step debugging
- Inherit: Uses whatever model your main conversation is using
Step 6: Save and test
Save the agent. It's available immediately—no restart needed. Test it:
Use the code-reviewer agent to check my recent changes
Agent File Structure
Agents are Markdown files with YAML frontmatter. Here's the anatomy of an agent file:
---
name: code-reviewer
description: Reviews code for quality, security, and best practices
tools: Read, Glob, Grep
model: sonnet
---
You are a senior code reviewer. When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Check for security issues, performance problems, and code quality
Report findings as:
- Critical (must fix)
- Warnings (should fix)
- Suggestions (nice to have)
Include specific examples of how to fix each issue.
The frontmatter defines metadata and configuration. The body is the system prompt that guides the agent's behavior.
Frontmatter Fields Reference
| Field | Required | Description |
|---|---|---|
name |
Yes | Unique identifier (lowercase, hyphens only) |
description |
Yes | When Claude should delegate to this agent |
tools |
No | Allowed tools (inherits all if omitted) |
disallowedTools |
No | Tools to explicitly deny |
model |
No | sonnet, opus, haiku, or inherit |
permissionMode |
No | Permission handling (see below) |
skills |
No | Skills to preload into the agent |
hooks |
No | Lifecycle hooks for this agent |
Agents vs Skills: When to Use Each
Claude Code has two ways to extend its capabilities: agents and skills. They solve different problems.
Use Agents When
- Task produces verbose output you don't need
- You need to restrict tool access
- Work should be isolated from main context
- Different permission levels are needed
- You want to use a different AI model
Use Skills When
- You want reusable prompts/workflows
- Context should stay in main conversation
- You need slash command access
- Multiple phases share context
- Quick, targeted changes
The key difference: Agents run in isolated context windows. Skills run in your main conversation. Use agents when you want separation; use skills when you want continuity.
As of Claude Code version 2.1.3, slash commands and skills have been unified into a single system. Creating a skill automatically makes it available as a slash command with the / prefix. Existing slash command files still work—they are treated as skills behind the scenes. Skills follow the Agent Skills open standard, which means they work across multiple AI tools, not just Claude Code.
Quick rule
If you'd tell a human colleague "go figure this out and report back," use an agent. If you'd say "help me with this while I watch," use a skill.
Practical Agent Examples
Code Reviewer Agent
A read-only agent that reviews code without modifying it:
---
name: code-reviewer
description: Expert code review specialist. Use after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: sonnet
---
You are a senior code reviewer ensuring high standards.
When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately
Review checklist:
- Code clarity and readability
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Performance considerations
Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)
Include specific fix examples for each issue.
Debugger Agent
An agent that can both analyze and fix issues:
---
name: debugger
description: Debugging specialist for errors and test failures. Use when encountering issues.
tools: Read, Edit, Bash, Grep, Glob
model: inherit
---
You are an expert debugger specializing in root cause analysis.
When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works
For each issue, provide:
- Root cause explanation
- Evidence supporting diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations
Focus on fixing the underlying issue, not symptoms.
Database Query Agent (Read-Only)
An agent that allows Bash but only for SELECT queries:
---
name: db-reader
description: Execute read-only database queries for analysis and reports.
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
You are a database analyst with read-only access.
Execute SELECT queries to answer questions about the data.
Present results clearly with context.
You cannot modify data. If asked to INSERT, UPDATE, DELETE,
or modify schema, explain that you only have read access.
This uses a hook to validate commands before execution. Create the validation script:
#!/bin/bash
# ./scripts/validate-readonly-query.sh
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
# Block write operations
if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER)\b' > /dev/null; then
echo "Blocked: Only SELECT queries allowed" >&2
exit 2
fi
exit 0
Advanced Agent Configuration
Permission Modes
Control how agents handle permission prompts:
| Mode | Behavior |
|---|---|
default |
Standard permission checking with prompts |
acceptEdits |
Auto-accept file edits |
dontAsk |
Auto-deny prompts (allowed tools still work) |
bypassPermissions |
Skip all permission checks (use with caution) |
plan |
Read-only exploration mode |
Async Hooks
Hooks can now run in the background without blocking Claude Code's execution. Add async: true to your hook config for non-blocking operations like logging, notifications, or analytics. The tool hook execution timeout has also been extended from 60 seconds to 10 minutes, giving hooks more time for longer-running validations.
hooks:
PostToolUse:
- matcher: "Edit"
hooks:
- type: command
command: "./scripts/log-edit.sh"
async: true
Preloading Skills
Inject skill content into an agent's context at startup:
---
name: api-developer
description: Implement API endpoints following team conventions
skills:
- api-conventions
- error-handling-patterns
---
Implement API endpoints. Follow the conventions from preloaded skills.
CLI-Defined Agents
Create temporary agents when launching Claude Code:
claude --agents '{
"quick-review": {
"description": "Fast code review",
"prompt": "Review code briefly. Focus on critical issues only.",
"tools": ["Read", "Grep"],
"model": "haiku"
}
}'
These agents exist only for that session—useful for testing or automation scripts.
Common Mistakes
- Description too vague: Claude uses the description to decide when to delegate. "A helpful agent" tells it nothing. "Code reviewer for security issues and best practices" is clear.
- Giving too many tools: Agents inherit all tools by default. For a read-only reviewer, explicitly limit tools to
Read, Grep, Glob. - Using Opus for simple tasks: Haiku 4.5 costs $1/$5 per million tokens (input/output) versus Opus 4.6 at $5/$25. That is 5x cheaper on both input and output. Use Haiku for lightweight, frequent tasks like linting checks, simple searches, or formatting verification.
- Forgetting agents can't spawn agents: Subagents cannot create other subagents. If you need nested delegation, chain agents from the main conversation.
- Not checking into git: Project agents in
.claude/agents/should be version controlled so your team shares the same configurations.
FAQ
How do I see all available agents?
Run /agents in Claude Code. It shows built-in agents, your custom agents, and any plugin agents you've installed.
Can I run agents in the background?
Yes. Claude decides automatically, or you can ask it to "run this in the background." Press Ctrl+B to background a running task. Background agents run concurrently while you continue working.
How do I disable a built-in agent?
Add it to your settings deny list: "deny": ["Task(Explore)"] in your settings.json. Or use the CLI flag: claude --disallowedTools "Task(Explore)".
Why isn't my agent being used?
Check the description field. Claude matches tasks to agents based on descriptions. Make sure yours clearly explains when to use it. Also verify the file is in the right location (~/.claude/agents/ or .claude/agents/) and has the .md extension.
Can agents access MCP tools?
Foreground agents can use MCP tools. Background agents cannot—they run with a limited toolset for safety. MCP (Model Context Protocol) servers give Claude access to external tools, databases, and APIs. Configure them via the CLI and they become available in both the terminal and VS Code extension.
What are the latest Claude models I can use for agents?
The current model options are Claude Opus 4.6 (the most capable, best for complex reasoning), Claude Sonnet 4.5 (balanced speed and quality, good default for most agents), and Claude Haiku 4.5 (fastest and cheapest, ideal for simple read-only tasks). Specify them in your agent's frontmatter as model: opus, model: sonnet, or model: haiku.
Can I use agents from within the VS Code extension?
Yes. The official Claude Code VS Code extension supports the full agents system. Your custom agents are available in VS Code just as they are in the terminal. You can create, edit, and invoke agents from the VS Code interface.
Related Guides
- How to Use Slash Commands — including the /agents command
- How to Use CLAUDE.md Files — persistent memory for your projects
- How to Configure Claude Code Settings — permissions, tools, and more
Like Claude Code? Meet Your Chief AI Officer
Watch me build a complete website using only plain English—no coding required. Then try it yourself.
Get the Free Blueprint href="/blueprint">Watch the Free Setup Video →rarr;