MCP Servers
Khái niệm cơ bản
Phần tiêu đề “Khái niệm cơ bản”Tưởng tượng Server như “nhà máy cung cấp điện”…
- Nhà máy có máy phát điện (Resources - data)
- Nhà máy có công nhân vận hành (Tools - actions)
- Nhà máy có hướng dẫn sử dụng (Prompts - templates)
Server = Nơi cung cấp data, tools, và prompts cho AI sử dụng.
3 Primitives của MCP Server
Phần tiêu đề “3 Primitives của MCP Server”┌─────────────────────────────────────────┐│ MCP SERVER ││ ││ ┌───────────┐ ┌───────────┐ ┌───────────┐│ │ Resources │ │ Tools │ │ Prompts ││ │ │ │ │ │ ││ │ - Files │ │ - Actions │ │ - Templates││ │ - DB data │ │ - APIs │ │ - Workflows││ │ - Logs │ │ - Queries │ │ - Guides ││ └───────────┘ └───────────┘ └───────────┘│ │└─────────────────────────────────────────┘1. Resources (Tài nguyên)
Phần tiêu đề “1. Resources (Tài nguyên)”Data cho AI đọc. Thường là read-only.
Ví dụ Resources
Phần tiêu đề “Ví dụ Resources”@mcp.resource("file:///{path}")def read_file(path: str) -> str: """Read content of a file.""" with open(path) as f: return f.read()
@mcp.resource("db://users/{user_id}")def get_user(user_id: str) -> dict: """Get user profile from database.""" return db.users.find_one({"id": user_id})Resource URI Patterns
Phần tiêu đề “Resource URI Patterns”| Pattern | Ví dụ |
|---|---|
file:///{path} |
file:///Users/me/doc.txt |
db://table/{id} |
db://users/123 |
api://endpoint |
api://weather/current |
2. Tools (Công cụ)
Phần tiêu đề “2. Tools (Công cụ)”Actions mà AI có thể thực hiện. Có thể có side-effects.
Ví dụ Tools
Phần tiêu đề “Ví dụ Tools”@mcp.tool()def send_email(to: str, subject: str, body: str) -> str: """Send an email to the specified recipient.""" email_client.send(to=to, subject=subject, body=body) return f"Email sent to {to}"
@mcp.tool()def query_database(sql: str) -> list: """Execute SQL query on the database.""" return db.execute(sql).fetchall()
@mcp.tool()def create_github_issue(repo: str, title: str, body: str) -> dict: """Create a new GitHub issue.""" return github.create_issue(repo, title, body)Tool Definition (JSON Schema)
Phần tiêu đề “Tool Definition (JSON Schema)”{ "name": "send_email", "description": "Send an email to the specified recipient", "inputSchema": { "type": "object", "properties": { "to": {"type": "string", "description": "Email address"}, "subject": {"type": "string"}, "body": {"type": "string"} }, "required": ["to", "subject", "body"] }}3. Prompts (Templates)
Phần tiêu đề “3. Prompts (Templates)”Câu hỏi/workflow mẫu để user dùng nhanh.
Ví dụ Prompts
Phần tiêu đề “Ví dụ Prompts”@mcp.prompt()def code_review(code: str) -> str: """Review code for bugs, security issues, and best practices.""" return f""" Please review the following code:
[CODE START] {code} [CODE END]
Check for: 1. Bugs and logic errors 2. Security vulnerabilities 3. Performance issues 4. Code style and best practices """
@mcp.prompt()def summarize_logs(log_file: str) -> str: """Summarize system logs and highlight issues.""" logs = read_file(log_file) return f"Summarize these logs and highlight any errors:\n{logs}"Server phổ biến
Phần tiêu đề “Server phổ biến”| Server | Primitives | Chức năng |
|---|---|---|
| Filesystem | Resources, Tools | Đọc/ghi files |
| PostgreSQL | Resources, Tools | Query database |
| GitHub | Resources, Tools | Issues, PRs, repos |
| Slack | Resources, Tools | Messages, channels |
| Memory | Resources, Tools | Persistent memory |
| Fetch | Tools | HTTP requests |
| Puppeteer | Tools | Browser automation |
Cài đặt Server từ NPM
Phần tiêu đề “Cài đặt Server từ NPM”# Filesystemnpx -y @modelcontextprotocol/server-filesystem /path/to/folder
# PostgreSQLDATABASE_URL=postgres://... npx -y @modelcontextprotocol/server-postgres
# GitHubGITHUB_TOKEN=ghp_xxx npx -y @modelcontextprotocol/server-github
# Memory (persistent across sessions)npx -y @modelcontextprotocol/server-memoryViết Custom Server (Python)
Phần tiêu đề “Viết Custom Server (Python)”from mcp.server.fastmcp import FastMCP
# Khởi tạo servermcp = FastMCP("My Custom Server")
# Resource: đọc data@mcp.resource("weather://current/{city}")def get_weather(city: str) -> dict: """Get current weather for a city.""" return {"city": city, "temp": 25, "condition": "sunny"}
# Tool: thực hiện action@mcp.tool()def calculate(expression: str) -> str: """Calculate a math expression.""" result = eval(expression) # Cẩn thận với eval! return f"Result: {result}"
# Prompt: template có sẵn@mcp.prompt()def explain_code(language: str) -> str: """Explain code in simple terms.""" return f"Explain the following {language} code in simple Vietnamese:"
# Chạy serverif __name__ == "__main__": mcp.run()Bài tập thực hành
Phần tiêu đề “Bài tập thực hành”Mục tiêu
Phần tiêu đề “Mục tiêu”Viết một MCP Server đơn giản với cả 3 primitives.
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Todo Server")
# In-memory storagetodos = []
# Resource: list all todos@mcp.resource("todos://all")def list_todos() -> list: """Get all todo items.""" return todos
# Tool: add a todo@mcp.tool()def add_todo(task: str) -> str: """Add a new todo item.""" todos.append({"task": task, "done": False}) return f"Added: {task}"
# Tool: complete a todo@mcp.tool()def complete_todo(index: int) -> str: """Mark a todo as complete.""" if 0 <= index < len(todos): todos[index]["done"] = True return f"Completed: {todos[index]['task']}" return "Invalid index"
# Prompt: daily planning@mcp.prompt()def daily_plan() -> str: """Create a daily plan based on todos.""" return "Based on my todo list, create a daily schedule with time blocks."
if __name__ == "__main__": mcp.run()Config Claude Desktop
Phần tiêu đề “Config Claude Desktop”{ "mcpServers": { "todo": { "command": "python3", "args": ["/path/to/todo_server.py"] } }}- “Thêm task: Học MCP”
- “Liệt kê todos”
- “Đánh dấu task 0 hoàn thành”
Tóm tắt
Phần tiêu đề “Tóm tắt”| Primitive | Tính chất | Ví dụ |
|---|---|---|
| Resources | Read data | Files, DB records |
| Tools | Execute actions | Send email, query DB |
| Prompts | Templates | Code review, summarize |
Bài tiếp theo: Using Existing Servers - Cài server có sẵn.