5 分钟上手 Claude 自定义 Subagents

5 分钟上手 Claude 自定义 Subagents

深入了解如何创建、管理和优化你的自定义 AI 助手

前言

Claude Code 的 Subagents(子代理)是一个强大的功能,它允许你创建专门处理特定类型任务的 AI 助手。通过自定义 Subagents,你可以将重复性工作自动化,让不同专业领域的 AI 专家帮你处理特定任务,从而大幅提升开发效率。

本文将详细介绍如何创建自定义 Subagents,并分享来自官方文档和社区的最佳实践。


什么是 Subagent?

Subagent 是 Claude Code 中的专业化 AI 助手概念。每个 Subagent 运行在独立的上下文窗口中,拥有:

  • 自定义系统提示词 --- 针对特定领域的专业化指令
  • 特定工具访问权限 --- 细粒度的能力控制
  • 独立的权限设置 --- 可自定义权限模式
  • 可选的模型选择 --- 可使用 Opus、Sonnet 或 Haiku

核心价值:

价值 说明
保护主上下文 将探索、分析等操作隔离在主对话之外
强制约束 限制 Subagent 可用的工具,防止误操作
跨项目复用 用户级 Subagent 在所有项目中可用
行为专精 针对特定领域使用聚焦的系统提示词
成本控制 可选择更快的模型(如 Haiku)处理简单任务

创建 Subagent 的三种方式

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

在 Claude Code 中直接运行:

bash 复制代码
/agents

这会打开交互式界面,让你创建、查看、编辑和删除 Subagents。

方式二:手动创建 Markdown 文件

Subagent 本质上是一个带有 YAML frontmatter 的 Markdown 文件:

markdown 复制代码
---
name: my-subagent
description: 描述 Claude 何时应该委托任务给这个 Subagent
tools: ["Read", "Grep", "Glob"]
model: sonnet
---

你的系统提示词内容...

方式三:CLI 标志(临时会话)

bash 复制代码
claude --agents '{
  "temp-agent": {
    "description": "临时使用的 Subagent",
    "prompt": "你是一个...",
    "tools": ["Read", "Bash"],
    "model": "sonnet"
  }
}'

Subagent 文件格式详解

文件位置与优先级

位置 作用范围 优先级 说明
--agents CLI 标志 当前会话 1(最高) 临时使用
.claude/agents/ 当前项目 2 可纳入版本控制
~/.claude/agents/ 所有项目 3 个人专用
插件的 agents/ 插件启用处 4(最低) 插件提供

最佳实践:

  • 项目特定的 Subagent 放在 .claude/agents/,可与团队共享
  • 个人偏好的 Subagent 放在 ~/.claude/agents/

YAML Frontmatter 完整字段

yaml 复制代码
---
name: code-reviewer                    # 唯一标识符(必填),使用小写字母和连字符
description: 专家代码审查员...         # 描述(必填),决定何时自动委托
tools: ["Read", "Grep", "Glob", "Bash"]  # 允许的工具列表(可选)
model: opus                            # 使用的模型:sonnet/opus/haiku/inherit
permissionMode: default                # 权限模式:default/acceptEdits/dontAsk/bypassPermissions
maxTurns: 20                          # 最大 agentic 轮次
skills: ["tdd", "security-review"]    # 启动时加载的 Skills
mcpServers: {}                         # MCP 服务器配置
hooks: {}                              # 生命周期钩子
memory: project                        # 持久化记忆:user/project/local
background: false                      # 是否始终后台运行
isolation: worktree                    # 是否在临时 git worktree 中运行
---

字段详解:

字段 必填 说明 示例
name 唯一标识符 code-reviewer, security-expert
description 触发条件描述 Use PROACTIVELY when 用户请求代码审查
tools 工具白名单 ["Read", "Grep"]
model 指定模型 sonnet / opus / haiku / inherit
permissionMode 权限模式 default / bypassPermissions
maxTurns 最大轮次 20
skills 加载的技能 ["tdd", "vue"]
memory 记忆范围 user / project / local
background 后台运行 true
isolation 隔离模式 worktree

模型选择策略

yaml 复制代码
# 处理复杂架构决策 - 使用 Opus
model: opus

