Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions litellm/proxy/_experimental/mcp_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@
get_server_prefix,
iter_known_server_prefixes,
)
from litellm.llms.custom_httpx.http_handler import (
get_async_httpx_client,
httpxSpecialProvider,
)
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.auth.ip_address_utils import IPAddressUtils
from litellm.proxy.litellm_pre_call_utils import (
Expand Down Expand Up @@ -2754,6 +2758,41 @@ async def _apply_toolset_scope(
)
return user_api_key_auth.model_copy(update={"object_permission": updated_op})

def _get_forwarded_auth_from_scope(scope: dict) -> Optional[str]:
"""Return the raw Authorization header value from the ASGI scope, or None."""
for key, value in scope.get("headers", []):
if key.lower() == b"authorization":
return value.decode("latin-1")
return None

async def _probe_upstream_auth(
url: str,
auth_header: str,
timeout: float = 5.0,
) -> tuple:
"""HEAD-probe the upstream URL to check whether the token is accepted.

Uses HEAD so the upstream receives no request body and allocates no
session or audit state. Returns (status_code, www_authenticate).
Fails-open with (200, None) on network errors so a transient hiccup
does not block valid requests.
"""
try:
client = get_async_httpx_client(
llm_provider=httpxSpecialProvider.MCP,
params={"timeout": timeout},
)
resp = await client.head(
url,
headers={"Authorization": auth_header},
)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
return resp.status_code, resp.headers.get("www-authenticate")
except Exception as exc:
verbose_logger.debug(
f"_probe_upstream_auth: probe to {url} failed ({exc}), allowing request through"
)
return 200, None
Comment thread
Sameerlite marked this conversation as resolved.
Resolved

async def handle_streamable_http_mcp(
scope: Scope, receive: Receive, send: Send
) -> None:
Expand Down Expand Up @@ -2812,6 +2851,50 @@ async def handle_streamable_http_mcp(
headers={"www-authenticate": authorization_uri},
)

# Pre-flight auth check for pass-through servers: probe upstream before
# the session begins so we can still return HTTP 401 (the MCP SDK sends
# 200 OK before calling handlers, making mid-stream status changes impossible).
forwarded_auth = _get_forwarded_auth_from_scope(scope)
if forwarded_auth and mcp_servers:
passthrough_servers = [
(
name,
global_mcp_server_manager.get_mcp_server_by_name(
Comment thread
veria-ai[bot] marked this conversation as resolved.
Resolved
name, client_ip=_client_ip
),
)
for name in mcp_servers
]
passthrough_servers = [
(name, srv)
for name, srv in passthrough_servers
if srv
and srv.extra_headers
and any(h.lower() == "authorization" for h in srv.extra_headers)
]
if passthrough_servers:
probe_results = await asyncio.gather(
*[
_probe_upstream_auth(srv.url or "", forwarded_auth)
for _, srv in passthrough_servers
]
)
request = StarletteRequest(scope)
base_url = get_request_base_url(request)
for (server_name, _), (probe_status, _) in zip(
passthrough_servers, probe_results
):
if probe_status in (401, 403):
authorization_uri = (
f"Bearer authorization_uri="
f"{base_url}/.well-known/oauth-authorization-server/{server_name}"
)
raise HTTPException(
status_code=401,
detail="Unauthorized",
headers={"WWW-Authenticate": authorization_uri},
)

# Strip any client-supplied x-mcp-toolset-id to prevent forgery.
scope["headers"] = [
(k, v)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3256,3 +3256,75 @@ async def capture_create_mcp_client(*args, **kwargs):
), "P2 API consistency issue: expected None for empty extra_headers, got: " + str(
captured_extra_headers
)


# ---------------------------------------------------------------------------
# Pre-flight upstream auth check tests
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_probe_upstream_auth_returns_upstream_status():
"""_probe_upstream_auth forwards the status code from the upstream server."""
from litellm.proxy._experimental.mcp_server.server import _probe_upstream_auth

mock_response = MagicMock()
mock_response.status_code = 401
mock_response.headers = {"www-authenticate": 'Bearer realm="test"'}

mock_client = AsyncMock()
mock_client.head = AsyncMock(return_value=mock_response)

with patch(
"litellm.proxy._experimental.mcp_server.server.get_async_httpx_client",
return_value=mock_client,
):
status, www_auth = await _probe_upstream_auth(
"http://upstream/mcp", "Bearer some-token"
)

assert status == 401
assert www_auth == 'Bearer realm="test"'


@pytest.mark.asyncio
async def test_probe_upstream_auth_fails_open_on_network_error():
"""_probe_upstream_auth returns (200, None) when the network call fails."""
from litellm.proxy._experimental.mcp_server.server import _probe_upstream_auth

mock_client = AsyncMock()
mock_client.head = AsyncMock(side_effect=Exception("connection refused"))

with patch(
"litellm.proxy._experimental.mcp_server.server.get_async_httpx_client",
return_value=mock_client,
):
status, www_auth = await _probe_upstream_auth(
"http://upstream/mcp", "Bearer some-token"
)

assert status == 200
assert www_auth is None


def test_get_forwarded_auth_from_scope_extracts_header():
"""_get_forwarded_auth_from_scope returns the Authorization value."""
from litellm.proxy._experimental.mcp_server.server import (
_get_forwarded_auth_from_scope,
)

scope = {
"headers": [
(b"content-type", b"application/json"),
(b"authorization", b"Bearer my-token"),
]
}
assert _get_forwarded_auth_from_scope(scope) == "Bearer my-token"


def test_get_forwarded_auth_from_scope_returns_none_when_missing():
from litellm.proxy._experimental.mcp_server.server import (
_get_forwarded_auth_from_scope,
)

assert _get_forwarded_auth_from_scope({"headers": []}) is None
Loading