All Articles Claude Code

Creating Custom Agents in .claude/agents/

You're working on a complex project where standard Claude responses just don't cut it anymore.

You’re working on a complex project where standard Claude responses just don’t cut it anymore. You need specialized expertise—a data validation specialist, a documentation reviewer, a code architecture advisor. Sure, you could prompt-engineer your way through it, but that gets messy fast. What if you could create purpose-built agents that live in your codebase, version-controlled alongside your code, ready to be summoned whenever you need them?

Welcome to custom agents in Claude Code.

This is one of the most powerful—and underutilized—features in the Claude Code ecosystem. Instead of wrestling with long prompts or maintaining external agent configurations, you can define specialized agents directly in .claude/agents/ as markdown files. These agents have their own instructions, tool access, and model choices. They integrate seamlessly with your main session and team workflows. And they’re just plain markdown files in git, which means your agents evolve with your project.

In this article, we’ll walk through everything: why you’d want custom agents, how the directory structure works, how to write agent markdown files with the right frontmatter format, how to register and invoke them, and the patterns that make agent teams actually work. We’ll also dive into the operational details—how to test agents before deploying them, how to manage agent versioning, and how to build escalation chains that route work intelligently. By the end, you’ll have the knowledge to build a squad of specialized agents that supercharge your Claude Code workflows.

Let’s dive in.

Why Custom Agents? The Problem They Solve

Here’s the friction point: standard Claude responses are one-size-fits-all. You give Claude a task, Claude handles it with its baseline reasoning. That works great for general questions, but breaks down when you need consistent, specialized behavior across your team and project.

The core problem is knowledge fragmentation. Your team’s expertise—what constitutes good architecture in your domain, what patterns you’ve standardized on, what constraints you operate under—lives in people’s heads, old Slack conversations, scattered documentation, and code comments. When you ask Claude a question, it has none of that context. So it gives generic advice that might be technically correct but doesn’t fit your project’s reality. A human senior engineer would know better. A custom agent, built with your team’s accumulated expertise baked into its instructions, knows better too.

Imagine you’re building a codebase with strict architectural rules. You want Claude to:

  • Always verify that imports follow a specific pattern
  • Flag architectural violations immediately
  • Suggest refactors in terms of your specific domain
  • Use certain technical vocabulary
  • Skip over irrelevant files
  • Apply your specific linting rules
  • Catch dependency cycles before they ship

If you do this with a single session, you’ll repeat the same context setup in every prompt. “Remember the architectural rules… remember the domain vocabulary… remember that we use Repository pattern, not DAOs…” It’s repetitive and error-prone. And when a team member doesn’t know all the context, they produce inconsistent results.

Custom agents solve this by packaging expertise into reusable, persistent units. You define the agent once. The instructions, tool access, and model choice stay locked in. Every time you invoke that agent, it brings the same specialized knowledge to bear. New team members don’t have to learn all the context—they just say “@code-architect, analyze this module” and get expert-level review every single time.

This matters at scale. When you have multiple team members, multiple projects, or complex workflows with many steps, custom agents eliminate friction. They’re the difference between “Claude, can you please review this architecture with these 17 rules in mind?” and “@code-architect, analyze this module.” The first takes explanation. The second just works.

There’s also a quality multiplier effect. As your team figures out better instructions for a particular domain, you update the agent once, and everyone benefits immediately. If one person discovers that checking for circular dependencies should happen before checking naming conventions (because a naming violation in circular code is irrelevant), you update the agent and everyone’s reviews get better.

The .claude/agents/ Directory: Where Agents Live

Let’s start with the simplest question: where do agents live?

Project-level agents live in .claude/agents/ at the root of your git repository:

your-project/
├── .claude/
│   ├── agents/                    ← Custom agents here
│   │   ├── code-architect.md
│   │   ├── data-validator.md
│   │   ├── security-reviewer.md
│   │   ├── doc-writer.md
│   │   ├── README.md              ← Agent documentation
│   │   └── AGENT-PATTERNS.md      ← Team guidelines
│   ├── commands/
│   ├── skills/
│   ├── hooks/
│   └── config.yaml
├── src/
├── tests/
└── README.md

User-level agents (personal, not project-specific) live in ~/.claude/agents/:

