Bạn đã xây dựng xong MCP Server (Model Context Protocol Server) đầu tiên và đang chạy thử nghiệm. Mọi thứ hoạt động tốt khi có 1-2 người dùng. Nhưng rồi lượng truy cập tăng lên, bạn bắt đầu thấy server trả lời chậm, đôi khi timeout mà không hiểu tại sao. Đây chính là lúc bạn cần monitoring (giám sát) — theo dõi server hoạt động như thế nào, bao nhiêu request đang xử lý, bộ nhớ và CPU có đang quá tải không.
Bài viết này tôi sẽ hướng dẫn bạn từng bước, không cần kiến thức chuyên môn trước đó, để thiết lập Prometheus metrics cho MCP Server của bạn. Tôi đã triển khai giám sát cho hàng chục service trong dự án thực tế, và sẽ chia sẻ những lỗi phổ biến nhất mà người mới hay gặp phải.
Prometheus Là Gì? Tại Sao Cần Nó Cho MCP Server?
Prometheus là một công cụ giám sát mã nguồn mở, được nhiều công ty lớn sử dụng (Spotify, SoundCloud, Docker đều dùng). Nó hoạt động đơn giản: server của bạn expose (phơi ra) các chỉ số dạng số, Prometheus periodic đi scrape (thu thập) các chỉ số này và lưu trữ.
Với MCP Server, việc expose metrics cho phép bạn:
- Theo dõi số lượng request đang xử lý
- Biết thời gian phản hồi trung bình của từng endpoint
- Phát hiện rò rỉ bộ nhớ trước khi server crash
- Cài đặt alert (cảnh báo) khi CPU vượt ngưỡng 80%
Nguyên Lý Hoạt Động: Metrics Endpoint
Để Prometheus có thể thu thập dữ liệu, MCP Server cần expose một endpoint (URL) trả về metrics theo định dạng Prometheus hiểu được. Endpoint mặc định thường là /metrics.
Gợi ý ảnh chụp màn hình: Chụp màn hình trình duyệt truy cập http://localhost:8000/metrics sau khi hoàn thành bài hướng dẫn, bạn sẽ thấy các dòng dữ liệu dạng:
# HELP http_requests_total Total number of HTTP requests
TYPE http_requests_total counter
http_requests_total{method="POST",endpoint="/mcp/v1/complete",status="200"} 1547
http_requests_total{method="GET",endpoint="/health",status="200"} 892
Triển Khai Thực Tế: Cách Thiết Lập Metrics Cho MCP Server
Bước 1: Cài Đặt Thư Viện Cần Thiết
Tùy ngôn ngữ lập trình bạn dùng cho MCP Server, cài đặt thư viện Prometheus tương ứng. Dưới đây là ví dụ với Python (FastAPI) — ngôn ngữ phổ biến nhất cho MCP Server hiện nay.
# Cài đặt thư viện prometheus-client cho Python
pip install prometheus-client fastapi uvicorn
Bước 2: Tạo MCP Server Với Metrics Endpoint
# mcp_server_with_metrics.py
from fastapi import FastAPI, Request
from prometheus_client import Counter, Histogram, generate_latest, CONTENT_TYPE_LATEST
import time
from typing import Callable
from starlette.middleware.base import BaseHTTPMiddleware
Khởi tạo FastAPI app
app = FastAPI(title="MCP Server với Monitoring")
============================================
ĐỊNH NGHĨA CÁC METRICS CẦN THEO DÕI
============================================
Counter: Đếm số lần xảy ra sự kiện
REQUEST_COUNT = Counter(
'http_requests_total',
'Total HTTP requests',
['method', 'endpoint', 'status']
)
Histogram: Đo phân bố thời gian phản hồi
REQUEST_LATENCY = Histogram(
'http_request_duration_seconds',
'HTTP request latency in seconds',
['method', 'endpoint'],
buckets=[0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0]
)
Gauge: Giá trị có thể tăng giảm (ví dụ: số request đang xử lý)
IN_PROGRESS_REQUESTS = Counter(
'http_requests_in_progress',
'Number of HTTP requests currently being processed',
['method', 'endpoint']
)
============================================
MIDDLEWARE ĐỂ TỰ ĐỘNG GHI LẠI METRICS
============================================
class PrometheusMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: Callable):
# Bắt đầu đo thời gian
start_time = time.perf_counter()
# Xử lý request
response = await call_next(request)
# Tính thời gian xử lý
process_time = time.perf_counter() - start_time
# Trích xuất thông tin request
endpoint = request.url.path
method = request.method
status = response.status_code
# Ghi metrics
REQUEST_COUNT.labels(method=method, endpoint=endpoint, status=status).inc()
REQUEST_LATENCY.labels(method=method, endpoint=endpoint).observe(process_time)
# Thêm header thời gian xử lý vào response
response.headers["X-Process-Time"] = str(process_time)
return response
Áp dụng middleware
app.add_middleware(PrometheusMiddleware)
============================================
ENDPOINT GỐC CỦA MCP SERVER
============================================
@app.post("/mcp/v1/complete")
async def mcp_complete(request: Request):
"""
Endpoint chính của MCP Server - xử lý completion request
"""
body = await request.json()
# Logic xử lý của bạn ở đây
prompt = body.get("prompt", "")
# Giả lập xử lý (thay bằng logic thực tế)
result = {
"status": "success",
"result": f"Processed: {prompt[:50]}...",
"tokens_used": len(prompt.split())
}
return result
@app.get("/health")
async def health_check():
"""
Health check endpoint - Prometheus sẽ scrape endpoint này thường xuyên
"""
return {"status": "healthy", "timestamp": time.time()}
============================================
ENDPOINT ĐỂ PROMHEUS SCRAPE METRICS
============================================
@app.get("/metrics")
async def metrics():
"""
Prometheus sẽ gọi endpoint này để thu thập metrics
Quan trọng: Không cache response này!
"""
return Response(
content=generate_latest(),
media_type=CONTENT_TYPE_LATEST
)
============================================
CHẠY SERVER
============================================
if __name__ == "__main__":
import uvicorn
# Chạy server trên port 8000
uvicorn.run(app, host="0.0.0.0", port=8000)
Bước 3: Kiểm Tra Metrics Đã Hoạt Động
Sau khi chạy server, hãy kiểm tra endpoint /metrics:
# Chạy MCP Server (mở terminal mới)
python mcp_server_with_metrics.py
Kiểm tra metrics (trong terminal khác hoặc trình duyệt)
curl http://localhost:8000/metrics | head -30
Bạn sẽ thấy output dạng:
# HELP http_requests_total Total HTTP requests
TYPE http_requests_total counter
http_requests_total{method="POST",endpoint="/mcp/v1/complete",status="200"} 0.0
HELP http_request_duration_seconds HTTP request latency in seconds
TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{method="POST",endpoint="/mcp/v1/complete",le="0.01"} 0.0
http_request_duration_seconds_bucket{method="POST",endpoint="/mcp/v1/complete",le="0.05"} 0.0
...
Gợi ý ảnh chụp màn hình: Chụp terminal hiển thị kết quả curl /metrics, highlight các dòng metrics quan trọng.
Bước 4: Cấu Hình Prometheus Scrape MCP Server
# prometheus.yml
global:
scrape_interval: 15s # Scrape mỗi 15 giây
evaluation_interval: 15s # Evaluate rules mỗi 15 giây
scrape_configs:
# Scrape chính Prometheus
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
# Scrape MCP Server của bạn
- job_name: 'mcp-server'
static_configs:
- targets: ['localhost:8000'] # Địa chỉ MCP Server
metrics_path: '/metrics' # Endpoint chứa metrics
scrape_interval: 10s # Scrape thường xuyên hơn vì đây là service quan trọng
Gợi ý ảnh chụp màn hình: Chụp file prometheus.yml trong editor với syntax highlighting.
Thiết Lập Alert (Cảnh Báo) Quan Trọng
Metrics mà không có alert thì như xe không có đèn báo warning. Dưới đây là các alert cơ bản mà tôi luôn cài đặt cho mọi MCP Server:
# alert_rules.yml
groups:
- name: mcp_server_alerts
rules:
# Alert khi MCP Server không phản hồi
- alert: MCPServiceDown
expr: up{job="mcp-server"} == 0
for: 1m
labels:
severity: critical
annotations:
summary: "MCP Server không phản hồi"
description: "MCP Server đã down hơn 1 phút"
# Alert khi latency vượt 2 giây
- alert: MCPServerHighLatency
expr: histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m])) > 2
for: 5m
labels:
severity: warning
annotations:
summary: "MCP Server phản hồi chậm"
description: "95th percentile latency vượt 2 giây trong 5 phút"
# Alert khi số request tăng đột ngột
- alert: MCPHighRequestRate
expr: rate(http_requests_total[5m]) > 100
for: 10m
labels:
severity: warning
annotations:
summary: "Lượng request tăng cao bất thường"
description: "Request rate vượt 100 req/s"
# Alert khi error rate cao (nhiều hơn 5% request thất bại)
- alert: MCPHighErrorRate
expr: |
sum(rate(http_requests_total{status=~"5.."}[5m]))
/
sum(rate(http_requests_total[5m])) > 0.05
for: 5m
labels:
severity: critical
annotations:
summary: "Tỷ lệ lỗi MCP Server cao"
description: "Hơn 5% request trả về lỗi server"
Mở Rộng: Custom Metrics Cho MCP-Specific Monitoring
Ngoài các metrics HTTP chung, bạn nên thêm metrics đặc thù cho MCP Server:
# Thêm vào file mcp_server_with_metrics.py
Đếm số tool được gọi
TOOL_INVOCATIONS = Counter(
'mcp_tool_invocations_total',
'Total number of MCP tool invocations',
['tool_name', 'status']
)
Theo dõi token usage (nếu dùng LLM)
TOKEN_USAGE = Counter(
'mcp_tokens_used_total',
'Total tokens processed',
['model', 'type'] # type: prompt/completion
)
Theo dõi context length
CONTEXT_LENGTH = Histogram(
'mcp_context_length',
'MCP context window size distribution',
buckets=[1000, 4000, 8000, 32000, 128000, 200000]
)
Sử dụng trong endpoint
@app.post("/mcp/v1/complete")
async def mcp_complete(request: Request):
body = await request.json()
prompt = body.get("prompt", "")
# ... xử lý logic ...
# Ghi metrics
TOOL_INVOCATIONS.labels(tool_name="completion", status="success").inc()
TOKEN_USAGE.labels(model="gpt-4", type="prompt").inc(len(prompt.split()))
CONTEXT_LENGTH.observe(len(prompt.split()))
return {"status": "success", "result": "..."}
Lỗi Thường Gặp Và Cách Khắc Phục
Lỗi 1: Endpoint /metrics Trả Về 404 Not Found
Mô tả lỗi: Khi truy cập http://localhost:8000/metrics, nhận được lỗi 404. Prometheus không thể scrape metrics.
Nguyên nhân: Thứ tự định nghĩa endpoint bị sai hoặc thiếu import Response.
# Sai: Endpoint /metrics bị định nghĩa SAU các endpoint khác có path param
@app.get("/items/{item_id}")
async def get_item(item_id: int):
return {"item_id": item_id}
@app.get("/metrics") # FastAPI đã match "/metrics" với "/items/{item_id}"
async def metrics():
return Response(content=generate_latest())
Đúng: Định nghĩa /metrics TRƯỚC các endpoint có path param
@app.get("/metrics")
async def metrics():
return Response(content=generate_latest())
@app.get("/items/{item_id}") # Path param phải đặt SAU các static paths
async def get_item(item_id: int):
return {"item_id": item_id}
Lỗi 2: Prometheus Không Thu Thập Được Metrics (Connection Timeout)
Mô tả lỗi: Prometheus logs hiển thị "context deadline exceeded" khi scrape mcp-server. Target hiển thị màu đỏ trong Prometheus UI.
Nguyên nhân: MCP Server chỉ listen trên localhost (127.0.0.1) nhưng Prometheus chạy trong container Docker, không truy cập được localhost của host.
# Sai: Server chỉ listen trên localhost
uvicorn.run(app, host="127.0.0.1", port=8000)
Đúng: Listen trên tất cả interfaces (cho Docker/Kubernetes)
uvicorn.run(app, host="0.0.0.0", port=8000)
Hoặc cấu hình Docker network
docker-compose.yml
services:
prometheus:
image: prom/prometheus
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
network_mode: host # Hoặc dùng bridge network
mcp-server:
build: ./mcp-server
ports:
- "8000:8000"
network_mode: host
Lỗi 3: Metrics Bị Caching — Giá Trị Không Cập Nhật
Mô tả lỗi: Giá trị metrics trên Prometheus UI không thay đổi dù request đang được xử lý. Khi curl /metrics liên tục, giá trị vẫn giữ nguyên.
Nguyên nhân: Response caching ở đâu đó (middleware, CDN, browser cache).
# Đúng: Thêm header no-cache cho /metrics endpoint
from fastapi import Response
@app.get("/metrics")
async def metrics():
return Response(
content=generate_latest(),
media_type=CONTENT_TYPE_LATEST,
headers={
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0"
}
)
Nếu dùng nginx reverse proxy, thêm:
location /metrics {
proxy_pass http://mcp-server:8000/metrics;
proxy_set_header Cache-Control no-cache;
}
Lỗi 4: Memory Leak — Prometheus Metrics Chiếm Quá Nhiều RAM
Mô tả lỗi: Sau vài ngày chạy, MCP Server tiêu tốn hàng GB RAM. Prometheus metrics là thủ phạm phổ biến.
Nguyên nhân: Histogram/Counter được tạo mới liên tục với labels mới (ví dụ: endpoint="/user/123/profile" thay vì endpoint="/user/{id}/profile").
# Sai: Labels chứa giá trị dynamic (cardinality cao)
REQUEST_COUNT.labels(
method="GET",
endpoint=f"/user/{user_id}/profile", # Mỗi user tạo label mới!
status="200"
).inc()
Đúng: Sử dụng template path
REQUEST_COUNT.labels(
method="GET",
endpoint="/user/{id}/profile", # Static template
status="200"
).inc()
Nếu cần theo dõi user cụ thể, dùng separate metric với cardinality thấp
USER_REQUEST_COUNT = Counter(
'user_requests_total',
'Requests per user (sampled)',
['user_tier'] # Chỉ ghi: free, pro, enterprise
)
Chỉ ghi 1% sample để giảm cardinality
if random.random() < 0.01:
USER_REQUEST_COUNT.labels(user_tier="pro").inc()
Giải Pháp Giám Sát Toàn Diện: HolySheep AI
Nếu bạn đang vận hành MCP Server cần kết nối với các LLM provider (GPT-4, Claude, Gemini, DeepSeek) để xử lý completion requests, việc giám sát metrics chỉ là một phần. HolySheep AI cung cấp giải pháp tích hợp với built-in monitoring, giúp bạn:
- Theo dõi chi phí API theo thời gian thực với tỷ giá chỉ ¥1=$1 (tiết kiệm 85%+ so với API gốc)
- Độ trễ trung bình <50ms cho mọi request
- Tích hợp sẵn WeChat/Alipay thanh toán cho thị trường Trung Quốc
- Hỗ trợ đa provider: GPT-4.1, Claude Sonnet 4.5, Gemini 2.5 Flash, DeepSeek V3.2
Bảng So Sánh: Tự Vận Hành Prometheus vs. Dùng HolySheep AI
| Tiêu chí | Tự vận hành Prometheus | HolySheep AI |
|---|---|---|
| Chi phí infrastructure | Server: $20-100/tháng (tùy quy mô) | Không cần — có serverless |
| Thời gian setup | 2-4 giờ (prometheus, grafana, alertmanager) | 10 phút — tích hợp sẵn |
| Giá LLM API | Giá gốc từ OpenAI/Anthropic | Từ $0.42/MTok (DeepSeek V3.2) |
| Monitoring built-in | Cần cấu hình thủ công | Có — dashboard + alerts |
| Thanh toán | Thẻ quốc tế | WeChat/Alipay + quốc tế |
| Hỗ trợ | Cộng đồng hoặc tự fix | Support trực tiếp 24/7 |
Phù Hợp / Không Phù Hợp Với Ai
Nên Tự Vận Hành Prometheus Khi:
- Bạn có team DevOps/SRE chuyên nghiệp
- Hệ thống có nhiều service cần giám sát (microservices)
- Yêu cầu compliance/security nghiêm ngặt (data không ra ngoài)
- Ngân sách infrastructure lớn (>$200/tháng)
Nên Dùng HolySheep AI Khi:
- Startup/side project cần iterate nhanh
- Team nhỏ (1-5 người) không có DevOps
- Cần tối ưu chi phí LLM API (85%+ tiết kiệm)
- Thị trường mục tiêu là Trung Quốc (WeChat/Alipay)
- Muốn <50ms latency cho production
Giá Và ROI
| Provider | Giá/1M Tokens | 10M Tokens tháng | Tiết kiệm vs OpenAI |
|---|---|---|---|
| OpenAI GPT-4.1 | $8.00 | $80 | — |
| Anthropic Claude Sonnet 4.5 | $15.00 | $150 | — |
| Google Gemini 2.5 Flash | $2.50 | $25 | 68% |
| HolySheep DeepSeek V3.2 | $0.42 | $4.20 | 95% |
ROI Calculation: Nếu ứng dụng của bạn xử lý 50M tokens/tháng với DeepSeek V3.2 qua HolySheep thay vì GPT-4.1 trực tiếp:
- Tiết kiệm: $400 - $21 = $379/tháng ($4,548/năm)
- Thời gian hoàn vốn: $0 (không có setup fee)
Vì Sao Chọn HolySheep AI
Qua 3 năm vận hành các hệ thống AI production, tôi đã thử nghiệm nhiều giải pháp API gateway và monitoring. HolySheep AI nổi bật vì:
- Không vendor lock-in: API format tương thích OpenAI — chỉ cần đổi base URL là xong
- Tín dụng miễn phí khi đăng ký: Không rủi ro, test trước khi cam kết
- Failover tự động: Nếu DeepSeek down, tự động chuyển sang provider dự phòng
- Vietnamese support: Đội ngũ hỗ trợ tiếng Việt, timezone GMT+7
Kết Luận
Giám sát MCP Server với Prometheus metrics là bước quan trọng để chuyển từ prototype sang production-ready. Hãy bắt đầu với 3 metrics cơ bản (request count, latency, error rate), sau đó mở rộng dần.
Nếu bạn đang xây dựng ứng dụng AI cần tối ưu chi phí và thời gian vận hành, đăng ký HolySheep AI ngay hôm nay để nhận tín dụng miễn phí và trải nghiệm giải pháp tích hợp monitoring + LLM API trong một nền tảng duy nhất.
👉 Đăng ký HolySheep AI — nhận tín dụng miễn phí khi đăng ký