Tự động hóa code review là bước tiến lớn giúp team của bạn tiết kiệm hàng giờ đồng hồ mỗi tuần. Trong bài viết này, tôi sẽ hướng dẫn bạn cách cấu hình MCP (Model Context Protocol) trong Cursor kết hợp với GitHub API để tạo hệ thống code review tự động thông minh.

Điều đặc biệt là chúng ta sẽ sử dụng HolySheep AI làm backend — nền tảng hỗ trợ thanh toán WeChat/Alipay, độ trễ dưới 50ms, và tiết kiệm đến 85% chi phí so với API chính thức.

Tại sao cần so sánh các giải pháp?

Trước khi bắt đầu, hãy cùng xem bảng so sánh toàn diện để hiểu rõ lợi thế của từng giải pháp:

Tiêu chíHolySheep AIAPI chính thứcDịch vụ Relay khác
Tỷ giá thực tế¥1 ≈ $1$0.03-$15/MTokBiến đổi theo tỷ giá
Thanh toánWeChat/Alipay, VisaChỉ thẻ quốc tếHạn chế phương thức
Độ trễ trung bình<50ms100-300ms200-500ms
Tín dụng miễn phíCó khi đăng kýKhôngTùy nhà cung cấp
GPT-4.1$8/MTok$15/MTok$10-12/MTok
Claude Sonnet 4.5$15/MTok$3/MTok$5-8/MTok
Gemini 2.5 Flash$2.50/MTok$0.30/MTok$1-2/MTok
DeepSeek V3.2$0.42/MTok$0.27/MTok$0.35-0.50/MTok
Hỗ trợ MCPĐầy đủKhông hỗ trợ trực tiếpHạn chế

Như bạn thấy, HolySheep AI nổi bật với tỷ giá cố định ¥1=$1 giúp tính toán chi phí dễ dàng, thanh toán linh hoạt qua WeChat/Alipay, và độ trễ cực thấp — lý tưởng cho các tác vụ code review cần phản hồi nhanh.

MCP là gì và tại sao cần thiết?

MCP (Model Context Protocol) là giao thức chuẩn hóa cho phép các công cụ AI kết nối với nhiều nguồn dữ liệu và dịch vụ bên ngoài một cách thống nhất. Với MCP, bạn có thể:

Cài đặt MCP Server cho Cursor

Bước 1: Cài đặt các package cần thiết

# Cài đặt Node.js và npm (nếu chưa có)

macOS

brew install node

Ubuntu/Debian

curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt-get install -y nodejs

Kiểm tra phiên bản

node --version # v18.x hoặc cao hơn npm --version # 9.x hoặc cao hơn

Cài đặt các package MCP cần thiết

npm install -g @modelcontextprotocol/server-github npm install -g @modelcontextprotocol/sdk npm install -g typescript ts-node

Cài đặt Cursor MCP CLI

npm install -g @cursor-ai/mcp-cli

Bước 2: Cấu hình MCP trong Cursor

Tạo file cấu hình MCP tại thư mục project của bạn:

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-github"
      ],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "code-review": {
      "command": "node",
      "args": [
        "${PROJECT_ROOT}/mcp-servers/code-review-server.js"
      ],
      "env": {
        "HOLYSHEEP_API_KEY": "${HOLYSHEEP_API_KEY}",
        "HOLYSHEEP_BASE_URL": "https://api.holysheep.ai/v1"
      }
    }
  }
}

Lưu file này với tên .cursor/mcp.json trong thư mục gốc của project.

Xây dựng Code Review Server với HolySheep AI

Tạo code review server

// mcp-servers/code-review-server.js
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
const {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} = require('@modelcontextprotocol/sdk/types.js');

// Cấu hình HolySheep AI - thay YOUR_HOLYSHEEP_API_KEY bằng key thực tế
const HOLYSHEEP_CONFIG = {
  baseUrl: 'https://api.holysheep.ai/v1',
  model: 'gpt-4.1',
  apiKey: process.env.HOLYSHEEP_API_KEY || 'YOUR_HOLYSHEEP_API_KEY',
  maxTokens: 4000,
  temperature: 0.3
};

