Skip to content

Tool Validation

Tool validation guardrails ensure your agent uses tools correctly and securely.

GuardrailPurpose
require_tool_use()Ensure specific tools were called
tool_allowlist()Restrict which tools can be called
validate_tool_parameters()Validate tool call arguments
from pydantic_ai_guardrails.guardrails.output import (
require_tool_use,
tool_allowlist,
validate_tool_parameters,
)

Ensure the agent called specific tools during execution.

ParameterTypeDefaultDescription
tool_nameslist[str]RequiredTools that must be called
mode'any' | 'all''any'Require any or all tools
# At least one of these tools must be called
guardrail = require_tool_use(
tool_names=['search', 'calculate'],
mode='any',
)
# All of these tools must be called
guardrail = require_tool_use(
tool_names=['fetch_data', 'validate_data'],
mode='all',
)
  • Ensure agent uses retrieval before answering
  • Verify calculations were performed
  • Enforce workflow steps

Restrict which tools the agent is allowed to call.

ParameterTypeDefaultDescription
allowed_toolslist[str]RequiredOnly these tools are permitted
# Only allow safe, read-only tools
guardrail = tool_allowlist(
allowed_tools=['search', 'get_weather', 'calculate'],
)
  • Prevent dangerous tool calls
  • Enforce role-based permissions
  • Sandbox agent capabilities

Validate the arguments passed to tool calls.

ParameterTypeDefaultDescription
schemasdict[str, dict]RequiredJSON schemas per tool
guardrail = validate_tool_parameters(
schemas={
'search': {
'type': 'object',
'properties': {
'query': {'type': 'string', 'minLength': 3},
'limit': {'type': 'integer', 'minimum': 1, 'maximum': 100},
},
'required': ['query'],
},
'send_email': {
'type': 'object',
'properties': {
'to': {'type': 'string', 'format': 'email'},
'subject': {'type': 'string', 'maxLength': 200},
},
'required': ['to', 'subject'],
},
}
)
  • Prevent SQL injection via tool parameters
  • Enforce parameter constraints
  • Validate email formats, URLs, etc.

from pydantic_ai_guardrails import GuardedAgent
from pydantic_ai_guardrails.guardrails.output import (
require_tool_use,
tool_allowlist,
validate_tool_parameters,
)
guarded_agent = GuardedAgent(
agent,
output_guardrails=[
# Only allow these tools
tool_allowlist(allowed_tools=['search', 'get_user']),
# Search must be called
require_tool_use(tool_names=['search'], mode='any'),
# Validate parameters
validate_tool_parameters(schemas={
'search': {
'type': 'object',
'properties': {
'query': {'type': 'string', 'minLength': 1},
},
},
}),
],
)

Tool guardrails access the message history via GuardrailContext.messages:

async def check_tools(ctx: GuardrailContext, output: str) -> GuardrailResult:
for msg in ctx.messages or []:
if hasattr(msg, 'parts'):
for part in msg.parts:
if hasattr(part, 'tool_name'):
# Found a tool call
tool_name = part.tool_name
tool_args = part.args
# ... validate ...