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

MCP Server Logging & Observability

Bạn deploy MCP server lên production 1 tuần rồi user complain "Claude trả sai data" mà không biết tool nào lỗi, request nào, user nào? Câu trả lời nằm ở observability layer mà 70% MCP early-stage skip vì "thêm sau". Theo SurePrompts (2026), audit log retention 12 tháng là yêu cầu compliance bắt buộc cho enterprise. OpenTelemetry trở thành de facto standard cho distributed tracing, structured logging với JSON format giúp debug nhanh 5×. Bài này tổng hợp 3 pillar observability (logs, metrics, traces) cho MCP server, plus code TypeScript ready production cho cộng đồng dev Việt.

Key Takeaways - MCP observability dựa trên 3 pillar: structured logs, metrics (Prometheus), distributed traces (OpenTelemetry) (Anthropic News, 2026). - Audit log retention tối thiểu 12 tháng cho compliance, log mọi tool call kèm who, when, what, params, result (SurePrompts, 2026). - SLO chuẩn cho MCP server: latency p99 <2s, availability 99,9%, tool success rate >99% (Anthropic Docs, 2026). - 78% enterprise team có MCP production, đa phần bắt buộc OpenTelemetry instrumentation (Effloow, 2026).

MCP observability dashboard với traces metrics logs

Vì Sao MCP Server Cần Observability Nghiêm Túc?

Bốn lý do chính: debug khó, compliance bắt buộc, cost optimization, và LLM behavior visibility. Khác với REST API truyền thống, MCP server có thêm dimension "Claude tự chọn tool", debug không có observability gần như không thể.

Khi user complain "Claude trả sai data", debug cần: (1) Request nào? (2) Claude chọn tool gì? (3) Param Claude truyền? (4) Tool trả về data gì? (5) Tool có error không? (6) Latency từng bước? Không có observability, dev mò lại từ đầu, mất 4-8 tiếng/case.

Compliance: enterprise trong tài chính, y tế, công bắt buộc audit log mọi tool call. Theo SurePrompts (2026), retention 12 tháng là minimum, một số ngành (medical, financial) yêu cầu 7 năm. Audit log thiếu = không thể chứng minh compliance khi audit.

Cost optimization: Claude API tính theo token, mỗi tool call tốn $0,01-0,05. Không tracking, không biết tool nào chiếm 80% cost. Pareto thường đúng: 20% tool gây 80% chi phí. Optimize chính xác cần metrics breakdown by tool.

LLM behavior visibility: Claude có thể "hallucinate" tool name, gọi tool sai param, retry quá nhiều khi error. Observability phát hiện pattern bất thường: tool A bị retry 10× cho 5% request. Đây là dấu hiệu prompt cần điều chỉnh, không phải tool lỗi.

Tham khảo thêm: - MCP Authentication Patterns - MCP Security Prevention

OpenTelemetry Tracing Cho MCP Server Là Gì?

OpenTelemetry (OTel) là framework observability open-source, chuẩn de facto cho distributed tracing 2026. Mỗi request tạo 1 trace, gồm nhiều span (mỗi operation = 1 span). Trace cho phép visualize "request đi qua đâu, mất bao lâu ở đâu".

OpenTelemetry distributed tracing spans MCP request flow

Cài đặt OTel cho MCP server TypeScript:

import { NodeSDK } from "@opentelemetry/sdk-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { trace, SpanStatusCode } from "@opentelemetry/api";

const sdk = new NodeSDK({
  traceExporter: new OTLPTraceExporter({
    url: "https://api.honeycomb.io/v1/traces",
    headers: { "x-honeycomb-team": process.env.HONEYCOMB_API_KEY }
  }),
  serviceName: "mcp-acme-server"
});
sdk.start();

const tracer = trace.getTracer("mcp-server");

