Model Context Protocol (MCP): Tiêu Chuẩn Kết Nối AI Agent Với Công Cụ

Model Context Protocol (MCP) là tiêu chuẩn mở của Anthropic cho phép AI Agent kết nối an toàn với dữ liệu, công cụ và hệ thống bên ngoài. MCP giải quyết vấn đề “M×N integration” — thay vì mỗi agent phải tự xây dựng connector cho từng tool, giờ có một giao thức chung mà cả hai bên tuân thủ.

Sơ đồ kiến trúc MCP client-server với JSON-RPC transport

Vấn đề MCP giải quyết

Trước MCP, developer muốn AI Agent truy cập database, file system, GitHub, Slack… phải viết custom function cho từng cặp (agent, tool). Với M agentsN tools → cần M×N tích hợp. MCP biến thành M+N: agent nói MCP, tool expose MCP server.

Kiến trúc MCP: 3 thành phần cốt lõi

  • MCP Host: Ứng dụng chứa LLM (Claude Desktop, Cursor, VS Code extension, custom app). Host khởi tạo client.
  • MCP Client: Thành phần trong host quản lý kết nối 1-1 đến MCP Server qua transport (stdio, HTTP+SSE, WebSocket).
  • MCP Server: Chương trình độc lập expose Resources (dữ liệu đọc), Tools (hành động ghi/thực thi), Prompts (template prompt tái sử dụng).

Ba primitive cốt lõi

Primitive Mục đích Ví dụ
Resources Cung cấp dữ liệu chỉ đọc, có URI file:///project/README.md, postgres://db/users
Tools Hành động có side-effect, LLM quyết định khi gọi GitHub create issue, SQL execute, send email
Prompts Template prompt có tham số, người dùng chọn Code review prompt, commit message generator

MCP server code ví dụ Python FastMCP expose tool get_weather

Transport: stdio vs HTTP+SSE vs WebSocket

  • stdio: Mặc định cho local server. Host spawn process, giao tiếp qua stdin/stdout. Đơn giản, an toàn, phù hợp CLI tool.
  • HTTP+SSE: Server chạy remote, client kết nối qua HTTP. Hỗ trợ authentication, load balancer, phù hợp production.
  • WebSocket: Full-duplex, latency thấp hơn SSE. Dùng khi cần real-time cao.

Ví dụ: Tạo MCP Server Python với FastMCP

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Weather Server")

@mcp.tool()
async def get_weather(city: str) -> str:
    """Lấy thời tiết hiện tại của thành phố."""
    # Gọi API weather thực tế ở đây
    return f"Thời tiết {city}: 28°C, nắng"

@mcp.resource("weather://{city}/current")
async def weather_resource(city: str) -> str:
    return f"Dữ liệu thời tiết {city}"

if __name__ == "__main__":
    mcp.run(transport="stdio")

Client: Kết nối từ Claude Desktop hoặc code tùy chỉnh

Cấu hình claude_desktop_config.json:

{
  "mcpServers": {
    "weather": {
      "command": "python",
      "args": ["/path/to/weather_server.py"]
    }
  }
}

Hoặc dùng SDK TypeScript/Python trong ứng dụng riêng:

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

const client = new Client({ name: "my-app", version: "1.0" });
await client.connect(new StdioClientTransport({
  command: "python", args: ["weather_server.py"]
}));

const tools = await client.listTools();
const result = await client.callTool({ name: "get_weather", arguments: { city: "Hà Nội" } });

Bảo mật & Best Practices

  • Capability-based: Server chỉ expose tool/resource cần thiết. Không cho LLM quyền root filesystem.
  • User consent: Host nên hỏi xác nhận trước khi gọi tool có side-effect (ghi file, gửi email, tốn tiền API).
  • Sandbox: Chạy MCP Server trong container/VM riêng biệt, giới hạn network/filesystem.
  • Rate limit: Bảo vệ server khỏi loop agent gọi tool vô hạn.

Hệ sinh thái MCP hiện nay

  • Official servers: Filesystem, GitHub, GitLab, PostgreSQL, SQLite, Redis, S3, Slack, Google Drive, Brave Search, Puppeteer…
  • Community: 500+ server trên github.com/modelcontextprotocol/servers
  • Host support: Claude Desktop, Cursor, Zed, VS Code (Cline, Roo Code), Continue, LibreChat…

MCP so với Function Calling / Tool Use truyền thống

Đặc điểm Function Calling (OpenAI/Anthropic) MCP
Chuẩn hóa Vendor-specific schema Open spec, vendor-neutral
Stateful session Không (stateless) Có (session, progress, cancellation)
Resource discovery Không Có (listResources, subscribe)
Prompt templates Không Có (Prompts primitive)
Remote server Phức tạp (cần proxy) Built-in HTTP/SSE/WebSocket

Khi nào nên dùng MCP?

  • Xây dựng AI Agent cần truy cập nhiều nguồn dữ liệu/công cụ khác nhau.
  • Muốn chia sẻ server tool giữa nhiều host/agent khác nhau.
  • Cần bảo mật, audit trail, rate limit cho hành động AI.
  • Triển khai production với remote server, authentication, load balancing.

Tham khảo thêm

Tôi là một lập trình viên IOS. Code chính là IOS nhưng thỉnnh thoảng vẫn đá sang Android hoặc web. Mặc dù không quá thông thạo nhưng tôi sẽ chia sẻ những kiến thức mà mình đã tìm hiểu, áp dụng qua.

Bài viết liên quan

AutoGPT terminal interface showing AI agent planning and executing tasks

AutoGPT và BabyAGI: So sánh 2 Framework Agent AI Tự Chủ Phổ Biến

AutoGPT là một trong những framework agent AI tự chủ đầu tiên được mã nguồn mở, cho phép GPT-4 (hoặc GPT-3.5) tự lập kế hoạch, thực thi và lặp lại…

Xem thêm

LangGraph là gì? Framework orchestration agent AI có state

LangGraph là gì? Framework orchestration AI mã nguồn mở từ LangChain cho phép xây dựng agent AI dạng graph — nơi bạn kết hợp deterministic code và LLM-driven steps trong…

Xem thêm

So sánh hiệu suất của 4 mô hình AI bảo vệ quyền riêng tư

Tổng quan về các mô hình AI bảo vệ quyền riêng tư Trong kỷ nguyên dữ liệu lớn, quyền riêng tư trở thành mối quan tâm hàng đầu khi triển…

Xem thêm
0 0 đánh giá
Article Rating
Theo dõi
Thông báo của
guest
0 Comments
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất