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 OAuth2 client-side debug headers (#21151)
Ishaan Jaffa06113ec82cd
diff --git a/docs/my-website/docs/mcp_oauth.md b/docs/my-website/docs/mcp_oauth.mdindex 9cd7b1e77be..5c4b70cc5b3 100644--- a/docs/my-website/docs/mcp_oauth.md+++ b/docs/my-website/docs/mcp_oauth.md@@ -242,3 +242,96 @@ curl http://localhost:4000/mcp-rest/tools/call \| `client_secret` | Yes | OAuth2 client secret. Supports `os.environ/VAR_NAME` || `token_url` | Yes | Token endpoint URL || `scopes` | No | List of scopes to request |++## Debugging OAuth++When the LiteLLM proxy is hosted remotely and you cannot access server logs, enable **debug headers** to get masked authentication diagnostics in the HTTP response.++### Enable Debug Mode++Add the `x-litellm-mcp-debug: true` header to your MCP client request.++**Claude Code:**++```bash+claude mcp add --transport http litellm_proxy http://proxy.example.com/atlassian_mcp/mcp \+ --header "x-litellm-api-key: Bearer sk-..." \+ --header "x-litellm-mcp-debug: true"+```++**curl:**++```bash+curl -X POST http://localhost:4000/atlassian_mcp/mcp \+ -H "Content-Type: application/json" \+ -H "x-litellm-api-key: Bearer sk-..." \+ -H "x-litellm-mcp-debug: true" \+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'+```++### Reading the Debug Response Headers++The response includes these headers (all sensitive values are masked):++| Header | Description |+|--------|-------------|+| `x-mcp-debug-inbound-auth` | Which inbound auth headers were present. |+| `x-mcp-debug-oauth2-token` | The OAuth2 token (masked). Shows `SAME_AS_LITELLM_KEY` if the LiteLLM key is leaking. |+| `x-mcp-debug-auth-resolution` | Which auth method was used: `oauth2-passthrough`, `m2m-client-credentials`, `per-request-header`, `static-token`, or `no-auth`. |+| `x-mcp-debug-outbound-url` | The upstream MCP server URL. |+| `x-mcp-debug-server-auth-type` | The `auth_type` configured on the server. |++**Example — healthy OAuth2 passthrough:**++```+x-mcp-debug-inbound-auth: x-litellm-api-key=Bearer****1234; authorization=Bearer****ef01+x-mcp-debug-oauth2-token: Bearer****ef01+x-mcp-debug-auth-resolution: oauth2-passthrough+x-mcp-debug-outbound-url: https://mcp.atlassian.com/v1/mcp+x-mcp-debug-server-auth-type: oauth2+```++**Example — LiteLLM key leaking (misconfigured):**++```+x-mcp-debug-inbound-auth: authorization=Bearer****1234+x-mcp-debug-oauth2-token: Bearer****1234 (SAME_AS_LITELLM_KEY - likely misconfigured)+x-mcp-debug-auth-resolution: oauth2-passthrough+x-mcp-debug-outbound-url: https://mcp.atlassian.com/v1/mcp+x-mcp-debug-server-auth-type: oauth2+```++### Common Issues++#### LiteLLM API key leaking to the MCP server++**Symptom:** `x-mcp-debug-oauth2-token` shows `SAME_AS_LITELLM_KEY`.++The `Authorization` header carries the LiteLLM API key instead of an OAuth2 token. The OAuth2 flow never ran because the client already had an `Authorization` header set.++**Fix:** Move the LiteLLM key to `x-litellm-api-key`:++```bash+# WRONG — blocks OAuth2 discovery+claude mcp add --transport http my_server http://proxy/mcp/server \+ --header "Authorization: Bearer sk-..."++# CORRECT — LiteLLM key in dedicated header, Authorization free for OAuth2+claude mcp add --transport http my_server http://proxy/mcp/server \+ --header "x-litellm-api-key: Bearer sk-..."+```++#### No OAuth2 token present++**Symptom:** `x-mcp-debug-oauth2-token` shows `(none)` and `x-mcp-debug-auth-resolution` shows `no-auth`.++Check that:+1. The `Authorization` header is NOT set as a static header in the client config.+2. The MCP server in LiteLLM config has `auth_type: oauth2`.+3. The `.well-known/oauth-protected-resource` endpoint returns valid metadata.++#### M2M token used instead of user token++**Symptom:** `x-mcp-debug-auth-resolution` shows `m2m-client-credentials`.++The server has `client_id`/`client_secret`/`token_url` configured so LiteLLM is fetching a machine-to-machine token instead of using the per-user OAuth2 token. To use per-user tokens, remove the client credentials from the server config.diff --git a/docs/my-website/docs/mcp_troubleshoot.md b/docs/my-website/docs/mcp_troubleshoot.mdindex 27ba0e4d787..57e7bfa674d 100644--- a/docs/my-website/docs/mcp_troubleshoot.md+++ b/docs/my-website/docs/mcp_troubleshoot.md@@ -6,6 +6,39 @@ When LiteLLM acts as an MCP proxy, traffic normally flows `Client → LiteLLM PrFor provisioning steps, transport options, and configuration fields, refer to [mcp.md](./mcp.md).+## Quick Start: Debug with One Command++The fastest way to debug MCP issues is to enable **debug headers**. Run this curl against your LiteLLM proxy and check the response headers:++```bash+curl -si -X POST http://localhost:4000/{your_mcp_server}/mcp \+ -H "Content-Type: application/json" \+ -H "x-litellm-api-key: Bearer sk-YOUR_KEY" \+ -H "x-litellm-mcp-debug: true" \+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' \+ 2>&1 | grep -i "x-mcp-debug"+```++This returns masked diagnostic headers that tell you exactly what's happening with authentication:++```+x-mcp-debug-inbound-auth: x-litellm-api-key=Bearer****1234+x-mcp-debug-oauth2-token: Bearer****ef01+x-mcp-debug-auth-resolution: oauth2-passthrough+x-mcp-debug-outbound-url: https://mcp.atlassian.com/v1/mcp+x-mcp-debug-server-auth-type: oauth2+```++If you see `SAME_AS_LITELLM_KEY` in `x-mcp-debug-oauth2-token`, your LiteLLM API key is leaking to the MCP server instead of an OAuth2 token. See [Debugging OAuth](./mcp_oauth#debugging-oauth) for the fix and other common issues.++For Claude Code, add the debug header to your MCP config:++```bash+claude mcp add --transport http my_server http://localhost:4000/my_mcp/mcp \+ --header "x-litellm-api-key: Bearer sk-..." \+ --header "x-litellm-mcp-debug: true"+```+## Locate the Error SourcePin down where the failure occurs before adjusting settings so you do not mix symptoms from separate hops.@@ -13,7 +46,7 @@ Pin down where the failure occurs before adjusting settings so you do not mix sy### LiteLLM UI / Playground Errors (LiteLLM → MCP)Failures shown on the MCP creation form or within the MCP Tool Testing Playground mean the LiteLLM proxy cannot reach the MCP server. Typical causes are misconfiguration (transport, headers, credentials), MCP/server outages, network/firewall blocks, or inaccessible OAuth metadata.-<Image+<Imageimg={require('../img/mcp_tool_testing_playground.png')}style={{width: '80%', display: 'block', margin: '0'}}/>@@ -22,7 +55,7 @@ Failures shown on the MCP creation form or within the MCP Tool Testing Playgroun**Actions**- Capture LiteLLM proxy logs alongside MCP-server logs (see [Error Log Example](./mcp_troubleshoot#error-log-example-failed-mcp-call)) to inspect the request/response pair and stack traces.-- From the LiteLLM server, run Method 2 ([`curl` smoke test](./mcp_troubleshoot#curl-smoke-test)) against the MCP endpoint to confirm basic connectivity.+- From the LiteLLM server, run a [`curl` smoke test](./mcp_troubleshoot#curl-smoke-test) against the MCP endpoint to confirm basic connectivity.### Client Traffic Issues (Client → LiteLLM)If only real client requests fail, determine whether LiteLLM ever reaches the MCP hop.@@ -43,7 +76,7 @@ During `/responses` or `/chat/completions`, LiteLLM may trigger MCP tool calls m- Validate MCP connectivity with the [MCP Inspector](./mcp_troubleshoot#mcp-inspector) to ensure the server responds.- Reproduce the same MCP call via the LiteLLM Playground to confirm LiteLLM can complete the MCP hop independently.-<Image+<Imageimg={require('../img/mcp_playground.png')}style={{width: '80%', display: 'block', margin: '0'}}/>@@ -55,6 +88,10 @@ LiteLLM performs metadata discovery per the MCP spec ([section 2.3](https://mode- Use `curl <metadata_url>` (or similar) from the LiteLLM host to ensure the discovery document is reachable and contains the expected authorization/token endpoints.- Record the exact metadata URL, requested scopes, and any static client credentials so support can replay the discovery step if needed.+## Debugging OAuth++For detailed OAuth2 debugging — including debug header reference, common misconfigurations, and example output — see [Debugging OAuth](./mcp_oauth#debugging-oauth).+## Verify ConnectivityRun lightweight validations before impacting production traffic.@@ -66,7 +103,7 @@ Use the MCP Inspector when you need to test both `Client → LiteLLM` and `Clien2. Configure and connect:- **Transport Type:** choose the transport the client uses (Streamable HTTP for LiteLLM).- **URL:** the endpoint under test (LiteLLM MCP URL for `Client → LiteLLM`, or the MCP server URL for `Client → MCP`).- - **Custom Headers:** e.g., `Authorization: Bearer <LiteLLM API Key>`.+ - **Custom Headers:** e.g., `x-litellm-api-key: Bearer <LiteLLM API Key>`.3. Open the **Tools** tab and click **List Tools** to verify the MCP alias responds.### `curl` Smoke Test@@ -79,7 +116,7 @@ curl -X POST https://your-target-domain.example.com/mcp \-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'```-Add `-H "Authorization: Bearer <LiteLLM API Key>"` when the target is a LiteLLM endpoint that requires authentication. Adjust the headers, or payload to target other MCP methods. Matching failures between `curl` and LiteLLM confirm that the MCP server or network/OAuth layer is the culprit.+Add `-H "x-litellm-api-key: Bearer <LiteLLM API Key>"` when the target is a LiteLLM endpoint that requires authentication. Adjust the headers or payload to target other MCP methods. Matching failures between `curl` and LiteLLM confirm that the MCP server or network/OAuth layer is the culprit.## Review Logsdiff --git a/docs/my-website/docs/troubleshoot.md b/docs/my-website/docs/troubleshoot.mdindex 179f1c7897c..1539e1959f7 100644--- a/docs/my-website/docs/troubleshoot.md+++ b/docs/my-website/docs/troubleshoot.md@@ -1,102 +1,48 @@-# Troubleshooting & Support--## Information to Provide When Seeking Help+# Issue ReportingWhen reporting issues, please include as much of the following as possible. It's okay if you can't provide everything—especially in production scenarios where the trigger might be unknown. Sharing most of this information will help us assist you more effectively.-### 1. LiteLLM Configuration File+## 1. LiteLLM Configuration FileYour `config.yaml` file (redact sensitive info like API keys). Include number of workers if not in config.-### 2. Initialization Command+## 2. Initialization CommandThe command used to start LiteLLM (e.g., `litellm --config config.yaml --num_workers 8 --detailed_debug`).-### 3. LiteLLM Version+## 3. LiteLLM Version-- Current version-- Version when the issue first appeared (if different)+- Current version+- Version when the issue first appeared (if different)- If upgraded, the version changed from → to-### 4. Environment Variables+## 4. Environment VariablesNon-sensitive environment variables not in your config (e.g., `NUM_WORKERS`, `LITELLM_LOG`, `LITELLM_MODE`). Do not include passwords or API keys.-### 5. Server Specifications+## 5. Server SpecificationsCPU cores, RAM, OS, number of instances/replicas, etc.-### 6. Database and Redis Usage+## 6. Database and Redis Usage- **Database:** Using database? (`DATABASE_URL` set), database type and version- **Redis:** Using Redis? Redis version, configuration type (Standalone/Cluster/Sentinel).-### 7. Endpoints+## 7. EndpointsThe endpoint(s) you're using that are experiencing issues (e.g., `/chat/completions`, `/embeddings`).-### 8. Request Example+## 8. Request ExampleA realistic example of the request causing issues, including expected vs. actual response and any error messages.-### 9. Error Logs, Stack Traces, and Metrics+## 9. Error Logs, Stack Traces, and MetricsFull error logs, stack traces, and any images from service metrics (CPU, memory, request rates, etc.) that might help diagnose the issue.----## UI Issues--If you're experiencing issues with the LiteLLM Admin UI, please include the following information in addition to the general details above.--### 1. Steps to Reproduce--A clear, step-by-step description of how to trigger the issue (e.g., "Navigate to Settings → Team, click 'Create Team', fill in fields, click submit → error appears").--### 2. LiteLLM Version--The current version of LiteLLM you're running. Check via `litellm --version` or the UI's settings page.--### 3. Architecture & Deployment Setup--Distributed environments are a known source of UI issues. Please describe:--- **Number of LiteLLM instances/replicas** and how they are deployed (e.g., Kubernetes, Docker Compose, ECS)-- **Load balancer** type and configuration (e.g., ALB, Nginx, Cloudflare Tunnel) — include whether sticky sessions are enabled-- **How the UI is accessed** — directly via LiteLLM, through a reverse proxy, or behind an ingress controller-- **Any CDN or caching layers** between the user and the LiteLLM server--### 4. Network Tab Requests--Open your browser's Developer Tools (F12 → Network tab), reproduce the issue, and share:--- The **failing request(s)** — URL, method, status code, and response body-- **Screenshots or HAR export** of the relevant network activity-- Any **CORS or mixed-content errors** shown in the Console tab--### 5. Environment Variables--Non-sensitive environment variables related to the UI and proxy setup, such as:--- `LITELLM_MASTER_KEY`-- `PROXY_BASE_URL` / `LITELLM_PROXY_BASE_URL`-- `UI_BASE_PATH`-- Any SSO-related variables (e.g., `GOOGLE_CLIENT_ID`, `MICROSOFT_TENANT`)--Do **not** include passwords, secrets, or API keys.--### 6. Browser & Access Details--- **Browser** and version (e.g., Chrome 120, Firefox 121)-- **Access URL** used to reach the UI (redact sensitive parts)-- Whether the issue occurs for **all users or specific roles** (Admin, Internal User, etc.)--### 7. Screenshots or Screen Recordings--A screenshot or short screen recording of the issue is extremely helpful. Include any visible error messages, toasts, or unexpected behavior.------## Support Channels[Schedule Demo 👋](https://calendly.com/d/4mp-gd3-k5k/berriai-1-1-onboarding-litellm-hosted-version)@@ -109,4 +55,3 @@ Our numbers 📞 +1 (770) 8783-106 / +1 (412) 618-6238Our emails ✉️ [email protected] / [email protected][](https://wa.link/huol9n) [](https://discord.gg/wuPM9dRgDw)-diff --git a/docs/my-website/docs/troubleshoot/ui_issues.md b/docs/my-website/docs/troubleshoot/ui_issues.mdnew file mode 100644index 00000000000..90912b1daeb--- /dev/null+++ b/docs/my-website/docs/troubleshoot/ui_issues.md@@ -0,0 +1,49 @@+# UI Troubleshooting++If you're experiencing issues with the LiteLLM Admin UI, please include the following information when reporting.++## 1. Steps to Reproduce++A clear, step-by-step description of how to trigger the issue (e.g., "Navigate to Settings → Team, click 'Create Team', fill in fields, click submit → error appears").++## 2. LiteLLM Version++The current version of LiteLLM you're running. Check via `litellm --version` or the UI's settings page.++## 3. Architecture & Deployment Setup++Distributed environments are a known source of UI issues. Please describe:++- **Number of LiteLLM instances/replicas** and how they are deployed (e.g., Kubernetes, Docker Compose, ECS)+- **Load balancer** type and configuration (e.g., ALB, Nginx, Cloudflare Tunnel) — include whether sticky sessions are enabled+- **How the UI is accessed** — directly via LiteLLM, through a reverse proxy, or behind an ingress controller+- **Any CDN or caching layers** between the user and the LiteLLM server++## 4. Network Tab Requests++Open your browser's Developer Tools (F12 → Network tab), reproduce the issue, and share:++- The **failing request(s)** — URL, method, status code, and response body+- **Screenshots or HAR export** of the relevant network activity+- Any **CORS or mixed-content errors** shown in the Console tab++## 5. Environment Variables++Non-sensitive environment variables related to the UI and proxy setup, such as:++- `LITELLM_MASTER_KEY`+- `PROXY_BASE_URL` / `LITELLM_PROXY_BASE_URL`+- `UI_BASE_PATH`+- Any SSO-related variables (e.g., `GOOGLE_CLIENT_ID`, `MICROSOFT_TENANT`)++Do **not** include passwords, secrets, or API keys.++## 6. Browser & Access Details++- **Browser** and version (e.g., Chrome 120, Firefox 121)+- **Access URL** used to reach the UI (redact sensitive parts)+- Whether the issue occurs for **all users or specific roles** (Admin, Internal User, etc.)++## 7. Screenshots or Screen Recordings++A screenshot or short screen recording of the issue is extremely helpful. Include any visible error messages, toasts, or unexpected behavior.diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.jsindex eb075c2b77c..9e2eb47f4c9 100644--- a/docs/my-website/sidebars.js+++ b/docs/my-website/sidebars.js@@ -1099,16 +1099,24 @@ const sidebars = {"proxy_server",],},- "troubleshoot",{type: "category",- label: "Issue Reporting",+ label: "Troubleshooting",items: [- "troubleshoot/prisma_migrations",- "troubleshoot/cpu_issues",- "troubleshoot/memory_issues",- "troubleshoot/spend_queue_warnings",- "troubleshoot/max_callbacks",+ "troubleshoot/ui_issues",+ "mcp_troubleshoot",+ {+ type: "category",+ label: "Performance / Latency",+ items: [+ "troubleshoot/cpu_issues",+ "troubleshoot/memory_issues",+ "troubleshoot/spend_queue_warnings",+ "troubleshoot/max_callbacks",+ "troubleshoot/prisma_migrations",+ ],+ },+ "troubleshoot",],},{diff --git a/litellm/proxy/_experimental/mcp_server/mcp_debug.py b/litellm/proxy/_experimental/mcp_server/mcp_debug.pynew file mode 100644index 00000000000..46741a9df98--- /dev/null+++ b/litellm/proxy/_experimental/mcp_server/mcp_debug.py@@ -0,0 +1,329 @@+"""+MCP OAuth2 Debug Headers+========================++Client-side debugging for MCP authentication flows.++When a client sends the ``x-litellm-mcp-debug: true`` header, LiteLLM+returns masked diagnostic headers in the response so operators can+troubleshoot OAuth2 issues without SSH access to the gateway.++Response headers returned (all values are masked for safety):++ x-mcp-debug-inbound-auth+ Which inbound auth headers were present and how they were classified.+ Example: ``x-litellm-api-key=Bearer sk-12****1234``++ x-mcp-debug-oauth2-token+ The OAuth2 token extracted from the Authorization header (masked).+ Shows ``(none)`` if absent, or flags ``SAME_AS_LITELLM_KEY`` when+ the LiteLLM API key is accidentally leaking to the MCP server.++ x-mcp-debug-auth-resolution+ Which auth priority was used for the outbound MCP call:+ ``per-request-header``, ``m2m-client-credentials``, ``static-token``,+ ``oauth2-passthrough``, or ``no-auth``.++ x-mcp-debug-outbound-url+ The upstream MCP server URL that will receive the request.++ x-mcp-debug-server-auth-type+ The ``auth_type`` configured on the MCP server (e.g. ``oauth2``,+ ``bearer_token``, ``none``).++Debugging Guide+---------------++**Common issue: LiteLLM API key leaking to the MCP server**++Symptom: ``x-mcp-debug-oauth2-token`` shows ``SAME_AS_LITELLM_KEY``.++This means the ``Authorization`` header carries the LiteLLM API key and+it's being forwarded to the upstream MCP server instead of an OAuth2 token.++Fix: Move the LiteLLM key to ``x-litellm-api-key`` so the ``Authorization``+header is free for OAuth2 discovery::++ # WRONG — blocks OAuth2 discovery+ claude mcp add --transport http my_server http://proxy/mcp/server \\+ --header "Authorization: Bearer sk-..."++ # CORRECT — LiteLLM key in dedicated header, Authorization free for OAuth2+ claude mcp add --transport http my_server http://proxy/mcp/server \\+ --header "x-litellm-api-key: Bearer sk-..." \\+ --header "x-litellm-mcp-debug: true"++**Common issue: No OAuth2 token present**++Symptom: ``x-mcp-debug-oauth2-token`` shows ``(none)`` and+``x-mcp-debug-auth-resolution`` shows ``no-auth``.++This means the client didn't go through the OAuth2 flow. Check that:+1. The ``Authorization`` header is NOT set as a static header in the client config.+2. The ``.well-known/oauth-protected-resource`` endpoint returns valid metadata.+3. The MCP server in LiteLLM config has ``auth_type: oauth2``.++**Common issue: M2M token used instead of user token**++Symptom: ``x-mcp-debug-auth-resolution`` shows ``m2m-client-credentials``.++This means the server has ``client_id``/``client_secret``/``token_url``+configured and LiteLLM is fetching a machine-to-machine token instead of+using the per-user OAuth2 token. If you want per-user tokens, remove the+client credentials from the server config.++Usage from Claude Code::++ claude mcp add --transport http my_server http://proxy/mcp/server \\+ --header "x-litellm-api-key: Bearer sk-..." \\+ --header "x-litellm-mcp-debug: true"++Usage with curl::++ curl -H "x-litellm-mcp-debug: true" \\+ -H "x-litellm-api-key: Bearer sk-..." \\+ http://localhost:4000/mcp/atlassian_mcp+"""++from typing import TYPE_CHECKING, Dict, List, Optional++from starlette.types import Message, Send++from litellm.litellm_core_utils.sensitive_data_masker import SensitiveDataMasker++if TYPE_CHECKING:+ from litellm.types.mcp_server.mcp_server_manager import MCPServer++# Header the client sends to opt into debug mode+MCP_DEBUG_REQUEST_HEADER = "x-litellm-mcp-debug"++# Prefix for all debug response headers+_RESPONSE_HEADER_PREFIX = "x-mcp-debug"+++class MCPDebug:+ """+ Static helper class for MCP OAuth2 debug headers.++ Provides opt-in client-side diagnostics by injecting masked+ authentication info into HTTP response headers.+ """++ # Masker: show first 6 and last 4 chars so you can distinguish token types+ # e.g. "Bearer****ef01" vs "sk-123****cdef"+ _masker = SensitiveDataMasker(+ sensitive_patterns={+ "authorization",+ "token",+ "key",+ "secret",+ "auth",+ "bearer",+ },+ visible_prefix=6,+ visible_suffix=4,+ )++ @staticmethod+ def _mask(value: Optional[str]) -> str:+ """Mask a single value for safe display in headers."""+ if not value:+ return "(none)"+ return MCPDebug._masker._mask_value(value)++ @staticmethod+ def is_debug_enabled(headers: Dict[str, str]) -> bool:+ """+ Check if the client opted into MCP debug mode.++ Looks for ``x-litellm-mcp-debug: true`` (case-insensitive) in the+ request headers.+ """+ for key, val in headers.items():+ if key.lower() == MCP_DEBUG_REQUEST_HEADER:+ return val.strip().lower() in ("true", "1", "yes")+ return False++ @staticmethod+ def resolve_auth_resolution(+ server: "MCPServer",+ mcp_auth_header: Optional[str],+ mcp_server_auth_headers: Optional[Dict[str, Dict[str, str]]],+ oauth2_headers: Optional[Dict[str, str]],+ ) -> str:+ """+ Determine which auth priority will be used for the outbound MCP call.++ Returns one of: ``per-request-header``, ``m2m-client-credentials``,+ ``static-token``, ``oauth2-passthrough``, or ``no-auth``.+ """+ from litellm.types.mcp import MCPAuth++ has_server_specific = bool(+ mcp_server_auth_headers+ and (+ mcp_server_auth_headers.get(server.alias or "")+ or mcp_server_auth_headers.get(server.server_name or "")+ )+ )+ if has_server_specific or mcp_auth_header:+ return "per-request-header"+ if server.has_client_credentials:+ return "m2m-client-credentials"+ if server.authentication_token:+ return "static-token"+ if oauth2_headers and server.auth_type == MCPAuth.oauth2:+ return "oauth2-passthrough"+ return "no-auth"++ @staticmethod+ def build_debug_headers(+ *,+ inbound_headers: Dict[str, str],+ oauth2_headers: Optional[Dict[str, str]],+ litellm_api_key: Optional[str],+ auth_resolution: str,+ server_url: Optional[str],+ server_auth_type: Optional[str],+ ) -> Dict[str, str]:+ """+ Build masked debug response headers.++ Parameters+ ----------+ inbound_headers : dict+ Raw headers received from the MCP client.+ oauth2_headers : dict or None+ Extracted OAuth2 headers (``{"Authorization": "Bearer ..."}``).+ litellm_api_key : str or None+ The LiteLLM API key extracted from ``x-litellm-api-key`` or+ ``Authorization`` header.+ auth_resolution : str+ Which auth priority was selected for the outbound call.+ server_url : str or None+ Upstream MCP server URL.+ server_auth_type : str or None+ The ``auth_type`` configured on the server (e.g. ``oauth2``).++ Returns+ -------+ dict+ Headers to include in the response (all values masked).+ """+ debug: Dict[str, str] = {}++ # --- Inbound auth summary ---+ inbound_parts = []+ for hdr_name in ("x-litellm-api-key", "authorization", "x-mcp-auth"):+ for k, v in inbound_headers.items():+ if k.lower() == hdr_name:+ inbound_parts.append(f"{hdr_name}={MCPDebug._mask(v)}")+ break+ debug[f"{_RESPONSE_HEADER_PREFIX}-inbound-auth"] = (+ "; ".join(inbound_parts) if inbound_parts else "(none)"+ )++ # --- OAuth2 token ---+ oauth2_token = (oauth2_headers or {}).get("Authorization")+ if oauth2_token and litellm_api_key:+ oauth2_raw = oauth2_token.removeprefix("Bearer ").strip()+ litellm_raw = litellm_api_key.removeprefix("Bearer ").strip()+ if oauth2_raw == litellm_raw:+ debug[f"{_RESPONSE_HEADER_PREFIX}-oauth2-token"] = (+ f"{MCPDebug._mask(oauth2_token)} "+ f"(SAME_AS_LITELLM_KEY - likely misconfigured)"+ )+ else:+ debug[f"{_RESPONSE_HEADER_PREFIX}-oauth2-token"] = MCPDebug._mask(+ oauth2_token+ )+ else:+ debug[f"{_RESPONSE_HEADER_PREFIX}-oauth2-token"] = MCPDebug._mask(+ oauth2_token+ )++ # --- Auth resolution ---+ debug[f"{_RESPONSE_HEADER_PREFIX}-auth-resolution"] = auth_resolution++ # --- Server info ---+ debug[f"{_RESPONSE_HEADER_PREFIX}-outbound-url"] = server_url or "(unknown)"+ debug[f"{_RESPONSE_HEADER_PREFIX}-server-auth-type"] = (+ server_auth_type or "(none)"+ )++ return debug++ @staticmethod+ def wrap_send_with_debug_headers(+ send: Send, debug_headers: Dict[str, str]+ ) -> Send:+ """+ Return a new ASGI ``send`` callable that injects *debug_headers*+ into the ``http.response.start`` message.+ """++ async def _send_with_debug(message: Message) -> None:+ if message["type"] == "http.response.start":+ headers = list(message.get("headers", []))+ for k, v in debug_headers.items():+ headers.append((k.encode(), v.encode()))+ message = {**message, "headers": headers}+ await send(message)++ return _send_with_debug++ @staticmethod+ def maybe_build_debug_headers(+ *,+ raw_headers: Optional[Dict[str, str]],+ scope: Dict,+ mcp_servers: Optional[List[str]],+ mcp_auth_header: Optional[str],+ mcp_server_auth_headers: Optional[Dict[str, Dict[str, str]]],+ oauth2_headers: Optional[Dict[str, str]],+ client_ip: Optional[str],+ ) -> Dict[str, str]:+ """+ Build debug headers if debug mode is enabled, otherwise return empty dict.++ This is the single entry point called from the MCP request handler.+ """+ if not raw_headers or not MCPDebug.is_debug_enabled(raw_headers):+ return {}++ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (+ MCPRequestHandler,+ )+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (+ global_mcp_server_manager,+ )++ server_url: Optional[str] = None+ server_auth_type: Optional[str] = None+ auth_resolution = "no-auth"++ for server_name in mcp_servers or []:+ server = global_mcp_server_manager.get_mcp_server_by_name(+ server_name, client_ip=client_ip+ )+ if server:+ server_url = server.url+ server_auth_type = server.auth_type+ auth_resolution = MCPDebug.resolve_auth_resolution(+ server, mcp_auth_header, mcp_server_auth_headers, oauth2_headers+ )+ break++ scope_headers = MCPRequestHandler._safe_get_headers_from_scope(scope)+ litellm_key = MCPRequestHandler.get_litellm_api_key_from_headers(+ scope_headers+ )++ return MCPDebug.build_debug_headers(+ inbound_headers=raw_headers,+ oauth2_headers=oauth2_headers,+ litellm_api_key=litellm_key,+ auth_resolution=auth_resolution,+ server_url=server_url,+ server_auth_type=server_auth_type,+ )diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex da0df653106..ec31652aa54 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -23,8 +23,8 @@ from typing import (from fastapi import FastAPI, HTTPExceptionfrom pydantic import AnyUrl, ConfigDictfrom starlette.requests import Request as StarletteRequest-from starlette.types import Receive, Scope, Sendfrom starlette.responses import JSONResponse+from starlette.types import Receive, Scope, Sendfrom litellm._logging import verbose_loggerfrom litellm.constants import MAXIMUM_TRACEBACK_LINES_TO_LOG@@ -35,6 +35,7 @@ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (from litellm.proxy._experimental.mcp_server.discoverable_endpoints import (get_request_base_url,)+from litellm.proxy._experimental.mcp_server.mcp_debug import MCPDebugfrom litellm.proxy._experimental.mcp_server.utils import (LITELLM_MCP_SERVER_DESCRIPTION,LITELLM_MCP_SERVER_NAME,@@ -2025,6 +2026,19 @@ if MCP_AVAILABLE:headers={"www-authenticate": authorization_uri},)+ # Inject masked debug headers when client sends x-litellm-mcp-debug: true+ _debug_headers = MCPDebug.maybe_build_debug_headers(+ raw_headers=raw_headers,+ scope=scope,+ mcp_servers=mcp_servers,+ mcp_auth_header=mcp_auth_header,+ mcp_server_auth_headers=mcp_server_auth_headers,+ oauth2_headers=oauth2_headers,+ client_ip=_client_ip,+ )+ if _debug_headers:+ send = MCPDebug.wrap_send_with_debug_headers(send, _debug_headers)+# Set the auth context variable for easy access in MCP functionsset_auth_context(user_api_key_auth=user_api_key_auth,diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_debug.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_debug.pynew file mode 100644index 00000000000..0fb299a57cd--- /dev/null+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_debug.py@@ -0,0 +1,252 @@+"""+Tests for MCPDebug — MCP OAuth2 debug response headers.+"""++import asyncio+from unittest.mock import MagicMock++from litellm.proxy._experimental.mcp_server.mcp_debug import (+ MCP_DEBUG_REQUEST_HEADER,+ MCPDebug,+)+++class TestIsDebugEnabled:+ def test_enabled_true(self):+ assert MCPDebug.is_debug_enabled({MCP_DEBUG_REQUEST_HEADER: "true"}) is True++ def test_enabled_yes(self):+ assert MCPDebug.is_debug_enabled({MCP_DEBUG_REQUEST_HEADER: "yes"}) is True++ def test_enabled_one(self):+ assert MCPDebug.is_debug_enabled({MCP_DEBUG_REQUEST_HEADER: "1"}) is True++ def test_disabled_false(self):+ assert MCPDebug.is_debug_enabled({MCP_DEBUG_REQUEST_HEADER: "false"}) is False++ def test_disabled_missing(self):+ assert MCPDebug.is_debug_enabled({"other-header": "value"}) is False++ def test_case_insensitive_header_name(self):+ assert MCPDebug.is_debug_enabled({"X-LiteLLM-MCP-Debug": "true"}) is True++ def test_case_insensitive_value(self):+ assert MCPDebug.is_debug_enabled({MCP_DEBUG_REQUEST_HEADER: "TRUE"}) is True+++class TestMask:+ def test_none_returns_none_label(self):+ assert MCPDebug._mask(None) == "(none)"++ def test_empty_returns_none_label(self):+ assert MCPDebug._mask("") == "(none)"++ def test_short_value_unchanged(self):+ # visible_prefix=6 + visible_suffix=4 = 10, so <= 10 chars unchanged+ assert MCPDebug._mask("sk-1234") == "sk-1234"++ def test_long_value_masked(self):+ result = MCPDebug._mask("Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9")+ assert result.startswith("Bearer")+ assert result.endswith("VCJ9")+ assert "****" in result or "**" in result++ def test_litellm_key_masked(self):+ result = MCPDebug._mask("Bearer sk-1234567890abcdef")+ assert result.startswith("Bearer")+ assert "sk-1234567890abcdef" not in result+++class TestBuildDebugHeaders:+ def test_basic_no_auth(self):+ headers = MCPDebug.build_debug_headers(+ inbound_headers={"host": "localhost"},+ oauth2_headers=None,+ litellm_api_key=None,+ auth_resolution="no-auth",+ server_url="https://mcp.example.com",+ server_auth_type="oauth2",+ )+ assert headers["x-mcp-debug-inbound-auth"] == "(none)"+ assert headers["x-mcp-debug-oauth2-token"] == "(none)"+ assert headers["x-mcp-debug-auth-resolution"] == "no-auth"+ assert headers["x-mcp-debug-outbound-url"] == "https://mcp.example.com"+ assert headers["x-mcp-debug-server-auth-type"] == "oauth2"++ def test_litellm_key_in_dedicated_header(self):+ headers = MCPDebug.build_debug_headers(+ inbound_headers={+ "x-litellm-api-key": "Bearer sk-1234567890abcdef",+ "host": "localhost",+ },+ oauth2_headers=None,+ litellm_api_key="Bearer sk-1234567890abcdef",+ auth_resolution="no-auth",+ server_url="https://mcp.example.com",+ server_auth_type="oauth2",+ )+ assert "x-litellm-api-key=" in headers["x-mcp-debug-inbound-auth"]+ assert headers["x-mcp-debug-oauth2-token"] == "(none)"++ def test_same_key_flagged(self):+ """When Authorization and x-litellm-api-key carry the same token."""+ headers = MCPDebug.build_debug_headers(+ inbound_headers={+ "authorization": "Bearer sk-1234567890abcdef",+ },+ oauth2_headers={"Authorization": "Bearer sk-1234567890abcdef"},+ litellm_api_key="Bearer sk-1234567890abcdef",+ auth_resolution="oauth2-passthrough",+ server_url="https://mcp.example.com",+ server_auth_type="oauth2",+ )+ assert "SAME_AS_LITELLM_KEY" in headers["x-mcp-debug-oauth2-token"]++ def test_different_tokens_not_flagged(self):+ """When OAuth2 token is different from LiteLLM key."""+ headers = MCPDebug.build_debug_headers(+ inbound_headers={+ "x-litellm-api-key": "Bearer sk-litellm-key-here",+ "authorization": "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.atlassian",+ },+ oauth2_headers={+ "Authorization": "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.atlassian"+ },+ litellm_api_key="Bearer sk-litellm-key-here",+ auth_resolution="oauth2-passthrough",+ server_url="https://mcp.atlassian.com/v1/mcp",+ server_auth_type="oauth2",+ )+ assert "SAME_AS_LITELLM_KEY" not in headers["x-mcp-debug-oauth2-token"]+ assert headers["x-mcp-debug-auth-resolution"] == "oauth2-passthrough"++ def test_m2m_resolution(self):+ headers = MCPDebug.build_debug_headers(+ inbound_headers={"x-litellm-api-key": "Bearer sk-key"},+ oauth2_headers=None,+ litellm_api_key="Bearer sk-key",+ auth_resolution="m2m-client-credentials",+ server_url="https://mcp.example.com",+ server_auth_type="oauth2",+ )+ assert headers["x-mcp-debug-auth-resolution"] == "m2m-client-credentials"++ def test_missing_server_url(self):+ headers = MCPDebug.build_debug_headers(+ inbound_headers={},+ oauth2_headers=None,+ litellm_api_key=None,+ auth_resolution="no-auth",+ server_url=None,+ server_auth_type=None,+ )+ assert headers["x-mcp-debug-outbound-url"] == "(unknown)"+ assert headers["x-mcp-debug-server-auth-type"] == "(none)"++ def test_all_five_headers_present(self):+ headers = MCPDebug.build_debug_headers(+ inbound_headers={},+ oauth2_headers=None,+ litellm_api_key=None,+ auth_resolution="no-auth",+ server_url=None,+ server_auth_type=None,+ )+ expected_keys = {+ "x-mcp-debug-inbound-auth",+ "x-mcp-debug-oauth2-token",+ "x-mcp-debug-auth-resolution",+ "x-mcp-debug-outbound-url",+ "x-mcp-debug-server-auth-type",+ }+ assert set(headers.keys()) == expected_keys+++class TestResolveAuthResolution:+ def _make_server(self, **kwargs):+ server = MagicMock()+ server.alias = kwargs.get("alias", "test")+ server.server_name = kwargs.get("server_name", "test")+ server.has_client_credentials = kwargs.get("has_client_credentials", False)+ server.authentication_token = kwargs.get("authentication_token", None)+ server.auth_type = kwargs.get("auth_type", None)+ return server++ def test_per_request_header(self):+ server = self._make_server()+ result = MCPDebug.resolve_auth_resolution(+ server, mcp_auth_header="Bearer xxx", mcp_server_auth_headers=None, oauth2_headers=None+ )+ assert result == "per-request-header"++ def test_server_specific_header(self):+ server = self._make_server(alias="atlas")+ result = MCPDebug.resolve_auth_resolution(+ server, mcp_auth_header=None,+ mcp_server_auth_headers={"atlas": {"Authorization": "Bearer xxx"}},+ oauth2_headers=None,+ )+ assert result == "per-request-header"++ def test_m2m(self):+ server = self._make_server(has_client_credentials=True)+ result = MCPDebug.resolve_auth_resolution(+ server, mcp_auth_header=None, mcp_server_auth_headers=None, oauth2_headers=None+ )+ assert result == "m2m-client-credentials"++ def test_static_token(self):+ server = self._make_server(authentication_token="static-tok")+ result = MCPDebug.resolve_auth_resolution(+ server, mcp_auth_header=None, mcp_server_auth_headers=None, oauth2_headers=None+ )+ assert result == "static-token"++ def test_oauth2_passthrough(self):+ server = self._make_server(auth_type="oauth2")+ result = MCPDebug.resolve_auth_resolution(+ server, mcp_auth_header=None, mcp_server_auth_headers=None,+ oauth2_headers={"Authorization": "Bearer eyJ..."},+ )+ assert result == "oauth2-passthrough"++ def test_no_auth(self):+ server = self._make_server()+ result = MCPDebug.resolve_auth_resolution(+ server, mcp_auth_header=None, mcp_server_auth_headers=None, oauth2_headers=None+ )+ assert result == "no-auth"+++class TestWrapSendWithDebugHeaders:+ def test_injects_headers(self):+ captured = []++ async def mock_send(message):+ captured.append(message)++ wrapped = MCPDebug.wrap_send_with_debug_headers(+ mock_send, {"x-mcp-debug-test": "value123"}+ )++ message = {"type": "http.response.start", "status": 200, "headers": []}+ asyncio.get_event_loop().run_until_complete(wrapped(message))++ assert len(captured) == 1+ headers = dict(captured[0]["headers"])+ assert headers[b"x-mcp-debug-test"] == b"value123"++ def test_body_messages_unchanged(self):+ captured = []++ async def mock_send(message):+ captured.append(message)++ wrapped = MCPDebug.wrap_send_with_debug_headers(+ mock_send, {"x-mcp-debug-test": "value"}+ )++ body_msg = {"type": "http.response.body", "body": b"hello"}+ asyncio.get_event_loop().run_until_complete(wrapped(body_msg))++ assert captured[0] == body_msg