Claude Code Subagent 创建指南

8 阅读8分钟

Claude Code Subagent 创建指南

1. 什么是 Subagent 以及使用场景

1.1 定义

Subagent(子代理)是 Claude Code 中的专业化 AI 助手,用于处理特定类型的任务。每个 Subagent 在独立的上下文窗口中运行,拥有自定义的系统提示词、特定的工具访问权限和独立的权限设置。

1.2 核心优势

优势说明
上下文隔离探索和实现操作不会污染主对话的上下文
能力约束可以限制 Subagent 能使用的工具集
配置复用通过用户级 Subagent 在项目间共享配置
行为专业化为特定领域提供聚焦的系统提示词
成本控制将任务路由到更快、更便宜的模型(如 Haiku)

1.3 典型使用场景

  1. 代码审查 - 创建只读代理审查代码质量和安全性
  2. 调试问题 - 创建能够分析和修复问题的代理
  3. 数据分析 - 创建专注于 SQL 和数据查询的代理
  4. 文档探索 - 创建快速搜索和理解代码库的代理
  5. 测试运行 - 隔离测试输出,避免消耗主对话上下文

2. 创建步骤

2.1 目录结构

Subagent 文件可以存储在以下位置:

位置作用域优先级
--agents CLI 参数当前会话1(最高)
.claude/agents/当前项目2
~/.claude/agents/所有项目3
插件的 agents/ 目录插件启用时4(最低)

2.2 文件格式

Subagent 使用带有 YAML frontmatter 的 Markdown 文件格式:

---
name: my-subagent
description: 清晰描述何时应该委托给此 Subagent
tools: Read, Grep, Glob, Bash
model: sonnet
---

你是一个专业的 [角色描述]

当被调用时:
1. 步骤一
2. 步骤二
3. 步骤三

[详细的系统提示词内容]

2.3 创建方法

方法一:使用 /agents 命令(推荐)
/agents

然后选择:

  1. Create new agent
  2. 选择作用域(User-level 或 Project-level)
  3. 选择 Generate with Claude 或手动编写
  4. 选择工具权限
  5. 选择模型
  6. 选择颜色标识
  7. 保存
方法二:手动创建文件
# 用户级 Subagent
mkdir -p ~/.claude/agents
cat > ~/.claude/agents/my-agent.md << 'EOF'
---
name: my-agent
description: 描述此代理的功能
---

系统提示词内容...
EOF
方法三:通过 CLI 参数定义
claude --agents '{
  "code-reviewer": {
    "description": "代码审查专家",
    "prompt": "你是一个高级代码审查员...",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  }
}'

3. 配置详解

3.1 Frontmatter 字段参考

字段必需说明
name唯一标识符,使用小写字母和连字符
description描述何时委托给此 Subagent
tools允许使用的工具列表,省略则继承所有工具
disallowedTools禁止使用的工具列表
model模型选择:sonnetopushaikuinherit
permissionMode权限模式:defaultacceptEditsdontAskbypassPermissionsplan
maxTurns最大代理轮次
skills预加载的技能列表
mcpServers可用的 MCP 服务器
hooks生命周期钩子
memory持久化内存作用域:userprojectlocal
background是否作为后台任务运行
isolation设置为 worktree 在隔离的 git worktree 中运行

3.2 模型选择

model: sonnet    # 使用 Sonnet 模型
model: opus      # 使用 Opus 模型
model: haiku     # 使用 Haiku 模型(快速、低成本)
model: inherit   # 继承主对话的模型(默认)

3.3 工具权限控制

# 白名单方式 - 只允许指定工具
tools: Read, Grep, Glob, Bash

# 黑名单方式 - 禁止指定工具
disallowedTools: Write, Edit

# 组合使用
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit

3.4 持久化内存配置

memory: user     # 跨所有项目共享
memory: project  # 项目级,可通过版本控制共享
memory: local    # 项目级,但不提交到版本控制

4. 架构图

4.1 Subagent 工作流程

