Skip to content

阶段性大项目:构建 PR 审查机器人 ​

综合运用进阶篇(Ch5-9)的所有知识。构建一个工具,使用并行 subagent 审查任意 GitHub PR 的安全、性能和代码质量 -- 然后发布结构化审查评论。

你将构建什么 ​

一个完整的 PR 审查系统:

  1. 接收 GitHub PR URL 作为输入
  2. 通过 GitHub MCP 获取 diff 和变更文件
  3. 并行启动三个审查 agent(安全、性能、质量)
  4. 将发现综合为一个结构化审查
  5. 将审查作为 GitHub PR 评论发布

这是一个真实工具。规模化团队使用完全相同的模式 -- 在每个 PR 上运行自动化多视角审查。完成后,你可以将它指向任何仓库中的任何 PR,在 3 分钟内获得专业级审查。

架构 ​

/review-pr https://github.com/user/repo/pull/42
  |
  v
Skill loads --> GitHub MCP fetches PR diff + files
  |
  v
Lead session creates review plan
  |
  +---> Security Agent (P0 findings, confidence >= 80%)
  |       tools: Read, Glob, Grep
  |
  +---> Performance Agent (N+1, missing pagination, etc.)
  |       tools: Read, Glob, Grep
  |
  +---> Quality Agent (code style, error handling, tests)
  |       tools: Read, Glob, Grep
  |
  v (all three complete)
  |
  Lead synthesizes --> structured review
  |
  v
  GitHub MCP posts review comment on the PR

前置条件 ​

  • 完成第 5-9 章
  • GitHub MCP 已配置,token 有 PR 读写权限
  • 一个 GitHub 仓库至少有一个 open PR(或创建测试 PR)

第一步:Hook 套件 (Ch5) ​

配置生产级 hook。

bash
mkdir -p ~/claude-demos/capstone-pr-bot && cd ~/claude-demos/capstone-pr-bot
git init && git branch -M main
mkdir -p .claude/{hooks,skills,agents}

cat > CLAUDE.md << 'EOF'
# PR Review Bot

## Project
A CLI tool and Claude Code skill that reviews GitHub PRs using parallel agents.

## Standards
- TypeScript with strict mode
- Conventional Commits
- No secrets in code — use environment variables
- Every finding needs file:line reference and confidence score
EOF

创建三个 hook:

Commit 质量门禁(来自 Demo 11):

bash
# Copy your commit-quality-gate.sh from Demo 11
# or create a new one that enforces Conventional Commits

危险命令拦截器(来自 Demo 12):

bash
# Copy your block-dangerous.sh from Demo 12

使用观察器(来自 Demo 14):

bash
# Copy your observe.sh from Demo 14

在 .claude/settings.json 中配置:

json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "bash .claude/hooks/commit-quality-gate.sh" },
          { "type": "command", "command": "bash .claude/hooks/block-dangerous.sh" }
        ]
      }
    ],
    "PostToolUse": [
      {
        "hooks": [
          { "type": "command", "command": "bash .claude/hooks/observe.sh" }
        ]
      }
    ]
  }
}

第二步:审查 Agent (Ch8) ​

创建三个专用审查 agent。

安全 agent (.claude/agents/security-reviewer.md):

  • 工具:Read, Glob, Grep(只读)
  • 聚焦:SQL 注入、XSS、鉴权绕过、数据泄露、密钥
  • 输出:P0-P3 严重程度,file:line,置信度 >= 80%
  • P0 发现需包含概念验证(Proof-of-Concept)

性能 agent (.claude/agents/performance-reviewer.md):

  • 工具:Read, Glob, Grep(只读)
  • 聚焦:N+1 查询、缺失分页、无界结果、阻塞 I/O
  • 输出:影响评级(High/Medium/Low),file:line

质量 agent (.claude/agents/quality-reviewer.md):

  • 工具:Read, Glob, Grep(只读)
  • 聚焦:错误处理、输入验证、测试覆盖、代码重复
  • 输出:P1-P3,具体修复建议

使用 Demo 22(安全扫描器)和 Demo 24(多视角审查)的模式。

第三步:/review-pr Skill (Ch6) ​

创建编排一切的主 skill。

bash
cat > .claude/skills/review-pr.md << 'SKILLEOF'
---
name: review-pr
description: "Review a GitHub PR with parallel security, performance, and quality agents"
user-invocable: true
context: fork
allowed-tools:
  - Read
  - Glob
  - Grep
  - Bash
  - Agent
---

# PR Review Bot

Review a GitHub Pull Request using three specialized agents.

## Input

