Skip to content
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
ceeb90a
feat(ui): expose true_passthrough and oauth_delegate auth types with …
tin-berri Jul 8, 2026
22ab518
feat(ui): browser-only Authorize & Fetch for the client-forwarded tok…
tin-berri Jul 8, 2026
367aa90
fix(ui): wire the tool playground and gateway authorize flow for the …
tin-berri Jul 8, 2026
74a15c2
fix(mcp): run upstream OAuth endpoint discovery for config-defined cl…
tin-berri Jul 8, 2026
98818df
fix(mcp): recognize per-server auth header at connect and stop persis…
tin-berri Jul 8, 2026
1693761
feat(mcp): record auth_mode and upstream resource on MCP tool-call logs
tin-berri Jul 8, 2026
7c52cde
fix(mcp): redact upstream URL in tool-call logs and plug fan-out Auth…
tin-berri Jul 8, 2026
b62b30b
fix(ui): edit-form browser-authorize payload uses the selected auth_type
tin-berri Jul 8, 2026
ee5a065
refactor(ui): extract isClientForwardedTokenMode helper for the pass-…
tin-berri Jul 9, 2026
a199bf9
refactor(mcp): share one constant for the upstream-OAuth discovery au…
tin-berri Jul 9, 2026
e29e24e
fix(ui): keep the browser-authorized token out of form.credentials fo…
tin-berri Jul 9, 2026
a3f1873
fix(ui): extract inline object args in the MCP forms
tin-berri Jul 9, 2026
bff2c95
fix(ui): key the edit form's browser-held token handling off the effe…
tin-berri Jul 9, 2026
43726f2
refactor(ui): useTestMCPConnection uses the shared isClientForwardedT…
tin-berri Jul 9, 2026
65d0dcf
fix(mcp): never forward an Authorization header that satisfied admiss…
tin-berri Jul 9, 2026
d0f1c38
fix(mcp): log only the origin of the upstream MCP url in tool-call me…
tin-berri Jul 9, 2026
d4e02ac
refactor(mcp): share _UPSTREAM_OAUTH_DISCOVERY_AUTH_TYPES in the rela…
tin-berri Jul 9, 2026
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
14 changes: 10 additions & 4 deletions litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,8 +465,15 @@ async def _store_per_user_token_server_side(


def _raise_if_not_oauth2(mcp_server: MCPServer) -> None:
"""Reject a non-oauth2 server from the gateway's OAuth authorize/token/register flow."""
if mcp_server.auth_type == MCPAuth.oauth2:
"""Reject a server without upstream OAuth from the gateway's authorize/token/register flow.

The client-forwarded token modes (``true_passthrough`` / ``oauth_delegate``) are allowed
through: the caller owns the upstream token, and this relayed flow is how a browser obtains
one against the upstream IdP (the admin UI's browser-only Authorize uses it). The minted
token is upstream-audienced and held by the caller; the gateway persists nothing for these
modes (DCR persistence is opt-in and never enabled on this path).
"""
if mcp_server.auth_type in (MCPAuth.oauth2, MCPAuth.true_passthrough, MCPAuth.oauth_delegate):
return
raise HTTPException(
status_code=400,
Expand Down Expand Up @@ -515,8 +522,7 @@ async def authorize_with_server(
response_type: Optional[str] = None,
scope: Optional[str] = None,
):
if mcp_server.auth_type != "oauth2":
raise HTTPException(status_code=400, detail="MCP server is not OAuth2")
_raise_if_not_oauth2(mcp_server)
if mcp_server.authorization_url is None:
raise HTTPException(status_code=400, detail="MCP server authorization url is not set")

Expand Down
18 changes: 14 additions & 4 deletions litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,16 @@ def validate_tool_name(name: str) -> _ToolNameValidationResult: # type: ignore[
_USER_ENV_VARS_CACHE_TTL = 60 # seconds
_USER_ENV_VARS_CACHE_MAX_SIZE = 4096 # cap to prevent unbounded growth

# Auth types whose upstream OAuth endpoints (protected-resource + authorization-server metadata) the
# gateway discovers from the upstream itself: interactive oauth2 and the two client-forwarded modes.
# OBO/M2M endpoint discovery is decided separately via _obo_needs_endpoint_discovery. Shared by the
# config-YAML and DB server loaders so the two paths cannot drift on which modes trigger discovery.
_UPSTREAM_OAUTH_DISCOVERY_AUTH_TYPES: tuple[MCPAuth, ...] = (
MCPAuth.oauth2,
MCPAuth.true_passthrough,
MCPAuth.oauth_delegate,
)


def invalidate_user_env_vars_cache(user_id: str, server_id: str) -> None:
"""Drop a cached entry after the user stores or clears their env var values
Expand Down Expand Up @@ -984,7 +994,7 @@ async def load_servers_from_config(

auth_type = server_config.get("auth_type", None)
if server_url and (
auth_type == MCPAuth.oauth2
auth_type in _UPSTREAM_OAUTH_DISCOVERY_AUTH_TYPES
or self._obo_needs_endpoint_discovery(
auth_type,
server_config.get("token_exchange_endpoint"),
Expand All @@ -993,7 +1003,7 @@ async def load_servers_from_config(
):
mcp_oauth_metadata = await self._descovery_metadata(
server_url=server_url,
allow_origin_fallback=auth_type == MCPAuth.oauth2,
allow_origin_fallback=auth_type in _UPSTREAM_OAUTH_DISCOVERY_AUTH_TYPES,
)
else:
mcp_oauth_metadata = None
Expand Down Expand Up @@ -1385,7 +1395,7 @@ async def build_mcp_server_from_table(
auth_type = cast(MCPAuthType, mcp_server.auth_type)
server_url = mcp_server.url
needs_discovery = bool(server_url) and (
(auth_type == MCPAuth.oauth2 and not mcp_server.authorization_url)
(auth_type in _UPSTREAM_OAUTH_DISCOVERY_AUTH_TYPES and not mcp_server.authorization_url)
or self._obo_needs_endpoint_discovery(
auth_type,
mcp_server.token_exchange_endpoint
Expand All @@ -1396,7 +1406,7 @@ async def build_mcp_server_from_table(
mcp_oauth_metadata = (
await self._descovery_metadata(
server_url=server_url, # type: ignore[arg-type]
allow_origin_fallback=auth_type == MCPAuth.oauth2,
allow_origin_fallback=auth_type in _UPSTREAM_OAUTH_DISCOVERY_AUTH_TYPES,
)
if needs_discovery
else None
Expand Down
9 changes: 8 additions & 1 deletion litellm/proxy/_experimental/mcp_server/rest_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -1321,8 +1321,15 @@ async def test_tools_list(
if isinstance(credentials, dict):
mcp_auth_header = credentials.get("auth_value")

# Authorization doubles as the admission fallback (LITELLM_API_KEY_HEADER_NAME_SECONDARY):
# when the primary x-litellm-api-key header is absent, the Authorization value is the
# caller's LiteLLM key, not an upstream token, and must never be forwarded upstream.
oauth2_headers: Optional[Dict[str, str]] = None
if new_mcp_server_request.auth_type == MCPAuth.oauth2:
if new_mcp_server_request.auth_type in {
MCPAuth.oauth2,
MCPAuth.true_passthrough,
MCPAuth.oauth_delegate,
} and headers.get(MCPRequestHandler.LITELLM_API_KEY_HEADER_NAME_PRIMARY):
oauth2_headers = MCPRequestHandler._get_oauth2_headers_from_headers(headers)

async def _list_tools_operation(client):
Expand Down
23 changes: 23 additions & 0 deletions litellm/proxy/_experimental/mcp_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
Union,
cast,
)
from urllib.parse import urlsplit, urlunsplit

import httpx
from fastapi import FastAPI, HTTPException
Expand Down Expand Up @@ -105,6 +106,26 @@
_MCP_ROUTING_PEEK_MAX_BYTES = 4096


def _redact_mcp_resource_url(url: Optional[str]) -> Optional[str]:
"""Reduce an MCP server URL to its bare resource identifier for logging.

Keeps scheme, host, and path; drops userinfo (``user:pass@``), the query string,
and the fragment, so an upstream URL carrying an embedded token, userinfo, or a
secret query parameter never reaches spend-log metadata or logging callbacks.
Returns None when the URL has no host to identify (nothing safe to log).
"""
if not isinstance(url, str) or not url:
return None
try:
parts = urlsplit(url)
except ValueError:
return None
if not parts.hostname:
return None
netloc = f"{parts.hostname}:{parts.port}" if parts.port else parts.hostname
return urlunsplit((parts.scheme, netloc, parts.path, "", "")) or None
Comment thread
veria-ai[bot] marked this conversation as resolved.
Resolved


def _invalidate_byok_cred_cache(user_id: str, server_id: str) -> None:
"""Remove a (user_id, server_id) entry from the BYOK credential cache.

Expand Down Expand Up @@ -3064,6 +3085,8 @@ def _get_standard_logging_mcp_tool_call(
mcp_server_logo_url=mcp_info.get("logo_url"),
namespaced_tool_name=namespaced_tool_name,
mcp_session_id=session_id,
mcp_auth_mode=mcp_server.auth_type,
mcp_server_resource=_redact_mcp_resource_url(mcp_server.url),
)
else:
return StandardLoggingMCPToolCall(
Expand Down
16 changes: 16 additions & 0 deletions litellm/types/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2523,6 +2523,22 @@ class StandardLoggingMCPToolCall(TypedDict, total=False):
the client is driving a stateful session. Absent for stateless calls.
"""

mcp_auth_mode: Optional[str]
"""
The server's auth_type for this call (e.g. `true_passthrough`, `oauth_delegate`,
`oauth2`). For the client-forwarded token modes this records that the caller's own
upstream token was relayed, so an audit can attribute a relayed request to its mode
without logging any credential.
"""

mcp_server_resource: Optional[str]
"""
The upstream MCP server resource identifier (scheme + host + path) the tool call was
forwarded to. Redacted for logging: userinfo, query string, and fragment are stripped so an
upstream URL carrying an embedded token or secret query parameter never reaches log metadata.
Records which upstream received a relayed request; never a credential.
"""


class StandardLoggingVectorStoreRequest(TypedDict, total=False):
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import pytest
from fastapi import HTTPException

from litellm.types.mcp import MCPAuth


# Fixture to mock IP address check for all MCP tests
# This prevents tests from failing due to IP-based access control
Expand Down Expand Up @@ -119,6 +121,61 @@ async def test_authorize_endpoint_includes_response_type():
assert "scope=read+write" in response.headers["location"]


@pytest.mark.asyncio
@pytest.mark.parametrize("auth_type_value", ["true_passthrough", "oauth_delegate"])
async def test_authorize_endpoint_allows_client_forwarded_modes(auth_type_value):
"""The browser-only Authorize relays the gateway authorize flow for the client-forwarded
token modes; the oauth2-only gate must let them through and redirect to the upstream IdP."""
try:
from fastapi import Request

from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (
authorize,
)
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
global_mcp_server_manager,
)
from litellm.proxy._types import MCPTransport
from litellm.types.mcp import MCPAuth
from litellm.types.mcp_server.mcp_server_manager import MCPServer
except ImportError:
pytest.skip("MCP discoverable endpoints not available")

global_mcp_server_manager.registry.clear()

server = MCPServer(
server_id="test_cf_server",
name="test_cf",
server_name="test_cf",
alias="test_cf",
transport=MCPTransport.http,
auth_type=MCPAuth(auth_type_value),
# Discovery stamps these onto the in-memory registry entry at build time.
authorization_url="https://provider.com/oauth/authorize",
token_url="https://provider.com/oauth/token",
)
global_mcp_server_manager.registry[server.server_id] = server

mock_request = MagicMock(spec=Request)
mock_request.base_url = "https://litellm.example.com/"
mock_request.headers = {}

with patch("litellm.proxy._experimental.mcp_server.discoverable_endpoints.encrypt_value_helper") as mock_encrypt:
mock_encrypt.return_value = "mocked_encrypted_state"

response = await authorize(
request=mock_request,
client_id="dcr_client_id",
mcp_server_name="test_cf",
redirect_uri="http://127.0.0.1:60108/callback",
state="test_state",
)

assert response.status_code == 307
assert "https://provider.com/oauth/authorize" in response.headers["location"]
assert "client_id=dcr_client_id" in response.headers["location"]


@pytest.mark.asyncio
async def test_authorize_endpoint_preserves_existing_query_params():
"""Test that authorize endpoint merges OAuth params with existing query params in authorization_url"""
Expand Down Expand Up @@ -3348,6 +3405,83 @@ async def test_token_exchange_passes_through_upstream_expires_in():
assert body["expires_in"] == 43200


async def _exchange_persistence_attempted_for_auth_type(auth_type) -> bool:
"""Run exchange_token_with_server for a server of ``auth_type`` and report whether it attempted
to persist the exchanged token server-side. The client-forwarded token modes must not persist:
their contract is that the upstream token stays browser-held, minted/stored/refreshed nowhere."""
from fastapi import Request

from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (
exchange_token_with_server,
)
from litellm.proxy._types import MCPTransport
from litellm.types.mcp_server.mcp_server_manager import MCPServer

server = MCPServer(
server_id="t",
name="t",
server_name="t",
alias="t",
transport=MCPTransport.http,
auth_type=auth_type,
client_id="cid",
client_secret="cs",
authorization_url="https://provider.com/oauth/authorize",
token_url="https://provider.com/oauth/token",
)
mock_request = MagicMock(spec=Request)
mock_request.base_url = "https://litellm.example.com/"
mock_request.headers = {}

fake_http_response = MagicMock()
fake_http_response.json.return_value = {"access_token": "tok", "refresh_token": "r", "token_type": "Bearer"}
fake_http_response.raise_for_status = MagicMock()
fake_http_client = MagicMock()
fake_http_client.post = AsyncMock(return_value=fake_http_response)

with (
patch(
"litellm.proxy._experimental.mcp_server.discoverable_endpoints.get_async_httpx_client",
return_value=fake_http_client,
),
patch(
"litellm.proxy._experimental.mcp_server.discoverable_endpoints._extract_user_id_from_request",
new_callable=AsyncMock,
return_value="admin-user",
),
patch(
"litellm.proxy._experimental.mcp_server.discoverable_endpoints._store_per_user_token_server_side",
new_callable=AsyncMock,
) as mock_store,
):
await exchange_token_with_server(
request=mock_request,
mcp_server=server,
grant_type="authorization_code",
code="c",
redirect_uri="http://127.0.0.1:3000/cb",
client_id="cid",
client_secret=None,
code_verifier=None,
)
return mock_store.await_count > 0


@pytest.mark.asyncio
@pytest.mark.parametrize("auth_type", [MCPAuth.true_passthrough, MCPAuth.oauth_delegate])
async def test_token_exchange_does_not_persist_for_client_forwarded_modes(auth_type):
"""The browser-only Authorize for true_passthrough / oauth_delegate must not write the upstream
token to the DB: these modes forward a browser-held token and persist nothing server-side."""
assert await _exchange_persistence_attempted_for_auth_type(auth_type) is False


@pytest.mark.asyncio
async def test_token_exchange_persists_for_oauth2():
"""Guard the test's own discriminator: a genuine oauth2 (authorization_code) server DOES persist,
so the passthrough no-persist assertion above is meaningful and not vacuously true."""
assert await _exchange_persistence_attempted_for_auth_type(MCPAuth.oauth2) is True


# -------------------------------------------------------------------
# OBO (token_exchange) Protected Resource Metadata: discovery must name the
# JWT-auth issuer the client SSOs with, not the gateway.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6854,3 +6854,25 @@ async def capture_execute(*args, **kwargs):
resolved = captured_servers["allowed"]
assert resolved and resolved[0].oauth2_flow == "client_credentials"
assert resolved[0].has_client_credentials is True


@pytest.mark.parametrize(
"url, expected",
[
# userinfo + secret query param must both be stripped from the logged resource
("https://user:s3cr3t@mcp.example.com/mcp?token=abcd1234&x=1", "https://mcp.example.com/mcp"),
("https://mcp.example.com/mcp#frag", "https://mcp.example.com/mcp"),
("https://host:8443/a/b?q=1", "https://host:8443/a/b"),
("https://mcp.notion.com/mcp", "https://mcp.notion.com/mcp"),
(None, None),
("", None),
("not a url", None),
],
)
def test_redact_mcp_resource_url_strips_credentials(url, expected):
"""The MCP tool-call log records the upstream resource, so the URL must be redacted to
scheme+host+path: userinfo, query string, and fragment (which can carry embedded tokens or
secret parameters) must never reach spend-log metadata or logging callbacks."""
from litellm.proxy._experimental.mcp_server.server import _redact_mcp_resource_url

assert _redact_mcp_resource_url(url) == expected
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,39 @@ async def test_entra_obo_profile_survives_db_credentials_round_trip(self):
assert spec is not None and isinstance(spec.config, TokenExchangeConfig)
assert spec.config.profile == "entra_obo"

@pytest.mark.asyncio
@pytest.mark.parametrize("auth_type", [MCPAuth.true_passthrough, MCPAuth.oauth_delegate])
async def test_build_from_table_discovers_upstream_oauth_for_client_forwarded_modes(self, auth_type):
"""The gateway's relayed authorize flow (used by the browser-only Authorize) needs the
upstream's authorization_url on the registry entry, and these rows never persist one, so
the DB build must discover it the same way oauth2 rows do."""
from types import SimpleNamespace

manager = MCPServerManager()
row = LiteLLM_MCPServerTable(
server_id="cf-db-1",
alias="cf_db",
description="client-forwarded from db",
url="https://up.example.com/mcp",
transport=MCPTransport.http,
auth_type=auth_type,
created_at=datetime.now(),
updated_at=datetime.now(),
)

metadata = SimpleNamespace(
authorization_url="https://idp.example.com/authorize",
token_url="https://idp.example.com/token",
registration_url="https://idp.example.com/register",
scopes=None,
)
with patch.object(manager, "_descovery_metadata", new=AsyncMock(return_value=metadata)) as mock_discovery:
built = await manager.build_mcp_server_from_table(row, credentials_are_encrypted=False)

mock_discovery.assert_awaited_once()
assert built.authorization_url == "https://idp.example.com/authorize"
assert built.token_url == "https://idp.example.com/token"

async def _capture_subject_token(self, call) -> Optional[str]:
"""Run a manager method (via ``call(manager)``) and return the subject_token it threaded
into ``_create_mcp_client``."""
Expand Down
Loading
Loading