Skip to main content
Give your AI assistant superpowers with secure, isolated code execution through the Model Context Protocol (MCP). The Hopx MCP server enables Claude, Cursor, and other AI assistants to execute Python, JavaScript, Bash, and Go code in blazing-fast (0.1s startup), isolated cloud containers.
MCP is a protocol that allows AI assistants to interact with external tools and services. The Hopx MCP server provides a standardized way for AI assistants to execute code safely in isolated environments.

Quick Start

The easiest way to get started:
  1. Install the MCP server: uvx hopx-mcp
  2. Get your API key from hopx.ai
  3. Configure your IDE with the MCP server
  4. Your AI assistant can now execute code safely

Installation

Install the Hopx MCP server using uvx:
uvx hopx-mcp
You need Python 3.14+ and uvx installed. Get uvx from uv’s documentation.

Get Your API Key

Sign up at hopx.ai to get your free API key. You’ll need this to configure the MCP server.

Configuration

After installing with uvx hopx-mcp, configure your IDE by adding the MCP server configuration:
  • Cursor
  • VS Code
  • Claude Desktop
  • Windsurf
  • Other IDEs
Add to .cursor/mcp.json in your project or workspace:
{
  "mcpServers": {
    "hopx-sandbox": {
      "command": "uvx",
      "args": ["hopx-mcp"],
      "env": {
        "HOPX_API_KEY": "your-api-key-here"
      }
    }
  }
}
Replace your-api-key-here with your actual API key from hopx.ai.

Usage Examples

Once configured, your AI assistant can execute code directly. Here’s what it looks like:

Python Data Analysis

You: “Analyze this sales data: [100, 150, 200, 180, 220]” Claude: Uses execute_code_isolated() to run:
import pandas as pd
import numpy as np

sales = [100, 150, 200, 180, 220]
df = pd.DataFrame({'sales': sales})

print(f"Mean: ${df['sales'].mean():.2f}")
print(f"Median: ${df['sales'].median():.2f}")
print(f"Growth: {((sales[-1] - sales[0]) / sales[0] * 100):.1f}%")
Output:
Mean: $170.00
Median: $180.00
Growth: 120.0%

JavaScript Computation

You: “Calculate fibonacci numbers up to 100” Claude: Executes:
function fibonacci(max) {
  const fib = [0, 1];
  while (true) {
    const next = fib[fib.length - 1] + fib[fib.length - 2];
    if (next > max) break;
    fib.push(next);
  }
  return fib;
}

console.log(fibonacci(100));
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Primary Tool: execute_code_isolated()

The recommended way to execute code. Creates a sandbox, runs your code, returns output, and auto-destroys. Parameters:
  • code (required): Code to execute
  • language (optional): 'python', 'javascript', 'bash', or 'go' (default: 'python')
  • timeout (optional): Max execution time in seconds (default: 30, max: 300)
  • env (optional): Environment variables as a dictionary
  • template_name (optional): Template to use (default: 'code-interpreter')
  • region (optional): Deployment region (e.g., 'us-east', 'eu-west')
Returns:
{
  "stdout": "Hello, World!\n",
  "stderr": "",
  "exit_code": 0,
  "execution_time": 0.123,
  "sandbox_id": "1762778786mxaco6r2",
  "_note": "Sandbox will auto-destroy after 10 minutes"
}

Advanced: Persistent Sandboxes

For multi-step workflows where you need to maintain state:
  1. Create a long-lived sandbox:
    sandbox = create_sandbox(
        template_id='20',  # Get ID from get_template('code-interpreter')
        timeout_seconds=3600,
        internet_access=True
    )
    
  2. Extract connection details:
    vm_url = sandbox['direct_url']
    auth_token = sandbox['auth_token']
    
  3. Run multiple commands:
    execute_code(vm_url, 'import pandas as pd', auth_token=auth_token)
    execute_code(vm_url, 'df = pd.read_csv("data.csv")', auth_token=auth_token)
    result = execute_code(vm_url, 'print(df.head())', auth_token=auth_token)
    
  4. File operations:
    file_write(vm_url, '/workspace/output.txt', 'results', auth_token=auth_token)
    content = file_read(vm_url, '/workspace/output.txt', auth_token=auth_token)
    
  5. Clean up when done:
    delete_sandbox(sandbox['id'])
    

Available Tools

The MCP server exposes 30+ tools for complete control:

Sandbox Management

  • create_sandbox() - Create a new sandbox
  • list_sandboxes() - List all your sandboxes
  • get_sandbox() - Get sandbox details
  • delete_sandbox() - Terminate a sandbox
  • update_sandbox_timeout() - Extend runtime
  • resume_sandbox() - Resume a paused sandbox

Code Execution

  • execute_code_isolated() - ⭐ Primary method (one-shot)
  • execute_code() - Execute in existing sandbox
  • execute_code_rich() - Capture matplotlib plots, DataFrames
  • execute_code_background() - Long-running tasks (5-30 min)
  • execute_code_async() - Very long tasks with webhooks (30+ min)