# 平衡能力与成本 - 使用 Sonnet
model: sonnet

# 快速搜索和分析 - 使用 Haiku
model: haiku

# 继承父对话的模型
model: inherit

建议:

  • 复杂推理任务 → opus
  • 常规代码任务 → sonnet
  • 快速搜索/分析 → haiku

实战案例:创建专业 Subagent

案例 1:代码审查专家

markdown 复制代码
---
name: code-reviewer
description: 专家代码审查员。代码修改后主动使用 MUST BE USED for all code changes.
tools: ["Read", "Grep", "Glob", "Bash"]
model: opus
---

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 simple and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented

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

## Security Checks (CRITICAL)

- Hardcoded credentials (API keys, passwords, tokens)
- SQL injection risks (string concatenation in queries)
- XSS vulnerabilities (unescaped user input)

## Approval Criteria

- ✅ Approve: No CRITICAL or HIGH issues
- ⚠️ Warning: MEDIUM issues only
- ❌ Block: CRITICAL or HIGH issues found

案例 2:规划专家

markdown 复制代码
---
name: planner
description: 复杂功能实现和重构的规划专家。用户请求功能实现、架构变更或复杂重构时自动激活。
tools: ["Read", "Grep", "Glob"]
model: opus
---

You are an expert planning specialist focused on creating comprehensive, actionable implementation plans.

## Planning Process

### 1. Requirements Analysis
- Understand the feature request completely
- Ask clarifying questions if needed
- Identify success criteria

### 2. Architecture Review
- Analyze existing codebase structure
- Identify affected components

### 3. Step Breakdown
Create detailed steps with:
- Clear, specific actions
- File paths and locations
- Dependencies between steps

### 4. Implementation Order
- Prioritize by dependencies
- Enable incremental testing

## Plan Format

Provide plans in this format:
- Overview (2-3 sentence summary)
- Requirements list
- Implementation Steps (phased)
- Testing Strategy
- Risks & Mitigations
- Success Criteria (checklist)

案例 3:TDD 指导专家

markdown 复制代码
---
name: tdd-guide
description: 测试驱动开发专家。新功能开发、bug 修复或重构时主动使用。
tools: ["Read", "Write", "Edit", "Bash", "Grep"]
model: opus
---

You are a TDD (Test-Driven Development) specialist enforcing write-tests-first methodology.

## Workflow

1. **RED** - Write test first, it should FAIL
2. **GREEN** - Write minimal implementation to pass tests
3. **REFACTOR** - Improve code while keeping tests passing
4. **VERIFY** - Ensure 80%+ test coverage

## Test Types Required

1. **Unit Tests** - Individual functions, utilities, components
2. **Integration Tests** - API endpoints, database operations
3. **E2E Tests** - Critical user flows with Playwright

## Mandatory Coverage: 80%+

Before marking work complete:
- [ ] Unit tests cover all functions
- [ ] Integration tests cover key flows
- [ ] E2E tests cover critical paths
- [ ] Edge cases tested

案例 4:安全审查专家

markdown 复制代码
---
name: security-reviewer
description: 安全漏洞检测和修复专家。处理用户输入、认证、API 端点或敏感数据时主动使用。
tools: ["Read", "Grep", "Glob", "Bash"]
model: opus
---

You are a security vulnerability detection and remediation specialist.

## OWASP Top 10 Checks (Mandatory)

- [ ] A01:2021 - Broken Access Control
- [ ] A02:2021 - Cryptographic Failures
- [ ] A03:2021 - Injection
- [ ] A04:2021 - Insecure Design
- [ ] A05:2021 - Security Misconfiguration
- [ ] A06:2021 - Vulnerable Components
- [ ] A07:2021 - Auth Failures
- [ ] A08:2021 - Data Integrity Failures
- [ ] A09:2021 - Logging Failures
- [ ] A10:2021 - SSRF

## Vulnerability Patterns to Check