server.tool("lookup_inventory", { /* schema */ }, async (params) => {
  const span = tracer.startSpan("tool.lookup_inventory");
  span.setAttributes({
    "mcp.tool.name": "lookup_inventory",
    "mcp.user.id": params.userId,
    "mcp.product.code": params.code
  });

  try {
    const result = await sheetsAPI.query(params.code);
    span.setStatus({ code: SpanStatusCode.OK });
    return result;
  } catch (err: any) {
    span.recordException(err);
    span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
    throw err;
  } finally {
    span.end();
  }
});

Span attribute critical: mcp.tool.name, mcp.user.id, mcp.session.id, mcp.error, mcp.latency. Filter trace theo attribute để debug nhanh.

Effloow (2026) cho biết 78% enterprise team production có OTel instrumentation. Backend phổ biến: Honeycomb (developer-friendly), Datadog (enterprise full-stack), Grafana Tempo (open-source self-host), Jaeger (CNCF).

OpenTelemetry Backend Adoption (2026) Datadog Honeycomb Grafana Tempo Jaeger New Relic 38% 28% 22% 15% 9% % MCP server enterprise dùng backend OTel
Nguồn: Effloow MCP Ecosystem Report, 2026

Tham khảo thêm: - MCP Discovery Protocol Đầy Đủ - Build MCP Server TypeScript Step-By-Step

Structured Logging Khác Gì Với console.log?

Structured logging output JSON với field rõ ràng, query được. console.log output text, không query được. Sự khác biệt critical khi production có 10K log/giây.

Structured logging JSON output to ELK Loki Datadog pipeline

Bad (text log):

[2026-05-10T10:30:00Z] User abc123 called lookup_inventory with SP-001, returned 5 items

Good (structured JSON):

{
  "timestamp": "2026-05-10T10:30:00Z",
  "level": "info",
  "service": "mcp-acme",
  "trace_id": "abc-123",
  "span_id": "def-456",
  "user_id": "abc123",
  "tool": "lookup_inventory",
  "params": { "code": "SP-001" },
  "result_count": 5,
  "latency_ms": 420
}

JSON log query được trong Loki/Elasticsearch/Datadog: "tìm log có tool=lookup_inventorylatency_ms > 1000". Text log gần như không query được.

Code TypeScript dùng Pino (logger phổ biến nhất 2026):

import pino from "pino";

const logger = pino({
  level: process.env.LOG_LEVEL || "info",
  formatters: {
    bindings: () => ({
      service: "mcp-acme",
      env: process.env.NODE_ENV
    })
  },
  timestamp: pino.stdTimeFunctions.isoTime
});

server.tool("lookup_inventory", { /* schema */ }, async (params) => {
  const start = Date.now();
  logger.info({ tool: "lookup_inventory", params, user_id: params.userId }, "tool.start");

  try {
    const result = await sheetsAPI.query(params.code);
    logger.info({
      tool: "lookup_inventory",
      latency_ms: Date.now() - start,
      result_count: result.length
    }, "tool.success");
    return result;
  } catch (err: any) {
    logger.error({
      tool: "lookup_inventory",
      error: err.message,
      stack: err.stack,
      latency_ms: Date.now() - start
    }, "tool.error");
    throw err;
  }
});

Pragmatic Engineer (2026) khuyến nghị log level chuẩn: debug (dev only), info (mọi tool call thành công), warn (recoverable error), error (tool fail), fatal (server crash). Production thường set info hoặc warn để tránh log volume quá lớn.

Tham khảo thêm: - MCP Authentication Patterns - MCP Server Caching Strategy

Prometheus Metrics Cần Track Cái Gì Cho MCP?

Bốn nhóm metrics chính: tool call rate, tool latency, tool error rate, claude api cost. Mỗi nhóm phục vụ một câu hỏi vận hành cụ thể.

Prometheus Grafana metrics dashboard cho MCP server SLO

Tool call rate (mcp_tool_calls_total): tổng số tool call, label theo tool_name, user_id, status. Dùng để: detect spike abuse, capacity planning, cost forecast.

Tool latency (mcp_tool_latency_seconds): histogram latency, label theo tool_name, status. Dùng để: monitor SLO p99 <2s, alert khi degradation, debug slow tool.

