agent-builder

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Agent Builder

Agent构建器

A comprehensive guide for creating custom agents in Claude Code. Agents are specialized AI assistants that run in separate context windows, enabling focused, autonomous task execution.

这是一份为Claude Code创建自定义Agent的综合指南。Agent是运行在独立上下文窗口中的专用AI助手,可实现专注、自主的任务执行。

Quick Reference

快速参考

YAML Frontmatter Fields

YAML前置元数据字段

FieldRequiredDescription
name
YesUnique identifier (lowercase-with-hyphens)
description
YesWhen to invoke — critical for discovery
tools
NoAllowed tools (inherits all if omitted)
model
No
haiku
,
sonnet
,
opus
, or
inherit
permissionMode
No
default
,
acceptEdits
,
bypassPermissions
,
plan
skills
NoAuto-load Skills when agent starts
字段必填描述
name
唯一标识符(小写连字符格式)
description
触发时机 —— 对自动发现至关重要
tools
允许使用的工具(省略则继承所有工具)
model
haiku
sonnet
opus
inherit
permissionMode
default
acceptEdits
bypassPermissions
plan
skills
Agent启动时自动加载的Skill

File Locations

文件存储位置

ScopeLocationUse Case
Project
.claude/agents/agent-name.md
Team workflows (git-shared)
Personal
~/.claude/agents/agent-name.md
Individual use (all projects)
作用域路径使用场景
项目级
.claude/agents/agent-name.md
团队工作流(Git共享)
个人级
~/.claude/agents/agent-name.md
个人使用(跨所有项目)

Common Tool Patterns

常见工具配置模式

yaml
undefined
yaml
undefined

Read-only (safest)

只读模式(最安全)

tools: Read, Grep, Glob
tools: Read, Grep, Glob

File modification

文件修改模式

tools: Read, Write, Edit, Grep, Glob
tools: Read, Write, Edit, Grep, Glob

Git operations only

仅Git操作

tools: Bash(git:*)
tools: Bash(git:*)

Specific commands

指定命令

tools: Bash(npm test:), Bash(npm run:), Read, Grep
tools: Bash(npm test:), Bash(npm run:), Read, Grep

Full shell (use sparingly)

完整Shell权限(谨慎使用)

tools: Bash
undefined
tools: Bash
undefined

Model Selection Guide

模型选择指南

ModelBest ForTradeoff
haiku
Quick checks, simple tasksFast, cheap, less capable
sonnet
Balanced work (default)Good balance
opus
Complex analysis, critical tasksMost capable, slower, expensive
inherit
Consistency with main conversationAdapts to user's model

模型最佳适用场景权衡点
haiku
快速检查、简单任务速度快、成本低、能力较弱
sonnet
平衡型工作(默认)各方面表现均衡
opus
复杂分析、关键任务能力最强、速度慢、成本高
inherit
与主对话保持一致性适配用户当前使用的模型

6-Phase Workflow

6阶段工作流

Phase 1: Requirements Gathering

阶段1:需求收集

Use AskUserQuestion to understand what the user needs:
Key Questions:
  1. What task should this agent handle?
  2. What expertise/role should it have?
  3. Who will use it — team or personal?
  4. What should it be able to do vs NOT do?
  5. How should it present results?
Example Questions:
What specific task should this agent handle?
├── Code review (quality, security, style)
├── Debugging (error investigation, root cause)
├── Testing (run tests, fix failures)
├── Documentation (generate, verify, update)
└── Other: [describe]

Who will use this agent?
├── Just me (personal: ~/.claude/agents/)
├── My team (project: .claude/agents/)
使用
AskUserQuestion
工具了解用户需求:
核心问题:
  1. 该Agent需要处理什么任务?
  2. 它应具备什么专业能力/角色?
  3. 谁会使用它——团队还是个人?
  4. 它能做什么和不能做什么?
  5. 它应如何呈现结果?