PR reference: $ARGUMENTS
(accepts: URL like https://github.com/user/repo/pull/42, or owner/repo#42)

## Process

### Step 1: Fetch PR Data
Use GitHub MCP to get:
- PR title, description, author
- List of changed files
- Full diff

Parse the PR reference to extract owner, repo, and PR number.

### Step 2: Check Out the Code
If the repo is available locally, read the changed files directly.
Otherwise, use GitHub MCP to fetch file contents.

### Step 3: Parallel Review
Launch three agents simultaneously:

1. **security-reviewer**: Scan all changed files for vulnerabilities
2. **performance-reviewer**: Check for performance anti-patterns
3. **quality-reviewer**: Assess code quality and maintainability

### Step 4: Synthesize
Combine all three reports into a single review:

```markdown
# PR Review: [PR Title]

## Summary
[Overall assessment in 2-3 sentences]

## Verdict: APPROVE / REQUEST CHANGES / BLOCK

## Findings by Severity

### Critical (P0)
[From security and performance agents]

### Bugs (P1)
[From all three agents]

### Code Quality (P2)
[From quality agent]

### Style (P3)
[Nits from all agents]

## What's Good
[2-3 positive observations]

## Recommended Actions
1. [Most important fix]
2. [Second most important]
3. ...

---
Reviewed by: PR Review Bot (security + performance + quality agents)

Step 5: Post Review (Optional) ​

If the user says "post it", use GitHub MCP to add the review as a PR comment.

Rules ​

  • Never approve a PR with P0 findings
  • Every finding must have file:line and confidence >= 80%
  • "Consider improving" is not actionable — say exactly what to change
  • Include what the PR does RIGHT, not just what's wrong
  • If you can't fetch the PR data, tell the user why and stop SKILLEOF

## 第四步:MCP 集成 (Ch7)

确认 GitHub MCP 已配置:

```bash
# Verify GitHub MCP is set up
claude mcp list

# If not, add it
claude mcp add github -e GITHUB_PERSONAL_ACCESS_TOKEN -- npx -y @modelcontextprotocol/server-github

第五步:测试 ​

在真实 PR 上测试 ​

找到你仓库中的一个 PR(或创建一个测试 PR),然后:

bash
claude
/review-pr https://github.com/<your-username>/<your-repo>/pull/<number>

在已知有问题的 PR 上测试 ​

创建一个有意留有问题的 PR 来验证机器人能捕获:

bash
cd ~/claude-demos/capstone-pr-bot
git checkout -b feature/bad-code

# Create deliberately vulnerable code
cat > src/api.js << 'EOF'
app.get('/users', (req, res) => {
  // SQL injection
  const query = `SELECT * FROM users WHERE name = '${req.query.name}'`;
  // No pagination
  db.query(query).then(result => {
    // Returning password hashes
    res.json(result.rows);
  });
  // No error handling
});
EOF

git add -A && git commit -m "feat: add user endpoint"
git push -u origin feature/bad-code

# Create the PR
gh pr create --title "Add user endpoint" --body "New endpoint for listing users"

然后审查:

/review-pr <your-username>/<your-repo>#<pr-number>

预期发现:

  • P0:用户查询中的 SQL 注入
  • P1:列表端点无分页
  • P1:响应中暴露密码哈希
  • P1:无错误处理
  • P2:name 参数无输入验证

验收标准 ​

  • [ ] Hooks (Ch5):Commit 质量门禁拦截坏消息,危险命令被捕获
  • [ ] Skills (Ch6):/review-pr skill 可调用并编排完整工作流
  • [ ] MCP (Ch7):GitHub MCP 获取 PR 数据并能发布评论
  • [ ] Subagents (Ch8):三个审查 agent 以只读工具限制运行
  • [ ] Agent Teams (Ch9):Agent 并行运行,发现被综合为一份报告
  • [ ] 输出质量:发现有 file:line 引用、置信度 >= 80%、可执行的修复
  • [ ] Git 历史:至少 5 个遵循 Conventional Commits 格式的干净提交

进一步扩展 ​

基本功能运行后,扩展它:

  1. 添加 /review-pr-post 变体 -- 自动将审查作为 GitHub 评论发布
  2. 添加 Context7 集成 -- 检查 PR 的库使用是否遵循当前文档
  3. 添加回归检查 -- 对比此 PR 的发现与 main 分支
  4. 创建 SessionStart hook -- 检查分配给你的 open PR 并展示其 CI 状态
  5. 构建 /changelog skill -- 读取自上次标签以来合并的 PR 并生成发布说明

你展示了什么 ​

完成这个大项目,你证明了你能够:

  • 配置 hook 实现安全和可观测性
  • 构建编排复杂多步工作流的 skill
  • 通过 MCP 连接 Claude 到外部服务
  • 设计带有合适工具限制的专用 agent
  • 编排并行 agent 执行和依赖管理
  • 产出结构化、可执行的输出,在真实开发工作流中有用

这是中级工具箱。在高级篇(Ch10-14)中,你将学习如何防御提示注入(Prompt Injection)、优化 token 使用、在 CI/CD 中无头运行、以及构建生产级工具链。

基于 MIT 许可发布