1- """OpenTelemetry helpers for MCP.
2-
3- Provides a context manager that creates an OpenTelemetry span when
4- ``opentelemetry-api`` is installed, or acts as a no-op otherwise.
5- """
1+ """OpenTelemetry helpers for MCP."""
62
73from __future__ import annotations
84
9- import functools
105from collections .abc import Iterator
116from contextlib import contextmanager
127from typing import Any
138
9+ from opentelemetry .trace import SpanKind , get_tracer
1410
15- @functools .lru_cache (maxsize = 1 )
16- def _get_tracer () -> Any :
17- """Return the OTel tracer for ``mcp``, or ``None``."""
18- try :
19- from opentelemetry .trace import get_tracer
20-
21- return get_tracer ("mcp-python-sdk" )
22- except ImportError :
23- return None
11+ _tracer = get_tracer ("mcp-python-sdk" )
2412
2513
2614@contextmanager
@@ -30,14 +18,7 @@ def otel_span(
3018 kind : str = "INTERNAL" ,
3119 attributes : dict [str , Any ] | None = None ,
3220) -> Iterator [Any ]:
33- """Create an OTel span if ``opentelemetry-api`` is installed, else no-op."""
34- tracer = _get_tracer ()
35- if tracer is None :
36- yield None
37- return
38-
39- from opentelemetry .trace import SpanKind
40-
21+ """Create an OTel span."""
4122 span_kind = getattr (SpanKind , kind , SpanKind .INTERNAL )
42- with tracer .start_as_current_span (name , kind = span_kind , attributes = attributes ) as span :
23+ with _tracer .start_as_current_span (name , kind = span_kind , attributes = attributes ) as span :
4324 yield span
0 commit comments