NewAI Content Creation is now live in Early Access
Turning Point Training Instituteby Training Center
Skip to content
0%
Module 4 — Advanced: tool design and efficiencyLesson 2 of 2
8 min readIntermediate
Downloads & resources
Download this lesson's materials, ready to use.

Errors, diagnostics, logging and observability for MCP servers

Example prompt

What changed in V2: this lesson id used to hold the "many tools vs code" debate, which now lives in L15. This lesson is new: it covers what you need when a server misbehaves in production.

Where you are

Your L11 server works, is locked down (L14) and lean (L15). When a user says "the tool failed", can you tell what happened without guessing, and without leaking a secret into a log?

What you will be able to do

  • Choose between a tool execution error (isError: true) and a protocol error, and write error messages a model can act on.
  • Log safely from stdio and HTTP servers.
  • Tell application logging and observability apart from the deprecated MCP Logging feature.
  • Describe the trace-context keys the spec reserves, and which metrics are worth collecting.
  • Add structured, redacted logs to the L11 lab and verify them.

Two error channels (current)

The tools page defines two mechanisms:

  1. Protocol errors are standard JSON-RPC errors for problems with the request itself: an unknown tool, a malformed request, server errors. Example: {"code": -32602, "message": "Unknown tool: invalid_tool_name"}. Clients MAY show these to the model, but they rarely lead to recovery.
  2. Tool execution errors are normal results with isError: true: API failures, input validation errors such as a date in the wrong format or a value out of range, and business-logic errors. Clients SHOULD pass them to the model "to enable self-correction".

2026-07-28 also defines -32020 HeaderMismatch, -32021 MissingRequiredClientCapability and -32022 UnsupportedProtocolVersion, and moved resource-not-found from -32002 to -32602. The range -32020 to -32099 is reserved for the spec: never invent codes there.

Rule of thumb: if the model could fix it by changing arguments or trying something else, return isError: true with a short, actionable message. If the request itself is broken, it is a protocol error, which the SDK usually produces for you.

In the L11 lab (Python mcp 2.3.0), ToolError("No item with that SKU.") reached the client as is_error=True, and so did schema-validation failures. The model saw that sentence, not a stack trace or the upstream URL. Good messages say what was wrong and what is allowed ("quantity must be 1 to 10"), never include tokens, connection strings or internal hostnames, and are stable enough to grep for.

Where logs go

stdio servers. The server MUST NOT write anything to stdout that is not a valid MCP message. It MAY write UTF-8 logging to stderr; the client may capture, forward or ignore it, and should not assume it means an error. One stray print() can corrupt the protocol stream. In Python, log to sys.stderr or a file; in Node, use console.error, not console.log.

HTTP servers. stdout is not the protocol channel, but keep the same discipline: structured logs to stderr or a file, collected by your platform.

MCPServer in mcp 2.3.0 configures root logging with a stderr handler, so give your own logger its own handlers and propagate = False.

The deprecated MCP Logging feature (do not build on it)

MCP has a protocol-level Logging utility: the server sends notifications/message to the client. In 2026-07-28 it is deprecated (SEP-2577). It is still in the spec, with an earliest removal in the first revision on or after 2027-07-28. The logging/setLevel method is already removed: a client now asks for logs per request with io.modelcontextprotocol/logLevel in _meta, and servers MUST NOT emit log notifications for requests that did not include it.

The official migration path is: "Log to stderr for stdio transports; use OpenTelemetry for observability." In mcp 2.3.0, the context helpers that send these notifications (ctx.info(), ctx.debug() and so on) are marked deprecated with an MCPDeprecationWarning.

So keep two things separate:

Application logging and observabilityMCP Logging feature
AudienceYou, the operatorThe connected client or host
Channelstderr, files, log collector, OpenTelemetrynotifications/message on the request's response stream
StatusCurrent good practiceDeprecated

The Logging page's security rules are still worth copying for any log: messages MUST NOT contain credentials or secrets, personal identifying information, or internal details that could aid attacks.

Tracing (current spec convention, optional to adopt)

The spec reserves the _meta keys traceparent, tracestate and baggage for OpenTelemetry trace context (SEP-414, in the 2026-07-28 changelog). Values MUST follow the W3C Trace Context and W3C Baggage formats. If a client sends traceparent, a server using OpenTelemetry can continue the trace, so one user action can be followed from host to server to upstream API. The spec links OpenTelemetry's semantic conventions for MCP; that page has moved to OpenTelemetry's GenAI semantic-conventions repository, so check the current version before naming attributes. Whether your SDK propagates trace context automatically is not verified here: check its docs.

Metrics worth having

