Tutorial | 在 CI 中运行 Claude Code¶
难度:⭐⭐ 时间:~1.5h 前置:CI/CD 基础 产物:CI pipeline 自动跑 Claude Code
1. CI 跑 Claude Code 的场景¶
- PR review —— 自动审查 PR
- Issue triage —— 自动分类 issue
- Doc sync —— 自动同步文档
- Test gen —— 自动生成测试
- Code search —— 自动搜代码
5 场景。
2. 3 种集成方式¶
2.1 Headless 模式¶
headless —— 一问一答。
2.2 SDK 模式¶
import { query } from '@anthropic-ai/claude-code-sdk'
for await (const msg of query({ prompt: '...' })) { ... }
SDK —— 编程集成。
2.3 GitHub Action¶
Action —— GitHub 原生。
3. Headless 模式实战¶
3.1 基础¶
基本。
3.2 完整 CI 脚本¶
#!/bin/bash
# .github/workflows/claude-review.sh
set -e
# 1. 装 Claude Code
curl -fsSL https://claude.ai/install.sh | sh
# 2. 鉴权
export ANTHROPIC_API_KEY=$CLAUDE_API_KEY
# 3. 跑 review
claude -p "Review the changes in this PR. Be concise." \
--output-format json \
--max-turns 10 \
--max-budget-usd 2.00 \
--allowedTools "Read,Grep,Glob,Bash" \
--append-system-prompt "You are a CI code reviewer. Be specific. Cite line numbers." \
> /tmp/review.json
# 4. 解析输出
REVIEW=$(cat /tmp/review.json | jq -r '.result')
echo "## Claude Code Review" >> $GITHUB_STEP_SUMMARY
echo "$REVIEW" >> $GITHUB_STEP_SUMMARY
5 步。
3.3 GitHub Actions 集成¶
name: Claude Code Review
on: pull_request
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: |
curl -fsSL https://claude.ai/install.sh | sh
- env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude -p "Review this PR" \
--output-format json \
--max-budget-usd 2.00 \
> review.json
- uses: actions/upload-artifact@v4
with:
name: claude-review
path: review.json
完整。
4. SDK 模式实战¶
4.1 安装¶
npm。
4.2 TypeScript CI 脚本¶
// scripts/ci-review.ts
import { query } from '@anthropic-ai/claude-code-sdk'
import * as github from '@actions/github'
async function main() {
const pr = github.context.payload.pull_request
const diff = await getDiff(pr)
let output = ''
for await (const msg of query({
prompt: `Review this PR diff:\n\n${diff}`,
options: {
maxTurns: 10,
maxBudgetUsd: 2.00,
allowedTools: ['Read', 'Grep', 'Glob', 'Bash'],
appendSystemPrompt: 'You are a CI code reviewer.',
}
})) {
if (msg.type === 'assistant' && msg.message?.content) {
for (const block of msg.message.content) {
if (block.type === 'text') {
output += block.text
}
}
}
}
await github.createReviewComment(pr, output)
}
main()
完整。
4.3 异步 + 错误处理¶
try {
for await (const msg of query(opts)) {
// 处理
}
} catch (e) {
console.error('Review failed:', e)
process.exit(1)
}
try/catch。
5. GitHub Action 模式¶
5.1 官方 Action¶
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: |
Review this PR for:
- Security issues
- Performance issues
- Style violations
allowed_tools: 'Read,Grep,Glob'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
官方 Action。
5.2 自定义 Action¶
- uses: actions/checkout@v4
- uses: your-org/claude-review-action@v1
with:
api_key: ${{ secrets.ANTHROPIC_API_KEY }}
自定义。
6. 5 个 CI 实战场景¶
6.1 场景 1: PR 自动 review¶
on: pull_request
jobs:
claude-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- run: claude -p "Review this PR" --output-format json > review.json
- uses: actions/github-script@v7
with:
script: |
const review = require('fs').readFileSync('review.json', 'utf8')
const { result } = JSON.parse(review)
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `## Claude Code Review\n\n${result}`
})
完整。
6.2 场景 2: Issue triage¶
on:
issues:
types: [opened]
jobs:
triage:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: |
ISSUE_BODY="${{ github.event.issue.body }}"
claude -p "Triage this issue. Suggest label and priority." \
--append-system-prompt "Issue: $ISSUE_BODY" \
--output-format json > triage.json
- uses: actions/github-script@v7
with:
script: |
const { labels, priority } = JSON.parse(triage)
// 加 label
完整。
6.3 场景 3: 文档同步¶
# 检测代码变更,自动更新 README
claude -p "Update README based on recent code changes" \
--allowedTools "Read,Write"
docs。
6.4 场景 4: Test gen¶
# PR 改 .ts 文件 → 自动生成 test
claude -p "Generate tests for the new code" \
--allowedTools "Read,Write" \
--output-format json > tests.json
test。
6.5 场景 5: 每周 changelog¶
on:
schedule:
- cron: '0 9 * * 1' # 每周一 9 点
jobs:
changelog:
runs-on: ubuntu-latest
steps:
- run: |
claude -p "Generate changelog from this week's commits"
changelog。
7. 7 个最佳实践¶
- 预算上限 ——
--max-budget-usd - turns 上限 ——
--max-turns - 允许工具白名单 —— 防止滥用
- 结构化输出 ——
output-format: json - 超时 —— 避免挂起
- 错误处理 ——
try/catch - 审计日志 —— 记录每次调用
7 条。
8. 安全考虑¶
8.1 不传 secrets 到 prompt¶
env 注入。
8.2 沙箱工具¶
沙箱。
8.3 不上传数据¶
排除(推测)。
9. 成本控制¶
9.1 单 PR 成本¶
$0.15/次。
9.2 月度预算¶
$15/月。
9.3 上限¶
每 PR 上限。
10. 3 步调试 CI 集成¶
10.1 本地测¶
本地。
10.2 看日志¶
log。
10.3 简化 prompt¶
渐进。
11. 完整实战:每周 changelog¶
name: Weekly Changelog
on:
schedule:
- cron: '0 9 * * 1'
workflow_dispatch: # 手动触发
jobs:
changelog:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 100
- run: |
# 1. 装 Claude
curl -fsSL https://claude.ai/install.sh | sh
# 2. 装 jq
sudo apt-get install -y jq
- env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
# 3. 跑 changelog
COMMITS=$(git log --since="7 days ago" --pretty=format:"%H %s")
claude -p "Generate weekly changelog from these commits:\n\n$COMMITS" \
--output-format json \
--append-system-prompt "Output as markdown with sections: Features, Fixes, Breaking" \
> changelog.json
- uses: actions/github-script@v7
with:
script: |
const { result } = JSON.parse(require('fs').readFileSync('changelog.json'))
await github.rest.issues.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: `Changelog: ${new Date().toISOString().split('T')[0]}`,
body: result,
labels: ['changelog']
})
完整。
12. 下一步¶
- 装 Claude Code 在 CI
- 写一个 review 脚本
- 集成到现有 pipeline