Build This Now
Build This Now
What Is Claude Code?Claude Code InstallationClaude Code Native InstallerYour First Claude Code Project
Agent FundamentalsBackground Agents in Claude CodeSub-Agent RoutingSub-Agent Design in Claude CodeClaude Code Task DistributionBuilder-Validator Agent TeamsClaude Code Agent TeamsAgent Teams ControlsAgent Teams Prompt TemplatesAgent Teams Best PracticesAgent Teams WorkflowCustom AgentsAgent PatternsHuman-like Agents
Get Build This Now
speedy_devvkoen_salo
Blog/Handbook/Agents/Custom Agents

Custom Agents

Define your own Claude Code specialists with slash commands, .claude/agents/ YAML, and CLAUDE.md rules. Real examples and the mistakes to skip.

Problem: The out-of-the-box Claude Code behaviour doesn't line up with how your team actually works. Maybe you want a reviewer that knows the house style. Or a deploy specialist wired into your infrastructure.

Quick Win: Standing up your first slash command takes less than two minutes. Begin with this:

mkdir -p .claude/commands

Then create .claude/commands/code-review.md:

Review the recent code changes for quality and security:
 
1. Run git diff to see recent changes
2. Focus on modified files only
 
Review checklist:
 
- Code is readable and well-named
- No duplicated logic
- Proper error handling exists
- No exposed secrets or credentials
- Performance considerations addressed
 
Provide feedback by priority: Critical → Warnings → Suggestions

Then call it with /project:code-review inside Claude Code.

How Custom Commands Change Your Workflow

Understanding: A custom slash command is a saved, reusable prompt. Call it, Claude reads the instructions inside, and your specialist is on the job. Expert consultants, one keystroke away.

They also solve the "what was that prompt again" problem. Rather than retyping long instructions every session, you park them in a file. The file carries your team's accumulated expertise.

Three routes to a custom agent:

  1. Slash Commands (.claude/commands/): Fire manually with /project:command-name
  2. Agent Definitions (.claude/agents/): YAML-defined sub-agent roles that stay on call and spawn on their own during orchestration
  3. CLAUDE.md Instructions: Always-loaded behaviours that shape every turn of the conversation

Commands vs. Agents: The two solve different jobs. A slash command is a saved prompt you fire on demand for a known workflow. An .claude/agents/ entry stands up a persistent sub-agent that the Task tool can bring in on its own. Commands feel like tools sitting on a workbench. Agent files feel like teammates who are already clocked in.

Both share the same scoping model:

ScopeCommandsAgents
Project.claude/commands/.claude/agents/
User~/.claude/commands/~/.claude/agents/

Anything under the project path gets committed to git and shared with the whole team. The user path stays on your laptop and follows you from repo to repo.

Separation of Concerns: The same principle that makes small modules beat sprawling ones applies to prompts. A command wrapped around a single security checklist catches more issues than a general "review this code" ever will.

Creating Effective Custom Commands

Start Simple: Find the one problem that keeps showing up on your plate. Write the command for that.

Create .claude/commands/security-audit.md:

You are a security expert. Scan this codebase for vulnerabilities.
 
Check for:
 
- SQL injection vulnerabilities
- XSS attack vectors
- Authentication bypass issues
- Exposed API keys or secrets
- OWASP Top 10 violations
 
For each finding, provide:
 
1. Vulnerability description
2. Risk level (Critical/High/Medium/Low)
3. Specific fix recommendation
4. Code example of the fix
 
Start by searching for common vulnerability patterns in the codebase.

Run /project:security-audit any time you want a security sweep.

Dynamic Arguments: A command can read arguments through $ARGUMENTS:

Create .claude/commands/review-file.md:

Review this specific file for issues: $ARGUMENTS
 
Focus on: code quality, potential bugs, security concerns.

Invoke with /project:review-file src/auth/login.ts.

CLAUDE.md: Always-Active Agent Behavior

For rules you want live in every session, drop them into your project's CLAUDE.md:

## Code Review Standards
 
When reviewing code, always check:
 
