Skip to content

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

fix(mcp): retain selected guardrails for virtual REST calls

Joshua Valluru5b9119540650
diff --git a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py
index 6001ef537aa..6a0ab5bdec5 100644
--- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py
+++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py
@@ -329,7 +329,7 @@ if MCP_AVAILABLE:
virtual_processor: Final = ProxyBaseLLMRequestProcessing(data=data)
_request_start_time: Final = datetime.now() # noqa: DTZ005 # naive to match the tool start time below
try:
- (_, virtual_logging_obj) = await virtual_processor.common_processing_pre_call_logic(
+ (virtual_data, virtual_logging_obj) = await virtual_processor.common_processing_pre_call_logic(
request=request,
user_api_key_dict=user_api_key_dict,
proxy_config=proxy_config,
@@ -348,6 +348,7 @@ if MCP_AVAILABLE:
oauth2_headers=virtual_oauth2_headers,
raw_headers=virtual_raw_headers,
litellm_logging_obj=virtual_logging_obj,
+ guardrail_context=MCPRequestContext.resolve_guardrail_context(virtual_data),
)
except Exception as e:
virtual_request_data: Final = virtual_processor.data
diff --git a/litellm/proxy/_experimental/mcp_server/tool_search.py b/litellm/proxy/_experimental/mcp_server/tool_search.py
index 2c73f9b863b..e921ab0331e 100644
--- a/litellm/proxy/_experimental/mcp_server/tool_search.py
+++ b/litellm/proxy/_experimental/mcp_server/tool_search.py
@@ -596,6 +596,7 @@ async def handle_mcp_tool_call(
raw_headers: dict[str, str] | None = None,
litellm_logging_obj: LiteLLMLoggingObj | None = None,
requested_server_id: str | None = None,
+ guardrail_context: Mapping[str, object] | None = None,
) -> CallToolResult:
from litellm.proxy._experimental.mcp_server.server import (
_get_allowed_mcp_servers,
@@ -635,4 +636,5 @@ async def handle_mcp_tool_call(
raw_headers=raw_headers,
litellm_logging_obj=litellm_logging_obj,
requested_server_id=requested_server_id,
+ guardrail_context=guardrail_context,
)
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_rest_endpoints.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_rest_endpoints.py
index d535f2f6eaf..4ec4ae31ca6 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_rest_endpoints.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_rest_endpoints.py
@@ -3022,7 +3022,7 @@ class TestCallToolRestAPI:
self.data = data
async def common_processing_pre_call_logic(self, **kwargs):
- return None, MagicMock()
+ return self.data, MagicMock()
monkeypatch.setattr(rest_endpoints, "build_effective_auth_contexts", fake_contexts, raising=False)
monkeypatch.setattr(tool_search_mod, "handle_mcp_tool_call", fake_handle_mcp_tool_call, raising=False)
@@ -3106,6 +3106,82 @@ class TestCallToolRestAPI:
assert logging_obj is not None
[email protected]("virtual", [False, True])
[email protected]("selected", [False, True])
[email protected]("action", ["block", "modify"])
+async def test_request_selected_tool_specific_guardrail_applies_to_virtual_execution(
+ monkeypatch: pytest.MonkeyPatch, virtual: bool, selected: bool, action: str,
+) -> None:
+ import litellm
+ from litellm.caching.caching import DualCache
+ from litellm.proxy import proxy_server
+ from litellm.proxy._experimental.mcp_server import mcp_server_manager, server, tool_registry
+ from litellm.proxy._types import LiteLLM_ObjectPermissionTable
+ from litellm.proxy.guardrails.guardrail_hooks.custom_code.custom_code_guardrail import CustomCodeGuardrail
+ from litellm.proxy.utils import ProxyLogging
+
+ guardrail: Final = CustomCodeGuardrail(
+ guardrail_name="block-resolved-tool", event_hook="pre_mcp_call", default_on=False,
+ custom_code='def apply_guardrail(inputs, request_data, input_type):\n'
+ ' if inputs.get("tools", [{}])[0].get("function", {}).get("name") == "execute":\n'
+ f' return {{"action": "{action}", "reason": "resolved tool blocked", "texts": ["redacted"]}}\n'
+ ' return allow()\n',
+ )
+ manager: Final = mcp_server_manager.MCPServerManager()
+ managed_server: Final = MCPServer(
+ server_id="observer", name="observer", server_name="observer", transport="http",
+ url="https://observer.example/mcp", spec_path="observer.json", auth_type="none",
+ )
+ manager.registry = {"observer": managed_server}
+ manager.tool_name_to_mcp_server_name_mapping = {"observer-execute": "observer"}
+ upstream: Final = AsyncMock(return_value={"executed": True})
+ registry: Final = tool_registry.MCPToolRegistry()
+ registry.register_tool("observer-execute", "Execute", {"type": "object"}, upstream)
+
+ async def passthrough_request_data(data: dict[str, object], **kwargs: object) -> dict[str, object]:
+ return data
+
+ monkeypatch.setattr(litellm, "callbacks", [guardrail])
+ monkeypatch.setattr(tool_registry, "global_mcp_tool_registry", registry)
+ monkeypatch.setattr(mcp_server_manager, "global_mcp_server_manager", manager)
+ monkeypatch.setattr(server, "global_mcp_tool_registry", registry)
+ monkeypatch.setattr(server, "global_mcp_server_manager", manager)
+ monkeypatch.setattr(rest_endpoints, "global_mcp_server_manager", manager)
+ monkeypatch.setattr(server, "_get_allowed_mcp_servers", AsyncMock(return_value=[managed_server]))
+ monkeypatch.setattr(proxy_server, "proxy_logging_obj", ProxyLogging(user_api_key_cache=DualCache()))
+ monkeypatch.setattr(proxy_server, "add_litellm_data_to_request", passthrough_request_data)
+ monkeypatch.setattr(proxy_server, "proxy_config", {})
+ monkeypatch.setattr(proxy_server, "general_settings", {})
+ caller: Final = UserAPIKeyAuth(
+ api_key="hashed-key", request_route="/mcp-rest/tools/call",
+ object_permission=LiteLLM_ObjectPermissionTable(
+ object_permission_id="virtual-test", mcp_servers=["observer"], mcp_tool_search_enabled=True,
+ ),
+ )
+ request: Final = _build_request(
+ path="/mcp-rest/tools/call", method="POST",
+ json_body={
+ "name": "mcp_tool_call" if virtual else "observer-execute",
+ "server_id": "observer",
+ "arguments": {"tool_name": "observer-execute", "arguments": {"q": "confidential"}}
+ if virtual else {"q": "confidential"},
+ "guardrails": ["block-resolved-tool"] if selected else [],
+ },
+ )
+ if selected and action == "block":
+ with pytest.raises(HTTPException) as error:
+ await rest_endpoints.call_tool_rest_api(request, user_api_key_dict=caller)
+ assert error.value.status_code == 400
+ assert error.value.detail["message"] == "resolved tool blocked"
+ upstream.assert_not_awaited()
+ else:
+ result: Final = await rest_endpoints.call_tool_rest_api(request, user_api_key_dict=caller)
+ assert result.isError is False
+ upstream.assert_awaited_once()
+ assert upstream.await_args.kwargs == {"q": "redacted" if selected else "confidential"}
+
+
class TestGetToolsForSingleServer:
"""Test _get_tools_for_single_server with object_permission filtering"""
diff --git a/tests/test_litellm/proxy/utils/proxy_logging/test_mcp_bridging.py b/tests/test_litellm/proxy/utils/proxy_logging/test_mcp_bridging.py
index 438b2351034..4e02124e1b3 100644
--- a/tests/test_litellm/proxy/utils/proxy_logging/test_mcp_bridging.py
+++ b/tests/test_litellm/proxy/utils/proxy_logging/test_mcp_bridging.py
@@ -105,6 +105,7 @@ def test_convert_mcp_to_llm_format_exposes_caller_identity_on_metadata(proxy_log
"user_api_key_user_id": "u-1",
"user_api_key_team_id": "t-1",
"user_api_key_end_user_id": "eu-1",
+ "guardrails": [],
}