Skip to main content
Use an AST allow-list instead of eval() when a custom tool evaluates user-supplied math.
The user supplies a maths expression; the tool evaluates it via an AST allow-list, not raw eval().

Quick Start

1

Unsafe (don't do this)

This pattern is dangerous and vulnerable to remote code execution attacks:
2

Safe pattern

Use the AST-based allow-list for secure math evaluation:

How It Works


Allow-list Reference

The AST allow-list permits only these node types for safe arithmetic evaluation: Explicitly rejected constructs:
  • 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

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__.
Add an initial character filter to catch obviously malicious input:
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.
Prevent resource exhaustion by limiting expression length:

Security Guide

Complete security practices and hardening measures

Custom Tools

Build custom tools for agents with proper patterns