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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(ui): wire the tool playground and gateway authorize flow for the client-forwarded token modes
Tin367aa904de68
diff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.pyindex c87e900aa2a..7606deac241 100644--- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py@@ -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):returnraise HTTPException(status_code=400,@@ -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")diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.pyindex c4ad673b88f..c8681b94f5e 100644--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py@@ -1384,8 +1384,9 @@ class MCPServerManager:auth_type = cast(MCPAuthType, mcp_server.auth_type)server_url = mcp_server.url+ upstream_oauth_auth_types = (MCPAuth.oauth2, MCPAuth.true_passthrough, MCPAuth.oauth_delegate)needs_discovery = bool(server_url) and (- (auth_type == MCPAuth.oauth2 and not mcp_server.authorization_url)+ (auth_type in upstream_oauth_auth_types and not mcp_server.authorization_url)or self._obo_needs_endpoint_discovery(auth_type,mcp_server.token_exchange_endpoint@@ -1396,7 +1397,7 @@ class MCPServerManager: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_auth_types,)if needs_discoveryelse Nonediff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.pyindex 19d030f17c4..926c3d5a1f4 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@@ -119,6 +119,61 @@ async def test_authorize_endpoint_includes_response_type():assert "scope=read+write" in response.headers["location"][email protected]("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.asyncioasync def test_authorize_endpoint_preserves_existing_query_params():"""Test that authorize endpoint merges OAuth params with existing query params in authorization_url"""diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.pyindex 12e22de195b..e8fca9ac6ab 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py@@ -833,6 +833,39 @@ class TestMCPServerManager: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 threadedinto ``_create_mcp_client``."""diff --git a/ui/litellm-dashboard/src/components/mcp_tools/mcp_tools.test.tsx b/ui/litellm-dashboard/src/components/mcp_tools/mcp_tools.test.tsxindex 3346bc342f3..2e8fa901f6d 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/mcp_tools.test.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/mcp_tools.test.tsx@@ -91,6 +91,37 @@ describe("MCPToolsViewer auth gate routing", () => {expect(screen.queryByText(GATE_TEXT)).not.toBeInTheDocument();});+ it.each([["true_passthrough"], ["oauth_delegate"]])(+ "shows the Authorize gate for a %s server without a browser token and does not list tools",+ async (authType) => {+ renderViewer({ auth_type: authType, oauth2_flow: null, delegate_auth_to_upstream: false });++ expect(await screen.findByText(GATE_TEXT)).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Authorize" })).toBeInTheDocument();+ expect(vi.mocked(listMCPTools)).not.toHaveBeenCalled();+ expect(vi.mocked(getMCPOAuthUserCredentialStatus)).not.toHaveBeenCalled();+ },+ );++ it.each([["true_passthrough"], ["oauth_delegate"]])(+ "forwards the session token via the x-mcp header for a %s server that has one",+ async (authType) => {+ vi.mocked(isTokenValid).mockReturnValue(true);+ vi.mocked(getToken).mockReturnValue({ access_token: "upstream-tok" } as ReturnType<typeof getToken>);++ renderViewer({ auth_type: authType, oauth2_flow: null, delegate_auth_to_upstream: false });++ await waitFor(() =>+ expect(vi.mocked(listMCPTools)).toHaveBeenCalledWith(+ "litellm-key",+ "srv-1",+ expect.objectContaining({ "x-mcp-slack-authorization": "Bearer upstream-tok" }),+ ),+ );+ expect(screen.queryByText(GATE_TEXT)).not.toBeInTheDocument();+ },+ );+it("lists tools for an OBO server when the user has a DB credential, with no x-mcp header", async () => {renderViewer({ oauth2_flow: null, delegate_auth_to_upstream: false });diff --git a/ui/litellm-dashboard/src/components/mcp_tools/mcp_tools.tsx b/ui/litellm-dashboard/src/components/mcp_tools/mcp_tools.tsxindex e436732ba3b..6c99a53afaa 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/mcp_tools.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/mcp_tools.tsx@@ -2,7 +2,7 @@ import React, { useCallback, useEffect, useState } from "react";import { useQuery, useMutation } from "@tanstack/react-query";import { ToolTestPanel } from "./ToolTestPanel";import { resolveLogoSrc } from "@/lib/assetPaths";-import { MCPTool, MCPToolsViewerProps, MCPContent, CallMCPToolResponse, getMcpOAuthMode } from "./types";+import { AUTH_TYPE, MCPTool, MCPToolsViewerProps, MCPContent, CallMCPToolResponse, getMcpOAuthMode } from "./types";import { listMCPTools, callMCPTool, getMCPOAuthUserCredentialStatus } from "../networking";import { isTokenValid, getToken, removeToken } from "@/utils/mcpTokenStore";import { sanitizeMcpAliasForHeader, buildMcpPassthroughAuthHeader } from "@/utils/mcpHeaderUtils";@@ -42,19 +42,24 @@ const MCPToolsViewer = ({// service token and needs no gate.const oauthMode = getMcpOAuthMode({ auth_type, oauth2_flow, delegate_auth_to_upstream });const isPassthrough = oauthMode === "passthrough";+ // The client-forwarded token modes gate the same way as PKCE passthrough: the+ // browser session token (established via the browser-only Authorize in the+ // create/edit forms, or right here) is the upstream credential.+ const usesBrowserHeldToken =+ isPassthrough || auth_type === AUTH_TYPE.TRUE_PASSTHROUGH || auth_type === AUTH_TYPE.OAUTH_DELEGATE;const isAuthorizationCode = oauthMode === "authorization_code";const [oauthToken, setOauthToken] = useState<string | null>(() =>- isPassthrough && isTokenValid(serverId, userID) ? getToken(serverId, userID)?.access_token ?? null : null,+ usesBrowserHeldToken && isTokenValid(serverId, userID) ? getToken(serverId, userID)?.access_token ?? null : null,);// Re-sync token when serverId/userID changes (useState initializer only runs on mount).useEffect(() => {- if (!isPassthrough) {+ if (!usesBrowserHeldToken) {setOauthToken(null);return;}setOauthToken(isTokenValid(serverId, userID) ? getToken(serverId, userID)?.access_token ?? null : null);- }, [serverId, userID, isPassthrough]);+ }, [serverId, userID, usesBrowserHeldToken]);const {startOAuthFlow,@@ -109,7 +114,7 @@ const MCPToolsViewer = ({// x-mcp-{alias}-{header} pattern and forwards it to the upstream MCP server.// When no alias is available, fall back to x-mcp-auth (legacy but still supported).// Passthrough only: authorization_code/token_exchange/M2M tokens are attached server-side, not from the browser.- if (isPassthrough && oauthToken) {+ if (usesBrowserHeldToken && oauthToken) {Object.assign(customHeaders, buildMcpPassthroughAuthHeader(serverAlias, oauthToken));}@@ -164,7 +169,8 @@ const MCPToolsViewer = ({// Passthrough blocks until a browser session token exists; authorization_code blocks until// the user has a valid DB credential (else the backend returns no tools).enabled:- !!accessToken && (isPassthrough ? oauthToken !== null : isAuthorizationCode ? hasAuthorizationCodeCred : true),+ !!accessToken &&+ (usesBrowserHeldToken ? oauthToken !== null : isAuthorizationCode ? hasAuthorizationCodeCred : true),staleTime: 30000, // Consider data fresh for 30 secondsretry: (failureCount, error: any) => {// Don't retry on 401 — token is invalid, user must re-authenticate@@ -253,7 +259,8 @@ const MCPToolsViewer = ({// passthrough needs a browser token; authorization_code needs a stored DB credential or a// still-valid one — a 401 from the list call means the backend has none even// after attempting a refresh, so re-authorization is required.- const authGateActive = (isPassthrough && !oauthToken) || authorizationCodeNeedsAuth || authorizationCodeTokenRejected;+ const authGateActive =+ (usesBrowserHeldToken && !oauthToken) || authorizationCodeNeedsAuth || authorizationCodeTokenRejected;// Treat authorization_code credential-status loading as "tools loading" so the empty state// doesn't flash before we know whether the user needs to authorize.const toolsAreaLoading = isLoadingTools || authorizationCodeStatusLoading;@@ -359,7 +366,7 @@ const MCPToolsViewer = ({</Text>{/* Passthrough auth gate — browser session token absent */}- {isPassthrough && !oauthToken && (+ {usesBrowserHeldToken && !oauthToken && (<div className="p-4 text-center bg-white border border-gray-200 rounded-lg"><LockOutlined className="text-2xl text-gray-400 mb-2" /><p className="text-xs font-medium text-gray-700 mb-1">Authentication required</p>