Python Sandbox MCP server

Provides a secure sandbox environment for executing Python code within isolated Docker containers, enabling safe code testing with resource limits, package installation, and file operations through a RESTful API.
Back to servers
Setup instructions
Provider
Johan Li
Release date
Apr 16, 2025
Language
Python
Stats
17 stars

MCP Sandbox is an interactive Python code execution tool that enables users and language models to safely run Python code and install packages in isolated Docker containers. It provides a secure environment for code execution through containerization while offering package management capabilities and file generation support.

Installation

To set up the MCP Sandbox on your local machine:

# Clone the repository
git clone https://github.com/JohanLi233/python-mcp-sandbox.git
cd python-mcp-sandbox

uv venv
uv sync

# Start the server
uv run main.py

The server starts with the default SSE endpoint at http://localhost:8000/sse, which you can access via the MCP Inspector or any client that supports SSE connections.

Features

  • Docker Isolation: Run Python code securely in isolated Docker containers
  • Package Management: Install and manage Python packages within sandboxes
  • File Generation: Create files within the sandbox and access them via web links

Available Tools

Sandbox Management

Creating and Listing Sandboxes

# Create a new sandbox
create_sandbox()  # Returns a sandbox_id for future operations

# List existing sandboxes
list_sandboxes()  # Returns a list of available sandbox IDs

Code Execution

# Execute Python code in a sandbox
execute_python_code(sandbox_id="your_sandbox_id", code="print('Hello, World!')")

Package Management

# Install a package in a sandbox
install_package_in_sandbox(sandbox_id="your_sandbox_id", package_name="pandas")

# Check installation status
check_package_installation_status(sandbox_id="your_sandbox_id", package_name="pandas")

Terminal Commands

# Execute terminal commands in a sandbox
execute_terminal_command(sandbox_id="your_sandbox_id", command="ls -la")

File Operations

# Upload a file to a sandbox
upload_file_to_sandbox(
    sandbox_id="your_sandbox_id", 
    local_file_path="/path/to/file.csv", 
    dest_path="/app/results"  # Optional, defaults to /app/results
)

Usage Examples

Basic Workflow

  1. First, check for available sandboxes or create a new one:
# List existing sandboxes
sandboxes = list_sandboxes()

# If no sandboxes exist, create a new one
if not sandboxes:
    sandbox_response = create_sandbox()
    sandbox_id = sandbox_response["sandbox_id"]
else:
    sandbox_id = sandboxes[0]
  1. Install necessary packages:
# Install pandas and matplotlib
install_package_in_sandbox(sandbox_id=sandbox_id, package_name="pandas")
install_package_in_sandbox(sandbox_id=sandbox_id, package_name="matplotlib")

# Check installation status
pandas_status = check_package_installation_status(sandbox_id=sandbox_id, package_name="pandas")
matplotlib_status = check_package_installation_status(sandbox_id=sandbox_id, package_name="matplotlib")
  1. Execute Python code:
code = """
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Create sample data
data = {'x': np.random.rand(100), 'y': np.random.rand(100)}
df = pd.DataFrame(data)

# Save data to CSV
df.to_csv('/app/results/data.csv', index=False)

# Create and save a plot
plt.figure(figsize=(10, 6))
plt.scatter(df['x'], df['y'])
plt.title('Random Scatter Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.savefig('/app/results/scatter_plot.png')
# Note: Do not use plt.show() as it won't work in the sandbox

print("Data and plot generated successfully!")
"""

result = execute_python_code(sandbox_id=sandbox_id, code=code)
  1. Access the results:
# Result will contain stdout, stderr and any file_links to generated files
print("Output:", result["stdout"])
print("Errors:", result["stderr"])
print("Generated Files:", result["file_links"])

MCP Integration

Example Config for Local Server

{
  "mcpServers": {
    "mcpSandbox": {
      "command": "npx",
      "args": ["-y", "supergateway", "--sse", "http://localhost:8000/sse"]
    }
  }
}

Example Config for Online Demo

{
  "mcpServers": {
    "mcpSandbox": {
      "command": "npx",
      "args": ["-y", "supergateway", "--sse", "http://115.190.87.78/sse?api_key=<API_KEY>"]
    }
  }
}

Best Practices

  1. When generating visualizations, don't use plt.show(). Instead use:

    • plt.savefig() to save figures to files
    • df.to_csv() or df.to_excel() to save data
  2. All files should be saved to the /app/results directory to be accessible via links

  3. Always check for existing sandboxes before creating new ones to efficiently manage resources

  4. After installing packages, verify their installation status before using them in your code

How to install this MCP server

For Claude Code

To add this MCP server to Claude Code, run this command in your terminal:

claude mcp add-json "mcpSandbox" '{"command":"npx","args":["-y","supergateway","--sse","http://localhost:8000/sse"]}'

See the official Claude Code MCP documentation for more details.

For Cursor

There are two ways to add an MCP server to Cursor. The most common way is to add the server globally in the ~/.cursor/mcp.json file so that it is available in all of your projects.

If you only need the server in a single project, you can add it to the project instead by creating or adding it to the .cursor/mcp.json file.

Adding an MCP server to Cursor globally

To add a global MCP server go to Cursor Settings > Tools & Integrations and click "New MCP Server".

When you click that button the ~/.cursor/mcp.json file will be opened and you can add your server like this:

{
    "mcpServers": {
        "mcpSandbox": {
            "command": "npx",
            "args": [
                "-y",
                "supergateway",
                "--sse",
                "http://localhost:8000/sse"
            ]
        }
    }
}

Adding an MCP server to a project

To add an MCP server to a project you can create a new .cursor/mcp.json file or add it to the existing one. This will look exactly the same as the global MCP server example above.

How to use the MCP server

Once the server is installed, you might need to head back to Settings > MCP and click the refresh button.

The Cursor agent will then be able to see the available tools the added MCP server has available and will call them when it needs to.

You can also explicitly ask the agent to use the tool by mentioning the tool name and describing what the function does.

For Claude Desktop

To add this MCP server to Claude Desktop:

1. Find your configuration file:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json
  • Linux: ~/.config/Claude/claude_desktop_config.json

2. Add this to your configuration file:

{
    "mcpServers": {
        "mcpSandbox": {
            "command": "npx",
            "args": [
                "-y",
                "supergateway",
                "--sse",
                "http://localhost:8000/sse"
            ]
        }
    }
}

3. Restart Claude Desktop for the changes to take effect

Want to 10x your AI skills?

Get a free account and learn to code + market your apps using AI (with or without vibes!).

Nah, maybe later