### Python Development Workflow Example Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Demonstrates initializing a sandbox, installing the uv package manager, and installing Python dependencies. ```bash # Initialize sandbox uv run sbx init --timeout 900 export SANDBOX_ID=$(cat .sandbox_id) # Install uv package manager uv run sbx exec $SANDBOX_ID "curl -LsSf https://astral.sh/uv/install.sh | sh" --shell --timeout 120 # Install Python packages uv run sbx exec $SANDBOX_ID "/home/user/.local/bin/uv pip install --system requests beautifulsoup4" ``` -------------------------------- ### Install Dependencies and Start Dev Server Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/src/prompts/sandbox_fork_agent_system_prompt.md Installs project dependencies using npm or bun, then starts the development server in the background. A sleep period is included to allow the server to start. ```bash # Install dependencies if needed npm install # or bun install # Start dev server in background npm run dev & # or bun run dev & # Wait for server to start sleep 10 ``` -------------------------------- ### Set Up Node.js Project and Run Tests Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_mcp/README.md Example use case for setting up a Node.js project, including dependency installation, and running tests within a sandbox. ```text "Set up a Node.js project with dependencies and run tests" ``` -------------------------------- ### Install uv package manager Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_fundamentals/README.md Use this command to install the uv package manager required for running the examples. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### System Administration Task Example Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_mcp/README.md Example use case for system administration tasks, such as installing and configuring nginx, and verifying its status. ```text "Install nginx, configure it, and check if it's running" ``` -------------------------------- ### Install Dependencies Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_mcp/README.md Navigate to the project directory and install required dependencies using uv. ```bash # Navigate to this directory cd apps/sandbox_mcp # Install dependencies uv sync ``` -------------------------------- ### Installation and Usage Commands Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Commands for installing dependencies and running the sandbox-fork tool. ```bash cd apps/sandbox_workflows uv sync ``` ```bash cp .env.sample .env ``` ```bash uv run obox sandbox-fork https://github.com/user/repo --prompt "Add unit tests to all functions" ``` ```bash uv run obox sandbox-fork https://github.com/user/repo \ --prompt "Refactor the codebase to use async/await" \ --forks 5 ``` ```bash uv run obox sandbox-fork https://github.com/user/repo \ --branch feature/new-api \ --prompt "Review and document the new API endpoints" ``` -------------------------------- ### Install Dependencies and Run CLI Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Install project dependencies using 'uv sync' and then run the CLI with 'uv run sbx --help' to view available commands. ```bash # Install dependencies uv sync # Run the CLI uv run sbx --help ``` -------------------------------- ### Run an E2B example Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_fundamentals/README.md Execute a specific Python example script using uv. ```bash uv run 01_basic_sandbox.py ``` -------------------------------- ### Expose Web Servers with E2B SDK Source: https://context7.com/disler/agent-sandboxes/llms.txt Create a sandbox, set up a Vite project, configure it for E2B public URLs, start the dev server, and get a public URL. Ensure the server is configured to listen on 0.0.0.0 and uses port 5173. ```python import time from e2b import Sandbox # Create sandbox with Node.js template sbx = Sandbox.create(template="agent-sandbox-dev-node22", timeout=600) # Create Vite project sbx.commands.run( "bash -c 'source ~/.nvm/nvm.sh && npm create vite@latest my-app -- --template vue'", cwd="/home/user", timeout=60 ) # Install dependencies sbx.commands.run( "bash -c 'source ~/.nvm/nvm.sh && npm install'", cwd="/home/user/my-app", timeout=90 ) # Configure Vite for E2B public URLs vite_config = """import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], server: { host: '0.0.0.0', port: 5173, strictPort: true, allowedHosts: ['.e2b.app', 'localhost'], hmr: { clientPort: 443 } } }) """ sbx.files.write("/home/user/my-app/vite.config.js", vite_config) # Start dev server in background sbx.commands.run( "bash -c 'source ~/.nvm/nvm.sh && npm run dev'", cwd="/home/user/my-app", background=True, timeout=0 ) time.sleep(10) # Wait for server startup # Get public URL host = sbx.get_host(5173) url = f"https://{host}" print(f"Server live at: {url}") print(f"Sandbox ID: {sbx.sandbox_id}") ``` -------------------------------- ### Run E2B Fundamental Examples Source: https://github.com/disler/agent-sandboxes/blob/main/README.md Execute the sequence of example scripts to learn E2B sandbox concepts. ```bash cd apps/sandbox_fundamentals uv sync # Run through all examples in order uv run python 01_basic_sandbox.py uv run python 01_basic_sandbox_keep_alive.py uv run python 02_list_files.py uv run python 03_file_operations.py uv run python 04_run_commands.py uv run python 05_environment_vars.py uv run python 06_background_commands.py uv run python 07_reuse_sandbox.py uv run python 08_pause_resume.py uv run python 09_claude_code_agent.py uv run python 10_install_packages.py uv run python 11_git_operations.py uv run python 12_custom_template_build.py uv run python 12_custom_template_reuse.py uv run python 13_expose_simple_webserver.py uv run python 13_expose_vite_vue_webserver.py ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Use 'uv sync' to install project dependencies in the 'apps/sandbox_workflows' directory. ```bash cd apps/sandbox_workflows && uv sync ``` -------------------------------- ### Data Science Workflow Example Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_mcp/README.md Example use case demonstrating a data science workflow: creating a sandbox, installing libraries, training a model, and downloading results. ```text "Create a sandbox, install scikit-learn, train a model, and download the results" ``` -------------------------------- ### Install in Claude Desktop Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_mcp/README.md Register the server with the Claude Desktop application. ```bash # Install for use with Claude Desktop uv run mcp install server.py # Or with custom name uv run mcp install server.py --name "E2B Sandboxes" ``` -------------------------------- ### Initialize E2B Sandbox Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/src/prompts/sandbox_fork_agent_w_github_token_system_prompt.md Setup the sandbox environment with the required template and environment variables. ```python mcp__e2b-sandbox__init_sandbox(template='agent-sandbox-dev-node22', timeout=SANDBOX_LIFETIME_IN_SECONDS, env_vars='GITHUB_TOKEN={github_token}') ``` -------------------------------- ### Install Node Packages with Bun Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Install Node.js packages using 'bun add' within the sandbox. Ensure Bun is installed first. ```bash # Install Node packages uv run sbx exec $SANDBOX_ID "/home/user/.bun/bin/bun add cowsay" ``` -------------------------------- ### Install Python Packages Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Install Python packages using 'uv pip install' within the sandbox. Ensure 'uv' is installed first. ```bash # Install Python packages uv run sbx exec $SANDBOX_ID "/home/user/.local/bin/uv pip install --system requests pydantic" ``` -------------------------------- ### Manage Development Server Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/src/prompts/sandbox_fork_agent_w_github_token_system_prompt.md Commands for installing dependencies, running the dev server, and retrieving the public host URL. ```bash # Install dependencies if needed npm install # or bun install # Start dev server in background npm run dev & # or bun run dev & # Wait for server to start sleep 10 ``` ```python # Get public URL for the exposed port result = mcp__e2b-sandbox__get_host(sandbox_id='', port=5173) # The result will contain the public URL like: https://xxxxx.e2b.app ``` -------------------------------- ### Install Sandbox Fork Dependencies Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/README.md Install the necessary dependencies for the sandbox workflows. Ensure you are in the correct directory. ```bash cd apps/sandbox_workflows uv sync ``` -------------------------------- ### Configure Claude Desktop for MCP Source: https://context7.com/disler/agent-sandboxes/llms.txt Setup steps to integrate the sandbox MCP server with the Claude Desktop application. ```bash # Copy MCP configuration cp .mcp.json.sandbox .mcp.json # Edit .mcp.json to add your E2B API key # Start Claude Code with MCP support claude # Check MCP server status /mcp ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Install the 'uv' Python package manager within the sandbox using a curl command and shell execution. ```bash # Install uv (Python package manager) uv run sbx exec $SANDBOX_ID "curl -LsSf https://astral.sh/uv/install.sh | sh" --shell --timeout 120 ``` -------------------------------- ### Install Bun JavaScript Runtime Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Install the Bun JavaScript runtime within the sandbox using a curl command and shell execution. ```bash # Install bun (JavaScript runtime) uv run sbx exec $SANDBOX_ID "curl -fsSL https://bun.sh/install | bash" --shell --timeout 120 ``` -------------------------------- ### Create Python Sandbox and Run Analysis Script Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_mcp/README.md Example use case for creating a Python sandbox to execute an analysis script. ```text "Create a Python sandbox and run my analysis script" ``` -------------------------------- ### Sandbox Workflows Project Setup Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Details on the `pyproject.toml` file for the sandbox workflows project, including dependencies and entry point. ```APIDOC ## Sandbox Workflows Project Setup ### Description This section details the project configuration for the sandbox workflows, focusing on the `pyproject.toml` file. ### `pyproject.toml` - **Project Configuration**: Uses UV for project management. - **Dependencies**: Includes `typer`, `rich`, `claude-agent-sdk`, `python-dotenv`. - **CLI Entry Point**: Defined as `obox = "src.main:app"`. ``` -------------------------------- ### Open Files with VSCode Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Example of using subprocess to open specified log paths with VSCode. ```python import subprocess # Assuming log_paths is a list of file paths # Example: log_paths = ['path/to/log1.log', 'path/to/log2.log'] subprocess.run(["code", *log_paths]) ``` -------------------------------- ### Execute Parallel Agent Experiments with obox Source: https://github.com/disler/agent-sandboxes/blob/main/README.md Setup and execution commands for running parallel agent workflows using the obox tool. ```bash cp .mcp.json apps/sandbox_agent_working_dir/.mcp.json (after you fill it out with your e2b api key) cp .env apps/sandbox_agent_working_dir/.env (after you fill it out with your credentials) cd apps/sandbox_workflows uv sync uv run obox --branch --model --prompt "your task" --forks 3 ``` -------------------------------- ### Install Packages in Sandbox Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Run package manager commands within the sandbox repository directory. ```python mcp__e2b__execute_command(command="npm install express", cwd="/home/user/repo") mcp__e2b__execute_command(command="pip install requests", cwd="/home/user/repo") ``` -------------------------------- ### Verify Project Structure Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Lists the recursive structure of the project's source directory to validate the project setup and file organization. This is a manual testing step. ```bash ls -R apps/sandbox_workflows/src/ ``` -------------------------------- ### List Node Packages with Bun Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md List installed Node.js packages within the sandbox using 'bun pm ls'. ```bash # List Node packages uv run sbx exec $SANDBOX_ID "/home/user/.bun/bin/bun pm ls" ``` -------------------------------- ### Test Typer CLI Help Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Verifies the help message for the `obox` Typer CLI application. This is part of the project setup and dependency verification. ```bash uv run obox --help ``` -------------------------------- ### Test Multiple Sandbox Forks Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Execute multiple sandbox forks for a repository with a specific prompt. This example uses three forks to find and summarize TODO comments. ```bash uv run obox sandbox-fork https://github.com/anthropics/anthropic-sdk-python \ --prompt "Find all TODO comments and summarize them" \ --forks 3 ``` -------------------------------- ### Run Sandbox Fork for Code Review and Documentation Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/README.md Executes a sandbox fork to perform code review, add documentation (JSDoc), and generate usage examples for a specified branch and prompt. Suitable for improving code quality and maintainability. ```bash uv run obox sandbox-fork https://github.com/myorg/myrepo \ --branch feature/new-api \ --prompt "Review the new API implementation, add JSDoc comments, and create usage examples" \ --forks 1 ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/README.md Initializes the .env file from the provided sample. ```bash cp .env.sample .env # Edit .env with your keys ``` -------------------------------- ### Environment Configuration Files Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Sample configuration for API keys and git ignore rules. ```text # Anthropic API Key for Claude Code agents ANTHROPIC_API_KEY=your_api_key_here # E2B API Key for sandbox management E2B_API_KEY=your_e2b_api_key_here ``` ```text .env __pycache__/ *.pyc .venv/ logs/ *.log .uv/ ``` -------------------------------- ### Main CLI Entry Point Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Initializes the Typer application and registers the sandbox-fork command. ```python # src/main.py """ Main CLI entry point for obox (sandbox workflows). """ import typer from rich.console import Console from . import commands # Initialize Typer app app = typer.Typer( name="obox", help="Orchestrated Sandbox Workflows - Multi-agent experimentation with E2B sandboxes", add_completion=False, ) # Initialize Rich console for pretty output console = Console() # Register commands app.command(name="sandbox-fork")(commands.sandbox_fork.sandbox_fork_command) if __name__ == "__main__": app() ``` -------------------------------- ### Initialize SandboxForkAgent Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Initializes the agent with fork details, repository information, user prompt, and logger. It loads the system prompt, builds the full prompt, and configures agent options including tool access, hooks, and working directory. ```python self.options = ClaudeAgentOptions( system_prompt=self.full_system_prompt, mcp_servers=str(MCP_CONFIG_PATH), # Path to .mcp.json allowed_tools=ALLOWED_TOOLS, disallowed_tools=DISALLOWED_TOOLS, hooks=hooks_dict, # Install all hooks permission_mode="acceptEdits", max_turns=DEFAULT_MAX_TURNS, cwd=str(WORKING_DIR), ) ``` -------------------------------- ### Get Sandbox Information Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Retrieve detailed information about a specific sandbox using its ID. ```bash # Get sandbox information uv run sbx sandbox info $SANDBOX_ID ``` -------------------------------- ### CLI Usage Tips Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Common commands for managing sandbox environments, file transfers, and execution flags. ```bash export SANDBOX_ID=$(cat .sandbox_id) ``` ```bash uv run sbx exec $SANDBOX_ID "cat file.txt | grep pattern" --shell ``` ```bash uv run sbx exec $SANDBOX_ID "git status" --cwd /home/user/repo ``` ```bash uv run sbx exec $SANDBOX_ID "apt-get install nginx" --root --timeout 300 ``` ```bash uv run sbx init --timeout 3600 # 1 hour ``` ```bash # Upload an image uv run sbx files upload $SANDBOX_ID ./local_image.png /home/user/image.png # Download generated PDF uv run sbx files download $SANDBOX_ID /home/user/report.pdf ./report.pdf ``` -------------------------------- ### Configure Sandbox Fork Environment Variables Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/README.md Copy the sample environment file and fill in your API keys. This is required for the tool to authenticate with external services. ```bash cp .env.sample .env ``` -------------------------------- ### Execute complex multi-step operations Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Illustrates initializing a sandbox with a template, creating directory structures, and running multi-command shell operations. ```bash # Initialize with template uv run sbx init --template claude-code --env PROJECT=myapp export SANDBOX_ID=$(cat .sandbox_id) # Create project structure uv run sbx files mkdir $SANDBOX_ID /home/user/myapp uv run sbx files mkdir $SANDBOX_ID /home/user/myapp/src # Install dependencies and run tests (combined operation) uv run sbx exec $SANDBOX_ID " cd /home/user/myapp && python -m venv venv && source venv/bin/activate && pip install pytest && pytest --version " --shell --timeout 300 # Background task uv run sbx exec $SANDBOX_ID "python server.py" --background --cwd /home/user/myapp # Clean up uv run sbx sandbox kill $SANDBOX_ID ``` -------------------------------- ### Run Sandbox Fork with Prompt from File Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/README.md Provide the agent's prompt from a local markdown file. This is useful for longer or more complex prompts. ```bash uv run obox sandbox-fork https://github.com/user/repo \ --prompt ./prompts/my-experiment.md \ --forks 3 ``` -------------------------------- ### Get File Information in Sandbox Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Retrieve information about a file in the sandbox, such as size, modification time, etc. ```bash # Get file info uv run sbx files info $SANDBOX_ID /home/user/test.txt ``` -------------------------------- ### List Python Packages Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md List installed Python packages within the sandbox using 'uv pip list'. ```bash # List Python packages uv run sbx exec $SANDBOX_ID "/home/user/.local/bin/uv pip list" ``` -------------------------------- ### Project Structure Overview Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_mcp/README.md This shows the basic file structure for the sandbox MCP server implementation. ```text apps/sandbox_mcp/ ├── server.py # Main MCP server implementation ├── pyproject.toml # Project dependencies and metadata └── README.md # This file ``` -------------------------------- ### Create Sandbox Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Create a new sandbox, optionally specifying a template and timeout. The default template is 'base'. ```bash # Create a new sandbox uv run sbx sandbox create --template base --timeout 600 ``` -------------------------------- ### Use /wf_plan_build Slash Command Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/README.md Execute a complete plan-and-build workflow for a user-specified task. This command first generates a plan and then implements it. ```bash # Using /wf_plan_build for complete workflow uv run obox sandbox-fork https://github.com/user/repo \ --prompt "/wf_plan_build Add user authentication with JWT tokens" \ --forks 3 ``` -------------------------------- ### Create and execute a Python script Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Demonstrates writing a Python script to a sandbox, executing it, and terminating the sandbox. ```bash uv run sbx files write $SANDBOX_ID /home/user/scraper.py " import requests from bs4 import BeautifulSoup response = requests.get('https://example.com') soup = BeautifulSoup(response.content, 'html.parser') print(soup.title.string) " # Run the script uv run sbx exec $SANDBOX_ID "python3 /home/user/scraper.py" # Clean up uv run sbx sandbox kill $SANDBOX_ID ``` -------------------------------- ### Sandbox CLI: Initialize and Create Sandboxes Source: https://context7.com/disler/agent-sandboxes/llms.txt Commands for initializing and creating sandboxes using the Sandbox CLI. Supports custom templates, environment variables, timeouts, and auto-pause. ```bash # Initialize a new sandbox with default template uv run python src/main.py init ``` ```bash # Create sandbox with custom template and environment variables uv run python src/main.py init \ --template agent-sandbox-dev-node22 \ --env API_KEY=secret \ --timeout 3600 ``` ```bash # Create sandbox with advanced options uv run python src/main.py sandbox create \ --template agent-sandbox-dev-node22 \ --timeout 600 \ --env DEBUG=true \ --auto-pause ``` ```bash # Connect to existing sandbox uv run python src/main.py sandbox connect ``` ```bash # Check sandbox status uv run python src/main.py sandbox status ``` ```bash # Get sandbox information uv run python src/main.py sandbox info ``` ```bash # List all running sandboxes uv run python src/main.py sandbox list --limit 20 ``` ```bash # Kill a sandbox uv run python src/main.py sandbox kill ``` -------------------------------- ### Upload and Process CSV Files with Pandas Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_mcp/README.md Example use case for uploading CSV files and processing them using the pandas library within a sandbox. ```text "Upload these CSV files and process them with pandas" ``` -------------------------------- ### Configure and Run MCP Server with Claude Desktop Source: https://github.com/disler/agent-sandboxes/blob/main/README.md Commands to initialize the MCP configuration and interact with the sandbox agent via Claude Desktop. ```bash # cp the .mcp.json.sandbox to .mcp.json cp .mcp.json.sandbox .mcp.json # replace your e2b api key in the .mcp.json env section ... # Start a claude code agent with the .mcp.json claude # Check the mcp server status /mcp # Prompt the same commands as you would with the sandbox_cli with natural language prompt: What can we do with the e2b sandbox tools? prompt: init a new sandbox prompt: create a sandbox with custom template agent-sandbox-dev-node22 prompt: run ls -la in the sandbox prompt: search for all .py files in the sandbox with exec # Run custom slash commands prompt: /plan Add buttons to the nav bar that auto scroll to respective sections on the landing page prompt: /build prompt: /wf_plan_build Add buttons to the nav bar that auto scroll to respective sections on the landing page ``` -------------------------------- ### Execute Command in Sandbox Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/src/prompts/sandbox_fork_agent_system_prompt.md Use to run arbitrary commands within the sandbox environment, such as Git commands or package installations. Specify the working directory (cwd) if needed. ```python mcp__e2b-sandbox__execute_command(command="git status", cwd="DEFAULT_REPO_DIR") ``` ```python mcp__e2b-sandbox__execute_command(command="git add .", cwd="DEFAULT_REPO_DIR") ``` ```python mcp__e2b-sandbox__execute_command(command="git commit -m 'message'", cwd="DEFAULT_REPO_DIR") ``` ```python mcp__e2b-sandbox__execute_command(command="npm install express", cwd="DEFAULT_REPO_DIR") ``` ```python mcp__e2b-sandbox__execute_command(command="pip install requests", cwd="DEFAULT_REPO_DIR") ``` -------------------------------- ### Use /plan Slash Command Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/README.md Generate a detailed implementation plan for a user-specified task. The plan is saved to the `specs/` directory. ```bash # Using /plan in a prompt uv run obox sandbox-fork https://github.com/user/repo \ --prompt "/plan Add user authentication with JWT tokens" ``` -------------------------------- ### Get Public URL for Exposed Port Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/src/prompts/sandbox_fork_agent_system_prompt.md Retrieves the public URL for a service running on a specific port within the sandbox. This is essential for accessing web applications hosted in the sandbox. ```python # Get public URL for the exposed port result = mcp__e2b-sandbox__get_host(sandbox_id='', port=5173) # The result will contain the public URL like: https://xxxxx.e2b.app ``` -------------------------------- ### MCP Server - Sandbox Management Tools Source: https://context7.com/disler/agent-sandboxes/llms.txt Python code for the MCP server to manage E2B sandboxes, including initialization, command execution, file listing, writing files, and getting host URLs. ```APIDOC ## Initialize a new sandbox ### Description Initializes a new E2B sandbox with optional template, timeout, and environment variables. ### Method `POST` (via MCP tool) ### Endpoint `/init_sandbox` ### Parameters #### Query Parameters - **template** (string) - Optional - The sandbox template to use. - **timeout** (integer) - Optional - The timeout for the sandbox in seconds (default: 300). - **env_vars** (string) - Optional - Comma-separated environment variables (e.g., "VAR1=value1,VAR2=value2"). ### Request Example ```json { "template": "agent-sandbox-dev-node22", "timeout": 600, "env_vars": "API_KEY=abcdef123,DEBUG=true" } ``` ### Response #### Success Response (200) - **result** (dict) - The result of the sandbox initialization. ## Execute a command in the sandbox ### Description Executes a command within a specified sandbox. ### Method `POST` (via MCP tool) ### Endpoint `/execute_command` ### Parameters #### Path Parameters - **sandbox_id** (string) - Required - The ID of the sandbox. - **command** (string) - Required - The command to execute. #### Query Parameters - **cwd** (string) - Optional - The current working directory for the command. - **root** (boolean) - Optional - Whether to run the command as root (default: false). - **timeout** (integer) - Optional - The timeout for the command in seconds (default: 60). - **background** (boolean) - Optional - Whether to run the command in the background (default: false). ### Request Example ```json { "sandbox_id": "your_sandbox_id", "command": "ls -la", "cwd": "/app", "timeout": 120, "background": true } ``` ### Response #### Success Response (200) - **result** (dict) - The result of the command execution. ## List files in sandbox directory ### Description Lists files and directories within a specified path in the sandbox. ### Method `POST` (via MCP tool) ### Endpoint `/list_files` ### Parameters #### Path Parameters - **sandbox_id** (string) - Required - The ID of the sandbox. #### Query Parameters - **path** (string) - Optional - The directory path to list (default: "/"). - **depth** (integer) - Optional - The depth of directory traversal (default: 1). ### Request Example ```json { "sandbox_id": "your_sandbox_id", "path": "/home/user", "depth": 2 } ``` ### Response #### Success Response (200) - **result** (dict) - A dictionary containing file and directory information. ## Write file to sandbox ### Description Writes text content to a file in the sandbox. ### Method `POST` (via MCP tool) ### Endpoint `/write_file` ### Parameters #### Path Parameters - **sandbox_id** (string) - Required - The ID of the sandbox. - **path** (string) - Required - The path to the file within the sandbox. #### Request Body - **content** (string) - Required - The text content to write to the file. ### Request Example ```json { "sandbox_id": "your_sandbox_id", "path": "/app/config.json", "content": "{\"setting\": \"value\"}" } ``` ### Response #### Success Response (200) - **result** (dict) - The result of the file write operation. ## Get public URL for exposed sandbox port ### Description Retrieves the public URL for a specific port exposed by the sandbox. ### Method `POST` (via MCP tool) ### Endpoint `/get_host` ### Parameters #### Path Parameters - **sandbox_id** (string) - Required - The ID of the sandbox. - **port** (integer) - Required - The port number to get the URL for. ### Request Example ```json { "sandbox_id": "your_sandbox_id", "port": 8080 } ``` ### Response #### Success Response (200) - **result** (dict) - A dictionary containing the public URL and port. ``` -------------------------------- ### Run Basic Sandbox Fork Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/README.md Execute a single sandbox fork for a given repository URL and prompt. This is the most basic usage scenario. ```bash uv run obox sandbox-fork https://github.com/user/repo --prompt "Add unit tests to all functions" ``` -------------------------------- ### Initialize E2B Sandbox Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/src/prompts/sandbox_fork_agent_system_prompt.md Initializes a new E2B sandbox with a specified template and timeout. The GITHUB_TOKEN environment variable should be set. ```python mcp__e2b-sandbox__init_sandbox(template='base', timeout=SANDBOX_LIFETIME_IN_SECONDS) ``` -------------------------------- ### Sandbox CLI: File Operations Source: https://context7.com/disler/agent-sandboxes/llms.txt Commands for managing files and directories within a sandbox using the Sandbox CLI. Supports listing, reading, writing, checking existence, getting info, creating directories, moving, and removing files. ```bash # List files in directory uv run python src/main.py files ls $SANDBOX_ID /home/user uv run python src/main.py files ls $SANDBOX_ID /home/user --depth 2 ``` ```bash # Read file content uv run python src/main.py files read $SANDBOX_ID /home/user/config.json ``` ```bash # Write content to file uv run python src/main.py files write $SANDBOX_ID /tmp/test.txt "Hello World" ``` ```bash # Check if file exists uv run python src/main.py files exists $SANDBOX_ID /home/user/app.py ``` ```bash # Get file information uv run python src/main.py files info $SANDBOX_ID /home/user/app.py ``` ```bash # Create directory uv run python src/main.py files mkdir $SANDBOX_ID /home/user/new_project ``` ```bash # Move/rename files uv run python src/main.py files mv $SANDBOX_ID /tmp/old.txt /tmp/new.txt ``` ```bash # Remove files uv run python src/main.py files rm $SANDBOX_ID /tmp/test.txt ``` -------------------------------- ### Run Project Tests Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_workflows/README.md Executes the test suite using uv. ```bash uv run pytest ``` -------------------------------- ### Create Sandbox with Custom Environment Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Create a new sandbox with custom environment variables set for its runtime. ```bash # Create sandbox with custom environment uv run sbx sandbox create --env API_KEY=secret --env DEBUG=true ``` -------------------------------- ### MCP Server - Claude Desktop Integration Source: https://context7.com/disler/agent-sandboxes/llms.txt Instructions for setting up and using MCP with Claude Desktop for natural language control of sandboxes. ```APIDOC ## MCP Server Setup and Usage with Claude Desktop ### Description This section outlines the steps to configure and integrate the MCP server with Claude Desktop for seamless sandbox management using natural language commands. ### Setup Steps 1. **Copy MCP Configuration:** ```bash cp .mcp.json.sandbox .mcp.json ``` 2. **Add E2B API Key:** Edit the `.mcp.json` file and add your E2B API key. 3. **Start Claude Code with MCP Support:** ```bash claude ``` ### Checking MCP Server Status Send a request to the `/mcp` endpoint to check the server status. ### Natural Language Commands Examples - Initialize a new sandbox - Create a sandbox with template agent-sandbox-dev-node22 - Run ls -la in the sandbox - Search for all .py files in the sandbox with exec - Write a Python script to /home/user/app.py - Get the public URL for port 5173 ``` -------------------------------- ### Initialize a New Sandbox Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Initialize a new sandbox, optionally specifying a template, timeout, or environment variables. The sandbox ID is saved to '.sandbox_id'. ```bash # Create a new sandbox and save the ID uv run sbx init # Set the sandbox ID as an environment variable export SANDBOX_ID=$(cat .sandbox_id) # Create with a custom template uv run sbx init --template claude-code --timeout 900 # Create with environment variables uv run sbx init --env API_KEY=secret --env DEBUG=true ``` -------------------------------- ### Initialize MCP Server for Sandbox Management Source: https://context7.com/disler/agent-sandboxes/llms.txt Define tools for sandbox lifecycle and execution using the FastMCP framework. ```python # MCP Server setup (server.py) from mcp.server.fastmcp import FastMCP mcp = FastMCP( "E2B Sandbox Manager", instructions="Manage E2B sandboxes for isolated code execution." ) @mcp.tool() def init_sandbox( template: str = None, timeout: int = 300, env_vars: str = None, ) -> dict: """Initialize a new E2B sandbox.""" args = ["init", "--timeout", str(timeout)] if template: args.extend(["--template", template]) if env_vars: for env_pair in env_vars.split(","): args.extend(["--env", env_pair.strip()]) return run_sbx_cli(*args) @mcp.tool() def execute_command( sandbox_id: str, command: str, cwd: str = None, root: bool = False, timeout: int = 60, background: bool = False, ) -> dict: """Execute a command in the sandbox.""" args = ["exec", sandbox_id, command] if cwd: args.extend(["--cwd", cwd]) if root: args.append("--root") args.extend(["--timeout", str(timeout)]) if background: args.append("--background") return run_sbx_cli(*args) @mcp.tool() def list_files(sandbox_id: str, path: str = "/", depth: int = 1) -> dict: """List files in sandbox directory.""" return run_sbx_cli("files", "ls", sandbox_id, path, "--depth", str(depth)) @mcp.tool() def write_file(sandbox_id: str, path: str, content: str) -> dict: """Write text content to a file in the sandbox.""" return run_sbx_cli("files", "write", sandbox_id, path, content) @mcp.tool() def get_host(sandbox_id: str, port: int) -> dict: """Get public URL for exposed sandbox port.""" return run_sbx_cli("sandbox", "get-host", sandbox_id, "--port", str(port)) if __name__ == "__main__": mcp.run() ``` -------------------------------- ### Upload and Download Files via CLI Source: https://context7.com/disler/agent-sandboxes/llms.txt Use these commands to transfer files between your local machine and an E2B sandbox. ```bash uv run python src/main.py files upload $SANDBOX_ID ./local_file.py /home/user/remote.py ``` ```bash uv run python src/main.py files download $SANDBOX_ID /home/user/output.txt ./local_output.txt ``` -------------------------------- ### Create PreCompact logging hook Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Logs context window compaction events. ```python def create_pre_compact_hook(logger: ForkLogger): """ Create PreCompact hook for logging context compaction. Args: logger: Fork logger instance Returns: Hook callback function """ async def pre_compact_hook( input_data: Dict[str, Any], tool_use_id: Optional[str], context: Any ) -> Dict[str, Any]: """ PreCompact hook - logs before context window compaction. Args: input_data: Dict with 'tokens_before' tool_use_id: None for this hook context: Hook context Returns: Empty dict """ ``` -------------------------------- ### Manage Sandboxes via CLI Source: https://github.com/disler/agent-sandboxes/blob/main/README.md Use the sandbox CLI to initialize, create, and interact with isolated sandbox environments. ```bash cd apps/sandbox_cli uv sync # Get help uv run python src/main.py --help # Initialize a new sandbox uv run python src/main.py init # Create a sandbox with custom template (this is an e2b sandbox template - you can create this by running the `uv run python 12_custom_template_build.py` script) uv run python src/main.py sandbox create --template agent-sandbox-dev-node22 # Execute a command in a sandbox uv run python src/main.py exec "ls -la" # List files in a sandbox uv run python src/main.py files ls / ``` -------------------------------- ### Download File from Sandbox Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Download a file from the sandbox to your local machine. Supports binary files. ```bash # Download a file (binary support) uv run sbx files download $SANDBOX_ID /home/user/output.pdf /path/to/local/output.pdf ``` -------------------------------- ### Configure Environment and MCP Source: https://context7.com/disler/agent-sandboxes/llms.txt Defines required API keys and MCP server configuration for sandbox operations. ```bash # .env file in project root E2B_API_KEY=your_e2b_api_key_here ANTHROPIC_API_KEY=your_anthropic_api_key_here GITHUB_TOKEN=your_github_token_here # Optional: for git push/PR functionality # .mcp.json configuration for MCP server { "mcpServers": { "e2b-sandbox": { "command": "uv", "args": ["run", "python", "apps/sandbox_mcp/server.py"], "env": { "E2B_API_KEY": "${E2B_API_KEY}" } } } } ``` -------------------------------- ### Test Single Sandbox Fork Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Run a single sandbox fork for a given GitHub repository using 'uv run obox sandbox-fork'. Includes a prompt for analysis and specifies one fork. ```bash uv run obox sandbox-fork https://github.com/anthropics/anthropic-sdk-python \ --prompt "Analyze the project structure and list all main modules" \ --forks 1 ``` -------------------------------- ### Create Directory in Sandbox Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Create a new directory at the specified path within the sandbox. ```bash # Create directory uv run sbx files mkdir $SANDBOX_ID /home/user/mydir ``` -------------------------------- ### Define Configuration Constants Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Defines project paths, default values, and tool configurations for the sandbox-fork CLI. Ensure the directory structure matches the path calculations used here. ```python # src/modules/constants.py """ Configuration constants for sandbox-fork CLI. """ from pathlib import Path from typing import Final # === Project Paths === # Root directory of the sandbox_workflows project PROJECT_ROOT: Final[Path] = Path(__file__).parent.parent.parent # Working directory for agent execution (base directory) WORKING_DIR: Final[Path] = PROJECT_ROOT.parent / "sandbox_agent_working_dir" # Temp directory for local file operations (hooks enforce this restriction) TEMP_DIR: Final[Path] = WORKING_DIR / "temp" # Log directory for fork execution logs (separate from temp/) LOG_DIR: Final[Path] = WORKING_DIR / "logs" # MCP server configuration path (relative to agent-sandboxes root) MCP_CONFIG_PATH: Final[Path] = WORKING_DIR / ".mcp.json" # System prompt file path SYSTEM_PROMPT_PATH: Final[Path] = PROJECT_ROOT / "src" / "prompts" / "sandbox_fork_agent_system_prompt.md" # === Default Values === # Default number of forks to create DEFAULT_FORKS: Final[int] = 1 # Maximum number of forks allowed MAX_FORKS: Final[int] = 100 # Default sandbox timeout in seconds (5 minutes) DEFAULT_SANDBOX_TIMEOUT: Final[int] = 300 # Default agent max turns DEFAULT_MAX_TURNS: Final[int] = 100 # Default sandbox template DEFAULT_TEMPLATE: Final[str] = "base" # === Tools Configuration === ``` -------------------------------- ### Verify Log Files Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md List the contents of the log directory within the sandbox agent working directory to verify log file creation. ```bash ls -lh ../sandbox_agent_working_dir/logs/ ``` -------------------------------- ### Compare specialized vs unified interface Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_cli/README.md Highlights the transition from specialized command groups to a unified execution interface. ```bash # Multiple command groups, each with specific syntax sbx cmd run $ID "echo hello" sbx packages install-uv $ID sbx packages uv $ID --system requests sbx git clone $ID https://... /path sbx git status $ID /path ``` ```bash # One powerful command with composable flags sbx exec $ID "echo hello" sbx exec $ID "curl ... | sh" --shell --timeout 120 sbx exec $ID "uv pip install --system requests" sbx exec $ID "git clone https://... /path" sbx exec $ID "git status" --cwd /path ``` -------------------------------- ### Test with MCP Inspector Source: https://github.com/disler/agent-sandboxes/blob/main/apps/sandbox_mcp/README.md Launch the server in the MCP Inspector for interactive testing and tool validation. ```bash # Test the server interactively uv run mcp dev server.py ``` -------------------------------- ### Add Dependencies Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Commands to add necessary dependencies to the 'apps/sandbox_workflows' project using 'uv add'. ```bash # In apps/sandbox_workflows/ uv add typer[all] rich claude-agent-sdk python-dotenv e2b ``` -------------------------------- ### Test Sandbox Fork Command Help Source: https://github.com/disler/agent-sandboxes/blob/main/specs/sandbox-fork-cli-implementation.md Verifies the help message for the `sandbox-fork` subcommand within the `obox` Typer CLI application. This ensures the command and its arguments are correctly exposed. ```bash uv run obox sandbox-fork --help ```