Tool error rate (mcp_tool_errors_total): error count, label theo tool_name, error_type. Dùng để: alert khi error rate >1%, identify root cause (timeout, auth fail, downstream API).

Claude API cost (mcp_claude_tokens_total): input/output token count, label theo model, user_id. Dùng để: cost forecast, identify heavy user, optimize prompt.

Code TypeScript dùng prom-client:

import { Counter, Histogram } from "prom-client";

const toolCalls = new Counter({
  name: "mcp_tool_calls_total",
  help: "Total tool calls",
  labelNames: ["tool_name", "status"]
});

const toolLatency = new Histogram({
  name: "mcp_tool_latency_seconds",
  help: "Tool latency",
  labelNames: ["tool_name", "status"],
  buckets: [0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10]
});

server.tool("lookup_inventory", { /* schema */ }, async (params) => {
  const end = toolLatency.startTimer({ tool_name: "lookup_inventory" });
  try {
    const result = await sheetsAPI.query(params.code);
    toolCalls.inc({ tool_name: "lookup_inventory", status: "success" });
    end({ status: "success" });
    return result;
  } catch (err) {
    toolCalls.inc({ tool_name: "lookup_inventory", status: "error" });
    end({ status: "error" });
    throw err;
  }
});

Anthropic News (2026) khuyến nghị SLO cho MCP server: latency p99 <2s, availability 99,9%, tool success rate >99%. Vượt threshold = alert tới on-call.

Tham khảo thêm: - MCP Rate Limiting Best Practices - MCP Server Caching Strategy

SLO Và Alert Pattern Cho MCP Production?

SLO (Service Level Objective) là cam kết cụ thể về quality, ví dụ "99,9% request có latency <2s trong rolling 30 ngày". Alert khi vượt threshold giúp on-call response nhanh trước user notice.

Pattern SLO chuẩn cho MCP server: - Availability: 99,9% (max 43 phút downtime/tháng) - Latency p99: <2 giây cho tool đọc, <5 giây cho tool ghi - Tool success rate: >99% (1% error tolerance) - Auth success rate: >99,5%

Alert dùng error budget burn rate. Ví dụ: SLO 99,9% cho phép 0,1% error trong 30 ngày. Nếu trong 1 giờ error rate đạt 1%, đó là 10× faster than budget. Alert ngay khi burn rate >2× cho 1 giờ rolling.

Code Prometheus alert:

groups:
- name: mcp_slo
  rules:
  - alert: MCPHighErrorRate
    expr: |
      (
        sum(rate(mcp_tool_errors_total[5m])) 
        / 
        sum(rate(mcp_tool_calls_total[5m]))
      ) > 0.02
    for: 5m
    annotations:
      summary: "MCP tool error rate >2% trong 5 phút"
      runbook: "https://wiki.acme.com/mcp/error-rate"

  - alert: MCPLatencyHigh
    expr: histogram_quantile(0.99, mcp_tool_latency_seconds_bucket) > 2
    for: 10m
    annotations:
      summary: "MCP latency p99 >2s trong 10 phút"

McKinsey State of AI 2025 ghi nhận 88% tổ chức dùng AI, đa phần chưa định nghĩa SLO rõ ràng cho MCP. Đây là gap lớn cho team đang scale lên enterprise.

Tham khảo thêm: - MCP Discovery Protocol Đầy Đủ - Top MCP Servers Đáng Cài 2026

Audit Log Compliance Cho Doanh Nghiệp Việt?

Nghị định 13/2023 yêu cầu data processor lưu audit log đầy đủ cho mọi xử lý dữ liệu cá nhân, retention tối thiểu 2 năm. Áp dụng MCP server: log mọi tool call có chạm PII (contact, deal, message), đảm bảo retention 24 tháng minimum.

