> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo The Crash

> Explains how the MCP Python SDK masks sensitive runtime error details from models/clients while logging full diagnostics, and contrasts ToolError, MCPError, and unexpected exceptions

Welcome — in this demo we continue exploring error handling in the MCP Python SDK and how the SDK treats errors raised by tools. This lesson focuses on unexpected runtime failures that may contain sensitive details (IP addresses, database users, stack traces) and how the SDK prevents those details from leaking to the model or client while still providing developers with full diagnostics in server logs.

## Quick recap: anticipated vs protocol errors

We previously implemented a flaky tool that can fail in two distinct ways:

* Anticipated tool failures (`ToolError`): meaningful to the model — returned as an error result (`isError: true`) so the model can react (retry, fallback, etc.).
* Protocol-level failures (`MCPError` / JSON-RPC errors): indicate the request itself failed and the model receives no normal result object.

Example (anticipated vs protocol modes)

```python theme={null}
import sys
from typing import Literal

from mcp import MCPError
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

server = MCPServer(name="shipment-tracker", version="5.2.0")


@server.tool(description="Fail on purpose: as a tool failure, or as a protocol failure.")
async def flaky_lookup(mode: Literal["anticipated", "protocol"]) -> str:
    if mode == "anticipated":
        # The tool failed, but the request succeeded: a result with isError: true.
        # This message reaches the model so it can decide to retry.
        raise ToolError("The carrier's tracking API returned 503. Try again in a minute.")

    # The request itself failed: a JSON-RPC error, no result produced for the model.
    raise MCPError(-32002, "shipment-tracker is in maintenance and cannot serve lookups")


if __name__ == "__main__":
    print("shipment-tracker ready on stdio", file=sys.stderr)
    server.run("stdio")
```

Key points:

* ToolError: propagated back to the model as an error result (`isError: true`) and is useful to the model for decision making (e.g., retry).
* MCPError: a protocol-level error (JSON-RPC-level) meaning the request failed and the model does not get a normal result.

## This lesson: unexpected runtime errors and sensitive data

In real deployments you may encounter unanticipated runtime failures — for example, a database connection error that contains an IP address, username, or other sensitive information. The MCP Python SDK must avoid returning that sensitive text to the model or client, while still letting operators access the full details from server logs.

Example tool that raises an unexpected runtime error (contains sensitive details):

```python theme={null}
import sys

from mcp.server import MCPServer

server = MCPServer(name="shipment-tracker", version="5.3.0")


@server.tool(description="Fail on purpose with an unexpected exception.")
async def flaky_lookup() -> str:
    # A bug nobody planned for. The client only gets "Error executing tool 'flaky_lookup'".
    # The full exception (sensitive details) goes to the server logs.
    raise RuntimeError(
        "psycopg2.OperationalError: could not connect to server at "
        "10.0.4.19:5432, password authentication failed for user 'tracker'"
    )


if __name__ == "__main__":
    print("shipment-tracker ready on stdio", file=sys.stderr)
    server.run("stdio")
```

Behavior to expect:

* The tool raises an unexpected exception (RuntimeError) that includes sensitive details.
* The MCP SDK does not forward that raw exception text to the model/client.

## What the client/model sees

When an unexpected runtime exception occurs, the MCP Python SDK intentionally replaces the detailed, sensitive exception text with a short, non-sensitive message safe to send to the model. The model receives a result object with `isError: true` and a single non-sensitive text content item such as "Error executing tool flaky\_lookup".

JSON-RPC response returned to the client/model (example):

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 5,
  "result": {
    "_meta": {
      "io.modelcontextprotocol/serverInfo": {
        "name": "shipment-tracker",
        "version": "5.3.0"
      }
    },
    "content": [
      {
        "text": "Error executing tool flaky_lookup",
        "type": "text"
      }
    ],
    "isError": true,
    "resultType": "complete"
  }
}
```

Note how the model only sees the minimal, non-sensitive message "Error executing tool flaky\_lookup". Sensitive details (IP addresses, DB users, stack traces) are deliberately omitted from the payload sent to the model.

## Where the full error goes

The MCP Python SDK writes the full exception and traceback to the server logs / console so developers can debug the issue. Consult your server console or log files to see the complete traceback and exception details.

Example server console / traceback excerpt:

```text theme={null}
Server Console

16:59:13  Tool 'flaky_lookup' raised an unexpected exception
Traceback (most recent call last):
  File "/Users/awaiskamran/Documents/model-context-protocol-associates-670f7f9c/code/.venv/lib/python3.10/site-packages/mcp/server/mcpserver/tools/base.py", line 176, in run
    result = await self.fn_metadata.call_fn(self.fn, self.is_async, validated, pass_directly)
  File "/Users/awaiskamran/Documents/model-context-protocol-associates-670f7f9c/code/.venv/lib/python3.10/site-packages/mcp/server/mcpserver/utilities/func_metadata.py", line 163, in call_fn
    return await fn(**kwargs)
  File "/Users/awaiskamran/Documents/model-context-protocol-associates-670f7f9c/code/stage-5c-the-crash/server.py", line 12, in flaky_lookup
    raise RuntimeError(
RuntimeError: psycopg2.OperationalError: could not connect to server at 10.0.4.19:5432, password authentication failed for user 'tracker'
```

The MCP SDK intentionally masks sensitive runtime details from the model/client and logs them to the server console instead. This design prevents leaking IPs, credentials, or stack traces to the model while ensuring developers can still access full diagnostic information in the server logs.

## Error types at a glance

| Error type | Visible to model/client | Typical semantics | Where full details appear |
| - | - | - | - |
| `ToolError` | Yes — `isError: true` and the message is delivered | Intended tool-level errors; useful for model decisions (retry/fallback) | Error message included in result |
| `MCPError` | No — JSON-RPC/protocol error, no normal result | Protocol-level failures (request invalid, server maintenance) | Protocol logs / server console |
| Unexpected runtime errors (exceptions) | Minimal, non-sensitive text only (e.g., "Error executing tool flaky\_lookup") | Unplanned/bug/operational failures; may contain sensitive data internally | Full traceback in server logs / console |

## Summary

* Use `ToolError` for anticipated, meaningful tool failures you want the model to act on.
* Use `MCPError` for protocol-level failures where no normal result should be returned.
* Unexpected runtime exceptions are masked by the MCP SDK: the model receives a minimal, non-sensitive error string while the server logs hold the full exception and traceback for debugging.

## Links and references

* [Model Context Protocol (MCP) — Server SDK patterns](https://example.com)
* [JSON-RPC 2.0 specification](https://www.jsonrpc.org/specification)
* [Python logging best practices](https://docs.python.org/3/howto/logging.html)

That covers how the MCP Python SDK handles different error classes and why it masks unexpected runtime details before sending anything to the model.

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/model-context-protocol-associate-mcpa-certification/module/31dedbc5-6173-4700-b50e-7a581095c897/lesson/ad2e9cca-4fa4-4a5c-97dd-920e50b91dc1)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.