### Hardcoded Secrets
```typescript
// ❌ Bad
const apiKey = "sk-abc123"

// ✅ Good
const apiKey = process.env.API_KEY

SQL Injection

typescript 复制代码
// ❌ Bad
db.query(`SELECT * FROM users WHERE id = ${userId}`)

// ✅ Good
db.query('SELECT * FROM users WHERE id = $1', [userId])

Report Format

For each vulnerability:

  • Severity: CRITICAL/HIGH/MEDIUM/LOW
  • Location: file:line
  • Description: what the issue is
  • Proof: code showing the vulnerability
  • Fix: how to remediate
yaml 复制代码
---

## 工具权限配置模式

### 只读型 Subagent

```yaml
tools: ["Read", "Grep", "Glob"]
# 或
tools: ["Read", "Grep", "Glob", "Bash"]

适用于:代码审查、规划、安全分析、数据审查

可修改型 Subagent

yaml 复制代码
tools: ["Read", "Write", "Edit", "Bash", "Grep", "Glob"]

适用于:Bug 修复、重构、测试编写

构建/编译型 Subagent

yaml 复制代码
tools: ["Read", "Write", "Edit", "Bash", "Grep", "Glob"]
# 专注构建工具

适用于:构建错误修复、编译问题排查


调用 Subagent 的方式

1. 自然语言触发

复制代码
帮我审查一下刚才修改的代码

Claude 会根据 description 自动判断是否委托给 code-reviewer

2. @-提及(强制指定)

python 复制代码
@"code-reviewer" 帮我检查这段代码

3. 技能调用

bash 复制代码
/code-reviewer

4. 全会话模式

bash 复制代码
claude --agent code-reviewer

高级特性

1. 持久化记忆(Memory)

通过 memory 字段让 Subagent 跨会话学习:

yaml 复制代码
memory: user  # ~/.claude/agent-memory/<name>/
memory: project  # .claude/agent-memory/<name>/
memory: local  # .claude/agent-memory-local/<name>/

用途:

  • user --- 跨项目的学习
  • project --- 项目特定,可共享
  • local --- 本地私有

2. Hooks(钩子)

yaml 复制代码
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate.sh"
  PostToolUse:
    - matcher: "Edit|Write"
      hooks:
        - type: command
          command: "./scripts/format.sh"

3. 后台运行

yaml 复制代码
background: true  # 始终后台运行

或使用 Ctrl+B 将前台任务转为后台。

4. Git Worktree 隔离

yaml 复制代码
isolation: worktree  # 在临时 worktree 中运行

最佳实践

1. Description 编写技巧

yaml 复制代码
# ❌ 模糊 - Claude 无法准确判断何时委托
description: 代码审查

# ✅ 精确 - 包含触发条件
description: 专家代码审查员。代码修改后主动使用。MUST BE USED for all code changes.

# ✅ 包含 "PROACTIVELY" 鼓励自动委托
description: 安全审查专家。处理用户输入、认证、API端点或敏感数据时 PROACTIVELY 使用。

2. 工具权限最小化

yaml 复制代码
# ❌ 过度授权
tools: ["*"]  # 所有工具

# ✅ 最小权限
tools: ["Read", "Grep"]  # 只读
tools: ["Read", "Edit", "Bash"]  # 编辑 + 命令

3. 模型选择原则

任务类型 推荐模型 原因
代码审查 sonnet 平衡质量与成本
安全分析 opus 需要深度推理
快速搜索 haiku 简单任务不需要昂贵模型
复杂规划 opus 需要深度思考

4. Subagent 不宜过多

  • 3-5 个 核心 Subagent 是理想数量
  • 太多 Subagent 会导致混淆,难以选择
  • 每个 Subagent 应该职责单一

5. 职责单一原则

yaml 复制代码
# ❌ 多职责混合
name: coder
description: 编写代码、审查代码、修复 bug

# ✅ 单一职责
name: code-writer
name: code-reviewer
name: bug-fixer

6. 善用 PROACTIVELY

在 description 中加入 PROACTIVELY when 让 Claude 自动判断何时使用:

yaml 复制代码
description: 代码审查专家。代码修改后 PROACTIVELY 使用。
description: 构建错误修复专家。构建失败时自动激活。
description: 安全审查专家。处理认证或 API 时 PROACTIVELY 使用。

常见陷阱与解决方案

