Claude Code Subagent 创建指南
1. 什么是 Subagent 以及使用场景
1.1 定义
Subagent(子代理)是 Claude Code 中的专业化 AI 助手,用于处理特定类型的任务。每个 Subagent 在独立的上下文窗口中运行,拥有自定义的系统提示词、特定的工具访问权限和独立的权限设置。
1.2 核心优势
| 优势 | 说明 |
|---|---|
| 上下文隔离 | 探索和实现操作不会污染主对话的上下文 |
| 能力约束 | 可以限制 Subagent 能使用的工具集 |
| 配置复用 | 通过用户级 Subagent 在项目间共享配置 |
| 行为专业化 | 为特定领域提供聚焦的系统提示词 |
| 成本控制 | 将任务路由到更快、更便宜的模型(如 Haiku) |
1.3 典型使用场景
- 代码审查 - 创建只读代理审查代码质量和安全性
- 调试问题 - 创建能够分析和修复问题的代理
- 数据分析 - 创建专注于 SQL 和数据查询的代理
- 文档探索 - 创建快速搜索和理解代码库的代理
- 测试运行 - 隔离测试输出,避免消耗主对话上下文
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
然后选择:
- Create new agent
- 选择作用域(User-level 或 Project-level)
- 选择 Generate with Claude 或手动编写
- 选择工具权限
- 选择模型
- 选择颜色标识
- 保存
方法二:手动创建文件
# 用户级 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 | 否 | 模型选择:sonnet、opus、haiku、inherit |
permissionMode | 否 | 权限模式:default、acceptEdits、dontAsk、bypassPermissions、plan |
maxTurns | 否 | 最大代理轮次 |
skills | 否 | 预加载的技能列表 |
mcpServers | 否 | 可用的 MCP 服务器 |
hooks | 否 | 生命周期钩子 |
memory | 否 | 持久化内存作用域:user、project、local |
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 配置解析
| 配置项 | 值 | 说明 |
|---|---|---|
name | claude-code-tutor | 唯一标识符 |
description | 详细描述 | 定义何时触发此代理,包含关键词匹配 |
model | sonnet | 使用 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 设计原则
- 专注单一职责 - 每个 Subagent 应该擅长一项特定任务
- 编写详细描述 - Claude 依赖 description 决定何时委托
- 限制工具权限 - 只授予必要的权限以增强安全性
- 版本控制共享 - 项目级 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