Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

[MCP Gateway] QA/Fixes - Ensure Team/Key level enforcement works for MCPs (#15305)

Ishaan Jaff36c971a6fd4a
diff --git a/docs/my-website/docs/mcp.md b/docs/my-website/docs/mcp.md
index 33e9ebad153..9365b0a5542 100644
--- a/docs/my-website/docs/mcp.md
+++ b/docs/my-website/docs/mcp.md
@@ -2,7 +2,7 @@ import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import Image from '@theme/IdealImage';
-# /mcp - Model Context Protocol
+# MCP Overview
LiteLLM Proxy provides an MCP Gateway that allows you to use a fixed endpoint for all MCP tools and control MCP access by Key, Team.
@@ -306,211 +306,6 @@ mcp_servers:
- If you specify both `allowed_tools` and `disallowed_tools`, the allowed list takes priority
- Tool names are case-sensitive
-## Using your MCP
-
-### Use on LiteLLM UI
-
-Follow this walkthrough to use your MCP on LiteLLM UI
-
-<iframe width="840" height="500" src="https://www.loom.com/embed/57e0763267254bc79dbe6658d0b8758c" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
-
-### Use with Responses API
-
-Replace `http://localhost:4000` with your LiteLLM Proxy base URL.
-
-Demo Video Using Responses API with LiteLLM Proxy: [Demo video here](https://www.loom.com/share/34587e618c5c47c0b0d67b4e4d02718f?sid=2caf3d45-ead4-4490-bcc1-8d6dd6041c02)
-
-
-<Tabs>
-<TabItem value="curl" label="cURL">
-
-```bash title="cURL Example" showLineNumbers
-curl --location 'http://localhost:4000/v1/responses' \
---header 'Content-Type: application/json' \
---header "Authorization: Bearer sk-1234" \
---data '{
- "model": "gpt-5",
- "input": [
- {
- "role": "user",
- "content": "give me TLDR of what BerriAI/litellm repo is about",
- "type": "message"
- }
- ],
- "tools": [
- {
- "type": "mcp",
- "server_label": "litellm",
- "server_url": "litellm_proxy",
- "require_approval": "never"
- }
- ],
- "stream": true,
- "tool_choice": "required"
-}'
-```
-
-</TabItem>
-<TabItem value="python" label="Python SDK">
-
-```python title="Python SDK Example" showLineNumbers
-"""
-Use LiteLLM Proxy MCP Gateway to call MCP tools.
-
-When using LiteLLM Proxy, you can use the same MCP tools across all your LLM providers.
-"""
-import openai
-
-client = openai.OpenAI(
- api_key="sk-1234", # paste your litellm proxy api key here
- base_url="http://localhost:4000" # paste your litellm proxy base url here
-)
-print("Making API request to Responses API with MCP tools")
-
-response = client.responses.create(
- model="gpt-5",
- input=[
- {
- "role": "user",
- "content": "give me TLDR of what BerriAI/litellm repo is about",
- "type": "message"
- }
- ],
- tools=[
- {
- "type": "mcp",
- "server_label": "litellm",
- "server_url": "litellm_proxy",
- "require_approval": "never"
- }
- ],
- stream=True,
- tool_choice="required"
-)
-
-for chunk in response:
- print("response chunk: ", chunk)
-```
-
-</TabItem>
-</Tabs>
-
-#### Specifying MCP Tools
-
-You can specify which MCP tools are available by using the `allowed_tools` parameter. This allows you to restrict access to specific tools within an MCP server.
-
-To get the list of allowed tools when using LiteLLM MCP Gateway, you can naigate to the LiteLLM UI on MCP Servers > MCP Tools > Click the Tool > Copy Tool Name.
-
-<Tabs>
-<TabItem value="curl" label="cURL">
-
-```bash title="cURL Example with allowed_tools" showLineNumbers
-curl --location 'http://localhost:4000/v1/responses' \
---header 'Content-Type: application/json' \
---header "Authorization: Bearer sk-1234" \
---data '{
- "model": "gpt-5",
- "input": [
- {
- "role": "user",
- "content": "give me TLDR of what BerriAI/litellm repo is about",
- "type": "message"
- }
- ],
- "tools": [
- {
- "type": "mcp",
- "server_label": "litellm",
- "server_url": "litellm_proxy/mcp",
- "require_approval": "never",
- "allowed_tools": ["GitMCP-fetch_litellm_documentation"]
- }
- ],
- "stream": true,
- "tool_choice": "required"
-}'
-```
-
-</TabItem>
-<TabItem value="python" label="Python SDK">
-
-```python title="Python SDK Example with allowed_tools" showLineNumbers
-import openai
-
-client = openai.OpenAI(
- api_key="sk-1234",
- base_url="http://localhost:4000"
-)
-
-response = client.responses.create(
- model="gpt-5",
- input=[
- {
- "role": "user",
- "content": "give me TLDR of what BerriAI/litellm repo is about",
- "type": "message"
- }
- ],
- tools=[
- {
- "type": "mcp",
- "server_label": "litellm",
- "server_url": "litellm_proxy/mcp",
- "require_approval": "never",
- "allowed_tools": ["GitMCP-fetch_litellm_documentation"]
- }
- ],
- stream=True,
- tool_choice="required"
-)
-
-print(response)
-```
-
-</TabItem>
-</Tabs>
-
-### Use with Cursor IDE
-
-Use tools directly from Cursor IDE with LiteLLM MCP:
-
-**Setup Instructions:**
-
-1. **Open Cursor Settings**: Use `⇧+⌘+J` (Mac) or `Ctrl+Shift+J` (Windows/Linux)
-2. **Navigate to MCP Tools**: Go to the "MCP Tools" tab and click "New MCP Server"
-3. **Add Configuration**: Copy and paste the JSON configuration below, then save with `Cmd+S` or `Ctrl+S`
-
-```json title="Basic Cursor MCP Configuration" showLineNumbers
-{
- "mcpServers": {
- "LiteLLM": {
- "url": "litellm_proxy",
- "headers": {
- "x-litellm-api-key": "Bearer $LITELLM_API_KEY"
- }
- }
- }
-}
-```
-
-#### How it works when server_url="litellm_proxy"
-
-When server_url="litellm_proxy", LiteLLM bridges non-MCP providers to your MCP tools.
-
-- Tool Discovery: LiteLLM fetches MCP tools and converts them to OpenAI-compatible definitions
-- LLM Call: Tools are sent to the LLM with your input; LLM selects which tools to call
-- Tool Execution: LiteLLM automatically parses arguments, routes calls to MCP servers, executes tools, and retrieves results
-- Response Integration: Tool results are sent back to LLM for final response generation
-- Output: Complete response combining LLM reasoning with tool execution results
-
-This enables MCP tool usage with any LiteLLM-supported provider, regardless of native MCP support.
-
-#### Auto-execution for require_approval: "never"
-
-Setting require_approval: "never" triggers automatic tool execution, returning the final response in a single API call without additional user interaction.
-
-
-
## MCP Server Access Control
LiteLLM Proxy provides two methods for controlling access to specific MCP servers:
@@ -1489,221 +1284,6 @@ curl --location '<your-litellm-proxy-base-url>/v1/responses' \
}'
```
-
-
-## MCP Cost Tracking
-
-LiteLLM provides two ways to track costs for MCP tool calls:
-
-| Method | When to Use | What It Does |
-|--------|-------------|--------------|
-| **Config-based Cost Tracking** | Simple cost tracking with fixed costs per tool/server | Automatically tracks costs based on configuration |
-| **Custom Post-MCP Hook** | Dynamic cost tracking with custom logic | Allows custom cost calculations and response modifications |
-
-### Config-based Cost Tracking
-
-Configure fixed costs for MCP servers directly in your config.yaml:
-
-```yaml title="config.yaml" showLineNumbers
-model_list:
- - model_name: gpt-4o
- litellm_params:
- model: openai/gpt-4o
- api_key: sk-xxxxxxx
-
-mcp_servers:
- zapier_server:
- url: "https://actions.zapier.com/mcp/sk-xxxxx/sse"
- mcp_info:
- mcp_server_cost_info:
- # Default cost for all tools in this server
- default_cost_per_query: 0.01
- # Custom cost for specific tools
- tool_name_to_cost_per_query:
- send_email: 0.05
- create_document: 0.03
-
- expensive_api_server:
- url: "https://api.expensive-service.com/mcp"
- mcp_info:
- mcp_server_cost_info:
- default_cost_per_query: 1.50
-```
-
-### Custom Post-MCP Hook
-
-Use this when you need dynamic cost calculation or want to modify the MCP response before it's returned to the user.
-
-#### 1. Create a custom MCP hook file
-
-```python title="custom_mcp_hook.py" showLineNumbers
-from typing import Optional
-from litellm.integrations.custom_logger import CustomLogger
-from litellm.types.mcp import MCPPostCallResponseObject
-
-
-class CustomMCPCostTracker(CustomLogger):
- """
- Custom handler for MCP cost tracking and response modification
- """
-
- async def async_post_mcp_tool_call_hook(
- self,
- kwargs,
- response_obj: MCPPostCallResponseObject,
- start_time,
- end_time
- ) -> Optional[MCPPostCallResponseObject]:
- """
- Called after each MCP tool call.
- Modify costs and response before returning to user.
- """
-
- # Extract tool information from kwargs
- tool_name = kwargs.get("name", "")
- server_name = kwargs.get("server_name", "")
-
- # Calculate custom cost based on your logic
- custom_cost = 42.00
-
- # Set the response cost
- response_obj.hidden_params.response_cost = custom_cost
-
-
-
- return response_obj
-
-
-# Create instance for LiteLLM to use
-custom_mcp_cost_tracker = CustomMCPCostTracker()
-```
-
-#### 2. Configure in config.yaml
-
-```yaml title="config.yaml" showLineNumbers
-model_list:
- - model_name: gpt-4o
- litellm_params:
- model: openai/gpt-4o
- api_key: sk-xxxxxxx
-
-# Add your custom MCP hook
-callbacks:
- - custom_mcp_hook.custom_mcp_cost_tracker
-
-mcp_servers:
- zapier_server:
- url: "https://actions.zapier.com/mcp/sk-xxxxx/sse"
-```
-
-#### 3. Start the proxy
-
-```shell
-$ litellm --config /path/to/config.yaml
-```
-
-When MCP tools are called, your custom hook will:
-1. Calculate costs based on your custom logic
-2. Modify the response if needed
-3. Track costs in LiteLLM's logging system
-
-## MCP Guardrails
-
-LiteLLM supports applying guardrails to MCP tool calls to ensure security and compliance. You can configure guardrails to run before or during MCP calls to validate inputs and block or mask sensitive information.
-
-### Supported MCP Guardrail Modes
-
-MCP guardrails support the following modes:
-
-- `pre_mcp_call`: Run **before** MCP call, on **input**. Use this mode when you want to apply validation/masking/blocking for MCP requests
-- `during_mcp_call`: Run **during** MCP call execution. Use this mode for real-time monitoring and intervention
-
-### Configuration Examples
-
-Configure guardrails to run before MCP tool calls to validate and sanitize inputs:
-
-```yaml title="config.yaml" showLineNumbers
-guardrails:
- - guardrail_name: "mcp-input-validation"
- litellm_params:
- guardrail: presidio # or other supported guardrails
- mode: "pre_mcp_call" # or during_mcp_call
- pii_entities_config:
- CREDIT_CARD: "BLOCK" # Will block requests containing credit card numbers
- EMAIL_ADDRESS: "MASK" # Will mask email addresses
- PHONE_NUMBER: "MASK" # Will mask phone numbers
- default_on: true
-```
-
-
-### Usage Examples
-
-#### Testing Pre-MCP Call Guardrails
-
-Test your MCP guardrails with a request that includes sensitive information:
-
-```bash title="Test MCP Guardrail" showLineNumbers
-curl http://localhost:4000/chat/completions \
- -H "Content-Type: application/json" \
- -H "Authorization: Bearer sk-1234" \
- -d '{
- "model": "gpt-3.5-turbo",
- "messages": [
- {"role": "user", "content": "My credit card is 4111-1111-1111-1111 and my email is [email protected]"}
- ],
- "guardrails": ["mcp-input-validation"]
- }'
-```
-
-The request will be processed as follows:
-1. Credit card number will be blocked (request rejected)
-2. Email address will be masked (e.g., replaced with `<EMAIL_ADDRESS>`)
-
-#### Using with MCP Tools
-
-When using MCP tools, guardrails will be applied to the tool inputs:
-
-```python title="Python Example with MCP Guardrails" showLineNumbers
-import openai
-
-client = openai.OpenAI(
- api_key="your-api-key",
- base_url="http://localhost:4000"
-)
-
-# This request will trigger MCP guardrails
-response = client.chat.completions.create(
- model="gpt-3.5-turbo",
- messages=[
- {"role": "user", "content": "Send an email to 555-123-4567 with my SSN 123-45-6789"}
- ],
- tools=[{"type": "mcp", "server_label": "litellm", "server_url": "litellm_proxy"}],
- guardrails=["mcp-input-validation"]
-)
-```
-
-### Supported Guardrail Providers
-
-MCP guardrails work with all LiteLLM-supported guardrail providers:
-
-- **Presidio**: PII detection and masking
-- **Bedrock**: AWS Bedrock guardrails
-- **Lakera**: Content moderation
-- **Aporia**: Custom guardrails
-- **Custom**: Your own guardrail implementations
-
-## MCP Permission Management
-
-LiteLLM supports managing permissions for MCP Servers by Keys, Teams, Organizations (entities) on LiteLLM. When a MCP client attempts to list tools, LiteLLM will only return the tools the entity has permissions to access.
-
-When Creating a Key, Team, or Organization, you can select the allowed MCP Servers that the entity has access to.
-
-<Image
- img={require('../img/mcp_key.png')}
- style={{width: '80%', display: 'block', margin: '0'}}
-/>
-
-
## LiteLLM Proxy - Walk through MCP Gateway
LiteLLM exposes an MCP Gateway for admins to add all their MCP servers to LiteLLM. The key benefits of using LiteLLM Proxy with MCP are:
diff --git a/docs/my-website/docs/mcp_control.md b/docs/my-website/docs/mcp_control.md
new file mode 100644
index 00000000000..484cb13708c
--- /dev/null
+++ b/docs/my-website/docs/mcp_control.md
@@ -0,0 +1,45 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+import Image from '@theme/IdealImage';
+
+# MCP Permission Management
+
+Control which MCP servers and tools can be accessed by specific keys, teams, or organizations in LiteLLM. When a client attempts to list or call tools, LiteLLM enforces access controls based on configured permissions.
+
+## Overview
+
+LiteLLM provides fine-grained permission management for MCP servers, allowing you to:
+
+- **Restrict MCP access by entity**: Control which keys, teams, or organizations can access specific MCP servers
+- **Tool-level filtering**: Automatically filter available tools based on entity permissions
+- **Centralized control**: Manage all MCP permissions from the LiteLLM Admin UI or API
+
+This ensures that only authorized entities can discover and use MCP tools, providing an additional security layer for your MCP infrastructure.
+
+:::info Related Documentation
+- [MCP Overview](./mcp.md) - Learn about MCP in LiteLLM
+- [MCP Cost Tracking](./mcp_cost.md) - Track costs for MCP tool calls
+- [MCP Guardrails](./mcp_guardrail.md) - Apply security guardrails to MCP calls
+- [Using MCP](./mcp_usage.md) - How to use MCP with LiteLLM
+:::
+
+## How It Works
+
+LiteLLM supports managing permissions for MCP Servers by Keys, Teams, Organizations (entities) on LiteLLM. When a MCP client attempts to list tools, LiteLLM will only return the tools the entity has permissions to access.
+
+When Creating a Key, Team, or Organization, you can select the allowed MCP Servers that the entity has access to.
+
+<Image
+ img={require('../img/mcp_key.png')}
+ style={{width: '80%', display: 'block', margin: '0'}}
+/>
+
+
+## Set Allowed Tools for a Key, Team, or Organization
+
+Control 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`.
+
+
+This video shows how to set allowed tools for a Key, Team, or Organization.
+
+<iframe width="840" height="500" src="https://www.loom.com/embed/7464d444c3324078892367272fe50745" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
diff --git a/docs/my-website/docs/mcp_cost.md b/docs/my-website/docs/mcp_cost.md
new file mode 100644
index 00000000000..4f5d65fe019
--- /dev/null
+++ b/docs/my-website/docs/mcp_cost.md
@@ -0,0 +1,121 @@
+
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+import Image from '@theme/IdealImage';
+
+# MCP Cost Tracking
+
+LiteLLM provides two ways to track costs for MCP tool calls:
+
+| Method | When to Use | What It Does |
+|--------|-------------|--------------|
+| **Config-based Cost Tracking** | Simple cost tracking with fixed costs per tool/server | Automatically tracks costs based on configuration |
+| **Custom Post-MCP Hook** | Dynamic cost tracking with custom logic | Allows custom cost calculations and response modifications |
+
+### Config-based Cost Tracking
+
+Configure fixed costs for MCP servers directly in your config.yaml:
+
+```yaml title="config.yaml" showLineNumbers
+model_list:
+ - model_name: gpt-4o
+ litellm_params:
+ model: openai/gpt-4o
+ api_key: sk-xxxxxxx
+
+mcp_servers:
+ zapier_server:
+ url: "https://actions.zapier.com/mcp/sk-xxxxx/sse"
+ mcp_info:
+ mcp_server_cost_info:
+ # Default cost for all tools in this server
+ default_cost_per_query: 0.01
+ # Custom cost for specific tools
+ tool_name_to_cost_per_query:
+ send_email: 0.05
+ create_document: 0.03
+
+ expensive_api_server:
+ url: "https://api.expensive-service.com/mcp"
+ mcp_info:
+ mcp_server_cost_info:
+ default_cost_per_query: 1.50
+```
+
+### Custom Post-MCP Hook
+
+Use this when you need dynamic cost calculation or want to modify the MCP response before it's returned to the user.
+
+#### 1. Create a custom MCP hook file
+
+```python title="custom_mcp_hook.py" showLineNumbers
+from typing import Optional
+from litellm.integrations.custom_logger import CustomLogger
+from litellm.types.mcp import MCPPostCallResponseObject
+
+
+class CustomMCPCostTracker(CustomLogger):
+ """
+ Custom handler for MCP cost tracking and response modification
+ """
+
+ async def async_post_mcp_tool_call_hook(
+ self,
+ kwargs,
+ response_obj: MCPPostCallResponseObject,
+ start_time,
+ end_time
+ ) -> Optional[MCPPostCallResponseObject]:
+ """
+ Called after each MCP tool call.
+ Modify costs and response before returning to user.
+ """
+
+ # Extract tool information from kwargs
+ tool_name = kwargs.get("name", "")
+ server_name = kwargs.get("server_name", "")
+
+ # Calculate custom cost based on your logic
+ custom_cost = 42.00
+
+ # Set the response cost
+ response_obj.hidden_params.response_cost = custom_cost
+
+
+
+ return response_obj
+
+
+# Create instance for LiteLLM to use
+custom_mcp_cost_tracker = CustomMCPCostTracker()
+```
+
+#### 2. Configure in config.yaml
+
+```yaml title="config.yaml" showLineNumbers
+model_list:
+ - model_name: gpt-4o
+ litellm_params:
+ model: openai/gpt-4o
+ api_key: sk-xxxxxxx
+
+# Add your custom MCP hook
+callbacks:
+ - custom_mcp_hook.custom_mcp_cost_tracker
+
+mcp_servers:
+ zapier_server:
+ url: "https://actions.zapier.com/mcp/sk-xxxxx/sse"
+```
+
+#### 3. Start the proxy
+
+```shell
+$ litellm --config /path/to/config.yaml
+```
+
+When MCP tools are called, your custom hook will:
+1. Calculate costs based on your custom logic
+2. Modify the response if needed
+3. Track costs in LiteLLM's logging system
+
diff --git a/docs/my-website/docs/mcp_guardrail.md b/docs/my-website/docs/mcp_guardrail.md
new file mode 100644
index 00000000000..f71ea2fe5ef
--- /dev/null
+++ b/docs/my-website/docs/mcp_guardrail.md
@@ -0,0 +1,88 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+import Image from '@theme/IdealImage';
+
+# MCP Guardrails
+
+LiteLLM supports applying guardrails to MCP tool calls to ensure security and compliance. You can configure guardrails to run before or during MCP calls to validate inputs and block or mask sensitive information.
+
+### Supported MCP Guardrail Modes
+
+MCP guardrails support the following modes:
+
+- `pre_mcp_call`: Run **before** MCP call, on **input**. Use this mode when you want to apply validation/masking/blocking for MCP requests
+- `during_mcp_call`: Run **during** MCP call execution. Use this mode for real-time monitoring and intervention
+
+### Configuration Examples
+
+Configure guardrails to run before MCP tool calls to validate and sanitize inputs:
+
+```yaml title="config.yaml" showLineNumbers
+guardrails:
+ - guardrail_name: "mcp-input-validation"
+ litellm_params:
+ guardrail: presidio # or other supported guardrails
+ mode: "pre_mcp_call" # or during_mcp_call
+ pii_entities_config:
+ CREDIT_CARD: "BLOCK" # Will block requests containing credit card numbers
+ EMAIL_ADDRESS: "MASK" # Will mask email addresses
+ PHONE_NUMBER: "MASK" # Will mask phone numbers
+ default_on: true
+```
+
+
+### Usage Examples
+
+#### Testing Pre-MCP Call Guardrails
+
+Test your MCP guardrails with a request that includes sensitive information:
+
+```bash title="Test MCP Guardrail" showLineNumbers
+curl http://localhost:4000/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer sk-1234" \
+ -d '{
+ "model": "gpt-3.5-turbo",
+ "messages": [
+ {"role": "user", "content": "My credit card is 4111-1111-1111-1111 and my email is [email protected]"}
+ ],
+ "guardrails": ["mcp-input-validation"]
+ }'
+```
+
+The request will be processed as follows:
+1. Credit card number will be blocked (request rejected)
+2. Email address will be masked (e.g., replaced with `<EMAIL_ADDRESS>`)
+
+#### Using with MCP Tools
+
+When using MCP tools, guardrails will be applied to the tool inputs:
+
+```python title="Python Example with MCP Guardrails" showLineNumbers
+import openai
+
+client = openai.OpenAI(
+ api_key="your-api-key",
+ base_url="http://localhost:4000"
+)
+
+# This request will trigger MCP guardrails
+response = client.chat.completions.create(
+ model="gpt-3.5-turbo",
+ messages=[
+ {"role": "user", "content": "Send an email to 555-123-4567 with my SSN 123-45-6789"}
+ ],
+ tools=[{"type": "mcp", "server_label": "litellm", "server_url": "litellm_proxy"}],
+ guardrails=["mcp-input-validation"]
+)
+```
+
+### Supported Guardrail Providers
+
+MCP guardrails work with all LiteLLM-supported guardrail providers:
+
+- **Presidio**: PII detection and masking
+- **Bedrock**: AWS Bedrock guardrails
+- **Lakera**: Content moderation
+- **Aporia**: Custom guardrails
+- **Custom**: Your own guardrail implementations
\ No newline at end of file
diff --git a/docs/my-website/docs/mcp_usage.md b/docs/my-website/docs/mcp_usage.md
new file mode 100644
index 00000000000..ef9d8a5ed1b
--- /dev/null
+++ b/docs/my-website/docs/mcp_usage.md
@@ -0,0 +1,209 @@
+
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+import Image from '@theme/IdealImage';
+
+# Using your MCP
+
+This document covers how to use LiteLLM as an MCP Gateway. You can see how to use it with Responses API, Cursor IDE, and OpenAI SDK.
+
+### Use on LiteLLM UI
+
+Follow this walkthrough to use your MCP on LiteLLM UI
+
+<iframe width="840" height="500" src="https://www.loom.com/embed/57e0763267254bc79dbe6658d0b8758c" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
+
+### Use with Responses API
+
+Replace `http://localhost:4000` with your LiteLLM Proxy base URL.
+
+Demo Video Using Responses API with LiteLLM Proxy: [Demo video here](https://www.loom.com/share/34587e618c5c47c0b0d67b4e4d02718f?sid=2caf3d45-ead4-4490-bcc1-8d6dd6041c02)
+
+
+<Tabs>
+<TabItem value="curl" label="cURL">
+
+```bash title="cURL Example" showLineNumbers
+curl --location 'http://localhost:4000/v1/responses' \
+--header 'Content-Type: application/json' \
+--header "Authorization: Bearer sk-1234" \
+--data '{
+ "model": "gpt-5",
+ "input": [
+ {
+ "role": "user",
+ "content": "give me TLDR of what BerriAI/litellm repo is about",
+ "type": "message"
+ }
+ ],
+ "tools": [
+ {
+ "type": "mcp",
+ "server_label": "litellm",
+ "server_url": "litellm_proxy",
+ "require_approval": "never"
+ }
+ ],
+ "stream": true,
+ "tool_choice": "required"
+}'
+```
+
+</TabItem>
+<TabItem value="python" label="Python SDK">
+
+```python title="Python SDK Example" showLineNumbers
+"""
+Use LiteLLM Proxy MCP Gateway to call MCP tools.
+
+When using LiteLLM Proxy, you can use the same MCP tools across all your LLM providers.
+"""
+import openai
+
+client = openai.OpenAI(
+ api_key="sk-1234", # paste your litellm proxy api key here
+ base_url="http://localhost:4000" # paste your litellm proxy base url here
+)
+print("Making API request to Responses API with MCP tools")
+
+response = client.responses.create(
+ model="gpt-5",
+ input=[
+ {
+ "role": "user",
+ "content": "give me TLDR of what BerriAI/litellm repo is about",
+ "type": "message"
+ }
+ ],
+ tools=[
+ {
+ "type": "mcp",
+ "server_label": "litellm",
+ "server_url": "litellm_proxy",
+ "require_approval": "never"
+ }
+ ],
+ stream=True,
+ tool_choice="required"
+)
+
+for chunk in response:
+ print("response chunk: ", chunk)
+```
+
+</TabItem>
+</Tabs>
+
+#### Specifying MCP Tools
+
+You can specify which MCP tools are available by using the `allowed_tools` parameter. This allows you to restrict access to specific tools within an MCP server.
+
+To get the list of allowed tools when using LiteLLM MCP Gateway, you can naigate to the LiteLLM UI on MCP Servers > MCP Tools > Click the Tool > Copy Tool Name.
+
+<Tabs>
+<TabItem value="curl" label="cURL">
+
+```bash title="cURL Example with allowed_tools" showLineNumbers
+curl --location 'http://localhost:4000/v1/responses' \
+--header 'Content-Type: application/json' \
+--header "Authorization: Bearer sk-1234" \
+--data '{
+ "model": "gpt-5",
+ "input": [
+ {
+ "role": "user",
+ "content": "give me TLDR of what BerriAI/litellm repo is about",
+ "type": "message"
+ }
+ ],
+ "tools": [
+ {
+ "type": "mcp",
+ "server_label": "litellm",
+ "server_url": "litellm_proxy/mcp",
+ "require_approval": "never",
+ "allowed_tools": ["GitMCP-fetch_litellm_documentation"]
+ }
+ ],
+ "stream": true,
+ "tool_choice": "required"
+}'
+```
+
+</TabItem>
+<TabItem value="python" label="Python SDK">
+
+```python title="Python SDK Example with allowed_tools" showLineNumbers
+import openai
+
+client = openai.OpenAI(
+ api_key="sk-1234",
+ base_url="http://localhost:4000"
+)
+
+response = client.responses.create(
+ model="gpt-5",
+ input=[
+ {
+ "role": "user",
+ "content": "give me TLDR of what BerriAI/litellm repo is about",
+ "type": "message"
+ }
+ ],
+ tools=[
+ {
+ "type": "mcp",
+ "server_label": "litellm",
+ "server_url": "litellm_proxy/mcp",
+ "require_approval": "never",
+ "allowed_tools": ["GitMCP-fetch_litellm_documentation"]
+ }
+ ],
+ stream=True,
+ tool_choice="required"
+)
+
+print(response)
+```
+
+</TabItem>
+</Tabs>
+
+### Use with Cursor IDE
+
+Use tools directly from Cursor IDE with LiteLLM MCP:
+
+**Setup Instructions:**
+
+1. **Open Cursor Settings**: Use `⇧+⌘+J` (Mac) or `Ctrl+Shift+J` (Windows/Linux)
+2. **Navigate to MCP Tools**: Go to the "MCP Tools" tab and click "New MCP Server"
+3. **Add Configuration**: Copy and paste the JSON configuration below, then save with `Cmd+S` or `Ctrl+S`
+
+```json title="Basic Cursor MCP Configuration" showLineNumbers
+{
+ "mcpServers": {
+ "LiteLLM": {
+ "url": "litellm_proxy",
+ "headers": {
+ "x-litellm-api-key": "Bearer $LITELLM_API_KEY"
+ }
+ }
+ }
+}
+```
+
+#### How it works when server_url="litellm_proxy"
+
+When server_url="litellm_proxy", LiteLLM bridges non-MCP providers to your MCP tools.
+
+- Tool Discovery: LiteLLM fetches MCP tools and converts them to OpenAI-compatible definitions
+- LLM Call: Tools are sent to the LLM with your input; LLM selects which tools to call
+- Tool Execution: LiteLLM automatically parses arguments, routes calls to MCP servers, executes tools, and retrieves results
+- Response Integration: Tool results are sent back to LLM for final response generation
+- Output: Complete response combining LLM reasoning with tool execution results
+
+This enables MCP tool usage with any LiteLLM-supported provider, regardless of native MCP support.
+
+#### Auto-execution for require_approval: "never"
+
+Setting require_approval: "never" triggers automatic tool execution, returning the final response in a single API call without additional user interaction.
diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.js
index 12fb2a681f3..74dcc90ad37 100644
--- a/docs/my-website/sidebars.js
+++ b/docs/my-website/sidebars.js
@@ -333,7 +333,17 @@ const sidebars = {
"image_variations",
]
},
- "mcp",
+ {
+ type: "category",
+ label: "/mcp - Model Context Protocol",
+ items: [
+ "mcp",
+ "mcp_usage",
+ "mcp_control",
+ "mcp_cost",
+ "mcp_guardrail",
+ ]
+ },
"moderation",
{
type: "category",
diff --git a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py
index cc890abb95b..0c15138b05b 100644
--- a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py
+++ b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py
@@ -369,7 +369,7 @@ class MCPRequestHandler:
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
):
"""Helper to get team object_permission from cache or DB."""
- from litellm.proxy.auth.auth_checks import get_team_object
+ from litellm.proxy.auth.auth_checks import get_object_permission, get_team_object
from litellm.proxy.proxy_server import (
prisma_client,
proxy_logging_obj,
@@ -379,6 +379,7 @@ class MCPRequestHandler:
if not user_api_key_auth or not user_api_key_auth.team_id or not prisma_client:
return None
+ # First get the team object (which may have object_permission already loaded)
team_obj: Optional[LiteLLM_TeamTable] = await get_team_object(
team_id=user_api_key_auth.team_id,
prisma_client=prisma_client,
@@ -387,7 +388,24 @@ class MCPRequestHandler:
proxy_logging_obj=proxy_logging_obj,
)
- return team_obj.object_permission if team_obj else None
+ if not team_obj:
+ return None
+
+ # Already loaded
+ if team_obj.object_permission:
+ return team_obj.object_permission
+
+ # Need to fetch from DB using object_permission_id
+ if team_obj.object_permission_id:
+ return await get_object_permission(
+ object_permission_id=team_obj.object_permission_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=user_api_key_auth.parent_otel_span,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+ return None
@staticmethod
async def get_allowed_tools_for_server(
@@ -536,41 +554,24 @@ class MCPRequestHandler:
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
) -> List[str]:
"""
- The `object_permission` for a team is not stored on the user_api_key_auth object
-
- first we check if the team has a object_permission_id attached
- - if it does then we look up the object_permission for the team
+ Get allowed MCP servers for a team.
+
+ Uses the helper _get_team_object_permission which:
+ 1. First checks if object_permission is already loaded on the team
+ 2. If not, fetches from DB using object_permission_id if it exists
"""
- from litellm.proxy.auth.auth_checks import get_team_object
- from litellm.proxy.proxy_server import (
- prisma_client,
- proxy_logging_obj,
- user_api_key_cache,
- )
-
if user_api_key_auth is None:
return []
if user_api_key_auth.team_id is None:
return []
- if prisma_client is None:
- verbose_logger.debug("prisma_client is None")
- return []
-
try:
- team_obj: Optional[LiteLLM_TeamTable] = await get_team_object(
- team_id=user_api_key_auth.team_id,
- prisma_client=prisma_client,
- user_api_key_cache=user_api_key_cache,
- parent_otel_span=user_api_key_auth.parent_otel_span,
- proxy_logging_obj=proxy_logging_obj,
+ # Use the helper method that properly handles fetching from DB if needed
+ object_permissions = await MCPRequestHandler._get_team_object_permission(
+ user_api_key_auth
)
- if team_obj is None:
- verbose_logger.debug("team_obj is None")
- return []
-
- object_permissions = team_obj.object_permission
+
if object_permissions is None:
return []
diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py
index c70a1f7a454..d7ebfb805f3 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -527,14 +527,27 @@ if MCP_AVAILABLE:
server_id: str,
user_api_key_auth: Optional[UserAPIKeyAuth],
) -> List[MCPTool]:
- """Filter tools based on key/team mcp_tool_permissions."""
+ """
+ Filter tools based on key/team mcp_tool_permissions.
+
+ Note: Tool names in the DB are stored without server prefixes,
+ but tool names from MCP servers are prefixed. We need to strip
+ the prefix before comparing.
+ """
# Filter by key/team tool-level permissions
allowed_tool_names = await MCPRequestHandler.get_allowed_tools_for_server(
server_id=server_id,
user_api_key_auth=user_api_key_auth,
)
if allowed_tool_names is not None:
- filtered_tools = [t for t in tools if t.name in allowed_tool_names]
+ # Strip prefix from tool names before comparing
+ # Tools are stored in DB without prefix, but come from MCP server with prefix
+ filtered_tools = []
+ for t in tools:
+ # Get tool name without server prefix
+ unprefixed_tool_name, _ = get_server_name_prefix_tool_mcp(t.name)
+ if unprefixed_tool_name in allowed_tool_names:
+ filtered_tools.append(t)
else:
# No restrictions, return all tools
filtered_tools = tools
diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py
index 68af5b4c9f5..3226ea01798 100644
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@ -21,7 +21,6 @@ import fastapi
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request, status
import litellm
-from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
from litellm._logging import verbose_proxy_logger
from litellm._uuid import uuid
from litellm.caching import DualCache
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py b/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py
index 9e316289c87..7da941db390 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py
@@ -1,6 +1,7 @@
import json
import os
import sys
+from unittest import mock
from unittest.mock import AsyncMock, MagicMock, patch
import orjson
@@ -1043,3 +1044,205 @@ def test_get_mcp_server_auth_headers_from_headers(headers, expected_result):
headers = Headers(headers)
result = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers)
assert result == expected_result
+
+
+async def test_get_team_object_permission_with_already_loaded_permission():
+ """
+ Test that _get_team_object_permission returns the already loaded object_permission
+ from the team object without making an additional DB call.
+ """
+ from litellm.proxy._types import LiteLLM_ObjectPermissionTable, LiteLLM_TeamTable
+
+ # Create mock object permission
+ mock_object_permission = LiteLLM_ObjectPermissionTable(
+ object_permission_id="perm-123",
+ mcp_servers=["server1", "server2"],
+ mcp_access_groups=["group1"],
+ vector_stores=["store1"],
+ )
+
+ # Create mock team object with object_permission already loaded
+ mock_team_obj = LiteLLM_TeamTable(
+ team_id="team-123",
+ object_permission=mock_object_permission,
+ object_permission_id="perm-123",
+ )
+
+ # Create mock user auth
+ mock_user_auth = UserAPIKeyAuth(
+ api_key="test-key",
+ user_id="test-user",
+ team_id="team-123",
+ )
+
+ # Mock get_team_object to return our team with loaded permission
+ with patch(
+ "litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.get_team_object"
+ ) as mock_get_team:
+ with patch(
+ "litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.get_object_permission"
+ ) as mock_get_perm:
+ mock_get_team.return_value = mock_team_obj
+
+ # Call the method
+ result = await MCPRequestHandler._get_team_object_permission(
+ mock_user_auth
+ )
+
+ # Assert we got the object permission
+ assert result == mock_object_permission
+ assert result.mcp_servers == ["server1", "server2"]
+
+ # Verify get_team_object was called
+ mock_get_team.assert_called_once()
+
+ # Verify get_object_permission was NOT called (since it was already loaded)
+ mock_get_perm.assert_not_called()
+
+
+async def test_get_team_object_permission_fetches_from_db_when_not_loaded():
+ """
+ Test that _get_team_object_permission fetches from DB when object_permission
+ is not loaded but object_permission_id exists.
+ """
+ from litellm.proxy._types import LiteLLM_ObjectPermissionTable, LiteLLM_TeamTable
+
+ # Create mock object permission (to be returned from DB)
+ mock_object_permission = LiteLLM_ObjectPermissionTable(
+ object_permission_id="perm-456",
+ mcp_servers=["server3", "server4"],
+ mcp_access_groups=["group2"],
+ vector_stores=["store2"],
+ )
+
+ # Create mock team object WITHOUT object_permission loaded (but has ID)
+ mock_team_obj = LiteLLM_TeamTable(
+ team_id="team-456",
+ object_permission=None,
+ object_permission_id="perm-456",
+ )
+
+ # Create mock user auth
+ mock_user_auth = UserAPIKeyAuth(
+ api_key="test-key",
+ user_id="test-user",
+ team_id="team-456",
+ )
+
+ # Mock the methods
+ with patch(
+ "litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.get_team_object"
+ ) as mock_get_team:
+ with patch(
+ "litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.get_object_permission"
+ ) as mock_get_perm:
+ mock_get_team.return_value = mock_team_obj
+ mock_get_perm.return_value = mock_object_permission
+
+ # Call the method
+ result = await MCPRequestHandler._get_team_object_permission(
+ mock_user_auth
+ )
+
+ # Assert we got the object permission
+ assert result == mock_object_permission
+ assert result.mcp_servers == ["server3", "server4"]
+
+ # Verify get_team_object was called
+ mock_get_team.assert_called_once()
+
+ # Verify get_object_permission WAS called (since it wasn't loaded)
+ mock_get_perm.assert_called_once_with(
+ object_permission_id="perm-456",
+ prisma_client=mock.ANY,
+ user_api_key_cache=mock.ANY,
+ parent_otel_span=mock_user_auth.parent_otel_span,
+ proxy_logging_obj=mock.ANY,
+ )
+
+
+async def test_get_allowed_mcp_servers_for_team_uses_helper():
+ """
+ Test that _get_allowed_mcp_servers_for_team properly uses _get_team_object_permission
+ helper which handles both loaded and unloaded object_permission cases.
+ """
+ from litellm.proxy._types import LiteLLM_ObjectPermissionTable
+
+ # Create mock object permission with servers and access groups
+ mock_object_permission = LiteLLM_ObjectPermissionTable(
+ object_permission_id="perm-789",
+ mcp_servers=["direct-server1", "direct-server2"],
+ mcp_access_groups=["dev-group"],
+ vector_stores=[],
+ )
+
+ # Create mock user auth
+ mock_user_auth = UserAPIKeyAuth(
+ api_key="test-key",
+ user_id="test-user",
+ team_id="team-789",
+ )
+
+ # Mock the helper methods
+ with patch.object(
+ MCPRequestHandler, "_get_team_object_permission"
+ ) as mock_get_team_perm:
+ with patch.object(
+ MCPRequestHandler, "_get_mcp_servers_from_access_groups"
+ ) as mock_get_access_group_servers:
+ # Configure mocks
+ mock_get_team_perm.return_value = mock_object_permission
+ mock_get_access_group_servers.return_value = ["group-server1", "group-server2"]
+
+ # Call the method
+ result = await MCPRequestHandler._get_allowed_mcp_servers_for_team(
+ mock_user_auth
+ )
+
+ # Assert the result contains both direct and access group servers
+ assert set(result) == {
+ "direct-server1",
+ "direct-server2",
+ "group-server1",
+ "group-server2",
+ }
+
+ # Verify _get_team_object_permission was called (the helper we fixed)
+ mock_get_team_perm.assert_called_once_with(mock_user_auth)
+
+ # Verify access groups were resolved
+ mock_get_access_group_servers.assert_called_once_with(["dev-group"])
+
+
+async def test_get_allowed_mcp_servers_for_team_with_no_object_permission():
+ """
+ Test that _get_allowed_mcp_servers_for_team returns empty list when
+ team has no object_permission.
+ """
+ # Create mock user auth
+ mock_user_auth = UserAPIKeyAuth(
+ api_key="test-key",
+ user_id="test-user",
+ team_id="team-no-perm",
+ )
+
+ # Mock the helper to return None (no object permission)
+ with patch.object(
+ MCPRequestHandler, "_get_team_object_permission"
+ ) as mock_get_team_perm:
+ mock_get_team_perm.return_value = None
+
+ # Call the method
+ result = await MCPRequestHandler._get_allowed_mcp_servers_for_team(
+ mock_user_auth
+ )
+
+ # Assert empty list is returned
+ assert result == []
+
+ # Verify the helper was called
+ mock_get_team_perm.assert_called_once_with(mock_user_auth)
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py
index 9c23157f0fd..66871aefc1c 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py
@@ -995,3 +995,101 @@ async def test_list_tools_with_no_tool_permissions_shows_all():
assert len(tools) == 3
tool_names = sorted([t.name for t in tools])
assert tool_names == ["tool1", "tool2", "tool3"]
+
+
+async def test_list_tools_strips_prefix_when_matching_permissions():
+ """
+ Test that tool permission filtering correctly strips prefixes from tool names.
+
+ Tools from MCP servers are prefixed (e.g., "GITMCP-fetch_litellm_documentation"),
+ but allowed tools in DB are stored without prefix (e.g., "fetch_litellm_documentation").
+ The filtering should strip the prefix before comparing.
+ """
+ try:
+ from litellm.proxy._experimental.mcp_server.server import (
+ _get_tools_from_mcp_servers,
+ set_auth_context,
+ )
+ from litellm.proxy._types import LiteLLM_ObjectPermissionTable, UserAPIKeyAuth
+ except ImportError:
+ pytest.skip("MCP server not available")
+
+ # Create object permission with tool-level restrictions (WITHOUT prefix)
+ object_permission = LiteLLM_ObjectPermissionTable(
+ object_permission_id="perm_123",
+ mcp_tool_permissions={
+ "gitmcp_server": [
+ "fetch_litellm_documentation", # No prefix in DB
+ "search_litellm_code", # No prefix in DB
+ ],
+ },
+ )
+
+ user_api_key_auth = UserAPIKeyAuth(
+ api_key="test_key",
+ user_id="test_user",
+ object_permission=object_permission,
+ )
+ set_auth_context(user_api_key_auth)
+
+ # Mock server
+ server = MagicMock()
+ server.server_id = "gitmcp_server"
+ server.name = "GITMCP"
+ server.alias = "gitmcp"
+ server.allowed_tools = None
+ server.disallowed_tools = None
+
+ # Mock manager
+ mock_manager = MagicMock()
+ mock_manager.get_allowed_mcp_servers = AsyncMock(return_value=["gitmcp_server"])
+ mock_manager.get_mcp_server_by_id = lambda server_id: server
+
+ async def mock_get_tools_from_server(
+ server, mcp_auth_header=None, extra_headers=None, add_prefix=True
+ ):
+ # Return tools WITH prefix (as they come from MCP server)
+ tool1 = MagicMock()
+ tool1.name = "GITMCP-fetch_litellm_documentation" # Prefixed
+ tool1.description = "Fetch docs"
+ tool1.inputSchema = {}
+
+ tool2 = MagicMock()
+ tool2.name = "GITMCP-search_litellm_documentation" # Prefixed, not in allowed list
+ tool2.description = "Search docs"
+ tool2.inputSchema = {}
+
+ tool3 = MagicMock()
+ tool3.name = "GITMCP-search_litellm_code" # Prefixed
+ tool3.description = "Search code"
+ tool3.inputSchema = {}
+
+ tool4 = MagicMock()
+ tool4.name = "GITMCP-fetch_generic_url_content" # Prefixed, not in allowed list
+ tool4.description = "Fetch URL"
+ tool4.inputSchema = {}
+
+ return [tool1, tool2, tool3, tool4]
+
+ mock_manager._get_tools_from_server = mock_get_tools_from_server
+
+ with patch(
+ "litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager",
+ mock_manager,
+ ):
+ tools = await _get_tools_from_mcp_servers(
+ user_api_key_auth=user_api_key_auth,
+ mcp_auth_header=None,
+ mcp_servers=None,
+ mcp_server_auth_headers=None,
+ )
+
+ # Should only return the 2 tools that match (after stripping prefix)
+ assert len(tools) == 2
+ tool_names = sorted([t.name for t in tools])
+ # Tools still have prefixes in the output, but were filtered correctly
+ assert tool_names == [
+ "GITMCP-fetch_litellm_documentation",
+ "GITMCP-search_litellm_code",
+ ]