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
fix(mcp): scan and mask MCP tool call arguments in unified guardrails (#35142)
Yassin Kortam9832d6e4a6e3
diff --git a/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py b/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.pyindex 4918229c2b8..c0235077ecd 100644--- a/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py+++ b/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py@@ -1,16 +1,19 @@"""MCP Guardrail Handler for Unified Guardrails.-Converts an MCP call_tool (name + arguments) into a single OpenAI-compatible-tool_call and passes it to apply_guardrail. Works with the synthetic payload-from ProxyLogging._convert_mcp_to_llm_format.+Converts an MCP call_tool (name + arguments) into the OpenAI-compatible shape+apply_guardrail expects: the tool as a single-entry ``tools`` definition, and+every string leaf of the call arguments as ``texts`` so text guardrails can+detect and mask sensitive values in the payload. Works with the synthetic+request from ProxyLogging._convert_mcp_to_llm_format.Note: For MCP tool definitions (schema) -> OpenAI tools=[], seelitellm.experimental_mcp_client.tools.transform_mcp_tool_to_openai_toolwhen you have a full MCP Tool from list_tools. Here we only have the call-payload (name + arguments) so we just build the tool_call.+payload (name + arguments) so we just build the tool definition."""+from collections.abc import Mapping, Sequencefrom typing import TYPE_CHECKING, Any, Finalfrom fastapi import HTTPException@@ -20,6 +23,8 @@ from litellm._logging import verbose_proxy_loggerfrom litellm.experimental_mcp_client.tools import transform_mcp_tool_to_openai_toolfrom litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslationfrom litellm.proxy._experimental.mcp_server.utils import (+ MAX_STRUCTURED_CONTENT_SCAN_DEPTH,+ JSONLeafPath,json_string_leaves,json_unrewritable_labels,mcp_content_item_text,@@ -42,6 +47,72 @@ if TYPE_CHECKING:from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+def _blocked(reason: str) -> HTTPException:+ return HTTPException(status_code=400, detail={"error": f"Content blocked: {reason}"})+++def _too_deeply_nested() -> HTTPException:+ return _blocked(+ f"MCP tool call arguments exceed the maximum nesting depth of {MAX_STRUCTURED_CONTENT_SCAN_DEPTH} "+ "and cannot be scanned by the configured guardrail"+ )+++def _argument_replacements(+ argument_leaves: tuple[tuple[JSONLeafPath, str], ...],+ masked_texts: Sequence[str] | None,+) -> Mapping[JSONLeafPath, str]:+ """Positionally pair the guardrail's returned texts with the leaves they came from.++ Only leaves the guardrail actually rewrote are returned, so a guardrail that+ detects nothing leaves the outbound tool call byte-identical. A guardrail that+ returns the wrong number of texts fails closed, because a positional write-back+ would scramble the arguments rather than mask them.+ """+ if masked_texts is not None and len(masked_texts) != len(argument_leaves):+ raise _blocked(+ f"guardrail returned {len(masked_texts)} texts for {len(argument_leaves)} MCP tool call argument strings, "+ "so the redaction cannot be mapped back to the arguments"+ )+ return {path: masked for (path, original), masked in zip(argument_leaves, masked_texts or ()) if masked != original}+++def _conflicting_rewrite_paths(+ scanned_leaves: tuple[tuple[JSONLeafPath, str], ...],+ current_leaves: tuple[tuple[JSONLeafPath, str], ...],+ replacements: Mapping[JSONLeafPath, str],+) -> tuple[JSONLeafPath, ...]:+ """Paths another guardrail already rewrote differently from what this one wants.++ Guardrails opted into ``run_in_parallel`` all scan the same payload snapshot, so+ each one returns a full replacement string derived from the *original* leaf. Two+ of them rewriting one leaf to different values cannot be merged: writing either+ result discards the other guardrail's redaction. A leaf still holding the text+ this guardrail was handed, or already holding this guardrail's own replacement,+ is safe to write; the latter is how a guardrail that masks the arguments itself+ as well as through ``texts`` gets there first. Anything else fails closed,+ including a payload reshaped so the leaves no longer line up, because the+ write-back is positional and would land a redaction on the wrong value.+ """+ if tuple(path for path, _ in scanned_leaves) != tuple(path for path, _ in current_leaves):+ return tuple(replacements)+ return tuple(+ path+ for (path, scanned), (_, current) in zip(scanned_leaves, current_leaves)+ if path in replacements and current not in (scanned, replacements[path])+ )+++def _conflicting_rewrite(paths: tuple[JSONLeafPath, ...]) -> HTTPException:+ return _blocked(+ "two guardrails running concurrently rewrote the same MCP tool call "+ f"argument{'s' if len(paths) > 1 else ''} "+ f"({', '.join('.'.join(str(part) for part in path) for path in paths)}); "+ "their redactions cannot be merged. Remove run_in_parallel from one of them so they "+ "run in sequence."+ )++class MCPGuardrailTranslationHandler(BaseTranslation):"""Guardrail translation handler for MCP tool calls (passes a single tool_call to guardrail)."""@@ -52,10 +123,8 @@ class MCPGuardrailTranslationHandler(BaseTranslation):litellm_logging_obj: "LiteLLMLoggingObj | None" = None,) -> dict[str, Any]:mcp_tool_name: Final = data.get("mcp_tool_name") or data.get("name")- mcp_arguments = data.get("mcp_arguments") or data.get("arguments")+ mcp_arguments: Final[object] = data.get("mcp_arguments") or data.get("arguments")mcp_tool_description: Final = data.get("mcp_tool_description") or data.get("description")- if mcp_arguments is None or not isinstance(mcp_arguments, dict):- mcp_arguments = {}if not mcp_tool_name:verbose_proxy_logger.debug("MCP Guardrail: mcp_tool_name missing")@@ -84,16 +153,37 @@ class MCPGuardrailTranslationHandler(BaseTranslation):strict=fn.get("strict", False) or False, # Default to False if None),}+ argument_leaves: Final = json_string_leaves(mcp_arguments)+ if argument_leaves is None:+ raise _too_deeply_nested()inputs: Final[GenericGuardrailAPIInputs] = GenericGuardrailAPIInputs(tools=[tool_def],+ texts=[text for _, text in argument_leaves],)- await guardrail_to_apply.apply_guardrail(+ guarded: Final = await guardrail_to_apply.apply_guardrail(inputs=inputs,request_data=data,input_type="request",logging_obj=litellm_logging_obj,)+ replacements: Final = _argument_replacements(+ argument_leaves=argument_leaves,+ masked_texts=guarded.get("texts") if guarded else None,+ )+ if not replacements:+ return data++ current_arguments: Final[object] = data.get("mcp_arguments") or data.get("arguments")+ current_leaves: Final = json_string_leaves(current_arguments)+ if current_leaves is None:+ raise _too_deeply_nested()+ conflicting: Final = _conflicting_rewrite_paths(argument_leaves, current_leaves, replacements)+ if conflicting:+ raise _conflicting_rewrite(conflicting)+ masked_arguments: Final = with_json_string_leaves(current_arguments, replacements)+ data["mcp_arguments"] = masked_arguments # rebind-ok: preserve the mask for the outbound MCP call+ data["modified_arguments"] = masked_arguments # rebind-ok: expose the applied mask to the callerreturn dataasync def process_output_response(@@ -131,14 +221,8 @@ class MCPGuardrailTranslationHandler(BaseTranslation):structured_leaves: Final = json_string_leaves(structured) if structured is not None else ()structured_labels: Final = json_unrewritable_labels(structured) if structured is not None else ()if structured_leaves is None or structured_labels is None:- raise HTTPException(- status_code=400,- detail={- "error": (- "Content blocked: MCP tool result structuredContent is nested too deeply to be scanned "- "by the configured guardrail"- )- },+ raise _blocked(+ "MCP tool result structuredContent is nested too deeply to be scanned by the configured guardrail")if not text_blocks and not structured_leaves and not structured_labels:@@ -158,12 +242,10 @@ class MCPGuardrailTranslationHandler(BaseTranslation):if masked_texts is None:return responseif len(masked_texts) != len(originals):- verbose_proxy_logger.warning(- "MCP Guardrail: guardrail returned %d texts for %d tool result texts; leaving the result unmasked",- len(masked_texts),- len(originals),+ raise _blocked(+ f"guardrail returned {len(masked_texts)} texts for {len(originals)} MCP tool result texts, "+ "so the redaction cannot be mapped back to the result")- return responsesplit: Final = len(text_blocks)if content is not None:@@ -173,15 +255,10 @@ class MCPGuardrailTranslationHandler(BaseTranslation):label_start: Final = split + len(structured_leaves)if any(masked != original for original, masked in zip(structured_labels, masked_texts[label_start:])):- raise HTTPException(- status_code=400,- detail={- "error": (- "Content blocked: MCP tool result matched a masking rule on a non-rewritable field "- "(a structuredContent key or numeric value), which cannot be redacted without changing "- "the payload contract"- )- },+ raise _blocked(+ "MCP tool result matched a masking rule on a non-rewritable field "+ "(a structuredContent key or numeric value), which cannot be redacted without changing "+ "the payload contract")structured_replacements: Final = {diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/guardrail_translation/test_mcp_guardrail_handler.py b/tests/test_litellm/proxy/_experimental/mcp_server/guardrail_translation/test_mcp_guardrail_handler.pyindex 2e286a237c4..28959054195 100644--- a/tests/test_litellm/proxy/_experimental/mcp_server/guardrail_translation/test_mcp_guardrail_handler.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/guardrail_translation/test_mcp_guardrail_handler.py@@ -1,13 +1,22 @@"""Tests for the MCP guardrail translation handler."""+import asyncio+import pytest+from fastapi import HTTPExceptionfrom mcp.types import CallToolResult, ImageContent, TextContent+import litellm+import litellm.llms as litellm_llms+from litellm.caching.caching import DualCachefrom litellm.exceptions import BlockedPiiEntityErrorfrom litellm.integrations.custom_guardrail import CustomGuardrailfrom litellm.proxy._experimental.mcp_server.guardrail_translation.handler import (MCPGuardrailTranslationHandler,)+from litellm.proxy._experimental.mcp_server.utils import MAX_STRUCTURED_CONTENT_SCAN_DEPTH+from litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy.utils import ProxyLoggingfrom litellm.types.utils import GenericGuardrailAPIInputs@@ -24,12 +33,11 @@ class MockGuardrail(CustomGuardrail):self.call_count += 1self.last_inputs = inputsself.last_request_data = request_data- return None # Guardrail doesn't modify for MCP tools@pytest.mark.asyncioasync def test_process_input_messages_updates_content():- """Handler should pass tool definition to guardrail when mcp_tool_name is present."""+ """Handler should pass the tool definition and the argument strings to the guardrail."""handler = MCPGuardrailTranslationHandler()guardrail = MockGuardrail()@@ -45,7 +53,7 @@ async def test_process_input_messages_updates_content():assert result == data# Guardrail was calledassert guardrail.call_count == 1- # Guardrail received tools (not texts) with tool definition+ # Guardrail received tools with the tool definitionassert guardrail.last_inputs is not Nonetools = guardrail.last_inputs.get("tools", [])assert len(tools) == 1@@ -85,6 +93,412 @@ async def test_process_input_messages_handles_minimal_data():assert tools[0]["function"]["name"] == "simple_tool"+class ArgumentMaskingGuardrail(CustomGuardrail):+ """Unified guardrail that rewrites every text it is handed, like presidio does."""++ def __init__(+ self,+ secret: str = "[email protected]",+ replacement: str = "<EMAIL_ADDRESS>",+ texts_override: list[str] | None = None,+ **kwargs,+ ):+ kwargs.setdefault("guardrail_name", "argument-masking-mcp-guardrail")+ super().__init__(**kwargs)+ self.secret = secret+ self.replacement = replacement+ self.texts_override = texts_override+ self.seen_texts: list[str] | None = None++ def _mask(self, text: str) -> str:+ return text.replace(self.secret, self.replacement)++ async def apply_guardrail(self, inputs, request_data, input_type, **kwargs):+ self.seen_texts = list(inputs.get("texts") or [])+ if self.texts_override is not None:+ inputs["texts"] = self.texts_override+ else:+ inputs["texts"] = [self._mask(text) for text in self.seen_texts]+ return inputs+++def restore_callbacks(monkeypatch):+ """Restore the process-wide state driving pre_call_hook through unified_guardrail.++ litellm.llms memoizes the guardrail translation mappings in a module global, and+ ProxyLogging caches callback capabilities keyed on id()s of litellm.callbacks,+ so leaving either populated leaks into unrelated tests in the same worker.+ """+ monkeypatch.setattr(litellm, "callbacks", litellm.callbacks)+ monkeypatch.setattr(+ litellm_llms,+ "endpoint_guardrail_translation_mappings",+ litellm_llms.endpoint_guardrail_translation_mappings,+ )+ yield+ ProxyLogging._callback_capabilities_cache.clear()+++async def test_argument_strings_are_handed_to_the_guardrail():+ """A guardrail must see the argument values, not just the tool definition.++ Without this the guardrail is handed a name and an empty schema, so no+ sensitive-data detection can ever fire on an MCP tool call.+ """+ handler = MCPGuardrailTranslationHandler()+ guardrail = MockGuardrail()++ data = {+ "mcp_tool_name": "search",+ "mcp_arguments": {"query": "contact [email protected] about the invoice"},+ }++ await handler.process_input_messages(data, guardrail)++ assert guardrail.last_inputs is not None+ assert guardrail.last_inputs.get("texts") == ["contact [email protected] about the invoice"]+++async def test_masked_arguments_are_written_back_for_the_call_path():+ """A mask only takes effect once it lands in modified_arguments."""+ handler = MCPGuardrailTranslationHandler()+ guardrail = ArgumentMaskingGuardrail()++ data = {+ "mcp_tool_name": "search",+ "mcp_arguments": {"query": "contact [email protected] about the invoice"},+ }++ result = await handler.process_input_messages(data, guardrail)++ masked = {"query": "contact <EMAIL_ADDRESS> about the invoice"}+ assert result["modified_arguments"] == masked+ assert result["mcp_arguments"] == masked+++async def test_nested_arguments_keep_their_shape_when_masked():+ """Masking rewrites string leaves in place and preserves non-string values."""+ handler = MCPGuardrailTranslationHandler()+ guardrail = ArgumentMaskingGuardrail()++ arguments = {+ "recipients": ["[email protected]", "[email protected]"],+ "envelope": {"reply_to": "[email protected]", "retries": 3, "urgent": True, "cc": None},+ "count": 2,+ }+ data = {"mcp_tool_name": "send_email", "mcp_arguments": arguments}++ result = await handler.process_input_messages(data, guardrail)++ assert guardrail.seen_texts == [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ]+ assert result["modified_arguments"] == {+ "recipients": ["<EMAIL_ADDRESS>", "[email protected]"],+ "envelope": {"reply_to": "<EMAIL_ADDRESS>", "retries": 3, "urgent": True, "cc": None},+ "count": 2,+ }+++async def test_clean_arguments_are_not_overridden():+ """A guardrail that changes nothing must not set modified_arguments."""+ handler = MCPGuardrailTranslationHandler()+ guardrail = ArgumentMaskingGuardrail()++ data = {"mcp_tool_name": "search", "mcp_arguments": {"query": "quarterly revenue"}}++ result = await handler.process_input_messages(data, guardrail)++ assert "modified_arguments" not in result+ assert result["mcp_arguments"] == {"query": "quarterly revenue"}+++async def test_guardrail_returning_wrong_text_count_blocks_the_call():+ """Write-back is positional, so a length mismatch must block the call."""+ handler = MCPGuardrailTranslationHandler()+ guardrail = ArgumentMaskingGuardrail(texts_override=["only", "two", "texts"])++ arguments = {"query": "contact [email protected] about the invoice"}+ data = {"mcp_tool_name": "search", "mcp_arguments": arguments}++ with pytest.raises(HTTPException) as exc_info:+ await handler.process_input_messages(data, guardrail)++ assert exc_info.value.status_code == 400+ assert "modified_arguments" not in data+++async def test_deeply_nested_arguments_are_blocked_rather_than_skipped():+ """Arguments too deep to walk must block instead of passing unscanned."""+ handler = MCPGuardrailTranslationHandler()+ guardrail = ArgumentMaskingGuardrail()++ nested: dict = {"leaf": "[email protected]"}+ for _ in range(MAX_STRUCTURED_CONTENT_SCAN_DEPTH + 1):+ nested = {"next": nested}++ data = {"mcp_tool_name": "search", "mcp_arguments": nested}++ with pytest.raises(HTTPException) as exc_info:+ await handler.process_input_messages(data, guardrail)++ assert exc_info.value.status_code == 400+++class SelfWritingMaskingGuardrail(ArgumentMaskingGuardrail):+ """Masks through ``texts`` and writes the masked arguments itself.++ The shape the bundled content filter guardrail already has: it rewrites+ ``request_data["mcp_arguments"]`` from inside ``apply_guardrail`` as well as+ returning masked texts.+ """++ async def apply_guardrail(self, inputs, request_data, input_type, **kwargs):+ returned = await super().apply_guardrail(inputs, request_data, input_type, **kwargs)+ arguments = request_data.get("mcp_arguments") or {}+ masked = {key: self._mask(value) if isinstance(value, str) else value for key, value in arguments.items()}+ request_data["mcp_arguments"] = masked+ request_data["modified_arguments"] = masked+ return returned+++async def test_guardrail_that_masks_the_arguments_itself_is_not_treated_as_a_conflict():+ """Converging on the same replacement is not an unmergeable rewrite.++ A guardrail that both returns masked texts and rewrites the arguments in+ request_data must still mask, not be rejected as if a second guardrail had+ clobbered the leaf.+ """+ handler = MCPGuardrailTranslationHandler()+ guardrail = SelfWritingMaskingGuardrail()++ data = {+ "mcp_tool_name": "search",+ "mcp_arguments": {"query": "contact [email protected] about the invoice"},+ }++ result = await handler.process_input_messages(data, guardrail)++ assert result["modified_arguments"] == {"query": "contact <EMAIL_ADDRESS> about the invoice"}+++class ReshapingGuardrail(ArgumentMaskingGuardrail):+ """Masks through ``texts`` while moving the secret to a different path."""++ def __init__(self, reshaped: dict, **kwargs):+ super().__init__(**kwargs)+ self.reshaped = reshaped++ async def apply_guardrail(self, inputs, request_data, input_type, **kwargs):+ returned = await super().apply_guardrail(inputs, request_data, input_type, **kwargs)+ request_data["mcp_arguments"] = self.reshaped+ return returned+++async def test_arguments_reshaped_under_the_guardrail_fail_closed():+ """A payload that no longer lines up leaf for leaf must block, not be written blind.++ Write-back pairs masked texts to leaves positionally, so a tree another guardrail+ reshaped would take the redaction on the wrong value.+ """+ handler = MCPGuardrailTranslationHandler()+ guardrail = ReshapingGuardrail({"query": "contact [email protected]", "note": "added"})++ data = {+ "mcp_tool_name": "search",+ "mcp_arguments": {"query": "contact [email protected] about the invoice"},+ }++ with pytest.raises(HTTPException) as exc_info:+ await handler.process_input_messages(data, guardrail)++ assert exc_info.value.status_code == 400+++async def test_arguments_shortened_under_the_guardrail_fail_closed():+ handler = MCPGuardrailTranslationHandler()+ guardrail = ReshapingGuardrail({"padding": "[email protected]"})++ data = {+ "mcp_tool_name": "search",+ "mcp_arguments": {"padding": "x", "secret": "[email protected]"},+ }++ with pytest.raises(HTTPException) as exc_info:+ await handler.process_input_messages(data, guardrail)++ assert exc_info.value.status_code == 400+ assert "[email protected]" not in str(data.get("modified_arguments"))+++async def test_a_renamed_argument_key_blocks_rather_than_dropping_the_mask():+ """The leak this closes: same text, new path, so the write-back would find nothing.++ Matching purely on position would see an unchanged value and write the mask to a+ path that no longer exists, shipping the secret while reporting a clean scan.+ """+ handler = MCPGuardrailTranslationHandler()+ guardrail = ReshapingGuardrail({"renamed": "[email protected]", "other": "kept"})++ data = {+ "mcp_tool_name": "search",+ "mcp_arguments": {"query": "[email protected]", "other": "kept"},+ }++ with pytest.raises(HTTPException) as exc_info:+ await handler.process_input_messages(data, guardrail)++ assert exc_info.value.status_code == 400+ assert "[email protected]" not in str(data.get("modified_arguments"))++[email protected]("run_in_parallel", [False, True])+async def test_masked_arguments_reach_the_outbound_mcp_call(restore_callbacks, monkeypatch, run_in_parallel):+ """End to end over the real MCP pre-call path, not just the handler.++ Drives the same sequence mcp_server_manager.call_tool uses:+ synthetic payload -> pre_call_hook -> arguments sent upstream.++ Covers run_in_parallel both ways: that path shares one payload snapshot and+ discards whatever a guardrail returns, so the mask has to land on the caller's+ dict rather than on a copy of it.+ """+ guardrail = ArgumentMaskingGuardrail(+ event_hook="pre_mcp_call",+ default_on=True,+ run_in_parallel=run_in_parallel,+ )+ monkeypatch.setattr(litellm, "callbacks", [guardrail])++ proxy_logging_obj = ProxyLogging(user_api_key_cache=DualCache())+ arguments = {"query": "contact [email protected] about the invoice"}+ pre_hook_kwargs = {+ "name": "search",+ "arguments": arguments,+ "server_name": "test-server",+ "user_api_key_auth": UserAPIKeyAuth(api_key="sk-test", user_id="test-user"),+ }++ request_obj = proxy_logging_obj._create_mcp_request_object_from_kwargs(pre_hook_kwargs)+ synthetic_data = proxy_logging_obj._convert_mcp_to_llm_format(request_obj, pre_hook_kwargs)++ modified_data = await proxy_logging_obj.pre_call_hook(+ user_api_key_dict=pre_hook_kwargs["user_api_key_auth"],+ data=synthetic_data,+ call_type="call_mcp_tool",+ )+ modified_kwargs = proxy_logging_obj._convert_mcp_hook_response_to_kwargs(modified_data, pre_hook_kwargs)++ assert modified_kwargs["arguments"] == {"query": "contact <EMAIL_ADDRESS> about the invoice"}+++class SlowSubstitutionGuardrail(CustomGuardrail):+ """Rewrites one substring, after a delay, so two instances genuinely interleave."""++ def __init__(self, needle: str, replacement: str, delay: float, **kwargs):+ super().__init__(**kwargs)+ self.needle = needle+ self.replacement = replacement+ self.delay = delay++ async def apply_guardrail(self, inputs, request_data, input_type, **kwargs):+ await asyncio.sleep(self.delay)+ inputs["texts"] = [text.replace(self.needle, self.replacement) for text in (inputs.get("texts") or [])]+ return inputs+++def _two_interleaving_maskers(run_in_parallel: bool):+ return [+ SlowSubstitutionGuardrail(+ "[email protected]",+ "<EMAIL_ADDRESS>",+ 0.02,+ guardrail_name="mask-email",+ event_hook="pre_mcp_call",+ default_on=True,+ run_in_parallel=run_in_parallel,+ ),+ SlowSubstitutionGuardrail(+ "415-555-0132",+ "<PHONE_NUMBER>",+ 0.04,+ guardrail_name="mask-phone",+ event_hook="pre_mcp_call",+ default_on=True,+ run_in_parallel=run_in_parallel,+ ),+ ]+++async def _arguments_sent_upstream(arguments: dict):+ proxy_logging_obj = ProxyLogging(user_api_key_cache=DualCache())+ pre_hook_kwargs = {+ "name": "search",+ "arguments": arguments,+ "server_name": "test-server",+ "user_api_key_auth": UserAPIKeyAuth(api_key="sk-test", user_id="test-user"),+ }+ request_obj = proxy_logging_obj._create_mcp_request_object_from_kwargs(pre_hook_kwargs)+ modified_data = await proxy_logging_obj.pre_call_hook(+ user_api_key_dict=pre_hook_kwargs["user_api_key_auth"],+ data=proxy_logging_obj._convert_mcp_to_llm_format(request_obj, pre_hook_kwargs),+ call_type="call_mcp_tool",+ )+ return proxy_logging_obj._convert_mcp_hook_response_to_kwargs(modified_data, pre_hook_kwargs)["arguments"]+++async def test_two_sequential_guardrails_both_masks_survive(restore_callbacks, monkeypatch):+ """The recommended config: each guardrail sees the previous one's output."""+ monkeypatch.setattr(litellm, "callbacks", _two_interleaving_maskers(run_in_parallel=False))++ sent = await _arguments_sent_upstream({"note": "mail [email protected] or call 415-555-0132"})++ assert sent == {"note": "mail <EMAIL_ADDRESS> or call <PHONE_NUMBER>"}+++async def test_two_parallel_guardrails_on_separate_arguments_both_masks_survive(restore_callbacks, monkeypatch):+ """Concurrent rewrites of different leaves compose; neither is lost."""+ monkeypatch.setattr(litellm, "callbacks", _two_interleaving_maskers(run_in_parallel=True))++ sent = await _arguments_sent_upstream({"email": "[email protected]", "phone": "415-555-0132"})++ assert sent == {"email": "<EMAIL_ADDRESS>", "phone": "<PHONE_NUMBER>"}+++async def test_two_parallel_guardrails_on_one_argument_block_instead_of_losing_a_mask(restore_callbacks, monkeypatch):+ """Unmergeable concurrent rewrites must fail closed, not ship one redaction.++ Both guardrails derive a full replacement string from the same snapshot, so+ writing either result would silently discard the other's redaction and leak+ the value it was configured to mask.+ """+ monkeypatch.setattr(litellm, "callbacks", _two_interleaving_maskers(run_in_parallel=True))+ original = "mail [email protected] or call 415-555-0132"++ with pytest.raises(HTTPException) as exc_info:+ await _arguments_sent_upstream({"note": original})++ assert exc_info.value.status_code == 400+ assert "note" in str(exc_info.value.detail)++class MaskingGuardrail(CustomGuardrail):"""Guardrail that rewrites every scanned text, recording what it saw."""@@ -190,8 +604,8 @@ async def test_process_output_response_handles_result_without_content():@pytest.mark.asyncio-async def test_process_output_response_leaves_result_unmasked_on_text_count_mismatch():- """A guardrail returning the wrong number of texts must not shuffle content."""+async def test_process_output_response_blocks_on_text_count_mismatch():+ """A guardrail returning the wrong number of texts must block the result."""handler = MCPGuardrailTranslationHandler()guardrail = MaskingGuardrail(masked_texts=["<EMAIL_ADDRESS>"])result = CallToolResult(@@ -202,9 +616,10 @@ async def test_process_output_response_leaves_result_unmasked_on_text_count_mismisError=False,)- returned = await handler.process_output_response(response=result, guardrail_to_apply=guardrail)+ with pytest.raises(HTTPException) as exc_info:+ await handler.process_output_response(response=result, guardrail_to_apply=guardrail)- assert [item.text for item in returned.content] == ["[email protected]", "415-555-0132"]+ assert exc_info.value.status_code == 400class SubstitutingGuardrail(CustomGuardrail):diff --git a/type-discipline-budget.json b/type-discipline-budget.jsonindex e35e470c979..e7186dfe186 100644--- a/type-discipline-budget.json+++ b/type-discipline-budget.json@@ -27,7 +27,7 @@"limit": 0},"LIT010": {- "limit": 16430+ "limit": 16426},"LIT011": {"limit": 5506