const REVIEW_PROMPT = `Bạn là một senior code reviewer chuyên nghiệp. Hãy phân tích đoạn code dưới đây và cung cấp:

1. **Điểm mạnh**: Những phần code tốt, best practices được áp dụng
2. **Vấn đề bảo mật**: Các lỗ hổng tiềm ẩn (SQL injection, XSS, authentication issues)
3. **Performance**: Các điểm có thể tối ưu hóa
4. **Code quality**: Naming conventions, comments, structure
5. **Bug tiềm ẩn**: Logic errors, edge cases chưa xử lý
6. **Đề xuất cải thiện**: Code refactoring cụ thể

Format phản hồi theo Markdown với emoji phù hợp.

=== CODE CẦN REVIEW ===
{code}

=== NGỮ CẢNH ===
Ngôn ngữ: {language}
Framework: {framework}
File: {filename}`;

class CodeReviewServer {
  constructor() {
    this.server = new Server(
      {
        name: 'code-review-server',
        version: '1.0.0',
      },
      {
        capabilities: {
          tools: {},
        },
      }
    );

    this.setupTools();
  }

  setupTools() {
    this.server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: 'review_code',
            description: 'Phân tích và review code chi tiết sử dụng AI',
            inputSchema: {
              type: 'object',
              properties: {
                code: {
                  type: 'string',
                  description: 'Nội dung code cần review'
                },
                language: {
                  type: 'string',
                  description: 'Ngôn ngữ lập trình (javascript, python, go, etc.)',
                  default: 'javascript'
                },
                framework: {
                  type: 'string',
                  description: 'Framework đang sử dụng',
                  default: 'none'
                },
                filename: {
                  type: 'string',
                  description: 'Tên file để context thêm',
                  default: 'unknown'
                }
              },
              required: ['code']
            }
          },
          {
            name: 'review_pr',
            description: 'Review Pull Request từ GitHub',
            inputSchema: {
              type: 'object',
              properties: {
                pr_diff: {
                  type: 'string',
                  description: 'Diff content của Pull Request'
                },
                pr_title: {
                  type: 'string',
                  description: 'Tiêu đề PR'
                },
                pr_description: {
                  type: 'string',
                  description: 'Mô tả PR'
                }
              },
              required: ['pr_diff']
            }
          },
          {
            name: 'generate_summary',
            description: 'Tạo tóm tắt review cho commit/PR',
            inputSchema: {
              type: 'object',
              properties: {
                changes: {
                  type: 'string',
                  description: 'Danh sách thay đổi'
                },
                type: {
                  type: 'string',
                  enum: ['commit', 'pr', 'branch'],
                  description: 'Loại thay đổi'
                }
              },
              required: ['changes']
            }
          }
        ]
      };
    });

    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const { name, arguments: args } = request.params;

      try {
        switch (name) {
          case 'review_code':
            return await this.reviewCode(args);
          case 'review_pr':
            return await this.reviewPR(args);
          case 'generate_summary':
            return await this.generateSummary(args);
          default:
            throw new Error(Unknown tool: ${name});
        }
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: ❌ Lỗi: ${error.message}
            }
          ],
          isError: true
        };
      }
    });
  }

  async callHolySheepAI(prompt) {
    const startTime = Date.now();
    
    const response = await fetch(${HOLYSHEEP_CONFIG.baseUrl}/chat/completions, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': Bearer ${HOLYSHEEP_CONFIG.apiKey}
      },
      body: JSON.stringify({
        model: HOLYSHEEP_CONFIG.model,
        messages: [
          {
            role: 'system',
            content: 'Bạn là một code reviewer chuyên nghiệp. Trả lời bằng tiếng Việt, chi tiết và có code examples khi cần thiết.'
          },
          {
            role: 'user',
            content: prompt
          }
        ],
        max_tokens: HOLYSHEEP_CONFIG.maxTokens,
        temperature: HOLYSHEEP_CONFIG.temperature
      })
    });

    const latency = Date.now() - startTime;
    console.error([HolySheep AI] Latency: ${latency}ms | Model: ${HOLYSHEEP_CONFIG.model});

    if (!response.ok) {
      const error = await response.text();
      throw new Error(HolySheep API Error: ${response.status} - ${error});
    }

    const data = await response.json();
    return data.choices[0].message.content;
  }

  async reviewCode(args) {
    const { code, language = 'javascript', framework = 'none', filename = 'unknown' } = args;
    
    const prompt = REVIEW_PROMPT
      .replace('{code}', code)
      .replace('{language}', language)
      .replace('{framework}', framework)
      .replace('{filename}', filename);

    const review = await this.callHolySheepAI(prompt);

    return {
      content: [
        {
          type: 'text',
          text: review
        }
      ]
    };
  }

  async reviewPR(args) {
    const { pr_diff, pr_title = 'Untitled', pr_description = '' } = args;

    const prompt = `Hãy review Pull Request sau đây:

**Tiêu đề**: ${pr_title}
**Mô tả**: ${pr_description || 'Không có mô tả'}

**Diff**:
\\\`diff
${pr_diff}
\\\`

Hãy đánh giá:
1. Overall impression (tổng quan)
2. Potential issues (vấn đề tiềm ẩn)
3. Suggestions (đề xuất)
4. Approval recommendation (nên approve không?)

Trả lời bằng tiếng Việt, format Markdown.`;

    const review = await this.callHolySheepAI(prompt);

    return {
      content: [
        {
          type: 'text',
          text: review
        }
      ]
    };
  }

  async generateSummary(args) {
    const { changes, type = 'commit' } = args;

    const prompt = `Tạo một ${type === 'commit' ? 'commit message' : 'PR description'} chuyên nghiệp cho các thay đổi sau:

${changes}

Format:
- Tiếng Việt
- ${type === 'commit' ? 'Conventional commits format' : 'PR template format'}
- Ngắn gọn, rõ ràng
- Liệt kê key changes`;

    const summary = await this.callHolySheepAI(prompt);

    return {
      content: [
        {
          type: 'text',
          text: summary
        }
      ]
    };
  }

  async start() {
    const transport = new StdioServerTransport();
    await this.server.connect(transport);
    console.error('Code Review MCP Server started successfully');
  }
}

