Chuyển tới nội dung chính

MCP Server

MCP là gì?

Model Context Protocol (MCP) là một giao thức mở (open specification) cho phép kết nối các ứng dụng AI (LLM clients) với tools và resources bên ngoài. MCP Server expose các tools mà model AI có thể gọi trong cuộc hội thoại, nhận tham số từ model, thực thi logic, và trả về kết quả.

Trong AI App, MCP là xương sống giữ cho server, model, và UI đồng bộ. Bằng cách chuẩn hóa wire format, authentication, và metadata, nó giúp LLM hiểu và sử dụng app của bạn giống như sử dụng built-in tools.

3 khả năng cơ bản

MCP Server cho AI App cần implement 3 capabilities:

1. List Tools

Server liệt kê danh sách tools, bao gồm:

  • Tên và mô tả (để model biết khi nào gọi)
  • JSON Schema cho input và output
  • Annotations (readOnlyHint, destructiveHint, openWorldHint)
// Ví dụ: Tool "search_restaurants"
{
name: "search_restaurants",
description: "Use this when the user wants to find nearby restaurants.",
inputSchema: {
type: "object",
properties: {
query: { type: "string", description: "Từ khóa tìm kiếm" },
location: { type: "string", description: "Vị trí (lat,lng)" },
},
required: ["query"],
},
annotations: {
readOnlyHint: true,
destructiveHint: false,
openWorldHint: false,
},
}

2. Call Tools

Khi model chọn tool, nó gửi request tools/call với arguments tương ứng. Server thực thi action và trả về structured content mà model có thể đọc.

3. Return Components

Ngoài dữ liệu structured, mỗi tool có thể trỏ tới embedded resource — một UI template (HTML) sẽ được render trong Chat client. Khai báo qua _meta.ui.resourceUri trong tool descriptor.

_meta: {
ui: {
resourceUri: "ui://widget/restaurant-list", // Link tới widget HTML
},
}

Tại sao dùng MCP?

Lợi íchMô tả
Extensible AuthOAuth 2.1, dynamic client registration — không cần tự build handshake
Multiclient SupportMCP tự mô tả, connector hoạt động trên cả web và mobile mà không cần code riêng
Conversation AwarenessStructured content và component state tham gia vào cuộc hội thoại — model có thể tham chiếu ID, gọi follow-up
Discovery IntegrationModel sử dụng tool metadata để natural-language discovery và launcher ranking

Transport

MCP hỗ trợ 2 phương thức transport:

TransportKhuyến nghịMô tả
Streamable HTTP✅ RecommendedHTTP POST/GET trên /mcp, hỗ trợ streaming responses
Server-Sent EventsCũng hỗ trợSSE cho real-time updates

Server phải expose endpoint HTTPS tại /mcp path, hỗ trợ streaming responses và trả HTTP status codes phù hợp.

SDK hỗ trợ

SDKPackageCài đặt
TypeScript@modelcontextprotocol/sdknpm install @modelcontextprotocol/sdk @modelcontextprotocol/ext-apps zod
Pythonmcppip install mcp

Cả hai SDK đều cung cấp helper functions cho:

  • Đăng ký tools và resources
  • Xử lý authentication (token verification)
  • Expose HTTP server với CORS

Tài liệu tham khảo