Lộ trình học›Claude Code›Claude Code in Action Mở bản đồ

4.11 · Tích hợp GitHub — Claude trong pull request và issue

Bài viếtTrung cấp → Nâng30 phút đọc

Bạn mở PR. Hệ thống CI chạy: lint pass, test pass, build pass. Rồi Claude comment:

Sau bài này, bạn sẽ
  1. Cài đặt GitHub integration chính thức của Claude Code (/install-github-app)
  2. Kích hoạt Claude bằng @claude trong issue/PR comment
  3. Cấu hình auto-review mỗi PR mới
  4. Customize workflow YAML với custom_instructions, mcp_config, allowed_tools
  5. Bảo mật workflow với permission explicit + secret management

Mở đầu: Khi CI là đồng nghiệp

@claude: Reviewed this PR. Found 3 potential issues: 1. Race condition in updateUserProfile() — if two requests arrive simultaneously, second can overwrite first silently. Suggest: wrap in transaction. 2. Missing edge case in validatePhone() — doesn't handle international numbers. Test file covers only US format. 3. Duplicate logic — formatCurrency() at line 42 duplicates existing helper @lib/money.ts:formatAmount(). Consider reusing. Suggest addressing #1 before merge (security). #2 and #3 can be follow-up.

Đây không phải human reviewer. Đây là Claude trong GitHub Actions.

Kết quả: bạn có reviewer 24/7 nhìn mọi PR. Human reviewer chỉ cần focus vào high-level decisions. PR "chín muồi" nhanh hơn.

Bài này dạy bạn setup.

Hai workflow chính

GitHub integration cung cấp hai GitHub Actions workflow mặc định:

┌────────────────────────────────────────────────────────────┐
│                                                            │
│  1. @claude mention workflow                               │
│     ├── Trigger: @claude trong issue/PR comment            │
│     ├── Claude phân tích request                           │
│     ├── Execute task (có full codebase access)             │
│     └── Reply comment với kết quả                          │
│                                                            │
│  2. PR auto-review workflow                                │
│     ├── Trigger: mỗi PR tạo hoặc push mới                  │
│     ├── Claude review code changes                         │
│     ├── Analyze impact                                     │
│     └── Post comment với findings                          │
│                                                            │
└────────────────────────────────────────────────────────────┘

Setup: /install-github-app

Bước 1: Chạy command trong Claude Code

/install-github-app

Claude Code sẽ guide từng bước:

Step 1: Install GitHub App

Mở link được đưa → Install "Claude Code" app cho repo hoặc toàn org.

Step 2: Add API key secret

GitHub App cần Anthropic API key để gọi Claude. Thêm secret:

Settings → Secrets and variables → Actions → New repository secret
  Name:  ANTHROPIC_API_KEY
  Value: sk-ant-api03-...

Step 3: Claude tự tạo PR với workflow

Một PR tự động tạo, add hai file:

.github/
└── workflows/
    ├── claude.yml           ← @claude mention workflow
    └── claude-review.yml    ← auto-review workflow

Step 4: Merge PR

Merge vào main → workflow active ngay.

Bước 2: Test

Test @claude mention

Tạo issue mới:

Title: Test Claude integration

Body:
@claude list the top 5 largest files in this repo by line count.

Submit. Đợi ~30 giây. Claude reply comment với kết quả.

Test auto-review

Tạo branch mới, sửa 1-2 file, mở PR. Đợi ~1 phút. Claude post review comment.

Hiểu workflow YAML

Default claude.yml (@claude mention)

name: Claude

on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
  issues:
    types: [opened]
  pull_request_review:
    types: [submitted]

jobs:
  claude:
    if: |
      (github.event.comment.body && contains(github.event.comment.body, '@claude')) ||
      (github.event.issue.body && contains(github.event.issue.body, '@claude'))
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
      issues: write
    
    steps:
      - uses: actions/checkout@v4
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

Giải thích:

  • Trigger: Khi có comment mới hoặc issue mở, check có @claude không
  • Permissions: Claude cần write vào contents (để edit file), PR (comment), issues (reply)
  • Main step: Dùng anthropics/claude-code-action@v1 — tự xử lý phần còn lại

Default claude-review.yml (auto-review PR)

Tương tự nhưng:

  • Trigger: pull_request events (opened, synchronize)
  • Không cần @claude keyword
  • Claude review tự động

Customization — Nơi sức mạnh thực sự

Default workflow đã OK cho basic use. Nhưng team nào cũng có context riêng:

  • Project setup đặc biệt (cần npm run setup trước)
  • Convention riêng (review focus security với fintech, accessibility với public-facing)
  • Tool riêng (MCP server internal)

Workflow YAML cho phép inject những thứ đó.

Tùy chỉnh 1: Project Setup

Claude cần code runnable để test. Nếu project cần setup phức tạp:

steps:
  - uses: actions/checkout@v4
  
  - name: Node setup
    uses: actions/setup-node@v4
    with:
      node-version: '20'
  
  - name: Project Setup
    run: |
      npm run setup
      npm run dev:daemon   # start dev server background
  
  - uses: anthropics/claude-code-action@v1
    with:
      anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
      custom_instructions: |
        The project is already set up with all dependencies installed.
        The server is already running at localhost:3000. Logs are at 
        logs.txt. You can query the SQLite db with 'sqlite3' CLI.

Giờ Claude biết:

  • App đã chạy → không cần spin lại
  • Có db cli để query
  • Log file ở đâu

Tùy chỉnh 2: MCP Server trong Actions

Muốn Claude dùng Playwright trong CI (e.g., reproduce visual bug):

- uses: anthropics/claude-code-action@v1
  with:
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
    mcp_config: |
      {
        "mcpServers": {
          "playwright": {
            "command": "npx",
            "args": [
              "@playwright/mcp@latest",
              "--allowed-origins",
              "localhost:3000;cdn.tailwindcss.com;esm.sh"
            ]
          }
        }
      }

Giờ @claude reproduce the bug from screenshot in issue #1234 sẽ launch browser và check.

Tùy chỉnh 3: Allowed tools — BẮT BUỘC cho MCP

Local Claude Code auto-allow tools (tùy settings). Nhưng trong GitHub Actions, phải explicit list mọi tool:

- uses: anthropics/claude-code-action@v1
  with:
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
    allowed_tools: |
      Bash(npm:*),
      Bash(sqlite3:*),
      Bash(git:*),
      Read,
      Write,
      Edit,
      Grep,
      Glob,
      mcp__playwright__browser_snapshot,
      mcp__playwright__browser_click,
      mcp__playwright__browser_navigate,
      mcp__playwright__browser_type

Không có shortcut — mỗi tool MCP phải list explicit. Lý do: security — Actions chạy có quyền nhiều hơn local, Anthropic conservative default.

Tùy chỉnh 4: Scope custom instructions

Nhiều team có CLAUDE.md trong repo. Claude Action tự đọc → không cần duplicate vào instructions. Nhưng bạn có thể thêm context specific CI:

custom_instructions: |
  CI Context:
  - You're running in GitHub Actions, not a dev machine.
  - Do not run dangerous commands (rm, drop db).
  - If unable to complete in 10 minutes, report progress and stop.
  - For code reviews: focus on security > correctness > style.

Ví dụ thực chiến: Auto-triage workflow

Tình huống

Team fintech 20 dev, ~30 issue mở mỗi tuần. Engineering manager tốn 2-3 giờ/tuần triage: gán label, priority, owner.

Workflow custom

.github/workflows/claude-triage.yml:

name: Issue Triage

on:
  issues:
    types: [opened]

jobs:
  triage:
    runs-on: ubuntu-latest
    permissions:
      issues: write
    
    steps:
      - uses: actions/checkout@v4
      
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          trigger: 'issues:opened'
          custom_instructions: |
            Triage this new issue. Output:
            
            1. **Category label**: bug / feature / question / docs
            2. **Priority**: P0 (breaks prod) / P1 (important) / 
               P2 (nice to have) / P3 (backlog)
            3. **Component label**: auth / billing / admin / api / 
               frontend / infra
            4. **Suggested owner**: look up @CODEOWNERS, match 
               component to team
            5. **Duplicate check**: grep recent issues, flag if 
               seems duplicate
            
            Apply labels via gh CLI. If priority is P0, also 
            @mention engineering-manager.
          allowed_tools: |
            Bash(gh:*),
            Read,
            Grep

Kết quả

  • 100% issue mới được triage trong 2 phút
  • Engineering manager chỉ review triage đã có (5 phút/tuần thay vì 2-3 giờ)
  • Ít issue rớt qua khe hở (0 P0 bị miss trong 3 tháng vs trước 1-2/tháng)

Case studies theo ngành

Open source maintainer — 500 issue/tháng

Trước: Maintainer chính chết đuối trong issue trả lời câu hỏi cơ bản.

Với Claude Action:

  • @claude trả lời câu hỏi cơ bản (đã có answer trong docs)
  • Auto-close duplicate, link tới issue gốc
  • Tag advanced question cho human
  • Kết quả: Maintainer thời gian focus dev → ship feature 2x nhanh.

Enterprise — Compliance review tự động

Trước: "Mỗi PR cần security reviewer ký → bottleneck 1-2 ngày."

Với Claude review workflow:

  • Auto-scan cho security issue (hardcoded secret, SQL injection pattern, etc.)
  • Approve silently nếu clean
  • Flag + assign human reviewer nếu có concern
  • Kết quả: 80% PR tự động pass, human review 20% thực sự cần.

HealthTech — HIPAA audit trong CI

Setup: Claude Action chạy mỗi PR với prompt đặc biệt:

Scan diff for HIPAA violations:
- Any PHI in logs?
- Any PHI in test fixtures?
- Any PHI crossing boundary services?
Block merge if violation found.
  • Kết quả: Zero HIPAA incident trong 6 tháng, pass audit lần đầu.

Platform team — Bot cho infra queries

Pattern:

@claude what Terraform module do we use for setting up S3 
bucket with encryption?

Claude đọc repo IaC, trả lời ngay trong comment.

  • Kết quả: Platform team tránh câu hỏi lặp, focus cho infra work.

EdTech — Auto-answer student issue

Setup: Student submit bug report → Claude check docs + recent issues → trả lời nếu đã có answer, escalate nếu không.

  • Kết quả: 60% student issue self-resolved, support ticket giảm 60%.

Anti-patterns

Quên tắt workflow khi experiment

Biểu hiện: bạn test, mọi commit push trigger Claude review → tốn $$$ token.

Cách đúng: Trong YAML, add if condition:

if: github.actor != 'my-experiment-bot'

Hoặc tạm paths-ignore khi đang rush.

API key rò rỉ qua logs

Biểu hiện: echo $ANTHROPIC_API_KEY trong debug step → key xuất hiện trong logs public.

Cách đúng: KHÔNG echo secret. Chỉ reference qua ${{ secrets.XXX }} trong step that needs.

Permission quá rộng

Biểu hiện:

permissions:
  contents: write
  pull-requests: write
  actions: write   # ← nguy hiểm
Hậu quả
Claude có thể modify workflow → rút chân. Nếu bị compromised → badness.
Cách đúng
Minimum permission. Chỉ write khi thực sự cần (thường chỉ contents: write + pull-requests: write).

Allowed tools quá lỏng

Biểu hiện: allowed_tools: "Bash(:)" cho phép Claude chạy mọi command.

Rủi ro
Claude có thể rm -rf, curl exfiltrate data.
Cách đúng
Specific allowed: Bash(npm:),Bash(git:),Bash(gh:*). Không wildcard.

Không có human-in-loop cho destructive action

Biểu hiện: @claude delete all closed issues older than 1 year → Claude chạy luôn.

Cách đúng: Workflow có "dry-run first, confirm, execute" pattern. Hoặc đòi @claude delete --confirm keyword.

Mẹo nâng cao

Mẹo 1: Cost control với path filter

Chỉ chạy Claude review khi đụng code quan trọng:

on:
  pull_request:
    paths:
      - 'src/**'
      - '!src/**/*.md'   # skip docs-only PR
      - '!**/*.test.ts'  # skip test-only

Mẹo 2: Multiple workflow cho multiple persona

Thay vì 1 workflow monolithic, có nhiều workflow "chuyên môn":

  • claude-security.yml — chỉ review security, chạy với prompt security-focused
  • claude-accessibility.yml — chỉ a11y, cho public-facing PR
  • claude-performance.yml — chỉ perf, cho API PR

Mỗi workflow có prompt khác, tool khác.

Mẹo 3: Matrix strategy cho multi-language repo

Repo có cả TS + Go + Python? Matrix review:

strategy:
  matrix:
    language: [typescript, go, python]

Mỗi matrix nhánh có prompt chuyên ngôn ngữ.

Mẹo 4: Rate limit Claude response

Issue bị spam "@claude" → cost tăng. Thêm rate limit:

if: |
  github.event.comment.body != null &&
  contains(github.event.comment.body, '@claude') &&
  github.event.sender.login != 'claude-spammer'

Hoặc logic "max 3 @claude mention per issue".

Áp dụng ngay

Bài tập 1: Setup GitHub integration (20 phút)

Bước 1
Trong Claude Code, chạy /install-github-app. Follow wizard.
Bước 2
Merge PR tự động tạo.
Bước 3
Tạo issue test:
Title: Claude test
Body: @claude count all .ts files in this repo.

Bước 4: Ghi:

  • Thời gian Claude reply: _____ giây
  • Answer đúng không: Có Không
  • Bất ngờ gì: ____________

Bài tập 2 (optional, 30 phút): Customize review workflow

Bước 1: Edit .github/workflows/claude-review.yml. Thêm custom_instructions cho project:

custom_instructions: |
  Review focus for this project:
  1. Security: look for hardcoded secrets, SQL injection
  2. Tests: new code must have test coverage
  3. Types: TypeScript strict, no `any` escape
  4. Performance: flag N+1 queries
  
  Skip: style nitpicks (prettier handles).
Bước 2
Push, mở PR test với code cố ý có vấn đề (1 any, 1 missing test).
Bước 3
Quan sát review comment Claude. Có catch được các issue không?

Tóm tắt bài học

Những điều cốt lõi
  • /install-github-app — setup wizard 5 phút, xong có auto-review + @claude mention.
  • Hai workflow default — mention (trigger thủ công) + auto-review (mọi PR).
  • Customize với YAML — project setup, MCP, custom instructions, allowed tools.
  • Permission strict trong Actions — list explicit tool, không wildcard.
  • Cost-aware — path filter, rate limit, không run trên mọi commit vô nghĩa.

Tài liệu tham khảo

Kiểm tra nhanh1 câu hỏi · chọn đáp án để xem giải thích
    Bạn đã hoàn thành bài này chưa?Tiến độ lưu trên trình duyệt của bạn.