Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
30 changes: 30 additions & 0 deletions litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
from litellm.proxy._experimental.mcp_server.outbound_credentials import (
Error,
Ok,
StaticHeaderAuth,
UpstreamCredentialProvider,
)
from litellm.proxy._experimental.mcp_server.outbound_credentials.adapter import (
Expand Down Expand Up @@ -3771,6 +3772,35 @@ async def has_user_oauth_token(self, server: MCPServer, user_api_key_auth: Optio
return False
return await self._cred_provider.has_user_token(to_subject(user_api_key_auth, None), spec)

async def resolve_user_oauth_authorization_header(
self, server: MCPServer, user_api_key_auth: Optional[UserAPIKeyAuth]
) -> Optional[str]:
"""The stored per-user ``Authorization`` value the egress would send for this server, or None.

The transport-edge preflight probe (``_check_oauth2_upstream_auth``) tests this exact
credential against the upstream. Routed through the v2 resolver for servers it owns
(``authorization_code``) so the probe reads the same store, cache, and refresh chain as
the call path; a server the resolver does not own (delegate/BYOK, a None spec) falls back
to the v1 lookup. A missing token maps to None, never a raise: the missing-token challenge
belongs to the preemptive existence check, not the probe.
"""
spec = to_server_spec(server)
if spec is None or not isinstance(spec.config, AuthorizationCodeConfig):
from litellm.proxy._experimental.mcp_server.server import ( # noqa: PLC0415
_get_user_oauth_extra_headers_from_db,
)

stored_headers = await _get_user_oauth_extra_headers_from_db(
server=server,
user_api_key_auth=user_api_key_auth,
)
return (stored_headers or {}).get("Authorization")
match await self._cred_provider.resolve_credentials(to_subject(user_api_key_auth, None), spec):
case Ok(StaticHeaderAuth() as auth):
return auth.header_value()
case _:
return None

async def _resolve_oauth2_headers_for_tool_call(
self,
mcp_server: MCPServer,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ def __init__(self, header_value: str, header_name: str = "Authorization") -> Non
self.header_name = header_name
self._header_value = SecretStr(header_value)

def header_value(self) -> str:
"""The unwrapped credential, for a caller that must send it outside an ``httpx.Auth``
flow (the transport-edge preflight probe builds its request headers by hand)."""
return self._header_value.get_secret_value()

def auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]:
request.headers[self.header_name] = self._header_value.get_secret_value()
yield request
177 changes: 143 additions & 34 deletions litellm/proxy/_experimental/mcp_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3404,6 +3404,14 @@ def _get_passthrough_www_authenticate(
params.append(f'resource_metadata="{resource_metadata_url}"')
return "Bearer " + ", ".join(params)

def _get_gateway_oauth2_challenge(scope: Scope, server_name: str) -> str:
base_url = get_request_base_url(StarletteRequest(scope))
path = scope.get("_original_path") or scope.get("path", "") or ""
# Pick the well-known AS-metadata form that matches the inbound route
# so strict RFC 9728 §3.2 clients can resolve it correctly.
well_known_path = f"mcp/{server_name}" if path.startswith(f"/mcp/{server_name}") else server_name
return f'Bearer authorization_uri="{base_url}/.well-known/oauth-authorization-server/{well_known_path}"'

async def _raise_preemptive_401_for_unauthenticated_servers(
scope: Scope,
mcp_servers: Optional[List[str]],
Expand Down Expand Up @@ -3456,22 +3464,10 @@ async def _raise_preemptive_401_for_unauthenticated_servers(
if await global_mcp_server_manager.has_user_oauth_token(server, user_api_key_auth):
continue

request = StarletteRequest(scope)
base_url = get_request_base_url(request)
_path = scope.get("_original_path") or scope.get("path", "") or ""

# Pick the well-known AS-metadata form that matches the inbound route
# so strict RFC 9728 §3.2 clients can resolve it correctly.
if _path.startswith(f"/mcp/{server_name}"):
_as_url = f"{base_url}/.well-known/oauth-authorization-server/mcp/{server_name}"
else:
_as_url = f"{base_url}/.well-known/oauth-authorization-server/{server_name}"
authorization_uri = f'Bearer authorization_uri="{_as_url}"'

raise HTTPException(
status_code=401,
detail="Unauthorized",
headers={"www-authenticate": authorization_uri},
headers={"www-authenticate": _get_gateway_oauth2_challenge(scope, server_name)},
)

# token_exchange (OBO): the caller supplied no subject token. Challenge at connect
Expand Down Expand Up @@ -3604,15 +3600,14 @@ async def _probe_upstream_auth(

async def _check_passthrough_upstream_auth(
scope: Scope,
user_api_key_auth: Optional[UserAPIKeyAuth],
mcp_servers: Optional[List[str]],
client_ip: Optional[str],
allowed_servers: list[MCPServer],
) -> None:
"""Probe pass-through upstream servers in parallel before the MCP session starts.

Only servers the caller's key is already authorized to reach are probed —
the list is derived from _get_allowed_mcp_servers so that a user cannot
trigger an upstream probe against a server their key is not permitted for.
``allowed_servers`` must be the caller's authorized server set (from
_get_allowed_mcp_servers), not the raw user-supplied names, so that a
user cannot trigger an upstream probe against a server their key is not
permitted for.

The MCP SDK commits HTTP 200 headers before invoking handlers, so a 401
can only be returned before that point. This function raises HTTPException(401)
Expand All @@ -3623,13 +3618,6 @@ async def _check_passthrough_upstream_auth(
if not forwarded_auth:
return

# Use the authorized server set, not the raw user-supplied names, so that
# a caller cannot force a probe to a server their key is not allowed to use.
allowed_servers = await _get_allowed_mcp_servers(
user_api_key_auth=user_api_key_auth,
mcp_servers=mcp_servers,
client_ip=client_ip,
)
passthrough_servers = [
srv
for srv in allowed_servers
Expand Down Expand Up @@ -3673,6 +3661,89 @@ async def _check_passthrough_upstream_auth(
detail="Forbidden",
)

async def _check_oauth2_upstream_auth(
scope: Scope,
user_api_key_auth: Optional[UserAPIKeyAuth],
oauth2_headers: Optional[dict[str, str]],
allowed_servers: list[MCPServer],
allowed_server_ids: Optional[set[str]] = None,
) -> None:
"""Probe gateway-managed per-user OAuth2 upstreams with the token the
request would actually use so a stale or revoked token surfaces as an
HTTP 401 challenge instead of degrading into an empty tool list.

Best-effort: only a genuine upstream 401 short-circuits the request;
non-401 responses and network errors fall through to the MCP session
manager. M2M (client_credentials) servers are skipped via
``needs_user_oauth_token`` so the proxy key is never replayed upstream,
and ``allowed_servers`` must be the caller's authorized server set
(from _get_allowed_mcp_servers) so only servers the caller's key is
authorized to reach are probed.

The stored per-user token is resolved the way the call path resolves
it (``resolve_user_oauth_authorization_header``: the v2 resolver for
servers it owns, the v1 store otherwise) and takes precedence over the
caller's ``Authorization`` header, so a stale client token (e.g. an
editor's cached bearer) cannot trigger a spurious 401 for a request
that would have used the fresh stored token.
"""
candidate_servers = tuple(
server
for server in allowed_servers
if server.needs_user_oauth_token
and server.url
and (allowed_server_ids is None or server.server_id in allowed_server_ids)
)
if not candidate_servers:
return

async def _probe_oauth2_server(
server: MCPServer,
) -> tuple[MCPServer, int, str | None] | None:
stored_auth = await global_mcp_server_manager.resolve_user_oauth_authorization_header(
server=server,
user_api_key_auth=user_api_key_auth,
)
auth_header = stored_auth or (oauth2_headers or {}).get("Authorization")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

High: Proxy API key forwarded to OAuth upstream

When clients authenticate normally through Authorization, process_mcp_request treats this value as their LiteLLM API key and also places it in oauth2_headers. If the resolver returns no stored upstream token, this fallback sends that proxy credential to server.url, allowing the upstream server to capture and reuse it. Keep the proxy admission credential separate from upstream OAuth credentials, and only use a caller-provided bearer here when the request authenticated through a distinct x-litellm-api-key header or the server explicitly delegates authentication upstream.

if not auth_header:
return None
probe_status, upstream_www_authenticate = await _probe_upstream_auth(server.url or "", auth_header)
return server, probe_status, upstream_www_authenticate

probe_results = await asyncio.gather(*(_probe_oauth2_server(server) for server in candidate_servers))
for result in probe_results:
if result is None:
continue
server, probe_status, upstream_www_authenticate = result
if probe_status == 401:
if upstream_www_authenticate:
www_authenticate = upstream_www_authenticate
elif getattr(server, "delegate_auth_to_upstream", False) is True:
# Delegate-auth servers run upstream PKCE: point the client
# at the proxied resource_metadata (RFC 9728) so it
# re-authorizes against the upstream IdP, not the gateway
# authorization_uri which would authorize against LiteLLM.
www_authenticate = _get_passthrough_www_authenticate(
scope=scope,
server_name=server.name,
invalid_token=True,
)
else:
www_authenticate = _get_gateway_oauth2_challenge(scope, server.name)
raise HTTPException(
status_code=401,
detail="Unauthorized",
headers={"www-authenticate": www_authenticate},
)
if probe_status == 403:
# Token is valid but the caller lacks permission — do not hint
# at re-authorization (RFC 9110: a fresh token with the same
# scopes would just hit 403 again and loop indefinitely).
raise HTTPException(
status_code=403,
detail="Forbidden",
)

async def handle_streamable_http_mcp(scope: Scope, receive: Receive, send: Send) -> None:
"""Handle MCP requests through StreamableHTTP."""
try:
Expand Down Expand Up @@ -3722,10 +3793,28 @@ async def handle_streamable_http_mcp(scope: Scope, receive: Receive, send: Send)
allowed_server_ids=toolset_allowed_server_ids,
)

# Pre-flight auth check for pass-through servers. Must run after
# toolset scoping so the probe list is derived from the fully-authorized
# server set, not the raw user-supplied names.
await _check_passthrough_upstream_auth(scope, user_api_key_auth, mcp_servers, _client_ip)
# Pre-flight auth checks below share one authorized-server lookup.
# Must run after toolset scoping so the probe list is derived from
# the fully-authorized server set, not the raw user-supplied names.
preflight_allowed_servers = await _get_allowed_mcp_servers(
user_api_key_auth=user_api_key_auth,
mcp_servers=mcp_servers,
client_ip=_client_ip,
)

# Pre-flight auth check for pass-through servers.
await _check_passthrough_upstream_auth(scope, preflight_allowed_servers)

# Pre-flight auth check for gateway-managed per-user OAuth2 servers so
# a present-but-stale token surfaces the upstream 401 challenge instead
# of degrading into an empty tool list.
await _check_oauth2_upstream_auth(
scope=scope,
user_api_key_auth=user_api_key_auth,
oauth2_headers=oauth2_headers,
allowed_servers=preflight_allowed_servers,
allowed_server_ids=toolset_allowed_server_ids,
)

Comment thread
mateo-berri marked this conversation as resolved.
Resolved
# Inject masked debug headers when client sends x-litellm-mcp-debug: true
_debug_headers = MCPDebug.maybe_build_debug_headers(
Expand Down Expand Up @@ -4043,13 +4132,33 @@ async def handle_sse_mcp(scope: Scope, receive: Receive, send: Send) -> None:
allowed_server_ids=toolset_allowed_server_ids,
)

# Pre-flight auth checks below share one authorized-server lookup.
# Must run after toolset scoping so the probe list is derived from
# the fully-authorized server set, not the raw user-supplied names.
preflight_allowed_servers = await _get_allowed_mcp_servers(
user_api_key_auth=user_api_key_auth,
mcp_servers=mcp_servers,
client_ip=_sse_client_ip,
)

# Pre-flight auth check for pass-through servers: surface upstream
# 401/403 as a proper challenge before the SSE session commits 200
# headers, so clients can refresh their OAuth token instead of
# being stuck with a silently empty tool list. Must run after
# toolset scoping so the probe list is derived from the fully-
# authorized server set, not the raw user-supplied names.
await _check_passthrough_upstream_auth(scope, user_api_key_auth, mcp_servers, _sse_client_ip)
# being stuck with a silently empty tool list.
await _check_passthrough_upstream_auth(scope, preflight_allowed_servers)

# Pre-flight auth check for gateway-managed per-user OAuth2 servers
# so a present-but-stale stored token surfaces the upstream 401
# challenge instead of degrading into an empty tool list on the
# /sse transport.
await _check_oauth2_upstream_auth(
scope=scope,
user_api_key_auth=user_api_key_auth,
oauth2_headers=oauth2_headers,
allowed_servers=preflight_allowed_servers,
allowed_server_ids=toolset_allowed_server_ids,
)

set_auth_context(
user_api_key_auth=user_api_key_auth,
mcp_auth_header=mcp_auth_header,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,9 @@ def test_static_header_auth_masks_credential_from_introspection():
auth = StaticHeaderAuth("Bearer super-secret-token")
assert "super-secret-token" not in repr(auth)
assert "super-secret-token" not in str(vars(auth))


def test_static_header_auth_header_value_unwraps_credential():
auth = StaticHeaderAuth("Bearer probe-token")
assert auth.header_value() == "Bearer probe-token"
assert "probe-token" not in repr(auth)
Loading
Loading