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: tool permission argument check (#16982)

YutaSaito06f2ecef42b8
diff --git a/docs/my-website/docs/proxy/guardrails/tool_permission.md b/docs/my-website/docs/proxy/guardrails/tool_permission.md
index 22ecdd2251e..2e0b72a8a8a 100644
--- a/docs/my-website/docs/proxy/guardrails/tool_permission.md
+++ b/docs/my-website/docs/proxy/guardrails/tool_permission.md
@@ -29,6 +29,13 @@ guardrails:
- id: "deny_read_commands"
tool_name: "Read"
decision: "Deny"
+ - id: "mail-domain"
+ tool_name: "send_email"
+ decision: "allow"
+ allowed_param_patterns:
+ "to[]": "^.+@berri\\.ai$"
+ "cc[]": "^.+@berri\\.ai$"
+ "subject": "^.{1,120}$"
default_action: "deny" # Fallback when no rule matches: "allow" or "deny"
on_disallowed_action: "block" # How to handle disallowed tools: "block" or "rewrite"
```
@@ -39,6 +46,8 @@ guardrails:
- id: "unique_rule_id" # Unique identifier for the rule
tool_name: "pattern" # Tool name or pattern to match
decision: "allow" # "allow" or "deny"
+ allowed_param_patterns: # Optional - regex map for argument paths (dot + [] notation)
+ "path.to[].field": "^regex$"
```
#### Supported values for `mode`
@@ -188,3 +197,27 @@ curl -X POST "http://localhost:4000/v1/chat/completions" \
</TabItem>
</Tabs>
+
+### Constrain Tool Arguments
+
+Sometimes you want to allow a tool but still restrict **how** it can be used. Add `allowed_param_patterns` to a rule to enforce regex patterns on specific argument paths (dot notation with `[]` for arrays).
+
+```yaml title="Only allow mail_mcp to mail @berri.ai addresses"
+guardrails:
+ - guardrail_name: "tool-permission-mail"
+ litellm_params:
+ guardrail: tool_permission
+ mode: "post_call"
+ rules:
+ - id: "mail-domain"
+ tool_name: "send_email"
+ decision: "allow"
+ allowed_param_patterns:
+ "to[]": "^.+@berri\\.ai$"
+ "cc[]": "^.+@berri\\.ai$"
+ "subject": "^.{1,120}$"
+ default_action: "deny"
+ on_disallowed_action: "block"
+```
+
+In this example the LLM can still call `send_email`, but the guardrail blocks the invocation (or rewrites it, depending on `on_disallowed_action`) if it tries to email anyone outside `@berri.ai` or produce a subject that fails the regex. Use this pattern for any tool where argument values matter—mail senders, escalation workflows, ticket creation, etc.
diff --git a/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py b/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py
index 19060fa9d6d..95d8f894dc2 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py
@@ -1,3 +1,4 @@
+import json
import re
from typing import Any, AsyncGenerator, Dict, List, Literal, Optional, Union
@@ -59,9 +60,24 @@ class ToolPermissionGuardrail(CustomGuardrail):
super().__init__(**kwargs)
self.rules: List[ToolPermissionRule] = []
+ self._compiled_rule_patterns: Dict[str, Dict[str, re.Pattern]] = {}
if rules:
for rule_dict in rules:
- self.rules.append(ToolPermissionRule(**rule_dict))
+ rule = ToolPermissionRule(**rule_dict)
+ self.rules.append(rule)
+
+ if rule.allowed_param_patterns:
+ compiled_patterns: Dict[str, re.Pattern] = {}
+ for path, pattern in rule.allowed_param_patterns.items():
+ try:
+ compiled_patterns[path] = re.compile(pattern)
+ except re.error as exc:
+ raise ValueError(
+ f"Invalid regex in allowed_param_patterns for rule '{rule.id}': {exc}"
+ ) from exc
+
+ if compiled_patterns:
+ self._compiled_rule_patterns[rule.id] = compiled_patterns
self.default_action = default_action
self.on_disallowed_action = on_disallowed_action
@@ -144,6 +160,131 @@ class ToolPermissionGuardrail(CustomGuardrail):
verbose_proxy_logger.debug(message)
return is_allowed, None, message
+ def _parse_tool_call_arguments(
+ self, tool_call: ChatCompletionMessageToolCall
+ ) -> Dict[str, Any]:
+ arguments = getattr(tool_call.function, "arguments", None)
+ if not arguments:
+ return {}
+
+ parsed_arguments: Any = {}
+ try:
+ if isinstance(arguments, str):
+ parsed_arguments = json.loads(arguments)
+ elif isinstance(arguments, dict):
+ parsed_arguments = arguments
+ except json.JSONDecodeError as exc:
+ verbose_proxy_logger.warning(
+ "Tool Permission Guardrail: Failed to decode arguments for tool %s: %s",
+ tool_call.function.name,
+ exc,
+ )
+ return {}
+
+ if isinstance(parsed_arguments, dict):
+ return parsed_arguments
+
+ verbose_proxy_logger.debug(
+ "Tool Permission Guardrail: Ignoring non-dict arguments for tool %s",
+ tool_call.function.name,
+ )
+ return {}
+
+ def _collect_argument_paths(
+ self, value: Any, current_path: str, collected: Dict[str, List[Any]]
+ ) -> None:
+ if isinstance(value, dict):
+ for key, sub_value in value.items():
+ next_path = f"{current_path}.{key}" if current_path else key
+ self._collect_argument_paths(sub_value, next_path, collected)
+ elif isinstance(value, list):
+ list_path = f"{current_path}[]" if current_path else "[]"
+ for item in value:
+ self._collect_argument_paths(item, list_path, collected)
+ else:
+ if not current_path:
+ return
+ collected.setdefault(current_path, []).append(value)
+
+ def _patterns_match_for_rule(
+ self,
+ *,
+ arguments: Dict[str, Any],
+ rule: ToolPermissionRule,
+ tool_name: str,
+ ) -> tuple[bool, Optional[str]]:
+ compiled_patterns = self._compiled_rule_patterns.get(rule.id)
+ if not compiled_patterns:
+ return True, None
+
+ path_value_map: Dict[str, List[Any]] = {}
+ self._collect_argument_paths(arguments, "", path_value_map)
+
+ for path, compiled_pattern in compiled_patterns.items():
+ values = path_value_map.get(path)
+ if not values:
+ return (
+ False,
+ f"Missing value for path '{path}' required by rule '{rule.id}'",
+ )
+ for raw_value in values:
+ if not compiled_pattern.fullmatch(str(raw_value)):
+ return (
+ False,
+ f"Value '{raw_value}' for path '{path}' does not match allowed pattern"
+ f" '{compiled_pattern.pattern}' for tool '{tool_name}'",
+ )
+
+ return True, None
+
+ def _get_permission_for_tool_call(
+ self, tool_call: ChatCompletionMessageToolCall
+ ) -> tuple[bool, Optional[str], Optional[str]]:
+ tool_name = tool_call.function.name if tool_call.function else None
+ if not tool_name:
+ return self.default_action == "allow", None, None
+
+ last_pattern_failure_msg: Optional[str] = None
+
+ for rule in self.rules:
+ if not self._matches_pattern(tool_name, rule.tool_name):
+ continue
+
+ if rule.allowed_param_patterns:
+ arguments = self._parse_tool_call_arguments(tool_call)
+ if not arguments:
+ last_pattern_failure_msg = f"Tool '{tool_name}' is missing arguments required by rule '{rule.id}'"
+ continue
+
+ patterns_match, failure_message = self._patterns_match_for_rule(
+ arguments=arguments,
+ rule=rule,
+ tool_name=tool_name,
+ )
+ if not patterns_match:
+ last_pattern_failure_msg = failure_message
+ continue
+
+ is_allowed = rule.decision == "allow"
+ default_message = f"Tool '{tool_name}' {'allowed' if is_allowed else 'denied'} by rule '{rule.id}'"
+ message = self.render_violation_message(
+ default=default_message,
+ context={"tool_name": tool_name, "rule_id": rule.id},
+ )
+ return is_allowed, rule.id, message
+
+ is_allowed = self.default_action == "allow"
+ default_message = (
+ last_pattern_failure_msg
+ if (last_pattern_failure_msg and not is_allowed)
+ else f"Tool '{tool_name}' {'allowed' if is_allowed else 'denied'} by default action"
+ )
+ message = self.render_violation_message(
+ default=default_message,
+ context={"tool_name": tool_name, "rule_id": None},
+ )
+ return is_allowed, None, message
+
def _extract_tool_calls_from_response(
self, response: ModelResponse
) -> List[ChatCompletionMessageToolCall]:
@@ -365,7 +506,7 @@ class ToolPermissionGuardrail(CustomGuardrail):
response: The model response to check
"""
if not isinstance(response, ModelResponse):
- return
+ return response
verbose_proxy_logger.debug(
"Tool Permission Guardrail Post-Call Hook: Checking response"
@@ -377,14 +518,14 @@ class ToolPermissionGuardrail(CustomGuardrail):
verbose_proxy_logger.debug(
"Tool Permission Guardrail: Skipping check (not enabled)"
)
- return
+ return response
# Extract tool_calls from the response
tool_calls = self._extract_tool_calls_from_response(response)
if not tool_calls:
verbose_proxy_logger.debug("Tool Permission Guardrail: No tool uses found")
- return
+ return response
verbose_proxy_logger.debug(
f"Tool Permission Guardrail: Found {len(tool_calls)} tool calls"
@@ -393,11 +534,7 @@ class ToolPermissionGuardrail(CustomGuardrail):
# Check permissions for each tool use
denied_tools = []
for tool_call in tool_calls:
- if tool_call.function.name is None:
- continue
- is_allowed, rule_id, message = self._check_tool_permission(
- tool_call.function.name
- )
+ is_allowed, rule_id, message = self._get_permission_for_tool_call(tool_call)
if not is_allowed and message is not None:
verbose_proxy_logger.warning(f"Tool Permission Guardrail: {message}")
@@ -411,7 +548,11 @@ class ToolPermissionGuardrail(CustomGuardrail):
(
tool_call,
PermissionError(
- tool_name=tool_call.function.name,
+ tool_name=(
+ tool_call.function.name
+ if tool_call.function and tool_call.function.name
+ else "unknown_tool"
+ ),
rule_id=rule_id,
message=message,
),
@@ -420,14 +561,15 @@ class ToolPermissionGuardrail(CustomGuardrail):
if denied_tools:
self._modify_response_with_permission_errors(response, denied_tools)
-
- verbose_proxy_logger.debug(
- "Tool Permission Guardrail Post-Call Hook: All tools allowed"
- )
+ else:
+ verbose_proxy_logger.debug(
+ "Tool Permission Guardrail Post-Call Hook: All tools allowed"
+ )
add_guardrail_to_applied_guardrails_header(
request_data=data, guardrail_name=self.guardrail_name
)
+ return response
async def async_post_call_streaming_iterator_hook(
self,
@@ -480,10 +622,8 @@ class ToolPermissionGuardrail(CustomGuardrail):
# Check permissions for each tool use
denied_tools = []
for tool_call in tool_calls:
- if tool_call.function.name is None:
- continue
- is_allowed, rule_id, message = self._check_tool_permission(
- tool_call.function.name
+ is_allowed, rule_id, message = self._get_permission_for_tool_call(
+ tool_call
)
if not is_allowed and message is not None:
@@ -500,28 +640,32 @@ class ToolPermissionGuardrail(CustomGuardrail):
(
tool_call,
PermissionError(
- tool_name=tool_call.function.name,
+ tool_name=(
+ tool_call.function.name
+ if tool_call.function and tool_call.function.name
+ else "unknown_tool"
+ ),
rule_id=rule_id,
message=message,
),
)
)
+ if denied_tools:
+ self._modify_response_with_permission_errors(
+ assembled_model_response, denied_tools
+ )
+ else:
verbose_proxy_logger.debug(
"Tool Permission Guardrail Post-Call Hook: All tools allowed"
)
- if denied_tools:
- self._modify_response_with_permission_errors(
- assembled_model_response, denied_tools
- )
-
- mock_response = MockResponseIterator(
- model_response=assembled_model_response
- )
- # Return the reconstructed stream
- async for chunk in mock_response:
- yield chunk
+ mock_response = MockResponseIterator(
+ model_response=assembled_model_response
+ )
+ # Return the reconstructed stream
+ async for chunk in mock_response:
+ yield chunk
else:
for chunk in all_chunks:
yield chunk
diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/tool_permission.py b/litellm/types/proxy/guardrails/guardrail_hooks/tool_permission.py
index dd4d63d75f5..b2248c51930 100644
--- a/litellm/types/proxy/guardrails/guardrail_hooks/tool_permission.py
+++ b/litellm/types/proxy/guardrails/guardrail_hooks/tool_permission.py
@@ -1,5 +1,5 @@
# Tool Permission Guardrail Type Definitions
-from typing import Literal, Optional
+from typing import Dict, Literal, Optional
from pydantic import BaseModel, Field
@@ -16,6 +16,10 @@ class ToolPermissionRule(BaseModel):
decision: Literal["allow", "deny"] = Field(
description="Whether to allow or deny this tool usage"
)
+ allowed_param_patterns: Optional[Dict[str, str]] = Field(
+ default=None,
+ description="Optional regex map enforcing nested parameter values using dot/[] paths",
+ )
class ToolResult(BaseModel):
diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_tool_permission.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_tool_permission.py
index 8c88b22f60e..0926fe10c9e 100644
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_tool_permission.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_tool_permission.py
@@ -221,6 +221,144 @@ class TestToolPermissionGuardrail:
data=data, user_api_key_dict=user_api_key_dict, response=response
)
+ @pytest.mark.asyncio
+ async def test_async_post_call_success_hook_param_patterns_allow(self):
+ guardrail = ToolPermissionGuardrail(
+ guardrail_name="mail-guardrail",
+ rules=[
+ {
+ "id": "allow_mail",
+ "tool_name": "mail_mcp-send_email",
+ "decision": "allow",
+ "allowed_param_patterns": {
+ "to[]": r"^.+@berri\.ai$",
+ "subject": r"^.{1,120}$",
+ },
+ }
+ ],
+ default_action="deny",
+ on_disallowed_action="block",
+ )
+
+ tool_call = {
+ "function": {
+ "name": "mail_mcp-send_email",
+ "arguments": '{"to": ["[email protected]"], "subject": "Hi"}',
+ },
+ "type": "function",
+ }
+ response = ModelResponse(choices=[Choices(message={"tool_calls": [tool_call]})])
+ user_api_key_dict = UserAPIKeyAuth()
+ data = {"guardrails": ["mail-guardrail"]}
+
+ with patch.object(guardrail, "should_run_guardrail", return_value=True):
+ await guardrail.async_post_call_success_hook(
+ data=data, user_api_key_dict=user_api_key_dict, response=response
+ )
+
+ @pytest.mark.asyncio
+ async def test_async_post_call_success_hook_param_patterns_block(self):
+ guardrail = ToolPermissionGuardrail(
+ guardrail_name="mail-guardrail",
+ rules=[
+ {
+ "id": "allow_mail",
+ "tool_name": "mail_mcp-send_email",
+ "decision": "allow",
+ "allowed_param_patterns": {"to[]": r"^.+@berri\.ai$"},
+ }
+ ],
+ default_action="deny",
+ on_disallowed_action="block",
+ )
+
+ tool_call = {
+ "function": {
+ "name": "mail_mcp-send_email",
+ "arguments": '{"to": ["[email protected]"]}',
+ },
+ "type": "function",
+ }
+ response = ModelResponse(choices=[Choices(message={"tool_calls": [tool_call]})])
+ user_api_key_dict = UserAPIKeyAuth()
+ data = {"guardrails": ["mail-guardrail"]}
+
+ with patch.object(guardrail, "should_run_guardrail", return_value=True):
+ with pytest.raises(GuardrailRaisedException):
+ await guardrail.async_post_call_success_hook(
+ data=data, user_api_key_dict=user_api_key_dict, response=response
+ )
+
+ @pytest.mark.asyncio
+ async def test_async_post_call_success_hook_param_patterns_rewrite(self):
+ guardrail = ToolPermissionGuardrail(
+ guardrail_name="mail-guardrail",
+ rules=[
+ {
+ "id": "allow_mail",
+ "tool_name": "mail_mcp-send_email",
+ "decision": "allow",
+ "allowed_param_patterns": {"to[]": r"^.+@berri\.ai$"},
+ }
+ ],
+ default_action="deny",
+ on_disallowed_action="rewrite",
+ )
+
+ tool_call = {
+ "id": "call_berri",
+ "function": {
+ "name": "mail_mcp-send_email",
+ "arguments": '{"to": ["[email protected]"]}',
+ },
+ "type": "function",
+ }
+ response = ModelResponse(choices=[Choices(message={"tool_calls": [tool_call]})])
+ user_api_key_dict = UserAPIKeyAuth()
+ data = {"guardrails": ["mail-guardrail"]}
+
+ with patch.object(guardrail, "should_run_guardrail", return_value=True):
+ await guardrail.async_post_call_success_hook(
+ data=data, user_api_key_dict=user_api_key_dict, response=response
+ )
+
+ choice = response.choices[0]
+ assert isinstance(choice, Choices)
+ assert not choice.message.tool_calls
+ assert isinstance(choice.message.content, str)
+ assert "berri" in choice.message.content
+
+ @pytest.mark.asyncio
+ async def test_async_post_call_success_hook_missing_arguments_default_allows(self):
+ guardrail = ToolPermissionGuardrail(
+ guardrail_name="mail-guardrail",
+ rules=[
+ {
+ "id": "deny_gmail",
+ "tool_name": "mail_mcp-send_email",
+ "decision": "deny",
+ "allowed_param_patterns": {"to[]": r"^.+@gmail\.com$"},
+ }
+ ],
+ default_action="allow",
+ on_disallowed_action="block",
+ )
+
+ tool_call = {
+ "function": {
+ "name": "mail_mcp-send_email",
+ },
+ "type": "function",
+ }
+ response = ModelResponse(choices=[Choices(message={"tool_calls": [tool_call]})])
+ user_api_key_dict = UserAPIKeyAuth()
+ data = {"guardrails": ["mail-guardrail"]}
+
+ with patch.object(guardrail, "should_run_guardrail", return_value=True):
+ await guardrail.async_post_call_success_hook(
+ data=data, user_api_key_dict=user_api_key_dict, response=response
+ )
+
@pytest.mark.asyncio
async def test_async_pre_call_hook_block_mode(self):
data = {