Audit log khác app log: tập trung vào who, what, when không phải why. Field bắt buộc: - actor_id: user nào trigger - actor_type: human / agent - tool_name: tool gì được gọi - tool_params: param gì (redact PII nếu cần) - tool_result_summary: result tóm tắt (không log full PII) - timestamp_iso: thời điểm - trace_id: liên kết với distributed trace

Storage: tách biệt với app log. Audit log immutable (write-only), retention dài, compliance SOC 2 yêu cầu encrypt at rest. Backend phổ biến: AWS CloudTrail (cho AWS infrastructure), Datadog Audit Logs, self-host PostgreSQL với column-level encryption.

SurePrompts (2026) khuyến nghị tách thành 2 stream: 1. App log (Pino → Loki/Datadog): debug, retention 30-90 ngày 2. Audit log (PostgreSQL/CloudTrail): compliance, retention 24 tháng+

Code TypeScript audit log writer:

async function auditLog(event: {
  actor_id: string;
  actor_type: "human" | "agent";
  tool_name: string;
  tool_params: any;
  result_summary: string;
  trace_id: string;
}) {
  await auditDB.query(`
    INSERT INTO audit_log (actor_id, actor_type, tool_name, params_json, result_summary, trace_id, ts)
    VALUES ($1, $2, $3, $4, $5, $6, NOW())
  `, [
    event.actor_id, event.actor_type, event.tool_name,
    JSON.stringify(redactPII(event.tool_params)),
    event.result_summary, event.trace_id
  ]);
}

Tham khảo thêm: - MCP Authentication Patterns - Claude Compliance Cho Doanh Nghiệp Việt

FAQ: Câu Hỏi Thường Gặp Về MCP Observability

1. OpenTelemetry có overhead lớn không? Không. Sampling 1-5% cho production thường đủ. Theo Anthropic Docs (2026), OTel overhead <2% latency cho hầu hết workload.

2. Datadog vs Honeycomb, chọn cái nào? Datadog full-stack enterprise, expensive. Honeycomb developer-friendly, cheaper, focus trace. Theo Effloow (2026), team <50 dev thường chọn Honeycomb.

3. Self-host vs SaaS observability backend? SaaS đỡ ops, scale auto. Self-host (Loki + Grafana + Tempo) cheaper với data lớn nhưng cần ops effort. Trade-off: SaaS $200-2000/tháng cho data 1TB/tháng, self-host VPS $50/tháng + 8h/tuần ops.

4. Có thể dùng Sentry cho MCP error tracking không? Có, Sentry hợp với error tracking + performance monitoring. Bổ sung OTel cho distributed tracing. Theo Pragmatic Engineer (2026), pattern phổ biến là Sentry + Honeycomb song song.

5. Audit log có cần immutable không? Có với compliance SOC 2 và regulated industries. Pattern: write-only table, không UPDATE/DELETE, backup encrypted với key rotation. Theo SurePrompts (2026), AWS CloudTrail là backend phổ biến nhất cho audit immutable.

Kết Luận: Observability Là Khoản Đầu Tư Phải Làm Sớm

Setup observability ngày 1 đắt nhưng add sau 6 tháng còn đắt hơn 10×. OpenTelemetry + structured logging + Prometheus là combo de facto. Audit log compliance là requirement không phải optional cho doanh nghiệp Việt theo Nghị định 13/2023.

Bước tiếp theo nên làm: - Cài @opentelemetry/sdk-node, configure backend (Honeycomb hoặc Datadog) - Replace console.log bằng Pino structured logger với JSON output - Setup Prometheus + Grafana, track 4 metric core (calls, latency, errors, cost) - Define SLO: p99 <2s, availability 99,9%, success rate >99% - Tách audit log riêng khỏi app log, retention 24 tháng PostgreSQL encrypted - Setup alert burn rate, page on-call khi vượt 2× error budget

Tham khảo thêm: - MCP Là Gì? Tổng Quan 2026 - MCP Authentication Patterns Đầy Đủ - MCP Rate Limiting Best Practices - MCP Caching Strategy

trong Claude AI
Claude Memory Across Conversations