陷阱 1:Description 过于模糊

yaml 复制代码
# 问题
description: 代码相关任务

# 解决
description: 代码审查专家。代码修改后立即使用,重点检查安全和质量。

陷阱 2:忘记 Subagent 不继承 Skills

yaml 复制代码
# 需要显式声明
skills: ["tdd", "vue", "security-review"]

陷阱 3:过度使用 Subagent

场景 建议
频繁迭代修改 留在主对话
快速简单任务 不需要 Subagent
多步骤复杂流程 考虑 Subagent 链

陷阱 4:忽略上下文管理

Subagent 也有上下文限制:

  • 容量达到 95% 时自动压缩
  • 长任务考虑拆分

陷阱 5:后台 Subagent 权限问题

后台 Subagent 需要预先获取权限

bash 复制代码
# 在启动后台任务前确保权限已批准

进阶技巧

1. 并行 Subagent 研究

生成多个 Subagent 同时调查不同领域:

markdown 复制代码
请同时启动 3 个 Subagent:
1. 数据库专家 - 优化查询性能
2. 安全专家 - 检查认证流程
3. 性能专家 - 分析性能瓶颈

2. 链式 Subagent

多步骤工作流可以串联:

markdown 复制代码
1. planner → 规划
2. code-writer → 实现
3. code-reviewer → 审查
4. tdd-guide → 测试

3. 恢复 Subagent

虽然每次调用创建新实例,但可以:

erlang 复制代码
继续之前的代码审查,上次的审查结果在...

4. 项目特定 Subagent

.claude/agents/ 中创建项目专用 Subagent:

yaml 复制代码
# .claude/agents/supabase-reviewer.md
---
name: supabase-reviewer
description: Supabase 专家。检查 RLS 策略、数据库操作和 Supabase 客户端使用。
tools: ["Read", "Grep", "Glob"]
model: opus
---

You are a Supabase specialist...

社区资源推荐

GitHub 仓库

官方文档


总结

自定义 Subagents 是 Claude Code 最强大的功能之一。通过本文,你应该已经掌握:

  1. 创建方式 --- /agents 命令、手动创建、CLI 标志
  2. 文件格式 --- YAML frontmatter + Markdown 提示词
  3. 配置选项 --- 工具权限、模型选择、持久化记忆、Hooks
  4. 最佳实践 --- 描述编写、权限控制、模型选择
  5. 常见陷阱 --- 以及如何避免

开始创建你的第一个 Subagent 吧!一个好的起点是:

yaml 复制代码
---
name: code-reviewer
description: 代码审查专家。代码修改后主动使用。
tools: ["Read", "Grep", "Glob", "Bash"]
model: sonnet
---

You are a senior code reviewer...

记住:好的 Subagent 是职责单一、描述清晰、权限恰当的

Happy Coding! 🚀

相关推荐
rainy雨2 小时前
精益生产系统功能拆解:利用精益生产解决多品种小批量场景下的库存积压难题
大数据·人工智能·精益工程
白鲸开源2 小时前
SeaTunnel × Gravitino:Schema URL 驱动的表结构自动感知方案
大数据·人工智能·开源
Narrastory2 小时前
明日香 - Pytorch 快速入门保姆级教程(七)
人工智能·pytorch·深度学习
说实话起个名字真难啊2 小时前
深入学习openclaw之记忆基础
人工智能·学习·openclaw
腾视科技TENSORTEC2 小时前
算力驱动智慧零售|腾视科技AI边缘算力盒子 —— 无人商超全场景解决方案重磅发布
人工智能·ai·零售·ainas·无人商超·ai边缘算力盒子·aibox
骥龙2 小时前
第四篇:部署阶段安全加固——从裸奔到生产级防护
运维·网络·人工智能·安全
小J听不清2 小时前
CSS 浮动(float)全解析:布局 / 文字环绕 / 清除浮动
前端·javascript·css·html·css3
wuhen_n2 小时前
生产环境极致优化:拆包、图片压缩、Gzip/Brotli 完全指南
前端·javascript·vue.js
NikoAI编程2 小时前
Claude Code Skill 实战:从「能用」到「好用」
人工智能·ai编程·claude