Kết nối AI (Claude, Cursor, VS Code, Antigravity...) với Database, API nội bộ hoặc công cụ riêng của doanh nghiệp thông qua chuẩn Model Context Protocol (MCP).
Hãy tưởng tượng AI (ChatGPT, Claude, Cursor) giống như một nhân viên rất thông minh nhưng bị nhốt trong phòng kín, không nhìn thấy dữ liệu công ty bạn. MCP (Model Context Protocol) chính là "ổ cắm USB chuẩn" giúp bạn cắm AI vào kho dữ liệu (Database, File, Đơn hàng, Zalo/Telegram) để AI tự tra cứu và làm việc trực tiếp cho bạn.
Khái niệm
Vai trò chính
Tools (Công cụ)
Hàm cho phép AI chủ động gọi để thực thi hành động (ví dụ: truy vấn SQL, gọi API, tạo đơn hàng, gửi Telegram).
Resources (Tài nguyên)
Dữ liệu tĩnh hoặc động để AI đọc tham khảo (file log, tài liệu nội bộ, schema DB).
Transport: stdio
AI Client tự khởi chạy MCP Server cục bộ trên máy thông qua Standard Input/Output (phổ biến nhất).
Transport: HTTP / SSE
MCP Server chạy trên VPS/Server riêng, AI Client kết nối từ xa qua URL + API Key.
2. Tạo file index.mjs định nghĩa 1 Tool mẫu (tra_cuu_don_hang):
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({
name: "tlptech-demo-mcp",
version: "1.0.0"
});
server.tool(
"tra_cuu_don_hang",
"Tra cứu trạng thái đơn hàng theo mã đơn",
{ order_id: z.string().describe("Mã đơn hàng cần kiểm tra") },
async ({ order_id }) => {
// Có thể thay bằng query MySQL hoặc gọi API thực tế
return {
content: [{ type: "text", text: `Đơn hàng #${order_id}: Đang hoạt động.` }]
};
}
);
const transport = new StdioServerTransport();
await server.connect(transport);
Cách B: Tạo nhanh bằng Python (FastMCP)
pip install mcp
# File server.py
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("tlptech-python-mcp")
@mcp.tool()
def tinh_vat(so_tien: float, thue_suat: float = 0.08) -> str:
"""Tính tiền thuế VAT từ số tiền gốc"""
return f"Tổng sau thuế: {so_tien * (1 + thue_suat):,.0f} VNĐ"
if __name__ == "__main__":
mcp.run(transport="stdio")
Bước 2
Cấu hình MCP Server vào AI Client (mcp.json)
Mở file cấu hình MCP của công cụ bạn đang dùng (Cursor: .cursor/mcp.json, Claude Desktop: claude_desktop_config.json, VS Code: .vscode/mcp.json) và tham khảo tài liệu chuẩn tại modelcontextprotocol.io:
1. Cấu hình chạy cục bộ (stdio) + Biến môi trường (env)