// Khởi động server
const server = new CodeReviewServer();
server.start().catch(console.error);

Kết nối với GitHub API

Script tự động review Pull Requests

// scripts/auto-review-pr.js
const https = require('https');

// Cấu hình - Sử dụng HolySheep AI
const CONFIG = {
  github: {
    token: process.env.GITHUB_TOKEN,
    owner: process.env.GITHUB_REPO_OWNER,
    repo: process.env.GITHUB_REPO_NAME,
    prNumber: parseInt(process.env.GITHUB_PR_NUMBER) || 0
  },
  holysheep: {
    apiKey: process.env.HOLYSHEEP_API_KEY,
    baseUrl: 'https://api.holysheep.ai/v1',
    model: 'gpt-4.1'
  }
};

// Hàm gọi GitHub API
function githubApiRequest(path, options = {}) {
  return new Promise((resolve, reject) => {
    const url = new URL(path, https://api.github.com);
    const reqOptions = {
      hostname: url.hostname,
      path: url.pathname,
      method: options.method || 'GET',
      headers: {
        'Authorization': token ${CONFIG.github.token},
        'Accept': 'application/vnd.github.v3+json',
        'User-Agent': 'CodeReviewBot/1.0'
      }
    };

    const req = https.request(reqOptions, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        try {
          resolve(JSON.parse(data));
        } catch {
          resolve(data);
        }
      });
    });

    req.on('error', reject);
    
    if (options.body) {
      req.write(JSON.stringify(options.body));
    }
    req.end();
  });
}

