Implement sandboxed tool execution for agent safety:
register_tool(name, func): Add tool to sandbox registryexecute(tool_name, params): Run with restrictions- Check if tool in allowlist
- Execute with timeout
- Log all attempts
is_allowed(tool_name): Check allowlistget_audit_log(): Return execution history
Security:
- Block execution of non-allowed tools
- Log blocked attempts separately
- Enforce timeout to prevent hung calls
- Catch all exceptions, return in error field
Audit Log Entry:
{'timestamp': ..., 'tool': ..., 'params': ..., 'allowed': bool, 'success': bool}
Examples
Example 1:
Input:
sb = ToolSandbox(['add']); sb.register_tool('add', lambda x,y: x+y); r = sb.execute('add', {'x':1,'y':2}); r['success']Output:
TrueExplanation: Allowed tool executes successfully
Starter Code
class ToolSandbox:
"""
Sandbox for safely executing agent tool calls.
Restricts operations to allowed set.
"""
def __init__(self, allowed_tools=None, timeout_sec=30):
self.allowed_tools = set(allowed_tools or [])
self.timeout_sec = timeout_sec
self.execution_log = []
self.blocked_attempts = []
def register_tool(self, name, func):
"""Register allowed tool"""
# Your implementation here
pass
def execute(self, tool_name, params):
"""
Execute tool if allowed.
Returns {'success': bool, 'result': ..., 'error': ..., 'execution_time': ...}
"""
# Your implementation here
pass
def is_allowed(self, tool_name):
"""Check if tool is in allowlist"""
# Your implementation here
pass
def get_audit_log(self):
"""Return complete execution history"""
# Your implementation here
passPython3
ReadyLines: 1Characters: 0
Ready