The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(otel): name the RPC system and upstream on MCP tool-call spans (#35857)
yucheng-berri0a606cb258f7
diff --git a/litellm/integrations/otel/__init__.py b/litellm/integrations/otel/__init__.pyindex 94442e96adb..9c1205bb277 100644--- a/litellm/integrations/otel/__init__.py+++ b/litellm/integrations/otel/__init__.py@@ -57,6 +57,7 @@ from litellm.integrations.otel.model.semconv import (Metric,Network,NetworkTransport,+ RpcSystem,Server,resolve_operation,resolve_provider,@@ -102,6 +103,7 @@ __all__ = ["ProxyRequestSpanData","RequestContext","RequestIdentity",+ "RpcSystem","Server","ServerInfo","ServiceSpanData",diff --git a/litellm/integrations/otel/mappers/genai.py b/litellm/integrations/otel/mappers/genai.pyindex af56734bec1..032441535e0 100644--- a/litellm/integrations/otel/mappers/genai.py+++ b/litellm/integrations/otel/mappers/genai.py@@ -31,7 +31,9 @@ from litellm.integrations.otel.model.semconv import (MCP,Error,GenAI,+ JsonRpc,LiteLLM,+ RpcSystem,Server,)from litellm.integrations.otel.model.spans import db_system@@ -94,11 +96,14 @@ class GenAIMapper:_MCP_ATTRS: dict[str, Callable[[MCPToolCallSpanData], AttrValue | None]] = {GenAI.OPERATION_NAME: lambda d: d.operation.value,+ JsonRpc.SYSTEM: lambda d: RpcSystem.JSONRPC.value if d.server_address and d.server_port else None,MCP.METHOD_NAME: lambda d: d.method,MCP.SESSION_ID: lambda d: d.session_id,GenAI.TOOL_NAME: lambda d: d.tool_name or None,GenAI.TOOL_CALL_ARGUMENTS: lambda d: d.arguments_json,GenAI.TOOL_CALL_RESULT: lambda d: d.result_json,+ Server.ADDRESS: lambda d: d.server_address,+ Server.PORT: lambda d: d.server_port,LiteLLM.MCP_SERVER_NAME: lambda d: d.server_name,LiteLLM.CALL_ID: lambda d: d.identity.call_id or None,f"{LiteLLM.COST_PREFIX}total": lambda d: d.response_cost,diff --git a/litellm/integrations/otel/model/payloads.py b/litellm/integrations/otel/model/payloads.pyindex 02499010624..aba9cc80240 100644--- a/litellm/integrations/otel/model/payloads.py+++ b/litellm/integrations/otel/model/payloads.py@@ -364,6 +364,34 @@ class LLMCallSpanData:# --- the MCP tool-call model ------------------------------------------------- #+def _upstream_address_port(resource: str | None) -> tuple[str | None, int | None]:+ """Split a redacted MCP server origin into ``server.address`` / ``server.port``.++ ``mcp_server_resource`` is a scheme + host + port origin with userinfo, path,+ query and fragment already stripped. The port falls back to the scheme default+ when the origin omits it, because a consumer that keys a downstream dependency+ off the address renders a missing port as ``0``.++ The origin is rebuilt without its IPv6 brackets upstream, so reading the port can+ raise on an address the host check still admits: a zone-scoped ``fe80::1%25eth0``+ leaves a truthy hostname of ``fe80`` behind. Both halves are read inside the guard+ so an unparseable origin yields no address rather than propagating out of span+ construction, matching how the redactor guards the same split.+ """+ if not resource:+ return None, None+ try:+ parsed: Final = urlsplit(resource)+ hostname: Final = parsed.hostname+ port: Final = parsed.port+ except ValueError:+ return None, None+ if not hostname:+ return None, None+ default_port: Final = 443 if parsed.scheme == "https" else 80 if parsed.scheme == "http" else None+ return hostname, port or default_port++@dataclass(frozen=True)class MCPToolCallSpanData:"""One MCP ``tools/call`` execution, parsed from a closed request's payload.@@ -378,6 +406,8 @@ class MCPToolCallSpanData:method: strtool_name: strserver_name: str | None+ server_address: str | None+ server_port: int | Nonesession_id: str | Nonearguments_json: str | Noneresult_json: str | None@@ -390,11 +420,14 @@ class MCPToolCallSpanData:cls, payload: StandardLoggingPayload, capture_content: bool = False) -> MCPToolCallSpanData:meta: Final = _mcp_tool_call_metadata(cast(Mapping[str, object], payload))+ address, port = _upstream_address_port(as_str(meta.get("mcp_server_resource")) or None)return cls(operation=resolve_operation(as_str(payload.get("call_type"))),method=MCPMethod.TOOLS_CALL.value,tool_name=as_str(meta.get("name")) or "",server_name=as_str(meta.get("mcp_server_name")),+ server_address=address,+ server_port=port,session_id=as_str(meta.get("mcp_session_id")),arguments_json=(_json_or_none(meta.get("arguments")) if capture_content and meta.get("arguments") is not None else Nonediff --git a/litellm/integrations/otel/model/semconv.py b/litellm/integrations/otel/model/semconv.pyindex 24f0b947b08..3d585c36b67 100644--- a/litellm/integrations/otel/model/semconv.py+++ b/litellm/integrations/otel/model/semconv.py@@ -130,11 +130,25 @@ class JsonRpc:"""JSON-RPC keys carried on MCP spans. The error/status code lives in the``rpc.*`` namespace per semconv, not ``jsonrpc.*``."""+ SYSTEM: Final = "rpc.system"REQUEST_ID: Final = "jsonrpc.request.id"PROTOCOL_VERSION: Final = "jsonrpc.protocol.version"RESPONSE_STATUS_CODE: Final = "rpc.response.status_code"+class RpcSystem(str, Enum):+ """Well-known values for ``rpc.system``. MCP frames every message as JSON-RPC 2.0.++ Naming the system also classifies the span: a CLIENT span carrying none of the+ ``rpc.*``/``http.*``/``db.*``/``messaging.*`` families records no span type or+ subtype in backends that derive those from the attribute family. It is emitted+ only alongside ``server.address``/``server.port``, since a backend that reads it+ as a downstream dependency names that dependency from the server address.+ """++ JSONRPC = "jsonrpc"++class NetworkTransport(str, Enum):"""Well-known values for ``network.transport``."""diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_logger.py b/tests/test_litellm/integrations/otel/test_otel_v2_logger.pyindex 41c02501acc..2573ad5a375 100644--- a/tests/test_litellm/integrations/otel/test_otel_v2_logger.py+++ b/tests/test_litellm/integrations/otel/test_otel_v2_logger.py@@ -356,6 +356,7 @@ def _mcp_payload(**overrides):"arguments": {"city": "Paris"},"result": {"temp_c": 21},"mcp_server_name": "weather-mcp",+ "mcp_server_resource": "https://weather.example.com","mcp_session_id": "sess-abc123",},},@@ -452,6 +453,8 @@ def test_mcp_tool_call_failure_marks_error():assert span.name == "tools/call get_weather"assert span.status.status_code is StatusCode.ERRORassert span.attributes["error.type"] == "MCPError"+ assert span.attributes["rpc.system"] == "jsonrpc"+ assert span.attributes["server.address"] == "weather.example.com"def test_mcp_tool_call_deduped_on_repeat():@@ -531,6 +534,82 @@ _MCP_SPAN_CASES = []+def test_mcp_tool_call_names_its_rpc_system_and_upstream():+ """A tool-call span names the RPC system, and always alongside the upstream it called.++ A CLIENT span holding none of the ``rpc.*``/``http.*``/``db.*``/``messaging.*``+ families is unclassifiable, so a backend deriving a span type from them has nothing+ to derive from: Elastic APM indexed these spans as ``span.type=unknown`` with no+ ``span.subtype`` at all, and its span-links API then rejected the whole trace with+ ``Missing required fields (span.subtype)``.++ The two assertions are one invariant, not two. Naming the RPC system makes a+ consumer treat the span as a downstream dependency and key that dependency off+ ``server.address``/``server.port``; emitting the first without the second names the+ dependency ``:0``, which is worse than leaving the span unclassified.+ """+ logger, exporter = _logger()+ asyncio.run(+ logger.async_log_success_event(+ {"standard_logging_object": _mcp_payload()}, None, None, None+ )+ )+ (span,) = exporter.get_finished_spans()+ assert span.attributes["rpc.system"] == "jsonrpc"+ assert span.attributes["server.address"] == "weather.example.com"+ assert span.attributes["server.port"] == 443+++ "resource",+ [None, "mcp://weather.example.com", "ws://weather.example.com"],+ ids=["no-resource", "scheme-with-no-default-port", "ws-scheme"],+)+def test_mcp_tool_call_omits_rpc_system_without_a_complete_upstream(resource):+ """A tool call drops the RPC system unless the full destination resolved.++ ``mcp_server_resource`` is absent whenever the tool name resolves to no registered+ server, and it is ``None`` for a transport with no host to log at all (stdio). A+ host-bearing scheme outside the HTTP(S) default-port map resolves an address but no+ port, and the ``url`` field is not scheme-validated, so that state is reachable from+ config. Each case names the dependency ``:0`` or ``host:0`` if ``rpc.system`` ships+ on its own, so the pairing is enforced here rather than left to the extractors+ happening to agree.+ """+ logger, exporter = _logger()+ payload = _mcp_payload()+ if resource is None:+ del payload["metadata"]["mcp_tool_call_metadata"]["mcp_server_resource"]+ else:+ payload["metadata"]["mcp_tool_call_metadata"]["mcp_server_resource"] = resource+ asyncio.run(+ logger.async_log_success_event({"standard_logging_object": payload}, None, None, None)+ )+ (span,) = exporter.get_finished_spans()+ assert "rpc.system" not in span.attributes+ assert "server.port" not in span.attributes+ assert span.attributes["mcp.method.name"] == "tools/call"+++def test_mcp_list_tools_omits_rpc_system_without_an_upstream():+ """The discovery span carries no upstream identity, so it must not claim to be RPC.++ ``tools/list`` reaches the callbacks with no ``mcp_tool_call_metadata``, so there is+ no ``server.address`` to attach and a listing can span several upstreams anyway.+ Naming ``rpc.system`` here would buy a ``span.subtype`` at the cost of a bogus ``:0``+ dependency node in every consumer that aggregates on it.+ """+ logger, exporter = _logger()+ asyncio.run(+ logger.async_log_success_event(+ {"standard_logging_object": _mcp_list_payload()}, None, None, None+ )+ )+ (span,) = exporter.get_finished_spans()+ assert "rpc.system" not in span.attributes+ assert "server.address" not in span.attributes++@pytest.mark.parametrize("make_payload, span_name", _MCP_SPAN_CASES)def test_mcp_span_nests_under_transport_without_propagated_context(make_payload, span_namediff --git a/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py b/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.pyindex 612ac1e5113..19d0cfc0b18 100644--- a/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py+++ b/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py@@ -24,7 +24,11 @@ from litellm.integrations.otel import (resolve_provider,)from litellm.integrations.otel.model import spans as spans_mod-from litellm.integrations.otel.model.payloads import LLMCallSpanData, RequestIdentity+from litellm.integrations.otel.model.payloads import (+ LLMCallSpanData,+ RequestIdentity,+ _upstream_address_port,+)from litellm.integrations.otel.model.spans import (SPAN_REGISTRY,LiteLLMSpanKind,@@ -177,6 +181,7 @@ def test_mcp_attribute_vocabulary_is_complete():"mcp.resource.uri","jsonrpc.request.id","jsonrpc.protocol.version",+ "rpc.system","rpc.response.status_code","gen_ai.operation.name","gen_ai.tool.name",@@ -808,3 +813,34 @@ def test_promoted_baggage_is_bounded_allowlist():# http.* is never a promoted keyassert HTTP.ROUTE not in promotedassert HTTP.REQUEST_METHOD not in promoted+++ "resource, expected",+ [+ ("https://weather.example.com", ("weather.example.com", 443)),+ ("http://weather.example.com", ("weather.example.com", 80)),+ ("https://weather.example.com:8443", ("weather.example.com", 8443)),+ ("mcp://weather.example.com", ("weather.example.com", None)),+ ("http://::1:8080", (None, None)),+ ("http://fe80::1%25eth0:80", (None, None)),+ (None, (None, None)),+ ("", (None, None)),+ ],+ ids=[+ "https-default",+ "http-default",+ "explicit-port",+ "no-default-port",+ "ipv6-unbracketed",+ "ipv6-zone-scoped",+ "none",+ "empty",+ ],+)+def test_upstream_address_port(resource, expected):+ """The redacted MCP origin resolves to the address and port a consumer names its+ dependency from. A scheme outside the default-port map yields no port, and an IPv6+ origin yields nothing at all because the redactor rebuilds it without its brackets;+ both are why the mapper gates ``rpc.system`` on the complete pair."""+ assert _upstream_address_port(resource) == expected