π The fast, Pythonic way to build MCP servers and clients.
fix(telemetry): record exceptions once per span (#5861)
Dylan Momplaisir4d5b6ef62140
diff --git a/fastmcp_slim/fastmcp/client/telemetry.py b/fastmcp_slim/fastmcp/client/telemetry.pyindex 785346ba9..126e5b7e2 100644--- a/fastmcp_slim/fastmcp/client/telemetry.py+++ b/fastmcp_slim/fastmcp/client/telemetry.py@@ -40,7 +40,11 @@ def client_span(tracer = get_tracer()with tracer.start_as_current_span(- name, kind=SpanKind.CLIENT, attributes=attrs+ name,+ kind=SpanKind.CLIENT,+ attributes=attrs,+ record_exception=False,+ set_status_on_exception=False,) as span:# Restore: `attributes=attrs` above lets on_start hooks and the# sampler see these values at creation time. But OTel'sdiff --git a/fastmcp_slim/fastmcp/server/telemetry.py b/fastmcp_slim/fastmcp/server/telemetry.pyindex 1226cda64..5df804807 100644--- a/fastmcp_slim/fastmcp/server/telemetry.py+++ b/fastmcp_slim/fastmcp/server/telemetry.py@@ -3,6 +3,7 @@from collections.abc import Generatorfrom contextlib import contextmanagerfrom contextvars import ContextVar+from dataclasses import dataclassfrom opentelemetry import context as otel_contextfrom opentelemetry.context import Context@@ -31,11 +32,18 @@ from fastmcp.telemetry import (# below (the API `Span` type does not expose readable attributes).SEAM_SPAN_MARKER = "fastmcp.span.seam"+# Tracks the SERVER span opened at the current request's seam. When the# high-level path reaches `server_span` and this span is still the active span,# `server_span` enriches it with component attributes instead of opening a# second span β restoring attribute parity on the single per-request span.-_active_seam_span: ContextVar[Span | None] = ContextVar(+@dataclass+class _SeamSpan:+ span: Span+ error: Exception | None = None+++_active_seam_span: ContextVar[_SeamSpan | None] = ContextVar("fastmcp_active_seam_span", default=None)@@ -205,6 +213,8 @@ def seam_span(method: str, server_name: str) -> Generator[Span, None, None]:context=_get_parent_trace_context(),kind=SpanKind.SERVER,attributes=attrs,+ record_exception=False,+ set_status_on_exception=False,) as span:# Restore: `attributes=attrs` above is what makes on_start hooks and# the sampler see these values at creation time (the whole point of@@ -218,16 +228,19 @@ def seam_span(method: str, server_name: str) -> Generator[Span, None, None]:# an SDK attribute limit that evicted some.if span.is_recording():restore_dropped_attributes(span, attrs)- token = _active_seam_span.set(span)+ seam = _SeamSpan(span)+ token = _active_seam_span.set(seam)# A seam is a new inbound request, even one an in-process proxy sends# from inside another server's tool call.open_token = _server_span_open.set(False)try:yield spanexcept Exception as e:- record_span_exception(span, e)+ seam.error = eraisefinally:+ if seam.error is not None:+ record_span_exception(span, seam.error)_server_span_open.reset(open_token)_active_seam_span.reset(token)@@ -281,7 +294,11 @@ def server_span(if _server_span_open.get():with get_tracer().start_as_current_span(- name, kind=SpanKind.INTERNAL, attributes=attrs+ name,+ kind=SpanKind.INTERNAL,+ attributes=attrs,+ record_exception=False,+ set_status_on_exception=False,) as span:if span.is_recording():restore_dropped_attributes(span, attrs)@@ -296,18 +313,20 @@ def server_span(active = get_current_span()if (seam is not None- and seam is active- and seam.is_recording()- and seam.get_span_context().is_valid+ and seam.span is active+ and seam.span.is_recording()+ and seam.span.get_span_context().is_valid):# Enrich the already-active seam span rather than opening a second one.- seam.update_name(name)- seam.set_attributes(attrs)+ seam.span.update_name(name)+ seam.span.set_attributes(attrs)token = _server_span_open.set(True)try:- yield seam+ yield seam.spanexcept Exception as e:- record_span_exception(seam, e)+ # The seam owns recording, including failures later converted to+ # isError results and exceptions rewrapped by protocol handlers.+ seam.error = eraisefinally:_server_span_open.reset(token)@@ -319,6 +338,8 @@ def server_span(context=_get_parent_trace_context(),kind=SpanKind.SERVER,attributes=attrs,+ record_exception=False,+ set_status_on_exception=False,) as span:# Restore for the same reason as `seam_span`: OTel builds the span# from `sampling_result.attributes`, which a custom Sampler may not@@ -356,7 +377,12 @@ def delegate_span(attrs["mcp.method.name"] = methodtracer = get_tracer()- with tracer.start_as_current_span(f"delegate {name}", attributes=attrs) as span:+ with tracer.start_as_current_span(+ f"delegate {name}",+ attributes=attrs,+ record_exception=False,+ set_status_on_exception=False,+ ) as span:# Restore for the same reason as `seam_span`: OTel builds the span# from `sampling_result.attributes`, which a custom Sampler may not# forward even though it was handed `attributes=attrs` above. Onlydiff --git a/tests/telemetry/test_exception_recording.py b/tests/telemetry/test_exception_recording.pynew file mode 100644index 000000000..382ae3405--- /dev/null+++ b/tests/telemetry/test_exception_recording.py@@ -0,0 +1,142 @@+"""Failures produce one exception event per span, including reused server spans."""++from collections.abc import Callable+from contextlib import AbstractContextManager+from typing import Literal++import pytest+from mcp import MCPError+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter+from opentelemetry.trace import Span, SpanKind, StatusCode++from fastmcp import Client, FastMCP+from fastmcp.client.telemetry import client_span+from fastmcp.exceptions import PromptError, ResourceError, ToolError+from fastmcp.server.telemetry import delegate_span, seam_span, server_span+++ "span_factory",+ [+ pytest.param(lambda: client_span("test", "tools/call", "fail"), id="client"),+ pytest.param(+ lambda: server_span("test", "tools/call", "server", "tool", "fail"),+ id="server",+ ),+ pytest.param(lambda: seam_span("tools/call", "server"), id="seam"),+ pytest.param(lambda: delegate_span("fail", "provider", "fail"), id="delegate"),+ ],+)+def test_span_records_exception_once(+ trace_exporter: InMemorySpanExporter,+ span_factory: Callable[[], AbstractContextManager[Span]],+) -> None:+ error = ValueError("one failure")+ with pytest.raises(ValueError) as caught, span_factory():+ raise error++ assert caught.value is error+ (span,) = trace_exporter.get_finished_spans()+ (event,) = span.events+ assert span.status.status_code == StatusCode.ERROR+ assert span.status.description == "one failure"+ assert span.attributes is not None+ assert span.attributes["error.type"] == "ValueError"+ assert event.name == "exception"+ assert event.attributes is not None+ assert event.attributes["exception.type"] == "ValueError"+ assert event.attributes["exception.message"] == "one failure"+ stacktrace = event.attributes["exception.stacktrace"]+ assert isinstance(stacktrace, str)+ assert "raise error" in stacktrace++[email protected]("operation", ["tool", "resource", "template", "prompt"])[email protected]("dispatch", ["direct", "client", "mounted"])+async def test_component_failure_records_exception_once_per_span(+ trace_exporter: InMemorySpanExporter,+ operation: Literal["tool", "resource", "template", "prompt"],+ dispatch: Literal["direct", "client", "mounted"],+) -> None:+ backend = FastMCP("backend")++ @backend.tool+ async def fail_tool() -> str:+ raise ValueError("one failure")++ @backend.resource("data://fail")+ async def fail_resource() -> str:+ raise ValueError("one failure")++ @backend.resource("data://items/{item_id}")+ async def fail_template(item_id: str) -> str:+ raise ValueError("one failure")++ @backend.prompt+ async def fail_prompt() -> str:+ raise ValueError("one failure")++ server = backend+ prefix = ""+ if dispatch == "mounted":+ server = FastMCP("parent")+ server.mount(backend, namespace="child")+ prefix = "child_"++ resource_uri = "data://child/fail" if prefix else "data://fail"+ template_uri = "data://child/items/1" if prefix else "data://items/1"+ if dispatch == "direct":+ if operation == "tool":+ with pytest.raises(ToolError, match="one failure"):+ await server.call_tool("fail_tool", {})+ elif operation in ("resource", "template"):+ uri = resource_uri if operation == "resource" else template_uri+ with pytest.raises(ResourceError, match="one failure"):+ await server.read_resource(uri)+ else:+ with pytest.raises(PromptError, match="one failure"):+ await server.render_prompt("fail_prompt", {})+ else:+ async with Client(server) as client:+ if operation == "tool":+ with pytest.raises(ToolError, match="one failure"):+ await client.call_tool(f"{prefix}fail_tool")+ elif operation in ("resource", "template"):+ uri = resource_uri if operation == "resource" else template_uri+ with pytest.raises(MCPError, match="one failure"):+ await client.read_resource(uri)+ else:+ with pytest.raises(MCPError, match="one failure"):+ await client.get_prompt(f"{prefix}fail_prompt")++ method = {+ "tool": "tools/call",+ "resource": "resources/read",+ "template": "resources/read",+ "prompt": "prompts/get",+ }[operation]+ spans = [+ span+ for span in trace_exporter.get_finished_spans()+ if span.instrumentation_scope is not None+ and span.instrumentation_scope.name == "fastmcp"+ and span.attributes is not None+ and span.attributes.get("mcp.method.name") == method+ ]+ assert len(spans) == {"direct": 1, "client": 2, "mounted": 4}[dispatch]+ for span in spans:+ assert span.status.status_code == StatusCode.ERROR+ assert span.status.description is not None+ assert "one failure" in span.status.description+ assert span.attributes is not None+ assert "error.type" in span.attributes+ if operation == "tool" and span.kind == SpanKind.CLIENT:+ # isError is a result, not an exception raised inside the CLIENT span.+ assert not span.events+ else:+ (event,) = span.events+ assert event.name == "exception"+ assert event.attributes is not None+ message = event.attributes["exception.message"]+ assert isinstance(message, str)+ assert "one failure" in message