~/.claude/
├── agents/                        ← Your personal agents
│   ├── my-prompt-optimizer.md
│   ├── my-research-bot.md
│   └── README.md
├── commands/
└── skills/

The distinction matters: project-level agents are shared and version-controlled with your team. Everyone on the project has access, and changes are reviewed via git. When you improve an agent’s instructions, it’s a commit. When it breaks something, you can roll back. User-level agents are personal—they don’t sync to the repo, useful for your own workflows that don’t need to be shared with the team.

For this article, we’ll focus on project-level agents, since those are where teams unlock real power.

Each agent is a single markdown file. The filename (minus the .md extension) becomes the agent identifier. So code-architect.md becomes an agent you invoke as code-architect. Naming is critical: use lowercase, hyphens instead of underscores, and descriptive names that signal the agent’s specialty. Don’t call it agent-1.md or helper.md. Be specific.

Agent Markdown Format: Frontmatter + Instructions

Here’s the structure of a custom agent file:

---
name: Code Architect
description: Analyzes and validates codebase architecture, identifies violations, suggests refactors
model: sonnet
tools:
  - Glob
  - Grep
  - Read
  - Bash
---

# Code Architect Agent

You are a specialized code review agent focused on architectural integrity...

Let’s break this down.

Frontmatter: The Configuration Block

The frontmatter (YAML between --- markers) defines how the agent behaves:

---
name: Code Architect
description: Analyzes and validates codebase architecture
model: sonnet
tools:
  - Glob
  - Grep
  - Read
  - Bash
---

name: The human-readable name. Used in logs and display. No strict constraints; make it clear and professional.

description: A one-line summary of what the agent does. Keep it under 100 characters. This shows up when listing agents, so clarity is crucial. “Validates architecture” is clear. “Does stuff” is not.

model: Which Claude model to use. Options:

  • haiku — Fast, cheap, good for simple tasks, quick summaries, filtering
  • sonnet — Balanced, the sweet spot for most specialized agents, good reasoning
  • opus — Powerful, expensive, for complex reasoning and synthesis, final decisions

The model choice is both a cost and capability decision. If your agent does quick classification (yes/no, this violates rules or not), haiku is fine and saves money. If it needs to understand complex architectural relationships and suggest solutions, sonnet is right. Opus is for when you need the absolute best reasoning and cost doesn’t matter.

tools: A YAML list of tools this agent can use. Available tools include:

  • Bash — Execute commands (run tests, compile, lint)
  • Read — Read files
  • Write — Write/create files
  • Edit — Modify files
  • Glob — File pattern matching
  • Grep — Search file contents
  • WebSearch — Search the web
  • WebFetch — Fetch URLs
  • Plus domain-specific tools (GitHub API, databases, etc.)

If you don’t list a tool in tools, the agent can’t use it. This is a security and focus feature. You’re saying: “This agent is only allowed to do these things.” It prevents agents from going rogue, keeps them narrowly focused, and makes their capabilities transparent.

Here’s a critical insight: be conservative with tool access. A documentation writer probably doesn’t need Bash or Edit. A security reviewer definitely does (to run security scanners, modify test files). A code-architect might use Edit to suggest refactors inline. Match tools to the agent’s actual purpose. Never grant permissions “just in case.”

Instructions: The System Prompt

Everything after the frontmatter is free-form markdown that becomes the agent’s system instructions. This is where the magic happens.

The instructions section is your chance to encode expertise. You write detailed, specific guidance about how the agent should approach its domain. What does good architecture look like? What are the most common mistakes? What should the agent prioritize? What should it ignore? The more thoughtful your instructions, the better the agent performs.

Some best practices for writing agent instructions:

  1. Be explicit about role and scope — “You are X. You focus on Y. You ignore Z.”
  2. Include process steps — “When you review code: 1) … 2) … 3)”
  3. Define vocabulary — If your domain has specific terms, lock them in.
  4. Call out pitfalls — What mistakes do agents commonly make in this role?
  5. Specify output format — What should the final response look like?
  6. Give examples — Show what good output looks like (if possible in markdown)
  7. Document constraints — What is this agent NOT supposed to do?

The more specific your instructions, the more consistent the agent’s behavior. Vague instructions lead to variable results.

Creating Your First Agent: A Complete Example

