Bỏ qua để đến nội dung

MCP Servers

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.


┌─────────────────────────────────────────┐
│ MCP SERVER │
│ │
│ ┌───────────┐ ┌───────────┐ ┌───────────┐
│ │ Resources │ │ Tools │ │ Prompts │
│ │ │ │ │ │ │
│ │ - Files │ │ - Actions │ │ - Templates│
│ │ - DB data │ │ - APIs │ │ - Workflows│
│ │ - Logs │ │ - Queries │ │ - Guides │
│ └───────────┘ └───────────┘ └───────────┘
│ │
└─────────────────────────────────────────┘

Data cho AI đọc. Thường là read-only.

@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})
Pattern Ví dụ
file:///{path} file:///Users/me/doc.txt
db://table/{id} db://users/123
api://endpoint api://weather/current

Actions mà AI có thể thực hiện. Có thể có side-effects.

@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)
{
"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"]
}
}

Câu hỏi/workflow mẫu để user dùng nhanh.

@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 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

Terminal window
# Filesystem
npx -y @modelcontextprotocol/server-filesystem /path/to/folder
# PostgreSQL
DATABASE_URL=postgres://... npx -y @modelcontextprotocol/server-postgres
# GitHub
GITHUB_TOKEN=ghp_xxx npx -y @modelcontextprotocol/server-github
# Memory (persistent across sessions)
npx -y @modelcontextprotocol/server-memory

from mcp.server.fastmcp import FastMCP
# Khởi tạo server
mcp = 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 server
if __name__ == "__main__":
mcp.run()

Viết một MCP Server đơn giản với cả 3 primitives.

todo_server.py
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Todo Server")
# In-memory storage
todos = []
# 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()
{
"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”

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.