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
feat(mcp): BYOK MCP servers with OAuth 2.1 PKCE authorization flow (#22850)
Ishaan Jaff1bb713bc7ba8
diff --git a/CLAUDE.md b/CLAUDE.mdindex c1eb75d2515..5b36c2be8ac 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -114,4 +114,14 @@ LiteLLM is a unified interface for 100+ LLM providers with two main components:### Enterprise Features- Enterprise-specific code in `enterprise/` directory- Optional features enabled via environment variables-- Separate licensing and authentication for enterprise features\ No newline at end of file+- Separate licensing and authentication for enterprise features++### Troubleshooting: DB schema out of sync after proxy restart+`litellm-proxy-extras` runs `prisma migrate deploy` on startup using **its own** bundled migration files, which may lag behind schema changes in the current worktree. Symptoms: `Unknown column`, `Invalid prisma invocation`, or missing data on new fields.++**Diagnose:** Run `\d "TableName"` in psql and compare against `schema.prisma` — missing columns confirm the issue.++**Fix options:**+1. **Create a Prisma migration** (permanent) — run `prisma migrate dev --name <description>` in the worktree. The generated file will be picked up by `prisma migrate deploy` on next startup.+2. **Apply manually for local dev** — `psql -d litellm -c "ALTER TABLE ... ADD COLUMN IF NOT EXISTS ..."` after each proxy start. Fine for dev, not for production.+3. **Update litellm-proxy-extras** — if the package is installed from PyPI, its migration directory must include the new file. Either update the package or run the migration manually until the next release ships it.\ No newline at end of filediff --git a/litellm/proxy/_experimental/mcp_server/byok_oauth_endpoints.py b/litellm/proxy/_experimental/mcp_server/byok_oauth_endpoints.pynew file mode 100644index 00000000000..db18885721a--- /dev/null+++ b/litellm/proxy/_experimental/mcp_server/byok_oauth_endpoints.py@@ -0,0 +1,786 @@+"""+BYOK (Bring Your Own Key) OAuth 2.1 Authorization Server endpoints for MCP servers.++When an MCP client connects to a BYOK-enabled server and no stored credential exists,+LiteLLM runs a minimal OAuth 2.1 authorization code flow. The "authorization page" is+just a form that asks the user for their API key — not a full identity-provider OAuth.++Endpoints implemented here:+ GET /.well-known/oauth-authorization-server — OAuth authorization server metadata+ GET /.well-known/oauth-protected-resource — OAuth protected resource metadata+ GET /v1/mcp/oauth/authorize — Shows HTML form to collect the API key+ POST /v1/mcp/oauth/authorize — Stores temp auth code and redirects+ POST /v1/mcp/oauth/token — Exchanges code for a bearer JWT token+"""++import base64+import hashlib+import html as _html_module+import time+import uuid+from typing import Dict, Optional, cast+from urllib.parse import urlencode, urlparse++import jwt+from fastapi import APIRouter, Form, HTTPException, Request+from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse++from litellm._logging import verbose_proxy_logger+from litellm.proxy._experimental.mcp_server.db import store_user_credential+from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (+ get_request_base_url,+)++# ---------------------------------------------------------------------------+# In-memory store for pending authorization codes.+# Each entry: {code: {api_key, server_id, code_challenge, redirect_uri, user_id, expires_at}}+# ---------------------------------------------------------------------------+_byok_auth_codes: Dict[str, dict] = {}++# Authorization codes expire after 5 minutes.+_AUTH_CODE_TTL_SECONDS = 300+# Hard cap to prevent memory exhaustion from incomplete OAuth flows.+_AUTH_CODES_MAX_SIZE = 1000++router = APIRouter(tags=["mcp"])+++# ---------------------------------------------------------------------------+# PKCE helper+# ---------------------------------------------------------------------------+++def _verify_pkce(code_verifier: str, code_challenge: str) -> bool:+ """Return True iff SHA-256(code_verifier) == code_challenge (base64url, no padding)."""+ digest = hashlib.sha256(code_verifier.encode()).digest()+ computed = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()+ return computed == code_challenge+++# ---------------------------------------------------------------------------+# Cleanup of expired auth codes (called lazily on each request)+# ---------------------------------------------------------------------------+++def _purge_expired_codes() -> None:+ now = time.time()+ expired = [k for k, v in _byok_auth_codes.items() if v["expires_at"] < now]+ for k in expired:+ del _byok_auth_codes[k]+++def _build_authorize_html(+ server_name: str,+ server_initial: str,+ client_id: str,+ redirect_uri: str,+ code_challenge: str,+ code_challenge_method: str,+ state: str,+ server_id: str,+ access_items: list,+ help_url: str,+) -> str:+ """Build the 2-step BYOK OAuth authorization page HTML."""++ # Escape all user-supplied / externally-derived values before interpolation+ e = _html_module.escape+ server_name = e(server_name)+ server_initial = e(server_initial)+ client_id = e(client_id)+ redirect_uri = e(redirect_uri)+ code_challenge = e(code_challenge)+ code_challenge_method = e(code_challenge_method)+ state = e(state)+ server_id = e(server_id)++ # Build access checklist rows+ access_rows = "".join(+ f'<div class="access-item"><span class="check">✓</span>{e(item)}</div>'+ for item in access_items+ )+ access_section = ""+ if access_rows:+ access_section = f"""+ <div class="access-box">+ <div class="access-header">+ <span class="shield">▮</span>+ <span>Requested Access</span>+ </div>+ {access_rows}+ </div>"""++ # Help link for step 2+ help_link_html = ""+ if help_url:+ help_link_html = f'<a class="help-link" href="{e(help_url)}" target="_blank">Where do I find my API key? ↗</a>'++ return f"""<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<meta name="viewport" content="width=device-width, initial-scale=1.0">+<title>Connect {server_name} — LiteLLM</title>+<style>+ *, *::before, *::after {{ box-sizing: border-box; margin: 0; padding: 0; }}+ body {{+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ background: #0f172a;+ min-height: 100vh;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 24px;+ }}+ .modal {{+ background: #ffffff;+ border-radius: 20px;+ padding: 36px 32px 32px;+ width: 440px;+ max-width: 100%;+ position: relative;+ box-shadow: 0 25px 60px rgba(0,0,0,0.35);+ }}+ /* Progress dots */+ .dots {{+ display: flex;+ justify-content: center;+ gap: 7px;+ margin-bottom: 28px;+ }}+ .dot {{+ width: 8px; height: 8px;+ border-radius: 50%;+ background: #e2e8f0;+ }}+ .dot.active {{ background: #38bdf8; }}+ /* Close button */+ .close-btn {{+ position: absolute;+ top: 16px; right: 16px;+ background: none; border: none;+ font-size: 16px; color: #94a3b8;+ cursor: pointer; line-height: 1;+ width: 28px; height: 28px;+ border-radius: 6px;+ display: flex; align-items: center; justify-content: center;+ }}+ .close-btn:hover {{ background: #f1f5f9; color: #475569; }}+ /* Logo pair */+ .logos {{+ display: flex; align-items: center; justify-content: center;+ gap: 12px; margin-bottom: 20px;+ }}+ .logo {{+ width: 52px; height: 52px;+ border-radius: 14px;+ display: flex; align-items: center; justify-content: center;+ font-size: 22px; font-weight: 800; color: white;+ }}+ .logo-img {{+ width: 52px; height: 52px;+ border-radius: 14px;+ object-fit: cover;+ border: 1.5px solid #e2e8f0;+ }}+ .logo-s {{ background: linear-gradient(135deg, #818cf8 0%, #4f46e5 100%); }}+ .logo-arrow {{ color: #cbd5e1; font-size: 20px; font-weight: 300; }}+ /* Headings */+ .step-title {{+ text-align: center;+ font-size: 21px; font-weight: 700;+ color: #0f172a; margin-bottom: 8px;+ }}+ .step-subtitle {{+ text-align: center;+ font-size: 14px; color: #64748b;+ line-height: 1.55; margin-bottom: 22px;+ }}+ /* Info box */+ .info-box {{+ background: #f8fafc;+ border-radius: 12px;+ padding: 14px 16px;+ display: flex; gap: 12px;+ margin-bottom: 14px;+ }}+ .info-icon {{ font-size: 17px; flex-shrink: 0; margin-top: 1px; color: #38bdf8; }}+ .info-box h4 {{ font-size: 13px; font-weight: 600; color: #1e293b; margin-bottom: 4px; }}+ .info-box p {{ font-size: 13px; color: #64748b; line-height: 1.5; }}+ /* Access checklist */+ .access-box {{+ background: #f8fafc;+ border-radius: 12px;+ padding: 14px 16px;+ margin-bottom: 22px;+ }}+ .access-header {{+ display: flex; align-items: center; gap: 8px;+ margin-bottom: 10px;+ }}+ .shield {{ color: #22c55e; font-size: 15px; }}+ .access-header > span:last-child {{+ font-size: 11px; font-weight: 700;+ letter-spacing: 0.07em;+ text-transform: uppercase;+ color: #475569;+ }}+ .access-item {{+ display: flex; align-items: center; gap: 9px;+ font-size: 13.5px; color: #374151;+ padding: 3px 0;+ }}+ .check {{ color: #22c55e; font-weight: 700; font-size: 13px; }}+ /* Primary CTA */+ .btn-primary {{+ width: 100%; padding: 15px;+ background: #0f172a; color: white;+ border: none; border-radius: 12px;+ font-size: 15px; font-weight: 600;+ cursor: pointer; margin-bottom: 10px;+ }}+ .btn-primary:hover {{ background: #1e293b; }}+ .btn-cancel {{+ width: 100%; padding: 8px;+ background: none; border: none;+ font-size: 13.5px; color: #94a3b8;+ cursor: pointer;+ }}+ .btn-cancel:hover {{ color: #64748b; }}+ /* Step 2 nav */+ .step2-nav {{+ display: flex; align-items: center;+ justify-content: space-between;+ margin-bottom: 24px;+ }}+ .back-btn {{+ background: none; border: none;+ font-size: 13.5px; color: #64748b;+ cursor: pointer; display: flex; align-items: center; gap: 4px;+ }}+ .back-btn:hover {{ color: #374151; }}+ /* Key icon */+ .key-icon-wrap {{+ width: 46px; height: 46px;+ background: #e0f2fe;+ border-radius: 12px;+ display: flex; align-items: center; justify-content: center;+ margin-bottom: 14px;+ }}+ .key-icon-wrap svg {{ width: 22px; height: 22px; color: #0284c7; }}+ /* Form elements */+ .field-label {{+ font-size: 13.5px; font-weight: 600;+ color: #1e293b; display: block;+ margin-bottom: 7px;+ }}+ .key-input {{+ width: 100%; padding: 11px 13px;+ border: 1.5px solid #e2e8f0;+ border-radius: 10px;+ font-size: 14px; color: #0f172a;+ outline: none; transition: border-color 0.15s, box-shadow 0.15s;+ }}+ .key-input:focus {{+ border-color: #38bdf8;+ box-shadow: 0 0 0 3px rgba(56,189,248,0.12);+ }}+ .help-link {{+ display: inline-flex; align-items: center; gap: 4px;+ color: #0ea5e9; font-size: 13px;+ text-decoration: none; margin: 8px 0 16px;+ }}+ .help-link:hover {{ text-decoration: underline; }}+ /* Save toggle card */+ .save-card {{+ border: 1.5px solid #e2e8f0;+ border-radius: 12px;+ padding: 13px 15px;+ margin-bottom: 6px;+ }}+ .save-row {{+ display: flex; align-items: center; gap: 10px;+ }}+ .save-icon {{ font-size: 16px; }}+ .save-label {{+ flex: 1;+ font-size: 14px; font-weight: 500; color: #1e293b;+ }}+ /* Toggle switch */+ .toggle {{ position: relative; width: 44px; height: 24px; flex-shrink: 0; }}+ .toggle input {{ opacity: 0; width: 0; height: 0; }}+ .slider {{+ position: absolute; inset: 0;+ background: #e2e8f0;+ border-radius: 24px; cursor: pointer;+ transition: background 0.18s;+ }}+ .slider::before {{+ content: '';+ position: absolute;+ width: 18px; height: 18px;+ left: 3px; bottom: 3px;+ background: white;+ border-radius: 50%;+ transition: transform 0.18s;+ box-shadow: 0 1px 3px rgba(0,0,0,0.18);+ }}+ input:checked + .slider {{ background: #38bdf8; }}+ input:checked + .slider::before {{ transform: translateX(20px); }}+ /* Duration pills */+ .duration-section {{ margin-top: 14px; }}+ .duration-label {{+ font-size: 12px; font-weight: 600;+ color: #64748b; margin-bottom: 8px;+ text-transform: uppercase; letter-spacing: 0.05em;+ }}+ .pills {{ display: flex; flex-wrap: wrap; gap: 7px; }}+ .pill {{+ padding: 6px 13px;+ border: 1.5px solid #e2e8f0;+ border-radius: 20px;+ font-size: 13px; color: #475569;+ cursor: pointer; background: white;+ transition: all 0.13s;+ user-select: none;+ }}+ .pill:hover {{ border-color: #94a3b8; }}+ .pill.sel {{+ border-color: #38bdf8;+ color: #0284c7;+ background: #e0f2fe;+ }}+ /* Security note */+ .sec-note {{+ background: #f8fafc;+ border-radius: 10px;+ padding: 11px 14px;+ display: flex; gap: 9px; align-items: flex-start;+ margin: 16px 0;+ }}+ .sec-icon {{ font-size: 13px; color: #94a3b8; margin-top: 1px; flex-shrink: 0; }}+ .sec-note p {{ font-size: 12.5px; color: #64748b; line-height: 1.5; }}+ /* Connect button */+ .btn-connect {{+ width: 100%; padding: 15px;+ border: none; border-radius: 12px;+ font-size: 15px; font-weight: 600;+ cursor: pointer;+ background: #bae6fd; color: #0369a1;+ transition: background 0.15s, color 0.15s;+ }}+ .btn-connect.ready {{+ background: #0ea5e9; color: white;+ }}+ .btn-connect.ready:hover {{ background: #0284c7; }}+ /* Step visibility */+ .step {{ display: none; }}+ .step.show {{ display: block; }}+</style>+</head>+<body>+<div class="modal">++ <!-- ── STEP 1: Connect ─────────────────────────────────────── -->+ <div id="s1" class="step show">+ <div class="dots">+ <div class="dot active"></div>+ <div class="dot"></div>+ </div>+ <button class="close-btn" type="button" onclick="doCancel()" title="Close">×</button>++ <div class="logos">+ <img src="/ui/assets/logos/litellm_logo.jpg" class="logo-img" alt="LiteLLM">+ <span class="logo-arrow">→</span>+ <div class="logo logo-s">{server_initial}</div>+ </div>++ <h2 class="step-title">Connect {server_name} MCP</h2>+ <p class="step-subtitle">LiteLLM needs access to {server_name} to complete your request.</p>++ <div class="info-box">+ <span class="info-icon">+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>+ </span>+ <div>+ <h4>How it works</h4>+ <p>LiteLLM acts as a secure bridge. Your requests are routed through our MCP client directly to {server_name}’s API.</p>+ </div>+ </div>++ {access_section}++ <button class="btn-primary" type="button" onclick="goStep2()">+ Continue to Authentication →+ </button>+ <button class="btn-cancel" type="button" onclick="doCancel()">Cancel</button>+ </div>++ <!-- ── STEP 2: Provide API Key ──────────────────────────────── -->+ <div id="s2" class="step">+ <div class="step2-nav">+ <button class="back-btn" type="button" onclick="goStep1()">← Back</button>+ <div class="dots">+ <div class="dot active"></div>+ <div class="dot active"></div>+ </div>+ <button class="close-btn" style="position:static;" type="button" onclick="doCancel()" title="Close">×</button>+ </div>++ <div class="key-icon-wrap">+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#0284c7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>+ </div>+ <h2 class="step-title" style="text-align:left;">Provide API Key</h2>+ <p class="step-subtitle" style="text-align:left;">Enter your {server_name} API key to authorize this connection.</p>++ <form method="POST" id="authForm" onsubmit="prepareSubmit()">+ <input type="hidden" name="client_id" value="{client_id}">+ <input type="hidden" name="redirect_uri" value="{redirect_uri}">+ <input type="hidden" name="code_challenge" value="{code_challenge}">+ <input type="hidden" name="code_challenge_method" value="{code_challenge_method}">+ <input type="hidden" name="state" value="{state}">+ <input type="hidden" name="server_id" value="{server_id}">+ <input type="hidden" name="duration" id="durInput" value="until_revoked">++ <label class="field-label">{server_name} API Key</label>+ <input+ type="password"+ name="api_key"+ id="apiKey"+ class="key-input"+ placeholder="Enter your API key"+ required+ autofocus+ oninput="syncBtn()"+ >++ {help_link_html}++ <div class="save-card">+ <div class="save-row">+ <span class="save-label">Save key for future use</span>+ <label class="toggle">+ <input type="checkbox" id="saveToggle" onchange="toggleDur()">+ <span class="slider"></span>+ </label>+ </div>+ <div id="durSection" class="duration-section" style="display:none;">+ <div class="duration-label">Duration</div>+ <div class="pills">+ <div class="pill" onclick="selDur('1h',this)">1 hour</div>+ <div class="pill sel" onclick="selDur('24h',this)">24 hours</div>+ <div class="pill" onclick="selDur('7d',this)">7 days</div>+ <div class="pill" onclick="selDur('30d',this)">30 days</div>+ <div class="pill" onclick="selDur('until_revoked',this)">Until I revoke</div>+ </div>+ </div>+ </div>++ <div class="sec-note">+ <span class="sec-icon">+ <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>+ </span>+ <p>Your key is stored securely and transmitted over HTTPS. It is never shared with third parties.</p>+ </div>++ <button type="submit" class="btn-connect" id="connectBtn">+ Connect & Authorize+ </button>+ </form>+ </div>++</div>+<script>+ function goStep2() {{+ document.getElementById('s1').classList.remove('show');+ document.getElementById('s2').classList.add('show');+ }}+ function goStep1() {{+ document.getElementById('s2').classList.remove('show');+ document.getElementById('s1').classList.add('show');+ }}+ function doCancel() {{+ if (window.opener) window.close();+ else window.history.back();+ }}+ function toggleDur() {{+ const on = document.getElementById('saveToggle').checked;+ document.getElementById('durSection').style.display = on ? 'block' : 'none';+ }}+ function selDur(val, el) {{+ document.querySelectorAll('.pill').forEach(p => p.classList.remove('sel'));+ el.classList.add('sel');+ document.getElementById('durInput').value = val;+ }}+ function syncBtn() {{+ const btn = document.getElementById('connectBtn');+ if (document.getElementById('apiKey').value.length > 0) {{+ btn.classList.add('ready');+ }} else {{+ btn.classList.remove('ready');+ }}+ }}+ function prepareSubmit() {{+ // nothing extra needed — duration is already in the hidden input+ }}+</script>+</body>+</html>"""+++# ---------------------------------------------------------------------------+# OAuth metadata discovery endpoints+# ---------------------------------------------------------------------------++[email protected]("/.well-known/oauth-authorization-server", include_in_schema=False)+async def oauth_authorization_server_metadata(request: Request) -> JSONResponse:+ """RFC 8414 Authorization Server Metadata for the BYOK OAuth flow."""+ base_url = get_request_base_url(request)+ return JSONResponse(+ {+ "issuer": base_url,+ "authorization_endpoint": f"{base_url}/v1/mcp/oauth/authorize",+ "token_endpoint": f"{base_url}/v1/mcp/oauth/token",+ "response_types_supported": ["code"],+ "grant_types_supported": ["authorization_code"],+ "code_challenge_methods_supported": ["S256"],+ }+ )++[email protected]("/.well-known/oauth-protected-resource", include_in_schema=False)+async def oauth_protected_resource_metadata(request: Request) -> JSONResponse:+ """RFC 9728 Protected Resource Metadata pointing back at this server."""+ base_url = get_request_base_url(request)+ return JSONResponse(+ {+ "resource": base_url,+ "authorization_servers": [base_url],+ }+ )+++# ---------------------------------------------------------------------------+# Authorization endpoint — GET (show form) and POST (process form)+# ---------------------------------------------------------------------------++[email protected]("/v1/mcp/oauth/authorize", include_in_schema=False)+async def byok_authorize_get(+ request: Request,+ client_id: Optional[str] = None,+ redirect_uri: Optional[str] = None,+ response_type: Optional[str] = None,+ code_challenge: Optional[str] = None,+ code_challenge_method: Optional[str] = None,+ state: Optional[str] = None,+ server_id: Optional[str] = None,+) -> HTMLResponse:+ """+ Show the BYOK API-key entry form.++ The MCP client navigates the user here; the user types their API key and+ clicks "Connect & Authorize", which POSTs back to this same path.+ """+ if response_type != "code":+ raise HTTPException(status_code=400, detail="response_type must be 'code'")+ if not redirect_uri:+ raise HTTPException(status_code=400, detail="redirect_uri is required")+ if not code_challenge:+ raise HTTPException(status_code=400, detail="code_challenge is required")++ # Resolve server metadata (name, description items, help URL).+ server_name = "MCP Server"+ access_items: list = []+ help_url = ""+ if server_id:+ try:+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (+ global_mcp_server_manager,+ )++ registry = global_mcp_server_manager.get_registry()+ if server_id in registry:+ srv = registry[server_id]+ server_name = srv.server_name or srv.name+ access_items = list(srv.byok_description or [])+ help_url = srv.byok_api_key_help_url or ""+ except Exception:+ pass++ server_initial = (server_name[0].upper()) if server_name else "S"++ html = _build_authorize_html(+ server_name=server_name,+ server_initial=server_initial,+ client_id=client_id or "",+ redirect_uri=redirect_uri,+ code_challenge=code_challenge,+ code_challenge_method=code_challenge_method or "S256",+ state=state or "",+ server_id=server_id or "",+ access_items=access_items,+ help_url=help_url,+ )+ return HTMLResponse(content=html)++[email protected]("/v1/mcp/oauth/authorize", include_in_schema=False)+async def byok_authorize_post(+ request: Request,+ client_id: str = Form(default=""),+ redirect_uri: str = Form(...),+ code_challenge: str = Form(...),+ code_challenge_method: str = Form(default="S256"),+ state: str = Form(default=""),+ server_id: str = Form(default=""),+ api_key: str = Form(...),+) -> RedirectResponse:+ """+ Process the BYOK API-key form submission.++ Stores a short-lived authorization code and redirects the client back to+ redirect_uri with ?code=...&state=... query parameters.+ """+ _purge_expired_codes()++ # Validate redirect_uri scheme to prevent open redirect+ parsed_uri = urlparse(redirect_uri)+ if parsed_uri.scheme not in ("http", "https"):+ raise HTTPException(status_code=400, detail="Invalid redirect_uri scheme")++ # Reject new codes if the store is at capacity (prevents memory exhaustion+ # from a burst of abandoned OAuth flows).+ if len(_byok_auth_codes) >= _AUTH_CODES_MAX_SIZE:+ raise HTTPException(status_code=503, detail="Too many pending authorization flows")++ if code_challenge_method != "S256":+ raise HTTPException(+ status_code=400, detail="Only S256 code_challenge_method is supported"+ )++ auth_code = str(uuid.uuid4())+ _byok_auth_codes[auth_code] = {+ "api_key": api_key,+ "server_id": server_id,+ "code_challenge": code_challenge,+ "redirect_uri": redirect_uri,+ "user_id": client_id, # external client passes LiteLLM user-id as client_id+ "expires_at": time.time() + _AUTH_CODE_TTL_SECONDS,+ }++ params = urlencode({"code": auth_code, "state": state})+ separator = "&" if "?" in redirect_uri else "?"+ location = f"{redirect_uri}{separator}{params}"+ return RedirectResponse(url=location, status_code=302)+++# ---------------------------------------------------------------------------+# Token endpoint+# ---------------------------------------------------------------------------++[email protected]("/v1/mcp/oauth/token", include_in_schema=False)+async def byok_token(+ request: Request,+ grant_type: str = Form(...),+ code: str = Form(...),+ redirect_uri: str = Form(default=""),+ code_verifier: str = Form(...),+ client_id: str = Form(default=""),+) -> JSONResponse:+ """+ Exchange an authorization code for a short-lived BYOK session JWT.++ 1. Validates the authorization code and PKCE challenge.+ 2. Stores the API key via store_user_credential().+ 3. Issues a signed JWT with type="byok_session".+ """+ from litellm.proxy.proxy_server import master_key, prisma_client++ _purge_expired_codes()++ if grant_type != "authorization_code":+ raise HTTPException(status_code=400, detail="unsupported_grant_type")++ record = _byok_auth_codes.get(code)+ if record is None:+ raise HTTPException(status_code=400, detail="invalid_grant")++ if time.time() > record["expires_at"]:+ del _byok_auth_codes[code]+ raise HTTPException(status_code=400, detail="invalid_grant")++ # PKCE verification+ if not _verify_pkce(code_verifier, record["code_challenge"]):+ raise HTTPException(status_code=400, detail="invalid_grant")++ # Consume the code (one-time use)+ del _byok_auth_codes[code]++ server_id: str = record["server_id"]+ api_key_value: str = record["api_key"]+ # Prefer the user_id that was stored when the code was issued; fall back to+ # whatever client_id the token request supplies (they should match).+ user_id: str = record.get("user_id") or client_id++ if not user_id:+ raise HTTPException(+ status_code=400,+ detail="Cannot determine user_id; pass LiteLLM user id as client_id",+ )++ # Persist the BYOK credential+ if prisma_client is not None:+ try:+ await store_user_credential(+ prisma_client=prisma_client,+ user_id=user_id,+ server_id=server_id,+ credential=api_key_value,+ )+ # Invalidate any cached negative result so the user isn't blocked+ # for up to the TTL period after completing the OAuth flow.+ from litellm.proxy._experimental.mcp_server.server import (+ _invalidate_byok_cred_cache,+ )+ _invalidate_byok_cred_cache(user_id, server_id)+ except Exception as exc:+ verbose_proxy_logger.error(+ "byok_token: failed to store user credential for user=%s server=%s: %s",+ user_id,+ server_id,+ exc,+ )+ raise HTTPException(status_code=500, detail="Failed to store credential")+ else:+ verbose_proxy_logger.warning(+ "byok_token: prisma_client is None — credential not persisted"+ )++ if master_key is None:+ raise HTTPException(+ status_code=500, detail="Master key not configured; cannot issue token"+ )++ now = int(time.time())+ payload = {+ "user_id": user_id,+ "server_id": server_id,+ # "type" distinguishes this from regular proxy auth tokens.+ # The proxy's SSO JWT path uses asymmetric keys (RS256/ES256), so an+ # HS256 token signed with master_key cannot be accepted there.+ "type": "byok_session",+ "iat": now,+ "exp": now + 3600,+ }+ access_token = jwt.encode(payload, cast(str, master_key), algorithm="HS256")++ return JSONResponse(+ {+ "access_token": access_token,+ "token_type": "bearer",+ "expires_in": 3600,+ }+ )diff --git a/litellm/proxy/_experimental/mcp_server/db.py b/litellm/proxy/_experimental/mcp_server/db.pyindex 1bc7e8f8a9d..4c6735bacd3 100644--- a/litellm/proxy/_experimental/mcp_server/db.py+++ b/litellm/proxy/_experimental/mcp_server/db.py@@ -13,6 +13,7 @@ from litellm.proxy._types import ()from litellm.proxy.common_utils.encrypt_decrypt_utils import (_get_salt_key,+ decrypt_value_helper,encrypt_value_helper,)from litellm.proxy.utils import PrismaClient@@ -68,6 +69,10 @@ def _prepare_mcp_server_data(# mcp_access_groups is already List[str], no serialization needed+ # Force include is_byok even when False (exclude_none=True would not drop it,+ # but be explicit to ensure a False value is always written to the DB).+ data_dict["is_byok"] = getattr(data, "is_byok", False)+return data_dict@@ -375,3 +380,74 @@ async def rotate_mcp_server_credentials_master_key("updated_by": touched_by,},)+++async def store_user_credential(+ prisma_client: PrismaClient,+ user_id: str,+ server_id: str,+ 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(+ 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_credential(+ prisma_client: PrismaClient,+ user_id: str,+ 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}}+ )+ if row is None:+ return None+ try:+ return base64.urlsafe_b64decode(row.credential_b64).decode()+ except Exception:+ # Fall back to nacl decryption for credentials stored by older code+ return decrypt_value_helper(+ value=row.credential_b64,+ key="byok_credential",+ exception_type="debug",+ return_original_value=False,+ )+++async def has_user_credential(+ prisma_client: PrismaClient,+ user_id: str,+ server_id: str,+) -> bool:+ """Return True if the user has a stored credential for this server."""+ row = await prisma_client.db.litellm_mcpusercredentials.find_unique(+ where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}}+ )+ return row is not None+++async def delete_user_credential(+ prisma_client: PrismaClient,+ user_id: str,+ server_id: str,+) -> None:+ """Delete the user's stored credential for a BYOK MCP server."""+ await prisma_client.db.litellm_mcpusercredentials.delete(+ where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}}+ )diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.pyindex 51bdfea172b..7c17da36bb7 100644--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py@@ -650,6 +650,9 @@ class MCPServerManager:tool_name_to_description=_deserialize_json_dict(getattr(mcp_server, "tool_name_to_description", None)),+ is_byok=bool(getattr(mcp_server, "is_byok", False)),+ byok_description=getattr(mcp_server, "byok_description", None) or [],+ byok_api_key_help_url=getattr(mcp_server, "byok_api_key_help_url", None),)return new_server@@ -2657,6 +2660,9 @@ class MCPServerManager:registration_url=server.registration_url,allow_all_keys=server.allow_all_keys,available_on_public_internet=server.available_on_public_internet,+ is_byok=server.is_byok,+ byok_description=server.byok_description,+ byok_api_key_help_url=server.byok_api_key_help_url,)async def get_all_mcp_servers_unfiltered(self) -> List[LiteLLM_MCPServerTable]:diff --git a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.pyindex 21d39c97d7c..bcbf91e5c56 100644--- a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py+++ b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py@@ -3,6 +3,7 @@ This module is used to generate MCP tools from OpenAPI specs."""import asyncio+import contextvarsimport jsonimport osfrom pathlib import PurePosixPath@@ -22,6 +23,13 @@ from litellm.proxy._experimental.mcp_server.tool_registry import (BASE_URL = ""HEADERS: Dict[str, str] = {}+# Per-request auth header override for BYOK servers.+# Set this ContextVar before calling a local tool handler to inject the user's+# stored credential into the HTTP request made by the tool function closure.+_request_auth_header: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar(+ "_request_auth_header", default=None+)+def _sanitize_path_parameter_value(param_value: Any, param_name: str) -> str:"""Ensure path params cannot introduce directory traversal."""@@ -211,6 +219,15 @@ def create_tool_function(The function safely handles parameter names that aren't valid Python identifiersby using **kwargs instead of named parameters."""+ # Allow per-request auth override (e.g. BYOK credential set via ContextVar).+ # The ContextVar holds the full Authorization header value, including the+ # correct prefix (Bearer / ApiKey / Basic) formatted by the caller in+ # server.py based on the server's configured auth_type.+ effective_headers = dict(headers)+ override_auth = _request_auth_header.get()+ if override_auth:+ effective_headers["Authorization"] = override_auth+# Build URL from base_url and pathurl = base_url + path@@ -263,20 +280,20 @@ def create_tool_function(client = get_async_httpx_client(llm_provider=httpxSpecialProvider.MCP)if original_method == "get":- response = await client.get(url, params=params, headers=headers)+ response = await client.get(url, params=params, headers=effective_headers)elif original_method == "post":response = await client.post(- url, params=params, json=json_body, headers=headers+ url, params=params, json=json_body, headers=effective_headers)elif original_method == "put":response = await client.put(- url, params=params, json=json_body, headers=headers+ url, params=params, json=json_body, headers=effective_headers)elif original_method == "delete":- response = await client.delete(url, params=params, headers=headers)+ response = await client.delete(url, params=params, headers=effective_headers)elif original_method == "patch":response = await client.patch(- url, params=params, json=json_body, headers=headers+ url, params=params, json=json_body, headers=effective_headers)else:return f"Unsupported HTTP method: {original_method}"diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex b131800e950..5c063839304 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -5,6 +5,7 @@ LiteLLM MCP Server Routesimport asyncioimport contextlib+import timeimport tracebackimport uuidfrom datetime import datetime@@ -54,6 +55,32 @@ from litellm.types.mcp_server.mcp_server_manager import MCPInfo, MCPServerfrom litellm.types.utils import CallTypes, StandardLoggingMCPToolCallfrom litellm.utils import Rules, client, function_setup+# Short-lived in-memory cache for BYOK credentials.+# Keyed by (user_id, server_id); value is (credential_or_None, monotonic_timestamp).+# Storing the credential value (not just a bool) means _get_byok_credential and+# _check_byok_credential share a single DB round-trip per TTL window.+_byok_cred_cache: Dict[Tuple[str, str], Tuple[Optional[str], float]] = {}+_BYOK_CRED_CACHE_TTL = 60 # seconds+_BYOK_CRED_CACHE_MAX_SIZE = 4096 # cap to prevent unbounded growth+++def _invalidate_byok_cred_cache(user_id: str, server_id: str) -> None:+ """Remove a (user_id, server_id) entry from the BYOK credential cache.++ Call this after storing or deleting a credential so subsequent calls+ see the fresh value rather than a stale cached result.+ """+ _byok_cred_cache.pop((user_id, server_id), None)+++def _write_byok_cred_cache(+ user_id: str, server_id: str, credential: Optional[str]+) -> None:+ """Write a credential value to the cache, evicting all entries if at capacity."""+ if len(_byok_cred_cache) >= _BYOK_CRED_CACHE_MAX_SIZE:+ _byok_cred_cache.clear()+ _byok_cred_cache[(user_id, server_id)] = (credential, time.monotonic())+# Check if MCP is available# "mcp" requires python 3.10 or higher, but several litellm users use python 3.8# We're making this conditional import to avoid breaking users who use python 3.8.@@ -118,6 +145,9 @@ if MCP_AVAILABLE:from litellm.proxy._experimental.mcp_server.mcp_server_manager import (global_mcp_server_manager,)+ from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import (+ _request_auth_header,+ )from litellm.proxy._experimental.mcp_server.sse_transport import SseServerTransportfrom litellm.proxy._experimental.mcp_server.tool_registry import (global_mcp_tool_registry,@@ -1498,6 +1528,122 @@ if MCP_AVAILABLE:)return name+ async def _get_byok_credential(+ mcp_server: MCPServer,+ user_api_key_auth: Optional[UserAPIKeyAuth],+ ) -> Optional[str]:+ """Retrieve the stored BYOK credential for a user+server pair.++ Uses the shared _byok_cred_cache to avoid a DB round-trip on every+ tool call within the TTL window.+ """+ if not mcp_server.is_byok:+ return None+ user_id = (user_api_key_auth.user_id if user_api_key_auth else None) or ""+ if not user_id:+ return None++ cache_key = (user_id, mcp_server.server_id)+ cached = _byok_cred_cache.get(cache_key)+ if cached is not None:+ credential, ts = cached+ if time.monotonic() - ts < _BYOK_CRED_CACHE_TTL:+ return credential++ from litellm.proxy._experimental.mcp_server.db import get_user_credential+ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is None:+ return None+ credential = await get_user_credential(+ prisma_client=prisma_client,+ user_id=user_id,+ server_id=mcp_server.server_id,+ )+ _write_byok_cred_cache(user_id, mcp_server.server_id, credential)+ return credential++ async def _check_byok_credential(+ mcp_server: MCPServer,+ user_api_key_auth: Optional[UserAPIKeyAuth],+ ) -> None:+ """+ If the MCP server is BYOK-enabled, verify that the requesting user has a+ stored credential. When no credential is found, raise an HTTP 401 with a+ WWW-Authenticate header that points the MCP client to our OAuth metadata+ endpoint so it can drive the authorization flow.+ """+ if not mcp_server.is_byok:+ return++ user_id = (user_api_key_auth.user_id if user_api_key_auth else None) or ""+ if not user_id:+ raise HTTPException(+ status_code=401,+ detail={+ "error": "byok_auth_required",+ "server_id": mcp_server.server_id,+ "server_name": mcp_server.server_name or mcp_server.name,+ "message": "User identity is required for BYOK servers",+ },+ headers={+ "WWW-Authenticate": 'Bearer resource_metadata="/.well-known/oauth-protected-resource"'+ },+ )++ # Check shared credential cache before hitting the DB.+ cache_key = (user_id, mcp_server.server_id)+ cached = _byok_cred_cache.get(cache_key)+ if cached is not None:+ cached_cred, ts = cached+ if time.monotonic() - ts < _BYOK_CRED_CACHE_TTL:+ if cached_cred is None:+ raise HTTPException(+ status_code=401,+ detail={+ "error": "byok_auth_required",+ "server_id": mcp_server.server_id,+ "server_name": mcp_server.server_name or mcp_server.name,+ "message": (+ "No stored credential found for this BYOK server. "+ "Complete the OAuth authorization flow to provide your API key."+ ),+ },+ headers={+ "WWW-Authenticate": 'Bearer resource_metadata="/.well-known/oauth-protected-resource"'+ },+ )+ return++ from litellm.proxy._experimental.mcp_server.db import get_user_credential+ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is None:+ return++ credential = await get_user_credential(+ prisma_client=prisma_client,+ user_id=user_id,+ server_id=mcp_server.server_id,+ )+ _write_byok_cred_cache(user_id, mcp_server.server_id, credential)+ if credential is None:+ raise HTTPException(+ status_code=401,+ detail={+ "error": "byok_auth_required",+ "server_id": mcp_server.server_id,+ "server_name": mcp_server.server_name or mcp_server.name,+ "message": (+ "No stored credential found for this BYOK server. "+ "Complete the OAuth authorization flow to provide your API key."+ ),+ },+ headers={+ "WWW-Authenticate": 'Bearer resource_metadata="/.well-known/oauth-protected-resource"'+ },+ )+async def execute_mcp_tool(name: str,arguments: Dict[str, Any],@@ -1573,57 +1719,99 @@ if MCP_AVAILABLE:"mcp_tool_call_metadata"] = standard_logging_mcp_tool_calllitellm_logging_obj.model = f"MCP: {name}"+ # Resolve the MCP server early so BYOK checks and credential injection+ # apply to ALL dispatch paths (local tool registry AND managed MCP server).+ if mcp_server is None:+ mcp_server = global_mcp_server_manager._get_mcp_server_from_tool_name(name)++ if mcp_server:+ standard_logging_mcp_tool_call["mcp_server_cost_info"] = (+ mcp_server.mcp_info or {}+ ).get("mcp_server_cost_info")+ if litellm_logging_obj:+ litellm_logging_obj.model_call_details[+ "mcp_tool_call_metadata"+ ] = standard_logging_mcp_tool_call++ # BYOK: retrieve the stored per-user credential. A single DB call+ # both checks existence and fetches the value, avoiding a double query.+ if mcp_server.is_byok and not mcp_auth_header:+ byok_cred = await _get_byok_credential(mcp_server, user_api_key_auth)+ if byok_cred is None:+ raise HTTPException(+ status_code=401,+ detail={+ "error": "byok_auth_required",+ "server_id": mcp_server.server_id,+ "server_name": mcp_server.server_name or mcp_server.name,+ "message": (+ "No stored credential found for this BYOK server. "+ "Complete the OAuth authorization flow to provide your API key."+ ),+ },+ headers={+ "WWW-Authenticate": 'Bearer resource_metadata="/.well-known/oauth-protected-resource"'+ },+ )+ mcp_auth_header = byok_cred+ elif mcp_server.is_byok:+ # External auth header supplied; still enforce user-identity check.+ await _check_byok_credential(mcp_server, user_api_key_auth)+# Check if tool exists in local registry first (for OpenAPI-based tools)# These tools are registered with their prefixed names#########################################################local_tool = global_mcp_tool_registry.get_tool(name)if local_tool:verbose_logger.debug(f"Executing local registry tool: {name}")- local_content = await _handle_local_mcp_tool(name, arguments)+ # For BYOK servers the credential must be injected via a ContextVar+ # because the tool function has headers baked into its closure.+ # Pre-format the full Authorization header value using the server's+ # configured auth_type so the generator doesn't need to know the prefix.+ auth_header_value: Optional[str] = None+ if mcp_auth_header:+ server_auth_type = getattr(mcp_server, "auth_type", None) if mcp_server else None+ if server_auth_type == MCPAuth.api_key:+ auth_header_value = f"ApiKey {mcp_auth_header}"+ elif server_auth_type == MCPAuth.basic:+ auth_header_value = f"Basic {mcp_auth_header}"+ else:+ auth_header_value = f"Bearer {mcp_auth_header}"+ _auth_token = _request_auth_header.set(auth_header_value)+ try:+ local_content = await _handle_local_mcp_tool(name, arguments)+ finally:+ _request_auth_header.reset(_auth_token)response = CallToolResult(content=cast(Any, local_content), isError=False)# Try managed MCP server tool (pass the full prefixed name)# Primary and recommended way to use external MCP servers#########################################################- else:- # If we haven't already resolved the server, do it now for dispatch- if mcp_server is None:- mcp_server = global_mcp_server_manager._get_mcp_server_from_tool_name(- name- )- if mcp_server:- standard_logging_mcp_tool_call["mcp_server_cost_info"] = (- mcp_server.mcp_info or {}- ).get("mcp_server_cost_info")- # Update model_call_details with the cost info- if litellm_logging_obj:- litellm_logging_obj.model_call_details[- "mcp_tool_call_metadata"- ] = standard_logging_mcp_tool_call- response = await _handle_managed_mcp_tool(- server_name=server_name,- name=original_tool_name, # Pass the full name (potentially prefixed)- arguments=arguments,- user_api_key_auth=user_api_key_auth,- mcp_auth_header=mcp_auth_header,- mcp_server_auth_headers=mcp_server_auth_headers,- oauth2_headers=oauth2_headers,- raw_headers=raw_headers,- litellm_logging_obj=litellm_logging_obj,- host_progress_callback=host_progress_callback,- )+ elif mcp_server:+ response = await _handle_managed_mcp_tool(+ server_name=server_name,+ name=original_tool_name, # Pass the full name (potentially prefixed)+ arguments=arguments,+ user_api_key_auth=user_api_key_auth,+ mcp_auth_header=mcp_auth_header,+ mcp_server_auth_headers=mcp_server_auth_headers,+ oauth2_headers=oauth2_headers,+ raw_headers=raw_headers,+ litellm_logging_obj=litellm_logging_obj,+ host_progress_callback=host_progress_callback,+ )- # Fall back to local tool registry with original name (legacy support)- #########################################################- # Deprecated: Local MCP Server Tool- #########################################################- else:- local_content = await _handle_local_mcp_tool(- original_tool_name, arguments- )- response = CallToolResult(- content=cast(Any, local_content), isError=False- )+ # Fall back to local tool registry with original name (legacy support)+ #########################################################+ # Deprecated: Local MCP Server Tool+ #########################################################+ else:+ local_content = await _handle_local_mcp_tool(+ original_tool_name, arguments+ )+ response = CallToolResult(+ content=cast(Any, local_content), isError=False+ )return responsediff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 9b07d44deb6..95dabd8bfd0 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -1108,6 +1108,9 @@ class NewMCPServerRequest(LiteLLMPydanticObjectBase):registration_url: Optional[str] = Noneallow_all_keys: bool = Falseavailable_on_public_internet: bool = True+ is_byok: bool = False+ byok_description: List[str] = Field(default_factory=list)+ byok_api_key_help_url: Optional[str] = None@model_validator(mode="before")@classmethod@@ -1164,6 +1167,9 @@ class UpdateMCPServerRequest(LiteLLMPydanticObjectBase):registration_url: Optional[str] = Noneallow_all_keys: bool = Falseavailable_on_public_internet: bool = True+ is_byok: bool = False+ byok_description: List[str] = Field(default_factory=list)+ byok_api_key_help_url: Optional[str] = None@model_validator(mode="before")@classmethod@@ -1223,12 +1229,26 @@ class LiteLLM_MCPServerTable(LiteLLMPydanticObjectBase):registration_url: Optional[str] = Noneallow_all_keys: bool = Falseavailable_on_public_internet: bool = True+ is_byok: bool = False+ byok_description: List[str] = Field(default_factory=list)+ byok_api_key_help_url: Optional[str] = None+ has_user_credential: Optional[bool] = Noneclass MakeMCPServersPublicRequest(LiteLLMPydanticObjectBase):mcp_server_ids: List[str]+class MCPUserCredentialRequest(LiteLLMPydanticObjectBase):+ credential: str+ save: bool = True+++class MCPUserCredentialResponse(LiteLLMPydanticObjectBase):+ server_id: str+ has_credential: bool++######## Skills API Types ########diff --git a/litellm/proxy/management_endpoints/mcp_management_endpoints.py b/litellm/proxy/management_endpoints/mcp_management_endpoints.pyindex 8c4d4e7937e..b48db72a536 100644--- a/litellm/proxy/management_endpoints/mcp_management_endpoints.py+++ b/litellm/proxy/management_endpoints/mcp_management_endpoints.py@@ -78,8 +78,11 @@ if MCP_AVAILABLE:from litellm.proxy._experimental.mcp_server.db import (create_mcp_server,delete_mcp_server,+ delete_user_credential,get_all_mcp_servers_for_user,get_mcp_server,+ get_user_credential,+ store_user_credential,update_mcp_server,)from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (@@ -98,6 +101,8 @@ if MCP_AVAILABLE:LiteLLM_MCPServerTable,LitellmUserRoles,MakeMCPServersPublicRequest,+ MCPUserCredentialRequest,+ MCPUserCredentialResponse,NewMCPServerRequest,SpecialMCPServerName,UpdateMCPServerRequest,@@ -599,6 +604,25 @@ if MCP_AVAILABLE:server.mcp_info = {}server.mcp_info["is_public"] = True+ # Annotate has_user_credential for BYOK servers (single batched query)+ from litellm.proxy.proxy_server import prisma_client as _byok_prisma_client++ user_id = user_api_key_dict.user_id or ""+ if user_id and _byok_prisma_client is not None:+ byok_server_ids = [+ s.server_id+ for s in redacted_mcp_servers+ if getattr(s, "is_byok", False)+ ]+ if byok_server_ids:+ cred_rows = await _byok_prisma_client.db.litellm_mcpusercredentials.find_many(+ where={"user_id": user_id, "server_id": {"in": byok_server_ids}}+ )+ cred_set = {r.server_id for r in cred_rows}+ for server in redacted_mcp_servers:+ if getattr(server, "is_byok", False):+ server.has_user_credential = server.server_id in cred_set+# Virtual keys only get a sanitized discovery view.if is_restricted_virtual_key:return _sanitize_mcp_server_list_for_virtual_key(redacted_mcp_servers)@@ -1036,6 +1060,80 @@ if MCP_AVAILABLE:return Response(status_code=status.HTTP_202_ACCEPTED)+ @router.post(+ "/server/{server_id}/user-credential",+ description="Store or update the calling user's API key for a BYOK MCP server",+ dependencies=[Depends(user_api_key_auth)],+ response_model=MCPUserCredentialResponse,+ )+ @management_endpoint_wrapper+ async def store_mcp_user_credential(+ server_id: str,+ payload: MCPUserCredentialRequest,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+ ):+ """Store a BYOK credential for 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"},+ )+ if not getattr(mcp_server, "is_byok", False):+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail={"error": "This MCP server does not support BYOK credentials"},+ )+ 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"},+ )+ if payload.save:+ await store_user_credential(prisma_client, user_id, server_id, payload.credential)+ from litellm.proxy._experimental.mcp_server.server import (+ _invalidate_byok_cred_cache,+ )+ _invalidate_byok_cred_cache(user_id, server_id)+ return MCPUserCredentialResponse(server_id=server_id, has_credential=True)+ # save=False: credential not persisted+ return MCPUserCredentialResponse(server_id=server_id, has_credential=False)++ @router.delete(+ "/server/{server_id}/user-credential",+ description="Delete the calling user's stored API key for a BYOK MCP server",+ dependencies=[Depends(user_api_key_auth)],+ response_model=MCPUserCredentialResponse,+ )+ @management_endpoint_wrapper+ async def delete_mcp_user_credential(+ server_id: str,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+ ):+ """Remove the calling user's BYOK 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"},+ )+ try:+ await delete_user_credential(prisma_client, user_id, server_id)+ except Exception:+ pass # Already deleted or didn't exist+ from litellm.proxy._experimental.mcp_server.server import (+ _invalidate_byok_cred_cache,+ )+ _invalidate_byok_cred_cache(user_id, server_id)+ return MCPUserCredentialResponse(server_id=server_id, has_credential=False)+@router.put("/server",description="Allows deleting mcp serves in the db",diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex ad31ff33802..33d84cd7078 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -231,6 +231,9 @@ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingfrom litellm.litellm_core_utils.sensitive_data_masker import SensitiveDataMaskerfrom litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandlerfrom litellm.llms.vertex_ai.vertex_llm_base import VertexBase+from litellm.proxy._experimental.mcp_server.byok_oauth_endpoints import (+ router as mcp_byok_oauth_router,+)from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (router as mcp_discoverable_endpoints_router,)@@ -12975,6 +12978,7 @@ app.include_router(vector_store_files_router)app.include_router(credential_router)app.include_router(llm_passthrough_router)app.include_router(mcp_management_router)+app.include_router(mcp_byok_oauth_router)app.include_router(anthropic_router)app.include_router(anthropic_skills_router)app.include_router(evals_router)diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prismaindex 5e1ba479298..43972724ecc 100644--- a/litellm/proxy/schema.prisma+++ b/litellm/proxy/schema.prisma@@ -305,6 +305,22 @@ model LiteLLM_MCPServerTable {registration_url String?allow_all_keys Boolean @default(false)available_on_public_internet Boolean @default(true)+ spec_path String?+ is_byok Boolean @default(false)+ byok_description String[] @default([])+ byok_api_key_help_url String?+}++// Per-user BYOK credentials for MCP servers+model LiteLLM_MCPUserCredentials {+ id String @id @default(uuid())+ user_id String+ server_id String+ credential_b64 String+ created_at DateTime @default(now()) @map("created_at")+ updated_at DateTime @default(now()) @updatedAt @map("updated_at")++ @@unique([user_id, server_id])}// Generate Tokens for Proxydiff --git a/litellm/types/mcp_server/mcp_server_manager.py b/litellm/types/mcp_server/mcp_server_manager.pyindex 7f6a8b3ea24..d94795fda2e 100644--- a/litellm/types/mcp_server/mcp_server_manager.py+++ b/litellm/types/mcp_server/mcp_server_manager.py@@ -55,6 +55,9 @@ class MCPServer(BaseModel):access_groups: Optional[List[str]] = Noneallow_all_keys: bool = Falseavailable_on_public_internet: bool = True+ is_byok: bool = False+ byok_description: List[str] = []+ byok_api_key_help_url: Optional[str] = Nonecreated_at: Optional[datetime] = Noneupdated_at: Optional[datetime] = Nonemodel_config = ConfigDict(arbitrary_types_allowed=True)diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_byok_oauth_endpoints.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_byok_oauth_endpoints.pynew file mode 100644index 00000000000..a7391666cda--- /dev/null+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_byok_oauth_endpoints.py@@ -0,0 +1,517 @@+"""+Unit tests for the BYOK OAuth 2.1 authorization server endpoints.++Covers:+- _verify_pkce helper+- OAuth metadata discovery endpoints+- Authorization GET / POST endpoints+- Token endpoint (PKCE verification, credential storage, JWT issuance)+- 401 challenge in execute_mcp_tool (_check_byok_credential)+"""++import base64+import hashlib+import time+import uuid+from typing import Any, Optional+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from fastapi import HTTPException+from fastapi.testclient import TestClient++from litellm.proxy._experimental.mcp_server.byok_oauth_endpoints import (+ _byok_auth_codes,+ _verify_pkce,+ router,+)+from litellm.proxy._types import MCPTransport++# ---------------------------------------------------------------------------+# _verify_pkce+# ---------------------------------------------------------------------------+++def _make_challenge(verifier: str) -> str:+ digest = hashlib.sha256(verifier.encode()).digest()+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode()+++def test_verify_pkce_valid():+ verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"+ challenge = _make_challenge(verifier)+ assert _verify_pkce(verifier, challenge) is True+++def test_verify_pkce_invalid():+ assert _verify_pkce("wrong_verifier", _make_challenge("right_verifier")) is False+++def test_verify_pkce_tampered_challenge():+ verifier = "test_verifier_value"+ challenge = _make_challenge(verifier)+ # Flip one character to tamper with the challenge+ tampered = challenge[:-1] + ("A" if challenge[-1] != "A" else "B")+ assert _verify_pkce(verifier, tampered) is False+++# ---------------------------------------------------------------------------+# Minimal FastAPI app for testing the router+# ---------------------------------------------------------------------------++from fastapi import FastAPI++_test_app = FastAPI()+_test_app.include_router(router)+++def client():+ return TestClient(_test_app, raise_server_exceptions=False)+++# ---------------------------------------------------------------------------+# OAuth metadata endpoints+# ---------------------------------------------------------------------------+++def test_oauth_authorization_server_metadata(client):+ resp = client.get("/.well-known/oauth-authorization-server")+ assert resp.status_code == 200+ data = resp.json()+ assert "issuer" in data+ assert data["authorization_endpoint"].endswith("/v1/mcp/oauth/authorize")+ assert data["token_endpoint"].endswith("/v1/mcp/oauth/token")+ assert "S256" in data["code_challenge_methods_supported"]+++def test_oauth_protected_resource_metadata(client):+ resp = client.get("/.well-known/oauth-protected-resource")+ assert resp.status_code == 200+ data = resp.json()+ assert "resource" in data+ assert "authorization_servers" in data+ assert len(data["authorization_servers"]) == 1+++# ---------------------------------------------------------------------------+# Authorization GET endpoint+# ---------------------------------------------------------------------------+++def test_authorize_get_returns_html(client):+ resp = client.get(+ "/v1/mcp/oauth/authorize",+ params={+ "client_id": "test-client",+ "redirect_uri": "https://client.example.com/callback",+ "response_type": "code",+ "code_challenge": "abc123",+ "code_challenge_method": "S256",+ "state": "xyz",+ "server_id": "my-server",+ },+ follow_redirects=False,+ )+ assert resp.status_code == 200+ assert "text/html" in resp.headers["content-type"]+ # The button text is HTML-entity-escaped in the template+ assert "Connect & Authorize" in resp.text+ # Hidden fields should be embedded+ assert "my-server" in resp.text+ assert "abc123" in resp.text+++def test_authorize_get_missing_redirect_uri(client):+ resp = client.get(+ "/v1/mcp/oauth/authorize",+ params={+ "response_type": "code",+ "code_challenge": "abc",+ },+ follow_redirects=False,+ )+ assert resp.status_code == 400+++def test_authorize_get_wrong_response_type(client):+ resp = client.get(+ "/v1/mcp/oauth/authorize",+ params={+ "redirect_uri": "https://example.com/cb",+ "response_type": "token",+ "code_challenge": "abc",+ },+ follow_redirects=False,+ )+ assert resp.status_code == 400+++# ---------------------------------------------------------------------------+# Authorization POST endpoint+# ---------------------------------------------------------------------------+++def test_authorize_post_creates_code_and_redirects(client):+ verifier = "my_code_verifier_that_is_long_enough_43chars"+ challenge = _make_challenge(verifier)++ resp = client.post(+ "/v1/mcp/oauth/authorize",+ data={+ "client_id": "user-123",+ "redirect_uri": "https://client.example.com/callback",+ "code_challenge": challenge,+ "code_challenge_method": "S256",+ "state": "st_abc",+ "server_id": "server-xyz",+ "api_key": "sk-supersecretkey",+ },+ follow_redirects=False,+ )+ assert resp.status_code == 302+ location = resp.headers["location"]+ assert "code=" in location+ assert "st_abc" in location++ # Extract the code from the redirect URL+ from urllib.parse import parse_qs, urlparse++ qs = parse_qs(urlparse(location).query)+ code = qs["code"][0]+ assert code in _byok_auth_codes+ entry = _byok_auth_codes[code]+ assert entry["api_key"] == "sk-supersecretkey"+ assert entry["server_id"] == "server-xyz"+ assert entry["user_id"] == "user-123"+ assert entry["code_challenge"] == challenge+++def test_authorize_post_unsupported_method(client):+ resp = client.post(+ "/v1/mcp/oauth/authorize",+ data={+ "client_id": "u",+ "redirect_uri": "https://example.com/cb",+ "code_challenge": "abc",+ "code_challenge_method": "plain",+ "state": "",+ "server_id": "s",+ "api_key": "key",+ },+ follow_redirects=False,+ )+ assert resp.status_code == 400+++# ---------------------------------------------------------------------------+# Token endpoint+# ---------------------------------------------------------------------------+++def _insert_code(+ api_key: str,+ server_id: str,+ user_id: str,+ challenge: str,+ redirect_uri: str,+ ttl: int = 300,+) -> str:+ code = str(uuid.uuid4())+ _byok_auth_codes[code] = {+ "api_key": api_key,+ "server_id": server_id,+ "user_id": user_id,+ "code_challenge": challenge,+ "redirect_uri": redirect_uri,+ "expires_at": time.time() + ttl,+ }+ return code+++async def test_token_endpoint_success():+ """Happy path: valid code + PKCE → credential stored → JWT returned."""+ verifier = "my_test_code_verifier_value_long_enough_yes"+ challenge = _make_challenge(verifier)+ code = _insert_code(+ api_key="sk-myapikey",+ server_id="server-1",+ user_id="user-42",+ challenge=challenge,+ redirect_uri="https://example.com/cb",+ )++ mock_prisma = MagicMock()+ mock_store = AsyncMock()+ test_master_key = "test_master_key_value"++ with patch(+ "litellm.proxy._experimental.mcp_server.byok_oauth_endpoints.store_user_credential",+ mock_store,+ ), patch(+ "litellm.proxy._experimental.mcp_server.byok_oauth_endpoints.router",+ ):+ # Import the actual handler function directly+ from litellm.proxy._experimental.mcp_server.byok_oauth_endpoints import (+ byok_token,+ )++ mock_request = MagicMock()+ # Patch module-level globals in the function's module+ with patch(+ "litellm.proxy._experimental.mcp_server.byok_oauth_endpoints.store_user_credential",+ mock_store,+ ):+ import litellm.proxy._experimental.mcp_server.byok_oauth_endpoints as mod++ original_prisma = None+ original_master_key = None++ # Temporarily inject our test values+ with patch(+ "litellm.proxy.proxy_server.prisma_client", mock_prisma+ ), patch("litellm.proxy.proxy_server.master_key", test_master_key):+ result = await byok_token(+ request=mock_request,+ grant_type="authorization_code",+ code=code,+ redirect_uri="https://example.com/cb",+ code_verifier=verifier,+ client_id="user-42",+ )++ assert result.status_code == 200+ body = result.body+ import json++ data = json.loads(body)+ assert "access_token" in data+ assert data["token_type"] == "bearer"+ assert data["expires_in"] == 3600++ # Verify JWT payload+ import jwt as pyjwt++ payload = pyjwt.decode(+ data["access_token"], test_master_key, algorithms=["HS256"]+ )+ assert payload["user_id"] == "user-42"+ assert payload["server_id"] == "server-1"+ assert payload["type"] == "byok_session"++ # Auth code was consumed+ assert code not in _byok_auth_codes++ # store_user_credential was called+ mock_store.assert_awaited_once_with(+ prisma_client=mock_prisma,+ user_id="user-42",+ server_id="server-1",+ credential="sk-myapikey",+ )+++async def test_token_endpoint_invalid_code():+ from litellm.proxy._experimental.mcp_server.byok_oauth_endpoints import byok_token++ mock_request = MagicMock()+ with pytest.raises(HTTPException) as exc_info:+ with patch("litellm.proxy.proxy_server.prisma_client", MagicMock()), patch(+ "litellm.proxy.proxy_server.master_key", "key"+ ):+ await byok_token(+ request=mock_request,+ grant_type="authorization_code",+ code="nonexistent-code",+ redirect_uri="",+ code_verifier="anything",+ client_id="u",+ )+ assert exc_info.value.status_code == 400+ assert "invalid_grant" in str(exc_info.value.detail)+++async def test_token_endpoint_expired_code():+ verifier = "exp_verifier_that_is_long_enough_to_be_valid"+ challenge = _make_challenge(verifier)+ code = _insert_code(+ api_key="key",+ server_id="s",+ user_id="u",+ challenge=challenge,+ redirect_uri="https://cb",+ ttl=-10, # already expired+ )++ from litellm.proxy._experimental.mcp_server.byok_oauth_endpoints import byok_token++ mock_request = MagicMock()+ with pytest.raises(HTTPException) as exc_info:+ with patch("litellm.proxy.proxy_server.prisma_client", MagicMock()), patch(+ "litellm.proxy.proxy_server.master_key", "key"+ ):+ await byok_token(+ request=mock_request,+ grant_type="authorization_code",+ code=code,+ redirect_uri="",+ code_verifier=verifier,+ client_id="u",+ )+ assert exc_info.value.status_code == 400+++async def test_token_endpoint_wrong_verifier():+ verifier = "correct_verifier_value_that_is_long_enough"+ challenge = _make_challenge(verifier)+ code = _insert_code(+ api_key="key",+ server_id="s",+ user_id="u",+ challenge=challenge,+ redirect_uri="https://cb",+ )++ from litellm.proxy._experimental.mcp_server.byok_oauth_endpoints import byok_token++ mock_request = MagicMock()+ with pytest.raises(HTTPException) as exc_info:+ with patch("litellm.proxy.proxy_server.prisma_client", MagicMock()), patch(+ "litellm.proxy.proxy_server.master_key", "key"+ ):+ await byok_token(+ request=mock_request,+ grant_type="authorization_code",+ code=code,+ redirect_uri="",+ code_verifier="wrong_verifier_value_that_wont_match",+ client_id="u",+ )+ assert exc_info.value.status_code == 400+ assert "invalid_grant" in str(exc_info.value.detail)+++async def test_token_endpoint_unsupported_grant_type():+ from litellm.proxy._experimental.mcp_server.byok_oauth_endpoints import byok_token++ mock_request = MagicMock()+ with pytest.raises(HTTPException) as exc_info:+ with patch("litellm.proxy.proxy_server.prisma_client", MagicMock()), patch(+ "litellm.proxy.proxy_server.master_key", "key"+ ):+ await byok_token(+ request=mock_request,+ grant_type="client_credentials",+ code="any",+ redirect_uri="",+ code_verifier="v",+ client_id="u",+ )+ assert exc_info.value.status_code == 400+ assert "unsupported_grant_type" in str(exc_info.value.detail)+++# ---------------------------------------------------------------------------+# _check_byok_credential (the 401 challenge in execute_mcp_tool)+# ---------------------------------------------------------------------------+++async def test_check_byok_credential_not_byok():+ """Non-BYOK servers should pass through without any DB check."""+ from litellm.proxy._experimental.mcp_server.server import _check_byok_credential+ from litellm.types.mcp_server.mcp_server_manager import MCPServer++ server = MCPServer(+ server_id="s1",+ name="normal-server",+ transport=MCPTransport.http,+ is_byok=False,+ )+ # Should not raise+ await _check_byok_credential(server, None)+++async def test_check_byok_credential_no_user_id():+ """BYOK server with no user identity → 401."""+ from litellm.proxy._experimental.mcp_server.server import _check_byok_credential+ from litellm.types.mcp_server.mcp_server_manager import MCPServer++ server = MCPServer(+ server_id="byok-1",+ name="byok-server",+ transport=MCPTransport.http,+ is_byok=True,+ )+ with pytest.raises(HTTPException) as exc_info:+ await _check_byok_credential(server, None)++ assert exc_info.value.status_code == 401+ assert "WWW-Authenticate" in (exc_info.value.headers or {}) # type: ignore[operator]+ assert "byok_auth_required" in str(exc_info.value.detail)+++async def test_check_byok_credential_missing_credential():+ """BYOK server with a known user but no stored credential → 401."""+ from litellm.proxy._experimental.mcp_server.server import _check_byok_credential+ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.types.mcp_server.mcp_server_manager import MCPServer++ server = MCPServer(+ server_id="byok-2",+ name="byok-server",+ transport=MCPTransport.http,+ is_byok=True,+ )+ user_auth = UserAPIKeyAuth(user_id="user-99", api_key="sk-test")++ mock_prisma = MagicMock()++ with patch(+ "litellm.proxy._experimental.mcp_server.db.get_user_credential",+ new=AsyncMock(return_value=None),+ ), patch("litellm.proxy.proxy_server.prisma_client", mock_prisma):+ ), patch("litellm.proxy.proxy_server.prisma_client", mock_prisma):+ with pytest.raises(HTTPException) as exc_info:+ await _check_byok_credential(server, user_auth)++ assert exc_info.value.status_code == 401+ detail: Any = exc_info.value.detail+ assert detail["error"] == "byok_auth_required"+ assert detail["server_id"] == "byok-2"+ headers = exc_info.value.headers or {}+ assert "WWW-Authenticate" in headers # type: ignore[operator]+ assert "oauth-protected-resource" in headers["WWW-Authenticate"] # type: ignore[index]+++async def test_check_byok_credential_has_credential():+ """BYOK server with a valid stored credential → no error raised."""+ from litellm.proxy._experimental.mcp_server.server import _check_byok_credential+ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.types.mcp_server.mcp_server_manager import MCPServer++ server = MCPServer(+ server_id="byok-3",+ name="byok-server",+ transport=MCPTransport.http,+ is_byok=True,+ )+ user_auth = UserAPIKeyAuth(user_id="user-77", api_key="sk-test")++ mock_prisma = MagicMock()++ with patch(+ "litellm.proxy._experimental.mcp_server.db.get_user_credential",+ new=AsyncMock(return_value="some-credential-value"),+ ), patch("litellm.proxy.proxy_server.prisma_client", mock_prisma):+ ), patch("litellm.proxy.proxy_server.prisma_client", mock_prisma):+ # Should not raise+ await _check_byok_credential(server, user_auth)diff --git a/ui/litellm-dashboard/src/app/(dashboard)/components/Sidebar2.tsx b/ui/litellm-dashboard/src/app/(dashboard)/components/Sidebar2.tsxindex b3829d0a8f4..dbc1c4d10e2 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/components/Sidebar2.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/components/Sidebar2.tsx@@ -111,6 +111,8 @@ const routeFor = (slug: string): string => {return "tools/mcp-servers";case "vector-stores":return "tools/vector-stores";+ case "byok-demo":+ return "tools/byok-demo";// experimentalcase "caching":diff --git a/ui/litellm-dashboard/src/components/mcp_tools/ByokCredentialModal.tsx b/ui/litellm-dashboard/src/components/mcp_tools/ByokCredentialModal.tsxnew file mode 100644index 00000000000..473918c1267--- /dev/null+++ b/ui/litellm-dashboard/src/components/mcp_tools/ByokCredentialModal.tsx@@ -0,0 +1,254 @@+"use client";++import React, { useState } from "react";+import { Modal, Input, Switch, message } from "antd";+import {+ KeyOutlined,+ LockOutlined,+ CheckOutlined,+ ArrowRightOutlined,+ ArrowLeftOutlined,+ CloseOutlined,+ LinkOutlined,+} from "@ant-design/icons";+import { MCPServer } from "./types";++interface ByokCredentialModalProps {+ server: MCPServer;+ open: boolean;+ onClose: () => void;+ onSuccess: (serverId: string) => void;+ accessToken: string;+}++export const ByokCredentialModal: React.FC<ByokCredentialModalProps> = ({+ server,+ open,+ onClose,+ onSuccess,+ accessToken,+}) => {+ const [step, setStep] = useState<1 | 2>(1);+ const [apiKey, setApiKey] = useState("");+ const [saveKey, setSaveKey] = useState(true);+ const [loading, setLoading] = useState(false);++ const serverDisplayName = server.alias || server.server_name || "Service";+ const firstLetter = serverDisplayName.charAt(0).toUpperCase();++ const handleClose = () => {+ setStep(1);+ setApiKey("");+ setSaveKey(true);+ setLoading(false);+ onClose();+ };++ const handleAuthorize = async () => {+ if (!apiKey.trim()) {+ message.error("Please enter your API key");+ return;+ }+ setLoading(true);+ try {+ const response = await fetch(`/v1/mcp/server/${server.server_id}/user-credential`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${accessToken}`,+ },+ body: JSON.stringify({ credential: apiKey.trim(), save: saveKey }),+ });+ if (!response.ok) {+ const err = await response.json();+ throw new Error(err?.detail?.error || "Failed to save credential");+ }+ message.success(`Connected to ${serverDisplayName}`);+ onSuccess(server.server_id);+ handleClose();+ } catch (e: any) {+ message.error(e.message || "Failed to connect");+ } finally {+ setLoading(false);+ }+ };++ return (+ <Modal+ open={open}+ onCancel={handleClose}+ footer={null}+ width={480}+ closeIcon={null}+ className="byok-modal"+ >+ <div className="relative p-2">+ {/* Step dots + close */}+ <div className="flex items-center justify-between mb-6">+ {step === 2 ? (+ <button+ onClick={() => setStep(1)}+ className="flex items-center gap-1 text-gray-500 hover:text-gray-800 text-sm"+ >+ <ArrowLeftOutlined /> Back+ </button>+ ) : (+ <div />+ )}+ <div className="flex items-center gap-1.5">+ <div className={`w-2 h-2 rounded-full ${step === 1 ? "bg-blue-500" : "bg-gray-300"}`} />+ <div className={`w-2 h-2 rounded-full ${step === 2 ? "bg-blue-500" : "bg-gray-300"}`} />+ </div>+ <button onClick={handleClose} className="text-gray-400 hover:text-gray-600">+ <CloseOutlined />+ </button>+ </div>++ {step === 1 ? (+ <div className="text-center">+ {/* Logos */}+ <div className="flex items-center justify-center gap-3 mb-6">+ <div className="w-14 h-14 rounded-xl bg-gradient-to-br from-teal-400 to-cyan-600 flex items-center justify-center text-white font-bold text-xl shadow">+ L+ </div>+ <ArrowRightOutlined className="text-gray-400 text-lg" />+ <div className="w-14 h-14 rounded-xl bg-gradient-to-br from-blue-600 to-indigo-800 flex items-center justify-center text-white font-bold text-xl shadow">+ {firstLetter}+ </div>+ </div>++ <h2 className="text-2xl font-bold text-gray-900 mb-2">Connect {serverDisplayName}</h2>+ <p className="text-gray-500 mb-6">+ LiteLLM needs access to {serverDisplayName} to complete your request.+ </p>++ {/* How it works */}+ <div className="bg-gray-50 rounded-xl p-4 text-left mb-4">+ <div className="flex items-start gap-3">+ <div className="mt-0.5">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" className="text-gray-500">+ <rect x="2" y="4" width="20" height="16" rx="2" stroke="currentColor" strokeWidth="2" />+ <path d="M8 4v16M16 4v16" stroke="currentColor" strokeWidth="2" />+ </svg>+ </div>+ <div>+ <p className="font-semibold text-gray-800 mb-1">How it works</p>+ <p className="text-gray-500 text-sm">+ LiteLLM acts as a secure bridge. Your requests are routed through our MCP client directly to{" "}+ {serverDisplayName}'s API.+ </p>+ </div>+ </div>+ </div>++ {/* Requested access */}+ {server.byok_description && server.byok_description.length > 0 && (+ <div className="bg-gray-50 rounded-xl p-4 text-left mb-6">+ <p className="text-xs font-semibold text-gray-500 uppercase tracking-widest mb-3 flex items-center gap-2">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" className="text-green-500">+ <path+ d="M12 2L12 22M2 12L22 12"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ />+ <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="2" />+ </svg>+ Requested Access+ </p>+ <ul className="space-y-2">+ {server.byok_description.map((item, i) => (+ <li key={i} className="flex items-center gap-2 text-sm text-gray-700">+ <CheckOutlined className="text-green-500 flex-shrink-0" />+ {item}+ </li>+ ))}+ </ul>+ </div>+ )}++ <button+ onClick={() => setStep(2)}+ className="w-full bg-gray-900 hover:bg-gray-700 text-white font-medium py-3 px-6 rounded-xl flex items-center justify-center gap-2 transition-colors"+ >+ Continue to Authentication <ArrowRightOutlined />+ </button>+ <button+ onClick={handleClose}+ className="mt-3 w-full text-gray-400 hover:text-gray-600 text-sm py-2"+ >+ Cancel+ </button>+ </div>+ ) : (+ <div>+ {/* Key icon */}+ <div className="w-12 h-12 rounded-full bg-blue-50 flex items-center justify-center mb-4">+ <KeyOutlined className="text-blue-400 text-xl" />+ </div>++ <h2 className="text-2xl font-bold text-gray-900 mb-2">Provide API Key</h2>+ <p className="text-gray-500 mb-6">+ Enter your {serverDisplayName} API key to authorize this connection.+ </p>++ <div className="mb-4">+ <label className="block text-sm font-semibold text-gray-800 mb-2">+ {serverDisplayName} API Key+ </label>+ <Input.Password+ placeholder="Enter your API key"+ value={apiKey}+ onChange={(e) => setApiKey(e.target.value)}+ size="large"+ className="rounded-lg"+ />+ {server.byok_api_key_help_url && (+ <a+ href={server.byok_api_key_help_url}+ target="_blank"+ rel="noopener noreferrer"+ className="text-blue-500 hover:text-blue-700 text-sm mt-2 flex items-center gap-1"+ >+ Where do I find my API key? <LinkOutlined />+ </a>+ )}+ </div>++ {/* Save toggle */}+ <div className="bg-gray-50 rounded-xl p-4 flex items-center justify-between mb-4">+ <div className="flex items-center gap-3">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" className="text-gray-500">+ <path+ d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"+ fill="currentColor"+ />+ </svg>+ <span className="text-sm font-medium text-gray-800">Save key for future use</span>+ </div>+ <Switch checked={saveKey} onChange={setSaveKey} />+ </div>++ {/* Security note */}+ <div className="bg-blue-50 rounded-xl p-4 flex items-start gap-3 mb-6">+ <LockOutlined className="text-blue-400 mt-0.5 flex-shrink-0" />+ <p className="text-sm text-blue-700">+ Your key is stored securely and transmitted over HTTPS. It is never shared with third parties.+ </p>+ </div>++ <button+ onClick={handleAuthorize}+ disabled={loading}+ className="w-full bg-blue-500 hover:bg-blue-600 disabled:opacity-60 text-white font-medium py-3 px-6 rounded-xl flex items-center justify-center gap-2 transition-colors"+ >+ <LockOutlined /> Connect & Authorize+ </button>+ </div>+ )}+ </div>+ </Modal>+ );+};++export default ByokCredentialModal;diff --git a/ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx b/ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsxindex 6dbb18887da..6ca58ffae24 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx@@ -1,5 +1,5 @@import React, { useState } from "react";-import { Modal, Tooltip, Form, Select, Input } from "antd";+import { Modal, Tooltip, Form, Select, Input, Switch } from "antd";import { InfoCircleOutlined } from "@ant-design/icons";import { Button, TextInput } from "@tremor/react";import { createMCPServer } from "../networking";@@ -624,6 +624,89 @@ const CreateMCPServer: React.FC<CreateMCPServerProps> = ({</Form.Item>)}+ {/* BYOK toggle - only for OpenAPI */}+ {transportType === TRANSPORT.OPENAPI && (+ <>+ <Form.Item+ label={+ <span className="text-sm font-medium text-gray-700 flex items-center gap-2">+ BYOK (Bring Your Own Key)+ <Tooltip title="When enabled, each user provides their own API key for this service. Keys are stored per-user and never shared.">+ <InfoCircleOutlined className="text-blue-400 hover:text-blue-600 cursor-help" />+ </Tooltip>+ </span>+ }+ name="is_byok"+ valuePropName="checked"+ >+ <Switch />+ </Form.Item>++ <Form.Item noStyle shouldUpdate={(prev, cur) => prev.is_byok !== cur.is_byok || prev.auth_type !== cur.auth_type}>+ {({ getFieldValue }) =>+ getFieldValue("is_byok") ? (+ <>+ {/* Auth format hint */}+ {getFieldValue("auth_type") && getFieldValue("auth_type") !== "none" && (+ <div className="mb-4 p-3 bg-blue-50 rounded-lg text-sm text-blue-700 flex items-start gap-2">+ <InfoCircleOutlined className="mt-0.5 flex-shrink-0" />+ <span>+ User keys will be sent as:{" "}+ <code className="font-mono bg-blue-100 px-1 rounded">+ {getFieldValue("auth_type") === "bearer_token" && "Authorization: Bearer {key}"}+ {getFieldValue("auth_type") === "api_key" && "x-api-key: {key}"}+ {getFieldValue("auth_type") === "basic" && "Authorization: Basic {key}"}+ {getFieldValue("auth_type") === "authorization" && "Authorization: {key}"}+ </code>+ {!getFieldValue("auth_type") && "Set Authentication Type below to specify the format."}+ </span>+ </div>+ )}+ {!getFieldValue("auth_type") && (+ <div className="mb-4 p-3 bg-yellow-50 rounded-lg text-sm text-yellow-700 flex items-start gap-2">+ <InfoCircleOutlined className="mt-0.5 flex-shrink-0" />+ <span>Set the <strong>Authentication Type</strong> below to specify how user keys are sent (e.g., Bearer Token, API Key header).</span>+ </div>+ )}+ <Form.Item+ label={+ <span className="text-sm font-medium text-gray-700">+ Access Description+ <Tooltip title="List of permissions shown to users in the connection modal (e.g. 'Create and manage Jira issues')">+ <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />+ </Tooltip>+ </span>+ }+ name="byok_description"+ >+ <Select+ mode="tags"+ placeholder="Add access description items (press Enter after each)"+ className="w-full"+ tokenSeparators={[","]}+ />+ </Form.Item>++ <Form.Item+ label={+ <span className="text-sm font-medium text-gray-700">+ API Key Help URL+ <Tooltip title="Optional link shown to users to help them find their API key">+ <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />+ </Tooltip>+ </span>+ }+ name="byok_api_key_help_url"+ >+ <Input placeholder="https://docs.example.com/api-keys" />+ </Form.Item>+ </>+ ) : null+ }+ </Form.Item>+ </>+ )}+{/* Authentication - show for HTTP, SSE, and OpenAPI */}{transportType !== "stdio" && transportType !== "" && (<Form.Itemdiff --git a/ui/litellm-dashboard/src/components/mcp_tools/mcp_server_columns.tsx b/ui/litellm-dashboard/src/components/mcp_tools/mcp_server_columns.tsxindex b30caa16d6b..0db1f4c14cd 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/mcp_server_columns.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/mcp_server_columns.tsx@@ -4,6 +4,7 @@ import { Icon } from "@tremor/react";import { PencilAltIcon, TrashIcon } from "@heroicons/react/outline";import { getMaskedAndFullUrl } from "./utils";import { Tooltip } from "antd";+import { CheckOutlined } from "@ant-design/icons";export const mcpServerColumns = (userRole: string,@@ -11,6 +12,7 @@ export const mcpServerColumns = (onEdit: (serverId: string) => void,onDelete: (serverId: string) => void,isLoadingHealth?: boolean,+ onByokConnect?: (server: MCPServer) => void,): ColumnDef<MCPServer>[] => [{accessorKey: "server_id",@@ -192,6 +194,41 @@ export const mcpServerColumns = ();},},+ {+ id: "byok_credential",+ header: "Credential",+ cell: ({ row }) => {+ const server = row.original;+ if (!server.is_byok) {+ return <span className="text-gray-300 text-xs">—</span>;+ }+ if (server.has_user_credential) {+ return (+ <div className="flex items-center gap-2">+ <span className="text-green-600 text-xs font-medium flex items-center gap-1">+ <CheckOutlined /> Connected+ </span>+ {onByokConnect && (+ <button+ className="text-xs text-gray-400 hover:text-blue-500 underline"+ onClick={() => onByokConnect(server)}+ >+ Reconnect+ </button>+ )}+ </div>+ );+ }+ return onByokConnect ? (+ <button+ className="text-xs bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded-lg font-medium"+ onClick={() => onByokConnect(server)}+ >+ Connect+ </button>+ ) : null;+ },+ },{id: "actions",header: "Actions",diff --git a/ui/litellm-dashboard/src/components/mcp_tools/mcp_servers.tsx b/ui/litellm-dashboard/src/components/mcp_tools/mcp_servers.tsxindex 0f87f5e87b8..f48649d6653 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/mcp_servers.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/mcp_servers.tsx@@ -16,6 +16,7 @@ import { DiscoverableMCPServer, MCPServer, MCPServerProps, Team } from "./types"import MCPSemanticFilterSettings from "../Settings/AdminSettings/MCPSemanticFilterSettings/MCPSemanticFilterSettings";import MCPNetworkSettings from "./MCPNetworkSettings";import MCPDiscovery from "./mcp_discovery";+import { ByokCredentialModal } from "./ByokCredentialModal";const { Text: AntdText, Title: AntdTitle } = Typography;const EDIT_OAUTH_UI_STATE_KEY = "litellm-mcp-oauth-edit-state";@@ -70,6 +71,7 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })const [isDiscoveryVisible, setDiscoveryVisible] = useState(false);const [prefillData, setPrefillData] = useState<DiscoverableMCPServer | null>(null);const [isDeletingServer, setIsDeletingServer] = useState(false);+ const [byokModalServer, setByokModalServer] = useState<MCPServer | null>(null);const isInternalUser = userRole === "Internal User";useEffect(() => {@@ -170,6 +172,7 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })},handleDelete,isLoadingHealth,+ (server: MCPServer) => setByokModalServer(server),),[userRole, isLoadingHealth],);@@ -427,6 +430,19 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })</TabPanel></TabPanels></TabGroup>++ {byokModalServer && (+ <ByokCredentialModal+ server={byokModalServer}+ open={!!byokModalServer}+ onClose={() => setByokModalServer(null)}+ onSuccess={(_serverId) => {+ refetch();+ setByokModalServer(null);+ }}+ accessToken={accessToken || ""}+ />+ )}</div>);};diff --git a/ui/litellm-dashboard/src/components/mcp_tools/types.tsx b/ui/litellm-dashboard/src/components/mcp_tools/types.tsxindex 8a08f13e22a..6ba25012197 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/types.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/types.tsx@@ -178,6 +178,12 @@ export interface MCPServer {command?: string | null;args?: string[] | null;env?: Record<string, string> | null;++ /** BYOK (Bring Your Own Key) fields */+ is_byok?: boolean | null;+ byok_description?: string[] | null;+ byok_api_key_help_url?: string | null;+ has_user_credential?: boolean | null;}export interface MCPServerProps {diff --git a/ui/litellm-dashboard/src/components/playground/chat_ui/ChatUI.tsx b/ui/litellm-dashboard/src/components/playground/chat_ui/ChatUI.tsxindex 3272e9b589a..9936f34452d 100644--- a/ui/litellm-dashboard/src/components/playground/chat_ui/ChatUI.tsx+++ b/ui/litellm-dashboard/src/components/playground/chat_ui/ChatUI.tsx@@ -33,6 +33,7 @@ import GuardrailSelector from "../../guardrails/GuardrailSelector";import PolicySelector from "../../policies/PolicySelector";import MCPToolArgumentsForm, { MCPToolArgumentsFormRef } from "../../mcp_tools/MCPToolArgumentsForm";import { MCPServer } from "../../mcp_tools/types";+import { ByokCredentialModal } from "../../mcp_tools/ByokCredentialModal";import NotificationsManager from "../../molecules/notifications_manager";import { callMCPTool, fetchMCPServers, listMCPTools } from "../../networking";import TagSelector from "../../tag_management/TagSelector";@@ -108,6 +109,7 @@ const ChatUI: React.FC<ChatUIProps> = ({fixedModel,}) => {const [mcpServers, setMCPServers] = useState<MCPServer[]>([]);+ const [byokModalServer, setByokModalServer] = useState<MCPServer | null>(null);const [selectedMCPServers, setSelectedMCPServers] = useState<string[]>(() => {const saved = sessionStorage.getItem("selectedMCPServers");try {@@ -1746,6 +1748,49 @@ const ChatUI: React.FC<ChatUIProps> = ({})}</div>)}++ {/* BYOK credential status for selected servers */}+ {selectedMCPServers.length > 0 &&+ !selectedMCPServers.includes("__all__") &&+ selectedMCPServers.some((serverId) => {+ const server = mcpServers.find((s) => s.server_id === serverId);+ return server?.is_byok;+ }) && (+ <div className="mt-3 space-y-2">+ {selectedMCPServers.map((serverId) => {+ const server = mcpServers.find((s) => s.server_id === serverId);+ if (!server?.is_byok) return null;+ const serverName = server.alias || server.server_name || serverId;+ return (+ <div key={serverId} className="border border-blue-100 rounded p-2 bg-blue-50 flex items-center justify-between">+ <Text className="text-xs text-blue-700">+ {serverName} requires your API key+ </Text>+ {server.has_user_credential ? (+ <div className="flex items-center gap-2">+ <span className="text-green-600 text-xs font-medium flex items-center gap-1">+ <KeyOutlined /> Connected+ </span>+ <button+ className="text-xs text-gray-400 hover:text-blue-500 underline"+ onClick={() => setByokModalServer(server)}+ >+ Reconnect+ </button>+ </div>+ ) : (+ <button+ className="text-xs bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded-lg font-medium"+ onClick={() => setByokModalServer(server)}+ >+ Connect+ </button>+ )}+ </div>+ );+ })}+ </div>+ )}</div><div>@@ -2498,6 +2543,20 @@ const ChatUI: React.FC<ChatUIProps> = ({{generatedCode}</SyntaxHighlighter></Modal>++ {byokModalServer && (+ <ByokCredentialModal+ server={byokModalServer}+ open={!!byokModalServer}+ onClose={() => setByokModalServer(null)}+ onSuccess={(_serverId) => {+ // Refresh MCP servers to pick up updated has_user_credential+ loadMCPServers();+ setByokModalServer(null);+ }}+ accessToken={accessToken || ""}+ />+ )}</div>);};