Subagent Patterns

Verified 高级 Advanced 参考型 Reference ⚡ Claude Code 专属 ⚡ Claude Code Optimized
4 min read · 192 lines

Subagent patterns: custom agent definitions + persistent memory + worktree isolation + orchestration

Subagent Patterns

Overview

Subagents are specialized AI assistants running in their own context window with custom system prompts, specific tool access, and independent permissions. They are a core extensibility mechanism of Claude Code.

Built-in Subagents

Agent Model Tools Purpose
Explore Haiku Read-only File discovery, code search, codebase exploration
Plan Inherited Read-only Codebase research for planning
general-purpose Inherited All tools Complex research, multi-step operations
Bash Inherited Terminal commands Shell operations
statusline-setup Sonnet Status line config Customize status bar
Claude Code Guide Haiku Feature queries Claude Code usage Q&A

Custom Subagents

Create Markdown files in .claude/agents/ or ~/.claude/agents/:

---
name: code-reviewer
description: Expert code reviewer. Use for PR reviews, code quality, and security checks.
tools: Read, Grep, Glob, Bash(npm run lint *)
model: sonnet
permissionMode: default
maxTurns: 20
---

You are a senior code reviewer. Perform these checks:

1. **Code Quality**: Naming conventions, function length, single responsibility
2. **Security**: Injection risks, data exposure, auth flaws
3. **Performance**: N+1 queries, unnecessary renders, memory leaks
4. **Maintainability**: Code duplication, coupling, test coverage

Output a structured review report.

Frontmatter Fields

Field Required Description
name Yes Unique identifier (lowercase, hyphens)
description Yes When Claude should delegate to this subagent
tools No Tools the subagent can use (inherits all if omitted)
disallowedTools No Tools to deny
model No sonnet, opus, haiku, full model ID, or inherit
permissionMode No default, acceptEdits, dontAsk, bypassPermissions, plan
maxTurns No Maximum agentic turns
skills No Skills to preload into context at startup
mcpServers No MCP servers available (inline definitions or string references)
hooks No Lifecycle hooks scoped to the subagent
memory No Persistent memory scope: user, project, or local
background No true to always run as background task
isolation No worktree to run in temporary git worktree

Subagent Locations & Priority

Location Scope Priority
--agents CLI flag Current session 1 (highest)
.claude/agents/ Current project 2
~/.claude/agents/ All your projects 3
Plugin's agents/ Where plugin enabled 4 (lowest)

CLI-defined Subagents

Define temporary subagents via command line:

claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer.",
    "prompt": "You are a senior code reviewer...",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  }
}'

Persistent Memory

Enable cross-session memory for subagents:

Scope Storage Location
user ~/.claude/agent-memory/<name>/
project .claude/agent-memory/<name>/
local .claude/agent-memory-local/<name>/

When enabled:

  • Subagent gets instructions for reading/writing memory
  • First 200 lines of MEMORY.md loaded at startup
  • Read/Write/Edit tools auto-enabled

Tool Restrictions

Restrict Which Subagents Can Be Spawned

tools: Agent(worker, researcher), Read, Bash

Only allows spawning worker and researcher subagents.

Scoped MCP Servers

mcpServers:
  my-db:
    command: npx
    args: ["-y", "@modelcontextprotocol/server-postgres", "postgresql://..."]

Define dedicated MCP servers for a subagent, enabling tool-level isolation.

Foreground vs Background

Mode Characteristics
Foreground (default) Blocks main conversation, permission prompts pass through to user
Background Runs concurrently, pre-approves permissions, auto-denies anything not pre-approved

Worktree Isolation

isolation: worktree

Subagent works in a temporary git worktree with an isolated copy of the repo. Ideal for:

  • Parallel modifications to the same files
  • Experimental changes (no impact on main branch)
  • Parallel processing units within /batch

Practical Patterns

Database Query Agent

---
name: db-reader
description: Safe read-only database query agent
tools: Bash(psql *)
model: haiku
maxTurns: 5
---

You may only execute SELECT queries. Never execute INSERT/UPDATE/DELETE/DROP.
Explain what you're querying before each query.

Research Agent

---
name: researcher
description: Deep codebase research on specific questions
tools: Read, Grep, Glob, WebSearch, WebFetch
model: sonnet
background: true
memory: project
---

You are a research specialist. Systematically search the codebase for complete answers.
Save your findings to memory for future reference.

Security Audit Agent

---
name: security-auditor
description: Security audit — check code for vulnerabilities and security issues
tools: Read, Grep, Glob, Bash(npm audit *)
model: opus
maxTurns: 30
---

Perform a comprehensive security audit: OWASP Top 10, dependency vulnerabilities,
secret exposure, authentication flaws. Output a structured report, sorted by severity.

相关技能 Related Skills