// Lấy thông tin PR
async function getPRDetails() {
  const pr = await githubApiRequest(
    /repos/${CONFIG.github.owner}/${CONFIG.github.repo}/pulls/${CONFIG.github.prNumber}
  );
  return pr;
}

// Lấy diff của PR
async function getPRDiff() {
  const url = new URL(
    /repos/${CONFIG.github.owner}/${CONFIG.github.repo}/pulls/${CONFIG.github.prNumber},
    'https://api.github.com'
  );
  url.searchParams.set('diff_file', 'true');
  
  return await githubApiRequest(url.toString());
}

// Lấy files changed
async function getPRFiles() {
  const files = await githubApiRequest(
    /repos/${CONFIG.github.owner}/${CONFIG.github.repo}/pulls/${CONFIG.github.prNumber}/files
  );
  return files;
}

// Gọi HolySheep AI để review
async function reviewWithAI(prData, diff, files) {
  const startTime = Date.now();
  
  const prompt = `Hãy review Pull Request sau:

**Thông tin PR**:
- Tiêu đề: ${prData.title}
- Người tạo: ${prData.user.login}
- Mô tả: ${prData.body || 'Không có mô tả'}
- Branch: ${prData.head.ref} → ${prData.base.ref}

**Files thay đổi (${files.length} files)**:
${files.map(f => - ${f.filename} (+${f.additions} lines, -${f.deletions} lines)).join('\n')}

**Diff đầy đủ**:
\\\`diff
${diff}
\\\`

Hãy cung cấp:
1. **Tóm tắt**: Tổng quan về PR (1-2 câu)
2. **Điểm mạnh**: Code tốt, best practices
3. **Vấn đề cần lưu ý**: Bugs, security, performance
4. **Comments cụ thể**: Gợi ý cho từng file
5. **Kết luận**: APPROVE / REQUEST_CHANGES / COMMENT

Format Markdown, tiếng Việt.`;

  const response = await fetch(${CONFIG.holysheep.baseUrl}/chat/completions, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': Bearer ${CONFIG.holysheep.apiKey}
    },
    body: JSON.stringify({
      model: CONFIG.holysheep.model,
      messages: [
        {
          role: 'system',
          content: 'Bạn là code reviewer chuyên nghiệp. Đánh giá khách quan, chi tiết.'
        },
        {
          role: 'user',
          content: prompt
        }
      ],
      max_tokens: 4000,
      temperature: 0.3
    })
  });

  const latency = Date.now() - startTime;
  console.error([Auto Review] HolySheep AI latency: ${latency}ms);
  console.error([Auto Review] Model: ${CONFIG.holysheep.model});

  if (!response.ok) {
    throw new Error(HolySheep API Error: ${response.status});
  }

  const data = await response.json();
  return data.choices[0].message.content;
}

// Đăng comment lên PR
async function postPRComment(review) {
  const body = `## 🤖 Code Review tự động

> Review bằng [HolySheep AI](https://www.holysheep.ai) | Model: ${CONFIG.holysheep.model}

${review}

---
*⚠️ Đây là review tự động. Vui lòng xem xét kỹ trước khi merge.*`;

  return await githubApiRequest(
    /repos/${CONFIG.github.owner}/${CONFIG.github.repo}/issues/${CONFIG.github.prNumber}/comments,
    {
      method: 'POST',
      body: { body }
    }
  );
}

