claude-code-agents
Use when creating custom Claude Code agents/subagents — frontmatter schema, built-in types, tools, permissions, memory, isolation, worktree support
| Model | Source |
|---|---|
| inherit | pack: claude-code-internals |
Tools: Read, Grep, Glob, WebFetch, WebSearch
Full Reference
Claude Code Agents
Section titled “Claude Code Agents”Announcement
Section titled “Announcement”┏━ 🔧 claude-code-agents ━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ your friendly armadillo is here to serve you ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
Reference for creating and configuring custom subagents in Claude Code. Covers all frontmatter fields, built-in types, permissions, memory, isolation, hooks, and agent teams.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Built-in Subagent Types
Section titled “Built-in Subagent Types”Claude Code ships with built-in subagents invoked automatically. You don’t create these — you override them or disable them.
| Agent | Model | Tools | Purpose |
|---|---|---|---|
| Explore | Haiku | Read-only | File discovery, code search, codebase exploration. Invoked with thoroughness: quick, medium, very thorough |
| Plan | Inherit | Read-only | Codebase research during plan mode. Prevents infinite nesting (subagents can’t spawn subagents) |
| general-purpose | Inherit | All | Complex multi-step tasks requiring both exploration and action |
| Bash | Inherit | Bash | Running terminal commands in a separate context |
| statusline-setup | Sonnet | — | Invoked by /statusline to configure the status line |
| Claude Code Guide | Haiku | — | Answers questions about Claude Code features |
Override a built-in by creating a subagent with the same name at a higher-priority location.
Disable a built-in via settings.json:
{ "permissions": { "deny": ["Agent(Explore)", "Agent(Plan)"] }}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Custom Agent Frontmatter Schema
Section titled “Custom Agent Frontmatter Schema”Subagent files are Markdown with YAML frontmatter. The body becomes the system prompt.
---name: my-agentdescription: When Claude should delegate to this agentmodel: sonnettools: Read, Grep, Glob, BashdisallowedTools: Write, EditpermissionMode: acceptEditsmaxTurns: 20skills: - api-conventions - error-handlingmemory: userisolation: worktreebackground: falsemcpServers: - slackhooks: PreToolUse: - matcher: "Bash" hooks: - type: command command: "./scripts/validate-command.sh"---
System prompt goes here. The agent receives only this prompt plusbasic env details (working directory, etc.) — NOT the full ClaudeCode system prompt and NOT the parent conversation history.All Frontmatter Fields
Section titled “All Frontmatter Fields”| Field | Required | Type | Default | Description |
|---|---|---|---|---|
name | Yes | string | — | Unique ID: lowercase letters and hyphens only |
description | Yes | string | — | When Claude should delegate — be specific, include “use proactively” to encourage automatic delegation |
model | No | enum | inherit | sonnet, opus, haiku, or inherit |
tools | No | list | all inherited | Allowlist of tools. Omit to inherit all tools including MCP |
disallowedTools | No | list | none | Denylist — removed from inherited or specified list |
permissionMode | No | enum | default | default, acceptEdits, dontAsk, bypassPermissions, plan |
maxTurns | No | integer | unlimited | Max agentic turns before the agent stops |
skills | No | list | none | Skills to inject into context at startup (full content, not invokable) |
memory | No | enum | none | user, project, or local — enables persistent cross-session memory |
isolation | No | enum | none | worktree — runs in a temporary git worktree, auto-cleaned if no changes |
background | No | boolean | false | Always run this agent as a background task |
mcpServers | No | list/object | none | MCP servers scoped to this agent — server name string or inline config object |
hooks | No | object | none | Lifecycle hooks scoped to this agent’s execution |
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
File Locations and Scope Precedence
Section titled “File Locations and Scope Precedence”When multiple agents share the same name, higher-priority location wins.
| Location | Scope | Priority | Creation |
|---|---|---|---|
--agents CLI flag | Current session only (not saved) | 1 (highest) | Pass JSON at launch |
.claude/agents/ | Current project | 2 | /agents command or manual |
~/.claude/agents/ | All projects on this machine | 3 | /agents command or manual |
Plugin agents/ dir | Where plugin is enabled | 4 (lowest) | Installed with plugin |
Project agents (.claude/agents/) — check into version control to share with team.
User agents (~/.claude/agents/) — personal agents available everywhere.
CLI-defined agents — session-scoped, not persisted. Useful for CI/CD and automation:
claude --agents '{ "code-reviewer": { "description": "Expert code reviewer. Use proactively after code changes.", "prompt": "You are a senior code reviewer...", "tools": ["Read", "Grep", "Glob"], "model": "sonnet" }}'The --agents flag uses prompt (not the markdown body) for the system prompt. All other frontmatter fields apply.
Reload: agents load at session start. Manually added files require /agents reload or session restart.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Model Selection
Section titled “Model Selection”| Value | Behavior |
|---|---|
sonnet | Latest Claude Sonnet — balanced capability and speed |
opus | Latest Claude Opus — highest capability, higher cost |
haiku | Latest Claude Haiku — fastest, cheapest, mechanical tasks |
inherit | Same model as the invoking conversation (default when omitted) |
Route expensive agents to haiku for cost control. Use opus for complex reasoning that benefits from max capability. Use inherit for agents that should flex with whatever the user has selected.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Permission Modes
Section titled “Permission Modes”permissionMode controls how the agent handles permission prompts. Subagents inherit the parent conversation’s permission context but can override the mode.
| Mode | Behavior |
|---|---|
default | Standard permission checking with prompts |
acceptEdits | Auto-accept file edits, prompt for everything else |
dontAsk | Auto-deny permission prompts (explicitly allowed tools still work) |
bypassPermissions | Skip all permission checks — use with caution |
plan | Read-only exploration mode |
⚠ If the parent conversation uses bypassPermissions, this takes precedence and cannot be overridden by the subagent.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Allowlist vs Denylist
Section titled “Allowlist vs Denylist”# Allowlist — only these toolstools: Read, Grep, Glob, Bash
# Denylist — all inherited tools except thesedisallowedTools: Write, Edit
# Both — start with allowlist, then removetools: Read, Grep, Glob, Bash, WritedisallowedTools: Write # net: Read, Grep, Glob, BashOmitting tools entirely means the agent inherits all tools from the main conversation, including MCP tools.
Restricting Agent Spawning
Section titled “Restricting Agent Spawning”When running as the main thread via claude --agent, control which subagents can be spawned using Agent(name) syntax in tools:
# Allowlist — only these subagent types can be spawnedtools: Agent(worker, researcher), Read, Bash
# Allow spawning any subagenttools: Agent, Read, Bash
# Block spawning entirely — omit Agent from tools listtools: Read, BashAgent(name) only affects agents running as the main thread (claude --agent). Subagents cannot spawn other subagents, so this has no effect in subagent definitions.
In version 2.1.63, the Task tool was renamed to Agent. Existing Task(...) references still work as aliases.
Available Tool Names
Section titled “Available Tool Names”Internal tools available to agents (exact names for tools field):
Read, Write, Edit, MultiEdit, Bash, Glob, Grep, LS,WebFetch, WebSearch, TodoRead, TodoWrite, Agent,NotebookRead, NotebookEditMCP-provided tools are also available and inherit by default.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Memory
Section titled “Memory”The memory field gives an agent a persistent directory that survives across conversations.
memory: user # or project, or localMemory Scopes
Section titled “Memory Scopes”| Scope | Location | Use When |
|---|---|---|
user | ~/.claude/agent-memory/<agent-name>/ | Learnings apply across all projects — recommended default |
project | .claude/agent-memory/<agent-name>/ | Knowledge is project-specific, shareable via version control |
local | .claude/agent-memory-local/<agent-name>/ | Project-specific but should NOT be committed |
How Memory Works
Section titled “How Memory Works”When memory is set:
- The agent’s system prompt includes instructions for reading/writing the memory directory
- The first 200 lines of
MEMORY.mdin the memory directory are injected into the system prompt at startup - Read, Write, and Edit tools are automatically enabled so the agent can manage its own memory files
- The agent is instructed to curate
MEMORY.mdif it exceeds 200 lines
MEMORY.md Conventions
Section titled “MEMORY.md Conventions”Keep MEMORY.md under 200 lines — content beyond 200 lines is truncated at injection. Structure it for fast scanning:
# Agent Memory
## Codebase Patterns- Auth uses JWT stored in httpOnly cookies- API routes live in src/routes/, not src/api/
## Recurring Issues- Rate limiter middleware order matters — must come before auth- Test database requires POSTGRES_TEST_URL env var
## Architectural Decisions- Using Hono not Express (decided 2026-01-15)- No global state — React Query for all server stateMemory Tips
Section titled “Memory Tips”- Include memory instructions in the agent’s markdown body so it proactively maintains its own knowledge base:
After each session, update your memory with new patterns, gotchas,and architectural decisions. Consult memory before starting work.
- Ask the agent explicitly: “Check your memory before starting” and “Update your memory when done”
- Use
projectscope when the knowledge only makes sense within one codebase
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Isolation: Worktree
Section titled “Isolation: Worktree”isolation: worktreeRunning with isolation: worktree creates a temporary git worktree for each invocation. The agent gets a fully isolated copy of the repository — changes don’t touch the main working tree.
Auto-cleanup behavior:
- If the agent makes no changes → worktree is deleted automatically
- If the agent makes changes → worktree persists; you review and merge manually
Use worktree isolation when:
- The agent might make destructive edits you want to review before applying
- Running the same agent in parallel on different tasks without conflicts
- Experimental refactoring or risky operations
How it works under the hood: Claude Code calls git worktree add with a temp path before spawning the agent. The agent’s working directory is set to the new worktree. On completion, git worktree remove is called if no changes were made.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Skills in Agents
Section titled “Skills in Agents”The skills field injects skill content into the agent’s context at startup:
skills: - api-conventions - error-handling-patterns - typescript-patternsKey behaviors:
- Full skill content is injected — not just made available for invocation
- Subagents do NOT inherit skills from the parent conversation
- Skills must be listed explicitly in the agent definition
- This is the inverse of
context: forkin a skill — with skills in agents, the agent controls the prompt and loads skill content
When to use: preloading domain knowledge the agent will need throughout its work (API conventions, code style, architecture patterns). Saves the agent from discovering and loading skills during execution.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
MCP Servers
Section titled “MCP Servers”Scope MCP servers to specific agents rather than making them globally available:
# Reference a pre-configured server by namemcpServers: - slack - github
# Inline definitionmcpServers: postgres-reader: type: stdio command: npx args: ["-y", "@modelcontextprotocol/server-postgres"] env: POSTGRES_CONNECTION_STRING: "postgresql://readonly:..."Agents inherit all parent conversation MCP tools by default. Use mcpServers to add agent-specific servers, or use disallowedTools to block parent MCP tools from reaching the agent.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Two ways to configure hooks for agents:
1. In Agent Frontmatter (agent-scoped)
Section titled “1. In Agent Frontmatter (agent-scoped)”These hooks run only while the agent is active and are cleaned up when it finishes.
hooks: PreToolUse: - matcher: "Bash" hooks: - type: command command: "./scripts/validate-command.sh" PostToolUse: - matcher: "Edit|Write" hooks: - type: command command: "./scripts/run-linter.sh" Stop: - hooks: - type: command command: "./scripts/on-agent-done.sh"Stop hooks in frontmatter are automatically converted to SubagentStop events at runtime.
Supported hook events in frontmatter:
| Event | Matcher input | When |
|---|---|---|
PreToolUse | Tool name | Before the agent uses a tool |
PostToolUse | Tool name | After the agent uses a tool |
Stop | (none) | When the agent finishes (becomes SubagentStop) |
2. In settings.json (session-level lifecycle)
Section titled “2. In settings.json (session-level lifecycle)”{ "hooks": { "SubagentStart": [ { "matcher": "db-agent", "hooks": [{ "type": "command", "command": "./scripts/setup-db.sh" }] } ], "SubagentStop": [ { "hooks": [{ "type": "command", "command": "./scripts/cleanup.sh" }] } ] }}| Event | Matcher | When |
|---|---|---|
SubagentStart | Agent type name | When a subagent begins execution |
SubagentStop | Agent type name | When a subagent completes |
Hook Exit Codes
Section titled “Hook Exit Codes”| Exit code | Effect |
|---|---|
0 | Continue normally |
2 | Block the operation, send stderr message back to agent |
| Other non-zero | Error, logged but continues |
Hook input is passed via stdin as JSON. For PreToolUse, access tool_input.command (for Bash) or other tool-specific fields.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Background Execution
Section titled “Background Execution”background: trueWhen background: true, this agent always runs as a background task. Claude Code prompts for any tool permissions upfront before launching — once running, the agent auto-denies anything not pre-approved.
Foreground vs background behavior:
| Mode | Permission prompts | Clarifying questions | Blocks main conversation |
|---|---|---|---|
| Foreground | Passed through to user | Passed through | Yes |
| Background | Pre-approved at launch | Tool call fails silently, agent continues | No |
Other ways to background:
- Ask Claude: “run this in the background”
- Press Ctrl+B to background a running task
- Set
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1to disable all background functionality
If a background agent fails due to missing permissions, resume it in the foreground to retry with interactive prompts.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Context Management
Section titled “Context Management”context:fork
Section titled “context:fork”Skills can specify context: fork in their frontmatter to run in a subagent context. This is the inverse of skills in agent definitions:
skillsin an agent definition → agent controls the prompt and loads skill contentcontext: forkin a skill → skill content is injected into the agent you specify
Both mechanisms use the same underlying system.
Resuming Agents
Section titled “Resuming Agents”Each subagent invocation creates a new instance with fresh context. To continue an existing agent’s work, ask Claude to resume it. Resumed agents retain full conversation history including all tool calls, results, and reasoning.
Agent transcripts are stored at:
~/.claude/projects/{project}/{sessionId}/subagents/agent-{agentId}.jsonlTranscripts persist across main conversation compaction (stored separately) and are cleaned up based on cleanupPeriodDays (default: 30 days).
Auto-Compaction
Section titled “Auto-Compaction”Subagents support auto-compaction using the same logic as the main conversation. Default trigger: ~95% context capacity. Override with CLAUDE_AUTOCOMPACT_PCT_OVERRIDE env var (e.g., 50 for 50%).
Subagents Cannot Spawn Subagents
Section titled “Subagents Cannot Spawn Subagents”This is a hard architectural constraint. If your workflow requires nested delegation, use Skills or chain subagents from the main conversation.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Agent Teams (Research Preview)
Section titled “Agent Teams (Research Preview)”Agent teams coordinate multiple Claude Code sessions working together. Unlike subagents (which only report back to the main agent), teammates can message each other directly.
Enable:
{ "env": { "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1" }}Architecture
Section titled “Architecture”| Component | Role |
|---|---|
| Team lead | Main Claude Code session — creates team, spawns teammates, coordinates |
| Teammates | Separate Claude Code instances, each with own context window |
| Task list | Shared work items teammates claim and complete |
| Mailbox | Messaging system for inter-agent communication |
Storage:
- Team config:
~/.claude/teams/{team-name}/config.json - Tasks:
~/.claude/tasks/{team-name}/
Subagents vs Agent Teams
Section titled “Subagents vs Agent Teams”| Subagents | Agent Teams | |
|---|---|---|
| Context | Own window, results return to caller | Own window, fully independent |
| Communication | Report back to main only | Teammates message each other directly |
| Coordination | Main agent manages all work | Shared task list, self-coordinating |
| Token cost | Lower | Higher (each teammate = separate Claude instance) |
| Best for | Focused tasks where only result matters | Complex work needing discussion and collaboration |
Display Modes
Section titled “Display Modes”| Mode | Behavior | Requirement |
|---|---|---|
in-process (default) | All teammates in main terminal, Shift+Down to cycle | None |
tmux | Each teammate in own split pane | tmux or iTerm2 with it2 CLI |
Configure in settings.json:
{ "teammateMode": "in-process" }Or per-session: claude --teammate-mode in-process
Task Coordination
Section titled “Task Coordination”Tasks have three states: pending, in_progress, completed. Tasks can declare dependencies — a task with unresolved dependencies cannot be claimed until those complete. File locking prevents race conditions when multiple teammates claim simultaneously.
Hooks for Agent Teams
Section titled “Hooks for Agent Teams”{ "hooks": { "TeammateIdle": [ { "hooks": [{ "type": "command", "command": "./scripts/quality-check.sh" }] } ], "TaskCompleted": [ { "hooks": [{ "type": "command", "command": "./scripts/task-gate.sh" }] } ] }}| Hook | When | Exit 2 behavior |
|---|---|---|
TeammateIdle | Teammate about to go idle | Send feedback, keep teammate working |
TaskCompleted | Task being marked complete | Prevent completion, send feedback |
Current Limitations (as of 2026-03-01)
Section titled “Current Limitations (as of 2026-03-01)”- No session resumption with in-process teammates (
/resumeand/rewinddon’t restore teammates) - Task status can lag — teammates sometimes fail to mark tasks completed
- One team per session (clean up before starting a new one)
- No nested teams — only the lead can manage the team
- Permissions set at spawn — can’t set per-teammate modes upfront
- Split panes require tmux or iTerm2 (not VS Code terminal, Windows Terminal, or Ghostty)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Common Patterns
Section titled “Common Patterns”Read-Only Reviewer
Section titled “Read-Only Reviewer”---name: code-reviewerdescription: Expert code review. Use proactively after writing or modifying code.tools: Read, Grep, Glob, Bashmodel: inheritmemory: project---
You are a senior code reviewer. When invoked:1. Run `git diff` to see recent changes2. Focus on modified files3. Review for: correctness, security, readability, error handling, test coverage
Provide feedback organized by priority:- ◆ Critical (must fix)- ⚠ Warning (should fix)- ◇ Suggestion (consider)Isolated Refactoring Agent
Section titled “Isolated Refactoring Agent”---name: refactor-agentdescription: Perform risky refactors in isolation. Use when refactoring shared modules.tools: Read, Write, Edit, Bash, Grep, Globmodel: sonnetisolation: worktreepermissionMode: bypassPermissions---
You are a refactoring specialist. Work in your isolated worktree.Make changes, run tests to verify, summarize what you did.Background Test Runner
Section titled “Background Test Runner”---name: test-watcherdescription: Run the test suite in the background after code changes.tools: Bash, Readmodel: haikubackground: truemaxTurns: 5---
Run `npm test` and report only failing tests with their error messages.Keep output concise — pass/fail counts plus failure details only.Domain Expert with Preloaded Knowledge
Section titled “Domain Expert with Preloaded Knowledge”---name: api-developerdescription: Implement API endpoints following team conventions.skills: - rest-api-patterns - error-handling - auth-conventionsmodel: sonnet---
Implement API endpoints. The preloaded skills contain the team'sconventions — follow them exactly.━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Common Mistakes
Section titled “Common Mistakes”| Mistake | Fix |
|---|---|
| Agent inherits all tools unintentionally | Specify tools explicitly to scope what the agent can do |
| Subagent tries to spawn another subagent | Architectural constraint — not possible. Chain from main conversation instead |
| Memory exceeds 200 lines | Agent only sees first 200 lines of MEMORY.md — curate proactively |
Forgetting skills don’t inherit | List every skill explicitly in skills field — no automatic inheritance |
Using bypassPermissions without scoping tools | Always pair with explicit tools allowlist when using bypass mode |
isolation: worktree on non-git repo | Requires a git repository — silently fails or errors otherwise |
| Background agent fails silently | Pre-approve tool permissions before launch; resume in foreground if stuck |
| Agent teams used for sequential tasks | Use subagents or single session — teams add coordination overhead without benefit |