Giới Thiệu MCP - Giao Thức Kết Nối AI Với Thế Giới Thực

Trong bài viết này, tôi sẽ chia sẻ cách xây dựng một công cụ code review tự động sử dụng Model Context Protocol (MCP) để phân tích thay đổi code và đưa ra gợi ý cải thiện. Đây là giải pháp mà đội ngũ của tôi đã triển khai thực tế, giúp giảm 70% thời gian review code thủ công.

So Sánh Các Dịch Vụ API AI

Trước khi đi vào chi tiết kỹ thuật, hãy cùng xem bảng so sánh giữa HolySheep AI và các dịch vụ khác:

Tiêu chí HolySheep AI API Chính Thức Proxy/Relay
Tỷ giá ¥1 = $1 (tiết kiệm 85%+) $1 = $1 Tùy nhà cung cấp
Thanh toán WeChat, Alipay, USDT Thẻ quốc tế Thẻ quốc tế
Độ trễ trung bình <50ms 100-300ms 150-500ms
Tín dụng miễn phí ✅ Có khi đăng ký ❌ Không ❌ Thường không
GPT-4.1 $8/MTok $60/MTok $15-25/MTok
Claude Sonnet 4.5 $15/MTok $45/MTok $20-35/MTok
DeepSeek V3.2 $0.42/MTok Không hỗ trợ $1-2/MTok

Như bạn thấy, HolySheep AI mang lại hiệu suất chi phí vượt trội với độ trễ cực thấp. Đặc biệt, việc hỗ trợ thanh toán qua WeChat/Alipay rất thuận tiện cho developers Châu Á.

MCP Là Gì Và Tại Sao Nên Dùng?

MCP (Model Context Protocol) là giao thức chuẩn hóa cho phép AI models kết nối với các nguồn dữ liệu và công cụ bên ngoài. Thay vì phải xây dựng custom integrations, MCP cung cấp một lớp trừu tượng thống nhất.

Kiến Trúc Hệ Thống Code Review Tool

Cài Đặt Môi Trường

# Cài đặt Node.js MCP SDK
npm install @modelcontextprotocol/sdk

Cài đặt thư viện Git

npm install simple-git

Cài đặt client HTTP cho HolySheep API

npm install axios

Khởi tạo project

mkdir mcp-code-review cd mcp-code-review npm init -y npm install @modelcontextprotocol/sdk simple-git axios dotenv

Xây Dựng MCP Server Cho Git Diff Analysis

// mcp-server.ts - MCP Server cho Code Review
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { simpleGit } from "simple-git";
import axios from "axios";

const HOLYSHEEP_API_KEY = process.env.HOLYSHEEP_API_KEY;
const HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1";

// Khởi tạo MCP Server
const server = new McpServer({
  name: "code-review-server",
  version: "1.0.0"
});

