This document provides context and guidance for AI assistants working with the LLM Sandbox codebase.
LLM Sandbox is a lightweight and portable sandbox environment designed to run Large Language Model (LLM) generated code in a safe and isolated mode. It provides secure execution environments for AI-generated code while offering flexibility in container backends and comprehensive language support.
Version: 0.3.13 License: MIT Python Support: 3.10+ Documentation: https://vndee.github.io/llm-sandbox/ Repository: https://github.com/vndee/llm-sandbox
-
Session Management (
llm_sandbox/session.py)SandboxSession: Basic code execution in isolated containersArtifactSandboxSession: Execution with automatic artifact capture (plots, visualizations)InteractiveSandboxSession: Stateful sessions maintaining Python interpreter statecreate_session(): Factory function for session creation
-
Container Backends (
llm_sandbox/docker.py,llm_sandbox/kubernetes.py,llm_sandbox/podman.py)- Docker (default, most common)
- Kubernetes (enterprise-grade orchestration)
- Podman (rootless containers)
-
Language Handlers (
llm_sandbox/language_handlers/)- Python (
python_handler.py) - JavaScript/Node.js (
javascript_handler.py) - Java (
java_handler.py) - C++ (
cpp_handler.py) - Go (
go_handler.py) - R (
r_handler.py) - Ruby (
ruby_handler.py)
- Python (
-
Container Pooling (
llm_sandbox/pool/)- Pre-warmed container management for performance
- Thread-safe concurrent execution
- Configurable pool sizes and lifecycle management
-
Security (
llm_sandbox/security.py)- Security policies and pattern matching
- Code scanning for vulnerabilities
- Resource limits and network isolation
-
MCP Server (
llm_sandbox/mcp_server/)- Model Context Protocol integration
- Enables Claude Desktop and other MCP clients to execute code
llm-sandbox/
├── llm_sandbox/ # Main package
│ ├── __init__.py # Public API exports
│ ├── session.py # Session implementations
│ ├── docker.py # Docker backend
│ ├── kubernetes.py # Kubernetes backend
│ ├── podman.py # Podman backend
│ ├── security.py # Security policies
│ ├── interactive.py # Interactive session support
│ ├── data.py # Data models (ExecutionResult, PlotOutput)
│ ├── const.py # Constants and enums
│ ├── exceptions.py # Custom exceptions
│ ├── core/ # Core abstractions
│ │ ├── config.py # Configuration models
│ │ ├── session_base.py # Base session class
│ │ └── mixins.py # Shared functionality
│ ├── language_handlers/ # Language-specific handlers
│ │ ├── base.py # Base handler interface
│ │ ├── python_handler.py
│ │ ├── javascript_handler.py
│ │ ├── java_handler.py
│ │ ├── cpp_handler.py
│ │ ├── go_handler.py
│ │ ├── r_handler.py
│ │ ├── ruby_handler.py
│ │ └── artifact_detection/ # Plot/artifact detection
│ ├── pool/ # Container pooling
│ │ ├── base.py # Base pool manager
│ │ ├── config.py # Pool configuration
│ │ ├── docker_pool.py # Docker pool implementation
│ │ ├── kubernetes_pool.py
│ │ ├── podman_pool.py
│ │ ├── session.py # Pooled session wrapper
│ │ └── factory.py # Pool factory
│ └── mcp_server/ # MCP integration
│ ├── server.py # MCP server implementation
│ ├── types.py # MCP data types
│ └── const.py # MCP constants
├── tests/ # Test suite
├── examples/ # Usage examples
├── docs/ # Documentation source
├── pyproject.toml # Project metadata and dependencies
├── README.md # User-facing documentation
└── CLAUDE.md # This file
- Formatter: Ruff (line length: 120)
- Type Checking: Mypy with strict settings
- Testing: pytest with integration tests for backends
- Pre-commit hooks: Configured for automated checks
- Context Managers: All sessions use context managers for proper resource cleanup
- Factory Pattern:
create_session()andcreate_pool_manager()for object creation - Strategy Pattern: Language handlers implement common interface
- Pool Pattern: Container pooling for performance optimization
- Unit tests for core logic
- Integration tests marked with
@pytest.mark.integration - Tests require Docker/Podman/Kubernetes depending on backend
- Run tests:
make testorpytest tests/
- Create handler in
llm_sandbox/language_handlers/ - Inherit from
BaseLanguageHandler - Implement required methods:
prepare_code()get_install_command()get_execution_command()
- Register in
factory.py - Add to
SupportedLanguageenum inconst.py - Add tests in
tests/
- Security patterns defined in
security.py - Code scanning happens before execution
- Add new patterns to
SecurityPatterndataclass - Test with
tests/test_security_*.py
- Pool managers in
llm_sandbox/pool/ - Configuration in
pool/config.py - Three exhaustion strategies: WAIT, FAIL_FAST, TEMPORARY
- Thread-safe implementation required
- MCP server in
llm_sandbox/mcp_server/server.py - Tools defined using MCP decorators
- Must handle async operations
- Test with MCP client (e.g., Claude Desktop)
# Always use context managers
with SandboxSession(lang="python") as session:
result = session.run("print('hello')")
# Container automatically cleaned up on exitSandboxError: Base exceptionContainerError: Container-related issuesSecurityError: Security violationsResourceError: Resource exhaustionValidationError: Input validation failures
# Libraries installed automatically when specified
session.run(code, libraries=["numpy", "pandas"])# Plots and visualizations automatically captured
with ArtifactSandboxSession(lang="python") as session:
result = session.run("plt.plot([1,2,3]); plt.show()")
for plot in result.plots:
# plot.content_base64 contains image data
passfrom langchain.tools import BaseTool
from llm_sandbox import SandboxSession
class PythonSandboxTool(BaseTool):
name = "python_sandbox"
description = "Execute Python code"
def _run(self, code: str) -> str:
with SandboxSession(lang="python") as session:
result = session.run(code)
return result.stdoutDefine as function with parameters matching SandboxSession.run() signature.
Use as custom tool with SandboxSession wrapper.
Configure in client (e.g., claude_desktop_config.json):
{
"mcpServers": {
"llm-sandbox": {
"command": "python3",
"args": ["-m", "llm_sandbox.mcp_server.server"]
}
}
}- Use Container Pooling for frequent executions (10x faster)
- Pre-install Libraries in custom images or pool configuration
- Reuse Sessions when possible (especially
InteractiveSandboxSession) - Set Appropriate Resource Limits to prevent resource exhaustion
- Choose Right Backend: Docker (development), Kubernetes (production scale)
- Always run untrusted code in sandbox
- Set resource limits (CPU, memory, execution time)
- Configure network isolation when needed
- Use security policies for sensitive operations
- Regularly update container images
- Monitor container metrics in production
- Enable Verbose Mode:
SandboxSession(verbose=True) - Keep Containers:
keep_template=Truefor inspection - Check Logs: Container logs available via backend APIs
- Test Backends: Verify Docker/Kubernetes/Podman availability
- Review Security Scanner: Check for flagged patterns in code
- Not using context managers - leads to resource leaks
- Forgetting to specify language - required parameter
- Large library installations - use custom images instead
- Not handling timeout errors - set appropriate timeouts
- Mixing pool and non-pool sessions - be consistent
- Project metadata
- Dependencies (base + optional extras)
- Development dependencies
- Tool configurations (mypy, pytest, ruff)
- Required: pydantic (data validation)
- Docker: docker (Docker API)
- Kubernetes: kubernetes (K8s API)
- Podman: docker + podman
- MCP: mcp (Model Context Protocol)
Check git log for recent commits. Notable features:
- Container pooling system (v0.3+)
- Interactive sessions with IPython kernel
- MCP server integration
- Multi-language support expansion (R, Ruby)
- Artifact detection improvements
- Security policy enhancements
- Documentation: https://vndee.github.io/llm-sandbox/
- GitHub: https://github.com/vndee/llm-sandbox
- PyPI: https://pypi.org/project/llm-sandbox/
- Issues: https://github.com/vndee/llm-sandbox/issues
- Discussions: https://github.com/vndee/llm-sandbox/discussions
- Read existing code in the relevant module
- Check tests for usage patterns
- Review documentation for context
- Consider security implications
- Maintain backward compatibility when possible
- Start with tests (TDD approach when appropriate)
- Update documentation
- Add examples if user-facing
- Consider performance impact
- Test with all supported backends (if applicable)
- Add regression test first
- Identify root cause
- Fix minimal code necessary
- Verify fix doesn't break other tests
- Update documentation if behavior changes
When implementing features, consider:
- Which backends does this affect?
- Are there security implications?
- How does this interact with pooling?
- Does this need language-specific handling?
- What are the performance characteristics?
- How should errors be handled?
- Is this a breaking change?
- Author: Duy Huynh (vndee.huynh@gmail.com)
- Issues: GitHub Issues
- Community: GitHub Discussions