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): fix OpenAPI OAuth flow — transport mapping, error messages, and discovery bypass (#23315)

Ishaan Jafff5e5d17e4ae7
diff --git a/CLAUDE.md b/CLAUDE.md
index 0c1caff9b45..5d62d2cdcda 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -102,6 +102,22 @@ LiteLLM is a unified interface for 100+ LLM providers with two main components:
### UI / Backend Consistency
- When wiring a new UI entity type to an existing backend endpoint, verify the backend API contract (single value vs. array, required vs. optional params) and ensure the UI controls match — e.g., use a single-select dropdown when the backend accepts a single value, not a multi-select
+### MCP OAuth / OpenAPI Transport Mapping
+- `TRANSPORT.OPENAPI` is a UI-only concept. The backend only accepts `"http"`, `"sse"`, or `"stdio"`. Always map it to `"http"` before any API call (including pre-OAuth temp-session calls).
+- FastAPI validation errors return `detail` as an array of `{loc, msg, type}` objects. Error extractors must handle: array (map `.msg`), string, nested `{error: string}`, and fallback.
+- When an MCP server already has `authorization_url` stored, skip OAuth discovery (`_discovery_metadata`) — the server URL for OpenAPI MCPs is the spec file, not the API base, and fetching it causes timeouts.
+- `client_id` should be optional in the `/authorize` endpoint — if the server has a stored `client_id` in credentials, use that. Never require callers to re-supply it.
+
+### MCP Credential Storage
+- OAuth credentials and BYOK credentials share the `litellm_mcpusercredentials` table, distinguished by a `"type"` field in the JSON payload (`"oauth2"` vs plain string).
+- When deleting OAuth credentials, check type before deleting to avoid accidentally deleting a BYOK credential for the same `(user_id, server_id)` pair.
+- Always pass the raw `expires_at` timestamp to the client — never set it to `None` for expired credentials. Let the frontend compute the "Expired" display state from the timestamp.
+- Use `RecordNotFoundError` (not bare `except Exception`) when catching "already deleted" in credential delete endpoints.
+
+### Browser Storage Safety (UI)
+- Never write LiteLLM access tokens or API keys to `localStorage` — use `sessionStorage` only. `localStorage` survives browser close and is readable by any injected script (XSS).
+- Shared utility functions (e.g. `extractErrorMessage`) belong in `src/utils/` — never define them inline in hooks or duplicate them across files.
+
### Database Migrations
- Prisma handles schema migrations
- Migration files auto-generated with `prisma migrate dev`
diff --git a/litellm/proxy/_experimental/mcp_server/db.py b/litellm/proxy/_experimental/mcp_server/db.py
index c6af4be314d..477229dc700 100644
--- a/litellm/proxy/_experimental/mcp_server/db.py
+++ b/litellm/proxy/_experimental/mcp_server/db.py
@@ -1,4 +1,6 @@
-from datetime import datetime, timezone
+import base64
+import json
+from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Iterable, List, Optional, Set, Union, cast
from litellm._logging import verbose_proxy_logger
@@ -495,7 +497,6 @@ async def store_user_credential(
credential: str,
) -> None:
"""Store a user credential for a BYOK MCP server."""
- import base64
encoded = base64.urlsafe_b64encode(credential.encode()).decode()
await prisma_client.db.litellm_mcpusercredentials.upsert(
@@ -517,7 +518,6 @@ async def get_user_credential(
server_id: str,
) -> Optional[str]:
"""Return credential for a user+server pair, or None."""
- import base64
row = await prisma_client.db.litellm_mcpusercredentials.find_unique(
where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}}
@@ -559,6 +559,120 @@ async def delete_user_credential(
)
+# ── OAuth2 user-credential helpers ────────────────────────────────────────────
+
+
+async def store_user_oauth_credential(
+ prisma_client: PrismaClient,
+ user_id: str,
+ server_id: str,
+ access_token: str,
+ refresh_token: Optional[str] = None,
+ expires_in: Optional[int] = None,
+ scopes: Optional[List[str]] = None,
+) -> None:
+ """Persist an OAuth2 access token for a user+server pair.
+
+ The payload is JSON-serialised and stored base64-encoded in the same
+ ``credential_b64`` column used by BYOK. A ``"type": "oauth2"`` key
+ differentiates it from plain BYOK API keys.
+ """
+
+ expires_at: Optional[str] = None
+ if expires_in is not None:
+ expires_at = (
+ datetime.now(timezone.utc) + timedelta(seconds=expires_in)
+ ).isoformat()
+
+ payload: Dict[str, Any] = {
+ "type": "oauth2",
+ "access_token": access_token,
+ "connected_at": datetime.now(timezone.utc).isoformat(),
+ }
+ if refresh_token:
+ payload["refresh_token"] = refresh_token
+ if expires_at:
+ payload["expires_at"] = expires_at
+ if scopes:
+ payload["scopes"] = scopes
+
+ # Guard against silently overwriting a BYOK credential with an OAuth token.
+ # BYOK credentials lack a "type" field (or use a non-"oauth2" type).
+ existing = await prisma_client.db.litellm_mcpusercredentials.find_unique(
+ where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}}
+ )
+ if existing is not None:
+ _byok_error = ValueError(
+ f"A non-OAuth2 credential already exists for user {user_id} "
+ f"and server {server_id}. Refusing to overwrite."
+ )
+ try:
+ raw = json.loads(base64.urlsafe_b64decode(existing.credential_b64).decode())
+ except Exception:
+ # Credential is not base64+JSON — it's a plain-text BYOK key.
+ raise _byok_error
+ if raw.get("type") != "oauth2":
+ raise _byok_error
+
+ encoded = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode()
+ await prisma_client.db.litellm_mcpusercredentials.upsert(
+ where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}},
+ data={
+ "create": {
+ "user_id": user_id,
+ "server_id": server_id,
+ "credential_b64": encoded,
+ },
+ "update": {"credential_b64": encoded},
+ },
+ )
+
+
+async def get_user_oauth_credential(
+ prisma_client: PrismaClient,
+ user_id: str,
+ server_id: str,
+) -> Optional[Dict[str, Any]]:
+ """Return the decoded OAuth2 payload dict for a user+server pair, or None."""
+
+ row = await prisma_client.db.litellm_mcpusercredentials.find_unique(
+ where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}}
+ )
+ if row is None:
+ return None
+ try:
+ decoded = base64.urlsafe_b64decode(row.credential_b64).decode()
+ parsed = json.loads(decoded)
+ if isinstance(parsed, dict) and parsed.get("type") == "oauth2":
+ return parsed
+ # Row exists but is a BYOK (plain string), not an OAuth token
+ return None
+ except Exception:
+ return None
+
+
+async def list_user_oauth_credentials(
+ prisma_client: PrismaClient,
+ user_id: str,
+) -> List[Dict[str, Any]]:
+ """Return all OAuth2 credential payloads for a user, tagged with server_id."""
+
+ rows = await prisma_client.db.litellm_mcpusercredentials.find_many(
+ where={"user_id": user_id}
+ )
+ results: List[Dict[str, Any]] = []
+ for row in rows:
+ try:
+ decoded = base64.urlsafe_b64decode(row.credential_b64).decode()
+ parsed = json.loads(decoded)
+ if isinstance(parsed, dict) and parsed.get("type") == "oauth2":
+ parsed["server_id"] = row.server_id
+ results.append(parsed)
+ except Exception:
+ pass # Skip non-OAuth rows (BYOK plain strings)
+ return results
+
+
async def approve_mcp_server(
prisma_client: PrismaClient,
server_id: str,
diff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py
index b731bc7bc2f..ad1dadb1222 100644
--- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py
+++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py
@@ -316,8 +316,8 @@ async def register_client_with_server(
@router.get("/authorize")
async def authorize(
request: Request,
- client_id: str,
redirect_uri: str,
+ client_id: Optional[str] = None,
state: str = "",
mcp_server_name: Optional[str] = None,
code_challenge: Optional[str] = None,
@@ -330,19 +330,34 @@ async def authorize(
global_mcp_server_manager,
)
- lookup_name = mcp_server_name or client_id
+ lookup_name: Optional[str] = mcp_server_name or client_id
client_ip = IPAddressUtils.get_mcp_client_ip(request)
- mcp_server = global_mcp_server_manager.get_mcp_server_by_name(
- lookup_name, client_ip=client_ip
+ mcp_server = (
+ global_mcp_server_manager.get_mcp_server_by_name(lookup_name, client_ip=client_ip)
+ if lookup_name
+ else None
)
if mcp_server is None and mcp_server_name is None:
mcp_server = _resolve_oauth2_server_for_root_endpoints()
if mcp_server is None:
raise HTTPException(status_code=404, detail="MCP server not found")
+ # Use server's stored client_id when caller doesn't supply one.
+ # Raise a clear error instead of passing an empty string — an empty
+ # client_id would silently produce a broken authorization URL.
+ resolved_client_id: str = mcp_server.client_id or client_id or ""
+ if not resolved_client_id:
+ raise HTTPException(
+ status_code=400,
+ detail={
+ "error": "client_id is required but was not supplied and is not "
+ "stored on the MCP server record. Provide client_id as a query "
+ "parameter or configure it on the server."
+ },
+ )
return await authorize_with_server(
request=request,
mcp_server=mcp_server,
- client_id=client_id,
+ client_id=resolved_client_id,
redirect_uri=redirect_uri,
state=state,
code_challenge=code_challenge,
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 36790e9feae..bb7d787d9d6 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -1284,6 +1284,37 @@ class MCPUserCredentialResponse(LiteLLMPydanticObjectBase):
has_credential: bool
+class MCPOAuthUserCredentialRequest(LiteLLMPydanticObjectBase):
+ """Stores a user's OAuth2 token for an OpenAPI MCP server."""
+
+ access_token: str
+ refresh_token: Optional[str] = None
+ expires_in: Optional[int] = None # seconds until expiry
+ scopes: Optional[List[str]] = None
+
+
+class MCPOAuthUserCredentialStatus(LiteLLMPydanticObjectBase):
+ """Describes whether the calling user has a stored OAuth credential."""
+
+ server_id: str
+ has_credential: bool
+ expires_at: Optional[str] = None # ISO-8601
+ is_expired: bool = False
+ connected_at: Optional[str] = None # ISO-8601
+
+
+class MCPUserCredentialListItem(LiteLLMPydanticObjectBase):
+ """One entry in the /user-credentials list."""
+
+ server_id: str
+ server_name: Optional[str] = None
+ alias: Optional[str] = None
+ credential_type: str # "oauth2" or "byok"
+ has_credential: bool
+ expires_at: Optional[str] = None # ISO-8601; None means non-expiring
+ connected_at: Optional[str] = None # ISO-8601
+
+
class RejectMCPServerRequest(LiteLLMPydanticObjectBase):
review_notes: Optional[str] = None
diff --git a/litellm/proxy/management_endpoints/mcp_management_endpoints.py b/litellm/proxy/management_endpoints/mcp_management_endpoints.py
index 7eeb2a83007..a94fd96a0ee 100644
--- a/litellm/proxy/management_endpoints/mcp_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/mcp_management_endpoints.py
@@ -36,6 +36,11 @@ from fastapi import (
)
from fastapi.responses import JSONResponse
+try:
+ from prisma.errors import RecordNotFoundError
+except ImportError:
+ RecordNotFoundError = Exception # type: ignore
+
import litellm
from litellm._logging import verbose_logger, verbose_proxy_logger
from litellm._uuid import uuid
@@ -84,9 +89,13 @@ if MCP_AVAILABLE:
delete_user_credential,
get_all_mcp_servers_for_user,
get_mcp_server,
+ get_mcp_servers,
get_mcp_submissions,
+ get_user_oauth_credential,
+ list_user_oauth_credentials,
reject_mcp_server,
store_user_credential,
+ store_user_oauth_credential,
update_mcp_server,
)
from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (
@@ -106,7 +115,10 @@ if MCP_AVAILABLE:
LitellmUserRoles,
MakeMCPServersPublicRequest,
MCPApprovalStatus,
+ MCPOAuthUserCredentialRequest,
+ MCPOAuthUserCredentialStatus,
MCPSubmissionsSummary,
+ MCPUserCredentialListItem,
MCPUserCredentialRequest,
MCPUserCredentialResponse,
NewMCPServerRequest,
@@ -1475,7 +1487,7 @@ if MCP_AVAILABLE:
)
try:
await delete_user_credential(prisma_client, user_id, server_id)
- except Exception:
+ except RecordNotFoundError:
pass # Already deleted or didn't exist
from litellm.proxy._experimental.mcp_server.server import (
_invalidate_byok_cred_cache,
@@ -1483,6 +1495,188 @@ if MCP_AVAILABLE:
_invalidate_byok_cred_cache(user_id, server_id)
return MCPUserCredentialResponse(server_id=server_id, has_credential=False)
+ # ── OAuth2 user-credential endpoints ──────────────────────────────────────
+
+ @router.post(
+ "/server/{server_id}/oauth-user-credential",
+ description="Store the calling user's OAuth2 token for an OpenAPI MCP server",
+ dependencies=[Depends(user_api_key_auth)],
+ response_model=MCPOAuthUserCredentialStatus,
+ )
+ @management_endpoint_wrapper
+ async def store_mcp_oauth_user_credential(
+ server_id: str,
+ payload: MCPOAuthUserCredentialRequest,
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+ ):
+ """Persist the OAuth2 access token obtained by the calling user."""
+ prisma_client = get_prisma_client_or_throw(
+ "Database not connected. Connect a database to your proxy"
+ )
+ mcp_server = await get_mcp_server(prisma_client, server_id)
+ if mcp_server is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail={"error": f"MCP Server {server_id} not found"},
+ )
+ user_id = user_api_key_dict.user_id or ""
+ if not user_id:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={"error": "User ID not found in token"},
+ )
+ await store_user_oauth_credential(
+ prisma_client,
+ user_id,
+ server_id,
+ payload.access_token,
+ refresh_token=payload.refresh_token,
+ expires_in=payload.expires_in,
+ scopes=payload.scopes,
+ )
+ # Read back the persisted record so the response reflects the stored
+ # expires_at rather than recomputing it here (which could diverge by
+ # milliseconds or if the storage logic ever adds a grace period).
+ stored = await get_user_oauth_credential(prisma_client, user_id, server_id)
+ expires_at: Optional[str] = stored.get("expires_at") if stored else None
+ return MCPOAuthUserCredentialStatus(
+ server_id=server_id,
+ has_credential=True,
+ expires_at=expires_at,
+ is_expired=False,
+ )
+
+ @router.delete(
+ "/server/{server_id}/oauth-user-credential",
+ description="Revoke the calling user's stored OAuth2 token for an MCP server",
+ dependencies=[Depends(user_api_key_auth)],
+ response_model=MCPOAuthUserCredentialStatus,
+ )
+ @management_endpoint_wrapper
+ async def delete_mcp_oauth_user_credential(
+ server_id: str,
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+ ):
+ """Revoke/delete the user's OAuth2 credential."""
+ prisma_client = get_prisma_client_or_throw(
+ "Database not connected. Connect a database to your proxy"
+ )
+ user_id = user_api_key_dict.user_id or ""
+ if not user_id:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={"error": "User ID not found in token"},
+ )
+ # Only delete if the stored credential is actually an OAuth2 token.
+ # This prevents accidentally deleting a BYOK credential if one exists
+ # for the same (user_id, server_id) pair.
+ cred_to_delete = await get_user_oauth_credential(prisma_client, user_id, server_id)
+ if cred_to_delete is not None:
+ try:
+ await delete_user_credential(prisma_client, user_id, server_id)
+ except RecordNotFoundError:
+ pass # Already gone — treat as a successful delete
+ return MCPOAuthUserCredentialStatus(
+ server_id=server_id,
+ has_credential=False,
+ is_expired=False,
+ )
+
+ @router.get(
+ "/server/{server_id}/oauth-user-credential/status",
+ description="Check whether the calling user has a stored OAuth2 credential for this MCP server",
+ dependencies=[Depends(user_api_key_auth)],
+ response_model=MCPOAuthUserCredentialStatus,
+ )
+ @management_endpoint_wrapper
+ async def get_mcp_oauth_user_credential_status(
+ server_id: str,
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+ ):
+ """Return credential status (has_credential, expiry) without exposing the token."""
+ prisma_client = get_prisma_client_or_throw(
+ "Database not connected. Connect a database to your proxy"
+ )
+ user_id = user_api_key_dict.user_id or ""
+ if not user_id:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={"error": "User ID not found in token"},
+ )
+ cred = await get_user_oauth_credential(prisma_client, user_id, server_id)
+ if cred is None:
+ return MCPOAuthUserCredentialStatus(
+ server_id=server_id, has_credential=False, is_expired=False
+ )
+ expires_at: Optional[str] = cred.get("expires_at")
+ is_expired = False
+ if expires_at:
+ try:
+ exp = datetime.fromisoformat(expires_at)
+ is_expired = exp < datetime.now(timezone.utc)
+ except Exception:
+ pass
+ return MCPOAuthUserCredentialStatus(
+ server_id=server_id,
+ has_credential=True,
+ expires_at=expires_at,
+ is_expired=is_expired,
+ connected_at=cred.get("connected_at"),
+ )
+
+ @router.get(
+ "/user-credentials",
+ description="List all OAuth2 MCP credentials stored for the calling user",
+ dependencies=[Depends(user_api_key_auth)],
+ response_model=List[MCPUserCredentialListItem],
+ )
+ @management_endpoint_wrapper
+ async def list_mcp_user_credentials(
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+ ):
+ """Return all servers the calling user has connected via OAuth2."""
+ prisma_client = get_prisma_client_or_throw(
+ "Database not connected. Connect a database to your proxy"
+ )
+ user_id = user_api_key_dict.user_id or ""
+ if not user_id:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={"error": "User ID not found in token"},
+ )
+ oauth_creds = await list_user_oauth_credentials(prisma_client, user_id)
+ if not oauth_creds:
+ return []
+ # Fetch server metadata for display names — single batch query instead of N+1.
+ server_ids = [c["server_id"] for c in oauth_creds]
+ servers = {
+ srv.server_id: srv
+ for srv in await get_mcp_servers(prisma_client, server_ids)
+ }
+ items: List[MCPUserCredentialListItem] = []
+ for cred in oauth_creds:
+ sid = cred["server_id"]
+ srv = servers.get(sid)
+ expires_at: Optional[str] = cred.get("expires_at")
+ is_expired = False
+ if expires_at:
+ try:
+ is_expired = datetime.fromisoformat(expires_at) < datetime.now(timezone.utc)
+ except Exception:
+ pass
+ items.append(
+ MCPUserCredentialListItem(
+ server_id=sid,
+ server_name=getattr(srv, "server_name", None) if srv else None,
+ alias=getattr(srv, "alias", None) if srv else None,
+ credential_type="oauth2",
+ has_credential=True,
+ expires_at=expires_at, # always pass the raw timestamp; client computes expiry state
+ connected_at=cred.get("connected_at"),
+ )
+ )
+ return items
+
@router.put(
"/server",
description="Allows deleting mcp serves in the db",
diff --git a/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py
index ea51965ebfc..8442d33e50d 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_mcp_management_endpoints.py
@@ -2005,3 +2005,183 @@ class TestValidateMCPRequiredFields:
_validate_mcp_required_fields(payload)
assert exc_info.value.status_code == 500
assert "source_Url" in str(exc_info.value.detail)
+
+
+# ── OAuth user credential endpoint unit tests ──────────────────────────────────
+
+
+def _make_user_auth(user_id: str = "user-abc") -> "UserAPIKeyAuth":
+ return UserAPIKeyAuth(
+ api_key="sk-test",
+ user_id=user_id,
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ )
+
+
+def _make_prisma_client():
+ """Return a minimal mock PrismaClient accepted by get_prisma_client_or_throw."""
+ client = MagicMock()
+ client.db = MagicMock()
+ return client
+
+
+async def test_store_mcp_oauth_user_credential_returns_status():
+ """store_mcp_oauth_user_credential persists the token and echoes back status."""
+ from litellm.proxy._types import (
+ MCPOAuthUserCredentialRequest,
+ MCPOAuthUserCredentialStatus,
+ )
+
+ if not mgmt_endpoints.MCP_AVAILABLE:
+ pytest.skip("MCP module not installed")
+
+ from litellm.proxy.management_endpoints.mcp_management_endpoints import (
+ store_mcp_oauth_user_credential,
+ )
+
+ server_id = "srv-1"
+ user_id = "user-123"
+ stored_payload = {
+ "type": "oauth2",
+ "access_token": "tok",
+ "expires_at": "2099-01-01T00:00:00+00:00",
+ "connected_at": "2026-01-01T00:00:00+00:00",
+ "server_id": server_id,
+ }
+
+ mock_prisma = _make_prisma_client()
+
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
+ return_value=mock_prisma,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_mcp_server",
+ new=AsyncMock(return_value=generate_mock_mcp_server_db_record(server_id=server_id)),
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.store_user_oauth_credential",
+ new=AsyncMock(return_value=None),
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_user_oauth_credential",
+ new=AsyncMock(return_value=stored_payload),
+ ),
+ ):
+ result = await store_mcp_oauth_user_credential(
+ server_id=server_id,
+ payload=MCPOAuthUserCredentialRequest(
+ access_token="tok",
+ expires_in=3600,
+ ),
+ user_api_key_dict=_make_user_auth(user_id),
+ )
+
+ assert isinstance(result, MCPOAuthUserCredentialStatus)
+ assert result.has_credential is True
+ assert result.server_id == server_id
+ # expires_at should come from the stored record, not be recomputed
+ assert result.expires_at == "2099-01-01T00:00:00+00:00"
+
+
+async def test_delete_mcp_oauth_user_credential_only_deletes_oauth():
+ """delete_mcp_oauth_user_credential only deletes OAuth2 credentials, not BYOK."""
+ from litellm.proxy._types import MCPOAuthUserCredentialStatus
+
+ if not mgmt_endpoints.MCP_AVAILABLE:
+ pytest.skip("MCP module not installed")
+
+ from litellm.proxy.management_endpoints.mcp_management_endpoints import (
+ delete_mcp_oauth_user_credential,
+ )
+
+ server_id = "srv-2"
+ user_id = "user-456"
+ delete_mock = AsyncMock(return_value=None)
+
+ # When get_user_oauth_credential returns None (no OAuth cred), delete should NOT be called.
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
+ return_value=_make_prisma_client(),
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_user_oauth_credential",
+ new=AsyncMock(return_value=None),
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.delete_user_credential",
+ new=delete_mock,
+ ),
+ ):
+ result = await delete_mcp_oauth_user_credential(
+ server_id=server_id,
+ user_api_key_dict=_make_user_auth(user_id),
+ )
+
+ delete_mock.assert_not_called()
+ assert isinstance(result, MCPOAuthUserCredentialStatus)
+ assert result.has_credential is False
+
+
+async def test_list_mcp_user_credentials_batch_server_fetch():
+ """list_mcp_user_credentials uses a single batch DB call, not N+1 queries."""
+ from litellm.proxy._types import MCPUserCredentialListItem
+
+ if not mgmt_endpoints.MCP_AVAILABLE:
+ pytest.skip("MCP module not installed")
+
+ from litellm.proxy.management_endpoints.mcp_management_endpoints import (
+ list_mcp_user_credentials,
+ )
+
+ user_id = "user-789"
+ server_id = "srv-3"
+ stored_creds = [
+ {
+ "type": "oauth2",
+ "access_token": "tok",
+ "expires_at": "2099-01-01T00:00:00+00:00",
+ "connected_at": "2026-01-01T00:00:00+00:00",
+ "server_id": server_id,
+ }
+ ]
+ mock_server = generate_mock_mcp_server_db_record(server_id=server_id, alias="My Server")
+ # get_mcp_servers (batch) should be called once; get_mcp_server (single) must not be called.
+ batch_mock = AsyncMock(return_value=[mock_server])
+ single_mock = AsyncMock(return_value=mock_server)
+
+ with (
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_prisma_client_or_throw",
+ return_value=_make_prisma_client(),
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.list_user_oauth_credentials",
+ new=AsyncMock(return_value=stored_creds),
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_mcp_servers",
+ new=batch_mock,
+ ),
+ patch(
+ "litellm.proxy.management_endpoints.mcp_management_endpoints.get_mcp_server",
+ new=single_mock,
+ ),
+ ):
+ result = await list_mcp_user_credentials(
+ user_api_key_dict=_make_user_auth(user_id),
+ )
+
+ batch_mock.assert_called_once()
+ single_mock.assert_not_called()
+ assert len(result) == 1
+ assert isinstance(result[0], MCPUserCredentialListItem)
+ assert result[0].server_id == server_id
+ assert result[0].alias == "My Server"
+ # expires_at should always be the raw timestamp (not set to None when expired)
+ assert result[0].expires_at == "2099-01-01T00:00:00+00:00"
diff --git a/ui/litellm-dashboard/package-lock.json b/ui/litellm-dashboard/package-lock.json
index d4f60ff0d7f..c062356ebbd 100644
--- a/ui/litellm-dashboard/package-lock.json
+++ b/ui/litellm-dashboard/package-lock.json
@@ -46,7 +46,7 @@
"@testing-library/user-event": "^14.6.1",
"@types/babel__traverse": "^7.28.0",
"@types/lodash": "^4.17.15",
- "@types/node": "^20",
+ "@types/node": "20.19.37",
"@types/react": "18.2.48",
"@types/react-copy-to-clipboard": "^5.0.7",
"@types/react-dom": "^18",
@@ -65,7 +65,7 @@
"postcss": "^8.4.33",
"prettier": "3.2.5",
"tailwindcss": "^3.4.1",
- "typescript": "^5.3.3",
+ "typescript": "5.9.3",
"vite": "^7.1.11",
"vitest": "^3.2.4"
},
@@ -3394,9 +3394,9 @@
"license": "MIT"
},
"node_modules/@types/node": {
- "version": "20.19.30",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.30.tgz",
- "integrity": "sha512-WJtwWJu7UdlvzEAUm484QNg5eAoq5QR08KDNx7g45Usrs2NtOPiX8ugDqmKdXkyL03rBqU5dYNYVQetEpBHq2g==",
+ "version": "20.19.37",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.37.tgz",
+ "integrity": "sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==",
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
@@ -12555,9 +12555,9 @@
}
},
"node_modules/typescript": {
- "version": "5.3.3",
- "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.3.tgz",
- "integrity": "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==",
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"devOptional": true,
"license": "Apache-2.0",
"bin": {
@@ -13279,21 +13279,6 @@
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
- },
- "node_modules/@next/swc-win32-ia32-msvc": {
- "version": "14.2.33",
- "resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.33.tgz",
- "integrity": "sha512-pc9LpGNKhJ0dXQhZ5QMmYxtARwwmWLpeocFmVG5Z0DzWq5Uf0izcI8tLc+qOpqxO1PWqZ5A7J1blrUIKrIFc7Q==",
- "cpu": [
- "ia32"
- ],
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">= 10"
- }
}
}
}
diff --git a/ui/litellm-dashboard/package.json b/ui/litellm-dashboard/package.json
index 06aff85e3f2..5cbe1ead886 100644
--- a/ui/litellm-dashboard/package.json
+++ b/ui/litellm-dashboard/package.json
@@ -58,7 +58,7 @@
"@testing-library/user-event": "^14.6.1",
"@types/babel__traverse": "^7.28.0",
"@types/lodash": "^4.17.15",
- "@types/node": "^20",
+ "@types/node": "20.19.37",
"@types/react": "18.2.48",
"@types/react-copy-to-clipboard": "^5.0.7",
"@types/react-dom": "^18",
@@ -77,7 +77,7 @@
"postcss": "^8.4.33",
"prettier": "3.2.5",
"tailwindcss": "^3.4.1",
- "typescript": "^5.3.3",
+ "typescript": "5.9.3",
"vite": "^7.1.11",
"vitest": "^3.2.4"
},
diff --git a/ui/litellm-dashboard/src/app/mcp/oauth/callback/page.tsx b/ui/litellm-dashboard/src/app/mcp/oauth/callback/page.tsx
index 73ff8c51bad..0c4cad8cb0b 100644
--- a/ui/litellm-dashboard/src/app/mcp/oauth/callback/page.tsx
+++ b/ui/litellm-dashboard/src/app/mcp/oauth/callback/page.tsx
@@ -3,7 +3,11 @@
import { Suspense, useEffect, useMemo } from "react";
import { useSearchParams } from "next/navigation";
-const RESULT_STORAGE_KEY = "litellm-mcp-oauth-result";
+// Written to sessionStorage so both the admin hook (useMcpOAuthFlow) and the
+// user hook (useUserMcpOAuthFlow) can pick up the result. Each hook reads
+// its own namespace to avoid cross-flow collisions.
+const ADMIN_RESULT_KEY = "litellm-mcp-oauth-result";
+const USER_RESULT_KEY = "litellm-user-mcp-oauth-result";
const RETURN_URL_STORAGE_KEY = "litellm-mcp-oauth-return-url";
const resolveDefaultRedirect = () => {
@@ -32,6 +36,10 @@ const McpOAuthCallbackContent = () => {
type: "litellm-mcp-oauth",
code: searchParams.get("code"),
state: searchParams.get("state"),
+ // Forward OAuth provider error params so the hook can surface the real
+ // reason (e.g. "access_denied") instead of a generic "code missing" error.
+ error: searchParams.get("error"),
+ error_description: searchParams.get("error_description"),
};
}, [searchParams]);
@@ -41,16 +49,16 @@ const McpOAuthCallbackContent = () => {
}
try {
- // Store in both sessionStorage and localStorage for redundancy
- window.sessionStorage.setItem(RESULT_STORAGE_KEY, JSON.stringify(payload));
- window.localStorage.setItem(RESULT_STORAGE_KEY, JSON.stringify(payload));
+ // Write to both namespace keys (admin and user) so whichever hook is
+ // active can consume the result. sessionStorage only — no localStorage.
+ const serialized = JSON.stringify(payload);
+ window.sessionStorage.setItem(ADMIN_RESULT_KEY, serialized);
+ window.sessionStorage.setItem(USER_RESULT_KEY, serialized);
} catch (err) {
// Silently ignore storage errors
}
- // Check both sessionStorage and localStorage for return URL
- const returnUrl = window.sessionStorage.getItem(RETURN_URL_STORAGE_KEY) ||
- window.localStorage.getItem(RETURN_URL_STORAGE_KEY);
+ const returnUrl = window.sessionStorage.getItem(RETURN_URL_STORAGE_KEY);
const destination = returnUrl || resolveDefaultRedirect();
window.location.replace(destination);
}, [payload]);
diff --git a/ui/litellm-dashboard/src/components/chat/ChatPage.tsx b/ui/litellm-dashboard/src/components/chat/ChatPage.tsx
index 6a67814e2c6..8a33a2487f4 100644
--- a/ui/litellm-dashboard/src/components/chat/ChatPage.tsx
+++ b/ui/litellm-dashboard/src/components/chat/ChatPage.tsx
@@ -11,6 +11,7 @@ import {
SearchOutlined,
MessageOutlined,
AppstoreOutlined,
+ KeyOutlined,
ArrowLeftOutlined,
DownOutlined,
CloseOutlined,
@@ -24,6 +25,7 @@ import ConversationList from "./ConversationList";
import ChatMessages from "./ChatMessages";
import MCPConnectPicker from "./MCPConnectPicker";
import MCPAppsPanel from "./MCPAppsPanel";
+import MCPCredentialsTab from "./MCPCredentialsTab";
import { fetchAvailableModels } from "../playground/llm_calls/fetch_models";
import { makeOpenAIChatCompletionRequest } from "../playground/llm_calls/chat_completion";
import { makeOpenAIResponsesRequest } from "../playground/llm_calls/responses_api";
@@ -142,7 +144,7 @@ const ChatPage: React.FC<ChatPageProps> = ({ accessToken, userRole, userId, user
const [inputText, setInputText] = useState("");
const [mcpPopoverOpen, setMcpPopoverOpen] = useState(false);
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
- const [sidebarView, setSidebarView] = useState<"chats" | "apps">("chats");
+ const [sidebarView, setSidebarView] = useState<"chats" | "apps" | "credentials">("chats");
const [storageBannerDismissed, setStorageBannerDismissed] = useState(false);
// Comparison mode state (active when selectedModels.length > 1)
@@ -859,6 +861,7 @@ const ChatPage: React.FC<ChatPageProps> = ({ accessToken, userRole, userId, user
<div style={{ padding: "4px 8px", flexShrink: 0 }}>
{sidebarNavItem(<MessageOutlined />, "Chats", () => setSidebarView("chats"), sidebarView === "chats")}
{sidebarNavItem(<AppstoreOutlined />, "Apps", () => setSidebarView("apps"), sidebarView === "apps")}
+ {sidebarNavItem(<KeyOutlined />, "Credentials", () => setSidebarView("credentials"), sidebarView === "credentials")}
<Tooltip title={sidebarCollapsed ? "Back to Developer Console UI" : undefined} placement="right">
<a
href={dashboardUrl}
@@ -969,6 +972,12 @@ const ChatPage: React.FC<ChatPageProps> = ({ accessToken, userRole, userId, user
/>
</div>
+ ) : sidebarView === "credentials" ? (
+ /* ---- Credentials view ---- */
+ <div style={{ flex: 1, minHeight: 0, overflow: "auto", maxWidth: 800, margin: "0 auto", width: "100%", padding: "32px 24px" }}>
+ <MCPCredentialsTab accessToken={accessToken} />
+ </div>
+
) : showBlankState ? (
/* ---- Blank state ---- */
<div style={{
diff --git a/ui/litellm-dashboard/src/components/chat/MCPAppsPanel.tsx b/ui/litellm-dashboard/src/components/chat/MCPAppsPanel.tsx
index 625478e98a4..a80468edfb8 100644
--- a/ui/litellm-dashboard/src/components/chat/MCPAppsPanel.tsx
+++ b/ui/litellm-dashboard/src/components/chat/MCPAppsPanel.tsx
@@ -1,11 +1,69 @@
"use client";
-import React, { useEffect, useState } from "react";
+import React, { useCallback, useEffect, useState } from "react";
import { Spin, Input, Button, Skeleton } from "antd";
-import { SearchOutlined, ArrowLeftOutlined, RightOutlined, ToolOutlined } from "@ant-design/icons";
-import { fetchMCPServers, listMCPTools } from "../networking";
+import { SearchOutlined, ArrowLeftOutlined, RightOutlined, ToolOutlined, CheckCircleOutlined } from "@ant-design/icons";
+import { deleteMCPOAuthUserCredential, fetchMCPServers, getMCPOAuthUserCredentialStatus, listMCPTools } from "../networking";
import { AUTH_TYPE, MCPServer, MCPTool, handleTransport } from "../mcp_tools/types";
import { message } from "antd";
+import { useUserMcpOAuthFlow } from "@/hooks/useUserMcpOAuthFlow";
+
+// ── OAuth2 connect button ─────────────────────────────────────────────────────
+// Wraps useUserMcpOAuthFlow so each server card can hold its own hook instance.
+interface OAuth2ConnectButtonProps {
+ server: MCPServer;
+ accessToken: string;
+ onConnect: (serverId: string) => void;
+ /** "badge" = small inline chip (grid card), "button" = full Ant Button (detail view) */
+ variant?: "badge" | "button";
+}
+
+const OAuth2ConnectButton: React.FC<OAuth2ConnectButtonProps> = ({
+ server,
+ accessToken,
+ onConnect,
+ variant = "badge",
+}) => {
+ const name = server.server_name ?? server.alias ?? server.server_id;
+ const { startOAuthFlow, status } = useUserMcpOAuthFlow({
+ accessToken,
+ serverId: server.server_id,
+ serverAlias: name,
+ onSuccess: useCallback(() => onConnect(server.server_id), [onConnect, server.server_id]),
+ });
+
+ const loading = status === "authorizing" || status === "exchanging";
+
+ if (variant === "button") {
+ return (
+ <Button
+ type="primary"
+ loading={loading}
+ onClick={startOAuthFlow}
+ style={{ borderRadius: 8, fontWeight: 600, height: 38, minWidth: 110 }}
+ >
+ {loading ? "Connecting…" : "Connect"}
+ </Button>
+ );
+ }
+
+ return (
+ <span
+ onClick={(e) => { e.stopPropagation(); if (!loading) startOAuthFlow(); }}
+ style={{
+ fontSize: 11, fontWeight: 600,
+ color: loading ? "#9ca3af" : "#fff",
+ background: loading ? "#e5e7eb" : "#1677ff",
+ borderRadius: 6, padding: "2px 8px",
+ cursor: loading ? "default" : "pointer",
+ flexShrink: 0, whiteSpace: "nowrap",
+ }}
+ >
+ {loading ? "Connecting…" : "Connect"}
+ </span>
+ );
+};
+// ─────────────────────────────────────────────────────────────────────────────
interface Props {
accessToken: string;
@@ -38,6 +96,8 @@ const MCPAppsPanel: React.FC<Props> = ({ accessToken, selectedServers, onChange
// tool counts per server name, preloaded in background
const [toolCounts, setToolCounts] = useState<Record<string, number>>({});
const [loadingCounts, setLoadingCounts] = useState(false);
+ // OAuth2 connect state — tracks which server_ids have a stored user credential
+ const [oauthConnected, setOauthConnected] = useState<Set<string>>(new Set());
const nameOf = (s: MCPServer) => s.server_name ?? s.alias ?? s.server_id;
@@ -72,6 +132,19 @@ const MCPAppsPanel: React.FC<Props> = ({ accessToken, selectedServers, onChange
if (remaining === 0) setLoadingCounts(false);
});
});
+
+ // 3. Check OAuth credential status for OAuth2 servers in parallel
+ const oauthServers = list.filter((s) => s.auth_type === AUTH_TYPE.OAUTH2);
+ oauthServers.forEach((s) => {
+ getMCPOAuthUserCredentialStatus(accessToken, s.server_id)
+ .then((status) => {
+ if (cancelled) return;
+ if (status.has_credential && !status.is_expired) {
+ setOauthConnected((prev) => new Set(prev).add(s.server_id));
+ }
+ })
+ .catch(() => {});
+ });
})
.catch(() => {
if (!cancelled) {
@@ -198,14 +271,41 @@ const MCPAppsPanel: React.FC<Props> = ({ accessToken, selectedServers, onChange
<h2 style={{ margin: "0 0 4px", fontSize: 22, fontWeight: 700, color: "#111827" }}>{name}</h2>
<p style={{ margin: 0, fontSize: 14, color: "#6b7280" }}>{detailServer.description ?? "MCP server"}</p>
</div>
- <Button
- type={isConnected ? "default" : "primary"}
- loading={isTogglingOn}
- onClick={() => handleToggle(name, !isConnected, detailServer.server_id)}
- style={{ borderRadius: 8, fontWeight: 600, height: 38, minWidth: 110 }}
- >
- {isConnected ? "Disconnect" : "Connect"}
- </Button>
+ {detailServer.auth_type === AUTH_TYPE.OAUTH2 ? (
+ oauthConnected.has(detailServer.server_id) ? (
+ <Button
+ type="default"
+ danger
+ onClick={async () => {
+ try {
+ await deleteMCPOAuthUserCredential(accessToken, detailServer.server_id);
+ } catch (_) {
+ // Ignore — credential may already be gone; update UI regardless.
+ }
+ setOauthConnected((prev) => { const n = new Set(prev); n.delete(detailServer.server_id); return n; });
+ }}
+ style={{ borderRadius: 8, fontWeight: 600, height: 38, minWidth: 110 }}
+ >
+ Disconnect
+ </Button>
+ ) : (
+ <OAuth2ConnectButton
+ server={detailServer}
+ accessToken={accessToken}
+ onConnect={(id) => setOauthConnected((prev) => new Set(prev).add(id))}
+ variant="button"
+ />
+ )
+ ) : (
+ <Button
+ type={isConnected ? "default" : "primary"}
+ loading={isTogglingOn}
+ onClick={() => handleToggle(name, !isConnected, detailServer.server_id)}
+ style={{ borderRadius: 8, fontWeight: 600, height: 38, minWidth: 110 }}
+ >
+ {isConnected ? "Disconnect" : "Connect"}
+ </Button>
+ )}
</div>
{/* Info table */}
@@ -410,24 +510,27 @@ const MCPAppsPanel: React.FC<Props> = ({ accessToken, selectedServers, onChange
) : null}
</div>
</div>
- {isConnected && (
+ {server.auth_type === AUTH_TYPE.OAUTH2 ? (
+ oauthConnected.has(server.server_id) ? (
+ <CheckCircleOutlined style={{ fontSize: 14, color: "#52c41a", flexShrink: 0 }} />
+ ) : (
+ <OAuth2ConnectButton
+ server={server}
+ accessToken={accessToken}
+ onConnect={(id) => setOauthConnected((prev) => new Set(prev).add(id))}
+ variant="badge"
+ />
+ )
+ ) : isConnected ? (
<span style={{ width: 7, height: 7, borderRadius: "50%", background: "#1677ff", flexShrink: 0 }} />
- )}
- {server.auth_type === AUTH_TYPE.OAUTH2 && (
- <span style={{
- fontSize: 10, fontWeight: 600, color: "#7c3aed",
- background: "#f3e8ff", borderRadius: 4, padding: "1px 5px",
- letterSpacing: "0.03em", flexShrink: 0, whiteSpace: "nowrap",
- }}>
- OAuth2
- </span>
- )}
+ ) : null}
<RightOutlined style={{ fontSize: 11, color: "#d1d5db", flexShrink: 0 }} />
</div>
);
})}
</div>
)}
+
</div>
);
};
diff --git a/ui/litellm-dashboard/src/components/chat/MCPCredentialsTab.tsx b/ui/litellm-dashboard/src/components/chat/MCPCredentialsTab.tsx
new file mode 100644
index 00000000000..9714da6d4d5
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/chat/MCPCredentialsTab.tsx
@@ -0,0 +1,187 @@
+"use client";
+
+/**
+ * MCPCredentialsTab
+ *
+ * Shows all OAuth2 MCP connections the calling user has stored.
+ * Lives in the Chat sidebar's "Credentials" tab.
+ */
+
+import React, { useCallback, useEffect, useState } from "react";
+import { Spin, message } from "antd";
+import { CheckCircleOutlined, DeleteOutlined, LinkOutlined } from "@ant-design/icons";
+import {
+ deleteMCPOAuthUserCredential,
+ listMCPUserCredentials,
+ MCPUserCredentialListItem,
+} from "../networking";
+
+interface Props {
+ accessToken: string;
+}
+
+function relativeTime(isoString: string | null | undefined): string {
+ if (!isoString) return "";
+ try {
+ const date = new Date(isoString);
+ const diffMs = Date.now() - date.getTime();
+ const diffSec = Math.floor(diffMs / 1000);
+ if (diffSec < 60) return "just now";
+ const diffMin = Math.floor(diffSec / 60);
+ if (diffMin < 60) return `${diffMin}m ago`;
+ const diffHr = Math.floor(diffMin / 60);
+ if (diffHr < 24) return `${diffHr}h ago`;
+ return `${Math.floor(diffHr / 24)}d ago`;
+ } catch {
+ return "";
+ }
+}
+
+function expiryLabel(isoString: string | null | undefined): string {
+ if (!isoString) return "Does not expire";
+ try {
+ const exp = new Date(isoString);
+ const diffMs = exp.getTime() - Date.now();
+ if (diffMs <= 0) return "Expired";
+ const diffSec = Math.floor(diffMs / 1000);
+ const diffMin = Math.floor(diffSec / 60);
+ const diffHr = Math.floor(diffMin / 60);
+ const diffDay = Math.floor(diffHr / 24);
+ if (diffDay > 0) return `Expires in ${diffDay}d`;
+ if (diffHr > 0) return `Expires in ${diffHr}h`;
+ return `Expires in ${diffMin}m`;
+ } catch {
+ return "";
+ }
+}
+
+const MCPCredentialsTab: React.FC<Props> = ({ accessToken }) => {
+ const [credentials, setCredentials] = useState<MCPUserCredentialListItem[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [revoking, setRevoking] = useState<Set<string>>(new Set());
+
+ const load = useCallback(() => {
+ setLoading(true);
+ listMCPUserCredentials(accessToken)
+ .then(setCredentials)
+ .catch(() => setCredentials([]))
+ .finally(() => setLoading(false));
+ }, [accessToken]);
+
+ useEffect(() => { load(); }, [load]);
+
+ const handleRevoke = async (serverId: string) => {
+ setRevoking((prev) => new Set(prev).add(serverId));
+ try {
+ await deleteMCPOAuthUserCredential(accessToken, serverId);
+ setCredentials((prev) => prev.filter((c) => c.server_id !== serverId));
+ } catch {
+ message.error("Failed to revoke connection. Please try again.");
+ } finally {
+ setRevoking((prev) => { const n = new Set(prev); n.delete(serverId); return n; });
+ }
+ };
+
+ const displayName = (c: MCPUserCredentialListItem) =>
+ c.alias || c.server_name || c.server_id;
+
+ return (
+ <div style={{ width: "100%" }}>
+ {/* Header */}
+ <div style={{ marginBottom: 20 }}>
+ <h2 style={{ margin: "0 0 4px", fontSize: 18, fontWeight: 600, color: "#111827" }}>
+ App Credentials
+ </h2>
+ <p style={{ margin: 0, fontSize: 13, color: "#6b7280" }}>
+ Your stored OAuth connections — used automatically in chat.
+ </p>
+ </div>
+
+ {loading ? (
+ <div style={{ display: "flex", justifyContent: "center", padding: "48px 0" }}>
+ <Spin />
+ </div>
+ ) : credentials.length === 0 ? (
+ <div style={{
+ textAlign: "center", color: "#9ca3af", fontSize: 13,
+ padding: "48px 12px", border: "1px dashed #e5e7eb", borderRadius: 10,
+ }}>
+ <LinkOutlined style={{ fontSize: 28, marginBottom: 12, display: "block", color: "#d1d5db" }} />
+ No connections yet.
+ <br />
+ Go to <strong>Apps</strong> and click <strong>Connect</strong> to authorize an MCP server.
+ </div>
+ ) : (
+ <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
+ {credentials.map((cred) => {
+ const name = displayName(cred);
+ const isRevoking = revoking.has(cred.server_id);
+ const exp = expiryLabel(cred.expires_at);
+ const connected = relativeTime(cred.connected_at);
+ const isExpired = exp === "Expired";
+
+ return (
+ <div
+ key={cred.server_id}
+ style={{
+ display: "flex", alignItems: "center", gap: 12,
+ padding: "14px 16px", border: "1px solid #e5e7eb",
+ borderRadius: 10, background: "#fff",
+ }}
+ >
+ {/* Status dot */}
+ <div style={{ flexShrink: 0 }}>
+ <CheckCircleOutlined style={{ fontSize: 20, color: isExpired ? "#d1d5db" : "#52c41a" }} />
+ </div>
+
+ {/* Info */}
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <div style={{ fontSize: 14, fontWeight: 600, color: "#111827", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
+ {name}
+ </div>
+ <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 2, flexWrap: "wrap" }}>
+ {connected && (
+ <span style={{ fontSize: 12, color: "#9ca3af" }}>
+ Connected {connected}
+ </span>
+ )}
+ <span style={{
+ fontSize: 11, fontWeight: 600,
+ color: isExpired ? "#ef4444" : "#16a34a",
+ background: isExpired ? "#fef2f2" : "#f0fdf4",
+ borderRadius: 4, padding: "1px 6px",
+ }}>
+ {exp}
+ </span>
+ </div>
+ </div>
+
+ {/* Revoke */}
+ <button
+ onClick={() => handleRevoke(cred.server_id)}
+ disabled={isRevoking}
+ title="Revoke connection"
+ style={{
+ background: "none", border: "1px solid #e5e7eb",
+ borderRadius: 6, padding: "4px 8px",
+ cursor: isRevoking ? "not-allowed" : "pointer",
+ color: "#9ca3af", display: "flex", alignItems: "center",
+ opacity: isRevoking ? 0.5 : 1, flexShrink: 0,
+ }}
+ >
+ {isRevoking ? (
+ <Spin size="small" />
+ ) : (
+ <DeleteOutlined style={{ fontSize: 14 }} />
+ )}
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default MCPCredentialsTab;
diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx
index 68c695d93b6..762fed91d14 100644
--- a/ui/litellm-dashboard/src/components/networking.tsx
+++ b/ui/litellm-dashboard/src/components/networking.tsx
@@ -9619,7 +9619,17 @@ export const storeMCPOAuthUserCredential = async (
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
- throw new Error((err as { detail?: { error?: string } })?.detail?.error || "Failed to store OAuth credential");
+ const errObj = err as { detail?: unknown };
+ const detail = errObj?.detail;
+ const detailMsg =
+ Array.isArray(detail)
+ ? detail.map((d: unknown) => (d && typeof d === "object" ? (d as Record<string, unknown>).msg ?? JSON.stringify(d) : String(d))).join("; ")
+ : typeof detail === "string"
+ ? detail
+ : detail && typeof (detail as Record<string, unknown>).error === "string"
+ ? (detail as Record<string, unknown>).error as string
+ : undefined;
+ throw new Error(detailMsg || "Failed to store OAuth credential");
}
return response.json();
};
@@ -9637,7 +9647,17 @@ export const deleteMCPOAuthUserCredential = async (
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
- throw new Error((err as { detail?: { error?: string } })?.detail?.error || "Failed to revoke OAuth credential");
+ const errObj = err as { detail?: unknown };
+ const detail = errObj?.detail;
+ const detailMsg =
+ Array.isArray(detail)
+ ? detail.map((d: unknown) => (d && typeof d === "object" ? (d as Record<string, unknown>).msg ?? JSON.stringify(d) : String(d))).join("; ")
+ : typeof detail === "string"
+ ? detail
+ : detail && typeof (detail as Record<string, unknown>).error === "string"
+ ? (detail as Record<string, unknown>).error as string
+ : undefined;
+ throw new Error(detailMsg || "Failed to revoke OAuth credential");
}
return response.json();
};
diff --git a/ui/litellm-dashboard/src/hooks/useMcpOAuthFlow.tsx b/ui/litellm-dashboard/src/hooks/useMcpOAuthFlow.tsx
index 97d48510c2e..67ace5db405 100644
--- a/ui/litellm-dashboard/src/hooks/useMcpOAuthFlow.tsx
+++ b/ui/litellm-dashboard/src/hooks/useMcpOAuthFlow.tsx
@@ -10,20 +10,10 @@ import {
registerMcpOAuthClient,
serverRootPath,
} from "@/components/networking";
+import { extractErrorMessage } from "@/utils/errorUtils";
export type McpOAuthStatus = "idle" | "authorizing" | "exchanging" | "success" | "error";
-function extractErrorMessage(err: unknown): string {
- if (err instanceof Error) return err.message;
- if (err && typeof err === "object") {
- const e = err as Record<string, unknown>;
- if (typeof e.detail === "string") return e.detail;
- if (typeof e.message === "string") return e.message;
- return JSON.stringify(err);
- }
- return String(err);
-}
-
interface UseMcpOAuthFlowOptions {
accessToken: string | null;
getCredentials: () => {
@@ -90,9 +80,10 @@ export const useMcpOAuthFlow = ({
const setStorageItem = (key: string, value: string) => {
if (typeof window === "undefined") return;
try {
- // Store in both sessionStorage and localStorage for redundancy
+ // Use sessionStorage only — the flow state may contain client credentials;
+ // writing them to localStorage would persist across browser sessions and
+ // make them readable by any injected script (XSS).
window.sessionStorage.setItem(key, value);
- window.localStorage.setItem(key, value);
} catch (err) {
console.warn(`Failed to set storage item ${key}`, err);
}
diff --git a/ui/litellm-dashboard/src/hooks/useUserMcpOAuthFlow.tsx b/ui/litellm-dashboard/src/hooks/useUserMcpOAuthFlow.tsx
new file mode 100644
index 00000000000..26aab97b341
--- /dev/null
+++ b/ui/litellm-dashboard/src/hooks/useUserMcpOAuthFlow.tsx
@@ -0,0 +1,283 @@
+"use client";
+
+/**
+ * OAuth2 PKCE flow for the *user* connect path.
+ *
+ * Unlike useMcpOAuthFlow (used in the admin create-server form), this hook
+ * targets a server that already exists in the database. It therefore skips
+ * the temp-session cache step and calls /server/oauth/{serverId}/authorize
+ * directly with the real server_id.
+ *
+ * On success it calls storeMCPOAuthUserCredential to persist the token for
+ * the user and then invokes onSuccess so the caller can refresh UI state.
+ */
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ buildMcpOAuthAuthorizeUrl,
+ exchangeMcpOAuthToken,
+ getProxyBaseUrl,
+ registerMcpOAuthClient,
+ serverRootPath,
+ storeMCPOAuthUserCredential,
+} from "@/components/networking";
+import NotificationsManager from "@/components/molecules/notifications_manager";
+import { extractErrorMessage } from "@/utils/errorUtils";
+
+export type UserMcpOAuthStatus = "idle" | "authorizing" | "exchanging" | "success" | "error";
+
+interface UseUserMcpOAuthFlowOptions {
+ accessToken: string;
+ serverId: string;
+ serverAlias?: string | null;
+ /** Scopes to request, e.g. ["repo", "read:user"] */
+ scopes?: string[];
+ /** Pre-configured client_id if the MCP server record has one. */
+ clientId?: string | null;
+ onSuccess: () => void;
+}
+
+interface UseUserMcpOAuthFlowResult {
+ startOAuthFlow: () => Promise<void>;
+ status: UserMcpOAuthStatus;
+ error: string | null;
+}
+
+const FLOW_STATE_KEY = "litellm-user-mcp-oauth-flow-state";
+// Use a user-flow-specific key to avoid collisions with the admin OAuth flow
+// (useMcpOAuthFlow) which uses "litellm-mcp-oauth-result".
+const RESULT_KEY = "litellm-user-mcp-oauth-result";
+const RETURN_URL_KEY = "litellm-mcp-oauth-return-url";
+
+type StoredFlowState = {
+ state: string;
+ codeVerifier: string;
+ serverId: string;
+ redirectUri: string;
+ clientId?: string;
+ clientSecret?: string;
+ scopes?: string[];
+};
+
+const b64url = (buf: ArrayBuffer) => {
+ const bytes = new Uint8Array(buf);
+ let s = "";
+ bytes.forEach((b) => (s += String.fromCharCode(b)));
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+};
+
+const genVerifier = () => {
+ const arr = new Uint8Array(32);
+ window.crypto.getRandomValues(arr);
+ return b64url(arr.buffer);
+};
+
+const genChallenge = async (verifier: string) => {
+ const data = new TextEncoder().encode(verifier);
+ const digest = await window.crypto.subtle.digest("SHA-256", data);
+ return b64url(digest);
+};
+
+const setStorage = (key: string, value: string) => {
+ try {
+ // Use sessionStorage only — do not write to localStorage.
+ // The flow state may contain the LiteLLM access token; writing it to
+ // localStorage would persist it across browser sessions and make it
+ // readable by any injected script (XSS).
+ window.sessionStorage.setItem(key, value);
+ } catch (_) {}
+};
+
+const getStorage = (key: string): string | null => {
+ try {
+ return window.sessionStorage.getItem(key);
+ } catch (_) {
+ return null;
+ }
+};
+
+const clearStorage = (...keys: string[]) => {
+ keys.forEach((k) => {
+ try {
+ window.sessionStorage.removeItem(k);
+ } catch (_) {}
+ });
+};
+
+const buildCallbackUrl = (): string => {
+ if (typeof window !== "undefined") {
+ const path = window.location.pathname || "";
+ const idx = path.indexOf("/ui");
+ const prefix = idx >= 0 ? path.slice(0, idx + 3).replace(/\/+$/, "") : "";
+ return `${window.location.origin}${prefix}/mcp/oauth/callback`;
+ }
+ const base = (getProxyBaseUrl() || "").replace(/\/+$/, "");
+ const root = serverRootPath && serverRootPath !== "/" ? serverRootPath : "";
+ return `${base}${root}/ui/mcp/oauth/callback`;
+};
+
+export const useUserMcpOAuthFlow = ({
+ accessToken,
+ serverId,
+ serverAlias,
+ scopes,
+ clientId: preClientId,
+ onSuccess,
+}: UseUserMcpOAuthFlowOptions): UseUserMcpOAuthFlowResult => {
+ const [status, setStatus] = useState<UserMcpOAuthStatus>("idle");
+ const [error, setError] = useState<string | null>(null);
+ const processingRef = useRef(false);
+
+ const startOAuthFlow = useCallback(async () => {
+ if (typeof window === "undefined") return;
+ try {
+ setStatus("authorizing");
+ setError(null);
+
+ let clientId: string | undefined = preClientId ?? undefined;
+ let clientSecret: string | undefined;
+
+ if (!clientId) {
+ // Attempt dynamic client registration against the server's registration endpoint.
+ try {
+ const reg = await registerMcpOAuthClient(accessToken, serverId, {
+ client_name: serverAlias || serverId,
+ grant_types: ["authorization_code", "refresh_token"],
+ response_types: ["code"],
+ token_endpoint_auth_method: "none",
+ });
+ clientId = reg?.client_id;
+ clientSecret = reg?.client_secret;
+ } catch (_) {
+ // Registration is optional; proceed without client_id
+ }
+ }
+
+ const verifier = genVerifier();
+ const challenge = await genChallenge(verifier);
+ const state = crypto.randomUUID();
+ const redirectUri = buildCallbackUrl();
+ const scopeString = scopes?.filter((s) => s.trim()).join(" ");
+
+ const authorizeUrl = buildMcpOAuthAuthorizeUrl({
+ serverId,
+ clientId,
+ redirectUri,
+ state,
+ codeChallenge: challenge,
+ scope: scopeString,
+ });
+
+ const flowState: StoredFlowState = {
+ state,
+ codeVerifier: verifier,
+ serverId,
+ redirectUri,
+ clientId,
+ clientSecret,
+ scopes,
+ };
+
+ setStorage(FLOW_STATE_KEY, JSON.stringify(flowState));
+ setStorage(RETURN_URL_KEY, window.location.href);
+
+ window.location.href = authorizeUrl;
+ } catch (err) {
+ const msg = extractErrorMessage(err);
+ setError(msg);
+ setStatus("error");
+ NotificationsManager.error(msg);
+ }
+ }, [accessToken, serverId, serverAlias, scopes, preClientId]);
+
+ const resumeOAuthFlow = useCallback(async () => {
+ if (typeof window === "undefined" || processingRef.current) return;
+
+ const storedResult = getStorage(RESULT_KEY);
+ if (!storedResult) return;
+
+ // When multiple OAuth2ConnectButton components are mounted (one per server
+ // card), each holds its own hook instance. All run resumeOAuthFlow() on
+ // mount and would compete for the same RESULT_KEY. Peek at the stored
+ // flow state first: only the hook instance whose serverId matches the one
+ // that initiated the OAuth flow should consume the result.
+ const rawFlowState = getStorage(FLOW_STATE_KEY);
+ if (rawFlowState) {
+ try {
+ const peeked = JSON.parse(rawFlowState) as StoredFlowState;
+ if (peeked.serverId && peeked.serverId !== serverId) return;
+ } catch (_) {}
+ }
+
+ processingRef.current = true;
+ clearStorage(RESULT_KEY);
+
+ let payload: Record<string, unknown> | null = null;
+ let flowState: StoredFlowState | null = null;
+
+ try {
+ payload = JSON.parse(storedResult);
+ const raw = getStorage(FLOW_STATE_KEY);
+ flowState = raw ? JSON.parse(raw) : null;
+ } catch (_) {
+ setError("Failed to resume OAuth flow. Please retry.");
+ setStatus("error");
+ processingRef.current = false;
+ clearStorage(FLOW_STATE_KEY);
+ return;
+ }
+
+ try {
+ if (!flowState?.state || !flowState.codeVerifier || !flowState.serverId) {
+ throw new Error("OAuth session state was lost. Please retry.");
+ }
+ if (!payload?.state || payload.state !== flowState.state) {
+ throw new Error("OAuth state mismatch. Please retry.");
+ }
+ if (payload.error) {
+ throw new Error((payload.error_description as string) || (payload.error as string));
+ }
+ if (!payload.code) {
+ throw new Error("Authorization code missing in callback.");
+ }
+
+ setStatus("exchanging");
+ const token = await exchangeMcpOAuthToken({
+ serverId: flowState.serverId,
+ code: payload.code as string,
+ clientId: flowState.clientId,
+ clientSecret: flowState.clientSecret,
+ codeVerifier: flowState.codeVerifier,
+ redirectUri: flowState.redirectUri,
+ });
+
+ // Persist the token for this user via the backend.
+ // accessToken comes from props — it is never stored in sessionStorage.
+ await storeMCPOAuthUserCredential(accessToken, flowState.serverId, {
+ access_token: token.access_token,
+ refresh_token: token.refresh_token,
+ expires_in: token.expires_in,
+ scopes: flowState.scopes,
+ });
+
+ setStatus("success");
+ setError(null);
+ NotificationsManager.success("Connected successfully");
+ onSuccess();
+ } catch (err) {
+ const msg = extractErrorMessage(err);
+ setError(msg);
+ setStatus("error");
+ NotificationsManager.error(msg);
+ } finally {
+ clearStorage(FLOW_STATE_KEY);
+ setTimeout(() => { processingRef.current = false; }, 1000);
+ }
+ }, [accessToken, serverId, onSuccess]);
+
+ useEffect(() => {
+ resumeOAuthFlow();
+ }, [resumeOAuthFlow]);
+
+ return { startOAuthFlow, status, error };
+};
diff --git a/ui/litellm-dashboard/src/utils/errorUtils.ts b/ui/litellm-dashboard/src/utils/errorUtils.ts
new file mode 100644
index 00000000000..665e4e9cb72
--- /dev/null
+++ b/ui/litellm-dashboard/src/utils/errorUtils.ts
@@ -0,0 +1,35 @@
+/**
+ * Shared error-message extraction utility.
+ *
+ * Handles the common shapes returned by LiteLLM / FastAPI:
+ * - Error instances (err.message)
+ * - { detail: "string" }
+ * - { detail: [{ msg, loc, type }] } (FastAPI 422)
+ * - { detail: { error: "string" } }
+ * - { message: "string" }
+ * - anything else → JSON.stringify / String()
+ */
+export function extractErrorMessage(err: unknown): string {
+ if (err instanceof Error) return err.message;
+ if (err && typeof err === "object") {
+ const e = err as Record<string, unknown>;
+ const detail = e.detail;
+ if (typeof detail === "string") return detail;
+ if (Array.isArray(detail)) {
+ return detail.map((d: unknown) => {
+ if (d && typeof d === "object") {
+ const item = d as Record<string, unknown>;
+ return typeof item.msg === "string" ? item.msg : JSON.stringify(d);
+ }
+ return String(d);
+ }).join("; ");
+ }
+ if (detail && typeof detail === "object") {
+ const detailObj = detail as Record<string, unknown>;
+ if (typeof detailObj.error === "string") return detailObj.error;
+ }
+ if (typeof e.message === "string") return e.message;
+ return JSON.stringify(err);
+ }
+ return String(err);
+}