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(anthropic): close hybrid tool-name allowlist gap and keep native tools through guardrails

mateo-berri6d7fafa34705
diff --git a/litellm/llms/anthropic/chat/guardrail_translation/handler.py b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
index 2afea1444f9..b9ca18c7843 100644
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@ -24,10 +24,12 @@ from litellm._logging import verbose_proxy_logger
from litellm.llms.anthropic.chat.transformation import AnthropicConfig
from litellm.llms.anthropic.experimental_pass_through.adapters.transformation import (
LiteLLMAnthropicMessagesAdapter,
+ is_provider_native_tool_dict,
)
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
from litellm.llms.base_llm.guardrail_translation.utils import (
anthropic_tool_name,
+ anthropic_tool_names,
effective_scan_only_tool_results_for_guardrail,
effective_skip_system_message_for_guardrail,
effective_skip_tool_message_for_guardrail,
@@ -360,7 +362,13 @@ class AnthropicMessagesHandler(BaseTranslation):
structured_messages: Final = [full_structured_messages[index] for index in scoped_message_indices]
tools_to_check: Final[list[ChatCompletionToolParam]] = (
- [] if scan_only_tool_results else chat_completion_compatible_request.get("tools", [])
+ []
+ if scan_only_tool_results
+ else [
+ tool
+ for tool in chat_completion_compatible_request.get("tools", [])
+ if not is_provider_native_tool_dict(tool)
+ ]
)
# Step 1: Extract all text content and images
@@ -419,7 +427,10 @@ class AnthropicMessagesHandler(BaseTranslation):
tool_name=anthropic_tool_name,
)
if scan_only_tool_results
- else anthropic_tools
+ else [
+ *(tool for tool in data.get("tools") or [] if is_provider_native_tool_dict(tool)),
+ *anthropic_tools,
+ ]
)
guardrailed_structured_messages: Final = guardrailed_inputs.get("structured_messages")
@@ -677,9 +688,9 @@ class AnthropicMessagesHandler(BaseTranslation):
)
def extract_request_tool_names(self, data: dict) -> list[str]:
- """Extract tool names from Anthropic messages request (tools[].name, or
- tools[].function.name for OpenAI-format tools the bridge forwards verbatim)."""
- return [name for tool in data.get("tools") or [] if (name := anthropic_tool_name(tool))]
+ """Extract every tool name in an Anthropic messages request: tools[].name, plus
+ tools[].function.name for OpenAI-format tools the bridge forwards verbatim."""
+ return [name for tool in data.get("tools") or [] for name in anthropic_tool_names(tool)]
@classmethod
def _extract_input_text_and_images(
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
index ca90df2ff75..c958f9f242f 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
@@ -27,7 +27,7 @@ def _is_openai_function_tool(tool: Mapping[str, object]) -> bool:
return tool.get("type") == "function" and "function" in tool
-def _is_provider_native_tool_dict(tool: Mapping[str, object]) -> bool:
+def is_provider_native_tool_dict(tool: Mapping[str, object]) -> bool:
if len(tool) != 1:
return False
key, value = next(iter(tool.items()))
@@ -786,7 +786,7 @@ class LiteLLMAnthropicMessagesAdapter:
new_tools.append(tool)
continue
- if _is_openai_function_tool(tool) or _is_provider_native_tool_dict(tool):
+ if _is_openai_function_tool(tool) or is_provider_native_tool_dict(tool):
new_tools.append(cast(ChatCompletionToolParam, tool)) # cast-ok: passed through verbatim to provider
continue
diff --git a/litellm/llms/base_llm/guardrail_translation/utils.py b/litellm/llms/base_llm/guardrail_translation/utils.py
index 4494f8451f4..aefe3861e3c 100644
--- a/litellm/llms/base_llm/guardrail_translation/utils.py
+++ b/litellm/llms/base_llm/guardrail_translation/utils.py
@@ -209,17 +209,20 @@ def openai_tool_name(tool: object) -> str | None:
return flat_name if isinstance(flat_name, str) else None
-def anthropic_tool_name(tool: object) -> str | None:
- """Anthropic tools carry a flat ``name``; an OpenAI-format function tool, which the
- non-Anthropic bridge forwards verbatim, carries it under ``function.name`` instead."""
+def anthropic_tool_names(tool: object) -> tuple[str, ...]:
+ """Every name a /v1/messages tool dict can act under: the flat Anthropic ``name`` plus
+ ``function.name`` for OpenAI-format tools the bridge forwards verbatim. Allowlist checks
+ must see both, or a decoy flat name could smuggle a disallowed ``function.name`` through."""
if not isinstance(tool, dict):
- return None
- flat_name: Final = tool.get("name")
- if isinstance(flat_name, str):
- return flat_name
+ return ()
function: Final = tool.get("function") if tool.get("type") == "function" else None
function_name: Final = function.get("name") if isinstance(function, dict) else None
- return function_name if isinstance(function_name, str) else None
+ return tuple(name for name in (tool.get("name"), function_name) if isinstance(name, str) and name)
+
+
+def anthropic_tool_name(tool: object) -> str | None:
+ names: Final = anthropic_tool_names(tool)
+ return names[0] if names else None
def merge_returned_tools_into_request_tools(
diff --git a/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py b/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
index 2b392456763..46bdd855a28 100644
--- a/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
+++ b/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
@@ -290,6 +290,24 @@ class TestAnthropicMessagesHandlerInputProcessing:
assert data.get("litellm_metadata", {}).get("guardrails")
assert guardrail.dynamic_params == {"policy_id": "policy-123"}
+ @pytest.mark.asyncio
+ async def test_provider_native_tools_survive_guardrail_round_trip(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockPassThroughGuardrail(guardrail_name="test")
+ data = {
+ "model": "gemini-2.5-flash",
+ "messages": [{"role": "user", "content": "coffee shops near Union Square?"}],
+ "tools": [
+ {"googleMaps": {"enable_widget": True}},
+ {"name": "get_weather", "input_schema": {"type": "object", "properties": {}}},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert {"googleMaps": {"enable_widget": True}} in data["tools"]
+ assert [tool["name"] for tool in data["tools"] if "name" in tool] == ["get_weather"]
+
@pytest.mark.asyncio
async def test_midturn_system_correction_is_guardrailed_when_top_level_system_is_skipped(
self,
diff --git a/tests/test_litellm/proxy/test_tools_allowlist_enforcement.py b/tests/test_litellm/proxy/test_tools_allowlist_enforcement.py
index c881effada5..3e9c7c14b95 100644
--- a/tests/test_litellm/proxy/test_tools_allowlist_enforcement.py
+++ b/tests/test_litellm/proxy/test_tools_allowlist_enforcement.py
@@ -106,6 +106,19 @@ class TestExtractRequestToolNames:
"run_sql",
]
+ def test_anthropic_hybrid_tool_yields_every_name(self):
+ data = {
+ "tools": [
+ {"type": "function", "name": "decoy", "function": {"name": "blocked_fn"}},
+ {"type": "function", "name": "", "function": {"name": "hidden_fn"}},
+ ]
+ }
+ assert extract_request_tool_names("/v1/messages", data) == [
+ "decoy",
+ "blocked_fn",
+ "hidden_fn",
+ ]
+
def test_generate_content_tools(self):
data = {
"tools": [
@@ -186,6 +199,20 @@ class TestCheckToolsAllowlist:
assert exc_info.value.type == ProxyErrorTypes.tool_access_denied
assert "get_weather" in str(exc_info.value.message)
+ @pytest.mark.asyncio
+ async def test_hybrid_tool_with_decoy_name_raises_on_messages_route(self):
+ token = _token(metadata={"allowed_tools": ["decoy"]})
+ body = {"tools": [{"type": "function", "name": "decoy", "function": {"name": "run_sql"}}]}
+ with pytest.raises(ProxyException) as exc_info:
+ await check_tools_allowlist(
+ request_body=body,
+ valid_token=token,
+ team_object=None,
+ route="/v1/messages",
+ )
+ assert exc_info.value.type == ProxyErrorTypes.tool_access_denied
+ assert "run_sql" in str(exc_info.value.message)
+
@pytest.mark.asyncio
async def test_disallowed_custom_tool_raises_on_responses_route(self):
token = _token(metadata={"allowed_tools": ["other_tool"]})