- All functions have error handling
- No console.log statements in production code
- API endpoints validate input parameters
- Database queries use parameterized statements
 
## Commit Message Format
 
Use conventional commits: type(scope): description
Types: feat, fix, docs, refactor, test, chore

Nothing to invoke. Claude pulls CLAUDE.md in when the session starts and applies the rules to every turn after that.

Project vs User Commands:

  • .claude/commands/ - Checked into git for the whole team
  • ~/.claude/commands/ - Private to your machine only

Persistent Sub-Agent Definitions with .claude/agents/

Sub-agents the orchestrator should spawn on its own live under .claude/agents/. Each file is Markdown with a YAML block on top. Identity, capabilities, and instructions all sit in that block.

Unlike a slash command, which waits for a keystroke, these definitions stay on standby. The Task tool sees them during orchestration. The moment Claude decides a task wants a specialist, it spawns the right one with its context and constraints already wired up.

YAML Frontmatter Syntax

Every file under .claude/agents/ starts with a YAML header that tells Claude how the agent should behave. The field reference:

---
# Required
name: "security-auditor" # Agent identity (used in Task invocations)
 
# Optional
model: "claude-sonnet-4-5" # Override the default model
allowedTools: # Restrict which tools this agent can use
  - Read
  - Grep
  - Bash
description: "Scans code for vulnerabilities and OWASP violations"
---

Everything below the YAML block is plain Markdown, holding the system prompt the agent runs with. Structurally, it looks the same as a slash command. The real gap is that the orchestrator can see this file on its own and spawn the agent without any manual invocation.

An Example From Practice

Here's a concrete agent, built around pre-commit quality gates. The file goes at .claude/agents/quality-engineer:

---
name: "quality-engineer"
allowedTools: ["Read", "Grep", "Bash"]
description: "Validates code against project standards before commits"
---
 
You are a quality engineer. Your job is to validate, never to modify.
 
## Validation Protocol
 
1. Read the files that changed (use git diff --name-only)
2. For each file, check:
   - Imports resolve correctly (grep for the import targets)
   - No console.log/print statements left in production code
   - Functions under 50 lines
   - All exported functions have JSDoc or docstring
3. Run the test suite: `npm test -- --bail`
4. Report pass/fail with specific line numbers for failures
 
Never edit files. Never suggest fixes. Only report what you find.

When the orchestrator spots a validation task, this definition gets picked up on its own. Because allowedTools leaves out Edit and Write, the agent physically cannot touch your codebase. Inspection is the only move it has. That limit is the entire reason the pattern holds.

Files in this folder also pick up your CLAUDE.md on the way in, so project conventions and coding standards come along without any extra plumbing.

For more on how sub-agents behave, including parallel runs, backgrounding via Ctrl+B, and invocation quality, the agent fundamentals guide goes deeper.

Common Command Examples

Database Optimizer (.claude/commands/db-optimize.md):

You are a database performance expert.
 
Analyze the database queries in this codebase:
 
1. Find slow or inefficient queries
2. Check for missing indexes
3. Review schema design
 
For each issue, provide:
 
- The problematic query or schema
- Why it's a problem
- Optimized version with explanation

Documentation Writer (.claude/commands/write-docs.md):

Write documentation for: $ARGUMENTS
 
Include:
 
- Purpose and overview
- Setup instructions
- Usage examples
- Common troubleshooting
 
Target audience: developers new to this project.
Write in clear, concise language.

Common Mistakes When Building Custom Agents

On the surface, a custom agent looks like nothing. Scope one badly and the cost is wasted tokens and flaky results.

Mistake 1: Scope too broad. An agent told to scan "this codebase for all issues" hands back thin observations spread over everything at once. Point that same agent at SQL injection, restrict it to database-adjacent files, and it'll surface actual bugs. Tighten the scope. Deepen the dig.

Mistake 2: Loose output format. Leave the report shape open and it drifts run to run. One pass gives you bullets. The next gives prose. Nail it down with something unambiguous like: For each finding, provide: file path, line number, severity, and a one-line fix.

