MCP: Giao Thức Kết Nối AI Agent Với Tool Bên Ngoài

MCP Là Gì?
TL;DR: MCP (Model Context Protocol) — giao thức mở do Anthropic phát triển, giúp AI agent kết nối với bất kỳ tool, database hay API nào. Think USB-C cho AI integration.
Trước MCP, mỗi LLM provider có kiểu tool calling riêng:
- OpenAI dùng function calling + JSON schema
- Anthropic có tool_use format
- LangChain có tool abstraction riêng
Viết tool một lần → adapt cho từng framework. Đổi GPT sang Claude? Viết lại.
MCP giải quyết bằng protocol chuẩn:
- Server — expose tool (database, API, file system...)
- Client — AI agent gọi tool
- JSON-RPC — giao thức truyền thông giữa hai bên
Kiến Trúc
AI Agent (MCP Client) ←── JSON-RPC ──→ MCP Server (Tool Provider)
3 capability chính:
- Tools — function AI agent có thể gọi (query DB, call API...)
- Resources — data agent có thể đọc (file, config...)
- Prompts — template prompt sử dụng được
Flow: Client gửi initialize → tools/list → Server trả schema → LLM gọi tools/call → Server thực thi.
Build MCP Server — 50 Dòng Code
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: "my-server", version: "1.0.0" });
server.tool(
"get_weather",
"Lấy thời tiết theo thành phố",
{ city: z.string() },
async ({ city }) => ({
content: [{ type: "text", text: `Thời tiết ${city}: 32°C, nắng nhẹ` }],
})
);
const transport = new StdioServerTransport();
await server.connect(transport);
Test bằng MCP Inspector: npx @modelcontextprotocol/inspector node dist/server.js
Kết nối với Claude Desktop — thêm config:
{
"mcpServers": {
"weather": { "command": "node", "args": ["dist/server.js"] }
}
}
MCP vs Function Calling
- Function calling — tightly coupled LLM provider. OpenAI schema ≠ Anthropic schema.
- MCP — decoupled. Viết server một lần, mọi MCP client dùng được.
Nên dùng MCP khi: nhiều tool, nhiều LLM, agent system phức tạp. Đơn giản 1-2 tool với 1 provider → function calling đủ.
Tips Production
- Tool description — LLM chọn tool dựa trên description. Viết rõ ràng, có ví dụ.
- Kiểm tra input — không trust client. Kiểm tra SQL chỉ SELECT, rate limit mỗi tool.
- Error message — trả lỗi rõ ràng cho LLM để nó quyết định retry hay báo user.
- Local vs Remote — stdio cho dev, SSE/HTTP cho production.
Kết Luận
- MCP đang trở thành infrastructure layer cho AI agent ecosystem
- Viết tool một lần, dùng mọi LLM — không bị lock-in
- Community ecosystem đang phát triển nhanh (
github.com/modelcontextprotocol/servers) - 2026 roadmap: agent-to-agent communication, enterprise security
Để bắt đầu: build 1 MCP server đơn giản, test với Inspector, rồi connect với Claude Desktop.
Bài viết nằm trong series AI For Developers — hướng dẫn thực tế cho developer muốn dùng AI trong công việc.