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]

feat(guardrails): add pre_mcp_call support to Content Filter (#32936)

yucheng-berrie7f41442d037
diff --git a/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py b/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py
index c3b66f8f388..dda4b0236eb 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py
@@ -29,9 +29,11 @@ from fastapi import HTTPException
from litellm import Router
from litellm._logging import verbose_proxy_logger
+from litellm.constants import DEFAULT_MAX_RECURSE_DEPTH
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.proxy._types import UserAPIKeyAuth
from litellm.types.utils import (
+ CallTypes,
GenericGuardrailAPIInputs,
GuardrailStatus,
GuardrailTracingDetail,
@@ -1683,6 +1685,66 @@ class ContentFilterGuardrail(CustomGuardrail):
tracing_detail=GuardrailTracingDetail(**tracing_kw), # type: ignore[typeddict-item]
)
+ @staticmethod
+ def _get_mcp_tool_name(request_data: dict) -> str | None:
+ raw_name: object = request_data.get("mcp_tool_name")
+ if isinstance(raw_name, str) and raw_name:
+ return raw_name
+ return None
+
+ def _assert_mcp_argument_label_clean(self, text: str, detections: list[ContentFilterDetection]) -> None:
+ if self._filter_single_text(text, detections=detections) != text:
+ raise HTTPException(
+ status_code=400,
+ detail={
+ "error": "Content blocked: MCP tool call argument matched a masking rule on a non-rewritable field"
+ },
+ )
+
+ def _filter_mcp_argument_value(
+ self, value: object, detections: list[ContentFilterDetection], depth: int = 0
+ ) -> object:
+ if depth > DEFAULT_MAX_RECURSE_DEPTH:
+ raise HTTPException(
+ status_code=400,
+ detail={"error": "Content blocked: MCP tool call arguments exceed the maximum nesting depth"},
+ )
+ if isinstance(value, str):
+ return self._filter_single_text(value, detections=detections)
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ self._assert_mcp_argument_label_clean(str(value), detections)
+ return value
+ if isinstance(value, dict):
+ for key in value:
+ if isinstance(key, str):
+ self._assert_mcp_argument_label_clean(key, detections)
+ return {key: self._filter_mcp_argument_value(item, detections, depth + 1) for key, item in value.items()}
+ if isinstance(value, list):
+ return [self._filter_mcp_argument_value(item, detections, depth + 1) for item in value]
+ return value
+
+ def _scan_mcp_tool_call_arguments(
+ self,
+ request_data: dict,
+ detections: list[ContentFilterDetection],
+ logging_obj: Optional["LiteLLMLoggingObj"] = None,
+ ) -> None:
+ if not self._event_hook_is_event_type(GuardrailEventHooks.pre_mcp_call):
+ return
+ call_type: object = getattr(logging_obj, "call_type", None)
+ if logging_obj is not None and call_type != CallTypes.call_mcp_tool.value:
+ return
+ if self._get_mcp_tool_name(request_data) is None:
+ return
+ raw_arguments: object = request_data.get("mcp_arguments")
+ if not isinstance(raw_arguments, dict) or not raw_arguments:
+ return
+ filtered_arguments = self._filter_mcp_argument_value(raw_arguments, detections)
+ if filtered_arguments == raw_arguments:
+ return
+ request_data["mcp_arguments"] = filtered_arguments
+ request_data["modified_arguments"] = filtered_arguments
+
async def apply_guardrail(
self,
inputs: "GenericGuardrailAPIInputs",
@@ -1737,6 +1799,11 @@ class ContentFilterGuardrail(CustomGuardrail):
verbose_proxy_logger.debug("ContentFilterGuardrail: Guardrail applied successfully")
inputs["texts"] = processed_texts
+ if input_type == "request":
+ self._scan_mcp_tool_call_arguments(
+ request_data=request_data, detections=detections, logging_obj=logging_obj
+ )
+
# Count masked entities by type
self._count_masked_entities(detections, masked_entity_count)
@@ -1903,4 +1970,5 @@ class ContentFilterGuardrail(CustomGuardrail):
GuardrailEventHooks.post_call,
GuardrailEventHooks.during_call,
GuardrailEventHooks.realtime_input_transcription,
+ GuardrailEventHooks.pre_mcp_call,
]
diff --git a/tests/code_coverage_tests/recursive_detector.py b/tests/code_coverage_tests/recursive_detector.py
index f9bd4a012cc..e08d703d21f 100644
--- a/tests/code_coverage_tests/recursive_detector.py
+++ b/tests/code_coverage_tests/recursive_detector.py
@@ -54,6 +54,7 @@ IGNORE_FUNCTIONS = [
"sanitize_oci_schema", # OCI: bounded by JSON-schema tree depth.
"_freeze_for_dedupe", # OTEL: max depth set (default 16, _FREEZE_MAX_DEPTH); fails closed by returning repr(value) at the cap.
"apply_json_merge_patch", # max depth set (_MAX_MERGE_DEPTH=64); fails closed by raising ValueError at the cap.
+ "_filter_mcp_argument_value", # max depth set (DEFAULT_MAX_RECURSE_DEPTH); fails closed by blocking the MCP call at the cap.
]
diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py
index bb079ea6580..452e2f666a9 100644
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py
@@ -2398,3 +2398,455 @@ class TestTracingFieldsE2E:
# No detections, so these should be None
assert slg.get("detection_method") is None
assert slg.get("match_details") is None
+
+
+class TestContentFilterMCPPreCall:
+ """Test pre_mcp_call support: MCP tool call argument scanning in apply_guardrail"""
+
+ def test_pre_mcp_call_is_supported_event_hook(self):
+ """
+ Constructing the guardrail with mode pre_mcp_call must succeed (LIT-4226)
+ """
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-mode",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ blocked_words=[BlockedWord(keyword="confidential", action=ContentFilterAction.BLOCK)],
+ )
+
+ assert GuardrailEventHooks.pre_mcp_call in guardrail.supported_event_hooks
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_blocks_mcp_tool_arguments(self):
+ """
+ Blocked word inside MCP tool call arguments raises HTTPException
+ """
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-block",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ blocked_words=[BlockedWord(keyword="confidential", action=ContentFilterAction.BLOCK)],
+ )
+
+ request_data = {
+ "mcp_tool_name": "send_email",
+ "mcp_arguments": {"body": "this is confidential data"},
+ }
+
+ with pytest.raises(HTTPException) as exc_info:
+ await guardrail.apply_guardrail(
+ inputs={},
+ request_data=request_data,
+ input_type="request",
+ )
+
+ assert exc_info.value.status_code == 400
+ assert "confidential" in str(exc_info.value.detail)
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_masks_mcp_tool_arguments(self):
+ """
+ MASK pattern match inside MCP arguments writes masked args to modified_arguments
+ """
+ patterns = [
+ ContentFilterPattern(
+ pattern_type="prebuilt",
+ pattern_name="email",
+ action=ContentFilterAction.MASK,
+ ),
+ ]
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-mask",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ patterns=patterns,
+ )
+
+ request_data = {
+ "mcp_tool_name": "send_email",
+ "mcp_arguments": {"contact": "reach me at [email protected]"},
+ }
+
+ await guardrail.apply_guardrail(
+ inputs={},
+ request_data=request_data,
+ input_type="request",
+ )
+
+ modified = request_data["modified_arguments"]
+ assert "[EMAIL_REDACTED]" in modified["contact"]
+ assert "[email protected]" not in modified["contact"]
+ assert request_data["mcp_arguments"] == modified
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_mcp_arguments_clean_pass(self):
+ """
+ Clean MCP arguments pass through without modification
+ """
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-clean",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ blocked_words=[BlockedWord(keyword="confidential", action=ContentFilterAction.BLOCK)],
+ )
+
+ request_data = {
+ "mcp_tool_name": "get_weather",
+ "mcp_arguments": {"city": "Paris"},
+ }
+
+ await guardrail.apply_guardrail(
+ inputs={},
+ request_data=request_data,
+ input_type="request",
+ )
+
+ assert "modified_arguments" not in request_data
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_mcp_anchored_regex_matches_argument_value(self):
+ """
+ Anchored custom regexes apply to each argument value, not to a serialized JSON document
+ """
+ patterns = [
+ ContentFilterPattern(
+ pattern_type="regex",
+ pattern="^secret$",
+ name="anchored_secret",
+ action=ContentFilterAction.BLOCK,
+ ),
+ ]
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-anchored",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ patterns=patterns,
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ await guardrail.apply_guardrail(
+ inputs={},
+ request_data={"mcp_tool_name": "save_note", "mcp_arguments": {"note": "secret"}},
+ input_type="request",
+ )
+
+ assert exc_info.value.status_code == 400
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_mcp_mask_preserves_nested_structure(self):
+ """
+ Masking rewrites string values inside nested dicts and lists without corrupting the structure
+ """
+ patterns = [
+ ContentFilterPattern(
+ pattern_type="prebuilt",
+ pattern_name="email",
+ action=ContentFilterAction.MASK,
+ ),
+ ]
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-nested-mask",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ patterns=patterns,
+ )
+
+ request_data = {
+ "mcp_tool_name": "send_email",
+ "mcp_arguments": {
+ "recipients": ["team", "cc [email protected]"],
+ "meta": {"note": "from [email protected]", "count": 2},
+ },
+ }
+
+ await guardrail.apply_guardrail(inputs={}, request_data=request_data, input_type="request")
+
+ modified = request_data["modified_arguments"]
+ assert modified["recipients"][0] == "team"
+ assert "[EMAIL_REDACTED]" in modified["recipients"][1]
+ assert "[email protected]" not in modified["recipients"][1]
+ assert "[EMAIL_REDACTED]" in modified["meta"]["note"]
+ assert modified["meta"]["count"] == 2
+ assert request_data["mcp_arguments"] == modified
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "mcp_arguments",
+ [
+ {"this is confidential data": "x"},
+ {"a": {"contains confidential stuff": "x"}},
+ ],
+ )
+ async def test_apply_guardrail_mcp_argument_keys_scanned(self, mcp_arguments):
+ """
+ Blocked content smuggled in argument keys (top-level or nested) is detected, not just values
+ """
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-key-smuggling",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ blocked_words=[BlockedWord(keyword="confidential", action=ContentFilterAction.BLOCK)],
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ await guardrail.apply_guardrail(
+ inputs={},
+ request_data={"mcp_tool_name": "send_email", "mcp_arguments": mcp_arguments},
+ input_type="request",
+ )
+
+ assert exc_info.value.status_code == 400
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_mcp_numeric_mask_match_blocks(self):
+ """
+ A MASK rule matching a numeric argument blocks the call, since a redaction tag cannot be
+ represented in a number
+ """
+ patterns = [
+ ContentFilterPattern(
+ pattern_type="prebuilt",
+ pattern_name="visa",
+ action=ContentFilterAction.MASK,
+ ),
+ ]
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-numeric-mask",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ patterns=patterns,
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ await guardrail.apply_guardrail(
+ inputs={},
+ request_data={"mcp_tool_name": "charge_card", "mcp_arguments": {"card": 4111111111111111}},
+ input_type="request",
+ )
+
+ assert exc_info.value.status_code == 400
+ assert "non-rewritable" in str(exc_info.value.detail)
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_mcp_arguments_exceeding_max_depth_block(self):
+ """
+ Arguments nested beyond DEFAULT_MAX_RECURSE_DEPTH block fail-closed instead of passing unscanned
+ """
+ from litellm.constants import DEFAULT_MAX_RECURSE_DEPTH
+
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-depth-cap",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ blocked_words=[BlockedWord(keyword="confidential", action=ContentFilterAction.BLOCK)],
+ )
+
+ deep: dict = {"leaf": "confidential data"}
+ for _ in range(DEFAULT_MAX_RECURSE_DEPTH + 1):
+ deep = {"level": deep}
+
+ with pytest.raises(HTTPException) as exc_info:
+ await guardrail.apply_guardrail(
+ inputs={},
+ request_data={"mcp_tool_name": "save_note", "mcp_arguments": deep},
+ input_type="request",
+ )
+
+ assert exc_info.value.status_code == 400
+ assert "nesting depth" in str(exc_info.value.detail)
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_mixed_mode_chat_call_not_scanned(self):
+ """
+ A mixed pre_call + pre_mcp_call guardrail must not run the MCP scan on a chat invocation,
+ identified by the proxy-owned logging object's call_type, even when MCP keys are planted
+ """
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mixed-mode-chat",
+ event_hook=[GuardrailEventHooks.pre_call, GuardrailEventHooks.pre_mcp_call],
+ blocked_words=[BlockedWord(keyword="confidential", action=ContentFilterAction.BLOCK)],
+ )
+
+ chat_logging_obj = MagicMock()
+ chat_logging_obj.call_type = "acompletion"
+
+ request_data = {
+ "mcp_tool_name": "send_email",
+ "mcp_arguments": {"body": "this is confidential data"},
+ "messages": [{"role": "user", "content": "hello"}],
+ }
+
+ await guardrail.apply_guardrail(
+ inputs={"texts": ["hello"]},
+ request_data=request_data,
+ input_type="request",
+ logging_obj=chat_logging_obj,
+ )
+
+ assert "modified_arguments" not in request_data
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("mcp_call_type", [None, "call_mcp_tool"])
+ async def test_apply_guardrail_mixed_mode_mcp_call_scanned(self, mcp_call_type):
+ """
+ The same mixed mode guardrail still scans genuine MCP invocations, whether the logging
+ object is absent (canonical synthetic payload) or carries the MCP call_type
+ """
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mixed-mode-mcp",
+ event_hook=[GuardrailEventHooks.pre_call, GuardrailEventHooks.pre_mcp_call],
+ blocked_words=[BlockedWord(keyword="confidential", action=ContentFilterAction.BLOCK)],
+ )
+
+ logging_obj = None
+ if mcp_call_type is not None:
+ logging_obj = MagicMock()
+ logging_obj.call_type = mcp_call_type
+
+ with pytest.raises(HTTPException):
+ await guardrail.apply_guardrail(
+ inputs={},
+ request_data={
+ "mcp_tool_name": "send_email",
+ "mcp_arguments": {"body": "this is confidential data"},
+ },
+ input_type="request",
+ logging_obj=logging_obj,
+ )
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_non_mcp_name_arguments_not_scanned(self):
+ """
+ A raw body with top-level name + arguments (e.g. pass-through) is not treated as an MCP call;
+ only the canonical mcp_tool_name + mcp_arguments keys trigger the scan
+ """
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-non-mcp-shape",
+ event_hook=GuardrailEventHooks.pre_call,
+ blocked_words=[BlockedWord(keyword="confidential", action=ContentFilterAction.BLOCK)],
+ )
+
+ await guardrail.apply_guardrail(
+ inputs={"texts": ["hello"]},
+ request_data={"name": "send_email", "arguments": {"body": "confidential data"}},
+ input_type="request",
+ )
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_mcp_response_side_not_scanned(self):
+ """
+ input_type response does not run the MCP argument scan
+ """
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-response-side",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ blocked_words=[BlockedWord(keyword="confidential", action=ContentFilterAction.BLOCK)],
+ )
+
+ await guardrail.apply_guardrail(
+ inputs={"texts": ["clean response"]},
+ request_data={
+ "mcp_tool_name": "send_email",
+ "mcp_arguments": {"body": "this is confidential data"},
+ },
+ input_type="response",
+ )
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_blocks_non_ascii_mcp_arguments(self):
+ """
+ Non-ASCII blocked words in MCP arguments must be detected (json.dumps must not escape them)
+ """
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-non-ascii",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ blocked_words=[BlockedWord(keyword="\u673a\u5bc6", action=ContentFilterAction.BLOCK)],
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ await guardrail.apply_guardrail(
+ inputs={},
+ request_data={
+ "mcp_tool_name": "send_email",
+ "mcp_arguments": {"body": "this is \u673a\u5bc6 data"},
+ },
+ input_type="request",
+ )
+
+ assert exc_info.value.status_code == 400
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_mcp_mask_survives_chained_guardrails(self):
+ """
+ A second masking guardrail must scan the already-masked arguments, not resurrect the originals
+ """
+ email_guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-chain-email",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ patterns=[
+ ContentFilterPattern(pattern_type="prebuilt", pattern_name="email", action=ContentFilterAction.MASK)
+ ],
+ )
+ phone_guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-chain-phone",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ patterns=[
+ ContentFilterPattern(pattern_type="prebuilt", pattern_name="us_phone", action=ContentFilterAction.MASK)
+ ],
+ )
+
+ request_data = {
+ "mcp_tool_name": "send_email",
+ "mcp_arguments": {"contact": "email [email protected] phone 555-123-4567"},
+ }
+
+ await email_guardrail.apply_guardrail(inputs={}, request_data=request_data, input_type="request")
+ await phone_guardrail.apply_guardrail(inputs={}, request_data=request_data, input_type="request")
+
+ final = request_data["modified_arguments"]
+ assert "[email protected]" not in final["contact"]
+ assert "555-123-4567" not in final["contact"]
+ assert "[EMAIL_REDACTED]" in final["contact"]
+ assert "[US_PHONE_REDACTED]" in final["contact"]
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_pre_call_mode_ignores_forged_mcp_keys(self):
+ """
+ A pre_call mode guardrail must not run the MCP scan even when a caller plants MCP keys in the body
+ """
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-forged-mcp-keys",
+ event_hook=GuardrailEventHooks.pre_call,
+ blocked_words=[BlockedWord(keyword="confidential", action=ContentFilterAction.BLOCK)],
+ )
+
+ request_data = {
+ "mcp_tool_name": "send_email",
+ "mcp_arguments": {"body": "this is confidential data"},
+ "messages": [{"role": "user", "content": "hello"}],
+ }
+
+ await guardrail.apply_guardrail(
+ inputs={"texts": ["hello"]},
+ request_data=request_data,
+ input_type="request",
+ )
+
+ assert "modified_arguments" not in request_data
+ assert request_data["mcp_arguments"] == {"body": "this is confidential data"}
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "request_data",
+ [
+ {"name": "send_email", "arguments": {"body": "confidential data"}},
+ {"name": "send_email", "mcp_arguments": {"body": "confidential data"}},
+ ],
+ )
+ async def test_apply_guardrail_pre_mcp_mode_requires_canonical_keys(self, request_data):
+ """
+ Even in pre_mcp_call mode, only the canonical mcp_tool_name key identifies an MCP call;
+ a bare name key must not, regardless of which arguments key accompanies it
+ """
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-mcp-canonical-keys",
+ event_hook=GuardrailEventHooks.pre_mcp_call,
+ blocked_words=[BlockedWord(keyword="confidential", action=ContentFilterAction.BLOCK)],
+ )
+
+ await guardrail.apply_guardrail(
+ inputs={},
+ request_data=request_data,
+ input_type="request",
+ )
+ assert "modified_arguments" not in request_data
diff --git a/tests/test_litellm/proxy/guardrails/test_guardrail_endpoints.py b/tests/test_litellm/proxy/guardrails/test_guardrail_endpoints.py
index eb0a670291e..21e7186fca3 100644
--- a/tests/test_litellm/proxy/guardrails/test_guardrail_endpoints.py
+++ b/tests/test_litellm/proxy/guardrails/test_guardrail_endpoints.py
@@ -2095,9 +2095,11 @@ async def test_get_guardrail_ui_settings_returns_per_provider_supported_modes():
modes_by_provider = result.supported_modes_by_provider
- # Guardrails from the bug report: neither accepts pre_mcp_call, and the
- # settings endpoint must reflect that so the UI can hide it.
- assert "pre_mcp_call" not in modes_by_provider["litellm_content_filter"]
+ # Content Filter now supports pre_mcp_call (LIT-4226 feature half) but not
+ # during_mcp_call; Tool Permission still supports neither, and the settings
+ # endpoint must reflect both so the UI shows exactly the savable modes.
+ assert "pre_mcp_call" in modes_by_provider["litellm_content_filter"]
+ assert "during_mcp_call" not in modes_by_provider["litellm_content_filter"]
assert modes_by_provider["tool_permission"] == ["pre_call", "post_call"]
# MCP-capable guardrails must still advertise the MCP hooks so users who
@@ -2139,10 +2141,12 @@ async def test_ui_settings_map_matches_runtime_supported_event_hooks():
], provider
-def test_content_filter_runtime_rejects_pre_mcp_call():
+def test_content_filter_runtime_rejects_unsupported_mcp_hook():
"""
Locks the runtime side of the LIT-4226 contract: the ContentFilterGuardrail
- validator must reject pre_mcp_call at construction. If someone widens the
+ validator must reject a hook missing from its supported list at
+ construction. pre_mcp_call is supported since the LIT-4226 feature half, so
+ during_mcp_call is the unsupported example now. If someone widens the
UI classmethod but forgets to widen the runtime supported_event_hooks (or
vice versa), the two-lists-must-agree test above catches the drift and this
test catches the specific bug the ticket reported.
@@ -2155,7 +2159,7 @@ def test_content_filter_runtime_rejects_pre_mcp_call():
with pytest.raises(ValueError, match="not in the supported event hooks"):
ContentFilterGuardrail(
guardrail_name="lit4226-runtime-check",
- event_hook=GuardrailEventHooks.pre_mcp_call,
+ event_hook=GuardrailEventHooks.during_mcp_call,
)
@@ -2197,14 +2201,14 @@ def test_strict_guardrail_modes_flag_controls_raise_vs_warn(monkeypatch, caplog)
with pytest.raises(ValueError, match="not in the supported event hooks"):
ContentFilterGuardrail(
guardrail_name="lit4226-strict-default",
- event_hook=GuardrailEventHooks.pre_mcp_call,
+ event_hook=GuardrailEventHooks.during_mcp_call,
)
monkeypatch.setenv("LITELLM_STRICT_GUARDRAIL_MODES", "false")
with caplog.at_level(logging.WARNING):
instance = ContentFilterGuardrail(
guardrail_name="lit4226-strict-off",
- event_hook=GuardrailEventHooks.pre_mcp_call,
+ event_hook=GuardrailEventHooks.during_mcp_call,
)
assert instance is not None
assert any("not in the supported event hooks" in rec.message for rec in caplog.records)