Tool Execution Sandbox

Medium
Agents

Implement sandboxed tool execution for agent safety:

  1. register_tool(name, func): Add tool to sandbox registry
  2. execute(tool_name, params): Run with restrictions
    • Check if tool in allowlist
    • Execute with timeout
    • Log all attempts
  3. is_allowed(tool_name): Check allowlist
  4. get_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: True
Explanation: 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
        pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews