🛠️ Dynamic One-Time Tools
The most advanced Nexus feature that allows LLMs to create custom tools on-the-fly for specific tasks that don't have existing solutions. This represents the pinnacle of agentic capabilities.
🌟 Overview
Dynamic One-Time Tools enable the following groundbreaking workflow:
- LLM Identifies Gap: Determines no existing tool can solve the problem
- Code Generation: LLM writes Python code for the specific task
- Dynamic Execution:
create_and_run_toolexecutes the code safely - Result Integration: Output is returned for further processing
🔒Maximum Security
Complete Docker isolation with resource limits and security validation
⚡On-Demand Creation
Tools are created, executed, and disposed for specific tasks
🎯Task-Specific
Perfect solution for unique problems that don't fit existing tools
🧠AI-Driven
LLMs can autonomously create tools based on natural language requirements
📚 Function Reference
Function Signature
create_and_run_tool(
python_code: str,
timeout: int = 60,
memory_limit_mb: int = 128
) -> Dict[str, Any]
Parameters
| Parameter | Type | Default | Range | Description |
|---|---|---|---|---|
python_code |
str | Required | - | The Python code for the custom tool |
timeout |
int | 60 | 10-300 | Execution timeout in seconds |
memory_limit_mb |
int | 128 | 32-512 | Memory limit in megabytes |
🔒 Security Features
The dynamic tool system implements multiple layers of security to ensure safe execution:
🔍Code Security Validation
- Scans for dangerous patterns
- Validates import statements
- Checks for file system access
- Prevents network operations
🐳Docker Isolation
- Complete environment isolation
- No access to host system
- Temporary container creation
- Automatic cleanup after execution
⚙️Resource Limits
- CPU usage restrictions (0.5 cores)
- Memory limits (32-512MB)
- Execution time limits (10-300s)
- No network access
📁Filesystem Restrictions
- Read-only filesystem
- Limited /tmp space (10MB)
- No persistent storage
- Non-root execution (nexus:1000)
🚀 Execution Modes
1. Docker Mode (Recommended)
🎯 Production Ready
The Docker mode provides maximum security and is recommended for all production deployments.
Features:
- Maximum Security: Complete isolation in Docker container
- Resource Limits: Memory (32-512MB), CPU (0.5 cores)
- Network Isolation: No network access during execution
- Filesystem: Read-only with limited /tmp access (10MB)
- User Security: Non-root execution (nexus:1000)
- Cleanup: Automatic container and image removal
2. Fallback Mode
⚠️ Limited Security
Fallback mode is used when Docker is unavailable. It provides reduced security compared to Docker mode.
Features:
- Local Execution: Runs on the host system when Docker is unavailable
- Restricted Environment: Limited builtins and import restrictions
- Resource Limits: Memory and CPU limits via system calls
- Security: Code validation and import filtering
- Isolation: Process-level isolation only
📋 Response Format
The function returns a comprehensive response with execution details:
{
"success": true,
"tool_id": "abc12345",
"execution_mode": "docker_isolated",
"timeout_seconds": 60,
"memory_limit_mb": 128,
"security_check": {
"safe": true,
"violations": []
},
"docker_image": "nexus-dynamic-tool-abc12345",
"container_name": "nexus-dynamic-tool-abc12345",
"container_execution_time_seconds": 1.234,
"container_return_code": 0,
"container_stderr": "",
"tool_result": {
"success": true,
"tool_id": "abc12345",
"execution_time_seconds": 0.123,
"stdout": "Tool output here...",
"stderr": "",
"message": "Dynamic tool executed successfully"
}
}
💡 Usage Examples
Example 1: Custom Date Converter
Scenario: Convert proprietary date format
Task: Convert "20250907-143022" format to ISO format
# LLM generates this code dynamically
python_code = """
from datetime import datetime
custom_date = "20250907-143022"
date_part, time_part = custom_date.split("-")
dt = datetime(
int(date_part[:4]), # year
int(date_part[4:6]), # month
int(date_part[6:8]), # day
int(time_part[:2]), # hour
int(time_part[2:4]), # minute
int(time_part[4:6]) # second
)
print(f"ISO: {dt.isoformat()}")
print(f"Human: {dt.strftime('%Y-%m-%d %H:%M:%S')}")
"""
# Claude calls this automatically
result = create_and_run_tool(python_code, timeout=30, memory_limit_mb=64)
Output:
ISO: 2025-09-07T14:30:22
Human: 2025-09-07 14:30:22
Example 2: Data Format Converter
Scenario: Convert legacy pipe-separated data to JSON
Task: Parse "JOHN|25|NYC|50000" format into structured JSON
# Dynamic tool for legacy data conversion
python_code = """
import json
legacy_data = "JOHN|25|NYC|50000\\nJANE|30|LA|75000"
records = []
for line in legacy_data.strip().split("\\n"):
if line.strip():
name, age, city, salary = line.split("|")
records.append({
"name": name,
"age": int(age),
"city": city,
"salary": int(salary)
})
print(json.dumps(records, indent=2))
"""
result = create_and_run_tool(python_code, timeout=45)
Output:
[
{
"name": "JOHN",
"age": 25,
"city": "NYC",
"salary": 50000
},
{
"name": "JANE",
"age": 30,
"city": "LA",
"salary": 75000
}
]
Example 3: Mathematical Calculator
Scenario: Custom mathematical function
Task: Calculate the nth pentagonal number with verification
# Specialized mathematical calculation
python_code = """
def pentagonal_number(n):
'''Calculate the nth pentagonal number: n(3n-1)/2'''
return n * (3 * n - 1) // 2
def verify_pentagonal(p):
'''Verify if a number is pentagonal'''
# Using quadratic formula: n = (1 + sqrt(1 + 24p)) / 6
import math
discriminant = 1 + 24 * p
if discriminant < 0:
return False
sqrt_d = math.sqrt(discriminant)
n = (1 + sqrt_d) / 6
return n == int(n) and n > 0
# Calculate pentagonal numbers
for i in range(1, 11):
pent = pentagonal_number(i)
is_valid = verify_pentagonal(pent)
print(f"P({i}) = {pent}, Valid: {is_valid}")
# Test specific number
test_num = 145
print(f"\\nIs {test_num} pentagonal? {verify_pentagonal(test_num)}")
"""
result = create_and_run_tool(python_code, timeout=30, memory_limit_mb=64)
🎯 Use Cases
🔄Data Format Conversion
- Convert proprietary formats
- Parse legacy data structures
- Transform between data formats
- Extract structured data from text
🧮Mathematical Computations
- Custom mathematical algorithms
- Statistical calculations
- Number theory operations
- Complex formula implementations
📝Text Processing
- Custom parsing logic
- Text analysis algorithms
- Format-specific extraction
- Content transformation
🔬Algorithm Implementation
- Specific algorithms for unique problems
- Prototype development
- Research computations
- One-off calculations
✨ Best Practices
Code Quality Guidelines
💡 Writing Effective Dynamic Tools
- Clear Output: Use print() statements for results
- Error Handling: Include try/except blocks for robustness
- Documentation: Add comments for complex logic
- Input Validation: Validate data before processing
- Efficiency: Optimize for the given resource limits
Security Guidelines
🔒 Security Considerations
- No Network Access: Tools cannot make external requests
- No File System: Limited to temporary storage only
- No Persistent State: Each execution is isolated
- Resource Limits: Stay within memory and time constraints
- Safe Libraries: Only use standard Python libraries
Performance Tips
⚡ Optimization
- Minimize memory usage
- Use efficient algorithms
- Avoid unnecessary computations
- Profile execution time
🎯 Resource Management
- Choose appropriate timeout values
- Set memory limits based on task complexity
- Monitor execution patterns
- Clean up variables when possible
🔍 Troubleshooting
Common Errors
🚫 Execution Failures
Symptoms: Tool execution fails or times out
Solutions:
- Check Docker is installed and running
- Verify Python code syntax
- Ensure imports are available
- Increase timeout or memory limits
⚠️ Security Violations
Symptoms: Code is rejected before execution
Solutions:
- Remove file system access attempts
- Avoid network-related imports
- Check for dangerous function calls
- Use only allowed standard libraries
Debugging Tips
- Test Locally: Verify code works in a standard Python environment
- Use Print Statements: Add debug output to track execution
- Check Resource Usage: Monitor memory and time consumption
- Simplify First: Start with simple versions and build complexity
⚠️ Limitations
Current Limitations
- No Network Access: Cannot make HTTP requests or external connections
- Standard Library Only: No pip packages or external dependencies
- No Persistent Storage: Cannot save files or maintain state between executions
- Resource Constraints: Limited CPU, memory, and execution time
- Docker Dependency: Requires Docker for maximum security features
🎯 Next Steps
💡 Try Examples
Experiment with the provided examples and create your own variations
Examples & Tutorials →🌐 API Integration
Use dynamic tools through the REST API from any programming language
Enhanced API →📚 Complete Tools
Explore all 500+ built-in tools available alongside dynamic creation
Tools Reference →