Skip to content

claude-code-agents

Use when creating custom Claude Code agents/subagents — frontmatter schema, built-in types, tools, permissions, memory, isolation, worktree support

ModelSource
inheritpack: claude-code-internals

Tools: Read, Grep, Glob, WebFetch, WebSearch

Full Reference

┏━ 🔧 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.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Claude Code ships with built-in subagents invoked automatically. You don’t create these — you override them or disable them.

AgentModelToolsPurpose
ExploreHaikuRead-onlyFile discovery, code search, codebase exploration. Invoked with thoroughness: quick, medium, very thorough
PlanInheritRead-onlyCodebase research during plan mode. Prevents infinite nesting (subagents can’t spawn subagents)
general-purposeInheritAllComplex multi-step tasks requiring both exploration and action
BashInheritBashRunning terminal commands in a separate context
statusline-setupSonnetInvoked by /statusline to configure the status line
Claude Code GuideHaikuAnswers 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)"]
}
}

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Subagent files are Markdown with YAML frontmatter. The body becomes the system prompt.

---
name: my-agent
description: When Claude should delegate to this agent
model: sonnet
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit
permissionMode: acceptEdits
maxTurns: 20
skills:
- api-conventions
- error-handling
memory: user
isolation: worktree
background: false
mcpServers:
- slack
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-command.sh"
---
System prompt goes here. The agent receives only this prompt plus
basic env details (working directory, etc.) — NOT the full Claude
Code system prompt and NOT the parent conversation history.
FieldRequiredTypeDefaultDescription
nameYesstringUnique ID: lowercase letters and hyphens only
descriptionYesstringWhen Claude should delegate — be specific, include “use proactively” to encourage automatic delegation
modelNoenuminheritsonnet, opus, haiku, or inherit
toolsNolistall inheritedAllowlist of tools. Omit to inherit all tools including MCP
disallowedToolsNolistnoneDenylist — removed from inherited or specified list
permissionModeNoenumdefaultdefault, acceptEdits, dontAsk, bypassPermissions, plan
maxTurnsNointegerunlimitedMax agentic turns before the agent stops
skillsNolistnoneSkills to inject into context at startup (full content, not invokable)
memoryNoenumnoneuser, project, or local — enables persistent cross-session memory
isolationNoenumnoneworktree — runs in a temporary git worktree, auto-cleaned if no changes
backgroundNobooleanfalseAlways run this agent as a background task
mcpServersNolist/objectnoneMCP servers scoped to this agent — server name string or inline config object
hooksNoobjectnoneLifecycle hooks scoped to this agent’s execution

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

When multiple agents share the same name, higher-priority location wins.

LocationScopePriorityCreation
--agents CLI flagCurrent session only (not saved)1 (highest)Pass JSON at launch
.claude/agents/Current project2/agents command or manual
~/.claude/agents/All projects on this machine3/agents command or manual
Plugin agents/ dirWhere plugin is enabled4 (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:

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

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

ValueBehavior
sonnetLatest Claude Sonnet — balanced capability and speed
opusLatest Claude Opus — highest capability, higher cost
haikuLatest Claude Haiku — fastest, cheapest, mechanical tasks
inheritSame 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.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

permissionMode controls how the agent handles permission prompts. Subagents inherit the parent conversation’s permission context but can override the mode.

ModeBehavior
defaultStandard permission checking with prompts
acceptEditsAuto-accept file edits, prompt for everything else
dontAskAuto-deny permission prompts (explicitly allowed tools still work)
bypassPermissionsSkip all permission checks — use with caution
planRead-only exploration mode

⚠ If the parent conversation uses bypassPermissions, this takes precedence and cannot be overridden by the subagent.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

# Allowlist — only these tools
tools: Read, Grep, Glob, Bash
# Denylist — all inherited tools except these
disallowedTools: Write, Edit
# Both — start with allowlist, then remove
tools: Read, Grep, Glob, Bash, Write
disallowedTools: Write # net: Read, Grep, Glob, Bash

Omitting tools entirely means the agent inherits all tools from the main conversation, including MCP tools.

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 spawned
tools: Agent(worker, researcher), Read, Bash
# Allow spawning any subagent
tools: Agent, Read, Bash
# Block spawning entirely — omit Agent from tools list
tools: Read, Bash

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

Internal tools available to agents (exact names for tools field):

Read, Write, Edit, MultiEdit, Bash, Glob, Grep, LS,
WebFetch, WebSearch, TodoRead, TodoWrite, Agent,
NotebookRead, NotebookEdit

MCP-provided tools are also available and inherit by default.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

The memory field gives an agent a persistent directory that survives across conversations.

memory: user # or project, or local
ScopeLocationUse 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

When memory is set:

  • The agent’s system prompt includes instructions for reading/writing the memory directory
  • The first 200 lines of MEMORY.md in 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.md if it exceeds 200 lines

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 state
  • 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 project scope when the knowledge only makes sense within one codebase

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

isolation: worktree

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

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

The skills field injects skill content into the agent’s context at startup:

skills:
- api-conventions
- error-handling-patterns
- typescript-patterns

Key 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: fork in 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.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Scope MCP servers to specific agents rather than making them globally available:

# Reference a pre-configured server by name
mcpServers:
- slack
- github
# Inline definition
mcpServers:
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:

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:

EventMatcher inputWhen
PreToolUseTool nameBefore the agent uses a tool
PostToolUseTool nameAfter 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" }]
}
]
}
}
EventMatcherWhen
SubagentStartAgent type nameWhen a subagent begins execution
SubagentStopAgent type nameWhen a subagent completes
Exit codeEffect
0Continue normally
2Block the operation, send stderr message back to agent
Other non-zeroError, 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: true

