Chuyển đến nội dung chính

Bài 13: MCP Servers — Kết nối AI với thế giới bên ngoài

Model Context Protocol (MCP) là gì. Cài đặt MCP servers trong VS Code. Figma MCP, GitHub MCP, Database MCP. Tạo custom MCP server. Security considerations. Use cases thực tế: design-to-code, DB queries, API integration. Copilot Hooks cho automation.

💻 Lập trình — Bài 13 Bài 13: MCP Servers — Kết nối AI với thế giới bên ngoài

Vibe Coding với GitHub Copilot: Từ Cơ bản đến Nâng cao

Phần 4: Customize & Extend Copilot

xdev.asia

1. Model Context Protocol (MCP) là gì?

MCP là giao thức chuẩn cho phép AI agents giao tiếp với external tools và services. Thay vì tự viết code tích hợp, bạn cài MCP servers để mở rộng khả năng của Copilot.

┌─────────────────────────────────────────────────┐
│              MCP ARCHITECTURE                    │
├─────────────────────────────────────────────────┤
│                                                  │
│  ┌──────────┐     ┌────────────┐                │
│  │ Copilot  │────▶│ MCP Server │                │
│  │ Agent    │◀────│ (Figma)    │                │
│  └──────────┘     └────────────┘                │
│       │                                          │
│       │           ┌────────────┐                │
│       └──────────▶│ MCP Server │                │
│       ◀───────────│ (Database) │                │
│                   └────────────┘                │
│       │                                          │
│       │           ┌────────────┐                │
│       └──────────▶│ MCP Server │                │
│       ◀───────────│ (GitHub)   │                │
│                   └────────────┘                │
│                                                  │
│  Copilot dùng tools từ MCP servers              │
│  như dùng built-in tools                        │
│                                                  │
└─────────────────────────────────────────────────┘

2. Cài đặt MCP Servers trong VS Code

2.1. Cấu hình trong settings.json

{
  "mcp": {
    "servers": {
      "figma": {
        "command": "npx",
        "args": ["-y", "@anthropic/mcp-server-figma"],
        "env": {
          "FIGMA_ACCESS_TOKEN": "${env:FIGMA_ACCESS_TOKEN}"
        }
      },
      "github": {
        "command": "npx",
        "args": ["-y", "@anthropic/mcp-server-github"],
        "env": {
          "GITHUB_TOKEN": "${env:GITHUB_TOKEN}"
        }
      },
      "postgres": {
        "command": "npx",
        "args": ["-y", "@anthropic/mcp-server-postgres"],
        "env": {
          "DATABASE_URL": "${env:DATABASE_URL}"
        }
      }
    }
  }
}

2.2. Cấu hình per-project (.vscode/mcp.json)

{
  "servers": {
    "project-db": {
      "command": "npx",
      "args": ["-y", "@anthropic/mcp-server-postgres"],
      "env": {
        "DATABASE_URL": "postgresql://dev:password@localhost:5432/myapp_dev"
      }
    }
  }
}

3. MCP Servers phổ biến

3.1. Figma MCP — Design to Code

Kết nối Figma với Copilot để chuyển design thành code:

// Prompt ví dụ:
Look at the Figma design for the login page and create
a React component that matches it exactly.
Use TailwindCSS for styling.

Tháng 3/2026: Figma MCP server có thể generate design layers trực tiếp từ VS Code.

3.2. GitHub MCP — Repository Operations

// Copilot có thể:
- Tìm và phân tích issues
- Đọc pull request comments
- Tạo issues từ code analysis
- Review PR changes

3.3. Database MCP — Query và Schema

// Prompt ví dụ:
Show me the schema of the users table and write a query
to find all users who registered in the last 30 days
but haven't made any purchases.

3.4. Các MCP servers khác

MCP Server Chức năng
Filesystem Read/write files ngoài workspace
Brave Search Web search từ trong Copilot
Puppeteer Browser automation và screenshots
Slack Gửi messages, tạo issues từ Slack
Memory Persistent memory cho conversations
GitKraken Git operations nâng cao

4. Tạo Custom MCP Server

Bạn có thể tạo MCP server riêng cho internal tools:

// custom-mcp-server/index.ts
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const server = new Server({
  name: 'internal-api',
  version: '1.0.0',
}, {
  capabilities: {
    tools: {},
  },
});

// Register tool
server.setRequestHandler('tools/list', async () => ({
  tools: [{
    name: 'get_customer',
    description: 'Lấy thông tin khách hàng từ CRM',
    inputSchema: {
      type: 'object',
      properties: {
        customerId: { type: 'string', description: 'Customer ID' },
      },
      required: ['customerId'],
    },
  }],
}));

server.setRequestHandler('tools/call', async (request) => {
  if (request.params.name === 'get_customer') {
    const { customerId } = request.params.arguments;
    // Call internal API
    const customer = await fetchCustomer(customerId);
    return { content: [{ type: 'text', text: JSON.stringify(customer) }] };
  }
});

const transport = new StdioServerTransport();
await server.connect(transport);

5. Copilot Hooks — Automation tại lifecycle events

Hooks cho phép chạy custom commands tại các events cụ thể:

{
  "github.copilot.chat.hooks": {
    "postSave": [
      {
        "command": "npm run lint:fix",
        "pattern": "**/*.{ts,tsx}"
      }
    ],
    "postCreate": [
      {
        "command": "npx prettier --write",
        "pattern": "**/*.{ts,tsx,css}"
      }
    ]
  }
}

Hooks đảm bảo code AI sinh ra luôn được format và lint tự động.

6. Security Considerations

⚠️ MCP servers có quyền truy cập mạnh:

  • Database MCP: có thể đọc/ghi database → chỉ dùng với dev database
  • Filesystem MCP: có thể truy cập files ngoài workspace
  • API MCP: có thể gọi external APIs với credentials của bạn

Best practices:

  • Dùng environment variables cho secrets, không hardcode
  • Limit scope: chỉ cấp quyền cần thiết cho MCP server
  • Review MCP source: kiểm tra code MCP server trước khi cài
  • Separate environments: dev database khác production database
  • Audit logs: theo dõi MCP server activity

7. Tổng kết

MCP Servers biến Copilot từ code generator thành full development assistant có thể tương tác với design tools, databases, APIs, và services bên ngoài.

MCP Server Vibe Coding Use Case
Figma "Build this design" → code
Database "Create API for this schema" → full CRUD
GitHub "Fix issues assigned to me" → auto-implement
Custom "Integrate with our CRM" → domain-specific tools

Từ Phần 5, chúng ta sẽ áp dụng tất cả kiến thức đã học vào dự án thực chiến — xây dựng full-stack app hoàn chỉnh bằng Vibe Coding.