Let’s build a real agent from scratch. We’re creating a data validation specialist who reviews CSV imports and data cleaning pipelines.

Create the file: .claude/agents/data-validator.md

This agent is responsible for checking that data pipelines are robust. It validates that CSVs are well-formed, that transformations handle edge cases, that schemas match reality, that errors are handled gracefully. It’s not a generic code reviewer—it’s specialized for data quality, with expertise in the specific pitfalls that data pipelines encounter.

When you create this agent and place it in your .claude/agents/ directory, you’re essentially encoding knowledge about your company’s data standards. What assumptions about data are acceptable? What edge cases must be handled? What’s the failure mode if something goes wrong? All of that gets baked into the agent.

Registering Agents: Making Them Available

Here’s the thing: once you create the markdown file in .claude/agents/, it’s automatically registered. You don’t need a manifest, a config file, or an initialization step. Claude Code scans .claude/agents/ at startup and makes all agents available.

But there’s a best practice: document your agents.

Create a file .claude/agents/README.md that lists all your project agents. This becomes a team reference: “Oh, there’s a data-validator agent? Let me check what it does and when to use it.”

Invoking Custom Agents: The Practical Side

Once your agents are in .claude/agents/, how do you use them?

There are several ways to invoke an agent. The most common is direct invocation within your chat or workflow. You might say something like “Please use the data-validator agent to check our CSV import logic in src/import.ts” and Claude Code detects the agent reference, loads the agent with its markdown instructions, and dispatches the task.

Many teams use mention syntax similar to Slack: @data-validator please validate the import pipeline in src/pipelines/ or @code-architect review the service layer structure. This is cleaner and creates clear audit trails of which agent did what.

Here’s where it gets powerful: agents can invoke other agents. Your code-architect agent finishes an architectural review and discovers security issues. It can delegate to the security-reviewer agent, ensuring security gets expert attention without leaving the workflow.

In team environments, you might have a dispatch agent that routes work to specialized agents. Architecture questions go to code-architect. Data validation questions go to data-validator. Security concerns go to security-reviewer. This creates a hub-and-spoke pattern where one agent orchestrates multiple specialists.

Practical Patterns: Building Agent Teams

Now let’s move from individual agents to teams. Real projects need multiple agents working together.

Pattern 1: The Review Pipeline — Create agents for different review phases. Code-quality catches obvious stuff. Architecture ensures structure is sound. Security checks for vulnerabilities. Performance looks for optimization opportunities. Chain them together and each agent has a specific lens.

Pattern 2: The Specialist Team — Build agents around domain roles. Frontend-specialist, backend-specialist, devops-specialist, documentation-specialist. When you have a feature request, you dispatch to relevant specialists.

Pattern 3: The Escalation Path — Start with a lightweight agent using haiku (fast, cheap), escalate to heavier ones. Quick-checker does an initial pass. Thorough-reviewer does detailed analysis. Expert-reviewer does complex reasoning. Most tasks finish at level one, complex ones get expert attention.

Pattern 4: The Domain Expert — One agent that gets very, very good at a specific domain. React Architecture Specialist knows hooks, state management, performance optimization, testing, modern patterns. When you have React questions, you get expert answers every time.

Version Control and Team Workflows

Custom agents are part of your codebase. They live in git alongside your code. This creates interesting workflows. You create an agent markdown file, test it on real problems, refine instructions based on results, commit with a meaningful message, review with your team, merge to main. Your agents improve just like your code does. Everyone on your team sees the same agents. When someone improves an agent, the improvement is shared immediately. This is powerful: if one person figures out better instructions for the data-validator agent, everyone benefits.

When committing agent changes, document what improved. This becomes a changelog of how your specialized AI expertise evolves.

Tool Access: The Security and Focus Layer

The tools field in frontmatter is more important than it seems. You’re explicitly saying which tools the agent can use. This is intentional and important. Best practices for tool assignment: Always include Read if you want the agent to analyze code. Include Grep for efficient searching. Include Bash only if the agent needs to execute commands. Restrict Edit to trusted agents. Very restrictively use Write, only for agents that generate content. Restrict WebSearch/WebFetch to agents that need external information.

This focus keeps the agent narrowly useful and prevents accidents.

Model Selection: Speed vs. Thinking