// Tool: Phân tích Git Diff
server.tool(
  "analyze-git-diff",
  "Phân tích thay đổi code từ git diff",
  {
    repoPath: z.string().describe("Đường dẫn đến repository"),
    baseBranch: z.string().describe("Branch gốc để so sánh"),
    targetBranch: z.string().describe("Branch cần review")
  },
  async ({ repoPath, baseBranch, targetBranch }) => {
    const git = simpleGit(repoPath);
    
    // Lấy diff giữa hai branch
    const diff = await git.diff([baseBranch, targetBranch]);
    const diffStat = await git.diff([baseBranch, targetBranch, "--stat"]);
    
    return {
      content: [
        { type: "text", text: ## Git Diff Analysis\n\n**Base:** ${baseBranch}\n**Target:** ${targetBranch}\n\n### Statistics:\n${diffStat}\n\n### Detailed Changes:\n${diff} }
      ]
    };
  }
);

// Tool: Tạo Code Review với AI
server.tool(
  "generate-review-suggestions",
  "Tạo gợi ý code review từ AI",
  {
    diffContent: z.string().describe("Nội dung git diff cần review"),
    language: z.string().optional().describe("Ngôn ngữ lập trình chính")
  },
  async ({ diffContent, language = "multiple" }) => {
    const prompt = `Bạn là một senior code reviewer. Hãy phân tích các thay đổi code sau và đưa ra feedback:

Ngôn ngữ: ${language}

---
${diffContent}
---

Hãy trả lời theo format JSON sau:
{
  "overall_score": số từ 1-10,
  "summary": "Tóm tắt ngắn về chất lượng code",
  "issues": [
    {
      "severity": "critical|warning|info",
      "file": "tên file",
      "line": "số dòng hoặc null",
      "description": "Mô tả vấn đề",
      "suggestion": "Gợi ý sửa chữa"
    }
  ],
  "praises": ["Những điểm tốt của code"],
  "security_concerns": ["Các vấn đề bảo mật tiềm ẩn"]
}`;

    try {
      const response = await axios.post(
        ${HOLYSHEEP_BASE_URL}/chat/completions,
        {
          model: "gpt-4.1",
          messages: [{ role: "user", content: prompt }],
          temperature: 0.3,
          max_tokens: 4000
        },
        {
          headers: {
            "Authorization": Bearer ${HOLYSHEEP_API_KEY},
            "Content-Type": "application/json"
          }
        }
      );

      const aiResponse = response.data.choices[0].message.content;
      
      return {
        content: [
          { type: "text", text: ## AI Code Review\n\n${aiResponse} }
        ]
      };
    } catch (error) {
      console.error("HolySheep API Error:", error.response?.data || error.message);
      throw new Error(AI Review failed: ${error.message});
    }
  }
);

// Khởi động server
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("MCP Code Review Server started");
}

main().catch(console.error);

Client Code Review Tool Hoàn Chỉnh

// code-review-client.ts - Client cho việc review code
import axios from "axios";
import { simpleGit } from "simple-git";
import * as fs from "fs";
import * as path from "path";

const HOLYSHEEP_API_KEY = process.env.HOLYSHEEP_API_KEY!;
const HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1";
const MODEL = "gpt-4.1"; // Hoặc "claude-sonnet-4.5", "deepseek-v3.2"

interface ReviewConfig {
  repoPath: string;
  targetBranch: string;
  baseBranch?: string;
  outputPath?: string;
  model?: string;
}

interface CodeIssue {
  severity: "critical" | "warning" | "info";
  file: string;
  line?: number;
  description: string;
  suggestion: string;
}

interface ReviewResult {
  timestamp: string;
  model: string;
  overallScore: number;
  summary: string;
  issues: CodeIssue[];
  praises: string[];
  securityConcerns: string[];
  processingTimeMs: number;
}

class CodeReviewTool {
  private apiKey: string;
  private baseUrl: string;

  constructor(apiKey: string) {
    this.apiKey = apiKey;
    this.baseUrl = HOLYSHEEP_BASE_URL;
  }

  async getGitDiff(repoPath: string, baseBranch: string, targetBranch: string): Promise {
    const git = simpleGit(repoPath);
    
    console.log(📊 Getting diff: ${baseBranch}...${targetBranch});
    
    const diff = await git.diff([baseBranch, targetBranch]);
    const diffStat = await git.diff([baseBranch, targetBranch, "--stat"]);
    
    return === DIFF STATISTICS ===\n${diffStat}\n\n=== DETAILED DIFF ===\n${diff};
  }

  async callAIForReview(diffContent: string, language: string = "TypeScript/JavaScript"): Promise {
    const startTime = Date.now();
    
    const systemPrompt = `Bạn là một Senior Code Reviewer với 15 năm kinh nghiệm. 
Nhiệm vụ của bạn:
1. Phân tích code changes một cách kỹ lưỡng
2. Đánh giá theo các tiêu chí: correctness, security, performance, maintainability, best practices
3. Chỉ ra issues với mức độ: critical, warning, info
4. Gợi ý cải thiện cụ thể và actionable

LUÔN trả lời theo format JSON sau (không có gì khác ngoài JSON):
{
  "overall_score": number (1-10),
  "summary": "Tóm tắt ngắn 1-2 câu",
  "issues": [
    {
      "severity": "critical|warning|info",
      "file": "đường dẫn file",
      "line": số dòng hoặc null,
      "description": "Mô tả vấn đề",
      "suggestion": "Gợi ý cụ thể để sửa"
    }
  ],
  "praises": ["điểm tốt 1", "điểm tốt 2"],
  "security_concerns": ["vấn đề bảo mật 1", "vấn đề bảo mật 2"]
}`;

    const userPrompt = Hãy review đoạn code changes sau:\n\n${diffContent};

    console.log("🤖 Calling HolySheep AI API...");
    
    const response = await axios.post(
      ${this.baseUrl}/chat/completions,
      {
        model: MODEL,
        messages: [
          { role: "system", content: systemPrompt },
          { role: "user", content: userPrompt }
        ],
        temperature: 0.2,
        max_tokens: 5000
      },
      {
        headers: {
          "Authorization": Bearer ${this.apiKey},
          "Content-Type": "application/json"
        },
        timeout: 60000 // 60s timeout
      }
    );

    const processingTimeMs = Date.now() - startTime;
    const aiContent = response.data.choices[0].message.content;
    
    // Parse JSON response
    let reviewData;
    try {
      reviewData = JSON.parse(aiContent);
    } catch (e) {
      // Fallback if JSON parsing fails
      reviewData = {
        overall_score: 5,
        summary: "Parse error - unable to analyze",
        issues: [],
        praises: [],
        security_concerns: []
      };
    }

    return {
      timestamp: new Date().toISOString(),
      model: MODEL,
      overallScore: reviewData.overall_score,
      summary: reviewData.summary,
      issues: reviewData.issues || [],
      praises: reviewData.praises || [],
      securityConcerns: reviewData.security_concerns || [],
      processingTimeMs
    };
  }

  async review(config: ReviewConfig): Promise {
    const baseBranch = config.baseBranch || "main";
    
    console.log(\n🔍 Starting code review...);
    console.log(📁 Repository: ${config.repoPath});
    console.log(🔀 Branch: ${config.targetBranch} (base: ${baseBranch}));
    
    // Step 1: Get diff
    const diff = await this.getGitDiff(config.repoPath, baseBranch, config.targetBranch);
    
    // Step 2: Get AI review
    const result = await this.callAIForReview(diff);
    
    // Step 3: Save results
    if (config.outputPath) {
      fs.writeFileSync(
        config.outputPath,
        JSON.stringify(result, null, 2)
      );
      console.log(💾 Results saved to: ${config.outputPath});
    }

    // Step 4: Print summary
    this.printSummary(result);
    
    return result;
  }

  private printSummary(result: ReviewResult): void {
    console.log("\n" + "=".repeat(60));
    console.log("📋 CODE REVIEW SUMMARY");
    console.log("=".repeat(60));
    console.log(⏱️  Processing time: ${result.processingTimeMs}ms);
    console.log(🤖 Model: ${result.model});
    console.log(⭐ Overall Score: ${result.overallScore}/10);
    console.log(📝 Summary: ${result.summary});
    
    if (result.issues.length > 0) {
      console.log(\n⚠️  ISSUES FOUND (${result.issues.length}):);
      result.issues.forEach((issue, i) => {
        const icon = issue.severity === "critical" ? "🔴" : 
                     issue.severity === "warning" ? "🟡" : "🔵";
        console.log(   ${icon} [${issue.severity.toUpperCase()}] ${issue.file});
        console.log(      ${issue.description});
        console.log(      💡 Suggestion: ${issue.suggestion});
      });
    }
    
    if (result.praises.length > 0) {
      console.log(\n✅ PRAISES:);
      result.praises.forEach(praise => {
        console.log(   ✓ ${praise});
      });
    }
    
    if (result.securityConcerns.length > 0) {
      console.log(\n🔒 SECURITY CONCERNS:);
      result.securityConcerns.forEach(concern => {
        console.log(   ⚠️  ${concern});
      });
    }
    
    console.log("=".repeat(60) + "\n");
  }
}

// Main execution
async function main() {
  const config: ReviewConfig = {
    repoPath: process.cwd(),
    targetBranch: "feature/my-feature",
    baseBranch: "develop",
    outputPath: "./review-results.json"
  };

  if (!HOLYSHEEP_API_KEY) {
    console.error("❌ HOLYSHEEP_API_KEY not set!");
    console.log("Set it with: export HOLYSHEEP_API_KEY=your_key");
    process.exit(1);
  }

  const tool = new CodeReviewTool(HOLYSHEEP_API_KEY);
  
  try {
    await tool.review(config);
  } catch (error) {
    console.error("❌ Review failed:", error);
    process.exit(1);
  }
}

main();

Tích Hợp Với Git Hooks Để Tự Động Review

#!/bin/bash

.git/hooks/pre-commit hoặc .git/hooks/pre-push

Chỉ chạy review nếu có thay đổi

if git diff --cached --name-only | grep -q .; then echo "🔍 Running automated code review..." # Lấy danh sách files đã staged CHANGED_FILES=$(git diff --cached --name-only) # Tạo diff cho các file đã staged STAGED_DIFF=$(git diff --cached) # Gọi review script npx ts-node code-review-client.ts << EOF ${STAGED_DIFF} EOF # Kiểm tra kết quả if [ $? -eq 0 ]; then echo "✅ Code review passed!" exit 0 else echo "❌ Code review found issues. Please fix before committing." exit 1 fi fi

Script Review Toàn Bộ PR

// review-pr.ts - Review toàn bộ Pull Request
import axios from "axios";
import { simpleGit } from "simple-git";

const HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1";
const HOLYSHEEP_API_KEY = process.env.HOLYSHEEP_API_KEY!;

interface PRInfo {
  number: number;
  title: string;
  sourceBranch: string;
  targetBranch: string;
  author: string;
}

async function getPRInfo(): Promise {
  // Parse git info
  const git = simpleGit();
  const branches = await git.branch();
  const currentBranch = branches.current;
  
  return