File Operations

  • file_read(), file_write(), file_list()
  • file_exists(), file_remove(), file_mkdir()

Process Management

  • list_processes() - All system processes
  • execute_list_processes() - Background executions
  • execute_kill_process() - Terminate process

Environment & System

  • env_set(), env_get(), env_clear() - Manage env vars
  • get_system_metrics() - CPU, memory, disk usage
  • run_command() - Execute shell commands

Templates

  • list_templates() - Browse available templates
  • get_template() - Get template details

Best Practices

For quick code execution, use execute_code_isolated(). It handles sandbox creation, execution, and cleanup automatically:
result = execute_code_isolated(
    code='print("Hello, World!")',
    language='python',
    timeout=30
)
This is perfect for:
  • Quick data analysis
  • Code testing
  • Package installation checks
  • One-off computations
For workflows requiring multiple operations, create a persistent sandbox:
sandbox = create_sandbox(template_id='20', timeout_seconds=3600)
vm_url = sandbox['direct_url']
auth_token = sandbox['auth_token']

# Multiple operations in same sandbox
execute_code(vm_url, 'import pandas as pd', auth_token=auth_token)
execute_code(vm_url, 'df = pd.read_csv("data.csv")', auth_token=auth_token)
result = execute_code(vm_url, 'print(df.head())', auth_token=auth_token)

# Clean up
delete_sandbox(sandbox['id'])
This maintains state between executions and is more efficient for complex workflows.
Always check execution results:
result = execute_code_isolated(code='...')

if result.get('exit_code') == 0:
    return result['stdout']
else:
    return f"Error: {result.get('stderr', 'Unknown error')}"
Use timeouts to prevent infinite loops or long-running code:
# Quick tasks
execute_code_isolated(code='...', timeout=30)

# Longer computations
execute_code_isolated(code='...', timeout=300)  # max 300s

# For very long tasks, use background execution
execute_code_background(vm_url, code='...', timeout=1800)
Pass sensitive data via environment variables:
result = execute_code_isolated(
    code='import os; print(os.getenv("API_KEY"))',
    env={'API_KEY': 'secret-123'}
)
Never hardcode secrets in code strings.

Production Example

Complete MCP server integration example:
# Example: How the MCP server uses Hopx API
import httpx
import os

BASE_URL = os.getenv("HOPX_BASE_URL", "https://api.hopx.dev")
API_KEY = os.getenv("HOPX_API_KEY")

def execute_code_isolated(code: str, language: str = "python", timeout: int = 30):
    """Execute code in an isolated sandbox (MCP tool implementation)"""
    
    # 1. Get template
    with httpx.Client(base_url=BASE_URL, timeout=30.0) as client:
        template_resp = client.get(
            f"/v1/templates/code-interpreter",
            headers={"X-API-Key": API_KEY}
        )
        template = template_resp.json()
        template_id = template["id"]
        
        # 2. Create sandbox
        sandbox_resp = client.post(
            "/v1/sandboxes",
            json={"template_id": template_id, "timeout_seconds": 600},
            headers={"X-API-Key": API_KEY}
        )
        sandbox = sandbox_resp.json()
        
        vm_url = sandbox["direct_url"]
        auth_token = sandbox["auth_token"]
        
        # 3. Wait for VM initialization
        import time
        time.sleep(3)
        
        # 4. Execute code
        execute_resp = client.post(
            f"https://{vm_url}/execute",
            json={"code": code, "language": language, "timeout": timeout},
            headers={"Authorization": f"Bearer {auth_token}"},
            timeout=60.0
        )
        result = execute_resp.json()
        
        # 5. Return result (sandbox auto-destroys after timeout)
        result["sandbox_id"] = sandbox["id"]
        return result

# Usage in MCP server
@mcp.tool()
def execute_code_isolated(code: str, language: str = "python", timeout: int = 30):
    """Execute code in isolated sandbox"""
    return execute_code_isolated(code, language, timeout)

Troubleshooting

”401 Unauthorized” Error

Cause: API key not set or invalid. Solution:
# Verify your API key is set
echo $HOPX_API_KEY

# Or check your IDE config file
# See Configuration section for your IDE

“Template not found” Error

Cause: Invalid template name. Solution: Use the default code-interpreter template or list available templates:
templates = list_templates(limit=20)

Slow First Execution

Cause: Cold start - container is being created. Why it happens: The first execution needs to:
  1. Create the container (~0.1ms)
  2. Wait for VM auth init (~3 seconds)
  3. Execute your code
Solution: Subsequent executions in the same sandbox are instant. For frequently-used environments, consider creating a persistent sandbox.

Execution Timeout

Cause: Code took longer than the timeout limit. Solution: Increase timeout or use background execution:
# Increase timeout
execute_code_isolated(code='...', timeout=300)  # max 300s

# Or use background for long tasks
proc = execute_code_background(vm_url, code='...', timeout=1800)

Next Steps