When 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:

ModePermission promptsClarifying questionsBlocks main conversation
ForegroundPassed through to userPassed throughYes
BackgroundPre-approved at launchTool call fails silently, agent continuesNo

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=1 to disable all background functionality

If a background agent fails due to missing permissions, resume it in the foreground to retry with interactive prompts.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Skills can specify context: fork in their frontmatter to run in a subagent context. This is the inverse of skills in agent definitions:

  • skills in an agent definition → agent controls the prompt and loads skill content
  • context: fork in a skill → skill content is injected into the agent you specify

Both mechanisms use the same underlying system.

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

Transcripts persist across main conversation compaction (stored separately) and are cleaned up based on cleanupPeriodDays (default: 30 days).

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

This is a hard architectural constraint. If your workflow requires nested delegation, use Skills or chain subagents from the main conversation.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

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"
}
}
ComponentRole
Team leadMain Claude Code session — creates team, spawns teammates, coordinates
TeammatesSeparate Claude Code instances, each with own context window
Task listShared work items teammates claim and complete
MailboxMessaging system for inter-agent communication

Storage:

  • Team config: ~/.claude/teams/{team-name}/config.json
  • Tasks: ~/.claude/tasks/{team-name}/
SubagentsAgent Teams
ContextOwn window, results return to callerOwn window, fully independent
CommunicationReport back to main onlyTeammates message each other directly
CoordinationMain agent manages all workShared task list, self-coordinating
Token costLowerHigher (each teammate = separate Claude instance)
Best forFocused tasks where only result mattersComplex work needing discussion and collaboration
ModeBehaviorRequirement
in-process (default)All teammates in main terminal, Shift+Down to cycleNone
tmuxEach teammate in own split panetmux or iTerm2 with it2 CLI

Configure in settings.json:

{ "teammateMode": "in-process" }

Or per-session: claude --teammate-mode in-process

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": {
"TeammateIdle": [
{
"hooks": [{ "type": "command", "command": "./scripts/quality-check.sh" }]
}
],
"TaskCompleted": [
{
"hooks": [{ "type": "command", "command": "./scripts/task-gate.sh" }]
}
]
}
}
HookWhenExit 2 behavior
TeammateIdleTeammate about to go idleSend feedback, keep teammate working
TaskCompletedTask being marked completePrevent completion, send feedback
  • No session resumption with in-process teammates (/resume and /rewind don’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)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

---
name: code-reviewer
description: Expert code review. Use proactively after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
memory: project
---
You are a senior code reviewer. When invoked:
1. Run `git diff` to see recent changes
2. Focus on modified files
3. Review for: correctness, security, readability, error handling, test coverage
Provide feedback organized by priority:
- ◆ Critical (must fix)
- ⚠ Warning (should fix)
- ◇ Suggestion (consider)
---
name: refactor-agent
description: Perform risky refactors in isolation. Use when refactoring shared modules.
tools: Read, Write, Edit, Bash, Grep, Glob
model: sonnet
isolation: worktree
permissionMode: bypassPermissions
---
You are a refactoring specialist. Work in your isolated worktree.
Make changes, run tests to verify, summarize what you did.
---
name: test-watcher
description: Run the test suite in the background after code changes.
tools: Bash, Read
model: haiku
background: true
maxTurns: 5
---
Run `npm test` and report only failing tests with their error messages.
Keep output concise — pass/fail counts plus failure details only.
---
name: api-developer
description: Implement API endpoints following team conventions.
skills:
- rest-api-patterns
- error-handling
- auth-conventions
model: sonnet
---
Implement API endpoints. The preloaded skills contain the team's
conventions — follow them exactly.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

MistakeFix
Agent inherits all tools unintentionallySpecify tools explicitly to scope what the agent can do
Subagent tries to spawn another subagentArchitectural constraint — not possible. Chain from main conversation instead
Memory exceeds 200 linesAgent only sees first 200 lines of MEMORY.md — curate proactively
Forgetting skills don’t inheritList every skill explicitly in skills field — no automatic inheritance
Using bypassPermissions without scoping toolsAlways pair with explicit tools allowlist when using bypass mode
isolation: worktree on non-git repoRequires a git repository — silently fails or errors otherwise
Background agent fails silentlyPre-approve tool permissions before launch; resume in foreground if stuck
Agent teams used for sequential tasksUse subagents or single session — teams add coordination overhead without benefit