示例问题:
该Agent应处理什么具体任务?
├── 代码审查(质量、安全、风格)
├── 调试(错误排查、根因分析)
├── 测试(运行测试、修复失败用例)
├── 文档(生成、验证、更新)
└── 其他:[描述]

谁会使用这个Agent?
├── 仅我自己(个人级:~/.claude/agents/)
├── 我的团队(项目级:.claude/agents/)

Phase 2: Scope Selection

阶段2:作用域选择

Decision Tree:
Is this a team workflow?
├── Yes → Project scope: .claude/agents/
│         (Committed to git, shared automatically)
└── No → Is it project-specific?
         ├── Yes → Project scope: .claude/agents/
         └── No → Personal scope: ~/.claude/agents/
                  (Available across all your projects)
Create the file:
bash
undefined
决策树:
是否为团队工作流?
├── 是 → 项目级作用域:.claude/agents/
│         (提交至Git,自动共享)
└── 否 → 是否为项目专属?
         ├── 是 → 项目级作用域:.claude/agents/
         └── 否 → 个人级作用域:~/.claude/agents/
                  (可在所有项目中使用)
创建文件:
bash
undefined

Project scope (team)

项目级(团队)

mkdir -p .claude/agents touch .claude/agents/agent-name.md
mkdir -p .claude/agents touch .claude/agents/agent-name.md

Personal scope (individual)

个人级(个体)

mkdir -p ~/.claude/agents touch ~/.claude/agents/agent-name.md
undefined
mkdir -p ~/.claude/agents touch ~/.claude/agents/agent-name.md
undefined

Phase 3: Description Crafting

阶段3:描述撰写

