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

4 — Mở rộng & Tự động hóaTrung cấp30 phút

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

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

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

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:

/install-github-app

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

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

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

Step 4: Merge PR

Merge vào main → workflow active ngay.

Bước 2: Test

Test @claude mention

Tạo issue mới:

.github/
└── workflows/
    ├── claude.yml           ← @claude mention workflow
    └── claude-review.yml    ← auto-review workflow
Settings → Secrets and variables → Actions → New repository secret
  Name:  ANTHROPIC_API_KEY
  Value: sk-ant-api03-...

Bước 2: Test

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.

Title: Test Claude integration

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

Hiểu workflow YAML

Default claude.yml (@claude mention)

Giải thích:

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

Tương tự nhưng:

  • 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
  • Trigger: pull_request events (opened, synchronize)
  • Không cần @claude keyword
  • Claude review tự động
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 }}

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:

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:

Giờ Claude biết:

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

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

  • 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)
  • App đã chạy → không cần spin lại
  • Có db cli để query
  • Log file ở đâu
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.

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

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 }}
    mcp_config: |
      {
        "mcpServers": {
          "playwright": {
            "command": "npx",
            "args": [
              "@playwright/mcp@latest",
              "--allowed-origins",
              "localhost:3000;cdn.tailwindcss.com;esm.sh"
            ]
          }
        }
      }

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

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:

- 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

Tùy chỉnh 4: Scope custom instructions

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:

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)
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

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:

🏢 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:

🏥 HealthTech — HIPAA audit trong CI

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

🛠️ Platform team — Bot cho infra queries

Pattern:

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

🛠️ Platform team — Bot cho infra queries

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

🎓 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ả: Platform team tránh câu hỏi lặp, focus cho infra work.
  • Kết quả: 60% student issue self-resolved, support ticket giảm 60%.
@claude what Terraform module do we use for setting up S3 
bucket with encryption?

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:

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:

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

❌ Permission quá rộng

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.

permissions:
  contents: write
  pull-requests: write
  actions: write   # ← nguy hiểm

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:

Mẹo 2: Multiple workflow cho multiple persona

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

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:

  • 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
on:
  pull_request:
    paths:
      - 'src/**'
      - '!src/**/*.md'   # skip docs-only PR
      - '!**/*.test.ts'  # skip test-only

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

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:

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

Mẹo 4: Rate limit Claude response

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

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

Á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:

Bước 4: Ghi:

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:

  • Thời gian Claude reply: _____ giây
  • Answer đúng không: ☐ Có ☐ Không
  • Bất ngờ gì: ____________
Title: Claude test
Body: @claude count all .ts files in this repo.

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

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?

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).

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

🎯 /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
  • Claude Code GitHub Actions docs
  • anthropics/claude-code-action repo
  • GitHub Actions security hardening
  • Bài 4.10 — MCP (bao gồm MCP trong Actions)
  • Bài 4.16 — Hooks hữu ích (pattern tương tự cho local)
Nội dung này có hữu ích không?