The model field matters for both speed and cost. Haiku is fast and cheap. Sonnet is balanced. Opus is slowest and most expensive. A common pattern uses haiku for quick passes, sonnet for detailed analysis, opus for complex reasoning. You could have quick-checker with haiku, code-architect with sonnet, and expert-reviewer with opus. Let the complexity and importance of the task drive the model choice.

The Agent Investment Decision: When It’s Worth It

Creating a good agent takes time. You’re writing detailed instructions, considering edge cases, choosing the right model, selecting appropriate tools. Is it worth it? When should you create an agent vs. just using Claude directly?

The math is simple: create an agent if the same task will be performed 20+ times by team members. If one person does it once, investing in an agent isn’t worth it. If the task is done daily by different people, an agent saves time and ensures consistency.

Real examples: Most teams that standardize on agents create 3-8 of them. One code-architect agent used dozens of times. One performance-analyzer used weekly. One data-validator used by the data team daily. But not dozens of agents—that’s too much maintenance. Quality over quantity. A few really good agents beat a dozen mediocre ones.

Before creating an agent, ask: “Will this be used regularly? Will different people need to do this? Is consistency important?” If yes to all three, build the agent. If no to any of them, maybe just improve your prompt to Claude instead.

Common Mistakes (And How to Avoid Them)

Mistake 1: Too Many Agents — Don’t create an agent for every task. You’ll end up with 50 agents nobody uses. Create agents for recurring, specialized tasks. If you find yourself repeating the same instructions to Claude multiple times per month, that’s a strong candidate for an agent.

Mistake 2: Vague Instructions — “You are a code reviewer. Review the code.” is useless. The agent has no idea what “good code” means to you. Be specific about what you’re reviewing, what patterns matter, what pitfalls to avoid.

Mistake 3: Giving Tools You Don’t Need — If your code-architect doesn’t need to run bash, don’t give it that tool. Whitelist only the tools the agent actually uses. Err on the side of restriction.

Mistake 4: Inconsistent Naming — Use lowercase-with-hyphens. Always. For every agent file.

Mistake 5: Not Testing Your Agent — Before committing, test the agent on realistic problems. Refine instructions based on real output. Then commit.

Testing Your Agents: A Practical Workflow

Create the agent file in .claude/agents/, run it on a known problem, check the output, refine instructions if needed, test on edge cases, test on team members’ real problems, get feedback, commit once you’re confident. This is the difference between agents that sit unused and agents that become team staples.

Building Your First Data Validator Agent

Let’s walk through creating one complete, production-grade agent from scratch. We’ll build the data-validator agent mentioned earlier.

Create .claude/agents/data-validator.md:

---
name: Data Validator Specialist
description: Validates data pipelines, CSV imports, schemas, and data transformation robustness
model: sonnet
tools:
  - Read
  - Grep
  - Bash
---

# Data Validator Agent

You are a specialized agent focused on data quality, pipeline robustness, and error handling in data transformations.

## Your Role

You review data pipelines for completeness and robustness. You validate that data processing handles edge cases, that schemas match reality, that transformations are reversible, and that failures fail gracefully.

## Review Process

When reviewing a data pipeline:

1. **Schema Validation**: Verify CSV column order, data types, required fields, constraints
2. **Edge Case Handling**: Check for null handling, empty strings, special characters, Unicode, encoding issues
3. **Transformation Correctness**: Validate business logic, numeric precision, date handling, timezone awareness
4. **Error Handling**: Verify failures fail fast with useful messages, not silently producing bad data
5. **Performance**: For large datasets, check for memory efficiency, streaming vs. loading
6. **Idempotency**: Can the pipeline run multiple times safely? Are retries safe?
7. **Logging and Observability**: Can you debug pipeline failures? Are there data quality metrics?

## Common Pitfalls to Flag

- Silent failures where bad data flows through instead of erroring
- Assumptions about data format that break with real data
- Float precision issues in financial calculations
- Date parsing that breaks with different locales
- Character encoding issues causing data corruption
- Memory issues when processing unexpectedly large datasets
- Race conditions in parallel data processing

## Output Format

Provide findings in this format:

**Critical Issues** (must fix before merge):
- Issue and why it matters
- Suggested fix with code example

**Important Issues** (should fix):
- Issue and impact
- Suggested improvement