// Main function
async function main() {
  console.error('[Auto Review] Bắt đầu review PR...');
  
  try {
    // Kiểm tra cấu hình
    if (!CONFIG.github.token || !CONFIG.holysheep.apiKey) {
      throw new Error('Thiếu GITHUB_TOKEN hoặc HOLYSHEEP_API_KEY');
    }

    // Lấy thông tin PR
    console.error('[Auto Review] Đang lấy thông tin PR...');
    const prData = await getPRDetails();
    console.error([Auto Review] PR: #${prData.number} - ${prData.title});

    // Lấy files changed
    console.error('[Auto Review] Đang lấy danh sách files...');
    const files = await getPRFiles();
    console.error([Auto Review] ${files.length} files thay đổi);

    // Lấy diff
    console.error('[Auto Review] Đang lấy diff...');
    const diff = await getPRDiff();

    // Review với AI
    console.error('[Auto Review] Đang gọi HolySheep AI...');
    const review = await reviewWithAI(prData, diff, files);

    // Đăng comment
    console.error('[Auto Review] Đang đăng comment lên GitHub...');
    await postPRComment(review);

    console.error('[Auto Review] ✅ Hoàn tất! Comment đã được đăng.');
    console.log(JSON.stringify({ success: true, pr: prData.number }));
    
  } catch (error) {
    console.error('[Auto Review] ❌ Lỗi:', error.message);
    process.exit(1);
  }
}

main();

GitHub Actions Workflow

Tạo workflow để tự động chạy review mỗi khi có PR mới:

# .github/workflows/code-review.yml
name: AI Code Review

on:
  pull_request:
    types: [opened, synchronize, reopened]
  issue_comment:
    types: [created]

jobs:
  review:
    runs-on: ubuntu-latest
    if: github.event_name == 'pull_request'
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
          
      - name: Install dependencies
        run: |
          npm install
          npm install @modelcontextprotocol/sdk node-fetch
          
      - name: Run AI Code Review
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITHUB_REPO_OWNER: ${{ github.repository_owner }}
          GITHUB_REPO_NAME: ${{ github.event.repository.name }}
          GITHUB_PR_NUMBER: ${{ github.event.pull_request.number }}
          HOLYSHEEP_API_KEY: ${{ secrets.HOLYSHEEP_API_KEY }}
        run: |
          node scripts/auto-review-pr.js
          
      - name: Post review summary
        if: always()
        run: |
          echo "## Code Review Status" >> $GITHUB_STEP_SUMMARY
          echo "- PR: #${{ github.event.pull_request.number }}" >> $GITHUB_STEP_SUMMARY  
          echo "- Status: ${{ job.status }}" >> $GITHUB_STEP_SUMMARY
          echo "- Powered by: [HolySheep AI](https://www.holysheep.ai)" >> $GITHUB_STEP_SUMMARY

Thêm Secrets vào GitHub Repository

Để workflow hoạt động, bạn cần thêm các secrets sau vào repository:

Để thêm secrets: Settings → Secrets and variables → Actions → New repository secret

Cấu hình .env file cho development local

# .env.example - Development configuration

Copy file này thành .env và điền thông tin thực tế

GitHub Configuration

GITHUB_TOKEN=ghp_your_github_personal_access_token_here GITHUB_REPO_OWNER=your_username GITHUB_REPO_NAME=your_repository GITHUB_PR_NUMBER=123

HolySheep AI Configuration - QUAN TRỌNG: Sử dụng HolySheep thay vì OpenAI

HOLYSHEEP_API_KEY=your_holysheep_api_key_here HOLYSHEEP_BASE_URL=https://api.holysheep.ai/v1 HOLYSHEEP_MODEL=gpt-4.1

Server Configuration

PORT=3000 NODE_ENV=development

Sau khi đăng ký tại HolySheep AI, bạn sẽ nhận được API key và tín dụng miễn phí để bắt đầu sử dụng ngay.

Lỗi thường gặp và cách khắc phục

1. Lỗi "401 Unauthorized" từ HolySheep API

# Nguyên nhân: API key không đúng hoặc chưa được set

Triệu chứng: Response status 401, error "Invalid API key"

Cách khắc phục:

1. Kiểm tra file .env đã được tạo chưa

ls -la .env

2. Verify API key đúng format

cat .env | grep HOLYSHEEP_API_KEY

Output phải là: HOLYSHEEP_API_KEY=hs_xxxxxxxxxxxx

3. Test API key trực tiếp

curl -X POST https://api.holysheep.ai/v1/models \ -H "Authorization: Bearer YOUR_HOLYSHEEP_API_KEY"

4. Nếu dùng nhầm key của OpenAI/Anthropic, hãy:

- Truy cập https://www.holysheep.ai/register

- Đăng ký và lấy API key mới

- Key của HolySheep luôn bắt đầu bằng "hs_"

2. Lỗi "MCP Server connection failed"

# Nguyên nhân: Cursor không tìm thấy MCP server hoặc package chưa cài

Triệu chứng: "Failed to connect to MCP server" trong Cursor

Cách khắc phục:

1. Kiểm tra Node.js đã cài đặt chưa

node --version npm --version

2. Cài đặt lại các package MCP

npm install -g @modelcontextprotocol/sdk npm install -g @modelcontextprotocol/server-github

3. Verify file cấu hình MCP

cat .cursor/mcp.json

Đảm bảo JSON format hợp lệ

4. Restart Cursor hoàn toàn

- Đóng Cursor

- Xóa cache: rm -rf ~/.cursor/cache

- Mở lại Cursor

5. Kiểm tra logs

Settings → Developer → Open Logs

Tìm các lỗi liên quan đến MCP

3. Lỗi "GitHub API rate limit exceeded"

# Nguyên nhân: GitHub giới hạn 5000 requests/giờ cho authenticated

Triệu chứng: Response 403, error "API rate limit exceeded"

Cách khắc phục:

1. Tạo GitHub Personal Access Token mới (nếu chưa có)

Truy cập: https://github.com/settings/tokens

Scope cần: repo, read:user, workflow

2. Kiểm tra rate limit hiện tại

curl -H "Authorization: token YOUR_GITHUB_TOKEN" \ https://api.github.com/rate_limit

3. Thêm token vào environment

export GITHUB_TOKEN="ghp_your_new_token_here"

4. Hoặc sử dụng GitHub App thay vì PAT để có rate limit cao hơn

Tạo App tại: https://github.com/settings/apps

Cài đặt vào organization/repository

5. Implement exponential backoff trong code

const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); async function fetchWithRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.status === 403 && error.headers['retry-after']) { await delay(parseInt(error.headers['retry-after']) * 1000); } else { throw error; } } } }

