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-oauth): PROXY_BASE_URL escape hatch + diagnostic logging for {"detail":"invalid_request"} (#28086)

Mateo Wang1b0ae3af8338
diff --git a/litellm/proxy/_experimental/mcp_server/oauth_utils.py b/litellm/proxy/_experimental/mcp_server/oauth_utils.py
index e6691329709..8541a691e88 100644
--- a/litellm/proxy/_experimental/mcp_server/oauth_utils.py
+++ b/litellm/proxy/_experimental/mcp_server/oauth_utils.py
@@ -30,23 +30,43 @@ _DEFAULT_PORTS = {"http": 80, "https": 443}
_TRUSTED_REDIRECT_ORIGINS_ENV = "MCP_TRUSTED_REDIRECT_ORIGINS"
+_warned_invalid_proxy_base_url: Optional[str] = None
+
+
+def _resolve_proxy_base_url_env() -> Optional[str]:
+ global _warned_invalid_proxy_base_url
+ configured = os.environ.get("PROXY_BASE_URL", "").strip()
+ if not configured:
+ return None
+ parsed = urlparse(configured)
+ if parsed.scheme in ("http", "https") and parsed.netloc:
+ normalized = urlunparse((parsed.scheme, parsed.netloc, parsed.path, "", "", ""))
+ return normalized.rstrip("/")
+ if _warned_invalid_proxy_base_url != configured:
+ verbose_logger.warning(
+ "PROXY_BASE_URL=%r is not a valid http(s) URL (missing scheme "
+ "or host) and will be ignored for MCP OAuth origin resolution. "
+ "Set it to a full URL like https://litellm.example.com.",
+ configured,
+ )
+ _warned_invalid_proxy_base_url = configured
+ return None
+
+
def get_request_base_url(request: Request) -> str:
"""
Get the base URL for the request, considering X-Forwarded-* headers.
- X-Forwarded-Proto / X-Forwarded-Host / X-Forwarded-Port are only honoured
- when the request comes from a configured trusted proxy
- (``use_x_forwarded_for`` enabled AND caller in ``mcp_trusted_proxy_ranges``).
- Otherwise the request's literal ``base_url`` is returned, so an
- untrusted caller cannot poison OAuth-discovery / redirect_uri values
- by injecting headers.
-
- Args:
- request: FastAPI Request object
-
- Returns:
- The reconstructed base URL (e.g., "https://proxy.example.com")
+ Resolution order: ``PROXY_BASE_URL`` env var, then X-Forwarded-* when
+ the caller is a trusted proxy (``use_x_forwarded_for`` enabled AND
+ caller in ``mcp_trusted_proxy_ranges``), otherwise the request's
+ literal ``base_url``. Untrusted callers cannot poison OAuth-discovery
+ / redirect_uri values by injecting headers.
"""
+ configured = _resolve_proxy_base_url_env()
+ if configured:
+ return configured
+
base_url = str(request.base_url).rstrip("/")
parsed = urlparse(base_url)
@@ -284,4 +304,22 @@ def validate_trusted_redirect_uri(request: Request, redirect_uri: str) -> None:
if _matches_trusted_origin_entry(redirect_netloc, entry):
return
+ verbose_logger.warning(
+ "MCP OAuth: rejecting redirect_uri %r as invalid_request. "
+ "Computed proxy base=%r (PROXY_BASE_URL=%r). "
+ "Inbound headers: X-Forwarded-Proto=%r X-Forwarded-Host=%r "
+ "X-Forwarded-Port=%r Host=%r. "
+ "Trusted-redirect-origins env=%r. "
+ "If this should be accepted, either align ingress X-Forwarded-* "
+ "with the browser URL, set PROXY_BASE_URL to your public origin, "
+ "or add the redirect_uri host to MCP_TRUSTED_REDIRECT_ORIGINS.",
+ redirect_uri,
+ proxy_base,
+ os.environ.get("PROXY_BASE_URL"),
+ request.headers.get("X-Forwarded-Proto"),
+ request.headers.get("X-Forwarded-Host"),
+ request.headers.get("X-Forwarded-Port"),
+ request.headers.get("Host"),
+ os.environ.get(_TRUSTED_REDIRECT_ORIGINS_ENV),
+ )
raise HTTPException(status_code=400, detail="invalid_request")
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py
index 581324d47d2..b06cc7f0f12 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py
@@ -1278,6 +1278,188 @@ def test_xff_misconfig_warning_emitted_once(caplog):
), f"expected exactly one warning, got {len(matching)}: {[r.getMessage() for r in matching]}"
+def test_get_request_base_url_honors_proxy_base_url_env(monkeypatch):
+ try:
+ from fastapi import Request
+
+ from litellm.proxy._experimental.mcp_server.oauth_utils import (
+ get_request_base_url,
+ )
+ except ImportError:
+ pytest.skip("MCP discoverable endpoints not available")
+
+ mock_request = MagicMock(spec=Request)
+ mock_request.base_url = "http://litellm-internal:4000/"
+ mock_request.client = MagicMock()
+ mock_request.client.host = "10.0.0.7"
+ headers = {
+ "X-Forwarded-Proto": "https",
+ "X-Forwarded-Host": "litellm-internal:4000",
+ "X-Forwarded-Port": "9999",
+ }
+ mock_request.headers.get = lambda name, default=None: headers.get(name, default)
+
+ monkeypatch.setenv("PROXY_BASE_URL", "https://litellm.example.com")
+ assert get_request_base_url(mock_request) == "https://litellm.example.com"
+
+ monkeypatch.setenv("PROXY_BASE_URL", "https://litellm.example.com/")
+ assert get_request_base_url(mock_request) == "https://litellm.example.com"
+
+
+def test_validate_trusted_redirect_uri_logs_diagnostic_on_rejection(
+ caplog, monkeypatch
+):
+ try:
+ from fastapi import HTTPException, Request
+
+ from litellm.proxy._experimental.mcp_server.oauth_utils import (
+ validate_trusted_redirect_uri,
+ )
+ except ImportError:
+ pytest.skip("MCP oauth_utils not available")
+
+ monkeypatch.delenv("PROXY_BASE_URL", raising=False)
+ monkeypatch.delenv("MCP_TRUSTED_REDIRECT_ORIGINS", raising=False)
+
+ mock_request = MagicMock(spec=Request)
+ mock_request.base_url = "http://litellm-internal:4000/"
+ mock_request.client = MagicMock()
+ mock_request.client.host = "203.0.113.5"
+ headers = {
+ "X-Forwarded-Proto": "https",
+ "X-Forwarded-Host": "litellm.example.com",
+ "X-Forwarded-Port": "443",
+ "Host": "litellm-internal:4000",
+ }
+ mock_request.headers.get = lambda name, default=None: headers.get(name, default)
+
+ import logging
+
+ with (
+ caplog.at_level(logging.WARNING, logger="LiteLLM"),
+ patch("litellm.proxy.proxy_server.general_settings", {}, create=True),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ validate_trusted_redirect_uri(
+ mock_request,
+ "https://litellm.example.com/ui/mcp/oauth/callback",
+ )
+ assert exc_info.value.status_code == 400
+ assert exc_info.value.detail == "invalid_request"
+
+ matching = [r for r in caplog.records if "rejecting redirect_uri" in r.getMessage()]
+ assert len(matching) == 1, (
+ "expected exactly one diagnostic warning, got "
+ f"{[r.getMessage() for r in caplog.records]}"
+ )
+ msg = matching[0].getMessage()
+ assert "https://litellm.example.com/ui/mcp/oauth/callback" in msg
+ assert "litellm-internal:4000" in msg
+ assert "X-Forwarded-Host" in msg
+
+
+ "bad_value",
+ [
+ "litellm.example.com",
+ "litellm.example.com/",
+ "://litellm.example.com",
+ "ftp://litellm.example.com",
+ "https://",
+ "not a url at all",
+ ],
+)
+def test_get_request_base_url_rejects_malformed_proxy_base_url(
+ bad_value, monkeypatch, caplog
+):
+ try:
+ from fastapi import Request
+
+ from litellm.proxy._experimental.mcp_server import oauth_utils
+ from litellm.proxy._experimental.mcp_server.oauth_utils import (
+ get_request_base_url,
+ )
+ except ImportError:
+ pytest.skip("MCP oauth_utils not available")
+
+ oauth_utils._warned_invalid_proxy_base_url = None
+
+ mock_request = MagicMock(spec=Request)
+ mock_request.base_url = "http://litellm-internal:4000/"
+ mock_request.client = MagicMock()
+ mock_request.client.host = "127.0.0.1"
+ mock_request.headers.get = lambda name, default=None: default
+
+ monkeypatch.setenv("PROXY_BASE_URL", bad_value)
+
+ import logging
+
+ with (
+ caplog.at_level(logging.WARNING, logger="LiteLLM"),
+ patch("litellm.proxy.proxy_server.general_settings", {}, create=True),
+ ):
+ result = get_request_base_url(mock_request)
+
+ assert result == "http://litellm-internal:4000", (
+ f"malformed PROXY_BASE_URL={bad_value!r} should be ignored, " f"got {result!r}"
+ )
+ matching = [
+ r
+ for r in caplog.records
+ if "PROXY_BASE_URL" in r.getMessage() and "ignored" in r.getMessage()
+ ]
+ assert len(matching) == 1, (
+ "expected one diagnostic for malformed PROXY_BASE_URL, got "
+ f"{[r.getMessage() for r in caplog.records]}"
+ )
+ assert (
+ repr(bad_value) in matching[0].getMessage()
+ or bad_value in matching[0].getMessage()
+ )
+
+
+def test_get_request_base_url_malformed_proxy_base_url_warning_is_one_shot(
+ monkeypatch, caplog
+):
+ try:
+ from fastapi import Request
+
+ from litellm.proxy._experimental.mcp_server import oauth_utils
+ from litellm.proxy._experimental.mcp_server.oauth_utils import (
+ get_request_base_url,
+ )
+ except ImportError:
+ pytest.skip("MCP oauth_utils not available")
+
+ oauth_utils._warned_invalid_proxy_base_url = None
+
+ mock_request = MagicMock(spec=Request)
+ mock_request.base_url = "http://litellm-internal:4000/"
+ mock_request.client = MagicMock()
+ mock_request.client.host = "127.0.0.1"
+ mock_request.headers.get = lambda name, default=None: default
+
+ monkeypatch.setenv("PROXY_BASE_URL", "litellm.example.com")
+
+ import logging
+
+ with (
+ caplog.at_level(logging.WARNING, logger="LiteLLM"),
+ patch("litellm.proxy.proxy_server.general_settings", {}, create=True),
+ ):
+ for _ in range(5):
+ get_request_base_url(mock_request)
+
+ matching = [
+ r
+ for r in caplog.records
+ if "PROXY_BASE_URL" in r.getMessage() and "ignored" in r.getMessage()
+ ]
+ assert (
+ len(matching) == 1
+ ), f"expected exactly one warning across 5 calls, got {len(matching)}"
+
+
# -------------------------------------------------------------------
# Tests for scopes_supported when mcp_server.scopes is None
# -------------------------------------------------------------------