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(proxy_server.py): preserve content field even if null (#16988)
Krish Dholakia760bce24bdc2
diff --git a/docs/my-website/docs/mcp.md b/docs/my-website/docs/mcp.mdindex 9a1e25a516c..887c5278144 100644--- a/docs/my-website/docs/mcp.md+++ b/docs/my-website/docs/mcp.md@@ -278,14 +278,14 @@ litellm_settings:LiteLLM can automatically convert OpenAPI specifications into MCP servers, allowing you to expose any REST API as MCP tools. This is useful when you have existing APIs with OpenAPI/Swagger documentation and want to make them available as MCP tools.-### Benefits+**Benefits:**- **Rapid Integration**: Convert existing APIs to MCP tools without writing custom MCP server code- **Automatic Tool Generation**: LiteLLM automatically generates MCP tools from your OpenAPI spec- **Unified Interface**: Use the same MCP interface for both native MCP servers and OpenAPI-based APIs- **Easy Testing**: Test and iterate on API integrations quickly-### Configuration+**Configuration:**Add your OpenAPI-based MCP server to your `config.yaml`:@@ -318,7 +318,7 @@ mcp_servers:auth_value: "your-bearer-token"```-### Configuration Parameters+**Configuration Parameters:**| Parameter | Required | Description ||-----------|----------|-------------|@@ -430,7 +430,7 @@ curl --location 'https://api.openai.com/v1/responses' \</TabItem></Tabs>-### How It Works+**How It Works**1. **Spec Loading**: LiteLLM loads your OpenAPI specification from the provided `spec_path`2. **Tool Generation**: Each API endpoint in the spec becomes an MCP tool@@ -438,7 +438,7 @@ curl --location 'https://api.openai.com/v1/responses' \4. **Request Handling**: When a tool is called, LiteLLM converts the MCP request to the appropriate HTTP request5. **Response Translation**: API responses are converted back to MCP format-### OpenAPI Spec Requirements+**OpenAPI Spec Requirements**Your OpenAPI specification should follow standard OpenAPI/Swagger conventions:- **Supported versions**: OpenAPI 3.0.x, OpenAPI 3.1.x, Swagger 2.0@@ -446,585 +446,94 @@ Your OpenAPI specification should follow standard OpenAPI/Swagger conventions:- **Operation IDs**: Each operation should have a unique `operationId` (this becomes the tool name)- **Parameters**: Request parameters should be properly documented with types and descriptions-### Example OpenAPI Spec Structure--```yaml title="sample-openapi.yaml" showLineNumbers-openapi: 3.0.0-info:- title: My API- version: 1.0.0-paths:- /pets/{petId}:- get:- operationId: getPetById- summary: Get a pet by ID- parameters:- - name: petId- in: path- required: true- schema:- type: integer- responses:- '200':- description: Successful response- content:- application/json:- schema:- type: object-```--## Allow/Disallow MCP Tools--Control which tools are available from your MCP servers. You can either allow only specific tools or block dangerous ones.--<Tabs>-<TabItem value="allowed" label="Only Allow Specific Tools">--Use `allowed_tools` to specify exactly which tools users can access. All other tools will be blocked.--```yaml title="config.yaml" showLineNumbers-mcp_servers:- github_mcp:- url: "https://api.githubcopilot.com/mcp"- auth_type: oauth2- authorization_url: https://github.com/login/oauth/authorize- token_url: https://github.com/login/oauth/access_token- client_id: os.environ/GITHUB_OAUTH_CLIENT_ID- client_secret: os.environ/GITHUB_OAUTH_CLIENT_SECRET- scopes: ["public_repo", "user:email"]- allowed_tools: ["list_tools"]- # only list_tools will be available-```--**Use this when:**-- You want strict control over which tools are available-- You're in a high-security environment-- You're testing a new MCP server with limited tools+## MCP Oauth-</TabItem>-<TabItem value="blocked" label="Block Specific Tools">+LiteLLM v 1.77.6 added support for OAuth 2.0 Client Credentials for MCP servers.-Use `disallowed_tools` to block specific tools. All other tools will be available.+This configuration is currently available on the config.yaml, with UI support coming soon.-```yaml title="config.yaml" showLineNumbers+```yamlmcp_servers:github_mcp:url: "https://api.githubcopilot.com/mcp"auth_type: oauth2- authorization_url: https://github.com/login/oauth/authorize- token_url: https://github.com/login/oauth/access_tokenclient_id: os.environ/GITHUB_OAUTH_CLIENT_IDclient_secret: os.environ/GITHUB_OAUTH_CLIENT_SECRET- scopes: ["public_repo", "user:email"]- disallowed_tools: ["repo_delete"]- # only repo_delete will be blocked```-**Use this when:**-- Most tools are safe, but you want to block a few dangerous ones-- You want to prevent expensive API calls-- You're gradually adding restrictions to an existing server--</TabItem>-</Tabs>--### Important Notes--- If you specify both `allowed_tools` and `disallowed_tools`, the allowed list takes priority-- Tool names are case-sensitive-------## Allow/Disallow MCP Tool Parameters--Control which parameters are allowed for specific MCP tools using the `allowed_params` configuration. This provides fine-grained control over tool usage by restricting the parameters that can be passed to each tool.--### Configuration--`allowed_params` is a dictionary that maps tool names to lists of allowed parameter names. When configured, only the specified parameters will be accepted for that tool - any other parameters will be rejected with a 403 error.--```yaml title="config.yaml with allowed_params" showLineNumbers-mcp_servers:- deepwiki_mcp:- url: https://mcp.deepwiki.com/mcp- transport: "http"- auth_type: "none"- allowed_params:- # Tool name: list of allowed parameters- read_wiki_contents: ["status"]-- my_api_mcp:- url: "https://my-api-server.com"- auth_type: "api_key"- auth_value: "my-key"- allowed_params:- # Using unprefixed tool name- getpetbyid: ["status"]- # Using prefixed tool name (both formats work)- my_api_mcp-findpetsbystatus: ["status", "limit"]- # Another tool with multiple allowed params- create_issue: ["title", "body", "labels"]-```+[**See Claude Code Tutorial**](./tutorials/claude_responses_api#connecting-mcp-servers)### How It Works-1. **Tool-specific filtering**: Each tool can have its own list of allowed parameters-2. **Flexible naming**: Tool names can be specified with or without the server prefix (e.g., both `"getpetbyid"` and `"my_api_mcp-getpetbyid"` work)-3. **Whitelist approach**: Only parameters in the allowed list are permitted-4. **Unlisted tools**: If `allowed_params` is not set, all parameters are allowed-5. **Error handling**: Requests with disallowed parameters receive a 403 error with details about which parameters are allowed--### Example Request Behavior--With the configuration above, here's how requests would be handled:--**✅ Allowed Request:**-```json-{- "tool": "read_wiki_contents",- "arguments": {- "status": "active"- }-}-```--**❌ Rejected Request:**-```json-{- "tool": "read_wiki_contents",- "arguments": {- "status": "active",- "limit": 10 // This parameter is not allowed- }-}-```--**Error Response:**-```json-{- "error": "Parameters ['limit'] are not allowed for tool read_wiki_contents. Allowed parameters: ['status']. Contact proxy admin to allow these parameters."-}-```--### Use Cases--- **Security**: Prevent users from accessing sensitive parameters or dangerous operations-- **Cost control**: Restrict expensive parameters (e.g., limiting result counts)-- **Compliance**: Enforce parameter usage policies for regulatory requirements-- **Staged rollouts**: Gradually enable parameters as tools are tested-- **Multi-tenant isolation**: Different parameter access for different user groups--### Combining with Tool Filtering--`allowed_params` works alongside `allowed_tools` and `disallowed_tools` for complete control:--```yaml title="Combined filtering example" showLineNumbers-mcp_servers:- github_mcp:- url: "https://api.githubcopilot.com/mcp"- auth_type: oauth2- authorization_url: https://github.com/login/oauth/authorize- token_url: https://github.com/login/oauth/access_token- client_id: os.environ/GITHUB_OAUTH_CLIENT_ID- client_secret: os.environ/GITHUB_OAUTH_CLIENT_SECRET- scopes: ["public_repo", "user:email"]- # Only allow specific tools- allowed_tools: ["create_issue", "list_issues", "search_issues"]- # Block dangerous operations- disallowed_tools: ["delete_repo"]- # Restrict parameters per tool- allowed_params:- create_issue: ["title", "body", "labels"]- list_issues: ["state", "sort", "perPage"]- search_issues: ["query", "sort", "order", "perPage"]-```--This configuration ensures that:-1. Only the three listed tools are available-2. The `delete_repo` tool is explicitly blocked-3. Each tool can only use its specified parameters-------## MCP Server Access Control--LiteLLM Proxy provides two methods for controlling access to specific MCP servers:--1. **URL-based Namespacing** - Use URL paths to directly access specific servers or access groups-2. **Header-based Namespacing** - Use the `x-mcp-servers` header to specify which servers to access-------### Method 1: URL-based Namespacing--LiteLLM Proxy supports URL-based namespacing for MCP servers using the format `/<servers or access groups>/mcp`. This allows you to:--- **Direct URL Access**: Point MCP clients directly to specific servers or access groups via URL-- **Simplified Configuration**: Use URLs instead of headers for server selection-- **Access Group Support**: Use access group names in URLs for grouped server access--#### URL Format--```-<your-litellm-proxy-base-url>/<server_alias_or_access_group>/mcp-```--**Examples:**-- `/github_mcp/mcp` - Access tools from the "github_mcp" MCP server-- `/zapier/mcp` - Access tools from the "zapier" MCP server-- `/dev_group/mcp` - Access tools from all servers in the "dev_group" access group-- `/github_mcp,zapier/mcp` - Access tools from multiple specific servers--#### Usage Examples--<Tabs>-<TabItem value="openai" label="OpenAI API">--```bash title="cURL Example with URL Namespacing" showLineNumbers-curl --location 'https://api.openai.com/v1/responses' \---header 'Content-Type: application/json' \---header "Authorization: Bearer $OPENAI_API_KEY" \---data '{- "model": "gpt-4o",- "tools": [- {- "type": "mcp",- "server_label": "litellm",- "server_url": "<your-litellm-proxy-base-url>/github_mcp/mcp",- "require_approval": "never",- "headers": {- "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY"- }- }- ],- "input": "Run available tools",- "tool_choice": "required"-}'-```--This example uses URL namespacing to access only the "github" MCP server.--</TabItem>--<TabItem value="litellm" label="LiteLLM Proxy">--```bash title="cURL Example with URL Namespacing" showLineNumbers-curl --location '<your-litellm-proxy-base-url>/v1/responses' \---header 'Content-Type: application/json' \---header "Authorization: Bearer $LITELLM_API_KEY" \---data '{- "model": "gpt-4o",- "tools": [- {- "type": "mcp",- "server_label": "litellm",- "server_url": "<your-litellm-proxy-base-url>/dev_group/mcp",- "require_approval": "never",- "headers": {- "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY"- }- }- ],- "input": "Run available tools",- "tool_choice": "required"-}'-```--This example uses URL namespacing to access all servers in the "dev_group" access group.--</TabItem>--<TabItem value="cursor" label="Cursor IDE">--```json title="Cursor MCP Configuration with URL Namespacing" showLineNumbers-{- "mcpServers": {- "LiteLLM": {- "url": "<your-litellm-proxy-base-url>/github_mcp,zapier/mcp",- "headers": {- "x-litellm-api-key": "Bearer $LITELLM_API_KEY"- }- }- }-}-```--This configuration uses URL namespacing to access tools from both "github" and "zapier" MCP servers.--</TabItem>-</Tabs>--#### Benefits of URL Namespacing--- **Direct Access**: No need for additional headers to specify servers-- **Clean URLs**: Self-documenting URLs that clearly indicate which servers are accessible-- **Access Group Support**: Use access group names for grouped server access-- **Multiple Servers**: Specify multiple servers in a single URL with comma separation-- **Simplified Configuration**: Easier setup for MCP clients that prefer URL-based configuration-------### Method 2: Header-based Namespacing--You can choose to access specific MCP servers and only list their tools using the `x-mcp-servers` header. This header allows you to:-- Limit tool access to one or more specific MCP servers-- Control which tools are available in different environments or use cases--The header accepts a comma-separated list of server aliases: `"alias_1,Server2,Server3"`--**Notes:**-- If the header is not provided, tools from all available MCP servers will be accessible-- This method works with the standard LiteLLM MCP endpoint--<Tabs>-<TabItem value="openai" label="OpenAI API">--```bash title="cURL Example with Header Namespacing" showLineNumbers-curl --location 'https://api.openai.com/v1/responses' \---header 'Content-Type: application/json' \---header "Authorization: Bearer $OPENAI_API_KEY" \---data '{- "model": "gpt-4o",- "tools": [- {- "type": "mcp",- "server_label": "litellm",- "server_url": "<your-litellm-proxy-base-url>/mcp/",- "require_approval": "never",- "headers": {- "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",- "x-mcp-servers": "alias_1"- }- }- ],- "input": "Run available tools",- "tool_choice": "required"-}'-```--In this example, the request will only have access to tools from the "alias_1" MCP server.--</TabItem>--<TabItem value="litellm" label="LiteLLM Proxy">--```bash title="cURL Example with Header Namespacing" showLineNumbers-curl --location '<your-litellm-proxy-base-url>/v1/responses' \---header 'Content-Type: application/json' \---header "Authorization: Bearer $LITELLM_API_KEY" \---data '{- "model": "gpt-4o",- "tools": [- {- "type": "mcp",- "server_label": "litellm",- "server_url": "<your-litellm-proxy-base-url>/mcp/",- "require_approval": "never",- "headers": {- "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",- "x-mcp-servers": "alias_1,Server2"- }- }- ],- "input": "Run available tools",- "tool_choice": "required"-}'-```--This configuration restricts the request to only use tools from the specified MCP servers.--</TabItem>--<TabItem value="cursor" label="Cursor IDE">--```json title="Cursor MCP Configuration with Header Namespacing" showLineNumbers-{- "mcpServers": {- "LiteLLM": {- "url": "<your-litellm-proxy-base-url>/mcp/",- "headers": {- "x-litellm-api-key": "Bearer $LITELLM_API_KEY",- "x-mcp-servers": "alias_1,Server2"- }- }- }-}-```--This configuration in Cursor IDE settings will limit tool access to only the specified MCP servers.--</TabItem>-</Tabs>-------### Comparison: Header vs URL Namespacing--| Feature | Header Namespacing | URL Namespacing |-|---------|-------------------|-----------------|-| **Method** | Uses `x-mcp-servers` header | Uses URL path `/<servers>/mcp` |-| **Endpoint** | Standard `litellm_proxy` endpoint | Custom `/<servers>/mcp` endpoint |-| **Configuration** | Requires additional header | Self-contained in URL |-| **Multiple Servers** | Comma-separated in header | Comma-separated in URL path |-| **Access Groups** | Supported via header | Supported via URL path |-| **Client Support** | Works with all MCP clients | Works with URL-aware MCP clients |-| **Use Case** | Dynamic server selection | Fixed server configuration |--<Tabs>-<TabItem value="openai" label="OpenAI API">--```bash title="cURL Example with Server Segregation" showLineNumbers-curl --location 'https://api.openai.com/v1/responses' \---header 'Content-Type: application/json' \---header "Authorization: Bearer $OPENAI_API_KEY" \---data '{- "model": "gpt-4o",- "tools": [- {- "type": "mcp",- "server_label": "litellm",- "server_url": "<your-litellm-proxy-base-url>/mcp/",- "require_approval": "never",- "headers": {- "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",- "x-mcp-servers": "alias_1"- }- }- ],- "input": "Run available tools",- "tool_choice": "required"-}'-```--In this example, the request will only have access to tools from the "alias_1" MCP server.--</TabItem>--<TabItem value="litellm" label="LiteLLM Proxy">--```bash title="cURL Example with Server Segregation" showLineNumbers-curl --location '<your-litellm-proxy-base-url>/v1/responses' \---header 'Content-Type: application/json' \---header "Authorization: Bearer $LITELLM_API_KEY" \---data '{- "model": "gpt-4o",- "tools": [- {- "type": "mcp",- "server_label": "litellm",- "server_url": "litellm_proxy",- "require_approval": "never",- "headers": {- "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",- "x-mcp-servers": "alias_1,Server2"- }- }- ],- "input": "Run available tools",- "tool_choice": "required"-}'-```--This configuration restricts the request to only use tools from the specified MCP servers.--</TabItem>--<TabItem value="cursor" label="Cursor IDE">--```json title="Cursor MCP Configuration with Server Segregation" showLineNumbers-{- "mcpServers": {- "LiteLLM": {- "url": "litellm_proxy",- "headers": {- "x-litellm-api-key": "Bearer $LITELLM_API_KEY",- "x-mcp-servers": "alias_1,Server2"- }- }- }-}-```--This configuration in Cursor IDE settings will limit tool access to only the specified MCP server.--</TabItem>-</Tabs>--### Grouping MCPs (Access Groups)--MCP Access Groups allow you to group multiple MCP servers together for easier management.--#### 1. Create an Access Group--##### A. Creating Access Groups using Config:--```yaml title="Creating access groups for MCP using the config" showLineNumbers-mcp_servers:- "deepwiki_mcp":- url: https://mcp.deepwiki.com/mcp- transport: "http"- auth_type: "none"- access_groups: ["dev_group"]-```--While adding `mcp_servers` using the config:-- Pass in a list of strings inside `access_groups`-- These groups can then be used for segregating access using keys, teams and MCP clients using headers+```mermaid+sequenceDiagram+ participant Browser as User-Agent (Browser)+ participant Client as Client+ participant LiteLLM as LiteLLM Proxy+ participant MCP as MCP Server (Resource Server)+ participant Auth as Authorization Server-##### B. Creating Access Groups using UI+ Note over Client,LiteLLM: Step 1 – Resource discovery+ Client->>LiteLLM: GET /.well-known/oauth-protected-resource/{mcp_server_name}/mcp+ LiteLLM->>Client: Return resource metadata-To create an access group:-- Go to MCP Servers in the LiteLLM UI-- Click "Add a New MCP Server"-- Under "MCP Access Groups", create a new group (e.g., "dev_group") by typing it-- Add the same group name to other servers to group them together+ Note over Client,LiteLLM: Step 2 – Authorization server discovery+ Client->>LiteLLM: GET /.well-known/oauth-authorization-server/{mcp_server_name}+ LiteLLM->>Client: Return authorization server metadata-<Image- img={require('../img/mcp_create_access_group.png')}- style={{width: '80%', display: 'block', margin: '0'}}-/>+ Note over Client,Auth: Step 3 – Dynamic client registration+ Client->>LiteLLM: POST /{mcp_server_name}/register+ LiteLLM->>Auth: Forward registration request+ Auth->>LiteLLM: Issue client credentials+ LiteLLM->>Client: Return client credentials-#### 2. Use Access Group in Cursor+ Note over Client,Browser: Step 4 – User authorization (PKCE)+ Client->>Browser: Open authorization URL + code_challenge + resource+ Browser->>Auth: Authorization request+ Note over Auth: User authorizes+ Auth->>Browser: Redirect with authorization code+ Browser->>LiteLLM: Callback to LiteLLM with code+ LiteLLM->>Browser: Redirect back with authorization code+ Browser->>Client: Callback with authorization code-Include the access group name in the `x-mcp-servers` header:+ Note over Client,Auth: Step 5 – Token exchange+ Client->>LiteLLM: Token request + code_verifier + resource+ LiteLLM->>Auth: Forward token request+ Auth->>LiteLLM: Access (and refresh) token+ LiteLLM->>Client: Return tokens-```json title="Cursor Configuration with Access Groups" showLineNumbers-{- "mcpServers": {- "LiteLLM": {- "url": "litellm_proxy",- "headers": {- "x-litellm-api-key": "Bearer $LITELLM_API_KEY",- "x-mcp-servers": "dev_group"- }- }- }-}+ Note over Client,MCP: Step 6 – Authenticated MCP call+ Client->>LiteLLM: MCP request with access token + LiteLLM API key+ LiteLLM->>MCP: MCP request with Bearer token+ MCP-->>LiteLLM: MCP response+ LiteLLM-->>Client: Return MCP response```-This gives you access to all servers in the "dev_group" access group.-- Which means that if deepwiki server (and any other servers) which have the access group `dev_group` assigned to them will be available for tool calling+**Participants**-#### Advanced: Connecting Access Groups to API Keys+- **Client** – The MCP-capable AI agent (e.g., Claude Code, Cursor, or another IDE/agent) that initiates OAuth discovery, authorization, and tool invocations on behalf of the user.+- **LiteLLM Proxy** – Mediates all OAuth discovery, registration, token exchange, and MCP traffic while protecting stored credentials.+- **Authorization Server** – Issues OAuth 2.0 tokens via dynamic client registration, PKCE authorization, and token endpoints.+- **MCP Server (Resource Server)** – The protected MCP endpoint that receives LiteLLM’s authenticated JSON-RPC requests.+- **User-Agent (Browser)** – Temporarily involved so the end user can grant consent during the authorization step.-When creating API keys, you can assign them to specific access groups for permission management:+**Flow Steps**-- Go to "Keys" in the LiteLLM UI and click "Create Key"-- Select the desired MCP access groups from the dropdown-- The key will have access to all MCP servers in those groups-- This is reflected in the Test Key page+1. **Resource Discovery**: The client fetches MCP resource metadata from LiteLLM’s `.well-known/oauth-protected-resource` endpoint to understand scopes and capabilities.+2. **Authorization Server Discovery**: The client retrieves the OAuth server metadata (token endpoint, authorization endpoint, supported PKCE methods) through LiteLLM’s `.well-known/oauth-authorization-server` endpoint.+3. **Dynamic Client Registration**: The client registers through LiteLLM, which forwards the request to the authorization server (RFC 7591). If the provider doesn’t support dynamic registration, you can pre-store `client_id`/`client_secret` in LiteLLM (e.g., GitHub MCP) and the flow proceeds the same way.+4. **User Authorization**: The client launches a browser session (with code challenge and resource hints). The user approves access, the authorization server sends the code through LiteLLM back to the client.+5. **Token Exchange**: The client calls LiteLLM with the authorization code, code verifier, and resource. LiteLLM exchanges them with the authorization server and returns the issued access/refresh tokens.+6. **MCP Invocation**: With a valid token, the client sends the MCP JSON-RPC request (plus LiteLLM API key) to LiteLLM, which forwards it to the MCP server and relays the tool response.-<Image- img={require('../img/mcp_key_access_group.png')}- style={{width: '80%', display: 'block', margin: '0'}}-/>+See the official [MCP Authorization Flow](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#authorization-flow-steps) for additional reference.## Forwarding Custom Headers to MCP ServersLiteLLM supports forwarding additional custom headers from MCP clients to backend MCP servers using the `extra_headers` configuration parameter. This allows you to pass custom authentication tokens, API keys, or other headers that your MCP server requires.-### Configuration+**Configuration**<Tabs>@@ -1110,7 +619,7 @@ if __name__ == "__main__":</Tabs>-### Client Usage+#### Client UsageWhen connecting from MCP clients, include the custom headers that match the `extra_headers` configuration:@@ -1195,109 +704,15 @@ curl --location 'http://localhost:4000/github_mcp/mcp' \</TabItem></Tabs>-### How It Works+#### How It Works1. **Configuration**: Define `extra_headers` in your MCP server config with the header names you want to forward2. **Client Headers**: Include the corresponding headers in your MCP client requests3. **Header Forwarding**: LiteLLM automatically forwards matching headers to the backend MCP server4. **Authentication**: The backend MCP server receives both the configured auth headers and the custom headers-### Use Cases--- **Custom Authentication**: Forward custom API keys or tokens required by specific MCP servers-- **Request Context**: Pass user identification, session data, or request tracking headers-- **Third-party Integration**: Include headers required by external services that your MCP server integrates with-- **Multi-tenant Systems**: Forward tenant-specific headers for proper request routing--### Security Considerations--- Only headers listed in `extra_headers` are forwarded to maintain security-- Sensitive headers should be passed through environment variables when possible-- Consider using server-specific auth headers for better security isolation-----## MCP Oauth--LiteLLM v 1.77.6 added support for OAuth 2.0 Client Credentials for MCP servers.--This configuration is currently available on the config.yaml, with UI support coming soon.--```yaml-mcp_servers:- github_mcp:- url: "https://api.githubcopilot.com/mcp"- auth_type: oauth2- client_id: os.environ/GITHUB_OAUTH_CLIENT_ID- client_secret: os.environ/GITHUB_OAUTH_CLIENT_SECRET-```--[**See Claude Code Tutorial**](./tutorials/claude_responses_api#connecting-mcp-servers)--### How It Works--```mermaid-sequenceDiagram- participant Browser as User-Agent (Browser)- participant Client as Client- participant LiteLLM as LiteLLM Proxy- participant MCP as MCP Server (Resource Server)- participant Auth as Authorization Server-- Note over Client,LiteLLM: Step 1 – Resource discovery- Client->>LiteLLM: GET /.well-known/oauth-protected-resource/{mcp_server_name}/mcp- LiteLLM->>Client: Return resource metadata-- Note over Client,LiteLLM: Step 2 – Authorization server discovery- Client->>LiteLLM: GET /.well-known/oauth-authorization-server/{mcp_server_name}- LiteLLM->>Client: Return authorization server metadata-- Note over Client,Auth: Step 3 – Dynamic client registration- Client->>LiteLLM: POST /{mcp_server_name}/register- LiteLLM->>Auth: Forward registration request- Auth->>LiteLLM: Issue client credentials- LiteLLM->>Client: Return client credentials-- Note over Client,Browser: Step 4 – User authorization (PKCE)- Client->>Browser: Open authorization URL + code_challenge + resource- Browser->>Auth: Authorization request- Note over Auth: User authorizes- Auth->>Browser: Redirect with authorization code- Browser->>LiteLLM: Callback to LiteLLM with code- LiteLLM->>Browser: Redirect back with authorization code- Browser->>Client: Callback with authorization code-- Note over Client,Auth: Step 5 – Token exchange- Client->>LiteLLM: Token request + code_verifier + resource- LiteLLM->>Auth: Forward token request- Auth->>LiteLLM: Access (and refresh) token- LiteLLM->>Client: Return tokens-- Note over Client,MCP: Step 6 – Authenticated MCP call- Client->>LiteLLM: MCP request with access token + LiteLLM API key- LiteLLM->>MCP: MCP request with Bearer token- MCP-->>LiteLLM: MCP response- LiteLLM-->>Client: Return MCP response-```--**Participants**--- **Client** – The MCP-capable AI agent (e.g., Claude Code, Cursor, or another IDE/agent) that initiates OAuth discovery, authorization, and tool invocations on behalf of the user.-- **LiteLLM Proxy** – Mediates all OAuth discovery, registration, token exchange, and MCP traffic while protecting stored credentials.-- **Authorization Server** – Issues OAuth 2.0 tokens via dynamic client registration, PKCE authorization, and token endpoints.-- **MCP Server (Resource Server)** – The protected MCP endpoint that receives LiteLLM’s authenticated JSON-RPC requests.-- **User-Agent (Browser)** – Temporarily involved so the end user can grant consent during the authorization step.--**Flow Steps**--1. **Resource Discovery**: The client fetches MCP resource metadata from LiteLLM’s `.well-known/oauth-protected-resource` endpoint to understand scopes and capabilities.-2. **Authorization Server Discovery**: The client retrieves the OAuth server metadata (token endpoint, authorization endpoint, supported PKCE methods) through LiteLLM’s `.well-known/oauth-authorization-server` endpoint.-3. **Dynamic Client Registration**: The client registers through LiteLLM, which forwards the request to the authorization server (RFC 7591). If the provider doesn’t support dynamic registration, you can pre-store `client_id`/`client_secret` in LiteLLM (e.g., GitHub MCP) and the flow proceeds the same way.-4. **User Authorization**: The client launches a browser session (with code challenge and resource hints). The user approves access, the authorization server sends the code through LiteLLM back to the client.-5. **Token Exchange**: The client calls LiteLLM with the authorization code, code verifier, and resource. LiteLLM exchanges them with the authorization server and returns the issued access/refresh tokens.-6. **MCP Invocation**: With a valid token, the client sends the MCP JSON-RPC request (plus LiteLLM API key) to LiteLLM, which forwards it to the MCP server and relays the tool response.--See the official [MCP Authorization Flow](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#authorization-flow-steps) for additional reference.## Using your MCP with client side credentialsdiff --git a/docs/my-website/docs/mcp_control.md b/docs/my-website/docs/mcp_control.mdindex 484cb13708c..c8c3d8e10f3 100644--- a/docs/my-website/docs/mcp_control.md+++ b/docs/my-website/docs/mcp_control.md@@ -35,6 +35,554 @@ When Creating a Key, Team, or Organization, you can select the allowed MCP Serve/>+## Allow/Disallow MCP Tools++Control which tools are available from your MCP servers. You can either allow only specific tools or block dangerous ones.++<Tabs>+<TabItem value="allowed" label="Only Allow Specific Tools">++Use `allowed_tools` to specify exactly which tools users can access. All other tools will be blocked.++```yaml title="config.yaml" showLineNumbers+mcp_servers:+ github_mcp:+ url: "https://api.githubcopilot.com/mcp"+ auth_type: oauth2+ authorization_url: https://github.com/login/oauth/authorize+ token_url: https://github.com/login/oauth/access_token+ client_id: os.environ/GITHUB_OAUTH_CLIENT_ID+ client_secret: os.environ/GITHUB_OAUTH_CLIENT_SECRET+ scopes: ["public_repo", "user:email"]+ allowed_tools: ["list_tools"]+ # only list_tools will be available+```++**Use this when:**+- You want strict control over which tools are available+- You're in a high-security environment+- You're testing a new MCP server with limited tools++</TabItem>+<TabItem value="blocked" label="Block Specific Tools">++Use `disallowed_tools` to block specific tools. All other tools will be available.++```yaml title="config.yaml" showLineNumbers+mcp_servers:+ github_mcp:+ url: "https://api.githubcopilot.com/mcp"+ auth_type: oauth2+ authorization_url: https://github.com/login/oauth/authorize+ token_url: https://github.com/login/oauth/access_token+ client_id: os.environ/GITHUB_OAUTH_CLIENT_ID+ client_secret: os.environ/GITHUB_OAUTH_CLIENT_SECRET+ scopes: ["public_repo", "user:email"]+ disallowed_tools: ["repo_delete"]+ # only repo_delete will be blocked+```++**Use this when:**+- Most tools are safe, but you want to block a few dangerous ones+- You want to prevent expensive API calls+- You're gradually adding restrictions to an existing server++</TabItem>+</Tabs>++### Important Notes++- If you specify both `allowed_tools` and `disallowed_tools`, the allowed list takes priority+- Tool names are case-sensitive++---++## Allow/Disallow MCP Tool Parameters++Control which parameters are allowed for specific MCP tools using the `allowed_params` configuration. This provides fine-grained control over tool usage by restricting the parameters that can be passed to each tool.++### Configuration++`allowed_params` is a dictionary that maps tool names to lists of allowed parameter names. When configured, only the specified parameters will be accepted for that tool - any other parameters will be rejected with a 403 error.++```yaml title="config.yaml with allowed_params" showLineNumbers+mcp_servers:+ deepwiki_mcp:+ url: https://mcp.deepwiki.com/mcp+ transport: "http"+ auth_type: "none"+ allowed_params:+ # Tool name: list of allowed parameters+ read_wiki_contents: ["status"]++ my_api_mcp:+ url: "https://my-api-server.com"+ auth_type: "api_key"+ auth_value: "my-key"+ allowed_params:+ # Using unprefixed tool name+ getpetbyid: ["status"]+ # Using prefixed tool name (both formats work)+ my_api_mcp-findpetsbystatus: ["status", "limit"]+ # Another tool with multiple allowed params+ create_issue: ["title", "body", "labels"]+```++### How It Works++1. **Tool-specific filtering**: Each tool can have its own list of allowed parameters+2. **Flexible naming**: Tool names can be specified with or without the server prefix (e.g., both `"getpetbyid"` and `"my_api_mcp-getpetbyid"` work)+3. **Whitelist approach**: Only parameters in the allowed list are permitted+4. **Unlisted tools**: If `allowed_params` is not set, all parameters are allowed+5. **Error handling**: Requests with disallowed parameters receive a 403 error with details about which parameters are allowed++### Example Request Behavior++With the configuration above, here's how requests would be handled:++**✅ Allowed Request:**+```json+{+ "tool": "read_wiki_contents",+ "arguments": {+ "status": "active"+ }+}+```++**❌ Rejected Request:**+```json+{+ "tool": "read_wiki_contents",+ "arguments": {+ "status": "active",+ "limit": 10 // This parameter is not allowed+ }+}+```++**Error Response:**+```json+{+ "error": "Parameters ['limit'] are not allowed for tool read_wiki_contents. Allowed parameters: ['status']. Contact proxy admin to allow these parameters."+}+```++### Use Cases++- **Security**: Prevent users from accessing sensitive parameters or dangerous operations+- **Cost control**: Restrict expensive parameters (e.g., limiting result counts)+- **Compliance**: Enforce parameter usage policies for regulatory requirements+- **Staged rollouts**: Gradually enable parameters as tools are tested+- **Multi-tenant isolation**: Different parameter access for different user groups++### Combining with Tool Filtering++`allowed_params` works alongside `allowed_tools` and `disallowed_tools` for complete control:++```yaml title="Combined filtering example" showLineNumbers+mcp_servers:+ github_mcp:+ url: "https://api.githubcopilot.com/mcp"+ auth_type: oauth2+ authorization_url: https://github.com/login/oauth/authorize+ token_url: https://github.com/login/oauth/access_token+ client_id: os.environ/GITHUB_OAUTH_CLIENT_ID+ client_secret: os.environ/GITHUB_OAUTH_CLIENT_SECRET+ scopes: ["public_repo", "user:email"]+ # Only allow specific tools+ allowed_tools: ["create_issue", "list_issues", "search_issues"]+ # Block dangerous operations+ disallowed_tools: ["delete_repo"]+ # Restrict parameters per tool+ allowed_params:+ create_issue: ["title", "body", "labels"]+ list_issues: ["state", "sort", "perPage"]+ search_issues: ["query", "sort", "order", "perPage"]+```++This configuration ensures that:+1. Only the three listed tools are available+2. The `delete_repo` tool is explicitly blocked+3. Each tool can only use its specified parameters++---++## MCP Server Access Control++LiteLLM Proxy provides two methods for controlling access to specific MCP servers:++1. **URL-based Namespacing** - Use URL paths to directly access specific servers or access groups+2. **Header-based Namespacing** - Use the `x-mcp-servers` header to specify which servers to access++---++### Method 1: URL-based Namespacing++LiteLLM Proxy supports URL-based namespacing for MCP servers using the format `/<servers or access groups>/mcp`. This allows you to:++- **Direct URL Access**: Point MCP clients directly to specific servers or access groups via URL+- **Simplified Configuration**: Use URLs instead of headers for server selection+- **Access Group Support**: Use access group names in URLs for grouped server access++#### URL Format++```+<your-litellm-proxy-base-url>/<server_alias_or_access_group>/mcp+```++**Examples:**+- `/github_mcp/mcp` - Access tools from the "github_mcp" MCP server+- `/zapier/mcp` - Access tools from the "zapier" MCP server+- `/dev_group/mcp` - Access tools from all servers in the "dev_group" access group+- `/github_mcp,zapier/mcp` - Access tools from multiple specific servers++#### Usage Examples++<Tabs>+<TabItem value="openai" label="OpenAI API">++```bash title="cURL Example with URL Namespacing" showLineNumbers+curl --location 'https://api.openai.com/v1/responses' \+--header 'Content-Type: application/json' \+--header "Authorization: Bearer $OPENAI_API_KEY" \+--data '{+ "model": "gpt-4o",+ "tools": [+ {+ "type": "mcp",+ "server_label": "litellm",+ "server_url": "<your-litellm-proxy-base-url>/github_mcp/mcp",+ "require_approval": "never",+ "headers": {+ "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY"+ }+ }+ ],+ "input": "Run available tools",+ "tool_choice": "required"+}'+```++This example uses URL namespacing to access only the "github" MCP server.++</TabItem>++<TabItem value="litellm" label="LiteLLM Proxy">++```bash title="cURL Example with URL Namespacing" showLineNumbers+curl --location '<your-litellm-proxy-base-url>/v1/responses' \+--header 'Content-Type: application/json' \+--header "Authorization: Bearer $LITELLM_API_KEY" \+--data '{+ "model": "gpt-4o",+ "tools": [+ {+ "type": "mcp",+ "server_label": "litellm",+ "server_url": "<your-litellm-proxy-base-url>/dev_group/mcp",+ "require_approval": "never",+ "headers": {+ "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY"+ }+ }+ ],+ "input": "Run available tools",+ "tool_choice": "required"+}'+```++This example uses URL namespacing to access all servers in the "dev_group" access group.++</TabItem>++<TabItem value="cursor" label="Cursor IDE">++```json title="Cursor MCP Configuration with URL Namespacing" showLineNumbers+{+ "mcpServers": {+ "LiteLLM": {+ "url": "<your-litellm-proxy-base-url>/github_mcp,zapier/mcp",+ "headers": {+ "x-litellm-api-key": "Bearer $LITELLM_API_KEY"+ }+ }+ }+}+```++This configuration uses URL namespacing to access tools from both "github" and "zapier" MCP servers.++</TabItem>+</Tabs>++#### Benefits of URL Namespacing++- **Direct Access**: No need for additional headers to specify servers+- **Clean URLs**: Self-documenting URLs that clearly indicate which servers are accessible+- **Access Group Support**: Use access group names for grouped server access+- **Multiple Servers**: Specify multiple servers in a single URL with comma separation+- **Simplified Configuration**: Easier setup for MCP clients that prefer URL-based configuration++---++### Method 2: Header-based Namespacing++You can choose to access specific MCP servers and only list their tools using the `x-mcp-servers` header. This header allows you to:+- Limit tool access to one or more specific MCP servers+- Control which tools are available in different environments or use cases++The header accepts a comma-separated list of server aliases: `"alias_1,Server2,Server3"`++**Notes:**+- If the header is not provided, tools from all available MCP servers will be accessible+- This method works with the standard LiteLLM MCP endpoint++<Tabs>+<TabItem value="openai" label="OpenAI API">++```bash title="cURL Example with Header Namespacing" showLineNumbers+curl --location 'https://api.openai.com/v1/responses' \+--header 'Content-Type: application/json' \+--header "Authorization: Bearer $OPENAI_API_KEY" \+--data '{+ "model": "gpt-4o",+ "tools": [+ {+ "type": "mcp",+ "server_label": "litellm",+ "server_url": "<your-litellm-proxy-base-url>/mcp/",+ "require_approval": "never",+ "headers": {+ "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",+ "x-mcp-servers": "alias_1"+ }+ }+ ],+ "input": "Run available tools",+ "tool_choice": "required"+}'+```++In this example, the request will only have access to tools from the "alias_1" MCP server.++</TabItem>++<TabItem value="litellm" label="LiteLLM Proxy">++```bash title="cURL Example with Header Namespacing" showLineNumbers+curl --location '<your-litellm-proxy-base-url>/v1/responses' \+--header 'Content-Type: application/json' \+--header "Authorization: Bearer $LITELLM_API_KEY" \+--data '{+ "model": "gpt-4o",+ "tools": [+ {+ "type": "mcp",+ "server_label": "litellm",+ "server_url": "<your-litellm-proxy-base-url>/mcp/",+ "require_approval": "never",+ "headers": {+ "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",+ "x-mcp-servers": "alias_1,Server2"+ }+ }+ ],+ "input": "Run available tools",+ "tool_choice": "required"+}'+```++This configuration restricts the request to only use tools from the specified MCP servers.++</TabItem>++<TabItem value="cursor" label="Cursor IDE">++```json title="Cursor MCP Configuration with Header Namespacing" showLineNumbers+{+ "mcpServers": {+ "LiteLLM": {+ "url": "<your-litellm-proxy-base-url>/mcp/",+ "headers": {+ "x-litellm-api-key": "Bearer $LITELLM_API_KEY",+ "x-mcp-servers": "alias_1,Server2"+ }+ }+ }+}+```++This configuration in Cursor IDE settings will limit tool access to only the specified MCP servers.++</TabItem>+</Tabs>++---++### Comparison: Header vs URL Namespacing++| Feature | Header Namespacing | URL Namespacing |+|---------|-------------------|-----------------|+| **Method** | Uses `x-mcp-servers` header | Uses URL path `/<servers>/mcp` |+| **Endpoint** | Standard `litellm_proxy` endpoint | Custom `/<servers>/mcp` endpoint |+| **Configuration** | Requires additional header | Self-contained in URL |+| **Multiple Servers** | Comma-separated in header | Comma-separated in URL path |+| **Access Groups** | Supported via header | Supported via URL path |+| **Client Support** | Works with all MCP clients | Works with URL-aware MCP clients |+| **Use Case** | Dynamic server selection | Fixed server configuration |++<Tabs>+<TabItem value="openai" label="OpenAI API">++```bash title="cURL Example with Server Segregation" showLineNumbers+curl --location 'https://api.openai.com/v1/responses' \+--header 'Content-Type: application/json' \+--header "Authorization: Bearer $OPENAI_API_KEY" \+--data '{+ "model": "gpt-4o",+ "tools": [+ {+ "type": "mcp",+ "server_label": "litellm",+ "server_url": "<your-litellm-proxy-base-url>/mcp/",+ "require_approval": "never",+ "headers": {+ "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",+ "x-mcp-servers": "alias_1"+ }+ }+ ],+ "input": "Run available tools",+ "tool_choice": "required"+}'+```++In this example, the request will only have access to tools from the "alias_1" MCP server.++</TabItem>++<TabItem value="litellm" label="LiteLLM Proxy">++```bash title="cURL Example with Server Segregation" showLineNumbers+curl --location '<your-litellm-proxy-base-url>/v1/responses' \+--header 'Content-Type: application/json' \+--header "Authorization: Bearer $LITELLM_API_KEY" \+--data '{+ "model": "gpt-4o",+ "tools": [+ {+ "type": "mcp",+ "server_label": "litellm",+ "server_url": "litellm_proxy",+ "require_approval": "never",+ "headers": {+ "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",+ "x-mcp-servers": "alias_1,Server2"+ }+ }+ ],+ "input": "Run available tools",+ "tool_choice": "required"+}'+```++This configuration restricts the request to only use tools from the specified MCP servers.++</TabItem>++<TabItem value="cursor" label="Cursor IDE">++```json title="Cursor MCP Configuration with Server Segregation" showLineNumbers+{+ "mcpServers": {+ "LiteLLM": {+ "url": "litellm_proxy",+ "headers": {+ "x-litellm-api-key": "Bearer $LITELLM_API_KEY",+ "x-mcp-servers": "alias_1,Server2"+ }+ }+ }+}+```++This configuration in Cursor IDE settings will limit tool access to only the specified MCP server.++</TabItem>+</Tabs>++### Grouping MCPs (Access Groups)++MCP Access Groups allow you to group multiple MCP servers together for easier management.++#### 1. Create an Access Group++##### A. Creating Access Groups using Config:++```yaml title="Creating access groups for MCP using the config" showLineNumbers+mcp_servers:+ "deepwiki_mcp":+ url: https://mcp.deepwiki.com/mcp+ transport: "http"+ auth_type: "none"+ access_groups: ["dev_group"]+```++While adding `mcp_servers` using the config:+- Pass in a list of strings inside `access_groups`+- These groups can then be used for segregating access using keys, teams and MCP clients using headers++##### B. Creating Access Groups using UI++To create an access group:+- Go to MCP Servers in the LiteLLM UI+- Click "Add a New MCP Server"+- Under "MCP Access Groups", create a new group (e.g., "dev_group") by typing it+- Add the same group name to other servers to group them together++<Image+ img={require('../img/mcp_create_access_group.png')}+ style={{width: '80%', display: 'block', margin: '0'}}+/>++#### 2. Use Access Group in Cursor++Include the access group name in the `x-mcp-servers` header:++```json title="Cursor Configuration with Access Groups" showLineNumbers+{+ "mcpServers": {+ "LiteLLM": {+ "url": "litellm_proxy",+ "headers": {+ "x-litellm-api-key": "Bearer $LITELLM_API_KEY",+ "x-mcp-servers": "dev_group"+ }+ }+ }+}+```++This gives you access to all servers in the "dev_group" access group.+- Which means that if deepwiki server (and any other servers) which have the access group `dev_group` assigned to them will be available for tool calling++#### Advanced: Connecting Access Groups to API Keys++When creating API keys, you can assign them to specific access groups for permission management:++- Go to "Keys" in the LiteLLM UI and click "Create Key"+- Select the desired MCP access groups from the dropdown+- The key will have access to all MCP servers in those groups+- This is reflected in the Test Key page++<Image+ img={require('../img/mcp_key_access_group.png')}+ style={{width: '80%', display: 'block', margin: '0'}}+/>+++## Set Allowed Tools for a Key, Team, or OrganizationControl which tools different teams can access from the same MCP server. For example, give your Engineering team access to `list_repositories`, `create_issue`, and `search_code`, while Sales only gets `search_code` and `close_issue`.diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.pyindex a8def13869f..077e99491c3 100644--- a/litellm/proxy/management_endpoints/key_management_endpoints.py+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py@@ -647,9 +647,9 @@ async def _common_key_generation_helper( # noqa: PLR0915request_type="key", **data_json, table_name="key")- response[- "soft_budget"- ] = data.soft_budget # include the user-input soft budget in the response+ response["soft_budget"] = (+ data.soft_budget+ ) # include the user-input soft budget in the responseresponse = GenerateKeyResponse(**response)@@ -1005,6 +1005,7 @@ async def generate_key_fn(- max_parallel_requests: Optional[int] - Rate limit a user based on the number of parallel requests. Raises 429 error, if user's parallel requests > x.- metadata: Optional[dict] - Metadata for key, store information for key. Example metadata = {"team": "core-infra", "app": "app2", "email": "[email protected]" }- guardrails: Optional[List[str]] - List of active guardrails for the key+ - disable_global_guardrails: Optional[bool] - Whether to disable global guardrails for the key.- permissions: Optional[dict] - key-specific permissions. Currently just used for turning off pii masking (if connected). Example - {"pii": false}- model_max_budget: Optional[Dict[str, BudgetConfig]] - Model-specific budgets {"gpt-4": {"budget_limit": 0.0005, "time_period": "30d"}}}. IF null or {} then no model specific budget.- model_rpm_limit: Optional[dict] - key-specific model rpm limit. Example - {"text-davinci-002": 1000, "gpt-3.5-turbo": 1000}. IF null or {} then no model specific rpm limit.@@ -1455,6 +1456,7 @@ async def update_key_fn(- permissions: Optional[dict] - Key-specific permissions- send_invite_email: Optional[bool] - Send invite email to user_id- guardrails: Optional[List[str]] - List of active guardrails for the key+ - disable_global_guardrails: Optional[bool] - Whether to disable global guardrails for the key.- prompts: Optional[List[str]] - List of prompts that the key is allowed to use.- blocked: Optional[bool] - Whether the key is blocked- aliases: Optional[dict] - Model aliases for the key - [Docs](https://litellm.vercel.app/docs/proxy/virtual_keys#model-aliases)@@ -2363,10 +2365,10 @@ async def delete_verification_tokens(try:if prisma_client:tokens = [_hash_token_if_needed(token=key) for key in tokens]- _keys_being_deleted: List[- LiteLLM_VerificationToken- ] = await prisma_client.db.litellm_verificationtoken.find_many(- where={"token": {"in": tokens}}+ _keys_being_deleted: List[LiteLLM_VerificationToken] = (+ await prisma_client.db.litellm_verificationtoken.find_many(+ where={"token": {"in": tokens}}+ ))if len(_keys_being_deleted) == 0:@@ -2474,9 +2476,9 @@ async def _rotate_master_key(from litellm.proxy.proxy_server import proxy_configtry:- models: Optional[- List- ] = await prisma_client.db.litellm_proxymodeltable.find_many()+ models: Optional[List] = (+ await prisma_client.db.litellm_proxymodeltable.find_many()+ )except Exception:models = None# 2. process model table@@ -2794,11 +2796,11 @@ async def validate_key_list_check(param="user_id",code=status.HTTP_403_FORBIDDEN,)- complete_user_info_db_obj: Optional[- BaseModel- ] = await prisma_client.db.litellm_usertable.find_unique(- where={"user_id": user_api_key_dict.user_id},- include={"organization_memberships": True},+ complete_user_info_db_obj: Optional[BaseModel] = (+ await prisma_client.db.litellm_usertable.find_unique(+ where={"user_id": user_api_key_dict.user_id},+ include={"organization_memberships": True},+ ))if complete_user_info_db_obj is None:@@ -2884,10 +2886,10 @@ async def get_admin_team_ids(if complete_user_info is None:return []# Get all teams that user is an admin of- teams: Optional[- List[BaseModel]- ] = await prisma_client.db.litellm_teamtable.find_many(- where={"team_id": {"in": complete_user_info.teams}}+ teams: Optional[List[BaseModel]] = (+ await prisma_client.db.litellm_teamtable.find_many(+ where={"team_id": {"in": complete_user_info.teams}}+ ))if teams is None:return []diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.pyindex fdbea56598c..3a66f95e812 100644--- a/litellm/proxy/management_endpoints/team_endpoints.py+++ b/litellm/proxy/management_endpoints/team_endpoints.py@@ -548,6 +548,7 @@ async def new_team( # noqa: PLR0915- organization_id: Optional[str] - The organization id of the team. Default is None. Create via `/organization/new`.- model_aliases: Optional[dict] - Model aliases for the team. [Docs](https://docs.litellm.ai/docs/proxy/team_based_routing#create-team-with-model-alias)- guardrails: Optional[List[str]] - Guardrails for the team. [Docs](https://docs.litellm.ai/docs/proxy/guardrails)+ - disable_global_guardrails: Optional[bool] - Whether to disable global guardrails for the key.- prompts: Optional[List[str]] - List of prompts that the team is allowed to use.- object_permission: Optional[LiteLLM_ObjectPermissionBase] - team-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "mcp_tool_permissions": {"server_id_1": ["tool1", "tool2"]}}. IF null or {} then no object permission.- team_member_budget: Optional[float] - The maximum budget allocated to an individual team member.@@ -1115,6 +1116,7 @@ async def update_team(- organization_id: Optional[str] - The organization id of the team. Default is None. Create via `/organization/new`.- model_aliases: Optional[dict] - Model aliases for the team. [Docs](https://docs.litellm.ai/docs/proxy/team_based_routing#create-team-with-model-alias)- guardrails: Optional[List[str]] - Guardrails for the team. [Docs](https://docs.litellm.ai/docs/proxy/guardrails)+ - disable_global_guardrails: Optional[bool] - Whether to disable global guardrails for the key.- prompts: Optional[List[str]] - List of prompts that the team is allowed to use.- object_permission: Optional[LiteLLM_ObjectPermissionBase] - team-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "mcp_tool_permissions": {"server_id_1": ["tool1", "tool2"]}}. IF null or {} then no object permission.- team_member_budget: Optional[float] - The maximum budget allocated to an individual team member.diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex dbd802a9f2f..c98330e4c66 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -42,6 +42,7 @@ from litellm.constants import ()from litellm.litellm_core_utils.safe_json_dumps import safe_dumpsfrom litellm.proxy.common_utils.callback_utils import normalize_callback_names+from litellm.proxy.common_utils.realtime_utils import _realtime_request_bodyfrom litellm.types.utils import (ModelResponse,ModelResponseStream,@@ -49,7 +50,6 @@ from litellm.types.utils import (TokenCountResponse,)from litellm.utils import load_credentials_from_list-from litellm.proxy.common_utils.realtime_utils import _realtime_request_bodyif TYPE_CHECKING:from aiohttp import ClientSession@@ -147,6 +147,7 @@ from litellm._logging import verbose_proxy_logger, verbose_router_loggerfrom litellm.caching.caching import DualCache, RedisCachefrom litellm.caching.redis_cluster_cache import RedisClusterCachefrom litellm.constants import (+ _REALTIME_BODY_CACHE_SIZE,APSCHEDULER_COALESCE,APSCHEDULER_MAX_INSTANCES,APSCHEDULER_MISFIRE_GRACE_TIME,@@ -160,7 +161,6 @@ from litellm.constants import (PROXY_BATCH_WRITE_AT,PROXY_BUDGET_RESCHEDULER_MAX_TIME,PROXY_BUDGET_RESCHEDULER_MIN_TIME,- _REALTIME_BODY_CACHE_SIZE,)from litellm.exceptions import RejectedRequestErrorfrom litellm.integrations.SlackAlerting.slack_alerting import SlackAlerting@@ -283,9 +283,7 @@ from litellm.proxy.management_endpoints.customer_endpoints import (from litellm.proxy.management_endpoints.internal_user_endpoints import (router as internal_user_router,)-from litellm.proxy.management_endpoints.internal_user_endpoints import (- user_update,-)+from litellm.proxy.management_endpoints.internal_user_endpoints import user_updatefrom litellm.proxy.management_endpoints.key_management_endpoints import (delete_verification_tokens,duration_in_seconds,@@ -339,9 +337,7 @@ from litellm.proxy.ocr_endpoints.endpoints import router as ocr_routerfrom litellm.proxy.openai_files_endpoints.files_endpoints import (router as openai_files_router,)-from litellm.proxy.openai_files_endpoints.files_endpoints import (- set_files_config,-)+from litellm.proxy.openai_files_endpoints.files_endpoints import set_files_configfrom litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints import (passthrough_endpoint_router,)@@ -390,6 +386,7 @@ from litellm.proxy.utils import (get_server_root_path,handle_exception_on_proxy,hash_token,+ model_dump_with_preserved_fields,update_spend,)from litellm.proxy.vector_store_endpoints.endpoints import router as vector_store_router@@ -431,9 +428,7 @@ from litellm.types.proxy.management_endpoints.ui_sso import (LiteLLM_UpperboundKeyGenerateParams,)from litellm.types.realtime import RealtimeQueryParams-from litellm.types.router import (- DeploymentTypedDict,-)+from litellm.types.router import DeploymentTypedDictfrom litellm.types.router import ModelInfo as RouterModelInfofrom litellm.types.router import (RouterGeneralSettings,@@ -3595,6 +3590,7 @@ class ProxyConfig:verbose_proxy_logger.exception(f"Error in _check_and_reload_model_cost_map: {str(e)}")+def _get_prompt_spec_for_db_prompt(self, db_prompt):"""Convert a DB prompt object to a PromptSpec object.@@ -3608,7 +3604,7 @@ class ProxyConfig:The PromptSpec object"""from litellm.proxy.prompts.prompt_endpoints import create_versioned_prompt_spec-+return create_versioned_prompt_spec(db_prompt=db_prompt)async def _init_prompts_in_db(self, prisma_client: PrismaClient):@@ -4856,7 +4852,7 @@ async def chat_completion( # noqa: PLR0915version=version,)if isinstance(result, BaseModel):- return result.model_dump(exclude_none=True, exclude_unset=True)+ return model_dump_with_preserved_fields(result, exclude_unset=True)else:return resultexcept RejectedRequestError as e:@@ -5585,6 +5581,7 @@ async def vertex_ai_live_passthrough_endpoint(######################################################################+@lru_cache(maxsize=_REALTIME_BODY_CACHE_SIZE)def _realtime_query_params_template(model: str, intent: Optional[str]@@ -5632,10 +5629,10 @@ async def realtime_websocket_endpoint(request = Request(scope=scope)request._url = websocket.url-+async def return_body():return _realtime_request_body(model)-+request.body = return_body # type: ignore### ROUTE THE REQUEST ###diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex c0cc374cbc6..9594a55962c 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -4027,3 +4027,178 @@ def validate_model_access(model_id),)+++def _path_matches_pattern(path: str, pattern: str) -> bool:+ """Check if a path matches a pattern (supporting * wildcard for list indices)."""+ path_parts = path.split(".")+ pattern_parts = pattern.split(".")++ if len(path_parts) != len(pattern_parts):+ return False++ for path_part, pattern_part in zip(path_parts, pattern_parts):+ if pattern_part == "*":+ # Wildcard matches any numeric index+ if not path_part.isdigit():+ return False+ elif path_part != pattern_part:+ return False++ return True+++def _build_preserved_paths(+ data: Any, current_path: str, preserve_fields: List[str], preserved_paths: set+) -> None:+ """Iteratively build set of paths that should be preserved."""+ # Use a stack to avoid recursion: (data, path)+ stack = [(data, current_path)]++ while stack:+ current_data, current_path_str = stack.pop()++ if isinstance(current_data, dict):+ for key, value in current_data.items():+ new_path = f"{current_path_str}.{key}" if current_path_str else key++ # Check if this path matches any preserve pattern+ for pattern in preserve_fields:+ if _path_matches_pattern(new_path, pattern):+ preserved_paths.add(new_path)++ if isinstance(value, (dict, list)):+ stack.append((value, new_path))++ elif isinstance(current_data, list):+ for idx, item in enumerate(current_data):+ new_path = f"{current_path_str}.{idx}" if current_path_str else str(idx)+ if isinstance(item, (dict, list)):+ stack.append((item, new_path))+++def _remove_none_except_preserved(+ data: Any, current_path: str, preserved_paths: set+) -> Any:+ """Iteratively remove None values except for preserved paths."""+ if not isinstance(data, (dict, list)):+ return data++ # Use a stack for iterative processing: (data, path, is_first_visit)+ # We'll process in a way that allows us to build the result bottom-up+ stack = [(data, current_path, True)] # (data, path, is_first_visit)+ results_map: dict[int, Any] = {} # Maps id(data) -> processed result++ while stack:+ current_data, current_path_str, is_first_visit = stack.pop()++ if is_first_visit:+ # First visit - mark for revisit and add children to stack+ stack.append((current_data, current_path_str, False))++ if isinstance(current_data, dict):+ # Add children in reverse order so they're processed in correct order+ for key in reversed(list(current_data.keys())):+ value = current_data[key]+ new_path = f"{current_path_str}.{key}" if current_path_str else key++ if isinstance(value, (dict, list)):+ stack.append((value, new_path, True))++ elif isinstance(current_data, list):+ # Add children in reverse order+ for idx in reversed(range(len(current_data))):+ item = current_data[idx]+ new_path = (+ f"{current_path_str}.{idx}" if current_path_str else str(idx)+ )++ if isinstance(item, (dict, list)):+ stack.append((item, new_path, True))+ else:+ # Second visit - children are processed, build result+ result: Union[dict[str, Any], list[Any]]+ if isinstance(current_data, dict):+ result = {}+ for key, value in current_data.items():+ new_path = f"{current_path_str}.{key}" if current_path_str else key++ if value is None:+ if new_path in preserved_paths:+ result[key] = None+ elif isinstance(value, (dict, list)):+ processed = results_map.get(id(value))+ if (+ processed is not None+ and processed != {}+ and processed != []+ ):+ result[key] = processed+ else:+ result[key] = value++ results_map[id(current_data)] = result++ elif isinstance(current_data, list):+ result = []+ for idx, item in enumerate(current_data):+ new_path = (+ f"{current_path_str}.{idx}" if current_path_str else str(idx)+ )++ if item is None:+ if new_path in preserved_paths:+ result.append(None)+ elif isinstance(item, (dict, list)):+ processed = results_map.get(id(item))+ if processed is not None:+ result.append(processed)+ else:+ result.append(item)++ results_map[id(current_data)] = result++ return results_map.get(id(data), data)+++def model_dump_with_preserved_fields(+ obj: Any,+ preserve_fields: Optional[List[str]] = None,+ exclude_unset: bool = True,+) -> Dict[str, Any]:+ """+ Serialize a Pydantic model to a dictionary while preserving specific fields even if they are None.++ This function is useful when you need to maintain API compatibility where certain fields+ must always be present in the response (e.g., message.content in OpenAI API responses).++ Args:+ obj: The Pydantic BaseModel instance to serialize+ preserve_fields: List of field paths to preserve even if None (e.g., ["choices.*.message.content"])+ exclude_unset: Whether to exclude fields that were not explicitly set++ Returns:+ Dictionary representation with None values excluded except for preserved fields++ Example:+ >>> result = model_dump_with_preserved_fields(+ ... response,+ ... preserve_fields=["choices.*.message.content", "choices.*.message.role"]+ ... )+ """+ if preserve_fields is None:+ preserve_fields = [+ "choices.*.message.content",+ "choices.*.message.role",+ "choices.*.delta.content",+ ]++ # First, get the full dump without excluding None values+ full_dump = obj.model_dump(exclude_none=False, exclude_unset=exclude_unset)++ # Build the set of preserved paths+ preserved_paths: set = set()+ _build_preserved_paths(full_dump, "", preserve_fields, preserved_paths)++ # Remove None values except for preserved paths+ return _remove_none_except_preserved(full_dump, "", preserved_paths)