Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Report JSON-RPC error codes and request ids on telemetry spans (#6427)

nate nowack12d665646546
diff --git a/docs/servers/telemetry.mdx b/docs/servers/telemetry.mdx
index 0b6641a26..e9088e184 100644
--- a/docs/servers/telemetry.mdx
+++ b/docs/servers/telemetry.mdx
@@ -433,7 +433,7 @@ def risky_operation() -> str:
raise ValueError("Something went wrong")
```
-The `tools/call risky_operation` server span gets status `ERROR` with the error message as its description, an exception event carrying the stack trace, and an `error.type` attribute. FastMCP wraps exceptions raised by a tool in a `ToolError`, so tool failures report `error.type` as `tool_error`; other failures report the exception class name.
+The `tools/call risky_operation` server span gets status `ERROR` with the error message as its description, an exception event carrying the stack trace, and an `error.type` attribute. FastMCP wraps exceptions raised by a tool in a `ToolError`, so tool failures report `error.type` as `tool_error`. A request rejected with a JSON-RPC error, such as a read of an unknown resource, reports the error code (for example `-32602`) as both `error.type` and `rpc.response.status_code`. Other failures report the exception class name.
## Attributes Reference
@@ -450,10 +450,12 @@ FastMCP implements the [OpenTelemetry MCP semantic conventions](https://opentele
| `mcp.method.name` | The MCP method being called (`tools/call`, `resources/read`, `prompts/get`, `tasks/get`, etc.) |
| `mcp.protocol.version` | The negotiated MCP protocol version for the request |
| `mcp.session.id` | Session identifier for the MCP connection |
+| `jsonrpc.request.id` | JSON-RPC request ID (on server spans for inbound requests) |
| `mcp.resource.uri` | The resource URI (for resource operations) |
| `gen_ai.tool.name` | Tool name (on `tools/call` spans) |
| `gen_ai.prompt.name` | Prompt name (on `prompts/get` spans) |
-| `error.type` | Error classification (`tool_error` for ToolError, otherwise exception class name) |
+| `error.type` | Error classification (the JSON-RPC error code for protocol errors, `tool_error` for ToolError, otherwise exception class name) |
+| `rpc.response.status_code` | JSON-RPC error code (on spans that failed with a protocol error) |
### Auth Attributes
diff --git a/fastmcp_slim/fastmcp/client/telemetry.py b/fastmcp_slim/fastmcp/client/telemetry.py
index 126e5b7e2..56c879a03 100644
--- a/fastmcp_slim/fastmcp/client/telemetry.py
+++ b/fastmcp_slim/fastmcp/client/telemetry.py
@@ -5,8 +5,11 @@ from contextlib import contextmanager
from opentelemetry.trace import Span, SpanKind, Status, StatusCode
-from fastmcp.exceptions import ToolError as _ToolError
-from fastmcp.telemetry import get_tracer, restore_dropped_attributes
+from fastmcp.telemetry import (
+ error_span_attributes,
+ get_tracer,
+ restore_dropped_attributes,
+)
@contextmanager
@@ -62,10 +65,7 @@ def client_span(
yield span
except Exception as e:
if span.is_recording():
- error_type = (
- "tool_error" if isinstance(e, _ToolError) else type(e).__qualname__
- )
- span.set_attribute("error.type", error_type)
+ span.set_attributes(error_span_attributes(e))
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR, str(e)))
raise
diff --git a/fastmcp_slim/fastmcp/server/telemetry.py b/fastmcp_slim/fastmcp/server/telemetry.py
index 9cc65de3d..2db962f09 100644
--- a/fastmcp_slim/fastmcp/server/telemetry.py
+++ b/fastmcp_slim/fastmcp/server/telemetry.py
@@ -16,8 +16,8 @@ from opentelemetry.trace import (
get_current_span,
)
-from fastmcp.exceptions import ToolError as _ToolError
from fastmcp.telemetry import (
+ error_span_attributes,
extract_trace_context,
get_tracer,
restore_dropped_attributes,
@@ -89,18 +89,23 @@ def get_session_span_attributes() -> dict[str, str]:
def get_protocol_span_attributes() -> dict[str, str]:
- """Get the negotiated MCP protocol version for the current request.
+ """Get the protocol attributes for the current request.
- Mirrors the `mcp.protocol.version` attribute the SDK's own
- `OpenTelemetryMiddleware` sets β€” FastMCP drops that middleware to avoid a
- duplicate SERVER span, so this restores the attribute on FastMCP's span.
+ Mirrors the `mcp.protocol.version` and `jsonrpc.request.id` attributes the
+ SDK's own `OpenTelemetryMiddleware` sets β€” FastMCP drops that middleware to
+ avoid a duplicate SERVER span, so this restores them on FastMCP's span.
"""
from fastmcp.server.dependencies import fastmcp_request_ctx
req_ctx = fastmcp_request_ctx.get()
- if req_ctx is not None and req_ctx.protocol_version:
- return {"mcp.protocol.version": req_ctx.protocol_version}
- return {}
+ attrs: dict[str, str] = {}
+ if req_ctx is None:
+ return attrs
+ if req_ctx.protocol_version:
+ attrs["mcp.protocol.version"] = req_ctx.protocol_version
+ if req_ctx.request_id is not None:
+ attrs["jsonrpc.request.id"] = req_ctx.request_id
+ return attrs
def _get_parent_trace_context() -> Context | None:
@@ -171,8 +176,7 @@ def _build_server_span_attrs(
def record_span_exception(span: Span, e: Exception) -> None:
"""Record an exception and error status on a span."""
if span.is_recording():
- error_type = "tool_error" if isinstance(e, _ToolError) else type(e).__qualname__
- span.set_attribute("error.type", error_type)
+ span.set_attributes(error_span_attributes(e))
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR, str(e)))
diff --git a/fastmcp_slim/fastmcp/telemetry.py b/fastmcp_slim/fastmcp/telemetry.py
index 61d751fed..ea936078c 100644
--- a/fastmcp_slim/fastmcp/telemetry.py
+++ b/fastmcp_slim/fastmcp/telemetry.py
@@ -180,6 +180,23 @@ def inject_trace_context(
return meta
+def error_span_attributes(exception: BaseException) -> dict[str, str]:
+ """Map an exception to the `error.type` attributes for a failed MCP span.
+
+ Per the MCP semantic conventions, a JSON-RPC error reports its code as
+ both `error.type` and `rpc.response.status_code`; a tool error reports
+ `tool_error`; anything else reports its class name.
+ """
+ from fastmcp.exceptions import MCPError, ToolError
+
+ if isinstance(exception, MCPError):
+ code = str(exception.error.code)
+ return {"error.type": code, "rpc.response.status_code": code}
+ if isinstance(exception, ToolError):
+ return {"error.type": "tool_error"}
+ return {"error.type": type(exception).__qualname__}
+
+
def record_span_error(span: Span, exception: BaseException) -> None:
"""Record an exception on a span and set error status."""
span.record_exception(exception)
@@ -305,6 +322,7 @@ __all__ = [
"INSTRUMENTATION_NAME",
"TRACE_PARENT_KEY",
"TRACE_STATE_KEY",
+ "error_span_attributes",
"extract_trace_context",
"get_tracer",
"inject_trace_context",
diff --git a/tests/client/telemetry/test_client_tracing.py b/tests/client/telemetry/test_client_tracing.py
index 0ca2e8759..2e266d915 100644
--- a/tests/client/telemetry/test_client_tracing.py
+++ b/tests/client/telemetry/test_client_tracing.py
@@ -9,7 +9,7 @@ from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanE
from opentelemetry.trace import SpanKind, StatusCode
from fastmcp import Client, FastMCP
-from fastmcp.exceptions import ToolError
+from fastmcp.exceptions import MCPError, ToolError
class TestClientToolTracing:
@@ -559,6 +559,28 @@ class TestClientErrorTracing:
# Server span should have ERROR status
assert server_span.status.status_code == StatusCode.ERROR
+ async def test_jsonrpc_error_reports_error_code(
+ self, trace_exporter: InMemorySpanExporter
+ ):
+ """A JSON-RPC error sets `error.type` and `rpc.response.status_code` to
+ the error code, not the exception class name."""
+ server = FastMCP("test-server")
+
+ async with Client(server) as client:
+ with pytest.raises(MCPError) as caught:
+ await client.read_resource("missing://x")
+
+ code = str(caught.value.error.code)
+ client_span = next(
+ s
+ for s in trace_exporter.get_finished_spans()
+ if s.kind == SpanKind.CLIENT and s.name == "resources/read"
+ )
+ assert client_span.status.status_code == StatusCode.ERROR
+ assert client_span.attributes is not None
+ assert client_span.attributes["error.type"] == code
+ assert client_span.attributes["rpc.response.status_code"] == code
+
class TestSessionIdOnSpans:
"""Tests for session ID capture on client and server spans.
diff --git a/tests/server/telemetry/test_server_tracing.py b/tests/server/telemetry/test_server_tracing.py
index 252d92b70..0fceafa41 100644
--- a/tests/server/telemetry/test_server_tracing.py
+++ b/tests/server/telemetry/test_server_tracing.py
@@ -11,7 +11,7 @@ from opentelemetry.trace import Span, SpanKind, StatusCode
import fastmcp
from fastmcp import Client, FastMCP
-from fastmcp.exceptions import NotFoundError, ToolError
+from fastmcp.exceptions import MCPError, NotFoundError, ToolError
from fastmcp.server.auth import AccessToken
from fastmcp.server.middleware.middleware import CallNext, Middleware, MiddlewareContext
@@ -769,3 +769,51 @@ class TestProtocolVersionAttribute:
version = seam_span.attributes.get("mcp.protocol.version")
assert isinstance(version, str)
assert version
+
+ async def test_server_span_has_jsonrpc_request_id(
+ self, trace_exporter: InMemorySpanExporter
+ ):
+ mcp = FastMCP("test-server")
+
+ @mcp.tool()
+ def greet(name: str) -> str:
+ return f"Hello, {name}!"
+
+ async with Client(mcp) as client:
+ await client.call_tool("greet", {"name": "World"})
+
+ spans = trace_exporter.get_finished_spans()
+ server_span = next(
+ s
+ for s in spans
+ if s.kind == SpanKind.SERVER and s.name == "tools/call greet"
+ )
+ sdk_span = next(s for s in spans if s.name == "MCP send tools/call greet")
+ assert server_span.attributes is not None
+ assert sdk_span.attributes is not None
+ assert (
+ server_span.attributes["jsonrpc.request.id"]
+ == sdk_span.attributes["jsonrpc.request.id"]
+ )
+
+ async def test_jsonrpc_error_reports_error_code(
+ self, trace_exporter: InMemorySpanExporter
+ ):
+ """A JSON-RPC error sets `error.type` and `rpc.response.status_code` to
+ the error code, not the exception class name."""
+ mcp = FastMCP("test-server")
+
+ async with Client(mcp) as client:
+ with pytest.raises(MCPError) as caught:
+ await client.read_resource("missing://x")
+
+ code = str(caught.value.error.code)
+ server_span = next(
+ s
+ for s in trace_exporter.get_finished_spans()
+ if s.kind == SpanKind.SERVER and s.name == "resources/read"
+ )
+ assert server_span.status.status_code == StatusCode.ERROR
+ assert server_span.attributes is not None
+ assert server_span.attributes["error.type"] == code
+ assert server_span.attributes["rpc.response.status_code"] == code