- Agents
- Create Subagent
Why create a custom agent?
Built-in agents cover the most common use cases, but every team has its own workflows, conventions, and processes. A custom agent lets you codify those specifics and make them reusable.
Structure of an agent
An agent is defined by a Markdown file in the .claude/agents/ folder (project level) or ~/.claude/agents/ (global level). Each file contains the following sections.
Full anatomy
# Agent name## RoleDescription of the agent's role and expertise.What the agent should and shouldn't do.## Available toolsList of tools the agent can use:- Read (file reading)- Edit (file modification)- Bash (command execution)- Grep (code search)- Glob (pattern-based file search)## InstructionsSpecific steps the agent must follow.1. First step2. Second step3. ...## Output formatHow the agent should structure its report or result.## ConstraintsWhat the agent must never do.
Complete frontmatter reference
The real starting point of an agent is its frontmatter: the YAML block at the top of the file that configures behavior before the first line of the prompt. Here are the 16 available fields.
| Field | Type | Description |
|---|---|---|
name | string | Agent name, used to invoke it |
description | string | Description Claude reads to decide whether to use this agent automatically. Adding "PROACTIVELY" encourages auto-invocation. |
tools | string[] | Allowed tools: Read, Write, Edit, Bash, Glob, Grep, Agent, etc. |
disallowedTools | string[] | Explicitly forbidden tools, even if the agent would try to use them |
model | string | Model to use: "haiku", "sonnet", "opus" or a full model ID |
permissionMode | string | Permission level: "default", "acceptEdits", "bypassPermissions", "auto" |
maxTurns | number | Maximum number of agentic turns before forced stop |
skills | string[] | Skills to preload into the agent's context |
mcpServers | string[] | MCP servers available to this agent |
hooks | object | Agent-specific hooks (pre/post-execution) |
memory | string | Memory type: "user", "project", "local" |
background | boolean | true to run the agent in the background |
effort | string | Cognitive effort level: "low", "medium", "high" |
isolation | string | "worktree" for an isolated Git environment |
initialPrompt | string | Additional system prompt injected before the instructions |
color | string | Display color in the statusline (hex or name) |
The PROACTIVELY keyword
The description field serves two purposes: documenting the agent for humans, and telling Claude when to use it automatically. Adding "PROACTIVELY" to the description signals that Claude should invoke this agent on its own, without waiting for an explicit instruction.
# The agent waits to be askeddescription: "Performs a code review after modifications."# The agent activates automaticallydescription: "Expert code reviewer. Use PROACTIVELY after writing or modifying code."
Choosing the right model for each agent
The model field is one of the most impactful settings: it directly affects speed, quality, and cost for every execution.
| Agent type | Recommended model | Why |
|---|---|---|
| Exploration, grep, file reading | haiku | Fast, minimal cost for simple tasks |
| Code review, everyday development | sonnet | Good quality/speed balance for most cases |
| Architecture, complex debugging, security | opus | Deep reasoning when it matters |
A well-designed pipeline uses haiku to explore, sonnet to code, and opus only for critical decisions.
Example agent with full frontmatter
---name: code-reviewerdescription: "Expert code reviewer. Use PROACTIVELY after writing or modifying code."model: opustools: [Read, Grep, Glob, Bash]disallowedTools: [Write, Edit]permissionMode: defaultmaxTurns: 20memory: projecteffort: highisolation: worktreeskills: [code-quality, security-scan]color: "#f59e0b"---You are a senior code reviewer. For each review, you analyze the quality,security, and maintainability of changes. You propose concrete fixes,ranked by severity.
Advanced fields in detail
A few fields deserve a deeper explanation because they radically change the agent's behavior.
effort: tuning reasoning
The effort field controls how many "thinking" tokens the agent can spend before acting.
| Value | Max thinking tokens | When to use |
|---|---|---|
low | ~500 | Mechanical tasks (lint, format, lookup) |
medium | ~5000 (default) | Day-to-day dev, light code review |
high | ~20000 | Architecture, complex debugging, security audit |
An effort: high agent costs more but avoids mistakes on critical calls. A low agent is nearly free but only fits unambiguous tasks.
background: non-blocking execution
With background: true, the agent runs without blocking the main session. You keep the prompt to do something else. You recover its output via /tasks when it's done.
---name: long-researchdescription: "Full tech-debt audit across 200 files."background: trueisolation: worktreemaxTurns: 200---
Combine with isolation: worktree to avoid conflicts if you're editing the same repo in parallel.
initialPrompt: injecting stable context
initialPrompt is concatenated before the user prompt on every invocation. Ideal to restate immutable conventions without repeating them on every call.
---name: react-component-builderdescription: "Creates a React component compliant with the design system."initialPrompt: |Design system conventions:- All components are function components with hooks- No default exports- Tailwind utility-first, never custom CSS- Vitest tests co-located as .test.tsx---
The advantage over putting these conventions in the main prompt: initialPrompt sits at the top of the agent context, so it's less likely to be ignored when the main prompt grows long.
hooks: agent-specific hooks
You can attach hooks to the agent's lifecycle, in addition to global hooks. Handy to log what one specific agent does without polluting other agents' logs.
---name: db-migration-agentdescription: "Applies Prisma migrations."hooks:PreToolUse:- matcher: Bashcommand: "echo '[db-migration] $(date)' >> /tmp/db-migrations.log"Stop:- command: "bash ~/.claude/hooks/notify-team.sh"---
These hooks only apply to invocations of this agent. Other agents and the main session are unaffected.
Example 1: Code review agent
This agent performs an in-depth code review focused on quality and conventions.
# Code Reviewer## RoleYou are a senior code reviewer with 15 years of experience.You analyze modified code with rigor and constructive feedback.You don't just flag problems, you propose concrete fixes.## Available tools- Bash (for git diff, git log)- Read (to read modified files and their context)- Grep (to search for problematic patterns)## Instructions1. Get the diff with `git diff main...HEAD`2. For each modified file:a. Read the full file (not just the diff)b. Check consistency with the project stylec. Look for potential bugsd. Check error handlinge. Check for hardcoded secrets3. Verify that tests exist for new code paths4. Produce the structured report## Output formatFor each issue found:- **File**: path/to/file.ts:line- **Severity**: CRITICAL | HIGH | MEDIUM | LOW- **Issue**: clear description of the problem- **Fix**: proposed corrected codeEnd with a summary: total number of issues by severity.## Constraints- NEVER modify code directly- Don't flag style issues already covered by the linter- Limit yourself to 20 issues maximum (prioritize the most critical)
Example 2: Testing agent
An agent specialized in writing unit and integration tests.
# Test Writer## RoleYou are a testing expert who writes exhaustive, readable,and maintainable tests. You follow the AAA pattern(Arrange-Act-Assert) and cover edge cases.## Available tools- Read (to read the source code to test)- Write (to create test files)- Bash (to run tests and check coverage)- Grep (to find existing tests)## Instructions1. Read the source file to test2. Identify all public functions3. For each function, list the test cases:- Nominal case (happy path)- Edge cases- Error paths- Cases with null/undefined values4. Write the tests following the AAA pattern5. Run the tests to verify they pass6. Check coverage (target: 80%+)## Output formatCreate the test file next to the source file:- `module.ts` → `module.test.ts`- `module.tsx` → `module.test.tsx`## Constraints- Don't use mocks unless absolutely necessary- Each test must be independent (no execution order)- Descriptive test names- Maximum 50 lines per test
Example 3: Documentation agent
An agent that generates and updates technical documentation.
# Doc Updater## RoleYou are a technical writer who produces clear, concise,and up-to-date documentation. You write for intermediate-leveldevelopers.## Available tools- Read (to read source code)- Edit (to update documentation files)- Glob (to find existing .md files)- Bash (to check project structure)## Instructions1. Analyze recent changes (git log --oneline -20)2. Identify impacted documentation files3. For each file to update:a. Read the corresponding source codeb. Verify the documentation reflects the current codec. Update obsolete sectionsd. Add undocumented new features4. Check internal links (no broken links)## Constraints- Keep the project's tone (check CLAUDE.md)- Don't invent features- Always include a working code example- Use standard Markdown format
Where to place agent files
Project agents (shared with the team)
Place them in .claude/agents/ at the root of your project. They will be version-controlled with Git and available to all team members.
my-project/.claude/agents/code-reviewer.mdtest-writer.mddoc-updater.mddb-migration.md
Personal agents (your preferences)
Place them in ~/.claude/agents/ in your home directory. They will be available in all your projects but not shared with the team.
~/.claude/agents/my-review-style.mdmy-test-preferences.mdbrainstorm-helper.md
Agents via CLAUDE.md (integrated into context)
You can also reference agents directly in your CLAUDE.md by describing when to use them.
# CLAUDE.md## Available agents- Use the **code-reviewer** agent after each modification- Use the **tdd-guide** agent for new features- Use the **security-reviewer** agent before each commit
Best practices for agent prompts
An agent's effectiveness depends directly on the quality of its prompt. Here are the fundamental principles.
1. Be specific about the role
# BADYou are a code review agent.# GOODYou are a senior code reviewer specialized in TypeScriptand React. You have 15 years of experience and pay particularattention to performance, security, and accessibility issues.You give constructive feedback with concrete fix suggestions.
2. Define clear steps
# BADAnalyze the code and tell me if it's good.# GOOD1. Read the full diff with git diff main...HEAD2. For each modified file, check:a. Error handling (try/catch, input validation)b. Performance issues (nested loops, N+1 queries)c. Security flaws (injection, XSS, hardcoded secrets)3. Check test coverage4. Produce a structured report by severity
3. Specify the output format
# BADGive me the results.# GOODFor each issue, provide:- **File**: path:line- **Severity**: CRITICAL / HIGH / MEDIUM / LOW- **Issue**: one-sentence description- **Suggestion**: corrected code in a code blockEnd with a summary table.
4. Define constraints (the "nevers")
## Constraints- NEVER modify code directly (review only)- Don't flag more than 15 issues (prioritize)- Ignore formatting issues (handled by Prettier)- Don't comment on architecture choices unless critical- Always respond in English
Advanced sub-agent patterns
Beyond simple agents, several patterns let you solve complex problems by combining sub-agents in structured ways.
Fan-out/fan-in pattern
Fan-out/fan-in launches multiple sub-agents in parallel on independent sub-tasks, then a synthesizer agent gathers the results.
# Fan-out/Fan-in: Multi-perspective review## Fan-out phase (parallel)Orchestrator agent prompt:> Launch 3 sub-agents in parallel:> 1. Quality agent: analyzes readability and patterns> 2. Security agent: looks for vulnerabilities> 3. Performance agent: identifies bottlenecks## Fan-in phase (synthesis)> Consolidate the 3 reports into a single document.> Deduplicate issues flagged by multiple agents.> Sort by descending severity.
This pattern is ideal for code reviews, audits, and multi-criteria analyses. The total time is that of the slowest agent (not the sum).
Pipeline pattern
The pipeline passes each agent's result to the next, like an assembly line.
# Pipeline: Complete featureAgent 1 (planner) → produces a planAgent 2 (coder) → implements according to the planAgent 3 (tester) → writes and runs testsAgent 4 (reviewer) → validates everythingEach agent receives the previous one's result as context.
# In practice, you phrase the request like this:> Implement the "PDF export" feature following this pipeline:> 1. First, plan the architecture with the planner agent> 2. Then, implement with the tdd-guide agent (tests first)> 3. Finally, do a review with the code-reviewer agent> Each step uses the result of the previous one.
Reviewer chain pattern
Multiple agents review the same work sequentially, each focusing on a different aspect. Each reviewer has access to the previous reviewers' comments.
# Reviewer Chain: 3 review passes## Pass 1: CorrectnessThe agent verifies the code does what it's supposed to do.Result: list of potential bugs.## Pass 2: Security (sees Pass 1 results)The agent checks for vulnerabilities, taking already-flagged bugs into account.Result: list of vulnerabilities.## Pass 3: Maintainability (sees Pass 1 + Pass 2)The agent evaluates the long-term quality of the code.Result: refactoring suggestions.## Final synthesisA final agent produces the consolidated report with priorities.
Context management between agents
Context (available information) is not automatically shared between agents. You need to choose an explicit strategy.
File strategy (recommended for large results)
Agent A writes its result to a file. Agent B reads it at the start of its mission.
# Agent A: Review> Do a review of the auth module.> Write the result to /tmp/review-auth.md# Agent B: Fix> Read the file /tmp/review-auth.md and fix> the issues by descending severity.
Prompt strategy (recommended for short results)
The orchestrator agent summarizes Agent A's result and includes it in Agent B's prompt.
# The orchestrator passes a concise summary> The review agent found 3 issues:> 1. CRITICAL: SQL injection in users.ts:42> 2. HIGH: no rate limiting on /api/login> 3. MEDIUM: unused variable in utils.ts:15>> Fix these 3 issues in priority order.
Git strategy (recommended for code changes)
Agent A commits its changes. Agent B works on the same branch and sees the modifications.
# Agent A modifies code and commits# Agent B sees the changes via git diff# No need to pass context explicitly
Parallelism strategies
Sub-agents can run in parallel to speed up workflows. Here are the rules to follow.
When to parallelize
- Tasks are independent (no data dependency)
- Agents work on different files
- One agent's result doesn't influence the others
When to stay sequential
- An agent needs the previous one's result
- Agents modify the same files
- Execution order changes the result
# GOOD: parallel (independent tasks)> Launch in parallel:> - Agent security: audit the auth module> - Agent tests: check the billing module coverage> - Agent docs: update the README# BAD: parallel on the same files> Launch in parallel:> - Agent A: refactor auth.ts> - Agent B: add tests in auth.ts# → Guaranteed conflict!
Testing your agent
Once your agent is created, test it on a real scenario.
# Launch Claude Code in your project$ claude# Explicitly request your agent> Use the code-reviewer agent to analyze my latest changes# Or integrate it into a larger workflow> Do a complete review of my PR with the code-reviewer> then check the tests with the test-writer
Iterate on your agents
A good agent is rarely perfect on the first try. Use it several times, observe the results, and adjust the instructions. Add constraints when the agent goes off track, and clarify steps when it skips some. Like with a real team member, communication improves over time.
Next steps
Now that you know how to create custom agents, learn how to make them collaborate.
- Agent Teams: Making multiple agents work together on the same project
- Top agents by use case: The best agents by category
- Advanced orchestration: Multi-agent orchestration patterns