**Nice-to-Have Improvements**:
- Enhancement opportunities

This agent is now available to your team. When someone says “@data-validator please check our import pipeline in src/import.ts,” the agent springs to life with all this specialized knowledge.

When to Create New Agents: Patterns That Work

You don’t need an agent for everything. Create agents for tasks where:

  1. Recurring specialization: You find yourself repeating the same instructions frequently
  2. Consistency matters: Different people doing the same task should get the same results
  3. Expertise encoding: You have domain knowledge worth baking in permanently
  4. Tool restriction: The task benefits from focused tool access
  5. Model selection: Different tasks benefit from different model choices (haiku for quick passes, sonnet for deep analysis)

Common candidates for agents:

  • Architecture reviewers: Deep code structure analysis
  • Security specialists: Vulnerability scanning and audit
  • Performance analysts: Bottleneck detection and optimization suggestions
  • Documentation reviewers: Checking docs for completeness and clarity
  • Test strategists: Determining what should be tested and how
  • Database designers: Schema reviews and optimization
  • API designers: REST/GraphQL design patterns and best practices
  • Configuration managers: Validating infrastructure configurations
  • Dependency auditors: Checking for security vulnerabilities in packages

Each of these is a role that would normally be a person. Encoding that expertise into an agent is powerful.


Agent Lifecycle: Creation to Retirement

Agents have a lifecycle. They’re created, refined, improved, possibly deprecated.

The First Month: Iteration and Refinement

When you first deploy an agent, it’s raw. You’re using it on real problems and discovering what works and what doesn’t. The instructions might be too vague. The model choice might be wrong. The tool set might be incomplete.

Iterate aggressively in the first month. Use the agent on diverse problems. Take notes on where it falls short. Update instructions based on what you learn. After a month of real usage, you’ll know if the agent is valuable and what improvements matter most.

Long-Term Evolution

Once an agent is established, it evolves more slowly. You update instructions based on team feedback. You refine based on observed usage patterns. You add tools if the agent frequently asks for access it doesn’t have.

Good agents become team infrastructure. They’re depended on. When you improve an agent, it impacts the entire team. This is why version control and documentation matter—when you change an agent, you’re making a team decision.

Deprecation and Sunset

Agents eventually become obsolete. Your architecture changes. Your team’s needs shift. An agent that was essential becomes unused. When an agent hasn’t been invoked in three months and nobody mentions it, it’s probably time to retire it. Archive the markdown file, document why it was retired, and move on.


Advanced: Agent Chains and Orchestration

Once you have multiple agents, interesting possibilities emerge. Agents can invoke other agents. A dispatcher agent can route work to specialists. Agents can form workflows.

The Dispatcher Pattern

Create a dispatcher agent that routes incoming work to appropriate specialists:

---
name: Work Dispatcher
description: Routes incoming tasks to appropriate specialist agents
model: haiku
tools:
  - Read
  - Grep
---

# Work Dispatcher Agent

You receive work requests and route them to appropriate specialist agents.

## Routing Rules

- Architecture questions → @code-architect
- Performance concerns → @performance-analyzer
- Security questions → @security-reviewer
- Testing strategy questions → @test-strategist
- Data pipeline questions → @data-validator
- Documentation issues → @doc-reviewer

When you receive a task:
1. Identify the category
2. Extract key information
3. Route to appropriate agent(s)
4. Summarize the delegation

The dispatcher becomes the entry point for your agent team. Work comes in, gets classified, and gets sent to specialists. This scales your team’s capacity without requiring everyone to know which agent handles what.

Workflow Agents

Create agents that orchestrate multi-step processes:

---
name: Feature Implementation Orchestrator
description: Guides feature implementation through all required quality gates
model: sonnet
tools:
  - Read
  - Edit
  - Bash
---

# Feature Implementation Orchestrator

You oversee feature implementations from design through deployment, ensuring quality at each stage.

## Implementation Stages

1. **Design Review** (delegate to @code-architect): Validate design before coding
2. **Implementation** (with your guidance): Implement with architecture in mind
3. **Testing** (delegate to @test-strategist): Ensure adequate test coverage
4. **Security Review** (delegate to @security-reviewer): Check for vulnerabilities
5. **Performance** (delegate to @performance-analyzer): Identify bottlenecks
6. **Documentation** (delegate to @doc-reviewer): Ensure docs are complete

