Code Kit v5.0 released for CC's new Agent Teams feature.
Claude FastClaude Fast
Agents

Claude Code Custom Commands: Build Your Own AI Agents

Build custom Claude Code agents with slash commands, YAML agent definitions, and CLAUDE.md rules. Real examples, common mistakes, and when to use each approach.

Stop configuring. Start shipping.Everything you're reading about and more..
Agentic Orchestration Kit for Claude Code.

Problem: Claude Code's default capabilities don't match your specific workflow. You need a code reviewer that follows your team's standards, or a deployment specialist that knows your infrastructure.

Quick Win: Create your first custom slash command in under 2 minutes:

mkdir -p .claude/commands

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 invoke it with /project:code-review in Claude Code.

Understanding: Custom slash commands are reusable prompts that invoke Claude with specialized instructions. They act like expert consultants you can summon with a single command.

How Custom Commands Transform Your Workflow

Custom commands solve the "remembering the prompt" problem. Instead of typing out detailed instructions every time, you create reusable command files that encode your team's expertise.

Three Approaches to Custom Agents:

  1. Slash Commands (.claude/commands/): Invoke on-demand with /project:command-name
  2. Agent Definitions (.claude/agents/): Persistent sub-agent identities with YAML frontmatter that Claude's orchestrator spawns automatically
  3. CLAUDE.md Instructions: Always-active behaviors that shape every interaction

Commands vs. Agents: These serve different purposes. Slash commands are prompts you invoke manually for specific workflows. Agent definitions in .claude/agents/ configure persistent sub-agents that Claude's Task tool can spawn during orchestration. Think of commands as "tools you pick up" and agents as "team members always available."

Both support the same scoping model:

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

Project-scoped files are shareable via git. User-scoped files are personal to your machine and available across all projects.

Separation of Concerns: Like good software architecture, specialized commands perform better than general prompts. A security-focused command with specific checklists catches more issues than asking "review this code."

Creating Effective Custom Commands

Start Simple: Begin with one specific problem you face repeatedly.

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.

Invoke with /project:security-audit whenever you need a security review.

Dynamic Arguments: Commands can accept arguments using $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 behaviors you want active in every session, add them to 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

These instructions shape Claude's behavior automatically without needing to invoke a command.

Project vs User Commands:

  • .claude/commands/ - Shared with your team via git
  • ~/.claude/commands/ - Personal commands on your machine only

Persistent Sub-Agent Definitions with .claude/agents/

For sub-agents that Claude's orchestrator should be able to spawn automatically, use the .claude/agents/ directory. These are Markdown files with YAML frontmatter that define the agent's identity, capabilities, and instructions.

Unlike slash commands (which you invoke manually), agent definitions are available to Claude's Task tool during orchestration. When Claude determines it needs a specialist for a particular task, it can spawn a defined agent with the right context and constraints already configured.

YAML Frontmatter Syntax

Every agent file in .claude/agents/ starts with YAML frontmatter that controls how the agent behaves. Here's 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"
---

Below the frontmatter, write the agent's system instructions in plain Markdown, just like a slash command. The difference is that Claude's orchestrator reads these definitions and can spawn the agent without you invoking it manually.

A Real-World Agent Definition

Here's an agent I use for pre-commit quality gates:

---
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.

This agent gets spawned automatically when the orchestrator detects a validation task. Because the allowedTools list excludes Edit and Write, the agent literally cannot modify your codebase, only inspect it. That constraint is the whole point.

Agents defined here also inherit your project's CLAUDE.md instructions, so they automatically follow your coding standards and project conventions. For a reference implementation of this pattern at scale, the ClaudeFast Code Kit ships 18 agent definitions in .claude/agents/ with YAML frontmatter controlling allowed tools, model selection, and routing rules, useful as templates when designing your own specialist agents.

For a deeper look at how sub-agents work, including parallel execution, backgrounding with Ctrl+B, and invocation quality, see the agent fundamentals guide.

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

Custom agents look simple, but scoping them wrong leads to wasted tokens and unreliable results.

Mistake 1: Scope too broad. An agent with instructions like "review this codebase for all issues" will produce surface-level observations across every dimension. A focused agent that checks only for SQL injection, only in files that touch the database, finds real problems. Narrow the task, expand the depth.

Mistake 2: No output format constraint. Without specifying how to report results, agents return inconsistent formats every time. One run gives you a bulleted list, the next gives prose paragraphs. Add explicit output structure to your command: "For each finding, provide: file path, line number, severity, and a one-line fix."

Mistake 3: Giving write access to read-only agents. If an agent's job is to validate or review, restrict its allowedTools to Read, Grep, and Bash. The moment a review agent has Edit access, it starts "fixing" things during review, which defeats the purpose of having a separate validation step.

Mistake 4: Duplicating CLAUDE.md content in commands. Your CLAUDE.md instructions already load for every session. Repeating those rules inside individual commands wastes context tokens. Commands should add specificity, not repeat baseline behavior. If your CLAUDE.md says "use parameterized queries," your database optimizer command doesn't need to say it again.

When to Use Each Approach

Choosing between slash commands, agent definitions, skills, and CLAUDE.md rules depends on the trigger and persistence you need:

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 dividing line: if you've typed the same detailed prompt three or more times, it belongs in a slash command. If the orchestrator should invoke it without you asking, it belongs in .claude/agents/. Everything else is either CLAUDE.md (universal behavior) or a skill (domain knowledge that loads on demand). For more on how skills work, see the skills guide.

Prompting for Specialized Roles

Sometimes you don't need a saved command. Just prompt Claude directly:

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

This works well for one-off tasks. Save it as a command when you find yourself repeating it.

Next Actions

Ready to build your specialist commands? Start with your biggest pain point:

Your custom commands become more valuable as you refine them. Commit them to git, share with your team, and build a library that encodes your collective expertise.

Last updated on

On this page

Stop configuring. Start shipping.Everything you're reading about and more..
Agentic Orchestration Kit for Claude Code.