flowchart TD
    subgraph Main["主会话"]
        User[用户请求] --> Claude{Claude 分析任务}
    end

    subgraph Delegation["委托决策"]
        Claude -->|匹配 description| Delegate[委托给 Subagent]
        Claude -->|不匹配| Direct[直接处理]
    end

    subgraph SubagentCtx["Subagent 上下文"]
        Delegate --> Load[加载配置]
        Load --> SystemPrompt[应用系统提示词]
        Load --> ToolRestrict[应用工具限制]
        Load --> Permission[应用权限模式]

        SystemPrompt --> Execute[执行任务]
        ToolRestrict --> Execute
        Permission --> Execute
    end

    subgraph Result["结果处理"]
        Execute --> Summary[生成摘要]
        Summary --> Return[返回主会话]
    end

    Direct --> Final[完成]
    Return --> Final

4.2 Subagent 上下文隔离

graph TB
    subgraph MainContext["主会话上下文"]
        M1[用户历史对话]
        M2[主会话工具调用]
        M3[项目文件内容]
    end

    subgraph SubagentContext["Subagent 独立上下文"]
        S1[Subagent 系统提示词]
        S2[工具调用结果]
        S3[推理过程]
    end

    subgraph Communication["通信机制"]
        Input[任务输入]
        Output[结果摘要]
    end

    MainContext --> Input
    Input --> SubagentContext
    SubagentContext --> Output
    Output --> MainContext

4.3 内置 Subagent 体系

graph LR
    subgraph BuiltIn["内置 Subagent"]
        Explore[Explore快速只读探索]
        Plan[Plan计划模式研究]
        General[General-purpose通用复杂任务]
    end

    subgraph Custom["自定义 Subagent"]
        CodeReviewer[Code Reviewer代码审查]
        Debugger[Debugger调试修复]
        DataScientist[Data Scientist数据分析]
    end

    subgraph Model["模型分配"]
        HaikuModel[Haiku快速响应]
        SonnetModel[Sonnet平衡能力]
        InheritModel[继承主会话]
    end

    Explore --> HaikuModel
    Plan --> InheritModel
    General --> InheritModel
    CodeReviewer --> SonnetModel
    Debugger --> InheritModel
    DataScientist --> SonnetModel

5. 实际案例:claude-code-tutor 代理

以下是用户创建的 claude-code-tutor 代理的完整配置:

5.1 文件位置

~/.claude/agents/claude-code-tutor.md

5.2 完整配置

---
name: claude-code-tutor
description: Use this agent when the user asks questions ("Can Claude...", "Does Claude...", "How do I...") about: (1) Claude Code (the CLI tool) - features, hooks, slash commands, MCP servers, settings, IDE integrations, keyboard shortcuts; (2) Claude Agent SDK - building custom agents; (3) Claude API (formerly Anthropic API) - API usage, tool use, Anthropic SDK usage. This agent specializes in sharing knowledge with clear, concise Markdown documentation for team learning.
model: sonnet
---

You are a Claude Code Knowledge Tutor. Your role is to help users understand
and share knowledge about Claude Code, Claude Agent SDK, and Claude API with
their team.

## Core Principles

1. **Clear & Concise**: All outputs should be in clean Markdown format
2. **Practical**: Provide real-world examples and use cases
3. **Actionable**: Give specific steps and commands users can copy-paste
4. **Team-Friendly**: Format outputs as shareable documentation

## Knowledge Sources

### Official Resources (use WebFetch/WebSearch)
- Claude Code docs: https://docs.anthropic.com/en/docs/claude-code
- Agent SDK docs: https://docs.anthropic.com/en/docs/agent-sdk
- API docs: https://docs.anthropic.com/en/api

### Personal Knowledge Base
Read from the user's memory files:
- `/Users/xiaofan/.claude/projects/-Users-xiaofan/memory/MEMORY.md`

## Capabilities

### 1. Answer Questions
When users ask about Claude Code features, provide:
- Clear explanation of the feature
- When/why to use it
- Practical examples

### 2. Provide Examples
Create working examples for:
- Hooks configuration
- MCP server setup
- Custom agents/skills
- CLI commands

### 3. Troubleshooting
Help diagnose and fix common issues

