eval() when a custom tool evaluates user-supplied math.
Quick Start
How It Works
Allow-list Reference
The AST allow-list permits only these node types for safe arithmetic evaluation:| Node Type | Purpose | Example |
|---|---|---|
ast.Expression | Root expression node | Required wrapper |
ast.BinOp | Binary operations | 2 + 3, 4 * 5 |
ast.UnaryOp | Unary operations | -5, +3 |
ast.Constant | Literal values | 42, 3.14 |
ast.Add | Addition operator | + |
ast.Sub | Subtraction operator | - |
ast.Mult | Multiplication operator | * |
ast.Div | Division operator | / |
ast.USub | Unary minus | -x |
ast.UAdd | Unary plus | +x |
- Function calls (
pow(),exec(),__import__()) - Attribute access (
.attr,obj.method) - Names/variables (
x,globals) - List/dict comprehensions
- Power operator (
**) - Modulo operator (
%)
Common Patterns
Integrate with MCP server
Integrate with a local provider tool
Best Practices
Never call eval() on user input
Never call eval() on user input
Always parse user expressions through AST validation before evaluation. The
eval() function can execute arbitrary Python code and should never receive untrusted input, even with restricted __builtins__.Reject before parsing using a character allow-list
Reject before parsing using a character allow-list
Add an initial character filter to catch obviously malicious input:
Return a sentinel string rather than raising
Return a sentinel string rather than raising
Return
"error" instead of raising exceptions to provide graceful degradation in agent workflows. This prevents the entire agent conversation from failing due to a malformed math expression.Cap expression length
Cap expression length
Prevent resource exhaustion by limiting expression length:
Related
Security Guide
Complete security practices and hardening measures
Custom Tools
Build custom tools for agents with proper patterns

