Skip to content

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]

fix(mcp): drop caller host and configured upstream headers from logged metadata (#36901)

yucheng-berrif9f5c03884fc
diff --git a/litellm/proxy/_experimental/mcp_server/utils.py b/litellm/proxy/_experimental/mcp_server/utils.py
index 4cf84dd0725..83883664df5 100644
--- a/litellm/proxy/_experimental/mcp_server/utils.py
+++ b/litellm/proxy/_experimental/mcp_server/utils.py
@@ -880,7 +880,9 @@ _HOP_BY_HOP_HEADERS: Final = frozenset(
}
)
-_SYNTHETIC_REQUEST_EXCLUDED_HEADERS: Final = _HOP_BY_HOP_HEADERS | frozenset({"content-type", "x-forwarded-for"})
+_SYNTHETIC_REQUEST_EXCLUDED_HEADERS: Final = _HOP_BY_HOP_HEADERS | frozenset(
+ {"content-type", "host", "x-forwarded-for"}
+)
_SYNTHETIC_REQUEST_SERVER: Final = ("127.0.0.1", 4000)
@@ -908,10 +910,57 @@ def _mcp_client_side_auth_header_name() -> str:
return MCPRequestHandler.LITELLM_MCP_AUTH_HEADER_NAME
+def _identity_header_names() -> frozenset[str]:
+ """Lowercased header names the deployment reads the caller's identity out of. A name here
+ is a claim about who the caller is rather than a secret, and ``get_user_from_headers``
+ resolves it off the request this module reconstructs, so dropping one would lose end user
+ attribution on the MCP paths that leave ``end_user_id`` unset at connect time.
+
+ ``user_header_mappings`` is accepted as a bare mapping as well as a list of them, matching
+ ``get_internal_user_header_from_mapping`` and ``get_customer_user_header_from_mapping``.
+ Iterating the bare form without normalizing yields its keys, which would silently exempt
+ nothing."""
+ try:
+ from litellm.proxy.proxy_server import general_settings
+ except ImportError:
+ return frozenset()
+ if not general_settings:
+ return frozenset()
+ user_header: Final = general_settings.get("user_header_name")
+ configured: Final = general_settings.get("user_header_mappings")
+ mappings: Final = configured if isinstance(configured, list) else (configured,) if configured else ()
+ mapped: Final = (mapping.get("header_name") for mapping in mappings if isinstance(mapping, Mapping))
+ return frozenset(name.lower() for name in (user_header, *mapped) if isinstance(name, str) and name)
+
+
+def _forwarded_upstream_header_names() -> frozenset[str]:
+ """Lowercased header names that a configured MCP server forwards upstream through its
+ ``extra_headers`` allowlist. The names are chosen by the admin, so no prefix rule can
+ recognize them, and a caller supplied value under one of them is an upstream credential.
+
+ ``authorization`` is left out because ``clean_headers`` already strips it, and claiming it
+ here would change which header ``authenticated_with_header`` resolves to on the oauth
+ passthrough config, which lists it in ``extra_headers`` by design. Identity headers are
+ left out for the same reason: naming one in ``extra_headers`` forwards the caller's
+ identity upstream, it does not turn that identity into a secret."""
+ try:
+ from .mcp_server_manager import global_mcp_server_manager
+ except ImportError:
+ return frozenset()
+ exempt: Final = _identity_header_names() | frozenset({"authorization"})
+ return frozenset(
+ name.lower()
+ for server in global_mcp_server_manager.get_registry().values()
+ for name in (server.extra_headers or ())
+ if name.lower() not in exempt
+ )
+
+
def _upstream_credential_headers(header_names: Iterable[str]) -> frozenset[str]:
"""Lowercased names of the headers in ``header_names`` that carry an upstream MCP
- credential rather than request context: the configured client side auth header and
- the per-server ``x-mcp-{alias}-{header}`` family. ``clean_headers`` only knows the
+ credential rather than request context: the configured client side auth header, any
+ header name a configured server forwards upstream via ``extra_headers``, and the
+ per-server ``x-mcp-{alias}-{header}`` family. ``clean_headers`` only knows the
credential headers of the chat completions path, so these are dropped on top of it.
"""
from .auth.user_api_key_auth_mcp import MCPRequestHandler
@@ -923,10 +972,13 @@ def _upstream_credential_headers(header_names: Iterable[str]) -> frozenset[str]:
}
)
client_side_auth: Final = _mcp_client_side_auth_header_name().lower()
+ forwarded_upstream: Final = _forwarded_upstream_header_names()
return frozenset(
name
for name in (raw_name.lower() for raw_name in header_names)
- if name == client_side_auth or (name.startswith(_MCP_SERVER_AUTH_HEADER_PREFIX) and name not in non_credential)
+ if name == client_side_auth
+ or name in forwarded_upstream
+ or (name.startswith(_MCP_SERVER_AUTH_HEADER_PREFIX) and name not in non_credential)
)
@@ -944,7 +996,9 @@ def build_synthetic_mcp_request(
``proxy_server_request``, header-based tags, guardrails and trace correlation
exactly as on the chat completions path. Hop-by-hop headers describe the
original HTTP framing rather than the logical request, so they are dropped, and
- ``x-forwarded-for`` comes from the resolved ``client_ip`` to avoid spoofing. Upstream
+ ``x-forwarded-for`` comes from the resolved ``client_ip`` to avoid spoofing. ``host`` is
+ dropped for the same reason: it is what ``Request.url`` is built from, so forwarding it
+ would let a caller choose the URL every logging callback records. Upstream
MCP credentials and the deployment's proxy key header, including a custom
``litellm_key_header_name``, are dropped so they cannot reach a callback or a guardrail
through the derived metadata even when a caller omits ``general_settings``.
@@ -991,7 +1045,8 @@ def logging_safe_mcp_headers(raw_headers: Mapping[str, str] | None) -> Mapping[s
too: these headers are read back out of the metadata to change proxy behaviour, so
leaving one in place would let any MCP client turn off the redaction an admin
configured. This path carries no key or team object to authorize an opt-out with, so
- it always strips them."""
+ it always strips them. ``host`` goes too, so that a caller cannot name the deployment in
+ the guardrail payload and the spend row the way it could once name the request URL."""
from starlette.datastructures import Headers
from litellm.proxy.litellm_pre_call_utils import (
@@ -1003,6 +1058,7 @@ def logging_safe_mcp_headers(raw_headers: Mapping[str, str] | None) -> Mapping[s
excluded: Final = (
_upstream_credential_headers(raw_headers.keys() if raw_headers else ())
| UNTRUSTED_REQUEST_HEADER_CONTROL_FIELDS
+ | frozenset({"host"})
)
cleaned: Final = clean_headers(
Headers(raw_headers),
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_utils.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_utils.py
index 00ed4e91efa..0252fb9843d 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_utils.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_utils.py
@@ -4,12 +4,32 @@ import pytest
from fastapi import HTTPException
from litellm.proxy._experimental.mcp_server.utils import (
+ _upstream_credential_headers,
build_synthetic_mcp_request,
logging_safe_mcp_headers,
validate_and_normalize_mcp_server_payload,
validate_tool_display_names,
)
from litellm.proxy._types import NewMCPServerRequest
+from litellm.types.mcp_server.mcp_server_manager import MCPServer
+
+
+def _server_forwarding(*header_names: str) -> MCPServer:
+ return MCPServer(
+ server_id="srv-1",
+ name="deepwiki",
+ transport="http",
+ url="https://mcp.example.com/mcp",
+ extra_headers=list(header_names),
+ )
+
+
+def _configured_servers(*servers: MCPServer):
+ return patch.dict(
+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager.config_mcp_servers",
+ {server.server_id: server for server in servers},
+ clear=False,
+ )
class TestValidateToolDisplayNames:
@@ -114,6 +134,70 @@ class TestLoggingSafeMcpHeaders:
assert safe == {"x-nuid": "nuid-1"}
+ def test_strips_headers_a_server_forwards_upstream(self):
+ """mcp_servers.<name>.extra_headers names the headers the proxy relays upstream, so a
+ caller supplied value under one of them is an upstream credential no prefix rule can spot.
+ Config is written in canonical casing while the wire header arrives lowercased."""
+ with _configured_servers(_server_forwarding("X-GitHub-Token", "X-Tenant")):
+ safe = logging_safe_mcp_headers({"x-github-token": "ghp_secret", "x-tenant": "acct-1", "x-nuid": "nuid-1"})
+
+ assert safe == {"x-nuid": "nuid-1"}
+
+ def test_strips_caller_asserted_host(self):
+ """This mapping reaches the guardrail payload and the list_tools spend row, so a caller
+ must not be able to name the deployment there either."""
+ safe = logging_safe_mcp_headers({"host": "evil.attacker.example", "x-nuid": "nuid-1"})
+
+ assert safe == {"x-nuid": "nuid-1"}
+
+ def test_keeps_identity_header_a_server_also_forwards(self):
+ """get_user_from_headers resolves end user attribution off this same request, so a header
+ the deployment reads identity from stays even when a server forwards it upstream."""
+ with patch.dict(
+ "litellm.proxy.proxy_server.general_settings",
+ {"user_header_name": "x-user-email"},
+ clear=False,
+ ):
+ with _configured_servers(_server_forwarding("x-user-email", "x-github-token")):
+ safe = logging_safe_mcp_headers({"x-user-email": "[email protected]", "x-github-token": "ghp_secret"})
+
+ assert safe == {"x-user-email": "[email protected]"}
+
+ @pytest.mark.parametrize(
+ "configured",
+ [
+ [{"header_name": "X-User", "litellm_user_role": "customer"}],
+ {"header_name": "X-User", "litellm_user_role": "customer"},
+ ],
+ ids=["list-of-mappings", "bare-mapping"],
+ )
+ def test_keeps_identity_header_from_user_header_mappings(self, configured):
+ """get_internal_user_header_from_mapping and get_customer_user_header_from_mapping both
+ accept a bare mapping as well as a list, and config_settings.md documents the key as a
+ dict, so the exemption has to read both shapes."""
+ with patch.dict(
+ "litellm.proxy.proxy_server.general_settings",
+ {"user_header_mappings": configured},
+ clear=False,
+ ):
+ with _configured_servers(_server_forwarding("X-User", "X-GitHub-Token")):
+ safe = logging_safe_mcp_headers({"x-user": "alice", "x-github-token": "ghp_secret"})
+
+ assert safe == {"x-user": "alice"}
+
+ def test_keeps_authorization_classification_for_oauth_passthrough(self):
+ """clean_headers already strips authorization, and claiming it here would change which
+ header authenticated_with_header resolves to on a config that lists it by design."""
+ with _configured_servers(_server_forwarding("Authorization", "X-GitHub-Token")):
+ assert "authorization" not in _upstream_credential_headers(["authorization", "x-github-token"])
+ assert "x-github-token" in _upstream_credential_headers(["authorization", "x-github-token"])
+
+ def test_keeps_headers_when_no_server_forwards_them(self):
+ with _configured_servers(_server_forwarding("x-github-token")):
+ safe = logging_safe_mcp_headers({"x-other-token": "not-forwarded", "x-nuid": "nuid-1"})
+
+ assert safe == {"x-other-token": "not-forwarded", "x-nuid": "nuid-1"}
+
class TestBuildSyntheticMcpRequest:
def test_forwards_client_headers_without_upstream_credentials(self):
@@ -147,3 +231,41 @@ class TestBuildSyntheticMcpRequest:
assert request.headers.get("x-nuid") == "nuid-1"
assert "x-company-key" not in request.headers
+
+ def test_drops_caller_host_so_the_logged_url_is_not_client_steerable(self):
+ """add_litellm_data_to_request records str(request.url) as proxy_server_request.url, and
+ Request.url is built from the host header, so forwarding it hands the caller that value."""
+ request = build_synthetic_mcp_request(
+ path="/mcp/tools/call",
+ raw_headers={"host": "evil.attacker.example", "x-nuid": "nuid-1"},
+ )
+
+ assert "evil.attacker.example" not in str(request.url)
+ assert "host" not in request.headers
+ assert request.headers.get("x-nuid") == "nuid-1"
+
+ def test_drops_headers_a_server_forwards_upstream(self):
+ with _configured_servers(_server_forwarding("x-github-token")):
+ request = build_synthetic_mcp_request(
+ path="/mcp/tools/call",
+ raw_headers={"x-github-token": "ghp_secret", "x-nuid": "nuid-1"},
+ )
+
+ assert "x-github-token" not in request.headers
+ assert request.headers.get("x-nuid") == "nuid-1"
+
+ def test_keeps_identity_header_so_end_user_attribution_survives(self):
+ """add_litellm_data_to_request reads user_header_name off this request to fill
+ end_user_id, so forwarding that header upstream must not remove it here."""
+ with patch.dict(
+ "litellm.proxy.proxy_server.general_settings",
+ {"user_header_name": "x-user-email"},
+ clear=False,
+ ):
+ with _configured_servers(_server_forwarding("x-user-email")):
+ request = build_synthetic_mcp_request(
+ path="/mcp/tools/call",
+ raw_headers={"x-user-email": "[email protected]"},
+ )
+
+ assert request.headers.get("x-user-email") == "[email protected]"
diff --git a/tests/test_litellm/responses/mcp/test_litellm_proxy_mcp_handler.py b/tests/test_litellm/responses/mcp/test_litellm_proxy_mcp_handler.py
index 4981caa10c3..87525273911 100644
--- a/tests/test_litellm/responses/mcp/test_litellm_proxy_mcp_handler.py
+++ b/tests/test_litellm/responses/mcp/test_litellm_proxy_mcp_handler.py
@@ -28,6 +28,7 @@ def _setup_mcp_call_environment(monkeypatch: pytest.MonkeyPatch) -> AsyncMock:
monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", proxy_module)
fake_manager = types.SimpleNamespace(
+ get_registry=MagicMock(return_value={}),
call_tool=AsyncMock(return_value=_DummyMCPResult()),
# Newer logging path calls this to enrich spend logs metadata
_get_mcp_server_from_tool_name=MagicMock(return_value=None),
@@ -373,6 +374,7 @@ async def test_execute_tool_calls_logs_failure_via_post_call_failure_hook(monkey
post_call_failure_hook = _setup_proxy_logging(monkeypatch)
fake_manager = types.SimpleNamespace(
+ get_registry=MagicMock(return_value={}),
call_tool=AsyncMock(side_effect=HTTPException(status_code=500, detail="boom"))
)
monkeypatch.setattr(
@@ -464,6 +466,7 @@ async def test_get_mcp_tools_from_manager_enables_list_tools_logging(monkeypatch
# Patch manager methods used by _get_mcp_tools_from_manager to avoid needing full UserAPIKeyAuth fields.
fake_manager = types.SimpleNamespace(
+ get_registry=MagicMock(return_value={}),
get_allowed_mcp_servers=AsyncMock(return_value=[]),
get_mcp_servers_from_ids=MagicMock(return_value=[]),
get_mcp_server_by_name=MagicMock(return_value=None),
@@ -516,6 +519,7 @@ async def test_get_mcp_tools_from_manager_forwards_request_tags(monkeypatch):
mock_get_tools,
)
fake_manager = types.SimpleNamespace(
+ get_registry=MagicMock(return_value={}),
get_allowed_mcp_servers=AsyncMock(return_value=[]),
get_mcp_servers_from_ids=MagicMock(return_value=[]),
get_mcp_server_by_name=MagicMock(return_value=None),
diff --git a/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.py b/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.py
index 24edf12fffe..aacd614abb9 100644
--- a/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.py
+++ b/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.py
@@ -69,6 +69,7 @@ def _mock_mcp_environment(monkeypatch: pytest.MonkeyPatch) -> AsyncMock:
"""Patch the MCP tool-call plumbing so _execute_tool_calls can run in tests."""
call_tool = AsyncMock(return_value=CallToolResult(content=[TextContent(type="text", text="ok")], isError=False))
fake_manager = types.SimpleNamespace(
+ get_registry=MagicMock(return_value={}),
call_tool=call_tool,
_get_mcp_server_from_tool_name=MagicMock(return_value=None),
get_mcp_server_by_name=MagicMock(return_value=None),