Start with a few, keyed by tool name: calls by outcome (ok, tool_error, protocol_error); latency (p50, p95) of tools and upstream calls; upstream status codes (spot a 409 or 5xx spike); and, for remote servers, 401 and 403 counts. Derive them from structured logs, as below, or emit OpenTelemetry metrics.

Worked example: a diagnosis

A user reports that reserve_stock "fails sometimes". The logs show reserve_stock upstream_call lines with status: 409, while get_item is all 200s, and the tool returned isError: true with "Cannot reserve: only 0 in stock." The server works; the item is out of stock and the model got an actionable message.

Practice: structured, redacted logs in the L11 lab

Work in a copy of lab-l11/. Create obs_logging.py:

python
import json, logging, os, sys, time

SENSITIVE = {"authorization", "api_key", "token", "password", "secret", "cookie"}

class JsonLines(logging.Formatter):
    def format(self, record):
        fields = {k: "[REDACTED]" if k.lower() in SENSITIVE else v
                  for k, v in getattr(record, "fields", {}).items()}
        return json.dumps({"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(record.created)),
                           "level": record.levelname, "event": record.getMessage(), **fields}, default=str)

def get_logger():
    log = logging.getLogger("lab.mcp")
    if log.handlers:
        return log
    log.setLevel(os.environ.get("LAB_LOG_LEVEL", "INFO"))
    log.propagate = False
    handlers = [logging.StreamHandler(sys.stderr)]          # never stdout
    if path := os.environ.get("LAB_LOG_FILE"):
        handlers.append(logging.FileHandler(path, encoding="utf-8"))
    for h in handlers:
        h.setFormatter(JsonLines()); log.addHandler(h)
    return log

def event(log, level, name, **fields):
    log.log(level, name, extra={"fields": fields})

Then edit mcp_server.py:

  1. Add import logging, time, uuid and from obs_logging import event, get_logger, then LOG = get_logger().
  2. Give _call_api a keyword argument tool: str, and pass tool="search_items", tool="get_item" or tool="reserve_stock" from each tool.
  3. In _call_api, record start = time.perf_counter() and call_id = uuid.uuid4().hex[:12]. On httpx.HTTPError, log event(LOG, logging.ERROR, "upstream_unavailable", call_id=..., tool=..., error_type=type(exc).__name__) before raising the ToolError. After a response, log upstream_call with call_id, tool, method, status and duration_ms: INFO below 400, WARNING otherwise. Do not log whole arguments, headers or bodies.
  4. At the start of main(), add event(LOG, logging.INFO, "server_start", upstream=UPSTREAM, port=MCP_PORT, api_key=os.environ.get("INVENTORY_API_KEY")). The lab has no real key; this simulates one.

The verifier discards the server's stderr, so use the file handler to observe the run:

bash
mkdir -p logs
LAB_LOG_FILE=logs/mcp.jsonl INVENTORY_API_KEY=sk-lab-fake-123 ./run.sh verify
grep -c "sk-lab-fake" logs/mcp.jsonl
.venv/bin/python -c "import json,collections; print(collections.Counter((e['tool'],e['status']) for e in map(json.loads,open('logs/mcp.jsonl')) if e['event']=='upstream_call'))"

To see the lines on stderr, run ./run.sh serve and call a tool from the pinned Inspector (@2.16.0) or a host.

Check your result

  • The verifier still ends with ALL CHECKS PASSED (22). Logging must not change behaviour.
  • logs/mcp.jsonl has 8 lines (reference run, 2026-11-26): one server_start and seven upstream_call.
  • The first line contains "api_key": "[REDACTED]", and grep -c "sk-lab-fake" prints 0.
  • Two lines have "level": "WARNING": reserve_stock with status 409 and get_item with status 404. Those are the verifier's negative cases, and each reached the model as isError: true.
  • The counter shows only 200, 404 and 409. Schema-rejected calls (../admin, quantity=500) never reached the API, so they have no upstream_call line; log at the tool layer too if you want them counted.

Check your understanding

  1. A date argument is in the wrong format. Protocol error or isError: true? isError: true. The spec lists input validation errors as tool execution errors, because the model can fix them and retry. Unknown tools and malformed requests are protocol errors.

  2. Your stdio server prints "connected to DB" with print() and the host disconnects. Why? print() writes to stdout, which in stdio is reserved for MCP messages. The host received a non-MCP line. Send logs to stderr or a file.

  3. Should a new server emit notifications/message so users see logs in their host? No. The MCP Logging feature is deprecated in 2026-07-28 and new implementations should not adopt it. Use stderr (stdio) or files and OpenTelemetry for observability, and return user-relevant problems as tool results.

Sources