4. Lỗi "Socket hang up" hoặc timeout

# Nguyên nhân: Kết nối mạng không ổn định hoặc request quá lâu

Triệu chứng: "socket hang up" error, connection timeout

Cách khắc phục:

1. Tăng timeout cho fetch request

const response = await fetch(url, { method: 'POST', headers: {...}, body: JSON.stringify(data), signal: AbortSignal.timeout(120000) // 2 phút timeout });

2. Kiểm tra kết nối mạng đến HolySheep

curl -I https://api.holysheep.ai/v1/models

Response phải là 200 OK

3. Nếu dùng proxy, cấu hình trong code

const agent = new https.Agent({ proxy: 'http://your-proxy:8080', timeout: 120000 });

4. Retry với exponential backoff

async function retryRequest(fn, retries = 3) { for (let i = 0; i < retries; i++) { try { return await fn(); } catch (error) { if (i === retries - 1) throw error; await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } } }

5. Lỗi parse JSON khi lấy PR diff

# Nguyên nhân: GitHub trả về raw diff không phải JSON

Triệu chứng: "Unexpected token" khi parse response

Cách khắc phục:

1. Sử dụng endpoint đúng cho diff

async function getPRDiff(prNumber) { // Endpoint này trả về raw diff, không phải JSON const response = await fetch( https://api.github.com/repos/${owner}/${repo}/pulls/${prNumber}, { headers: { 'Authorization': token ${token}, 'Accept': 'application/vnd.github.v3.diff' // QUAN TRỌNG! } } ); // Không parse JSON, lấy text trực tiếp return await response.text(); // Không phải response.json() } // 2. Hoặc lấy từ files changed async function getPRFiles(prNumber) { const files = await githubApiRequest( /repos/${owner}/${repo}/pulls/${prNumber}/files ); // Tạo diff từ patches return files.map(f => ({ filename: f.filename, patch: f.patch })); }

Tối ưu chi phí với HolySheep AI

Với cấu hình hiện tại, chi phí cho mỗi lần review được ước tính như sau: