π The fast, Pythonic way to build MCP servers and clients.
Preserve telemetry attributes when a sampler does not forward them (#4539)
Jeremiah Lowin252a29e5e605
diff --git a/fastmcp_slim/fastmcp/client/telemetry.py b/fastmcp_slim/fastmcp/client/telemetry.pyindex d6a866098..785346ba9 100644--- a/fastmcp_slim/fastmcp/client/telemetry.py+++ b/fastmcp_slim/fastmcp/client/telemetry.py@@ -6,7 +6,7 @@ from contextlib import contextmanagerfrom opentelemetry.trace import Span, SpanKind, Status, StatusCodefrom fastmcp.exceptions import ToolError as _ToolError-from fastmcp.telemetry import get_tracer+from fastmcp.telemetry import get_tracer, restore_dropped_attributes@contextmanager@@ -42,6 +42,18 @@ def client_span(with tracer.start_as_current_span(name, kind=SpanKind.CLIENT, attributes=attrs) as span:+ # Restore: `attributes=attrs` above lets on_start hooks and the+ # sampler see these values at creation time. But OTel's+ # Tracer.start_span builds the span from+ # `sampling_result.attributes`, not the `attributes` kwarg directly β+ # a custom Sampler whose SamplingResult.attributes defaults to None+ # silently drops everything we passed. This only fires when the span+ # ends up with no attributes at all, so any sampler that supplied+ # attributes of its own β forwarding ours, redacting or replacing+ # some, or substituting entirely its own β is left untouched, as is+ # an SDK attribute limit that evicted some.+ if span.is_recording():+ restore_dropped_attributes(span, attrs)try:yield spanexcept Exception as e:diff --git a/fastmcp_slim/fastmcp/server/sampling/run.py b/fastmcp_slim/fastmcp/server/sampling/run.pyindex 382bf8a47..bcb73cc66 100644--- a/fastmcp_slim/fastmcp/server/sampling/run.py+++ b/fastmcp_slim/fastmcp/server/sampling/run.py@@ -33,7 +33,7 @@ from typing_extensions import TypeVarfrom fastmcp import settingsfrom fastmcp.exceptions import ToolErrorfrom fastmcp.server.sampling.sampling_tool import SamplingTool-from fastmcp.telemetry import get_tracer+from fastmcp.telemetry import get_tracer, restore_dropped_attributesfrom fastmcp.tools.function_tool import FunctionToolfrom fastmcp.tools.tool_transform import TransformedToolfrom fastmcp.utilities.async_utils import gather@@ -310,14 +310,28 @@ async def execute_tools()tracer = get_tracer()+ span_attrs = {+ "gen_ai.tool.name": tool_use.name,+ "fastmcp.tool.use_id": tool_use.id,+ }with tracer.start_as_current_span(f"sampling tool {tool_use.name}",kind=SpanKind.INTERNAL,- attributes={- "gen_ai.tool.name": tool_use.name,- "fastmcp.tool.use_id": tool_use.id,- },+ attributes=span_attrs,) as span:+ # Restore: `attributes=span_attrs` above lets on_start hooks and+ # the sampler see these values at creation time. But OTel's+ # Tracer.start_span builds the span from+ # `sampling_result.attributes`, not the `attributes` kwarg+ # directly β a custom Sampler whose SamplingResult.attributes+ # defaults to None silently drops everything we passed. This+ # only fires when the span ends up with no attributes at all, so+ # any sampler that supplied attributes of its own β forwarding+ # ours, redacting or replacing some, or substituting entirely its+ # own β is left untouched, as is an SDK attribute limit that+ # evicted some.+ if span.is_recording():+ restore_dropped_attributes(span, span_attrs)try:result_value = await tool.run(tool_use.input)return ToolResultContent(@@ -554,16 +568,29 @@ async def sample_step_impl(# Make the LLM calltracer = get_tracer()+ span_attrs = {+ "mcp.method.name": "sampling/createMessage",+ "fastmcp.server.name": context.fastmcp.name,+ }with tracer.start_as_current_span("sampling create_message",kind=SpanKind.CLIENT,- attributes={- "mcp.method.name": "sampling/createMessage",- "fastmcp.server.name": context.fastmcp.name,- },+ attributes=span_attrs,record_exception=False,set_status_on_exception=False,) as span:+ # Restore: `attributes=span_attrs` above lets on_start hooks and the+ # sampler see these values at creation time. But OTel's+ # Tracer.start_span builds the span from+ # `sampling_result.attributes`, not the `attributes` kwarg directly β+ # a custom Sampler whose SamplingResult.attributes defaults to None+ # silently drops everything we passed. This only fires when the span+ # ends up with no attributes at all, so any sampler that supplied+ # attributes of its own β forwarding ours, redacting or replacing+ # some, or substituting entirely its own β is left untouched, as is+ # an SDK attribute limit that evicted some.+ if span.is_recording():+ restore_dropped_attributes(span, span_attrs)try:if use_fallback:response = await call_sampling_handler(diff --git a/fastmcp_slim/fastmcp/server/telemetry.py b/fastmcp_slim/fastmcp/server/telemetry.pyindex 2b994b24d..53350e8e8 100644--- a/fastmcp_slim/fastmcp/server/telemetry.py+++ b/fastmcp_slim/fastmcp/server/telemetry.py@@ -8,7 +8,11 @@ from opentelemetry.context import Contextfrom opentelemetry.trace import Span, SpanKind, Status, StatusCode, get_current_spanfrom fastmcp.exceptions import ToolError as _ToolError-from fastmcp.telemetry import extract_trace_context, get_tracer+from fastmcp.telemetry import (+ extract_trace_context,+ get_tracer,+ restore_dropped_attributes,+)# Marker attribute set on the SERVER span opened at the FastMCP middleware seam# (see `fastmcp.server.low_level.FastMCPServerMiddleware._seam_span`). The seam@@ -150,6 +154,18 @@ def seam_span(method: str, server_name: str) -> Generator[Span, None, None]:kind=SpanKind.SERVER,attributes=attrs,) 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+ # this helper). But OTel's Tracer.start_span builds the span from+ # `sampling_result.attributes`, not the `attributes` kwarg directly β+ # a custom Sampler whose SamplingResult.attributes defaults to None+ # silently drops everything we passed. This only fires when the span+ # ends up with no attributes at all, so any sampler that supplied+ # attributes of its own β forwarding ours, redacting or replacing+ # some, or substituting entirely its own β is left untouched, as is+ # an SDK attribute limit that evicted some.+ if span.is_recording():+ restore_dropped_attributes(span, attrs)token = _active_seam_span.set(span)try:yield span@@ -218,6 +234,12 @@ def server_span(kind=SpanKind.SERVER,attributes=attrs,) 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. Only+ # fires when the span ends up with no attributes at all.+ if span.is_recording():+ restore_dropped_attributes(span, attrs)try:yield spanexcept Exception as e:@@ -246,6 +268,12 @@ def delegate_span(tracer = get_tracer()with tracer.start_as_current_span(f"delegate {name}", attributes=attrs) 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. Only+ # fires when the span ends up with no attributes at all.+ if span.is_recording():+ restore_dropped_attributes(span, attrs)try:yield spanexcept Exception as e:diff --git a/fastmcp_slim/fastmcp/telemetry.py b/fastmcp_slim/fastmcp/telemetry.pyindex c1bb66dfd..dc0edf32a 100644--- a/fastmcp_slim/fastmcp/telemetry.py+++ b/fastmcp_slim/fastmcp/telemetry.py@@ -21,9 +21,9 @@ Example usage with SDK:```"""-from collections.abc import Iterator+from collections.abc import Iterator, Mappingfrom contextlib import contextmanager-from typing import Any+from typing import Any, Protocol, runtime_checkablefrom opentelemetry import context as otel_contextfrom opentelemetry import propagate, trace@@ -135,6 +135,80 @@ def record_span_error(span: Span, exception: BaseException) -> None:span.set_status(Status(StatusCode.ERROR))+@runtime_checkable+class _AttributeReadableSpan(Protocol):+ """Structural type for spans that expose their current attribute state.++ The `opentelemetry-api` `Span` ABC has no way to read attributes back β+ only SDK span implementations (e.g. `opentelemetry.sdk.trace.ReadableSpan`)+ expose `.attributes` and `.dropped_attributes`. FastMCP only depends on+ `opentelemetry-api`, so this module can't import the SDK class to+ `isinstance`-check against it. A runtime-checkable `Protocol` gets the+ same structural narrowing without that import: spans that don't expose+ this state (e.g. `NonRecordingSpan`) simply fail the check.+ """++ @property+ def attributes(self) -> Mapping[str, otel_types.AttributeValue] | None: ...++ @property+ def dropped_attributes(self) -> int: ...+++def restore_dropped_attributes(+ span: Span, attrs: Mapping[str, otel_types.AttributeValue]+) -> None:+ """Restore FastMCP attributes a non-forwarding sampler dropped entirely.++ `Tracer.start_span` builds the span from `SamplingResult.attributes`, not+ the `attributes=` kwarg it was given for creation β a custom `Sampler`+ whose `SamplingResult.attributes` defaults to `None` silently discards+ every attribute FastMCP passed at creation time. Call this immediately+ after span creation to recover from that case.++ The restore only fires when the span has *no* attributes at all AND the+ SDK hasn't evicted anything (`dropped_attributes == 0`):++ - A bare, non-forwarding sampler (the regression this exists to fix)+ leaves the span with an empty attribute mapping, so everything is+ restored.+ - A sampler that supplied any attributes of its own β whether by+ forwarding ours untouched, redacting or replacing some of our values,+ or substituting its own attributes entirely (e.g. to strip component+ names or resource URIs for privacy or cardinality control) β leaves+ the span non-empty, so it is left alone entirely. This is what makes+ the gate precise: a sampler that deliberately supplies only its own+ attributes must not have them clobbered by a restore that assumes+ "no FastMCP keys" means "sampler forwarding failed."+ - A sampler that forwards most of our attributes but deliberately drops+ one is still non-empty, so it's covered by the same "leave alone"+ branch β a dropped key here is indistinguishable from the SDK's+ bounded attribute map evicting it, and reinserting it would just push+ the map's bound and evict a *different* retained key, churning which+ attributes survive without changing how many are lost. No attempt is+ made to restore individual missing keys; the gate is all-or-nothing.+ - A low `OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT` that evicts every attribute a+ forwarding sampler passed through is indistinguishable, from the+ span's attribute state alone, from a bare non-forwarding sampler β+ both leave an empty mapping. `dropped_attributes == 0` is what tells+ them apart: eviction always increments it, so that case is correctly+ excluded from the restore and the SDK's bounded map is left as+ computed.++ Callers are expected to guard this with `if span.is_recording():`; it+ does no work worth skipping for non-recording spans, but the check is+ kept at call sites so it reads alongside the sibling `is_recording()`+ guards already in those functions.+ """+ existing: Mapping[str, otel_types.AttributeValue] = {}+ dropped = 0+ if isinstance(span, _AttributeReadableSpan):+ existing = span.attributes or {}+ dropped = span.dropped_attributes+ if not existing and dropped == 0:+ span.set_attributes(attrs)++def extract_trace_context(meta: dict[str, Any] | None) -> Context:"""Extract trace context from an MCP request meta dict.@@ -175,4 +249,5 @@ __all__ = ["get_tracer","inject_trace_context","record_span_error",+ "restore_dropped_attributes",]diff --git a/tests/server/telemetry/test_sampling_tracing.py b/tests/server/telemetry/test_sampling_tracing.pyindex 2a550ffb3..53e166cf3 100644--- a/tests/server/telemetry/test_sampling_tracing.py+++ b/tests/server/telemetry/test_sampling_tracing.py@@ -11,10 +11,18 @@ from __future__ import annotationsimport pytestfrom mcp_types import TextContentfrom opentelemetry.context import Context as OTelContext-from opentelemetry.sdk.trace import Span, SpanProcessor, TracerProvider+from opentelemetry.sdk.trace import (+ ReadableSpan,+ Span,+ SpanLimits,+ SpanProcessor,+ TracerProvider,+)from opentelemetry.sdk.trace.export import SimpleSpanProcessorfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter+from opentelemetry.sdk.trace.sampling import Decision, Sampler, SamplingResultfrom opentelemetry.trace import StatusCode+from opentelemetry.util import types as otel_typesfrom fastmcp import Client, Context, FastMCPfrom fastmcp.client.sampling import RequestContext, SamplingMessage, SamplingParams@@ -28,6 +36,109 @@ class OnStartRecorder(SpanProcessor):self.attributes[span.name] = dict(span.attributes or {})+class NonForwardingSampler(Sampler):+ """Samples every span but never forwards the attributes it was handed.++ See `tests/telemetry/test_span_attributes.py` for the full explanation:+ OTel's `Tracer.start_span` builds the finished span from+ `sampling_result.attributes`, not from the `attributes` kwarg passed to+ `start_as_current_span`, so a custom sampler like this one reproduces the+ regression where a non-forwarding sampler silently drops FastMCP's+ attributes.+ """++ def should_sample(+ self,+ parent_context: OTelContext | None,+ trace_id: int,+ name: str,+ kind: object = None,+ attributes: object = None,+ links: object = None,+ trace_state: object = None,+ ) -> SamplingResult:+ return SamplingResult(Decision.RECORD_AND_SAMPLE)++ def get_description(self) -> str:+ return "NonForwardingSampler"+++class RedactingSampler(Sampler):+ """Forwards the attributes it receives, but replaces `mcp.method.name`.++ See `tests/telemetry/test_span_attributes.py` for the full explanation:+ a sampler can legitimately keep an attribute FastMCP set while replacing+ its value (e.g. redacting the method name for privacy), and that decision+ must survive the restore step.+ """++ def should_sample(+ self,+ parent_context: OTelContext | None,+ trace_id: int,+ name: str,+ kind: object = None,+ attributes: otel_types.Attributes = None,+ links: object = None,+ trace_state: object = None,+ ) -> SamplingResult:+ forwarded = dict(attributes or {})+ forwarded["mcp.method.name"] = "REDACTED"+ return SamplingResult(Decision.RECORD_AND_SAMPLE, attributes=forwarded)++ def get_description(self) -> str:+ return "RedactingSampler"+++class AttributeAddingSampler(Sampler):+ """Forwards the attributes it receives unchanged and adds its own."""++ def should_sample(+ self,+ parent_context: OTelContext | None,+ trace_id: int,+ name: str,+ kind: object = None,+ attributes: otel_types.Attributes = None,+ links: object = None,+ trace_state: object = None,+ ) -> SamplingResult:+ forwarded = dict(attributes or {})+ forwarded["sampling.policy"] = "always_on"+ return SamplingResult(Decision.RECORD_AND_SAMPLE, attributes=forwarded)++ def get_description(self) -> str:+ return "AttributeAddingSampler"+++class FilteringSampler(Sampler):+ """Discards every attribute it receives and substitutes its own.++ See `tests/telemetry/test_span_attributes.py` for the full explanation:+ a sampler can legitimately supply only its own attributes (e.g. to strip+ component names or resource URIs for privacy or cardinality control),+ and the restore step must not reintroduce FastMCP's attributes in that+ case β doing so would defeat the filter.+ """++ def should_sample(+ self,+ parent_context: OTelContext | None,+ trace_id: int,+ name: str,+ kind: object = None,+ attributes: otel_types.Attributes = None,+ links: object = None,+ trace_state: object = None,+ ) -> SamplingResult:+ return SamplingResult(+ Decision.RECORD_AND_SAMPLE, attributes={"sampling.policy": "filtered"}+ )++ def get_description(self) -> str:+ return "FilteringSampler"++@pytest.fixturedef on_start_recorder(monkeypatch: pytest.MonkeyPatch,@@ -187,3 +298,566 @@ class TestSamplingToolSpan:# Tool spans catch-and-convert (no re-raise), so OTel auto-recording# never fires; the manual record_exception must fire exactly once.assert len(_exception_events(span)) == 1+++class TestAttributesSurviveANonForwardingSampler:+ """Regression: `sampling create_message` and `sampling tool ...` spans+ must keep FastMCP's attributes even when the configured Sampler doesn't+ forward the `attributes` it was handed to its `SamplingResult`.+ """++ @pytest.fixture+ def non_forwarding_recorder(+ self,+ monkeypatch: pytest.MonkeyPatch,+ trace_exporter: InMemorySpanExporter,+ ) -> OnStartRecorder:+ recorder = OnStartRecorder()+ provider = TracerProvider(sampler=NonForwardingSampler())+ provider.add_span_processor(recorder)+ provider.add_span_processor(SimpleSpanProcessor(trace_exporter))+ tracer = provider.get_tracer("test")+ monkeypatch.setattr("fastmcp.server.sampling.run.get_tracer", lambda: tracer)+ return recorder++ async def test_create_message_span_keeps_attributes(+ self,+ trace_exporter: InMemorySpanExporter,+ non_forwarding_recorder: OnStartRecorder,+ ):+ def sampling_handler(+ messages: list[SamplingMessage],+ params: SamplingParams,+ ctx: RequestContext,+ ) -> str:+ return "sampled-text"++ mcp = FastMCP("sampling-server")++ @mcp.tool+ async def ask(question: str, context: Context) -> str:+ result = await context.sample(messages=question)+ return result.text or ""++ async with Client(mcp, sampling_handler=sampling_handler) as client:+ await client.call_tool("ask", {"question": "hi"})++ spans = _spans_named(trace_exporter, "sampling create_message")+ assert len(spans) == 1+ span = spans[0]+ assert span.attributes is not None+ assert span.attributes["mcp.method.name"] == "sampling/createMessage"+ assert span.attributes["fastmcp.server.name"] == "sampling-server"+ # The sampler never forwards attributes, so on_start legitimately sees+ # none β this documents that limitation rather than asserting around it.+ assert non_forwarding_recorder.attributes["sampling create_message"] == {}++ async def test_sampling_tool_span_keeps_attributes(+ self,+ trace_exporter: InMemorySpanExporter,+ non_forwarding_recorder: OnStartRecorder,+ ):+ from mcp_types import CreateMessageResultWithTools, ToolUseContent++ def echo_tool(text: str) -> str:+ return text++ call_count = 0++ def sampling_handler(+ messages: list[SamplingMessage],+ params: SamplingParams,+ ctx: RequestContext,+ ) -> CreateMessageResultWithTools:+ nonlocal call_count+ call_count += 1+ if call_count == 1:+ return CreateMessageResultWithTools(+ role="assistant",+ content=[+ ToolUseContent(+ type="tool_use",+ id="call_1",+ name="echo_tool",+ input={"text": "hi"},+ )+ ],+ model="test-model",+ stop_reason="toolUse",+ )+ return CreateMessageResultWithTools(+ role="assistant",+ content=[TextContent(type="text", text="done")],+ model="test-model",+ stop_reason="endTurn",+ )++ mcp = FastMCP(sampling_handler=sampling_handler)++ @mcp.tool+ async def driver(context: Context) -> str:+ result = await context.sample(messages="go", tools=[echo_tool])+ return result.text or ""++ async with Client(mcp) as client:+ await client.call_tool("driver", {})++ spans = _spans_named(trace_exporter, "sampling tool echo_tool")+ assert len(spans) == 1+ span = spans[0]+ assert span.attributes is not None+ assert span.attributes["gen_ai.tool.name"] == "echo_tool"+ assert span.attributes["fastmcp.tool.use_id"] == "call_1"+ # The sampler never forwards attributes, so on_start legitimately sees+ # none β this documents that limitation rather than asserting around it.+ assert non_forwarding_recorder.attributes["sampling tool echo_tool"] == {}+++class TestAttributeRestoreRespectsSampler:+ """Restoring missing attributes must not clobber attributes a sampler+ deliberately kept and modified, must coexist with attributes a sampler+ adds of its own, and must not fire at all when a sampler supplies only+ its own attributes and drops FastMCP's entirely."""++ @pytest.fixture+ def redacting_tracer(+ self, monkeypatch: pytest.MonkeyPatch, trace_exporter: InMemorySpanExporter+ ) -> None:+ provider = TracerProvider(sampler=RedactingSampler())+ provider.add_span_processor(SimpleSpanProcessor(trace_exporter))+ tracer = provider.get_tracer("test")+ monkeypatch.setattr("fastmcp.server.sampling.run.get_tracer", lambda: tracer)++ @pytest.fixture+ def attribute_adding_tracer(+ self, monkeypatch: pytest.MonkeyPatch, trace_exporter: InMemorySpanExporter+ ) -> None:+ provider = TracerProvider(sampler=AttributeAddingSampler())+ provider.add_span_processor(SimpleSpanProcessor(trace_exporter))+ tracer = provider.get_tracer("test")+ monkeypatch.setattr("fastmcp.server.sampling.run.get_tracer", lambda: tracer)++ @pytest.fixture+ def filtering_tracer(+ self, monkeypatch: pytest.MonkeyPatch, trace_exporter: InMemorySpanExporter+ ) -> None:+ provider = TracerProvider(sampler=FilteringSampler())+ provider.add_span_processor(SimpleSpanProcessor(trace_exporter))+ tracer = provider.get_tracer("test")+ monkeypatch.setattr("fastmcp.server.sampling.run.get_tracer", lambda: tracer)++ async def test_create_message_span_keeps_redacted_value(+ self,+ trace_exporter: InMemorySpanExporter,+ redacting_tracer: None,+ ):+ def sampling_handler(+ messages: list[SamplingMessage],+ params: SamplingParams,+ ctx: RequestContext,+ ) -> str:+ return "sampled-text"++ mcp = FastMCP("sampling-server")++ @mcp.tool+ async def ask(question: str, context: Context) -> str:+ result = await context.sample(messages=question)+ return result.text or ""++ async with Client(mcp, sampling_handler=sampling_handler) as client:+ await client.call_tool("ask", {"question": "hi"})++ spans = _spans_named(trace_exporter, "sampling create_message")+ assert len(spans) == 1+ span = spans[0]+ assert span.attributes is not None+ # The redaction survives β it must not be overwritten by a restore.+ assert span.attributes["mcp.method.name"] == "REDACTED"+ # Attributes the sampler didn't touch are still present.+ assert span.attributes["fastmcp.server.name"] == "sampling-server"++ async def test_create_message_span_keeps_sampler_added_attribute(+ self,+ trace_exporter: InMemorySpanExporter,+ attribute_adding_tracer: None,+ ):+ def sampling_handler(+ messages: list[SamplingMessage],+ params: SamplingParams,+ ctx: RequestContext,+ ) -> str:+ return "sampled-text"++ mcp = FastMCP("sampling-server")++ @mcp.tool+ async def ask(question: str, context: Context) -> str:+ result = await context.sample(messages=question)+ return result.text or ""++ async with Client(mcp, sampling_handler=sampling_handler) as client:+ await client.call_tool("ask", {"question": "hi"})++ spans = _spans_named(trace_exporter, "sampling create_message")+ assert len(spans) == 1+ span = spans[0]+ assert span.attributes is not None+ assert span.attributes["sampling.policy"] == "always_on"+ assert span.attributes["mcp.method.name"] == "sampling/createMessage"+ assert span.attributes["fastmcp.server.name"] == "sampling-server"++ async def test_tool_span_keeps_redacted_value(+ self,+ trace_exporter: InMemorySpanExporter,+ redacting_tracer: None,+ ):+ from mcp_types import CreateMessageResultWithTools, ToolUseContent++ def echo_tool(text: str) -> str:+ return text++ call_count = 0++ def sampling_handler(+ messages: list[SamplingMessage],+ params: SamplingParams,+ ctx: RequestContext,+ ) -> CreateMessageResultWithTools:+ nonlocal call_count+ call_count += 1+ if call_count == 1:+ return CreateMessageResultWithTools(+ role="assistant",+ content=[+ ToolUseContent(+ type="tool_use",+ id="call_1",+ name="echo_tool",+ input={"text": "hi"},+ )+ ],+ model="test-model",+ stop_reason="toolUse",+ )+ return CreateMessageResultWithTools(+ role="assistant",+ content=[TextContent(type="text", text="done")],+ model="test-model",+ stop_reason="endTurn",+ )++ mcp = FastMCP(sampling_handler=sampling_handler)++ @mcp.tool+ async def driver(context: Context) -> str:+ result = await context.sample(messages="go", tools=[echo_tool])+ return result.text or ""++ async with Client(mcp) as client:+ await client.call_tool("driver", {})++ spans = _spans_named(trace_exporter, "sampling tool echo_tool")+ assert len(spans) == 1+ span = spans[0]+ assert span.attributes is not None+ # RedactingSampler only touches mcp.method.name, which this span+ # doesn't set β its attributes are forwarded unchanged, confirming+ # the restore step doesn't disturb them either.+ assert span.attributes["gen_ai.tool.name"] == "echo_tool"+ assert span.attributes["fastmcp.tool.use_id"] == "call_1"++ async def test_tool_span_keeps_sampler_added_attribute(+ self,+ trace_exporter: InMemorySpanExporter,+ attribute_adding_tracer: None,+ ):+ from mcp_types import CreateMessageResultWithTools, ToolUseContent++ def echo_tool(text: str) -> str:+ return text++ call_count = 0++ def sampling_handler(+ messages: list[SamplingMessage],+ params: SamplingParams,+ ctx: RequestContext,+ ) -> CreateMessageResultWithTools:+ nonlocal call_count+ call_count += 1+ if call_count == 1:+ return CreateMessageResultWithTools(+ role="assistant",+ content=[+ ToolUseContent(+ type="tool_use",+ id="call_1",+ name="echo_tool",+ input={"text": "hi"},+ )+ ],+ model="test-model",+ stop_reason="toolUse",+ )+ return CreateMessageResultWithTools(+ role="assistant",+ content=[TextContent(type="text", text="done")],+ model="test-model",+ stop_reason="endTurn",+ )++ mcp = FastMCP(sampling_handler=sampling_handler)++ @mcp.tool+ async def driver(context: Context) -> str:+ result = await context.sample(messages="go", tools=[echo_tool])+ return result.text or ""++ async with Client(mcp) as client:+ await client.call_tool("driver", {})++ spans = _spans_named(trace_exporter, "sampling tool echo_tool")+ assert len(spans) == 1+ span = spans[0]+ assert span.attributes is not None+ assert span.attributes["sampling.policy"] == "always_on"+ assert span.attributes["gen_ai.tool.name"] == "echo_tool"+ assert span.attributes["fastmcp.tool.use_id"] == "call_1"++ async def test_create_message_span_filtered_attributes_are_not_restored(+ self,+ trace_exporter: InMemorySpanExporter,+ filtering_tracer: None,+ ):+ """Regression: a sampler that intentionally supplies only its own+ attributes must not have FastMCP's attributes restored on top."""++ def sampling_handler(+ messages: list[SamplingMessage],+ params: SamplingParams,+ ctx: RequestContext,+ ) -> str:+ return "sampled-text"++ mcp = FastMCP("sampling-server")++ @mcp.tool+ async def ask(question: str, context: Context) -> str:+ result = await context.sample(messages=question)+ return result.text or ""++ async with Client(mcp, sampling_handler=sampling_handler) as client:+ await client.call_tool("ask", {"question": "hi"})++ spans = _spans_named(trace_exporter, "sampling create_message")+ assert len(spans) == 1+ span = spans[0]+ assert dict(span.attributes or {}) == {"sampling.policy": "filtered"}++ async def test_tool_span_filtered_attributes_are_not_restored(+ self,+ trace_exporter: InMemorySpanExporter,+ filtering_tracer: None,+ ):+ """Regression: a sampler that intentionally supplies only its own+ attributes must not have FastMCP's attributes restored on top."""+ from mcp_types import CreateMessageResultWithTools, ToolUseContent++ def echo_tool(text: str) -> str:+ return text++ call_count = 0++ def sampling_handler(+ messages: list[SamplingMessage],+ params: SamplingParams,+ ctx: RequestContext,+ ) -> CreateMessageResultWithTools:+ nonlocal call_count+ call_count += 1+ if call_count == 1:+ return CreateMessageResultWithTools(+ role="assistant",+ content=[+ ToolUseContent(+ type="tool_use",+ id="call_1",+ name="echo_tool",+ input={"text": "hi"},+ )+ ],+ model="test-model",+ stop_reason="toolUse",+ )+ return CreateMessageResultWithTools(+ role="assistant",+ content=[TextContent(type="text", text="done")],+ model="test-model",+ stop_reason="endTurn",+ )++ mcp = FastMCP(sampling_handler=sampling_handler)++ @mcp.tool+ async def driver(context: Context) -> str:+ result = await context.sample(messages="go", tools=[echo_tool])+ return result.text or ""++ async with Client(mcp) as client:+ await client.call_tool("driver", {})++ spans = _spans_named(trace_exporter, "sampling tool echo_tool")+ assert len(spans) == 1+ span = spans[0]+ assert dict(span.attributes or {}) == {"sampling.policy": "filtered"}+++class TestRestoreDoesNotChurnAttributeLimitEvictions:+ """Regression: under a low `OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`, the restore+ step in `fastmcp.server.sampling.run` must not reinsert an attribute the+ SDK's bounded attribute map already evicted.++ See `tests/telemetry/test_span_attributes.py::+ test_restore_does_not_churn_sdk_attribute_limit_evictions` for the full+ explanation: an evicted key looks identical to a sampler-omitted one from+ inside the restore helper, so reinserting it churns which attributes the+ SDK ultimately retains and inflates `dropped_attributes` beyond what the+ limit alone already cost. This proves the same discriminator holds+ end-to-end through the real sampling call path, not just at the helper+ level.+ """++ @staticmethod+ async def _run_create_message(+ span_limits: SpanLimits, *, stub_restore: bool+ ) -> ReadableSpan:+ with pytest.MonkeyPatch.context() as mp:+ exporter = InMemorySpanExporter()+ provider = TracerProvider(span_limits=span_limits)+ provider.add_span_processor(SimpleSpanProcessor(exporter))+ tracer = provider.get_tracer("test")+ mp.setattr("fastmcp.server.sampling.run.get_tracer", lambda: tracer)+ if stub_restore:+ mp.setattr(+ "fastmcp.server.sampling.run.restore_dropped_attributes",+ lambda span, attrs: None,+ )++ def sampling_handler(+ messages: list[SamplingMessage],+ params: SamplingParams,+ ctx: RequestContext,+ ) -> str:+ return "sampled-text"++ mcp = FastMCP("sampling-server")++ @mcp.tool+ async def ask(question: str, context: Context) -> str:+ result = await context.sample(messages=question)+ return result.text or ""++ async with Client(mcp, sampling_handler=sampling_handler) as client:+ await client.call_tool("ask", {"question": "hi"})++ spans = _spans_named(exporter, "sampling create_message")+ assert len(spans) == 1+ return spans[0]++ @staticmethod+ async def _run_tool_span(+ span_limits: SpanLimits, *, stub_restore: bool+ ) -> ReadableSpan:+ from mcp_types import CreateMessageResultWithTools, ToolUseContent++ with pytest.MonkeyPatch.context() as mp:+ exporter = InMemorySpanExporter()+ provider = TracerProvider(span_limits=span_limits)+ provider.add_span_processor(SimpleSpanProcessor(exporter))+ tracer = provider.get_tracer("test")+ mp.setattr("fastmcp.server.sampling.run.get_tracer", lambda: tracer)+ if stub_restore:+ mp.setattr(+ "fastmcp.server.sampling.run.restore_dropped_attributes",+ lambda span, attrs: None,+ )++ def echo_tool(text: str) -> str:+ return text++ call_count = 0++ def sampling_handler(+ messages: list[SamplingMessage],+ params: SamplingParams,+ ctx: RequestContext,+ ) -> CreateMessageResultWithTools:+ nonlocal call_count+ call_count += 1+ if call_count == 1:+ return CreateMessageResultWithTools(+ role="assistant",+ content=[+ ToolUseContent(+ type="tool_use",+ id="call_1",+ name="echo_tool",+ input={"text": "hi"},+ )+ ],+ model="test-model",+ stop_reason="toolUse",+ )+ return CreateMessageResultWithTools(+ role="assistant",+ content=[TextContent(type="text", text="done")],+ model="test-model",+ stop_reason="endTurn",+ )++ mcp = FastMCP(sampling_handler=sampling_handler)++ @mcp.tool+ async def driver(context: Context) -> str:+ result = await context.sample(messages="go", tools=[echo_tool])+ return result.text or ""++ async with Client(mcp) as client:+ await client.call_tool("driver", {})++ spans = _spans_named(exporter, "sampling tool echo_tool")+ assert len(spans) == 1+ return spans[0]++ async def test_create_message_span(self, monkeypatch: pytest.MonkeyPatch):+ # Two attributes on this span (`mcp.method.name`, `fastmcp.server.name`)+ # β a limit of 1 guarantees eviction.+ monkeypatch.setenv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", "1")+ span_limits = SpanLimits()+ assert span_limits.max_span_attributes == 1++ baseline = await self._run_create_message(span_limits, stub_restore=True)+ # The whole test is moot if the limit didn't actually bind.+ assert baseline.dropped_attributes > 0++ with_restore = await self._run_create_message(span_limits, stub_restore=False)++ assert dict(with_restore.attributes or {}) == dict(baseline.attributes or {})+ assert with_restore.dropped_attributes == baseline.dropped_attributes++ async def test_tool_span(self, monkeypatch: pytest.MonkeyPatch):+ # Two attributes on this span (`gen_ai.tool.name`, `fastmcp.tool.use_id`)+ # β a limit of 1 guarantees eviction.+ monkeypatch.setenv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", "1")+ span_limits = SpanLimits()+ assert span_limits.max_span_attributes == 1++ baseline = await self._run_tool_span(span_limits, stub_restore=True)+ # The whole test is moot if the limit didn't actually bind.+ assert baseline.dropped_attributes > 0++ with_restore = await self._run_tool_span(span_limits, stub_restore=False)++ assert dict(with_restore.attributes or {}) == dict(baseline.attributes or {})+ assert with_restore.dropped_attributes == baseline.dropped_attributesdiff --git a/tests/telemetry/test_span_attributes.py b/tests/telemetry/test_span_attributes.pyindex 82fde174e..554a288cb 100644--- a/tests/telemetry/test_span_attributes.py+++ b/tests/telemetry/test_span_attributes.py@@ -1,6 +1,20 @@+from collections.abc import Callable+from contextlib import AbstractContextManager+import pytestfrom opentelemetry.context import Context-from opentelemetry.sdk.trace import Span, SpanProcessor, TracerProvider+from opentelemetry.sdk.trace import (+ ReadableSpan,+ Span,+ SpanLimits,+ SpanProcessor,+ TracerProvider,+)+from opentelemetry.sdk.trace.export import SimpleSpanProcessor+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter+from opentelemetry.sdk.trace.sampling import Decision, Sampler, SamplingResult+from opentelemetry.trace import Span as APISpan+from opentelemetry.util import types as otel_typesfrom fastmcp.client.telemetry import client_spanfrom fastmcp.server.telemetry import delegate_span, seam_span, server_span@@ -14,6 +28,114 @@ class OnStartRecorder(SpanProcessor):self.attributes[span.name] = dict(span.attributes or {})+class NonForwardingSampler(Sampler):+ """Samples every span but never forwards the attributes it was handed.++ Mirrors a real-world custom sampler that builds its own `SamplingResult`+ without threading through the `attributes` it received β the+ `attributes` parameter defaults to `None`, so `RECORD_AND_SAMPLE` with no+ `attributes` argument reproduces the regression: OTel's `Tracer.start_span`+ constructs the span from `sampling_result.attributes`, not from the+ `attributes` kwarg passed to `start_as_current_span`.+ """++ def should_sample(+ self,+ parent_context: Context | None,+ trace_id: int,+ name: str,+ kind: object = None,+ attributes: object = None,+ links: object = None,+ trace_state: object = None,+ ) -> SamplingResult:+ return SamplingResult(Decision.RECORD_AND_SAMPLE)++ def get_description(self) -> str:+ return "NonForwardingSampler"+++class RedactingSampler(Sampler):+ """Forwards the attributes it receives, but replaces `mcp.method.name`.++ Mirrors a real-world sampler that deliberately alters a FastMCP attribute+ (e.g. redacting the method name for privacy) rather than failing to+ forward attributes at all. The restore-missing-attributes helper must+ respect this decision: `mcp.method.name` is present on the span, just not+ with FastMCP's original value, so it must not be overwritten.+ """++ def should_sample(+ self,+ parent_context: Context | None,+ trace_id: int,+ name: str,+ kind: object = None,+ attributes: otel_types.Attributes = None,+ links: object = None,+ trace_state: object = None,+ ) -> SamplingResult:+ forwarded = dict(attributes or {})+ forwarded["mcp.method.name"] = "REDACTED"+ return SamplingResult(Decision.RECORD_AND_SAMPLE, attributes=forwarded)++ def get_description(self) -> str:+ return "RedactingSampler"+++class AttributeAddingSampler(Sampler):+ """Forwards the attributes it receives unchanged and adds its own.++ Mirrors a sampler that annotates spans with sampling-policy metadata.+ Both the sampler's own attribute and FastMCP's attributes must survive.+ """++ def should_sample(+ self,+ parent_context: Context | None,+ trace_id: int,+ name: str,+ kind: object = None,+ attributes: otel_types.Attributes = None,+ links: object = None,+ trace_state: object = None,+ ) -> SamplingResult:+ forwarded = dict(attributes or {})+ forwarded["sampling.policy"] = "always_on"+ return SamplingResult(Decision.RECORD_AND_SAMPLE, attributes=forwarded)++ def get_description(self) -> str:+ return "AttributeAddingSampler"+++class FilteringSampler(Sampler):+ """Discards every attribute it receives and substitutes its own.++ Mirrors a real-world sampler that strips component names or resource+ URIs for privacy or cardinality control by returning a `SamplingResult`+ with only its own attribute, ignoring what it was handed entirely. None+ of FastMCP's attributes may survive on the span, and the restore helper+ must not reintroduce them β that would defeat the filter.+ """++ def should_sample(+ self,+ parent_context: Context | None,+ trace_id: int,+ name: str,+ kind: object = None,+ attributes: otel_types.Attributes = None,+ links: object = None,+ trace_state: object = None,+ ) -> SamplingResult:+ return SamplingResult(+ Decision.RECORD_AND_SAMPLE, attributes={"sampling.policy": "filtered"}+ )++ def get_description(self) -> str:+ return "FilteringSampler"++def test_known_span_attributes_are_available_on_start(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -72,3 +194,276 @@ def test_known_span_attributes_are_available_on_start("fastmcp.component.key": "tool:echo@","mcp.method.name": "tools/call",}+++SPAN_HELPER_CASES = [+ pytest.param(+ lambda: client_span(+ "client test",+ method="tools/call",+ component_key="tool:echo@",+ tool_name="echo",+ ),+ "client test",+ {+ "mcp.method.name": "tools/call",+ "fastmcp.component.key": "tool:echo@",+ "gen_ai.tool.name": "echo",+ },+ id="client_span",+ ),+ pytest.param(+ lambda: server_span(+ "server test",+ method="tools/call",+ server_name="test-server",+ component_type="tool",+ component_key="tool:echo@",+ tool_name="echo",+ ),+ "server test",+ {+ "mcp.method.name": "tools/call",+ "fastmcp.server.name": "test-server",+ "fastmcp.component.type": "tool",+ "fastmcp.component.key": "tool:echo@",+ "gen_ai.tool.name": "echo",+ },+ id="server_span",+ ),+ pytest.param(+ lambda: seam_span("initialize test", server_name="test-server"),+ "initialize test",+ {+ "fastmcp.span.seam": True,+ "mcp.method.name": "initialize test",+ "fastmcp.server.name": "test-server",+ },+ id="seam_span",+ ),+ pytest.param(+ lambda: delegate_span(+ "delegate test",+ provider_type="LocalProvider",+ component_key="tool:echo@",+ method="tools/call",+ ),+ "delegate delegate test",+ {+ "fastmcp.provider.type": "LocalProvider",+ "fastmcp.component.key": "tool:echo@",+ "mcp.method.name": "tools/call",+ },+ id="delegate_span",+ ),+]+++ ("span_factory", "span_name", "expected_attrs"), SPAN_HELPER_CASES+)+def test_attributes_survive_a_non_forwarding_sampler(+ monkeypatch: pytest.MonkeyPatch,+ span_factory: Callable[[], AbstractContextManager[APISpan]],+ span_name: str,+ expected_attrs: dict[str, object],+) -> None:+ """Regression: a custom Sampler that samples a span but doesn't forward+ the `attributes` it was handed must not erase FastMCP's telemetry.++ OTel's `Tracer.start_span` builds the finished span from+ `sampling_result.attributes`, not from the `attributes` kwarg passed to+ `start_as_current_span`. Built-in samplers forward what they're given, but+ a custom sampler can legally return `SamplingResult(attributes=None)` and+ silently drop everything FastMCP passed in. The span helpers must reapply+ their attributes after span creation so this can't happen.+ """+ exporter = InMemorySpanExporter()+ provider = TracerProvider(sampler=NonForwardingSampler())+ provider.add_span_processor(SimpleSpanProcessor(exporter))+ tracer = provider.get_tracer("test")+ monkeypatch.setattr("fastmcp.client.telemetry.get_tracer", lambda: tracer)+ monkeypatch.setattr("fastmcp.server.telemetry.get_tracer", lambda: tracer)++ with span_factory():+ pass++ spans = [s for s in exporter.get_finished_spans() if s.name == span_name]+ assert len(spans) == 1+ assert dict(spans[0].attributes or {}) == expected_attrs+++ ("span_factory", "span_name", "expected_attrs"), SPAN_HELPER_CASES+)+def test_redacted_attribute_survives_a_redacting_sampler(+ monkeypatch: pytest.MonkeyPatch,+ span_factory: Callable[[], AbstractContextManager[APISpan]],+ span_name: str,+ expected_attrs: dict[str, object],+) -> None:+ """A sampler that deliberately replaces one of FastMCP's attributes (e.g.+ redacting `mcp.method.name` for privacy) must have that decision survive.++ Restoring must only fill in attributes the sampler dropped, never+ overwrite attributes the sampler kept and intentionally changed.+ """+ exporter = InMemorySpanExporter()+ provider = TracerProvider(sampler=RedactingSampler())+ provider.add_span_processor(SimpleSpanProcessor(exporter))+ tracer = provider.get_tracer("test")+ monkeypatch.setattr("fastmcp.client.telemetry.get_tracer", lambda: tracer)+ monkeypatch.setattr("fastmcp.server.telemetry.get_tracer", lambda: tracer)++ with span_factory():+ pass++ spans = [s for s in exporter.get_finished_spans() if s.name == span_name]+ assert len(spans) == 1+ attrs = dict(spans[0].attributes or {})++ # The redaction must survive β not be clobbered by a blanket reapply.+ assert attrs["mcp.method.name"] == "REDACTED"++ # Every other FastMCP attribute the sampler forwarded unchanged is+ # untouched, and any it dropped are still restored.+ for key, value in expected_attrs.items():+ if key == "mcp.method.name":+ continue+ assert attrs[key] == value+++ ("span_factory", "span_name", "expected_attrs"), SPAN_HELPER_CASES+)+def test_sampler_added_attribute_survives_alongside_fastmcp_attributes(+ monkeypatch: pytest.MonkeyPatch,+ span_factory: Callable[[], AbstractContextManager[APISpan]],+ span_name: str,+ expected_attrs: dict[str, object],+) -> None:+ """A sampler that forwards attributes unchanged and adds its own must+ keep both: its own attribute and every FastMCP attribute."""+ exporter = InMemorySpanExporter()+ provider = TracerProvider(sampler=AttributeAddingSampler())+ provider.add_span_processor(SimpleSpanProcessor(exporter))+ tracer = provider.get_tracer("test")+ monkeypatch.setattr("fastmcp.client.telemetry.get_tracer", lambda: tracer)+ monkeypatch.setattr("fastmcp.server.telemetry.get_tracer", lambda: tracer)++ with span_factory():+ pass++ spans = [s for s in exporter.get_finished_spans() if s.name == span_name]+ assert len(spans) == 1+ attrs = dict(spans[0].attributes or {})++ assert attrs["sampling.policy"] == "always_on"+ for key, value in expected_attrs.items():+ assert attrs[key] == value+++ ("span_factory", "span_name", "expected_attrs"), SPAN_HELPER_CASES+)+def test_filtered_attributes_are_not_restored(+ monkeypatch: pytest.MonkeyPatch,+ span_factory: Callable[[], AbstractContextManager[APISpan]],+ span_name: str,+ expected_attrs: dict[str, object],+) -> None:+ """Regression: a sampler that intentionally supplies only its own+ attributes (e.g. to strip component names or resource URIs for privacy+ or cardinality control) must not have FastMCP's attributes restored.++ A gate keyed off "none of our keys are present" can't tell this apart+ from a bare non-forwarding sampler β both leave none of FastMCP's keys+ on the span β so it would restore everything and defeat the filter. The+ fix keys off the span having no attributes at all: a filtering sampler+ leaves the span non-empty (its own attribute is there), which a bare+ non-forwarding sampler never does.+ """+ exporter = InMemorySpanExporter()+ provider = TracerProvider(sampler=FilteringSampler())+ provider.add_span_processor(SimpleSpanProcessor(exporter))+ tracer = provider.get_tracer("test")+ monkeypatch.setattr("fastmcp.client.telemetry.get_tracer", lambda: tracer)+ monkeypatch.setattr("fastmcp.server.telemetry.get_tracer", lambda: tracer)++ with span_factory():+ pass++ spans = [s for s in exporter.get_finished_spans() if s.name == span_name]+ assert len(spans) == 1+ attrs = dict(spans[0].attributes or {})++ assert attrs == {"sampling.policy": "filtered"}+ for key in expected_attrs:+ assert key not in attrs+++ ("span_factory", "span_name", "expected_attrs"), SPAN_HELPER_CASES+)+def test_restore_does_not_churn_sdk_attribute_limit_evictions(+ monkeypatch: pytest.MonkeyPatch,+ span_factory: Callable[[], AbstractContextManager[APISpan]],+ span_name: str,+ expected_attrs: dict[str, object],+) -> None:+ """Regression: under a low `OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`, restoring+ must not reinsert a key the SDK's bounded attribute map already evicted.++ An evicted key is indistinguishable from a sampler-omitted one from+ inside the restore helper, so a per-key "reinsert what's missing"+ strategy would cycle an evicted key back onto the span, which evicts a+ *different* retained key and inflates `dropped_attributes` beyond what+ the SDK's own eviction already cost. The fix gates the restore on the+ span having no attributes at all (plus `dropped_attributes == 0`), so a+ normal forwarding sampler colliding with a low limit is left exactly as+ the SDK computed it β this test proves that by diffing against a+ baseline with the restore step stubbed out entirely.+ """+ monkeypatch.setenv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", "2")+ # SpanLimits reads the env var at construction time, so build it now+ # (after setting the env var) rather than relying on TracerProvider to+ # pick it up implicitly.+ span_limits = SpanLimits()+ assert span_limits.max_span_attributes == 2++ def run(*, stub_restore: bool) -> ReadableSpan:+ # Each run gets its own MonkeyPatch context so patches from one run+ # (e.g. stubbing the restore step for the baseline) don't leak into+ # the other β both runs must exercise their own code path.+ with pytest.MonkeyPatch.context() as mp:+ exporter = InMemorySpanExporter()+ provider = TracerProvider(span_limits=span_limits)+ provider.add_span_processor(SimpleSpanProcessor(exporter))+ tracer = provider.get_tracer("test")+ mp.setattr("fastmcp.client.telemetry.get_tracer", lambda: tracer)+ mp.setattr("fastmcp.server.telemetry.get_tracer", lambda: tracer)+ if stub_restore:+ mp.setattr(+ "fastmcp.client.telemetry.restore_dropped_attributes",+ lambda span, attrs: None,+ )+ mp.setattr(+ "fastmcp.server.telemetry.restore_dropped_attributes",+ lambda span, attrs: None,+ )++ with span_factory():+ pass++ spans = [s for s in exporter.get_finished_spans() if s.name == span_name]+ assert len(spans) == 1+ return spans[0]++ baseline = run(stub_restore=True)+ # The whole test is moot if the limit didn't actually bind.+ assert baseline.dropped_attributes > 0++ with_restore = run(stub_restore=False)++ assert dict(with_restore.attributes or {}) == dict(baseline.attributes or {})+ assert with_restore.dropped_attributes == baseline.dropped_attributes