### 4. Documentation Generation
Output format for team sharing with proper Markdown structure

5.3 配置解析

配置项说明
nameclaude-code-tutor唯一标识符
description详细描述定义何时触发此代理,包含关键词匹配
modelsonnet使用 Sonnet 模型平衡能力和速度
tools未指定继承所有工具(Read, Grep, Glob, WebFetch 等)

5.4 使用方式

# 直接调用
Use the claude-code-tutor agent to explain MCP servers

# 自动触发(通过 description 匹配)
How do I configure hooks in Claude Code?

6. 最佳实践建议

6.1 设计原则

  1. 专注单一职责 - 每个 Subagent 应该擅长一项特定任务
  2. 编写详细描述 - Claude 依赖 description 决定何时委托
  3. 限制工具权限 - 只授予必要的权限以增强安全性
  4. 版本控制共享 - 项目级 Subagent 提交到版本控制供团队使用

6.2 描述编写技巧

# 好的描述示例
description: |
  Expert code reviewer. Use proactively after code changes to review
  code quality, security, and best practices. Triggers on keywords
  like "review", "check code", or "analyze changes".

# 不好的描述
description: Reviews code  # 过于简短,Claude 难以判断何时使用

6.3 工具权限选择指南

场景推荐工具配置
只读分析tools: Read, Grep, Glob, Bash
代码修改tools: Read, Edit, Write, Bash
Web 研究tools: WebFetch, WebSearch, Read
数据分析tools: Bash, Read, Write

6.4 模型选择建议

模型适用场景
haiku快速探索、简单查询、低延迟需求
sonnet平衡场景、代码审查、中等复杂任务
opus复杂推理、架构设计、高难度问题
inherit需要与主会话保持一致的场景

6.5 持久化内存使用

---
name: learning-agent
description: 持续学习的代理
memory: user
---

你是一个持续学习的代理。

## 内存使用指南

1. 每次任务完成后,更新你的知识库
2. 记录发现的新模式、最佳实践和常见陷阱
3. 下次执行任务时先查阅历史记忆

 ~/.claude/agent-memory/learning-agent/MEMORY.md 中维护知识。

6.6 常见问题解决

问题解决方案
Subagent 未被触发检查 description 是否包含触发关键词
工具权限错误检查 tools/disallowedTools 配置
上下文溢出设置 memory 启用持久化,或使用 maxTurns 限制
输出过于冗长在系统提示词中明确输出格式要求

7. 进阶主题

7.1 与 Hooks 结合

---
name: db-reader
description: 执行只读数据库查询
tools: Bash
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate-readonly-query.sh"
---

7.2 与 Skills 结合

---
name: api-developer
description: 按团队规范实现 API 端点
skills:
  - api-conventions
  - error-handling-patterns
---

按照预加载的技能中定义的规范实现 API。

7.3 通过插件分发

将 Subagent 放入插件的 agents/ 目录:

my-plugin/
├── .claude-plugin/
│   └── plugin.json
└── agents/
    └── my-agent.md

8. 知识库配置

8.1 知识库目录结构

~/.claude/projects/-Users-xiaofan/memory/
├── MEMORY.md           # 主索引
├── subagent-guide.md   # 本文档
├── hooks.md            # Hooks 详解
├── mcp-servers.md      # MCP Servers
├── skills.md           # Skills 开发
├── cli-commands.md     # CLI 速查
└── mermaid.md          # Mermaid 图表

8.2 知识库索引

更新 MEMORY.md 添加新文件引用:

## Knowledge Base Files

| File | Topic |
|------|-------|
| [subagent-guide.md](subagent-guide.md) | Subagent 创建指南 |
| [hooks.md](hooks.md) | Hooks 配置详解 |
| [mcp-servers.md](mcp-servers.md) | MCP Servers 使用 |
| [skills.md](skills.md) | Skills 开发指南 |
| [cli-commands.md](cli-commands.md) | CLI 命令速查 |
| [mermaid.md](mermaid.md) | Mermaid 图表语法 |

参考资源


文档生成日期: 2026-03-06