AgentSkillsCN

claude-code-sub-agents

创建并使用 Claude Code 子代理的最佳实践——这些是专门的 AI 助手,可在隔离的上下文窗口中,通过自定义提示、工具访问权限及相应权限来高效处理特定任务。在设计子代理配置、权衡子代理与主对话之间的选择,或构建自定义代理工作流时,可运用此技能。

SKILL.md
--- frontmatter
name: claude-code-sub-agents
description: Best practices for creating and using Claude Code subagents — specialized AI assistants that handle specific tasks in isolated context windows with custom prompts, tool access, and permissions. Use this skill when designing subagent configurations, deciding between subagents vs main conversation, or building custom agent workflows.

Claude Code Sub-Agents Best Practices

Source: Claude Code Sub-Agents Documentation

What Are Subagents?

Subagents are specialized AI assistants that run in their own context window with a custom system prompt, specific tool access, and independent permissions. When Claude encounters a matching task, it delegates to the subagent, which works independently and returns results.

[!IMPORTANT] Subagents cannot spawn other subagents. If you need nested delegation, chain subagents from the main conversation or use Skills instead. For parallel agents that communicate with each other, use Agent Teams instead.

Why Use Subagents?

BenefitDescription
Preserve contextKeep exploration/investigation out of your main conversation
Enforce constraintsLimit which tools a subagent can use
Reuse configsUser-level subagents work across all projects
Specialize behaviorFocused system prompts for specific domains
Control costsRoute tasks to cheaper models like Haiku

Built-In Subagents

Claude Code includes these built-in subagents:

AgentModelToolsPurpose
ExploreHaiku (fast)Read-onlyFile discovery, code search, codebase exploration
PlanInheritsRead-onlyCodebase research for planning mode
General-purposeInheritsAll toolsComplex research, multi-step operations
BashInheritsBashRunning terminal commands in separate context
Claude Code GuideHaikuAnswering questions about Claude Code features

When to Use Subagents vs Main Conversation

Use the main conversation when:

  • The task needs frequent back-and-forth or iterative refinement
  • Multiple phases share significant context (planning → implementation → testing)
  • You're making a quick, targeted change
  • Latency matters — subagents start fresh and may need time to gather context

Use subagents when:

  • The task produces verbose output you don't need in your main context
  • You want to enforce specific tool restrictions or permissions
  • The work is self-contained and can return a summary
  • You need parallel research on independent topics

Use Agent Teams instead when:

  • Workers need to communicate with each other directly
  • You need sustained parallelism exceeding your context window
  • Complex work requiring discussion and collaboration between agents
  • Cross-layer coordination (frontend, backend, tests)

Creating Custom Subagents

File Format

Subagent files use YAML frontmatter + Markdown body for the system prompt:

markdown
---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep, Bash
model: sonnet
---

You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.

Supported Frontmatter Fields

FieldRequiredDescription
nameYesUnique identifier (lowercase + hyphens)
descriptionYesWhen Claude should delegate to this subagent
toolsNoAllowlisted tools (inherits all if omitted)
disallowedToolsNoTools to deny from inherited list
modelNosonnet, opus, haiku, or inherit (default: inherit)
permissionModeNodefault, acceptEdits, delegate, dontAsk, bypassPermissions, plan
maxTurnsNoMaximum agentic turns before stopping
skillsNoSkills to preload into subagent context at startup
mcpServersNoMCP servers available to this subagent
hooksNoLifecycle hooks scoped to this subagent
memoryNoPersistent memory scope: user, project, or local

Scope and Priority

LocationScopePriority
--agents CLI flagCurrent session only1 (highest)
.claude/agents/Current project2
~/.claude/agents/All your projects3
Plugin's agents/ directoryWhere plugin is enabled4 (lowest)

[!TIP] Project subagents (.claude/agents/) should be checked into version control so your team can share and improve them collaboratively.


Best Practices

1. Design Focused Subagents

Each subagent should excel at one specific task. Don't create Swiss-army-knife agents — instead, chain specialized ones.

2. Write Detailed Descriptions

Claude uses the description field to decide when to delegate. Include:

  • What the subagent does
  • When it should be used
  • Add "use proactively" to encourage automatic delegation
yaml
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.

3. Limit Tool Access (Principle of Least Privilege)

Grant only necessary permissions:

yaml
# Read-only reviewer
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit

# Debugging agent that needs edit access
tools: Read, Edit, Bash, Grep, Glob

4. Use Persistent Memory for Learning Across Sessions

yaml
memory: user  # Recommended default scope
ScopeLocationBest For
user~/.claude/agent-memory/<name>/Learnings across all projects
project.claude/agent-memory/<name>/Project-specific, shareable via VCS
local.claude/agent-memory-local/<name>/Project-specific, not in VCS

Include memory instructions in the subagent prompt:

markdown
Update your agent memory as you discover codepaths, patterns, library
locations, and key architectural decisions. This builds up institutional
knowledge across conversations.

5. Use Hooks for Conditional Validation

When you need finer control than the tools field provides:

yaml
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate-readonly-query.sh"

6. Preload Skills for Domain Knowledge

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

[!NOTE] Subagents don't inherit skills from the parent conversation. You must list them explicitly.


Common Patterns

Isolate High-Volume Operations

code
Use a subagent to run the test suite and report only the failing tests with their error messages

Run Parallel Research

code
Research the authentication, database, and API modules in parallel using separate subagents

Chain Subagents for Multi-Step Workflows

code
Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them

Foreground vs Background Execution

  • Foreground: Blocks main conversation, permission prompts pass through to you
  • Background: Runs concurrently, pre-approves permissions, auto-denies unapproved tools
  • Press Ctrl+B to background a running task
  • Ask Claude to "run this in the background"

Resume a Subagent

code
Continue that code review and now analyze the authorization logic

Resumed subagents retain their full conversation history.


Example Subagent Templates

Code Reviewer (Read-Only)

markdown
---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---

You are a senior code reviewer ensuring high standards of code quality and security.

When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately

Review checklist:
- Code is clear and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed

Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)

Include specific examples of how to fix issues.

Debugger (Read + Edit)

markdown
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---

You are an expert debugger specializing in root cause analysis.

When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works

Focus on fixing the underlying issue, not the symptoms.

Database Query Validator (Hook-Protected)

markdown
---
name: db-reader
description: Execute read-only database queries. Use when analyzing data or generating reports.
tools: Bash
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate-readonly-query.sh"
---

You are a database analyst with read-only access. Execute SELECT queries
to answer questions about the data. You cannot modify data.

CLI-Defined (Ephemeral Session)

bash
claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  }
}'

Quick Reference: Key Commands

ActionCommand
Manage subagents interactively/agents
Request specific subagentUse the <name> subagent to...
Background a running subagentCtrl+B
Disable background tasksCLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1
Disable specific subagentpermissions.deny: ["Task(agent-name)"]