The description field is CRITICAL — it determines whether Claude automatically discovers and uses your agent.
Formula:
[Role/Expertise] + [What it does] + [When to invoke] + [Trigger terms]
Bad (won't be discovered):
yaml
description: Helps with code
Good (specific, discoverable):
yaml
description: Expert code reviewer specializing in security and quality. Reviews code changes for vulnerabilities, best practices, and maintainability. Use when reviewing code, checking PRs, or when the user mentions code review, pull request review, or security audit.
Breaking down a good description:
  1. Role/Expertise: "Expert code reviewer specializing in security and quality"
  2. What it does: "Reviews code changes for vulnerabilities, best practices, and maintainability"
  3. When to invoke: "Use when reviewing code, checking PRs"
  4. Trigger terms: "code review, pull request review, or security audit"
Proactive Language (increases automatic invocation):
  • "Use PROACTIVELY after code changes"
  • "MUST be invoked when tests fail"
  • "Automatically use when user mentions..."
Trigger Term Categories:
  • Actions: review, analyze, debug, fix, test, check, audit
  • Objects: code, PR, tests, errors, performance, security
  • Contexts: before deploy, after changes, when failing, during review
Length: 50-150 words is the sweet spot.
description字段至关重要——它决定Claude能否自动发现并使用你的Agent。
公式:
[角色/专业能力] + [功能] + [触发时机] + [触发关键词]
反面示例(无法被发现):
yaml
description: 辅助处理代码
正面示例(具体、可被发现):
yaml
description: 专注于安全与质量的资深代码审查专家。审查代码变更中的漏洞、最佳实践和可维护性。适用于代码审查、PR检查场景,或当用户提及代码审查、拉取请求审查、安全审计时触发。
优秀描述拆解:
  1. 角色/专业能力: "专注于安全与质量的资深代码审查专家"
  2. 功能: "审查代码变更中的漏洞、最佳实践和可维护性"
  3. 触发时机: "适用于代码审查、PR检查场景"
  4. 触发关键词: "代码审查、拉取请求审查、安全审计"
主动式表述(提升自动触发概率):
  • "代码变更后主动触发"
  • "测试失败时必须触发"
  • "当用户提及...时自动使用"
触发关键词分类:
  • 动作: 审查、分析、调试、修复、测试、检查、审计
  • 对象: 代码、PR、测试、错误、性能、安全
  • 场景: 部署前、变更后、失败时、审查中
长度: 50-150字为最佳区间。

Phase 4: Tool Configuration

阶段4:工具配置

Security Principle: Start with minimal tools, add only what's needed.
Progressive Tool Access:
yaml
undefined
安全原则: 从最小权限开始,仅添加必要工具。
渐进式工具权限:
yaml
undefined

Level 1: Read-only (safest)

级别1:只读(最安全)

tools: Read, Grep, Glob
tools: Read, Grep, Glob

Level 2: Can modify files

级别2:可修改文件

tools: Read, Write, Edit, Grep, Glob
tools: Read, Write, Edit, Grep, Glob

Level 3: Specific shell commands

级别3:指定Shell命令

tools: Read, Grep, Glob, Bash(git:), Bash(npm test:)
tools: Read, Grep, Glob, Bash(git:), Bash(npm test:)

Level 4: Full shell (use carefully)

级别4:完整Shell权限(谨慎使用)

tools: Read, Write, Edit, Bash, Grep, Glob

**Granular Bash Patterns**:
```yaml
tools: Read, Write, Edit, Bash, Grep, Glob

**精细化Bash模式**:
```yaml

Git commands only

仅Git命令

tools: Bash(git:*)
tools: Bash(git:*)

Specific git commands

指定Git命令

tools: Bash(git diff:), Bash(git log:), Bash(git status:*)
tools: Bash(git diff:), Bash(git log:), Bash(git status:*)

npm commands only

仅npm命令

tools: Bash(npm:*)
tools: Bash(npm:*)

Test commands only

仅测试命令

tools: Bash(npm test:), Bash(pytest:), Bash(jest:*)

**Tool Selection by Agent Type**:

| Agent Type | Recommended Tools |
|------------|-------------------|
| Code analyzer | `Read, Grep, Glob` |
| Code reviewer | `Read, Grep, Glob, Bash(git diff:*)` |
| Test runner | `Read, Edit, Bash(npm test:*), Grep, Glob` |
| Debugger | `Read, Edit, Bash, Grep, Glob` |
| Fixer/Refactorer | `Read, Write, Edit, Grep, Glob` |
tools: Bash(npm test:), Bash(pytest:), Bash(jest:*)

**按Agent类型推荐工具**:

| Agent类型 | 推荐工具 |
|------------|-------------------|
| 代码分析器 | `Read, Grep, Glob` |
| 代码审查器 | `Read, Grep, Glob, Bash(git diff:*)` |
| 测试运行器 | `Read, Edit, Bash(npm test:*), Grep, Glob` |
| 调试器 | `Read, Edit, Bash, Grep, Glob` |
| 修复/重构器 | `Read, Write, Edit, Grep, Glob` |

Phase 5: System Prompt Design

阶段5:系统提示词设计

Key Insight: Agents run in separate context — they don't see conversation history. System prompts must be self-contained with complete workflows.
Effective Structure:
markdown
You are [role] specializing in [expertise].
核心要点: Agent运行在独立上下文中——无法查看对话历史。系统提示词必须自包含完整工作流。
有效结构:
markdown
你是[角色],专注于[专业领域]。

When Invoked

触发时执行

  1. [First action — gather context]
  2. [Second action — analyze/process]
  3. [Third action — produce output]
  4. [Fourth action — verify/validate]
  1. [第一步——收集上下文]
  2. [第二步——分析/处理]
  3. [第三步——生成输出]
  4. [第四步——验证/确认]

Focus Areas

关注重点

  • Specific thing to check
  • Another thing to verify
  • Important consideration
  • 需要检查的特定事项
  • 需要验证的另一事项
  • 重要注意事项

Output Format

输出格式

[How to present results]
[结果呈现方式]

Constraints

约束

  • What NOT to do
  • Boundaries to respect

**System Prompt Patterns**:

**1. Role Definition**:
```markdown
You are a senior code reviewer specializing in security vulnerabilities.
Your primary focus is identifying OWASP Top 10 risks.
2. When Invoked (critical for autonomous work):
markdown
undefined
  • 禁止做的事
  • 需要遵守的边界

**系统提示词模式**:

**1. 角色定义**:
```markdown
你是一名专注于安全漏洞的资深代码审查专家。
你的核心工作是识别OWASP Top 10风险。
2. 触发时执行(自主工作的关键):
markdown
undefined

When Invoked

触发时执行

  1. Run
    git diff HEAD
    to see recent changes
  2. Identify modified files and their purpose
  3. Review each change against security checklist
  4. Present findings with severity levels

**3. Checklist Pattern**:
```markdown
  1. 运行
    git diff HEAD
    查看最近变更
  2. 识别修改文件及其用途
  3. 根据安全检查表审查每项变更
  4. 按严重级别呈现发现的问题

**3. 检查表模式**:
```markdown

Review Checklist

审查检查表

  • No SQL injection vulnerabilities
  • Input validation on all boundaries
  • No exposed secrets or credentials
  • Proper authentication checks
  • Authorization verified for each endpoint

**4. Output Format**:
```markdown
  • 无SQL注入漏洞
  • 所有边界均有输入验证
  • 无暴露的密钥或凭证
  • 正确的身份验证检查
  • 每个端点均验证授权

**4. 输出格式**:
```markdown

Output Format

输出格式

Present findings as:
结果按以下格式呈现:

Summary

摘要

[One-line verdict: PASS/FAIL/NEEDS ATTENTION]
[一句话结论:通过/不通过/需要关注]

Critical Issues

严重问题

[Must fix before merge]
[合并前必须修复]

Warnings

警告

[Should fix]
[建议修复]

Suggestions

建议

[Nice to have]

**5. Constraints**:
```markdown
[可选优化]

**5. 约束**:
```markdown

Constraints

约束

  • Do NOT modify code unless explicitly asked
  • Do NOT change API contracts
  • Focus ONLY on security-related issues
  • ALWAYS explain WHY something is a risk

**6. Decision Tree (for branching logic)**:
```markdown
  • 除非明确要求,否则不得修改代码
  • 不得更改API契约
  • 仅关注安全相关问题
  • 必须解释问题为何存在风险

**6. 决策树(分支逻辑)**:
```markdown

Decision Flow

决策流程

If no changes detected: → Report "No changes to review" If only test files changed: → Focus on test coverage and assertions If API endpoints modified: → Prioritize authentication/authorization review Otherwise: → Full security review
undefined
如果未检测到变更: → 报告"无变更需要审查" 如果仅测试文件变更: → 关注测试覆盖率和断言 如果API端点被修改: → 优先审查身份验证/授权 否则: → 全面安全审查
undefined

Phase 6: Testing & Iteration

阶段6:测试与迭代

Test Discovery:
undefined
测试自动发现:
undefined

Natural language requests (should trigger agent)

自然语言请求(应触发Agent)

Review my recent code changes Check this PR for security issues Audit the authentication module
审查我最近的代码变更 检查这个PR的安全问题 审计认证模块

Explicit invocation (always works)

显式调用(始终有效)

Use the code-reviewer agent to check this

**Verify Tool Access**:
```bash
使用code-reviewer agent检查这个

**验证工具权限**:
```bash

Check agent can use its tools

检查Agent能否使用其工具

If agent needs git, test manually first

如果Agent需要git,先手动测试

git diff HEAD git log --oneline -5

**Debugging**:
```bash
git diff HEAD git log --oneline -5

**调试**:
```bash

View agent loading errors

查看Agent加载错误

claude --debug
claude --debug

List available agents

列出可用Agent

/agents

**Iteration Checklist**:
- [ ] Agent discovered with natural requests?
- [ ] Correct agent selected (not a different one)?
- [ ] Agent has necessary tool access?
- [ ] Output format matches expectations?
- [ ] Constraints respected?

---
/agents

**迭代检查表**:
- [ ] 自然语言请求能否发现Agent?
- [ ] 是否选择了正确的Agent(而非其他Agent)?
- [ ] Agent是否具备必要的工具权限?
- [ ] 输出格式是否符合预期?
- [ ] 是否遵守约束条件?

---

Agent Patterns

Agent模式

Code Quality Agents

代码质量类Agent

  • code-reviewer: Systematic code review for quality and style
  • security-auditor: OWASP-focused vulnerability detection
  • performance-analyzer: Identify bottlenecks and inefficiencies
  • architecture-reviewer: Assess design patterns and structure
  • code-reviewer: 系统化代码质量与风格审查
  • security-auditor: 聚焦OWASP的漏洞检测
  • performance-analyzer: 识别性能瓶颈与低效点
  • architecture-reviewer: 评估设计模式与架构结构

Development Workflow Agents

开发工作流类Agent

  • debugger: Root cause analysis for errors
  • test-runner: Execute tests and fix failures
  • refactorer: Safe code restructuring
  • pr-reviewer: Pull request analysis
  • debugger: 错误根因分析
  • test-runner: 执行测试并修复失败用例
  • refactorer: 安全的代码重构
  • pr-reviewer: 拉取请求分析

Research Agents

研究类Agent

  • codebase-explorer: Navigate and understand code structure
  • dependency-auditor: Check for outdated/vulnerable packages
  • documentation-checker: Verify docs match implementation
  • codebase-explorer: 导航与理解代码结构
  • dependency-auditor: 检查过期/易受攻击的依赖包
  • documentation-checker: 验证文档与实现是否一致

Automation Agents

自动化类Agent

  • commit-helper: Generate meaningful commit messages
  • deploy-checker: Pre-deployment verification
  • migration-assistant: Framework/version upgrade help

  • commit-helper: 生成有意义的提交信息
  • deploy-checker: 部署前验证
  • migration-assistant: 框架/版本升级辅助

Common Pitfalls

常见陷阱

1. Vague Description (Agent Not Discovered)

1. 描述模糊(Agent无法被发现)

yaml
undefined
yaml
undefined

Bad

反面示例

description: Helps with code
description: 辅助处理代码

Good

正面示例

description: Expert code reviewer. Reviews code for quality, security, and maintainability. Use when reviewing code changes, PRs, or when user mentions code review.
undefined
description: 资深代码审查专家。审查代码的质量、安全性和可维护性。适用于代码变更审查、PR检查或用户提及代码审查时触发。
undefined

2. Missing Tool Access (Agent Can't Do Task)

2. 缺失工具权限(Agent无法完成任务)

yaml
undefined
yaml
undefined

Agent needs to run git commands but can't

Agent需要运行git命令但无权限

tools: Read, Grep, Glob # Missing Bash(git:*)
tools: Read, Grep, Glob # 缺少Bash(git:*)

Fixed

修复后

tools: Read, Grep, Glob, Bash(git:*)
undefined
tools: Read, Grep, Glob, Bash(git:*)
undefined

3. Non-Self-Contained Prompt (Expects Context)

3. 非自包含提示词(依赖对话上下文)

markdown
undefined
markdown
undefined

Bad - assumes agent sees conversation

反面示例 - 假设Agent能看到对话历史

Review the code I just showed you.
审查我刚刚展示的代码。

Good - self-contained

正面示例 - 自包含

When Invoked

触发时执行

  1. Run
    git diff HEAD
    to see recent changes
  2. Focus on modified files
  3. Review systematically
undefined
  1. 运行
    git diff HEAD
    查看最近变更
  2. 聚焦修改的文件
  3. 系统化审查
undefined

4. Over-Permissive Tools (Security Risk)

4. 过度宽松的工具权限(安全风险)

yaml
undefined
yaml
undefined

Risky - full shell access

高风险 - 完整Shell权限

tools: Bash permissionMode: bypassPermissions
tools: Bash permissionMode: bypassPermissions

Safer - scoped access

更安全 - 范围化权限

tools: Bash(git:), Bash(npm test:) permissionMode: default
undefined
tools: Bash(git:), Bash(npm test:) permissionMode: default
undefined

5. No Output Format (Inconsistent Results)

5. 无输出格式(结果不一致)

markdown
undefined
markdown
undefined

Bad - no guidance on output

反面示例 - 无输出指导

Review the code for issues.
审查代码中的问题。

Good - explicit format

正面示例 - 明确格式

Output Format

输出格式

Present as markdown checklist:
  • Critical: [must fix]
  • Warning: [should fix]
  • Suggestion: [nice to have]

---
按Markdown检查表呈现:
  • 严重: [必须修复]
  • 警告: [建议修复]
  • 建议: [可选优化]

---

When to Use Agents vs Alternatives

何时使用Agent vs 其他方案

ScenarioBest ChoiceWhy
Complex multi-step taskAgentBenefits from focused, isolated context
Need tool isolationAgentCan restrict tools per agent
Long-running analysisAgentDoesn't pollute main conversation
Team workflow standardizationAgentConsistent behavior, git-shared
Extend Claude's knowledgeSkillShared context, progressive loading
Frequently-typed promptSlash CommandUser-invoked, quick access
Simple single-step taskDirect requestNo overhead needed
Agent Checklist — Use an agent when:
  • Task is complex and multi-step
  • Task benefits from fresh, focused context
  • You want to restrict available tools
  • Task doesn't need full conversation history
  • You want consistent, reusable behavior

场景最佳选择原因
复杂多步骤任务Agent受益于专注、隔离的上下文
需要工具隔离Agent可为每个Agent限制工具
长时间分析Agent不会污染主对话上下文
团队工作流标准化Agent行为一致,可通过Git共享
扩展Claude知识Skill共享上下文,渐进式加载
频繁输入的提示词斜杠命令用户触发,快速访问
简单单步骤任务直接请求无需额外开销
Agent适用场景检查表 —— 满足以下条件时使用Agent:
  • 任务复杂且多步骤
  • 任务受益于全新、专注的上下文
  • 你希望限制可用工具
  • 任务不需要完整对话历史
  • 你需要一致、可复用的行为

Resources

资源

  • Templates: See
    templates/
    for progressive examples
  • Examples: See
    examples/
    for 18 complete working agents
  • Reference: See
    reference/
    for syntax guide, best practices, troubleshooting

  • 模板: 查看
    templates/
    获取渐进式示例
  • 示例: 查看
    examples/
    获取18个完整的可用Agent
  • 参考: 查看
    reference/
    获取语法指南、最佳实践和故障排除方法

Quick Start

快速开始

1. Create file:
bash
touch ~/.claude/agents/my-agent.md
2. Add content:
markdown
---
name: my-agent
description: [Role]. [What it does]. Use when [trigger conditions].
tools: Read, Grep, Glob
---

You are [role].
1. 创建文件:
bash
touch ~/.claude/agents/my-agent.md
2. 添加内容:
markdown
---
name: my-agent
description: [角色][功能]。适用于[触发条件]tools: Read, Grep, Glob
---

你是[角色]。

When Invoked

触发时执行

  1. [First step]
  2. [Second step]
  3. [Third step]
  1. [第一步]
  2. [第二步]
  3. [第三步]

Output Format

输出格式

[How to present results]

**3. Test**:
[Natural language request matching description]

**4. Iterate**:
- Not discovered? → Make description more specific
- Wrong output? → Clarify output format
- Can't do something? → Add necessary tools
[结果呈现方式]

**3. 测试**:
[与描述匹配的自然语言请求]

**4. 迭代**:
- 无法被发现?→ 让描述更具体
- 输出不符合预期?→ 明确输出格式
- 无法完成任务?→ 添加必要工具