This orchestrator guides developers through a complete workflow, ensuring nothing is skipped. It’s like having a technical lead reviewing every stage of development.


Agent Teams and Communication Patterns

As your agent ecosystem grows, think about how agents communicate and coordinate. This is where the real leverage emerges.

Hub-and-Spoke Orchestration

One central coordinator agent distributes work to specialists. This is simple and scales well for most teams.

Peer-to-Peer Agents

Agents can invoke each other peer-to-peer. Your code-architect might discover performance issues and directly invoke the performance-analyzer. Your security-reviewer might flag architectural concerns and invoke the code-architect. This is more flexible but requires careful design to avoid circular invocations.

Sequential Pipelines

For workflows with clear stages, agents work in sequence. Pre-checklist verification → Implementation guidance → Testing oversight → Deployment preparation. Each agent does its job, then passes to the next.


Measuring Agent Effectiveness

How do you know if an agent is actually valuable? It’s tempting to assume that because an agent exists, it’s useful. In practice, some agents add huge value, while others sit unused.

Usage Metrics

Track basic usage:
– How often is the agent invoked per week?
– How many different people use it?
– How long is the average session?

Agents that are used by multiple people multiple times per week are adding real value. Agents that are invoked once and never again might be solving a problem that only existed once.

Quality Metrics

When agents are used, do their outputs improve results?
– Do developers accept agent suggestions or reject them?
– Does agent advice actually get implemented?
– Does code reviewed by agents have fewer issues in later review rounds?

These metrics tell you if the agent’s suggestions are actually valuable or just noise.

Satisfaction Metrics

Simple question: “Does this agent help you?” Get feedback from regular users. Agents that get enthusiastic endorsement from 80%+ of users are keepers. Agents that get lukewarm feedback from everyone might not be worth maintaining.


Common Agent Mistakes (And How to Avoid Them)

Mistake 1: Too Many Tools
Agents with full access to all tools often produce unfocused output. Restrict tools to what the agent actually needs. A documentation reviewer doesn’t need Bash. A code architect doesn’t need Write access. Whitelist conservatively.

Mistake 2: Vague Instructions
“You are a code reviewer. Review code.” teaches the agent nothing about what good code looks like in your project. Specific instructions about patterns, pitfalls, and priorities make agents useful.

Mistake 3: Wrong Model Choice
Using Opus for every agent is expensive and slow. Using Haiku for complex analysis loses quality. Match model to task: Haiku for quick passes, Sonnet for detailed analysis, Opus for complex reasoning.

Mistake 4: Not Testing Before Deployment
Create the agent, test it on realistic problems, refine based on results, then commit. Deploying untested agents wastes team time.

Mistake 5: Forgetting Documentation
Create a .claude/agents/README.md that explains what each agent does and when to use it. Without documentation, people either don’t know agents exist or don’t know when to invoke them.


Conclusion: Building Your Agent Team

Custom agents in .claude/agents/ are one of the most underrated features in Claude Code. They transform how teams work with AI by providing consistency, efficiency, collaboration, version control, flexibility, scalability, and continuous evolution. You start simple with one agent that handles a recurring task. That agent eliminates friction. Then you add another. And another. Soon you have a team of specialized experts at your fingertips.

The journey from “I have Claude Code installed” to “I have a team of specialized agents working autonomously” is measured in weeks, not months. Each new agent adds value incrementally. Each improvement compounds. Before you know it, your team is fundamentally more productive because you’ve built institutional expertise into your tooling.

The real power emerges when agents work together. A dispatcher routes work. Specialists handle their domains. Orchestrators manage complex workflows. Your team moves faster because everyone has access to the expertise they need, when they need it, without having to explain context every time.

Now go build yours. Start with one. Make it good. Let it prove its value. Then add the next. Before you know it, you’ll have a team of AI agents that thinks the way your team thinks, knows what your team knows, and works at your team’s pace.

That’s the promise of custom agents. Build it incrementally, refine relentlessly, and watch your team’s velocity multiply.


-iNet

Free Discovery Call

Start With a Conversation, Not a Commitment

Every engagement begins with a free 30-minute discovery call. We'll map what's slowing your business down and tell you exactly what we'd fix first – no pitch deck, no obligation.