Introduction
If you have been using Claude Code for your development workflow, you already know how powerful it is as an AI-powered coding assistant. But what if you could go beyond basic chat interactions and create specialized AI agents that handle specific tasks automatically? That is exactly what Claude Code’s custom agent system lets you do.
In this tutorial, I will walk you through everything you need to know about building custom AI agents with Claude Code. You will learn how these agents work under the hood, how to create your first custom agent, and how to deploy multiple agents for tasks like code review, security scanning, and documentation generation. By the end, you will have three production-ready agents you can start using in your projects today.
What Are Claude Code Custom Agents?
Custom agents in Claude Code are essentially pre-configured AI assistants that live inside your project. Instead of typing the same long instructions every time you need a code review or a security audit, you define an agent once as a Markdown file, and Claude will invoke it automatically when the situation calls for it.
Each custom agent consists of two parts:
- YAML frontmatter: Configuration metadata such as the agent name, model preference, and tool permissions.
- Markdown body: The system prompt that defines the agent’s behavior, expertise, and output format.
When Claude determines that a task matches one of your custom agents, it spins up an independent context window, loads that agent’s system prompt, and lets the agent work in isolation. This means your main conversation stays clean, and the agent inherits your project’s CLAUDE.md rules without polluting the primary chat.
Prerequisites
Before we start building agents, make sure you have the following set up:
- Claude Code installed: You can install it via npm with
npm install -g @anthropic-ai/claude-code@latestor use the official install script. On macOS and Linux, runcurl -fsSL https://claude.ai/install.sh | bash. On Windows PowerShell, useirm https://claude.ai/install.ps1 | iex. - Node.js 18+: Claude Code requires a recent version of Node.js.
- A Claude API key or Anthropic subscription: You need authentication to interact with Claude models.
- A code project: Agents work best within a project directory that has a version-controlled codebase.
Step 1: Create the Agents Directory
Custom agents live in the .claude/agents/ directory inside your project. Create this directory if it does not already exist:
mkdir -p .claude/agents
This is where all your agent definition files will go. Each agent is a single .md file with a descriptive name.
Step 2: Build Your First Agent — A Code Reviewer
Let us start with the most common use case: a code review agent that examines your code for quality, bugs, and best practices. Create a file called .claude/agents/code-reviewer.md:
---
name: code-reviewer
description: Reviews code changes for quality, bugs, and best practices
model: sonnet
tools:
- Read
- Glob
- Grep
---
You are an expert code reviewer with 15 years of experience in software engineering.
## Your Task
Review the code provided by the user and produce a structured review report.
## Review Checklist
1. **Correctness**: Are there any logic errors, off-by-one bugs, or race conditions?
2. **Performance**: Are there any obvious performance bottlenecks or unnecessary computations?
3. **Security**: Check for common vulnerabilities (XSS, SQL injection, hardcoded secrets, unsafe deserialization).
4. **Readability**: Is the code well-structured, properly named, and easy to understand?
5. **Best Practices**: Does the code follow language-specific conventions and design patterns?
## Output Format
Provide your review in this structure:
- Critical Issues (must fix before merging)
- Suggestions (recommended improvements)
- Positive Notes (things done well)
- Overall Assessment: A brief summary with a recommendation (approve / request changes / needs discussion)
Let me break down the configuration:
name: The identifier Claude uses to reference this agent internally.description: Helps Claude understand when to invoke this agent based on user intent.model: sonnet: Uses Claude Sonnet for this task, which is faster and cheaper than Opus for review work.tools: We only give this agent read access (Read,Glob,Grep) — no write permissions, keeping your codebase safe.
To use it, simply tell Claude: “Use the code-reviewer agent to review the changes in src/api/auth.ts”. Claude will spin up the agent, let it analyze the file, and return a structured review report.
Step 3: Create a Security Scanner Agent
Next, let us build an agent focused specifically on security analysis. Create .claude/agents/security-scanner.md:
---
name: security-scanner
description: Scans code for security vulnerabilities and compliance issues
model: sonnet
tools:
- Read
- Glob
- Grep
---
You are a senior application security engineer specializing in static analysis.
## Your Mission
Perform a thorough security audit of the provided code or project.
## Scan Categories
1. **Injection Attacks**: SQL injection, command injection, LDAP injection, XPath injection
2. **Authentication and Authorization**: Weak passwords, missing auth checks, privilege escalation
3. **Data Exposure**: Sensitive data in logs, hardcoded API keys, PII leakage
4. **Input Validation**: Missing sanitization, buffer overflows, type confusion
5. **Dependency Risks**: Known vulnerable dependencies, outdated packages
6. **Configuration**: Debug mode in production, overly permissive CORS, missing security headers
## Report Format
- Critical Vulnerabilities (exploitable, immediate action required)
- Warnings (potential risks that should be addressed)
- Informational (best practice recommendations)
- Remediation Steps: Specific, actionable fixes for each finding
This agent is particularly useful before deploying to production or when onboarding new code from third-party sources. You can invoke it with: “Run the security-scanner agent on the payment module.”
Step 4: Build a Documentation Generator Agent
Documentation is one of those tasks developers love to skip. Let us automate it with a documentation generator agent. Create .claude/agents/doc-generator.md:
---
name: doc-generator
description: Generates comprehensive documentation from code
model: sonnet
tools:
- Read
- Glob
- Grep
- Write
---
You are a technical writer who specializes in developer documentation.
## Your Task
Analyze the provided code and generate clear, comprehensive documentation.
## Documentation Types
Based on the user's request, generate one or more of the following:
1. **README.md**: Project overview, installation, usage, API reference
2. **API Docs**: Endpoint descriptions, request/response schemas, examples
3. **Code Comments**: Inline documentation for functions, classes, and modules
4. **Architecture Docs**: System design, data flow diagrams (in Mermaid), component relationships
## Writing Guidelines
- Use clear, concise language
- Include practical code examples
- Organize content with logical heading hierarchy
- Add a table of contents for long documents
- Use Mermaid diagrams for visual explanations where appropriate
Note that this agent has Write tool access, which means it can actually create or update documentation files in your project. Use it with: “Use the doc-generator agent to write API documentation for the user service.”
Step 5: Advanced Configuration — Agent Teams
For more complex workflows, Claude Code supports Agent Teams, which allow multiple agents to collaborate on a single task. Enable this experimental feature by setting the environment variable:
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
Once enabled, you can ask Claude to orchestrate multiple agents simultaneously. For example: “Create a team of three agents — the code-reviewer, security-scanner, and doc-generator — to audit the entire src/ directory.” Each agent runs in its own context, and Claude synthesizes their individual outputs into a consolidated report.
You can also configure team settings in ~/.claude/settings.json:
{
"model": "opus",
"agentSettings": {
"teammateModel": "sonnet"
}
}
This configuration uses the powerful Opus model as the coordinator while delegating work to the faster and more cost-effective Sonnet model for individual agents.
Best Practices for Custom Agents
After building and using agents across multiple projects, here are the key practices I recommend:
- Keep agent prompts focused: Each agent should have a single, clear responsibility. Do not try to make one agent do everything.
- Use the right model for the job: Reserve Opus for tasks that require deep reasoning. Use Sonnet for review, scanning, and documentation — it is faster and significantly cheaper.
- Minimize tool permissions: Only grant write access when the agent truly needs to modify files. For analysis tasks, read-only tools are safer.
- Version your agent files: Since agents live in
.claude/agents/, you can commit them to git and track changes over time. This is especially useful for team projects. - Test agents incrementally: Start with a simple prompt, test it on real code, and refine based on the output quality before adding complexity.
Conclusion
Claude Code’s custom agent system represents a significant leap forward in AI-assisted development. By encapsulating specialized knowledge and workflows into reusable agent definitions, you can transform Claude from a general-purpose chatbot into a team of domain experts that work alongside you every day.
In this tutorial, we built three practical agents — a code reviewer, a security scanner, and a documentation generator — and explored how to orchestrate them with Agent Teams. The beauty of this approach is that it scales: as your project grows, you can add more specialized agents for testing, deployment, performance optimization, or any other workflow you find yourself repeating.
The key takeaway is that custom agents turn repetitive AI instructions into permanent, shareable tools. If you find yourself typing the same prompt variations over and over, that is a clear signal to create an agent. Start small, iterate on the prompts, and gradually build out a comprehensive agent toolkit tailored to your development workflow.
Ready to supercharge your coding workflow? Open your terminal, create your first agent file, and experience the difference that specialized AI agents can make in your daily development work.