Mistake 3: Write access on a reviewer. When the agent's job is inspection, pin its allowedTools down to Read, Grep, and Bash. The second you hand a reviewer Edit, it drifts into fixing code instead of reporting on it. That erases the reason the validator was separate in the first place.

Mistake 4: Repeating CLAUDE.md rules inside commands. CLAUDE.md has already been loaded by the time a command runs. Restating those rules in every command file just eats context tokens. A command should narrow behaviour, not restate the universal baseline. If "use parameterized queries" sits in CLAUDE.md, your database command doesn't need that line too.

When to Use Each Approach

Picking among slash commands, agent files, skills, and CLAUDE.md comes down to two things. What triggers the behaviour, and how long it should stick around.

ScenarioBest ApproachWhy
You run the same review workflow 3x/weekSlash commandManual trigger, reusable, shareable via git
Claude should auto-spawn a specialist during orchestration.claude/agents/ definitionAutomatic trigger, persistent identity
You want every session to follow certain rulesCLAUDE.mdAlways loaded, no manual invocation
You have a complex domain workflow (payments, deploys)SkillLoads on demand, keeps context lean
You need a quick one-off perspectiveDirect promptingNo setup, immediate, disposable

The practical line runs like this. Any detailed prompt you've typed three times deserves to be saved as a slash command. Any specialist the orchestrator should invoke on its own belongs under .claude/agents/. Everything else lands in CLAUDE.md as universal behaviour, or in a skill for domain knowledge that loads lazily. The skills guide covers that last route in full.

Prompting for Specialized Roles

You don't always need a saved file. Sometimes a direct prompt is enough:

Act as a senior security engineer. Review the authentication
flow in src/auth/ for vulnerabilities. Be thorough and paranoid.

Good enough for a one-off. The moment you notice you've typed it twice, lift it out into a saved command.

Next Actions

Time to build your first specialist. Pick whichever pain point is loudest today:

  • Code Quality: Turn your house rules into a reviewer command, lifting from the agent fundamentals guide
  • Security Focus: Write a vulnerability scanner grounded in the sub-agent design notes
  • Team Workflow: Lay out a collaboration pattern using the task distribution playbook

Saved commands compound in value the longer you live with them. Push them to the repo. Pass them around the team. Grow a library that captures the way your group actually ships code.

More in this guide

  • Agent Fundamentals
    Five ways to build specialized agents in Claude Code, from sub-agents to .claude/agents/ definitions to perspective prompts.
  • Agent Patterns
    Orchestrator, fan-out, validation chain, specialist routing, progressive refinement, and watchdog. Six ways to wire sub-agents in Claude Code.
  • Agent Teams Best Practices
    Battle-tested patterns for Claude Code agent teams. Troubleshooting, limitations, plan mode quirks, and fixes shipped from v2.1.33 through v2.1.45.
  • Agent Teams Controls
    Stop your agent team lead from grabbing implementation work. Configure delegate mode, plan approval, hooks, and CLAUDE.md for teams.
  • Agent Teams Prompt Templates
    Ten tested Agent Teams prompts for Claude Code. Code review, debugging, feature builds, architecture calls, and campaign research. Paste and go.

Stop configuring. Start building.

SaaS builder templates with AI orchestration.

Get Build This Now

Agent Teams Workflow

The full Claude Code agent teams workflow. Structured planning, contract chains, and wave execution that ships production code from parallel agents.

Agent Patterns

Orchestrator, fan-out, validation chain, specialist routing, progressive refinement, and watchdog. Six ways to wire sub-agents in Claude Code.

On this page

How Custom Commands Change Your Workflow
Creating Effective Custom Commands
CLAUDE.md: Always-Active Agent Behavior
Persistent Sub-Agent Definitions with .claude/agents/
YAML Frontmatter Syntax
An Example From Practice
Common Command Examples
Common Mistakes When Building Custom Agents
When to Use Each Approach
Prompting for Specialized Roles
Next Actions

Stop configuring. Start building.

SaaS builder templates with AI orchestration.

Get Build This Now