Skip to main content
Glama
lu-zhengda

mcp-python-exec-sandbox

by lu-zhengda

mcp-python-exec-sandbox

CI PyPI Python License

Sandboxed Python execution for AI agents. Scripts run in ephemeral, isolated environments with inline dependencies (PEP 723) -- zero host pollution, zero leftover venvs, zero package conflicts.

Why?

Every coding agent can already run Python on your host. The problem is what happens next: packages accumulate, venvs sprawl, and a rogue pip install breaks your system. mcp-python-exec-sandbox eliminates this:

  • Scripts execute in a sandbox (bubblewrap on Linux, Docker on macOS/other platforms)

  • Dependencies are declared inline and resolved ephemerally via uv

  • Nothing touches your host's Python, site-packages, or virtualenvs

  • Each execution is isolated and disposable

Related MCP server: MCP Run Python

Features

  • Sandboxed execution -- platform-specific isolation prevents host filesystem access

  • PEP 723 inline metadata -- declare dependencies directly in scripts with # /// script blocks

  • Multi-version Python -- run scripts on Python 3.13, 3.14, or 3.15 (uv downloads the right version automatically)

  • Ephemeral environments -- dependencies are resolved per-execution, never persisted

  • Package caching -- uv's global cache makes repeat installs near-instant

  • Timeout enforcement -- configurable per-execution timeouts

  • Output truncation -- prevents runaway output from overwhelming the agent

Prerequisites

All setups require:

  • Python 3.13+ -- to run the MCP server process

  • uv -- manages script execution, dependency resolution, and Python version downloads. Also provides uvx for running the server without installing it globally.

Additional requirements depend on your chosen sandbox backend:

Setup

Additional requirements

Install

Native sandbox (Linux)

bubblewrap

sudo apt install bubblewrap

Docker sandbox (macOS, any)

Docker Engine

See Docker docs

No sandbox

None

--

Host Python vs. execution Python: These are independent. Python 3.13+ is needed to run the server process itself. The --python-version flag controls which Python version your scripts execute on -- uv downloads the target version automatically. You do not need to install Python 3.14 or 3.15 on your host to run scripts on those versions.

Quick start

Claude Code (Linux -- native sandbox)

claude mcp add python-sandbox -- uvx mcp-python-exec-sandbox
claude mcp add python-sandbox -- uvx mcp-python-exec-sandbox

The Docker sandbox image is pulled automatically from GHCR on first use. No manual build required.

Claude Code (no sandbox)

claude mcp add python-sandbox -- uvx mcp-python-exec-sandbox --sandbox-backend none

Cursor

Add to .cursor/mcp.json (project-level) or ~/.cursor/mcp.json (global):

{
  "mcpServers": {
    "python-sandbox": {
      "command": "uvx",
      "args": ["mcp-python-exec-sandbox"]
    }
  }
}

OpenAI Codex CLI

codex mcp add python-sandbox -- uvx mcp-python-exec-sandbox

Or add to .codex/config.toml:

[mcp_servers.python-sandbox]
command = "uvx"
args = ["mcp-python-exec-sandbox"]

Other MCP clients

Any client that supports the MCP stdio transport can use this server:

{
  "mcpServers": {
    "python-sandbox": {
      "command": "uvx",
      "args": ["mcp-python-exec-sandbox"]
    }
  }
}

Multi-version Python

Use --python-version to target a specific Python version. uv downloads it automatically -- no manual install needed.

# Python 3.13 (default)
uvx mcp-python-exec-sandbox --python-version 3.13

# Python 3.14
uvx mcp-python-exec-sandbox --python-version 3.14

# Python 3.15
uvx mcp-python-exec-sandbox --python-version 3.15

This works across all sandbox backends. The Docker sandbox uses uv inside the container to manage Python versions, so the same --python-version flag applies.

Tools

execute_python

Execute a Python script with automatic dependency management.

Parameter

Type

Default

Description

script

str

required

Python source code, may include PEP 723 inline metadata

dependencies

list[str]

[]

Extra PEP 508 dependency specifiers to merge

timeout_seconds

int

30

Maximum execution time (1--300)

# Simple script
execute_python(script="print('hello world')")

# Script with dependencies
execute_python(
    script="import requests; print(requests.get('https://httpbin.org/get').status_code)",
    dependencies=["requests"]
)

# Script with inline PEP 723 metadata
execute_python(script="""
# /// script
# dependencies = ["pandas", "matplotlib"]
# ///

import pandas as pd
print(pd.DataFrame({'a': [1,2,3]}).describe())
""")

check_environment

Returns information about the execution environment: Python version, uv version, platform, sandbox status, and configuration.

validate_script

Validates a script's PEP 723 metadata and dependencies without executing it.

Parameter

Type

Default

Description

script

str

required

Python source code to validate

dependencies

list[str]

[]

Extra dependency specifiers to validate

Sandbox backends

Backend

Platform

Tool

Notes

native

Linux

bubblewrap

Namespace isolation, network allowed

docker

Any

Docker

Container isolation, resource limits

none

Any

--

No sandboxing (not recommended)

The default backend is native (bubblewrap) on Linux and docker on macOS/other platforms. Specifying --sandbox-backend native on macOS automatically redirects to Docker. If the sandbox tool is unavailable, the server falls back to none with a warning.

Docker sandbox setup

The Docker sandbox image is published to GHCR and pulled automatically when the server starts. No manual setup is needed.

To build locally for development:

docker build -t ghcr.io/lu-zhengda/mcp-python-exec-sandbox profiles/

CLI options

mcp-python-exec-sandbox [OPTIONS]

Options:
  --python-version TEXT     Python version for execution (default: 3.13)
  --sandbox-backend TEXT    native | docker | none (default: native on Linux, docker on macOS)
  --max-timeout INT         Maximum allowed timeout in seconds (default: 300)
  --default-timeout INT     Default timeout in seconds (default: 30)
  --max-output-bytes INT    Maximum output size in bytes (default: 102400)
  --no-warm-cache           Skip cache warming on startup
  --uv-path TEXT            Path to uv binary (default: uv)

Development

Setup

git clone https://github.com/lu-zhengda/mcp-python-exec-sandbox.git
cd mcp-python-exec-sandbox
uv sync --dev

Project structure

src/mcp_python_exec_sandbox/   # Package source
  server.py               # FastMCP server + tool definitions
  executor.py             # uv subprocess orchestration
  script.py               # PEP 723 metadata parsing/merging
  sandbox.py              # Sandbox ABC + factory
  sandbox_linux.py        # bubblewrap sandbox (Linux)
  sandbox_docker.py       # Docker sandbox (macOS/any)
  config.py, cache.py, output.py, errors.py
tests/                    # Unit + integration tests (mocked or local uv)
e2e_tests/                # End-to-end tests (require uv + network)
profiles/                 # Dockerfile, warmup packages
.devcontainer/            # Devcontainer for Linux sandbox testing from macOS

Running tests

Unit and integration tests -- fast, run everywhere:

uv run pytest tests/ -v

E2E tests -- require uv and network access. These exercise real script execution, package installation, MCP protocol flow, and sandbox enforcement:

uv run pytest e2e_tests/ -v

Docker sandbox tests

The Docker E2E tests (e2e_tests/test_docker_sandbox.py) verify execution, dependency installation, read-only filesystem enforcement, host isolation, and timeout handling through the Docker backend.

Prerequisites:

  1. Docker must be installed and running

  2. Build the sandbox image:

docker build -t ghcr.io/lu-zhengda/mcp-python-exec-sandbox profiles/

Then run:

uv run pytest e2e_tests/test_docker_sandbox.py -v

These tests are automatically skipped if Docker is unavailable or the image hasn't been built.

Linux sandbox tests (devcontainer)

The Linux sandbox tests (e2e_tests/test_sandbox_enforcement.py::test_linux_sandbox_blocks_etc_shadow) use bubblewrap (bwrap) for namespace isolation. They are skipped on macOS because bwrap is Linux-only.

To run them from macOS, use the included devcontainer which provides Ubuntu 24.04 with bwrap pre-installed:

VS Code:

  1. Install the Dev Containers extension

  2. Open the project and select Reopen in Container

  3. In the integrated terminal:

uv run pytest e2e_tests/test_sandbox_enforcement.py -v

CLI:

# Install the devcontainer CLI (once)
npm install -g @devcontainers/cli

# Build and start the container
devcontainer up --workspace-folder .

# Run the Linux sandbox tests inside the container
devcontainer exec --workspace-folder . uv run pytest e2e_tests/test_sandbox_enforcement.py -v

Test matrix

Test suite

Command

Requirements

Unit tests

uv run pytest tests/ -v

uv

Integration tests

uv run pytest tests/test_integration.py -v

uv

E2E (general)

uv run pytest e2e_tests/ -v

uv, network

E2E (Docker sandbox)

uv run pytest e2e_tests/test_docker_sandbox.py -v

uv, Docker, sandbox image

E2E (Linux/bwrap sandbox)

uv run pytest e2e_tests/test_sandbox_enforcement.py -v

uv, Linux with bwrap (or devcontainer)

Contributing

  • One logical change per commit. Descriptive commit message (imperative mood).

  • Run uv run pytest tests/ -v before committing -- all tests must pass.

  • Add tests for new functionality: unit tests in tests/, E2E in e2e_tests/ if it needs real execution.

  • Keep dependencies minimal. Do not add runtime deps without strong justification.

  • Tool docstrings in server.py are user-facing MCP tool descriptions. Write them for an LLM audience.

  • Sandbox backends must degrade gracefully: if the required tool (bwrap, docker) is missing, fall back to NoopSandbox with a warning.

License

MIT

Available Tools

3 tools
check_environmentA

Check the execution environment and report status.

Returns information about Python version, uv version, platform, sandbox configuration, and cache status.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.6/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the burden. It lists the return information (Python version, uv version, platform, sandbox config, cache status) but does not mention side effects; however, no side effects are expected for a read-only check.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is short (two sentences) and front-loaded with the main purpose. Every sentence adds value without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given zero parameters and the presence of an output schema (not shown but mentioned), the description is complete enough. It effectively communicates the tool's purpose and output.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

There are no parameters, and schema coverage is 100%. The description adds meaning by specifying what the tool returns, which is helpful beyond the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses the specific verb 'Check' with the resource 'execution environment'. It clearly states what the tool does and distinguishes from siblings like execute_python and validate_script.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies the tool is for obtaining environment information before executing Python code. It does not explicitly state when not to use it, but the context provides adequate guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

execute_pythonA

Execute a Python script with automatic dependency management.

The script can include PEP 723 inline metadata (# /// script blocks) for declaring dependencies. Additional dependencies can also be passed via the dependencies parameter and will be merged.

Args: script: Python source code to execute. May include PEP 723 metadata. dependencies: Extra PEP 508 dependency specifiers to make available. timeout_seconds: Maximum execution time (1-300, default 30).

Returns: Formatted output with stdout, stderr, exit code, and duration.

Example - simple script:

execute_python(script="print('hello')")

Example - with dependencies parameter:

execute_python(
    script="import requests; print(requests.get('https://example.com').status_code)",
    dependencies=["requests>=2.32"]
)

Example - with inline dependency metadata (preferred for multiple deps):

execute_python(script='''
# /// script
# dependencies = ["pandas>=2.2", "numpy>=1.26"]
# ///

import pandas as pd
import numpy as np
print(pd.DataFrame({"a": np.arange(5)}).describe())
''')

Always pin dependency versions (e.g. "pandas>=2.2" instead of "pandas") for reproducible results.

The inline metadata block (# /// script ... # ///) is the recommended way to declare dependencies directly in the script (see PEP 723: https://peps.python.org/pep-0723/). The dependencies parameter is a simpler alternative when you just need to add a few packages. Both accept standard pip-style version specifiers like "requests>=2.28" or "pandas" (see PEP 508: https://peps.python.org/pep-0508/).

ParametersJSON Schema
NameRequiredDescriptionDefault
scriptYes
dependenciesNo
timeout_secondsNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.3/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so description carries full burden. It discloses timeout, return format, and dependency merging, but does not warn about potential side effects like network access or security risks, which are inherent to arbitrary Python execution.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Well-structured with summary, args, returns, examples, and notes. Front-loaded with key information. Slightly verbose but each section adds value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (3 params, output schema), the description covers all aspects: parameters, return format, best practices, and references to PEP standards. No gaps remain.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, but the description fully explains all three parameters: script (source code with PEP 723), dependencies (PEP 508 specifiers), and timeout_seconds (range and default). Examples clarify usage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool executes Python scripts with automatic dependency management. It distinguishes itself from sibling tools (check_environment, validate_script) by focusing on execution and dependency resolution.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides detailed guidance on how to use dependencies via inline metadata or parameter, and recommends pinning versions. Lacks explicit when-not-to-use or comparison to alternatives, but covers main usage patterns.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

validate_scriptA

Validate a Python script's PEP 723 metadata and dependencies without executing it.

Checks metadata syntax, dependency format, and requires-python compatibility.

Args: script: Python source code to validate. May include inline dependency metadata (# /// script blocks, see https://peps.python.org/pep-0723/). dependencies: Extra dependency specifiers to validate, using standard pip-style format like "requests>=2.28" (see https://peps.python.org/pep-0508/).

Returns: Validation result with metadata details or error information.

ParametersJSON Schema
NameRequiredDescriptionDefault
scriptYes
dependenciesNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.5/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Explicitly states it does not execute the script, a critical behavioral trait. No annotations are provided, so the description fully bears the transparency burden and does so well.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Front-loaded with the core purpose, uses clear bullet points for parameters and returns, no extraneous text. Every sentence adds value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Adequately covers the validation tool given its complexity (2 params, 1 required), with output schema presence reducing the need to detail return values. Description is sufficient for an agent to understand usage and behavior.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Adds meaning beyond the schema by describing the script parameter with PEP 723 context and the dependencies parameter with format examples and PEP 508 reference. Covers 100% of parameters despite 0% schema description coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Clearly states the tool validates PEP 723 metadata and dependencies without executing, distinguishing it from sibling tools like execute_python and check_environment.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Implies use for validation before execution, but does not explicitly state when not to use or compare with siblings. Could specify alternatives like check_environment for environment checks.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 3 tool updatesv0.1.8
    • First observedcheck_environment
    • First observedexecute_python
    • First observedvalidate_script

TDQS

A4.5/5.0
Disambiguation5/5

Each tool has a distinct purpose: checking environment, executing scripts, and validating metadata. There is no overlap or ambiguity.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern (check_environment, execute_python, validate_script) using snake_case.

Tool Count5/5

With 3 tools, the server is well-scoped for its purpose—covering environment check, execution, and validation without unnecessary bloat.

Completeness4/5

The tools cover core workflows, but missing features like standalone package installation or execution history are minor gaps for a sandbox server.

Maintenance

ActivityInactive
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    An interactive Python code execution environment that allows users and LLMs to safely execute Python code and install packages in isolated Docker containers.
    40
    Apache 2.0
  • A
    license
    Not graded
    quality
    F
    maintenance
    Enables secure execution of Python code in a sandboxed WebAssembly environment using Pyodide and Deno. Automatically handles package management and captures complete execution results including stdout, stderr, and return values.
    194
    MIT
  • -
    license
    Not graded
    quality
    Not graded
    maintenance
    Enables Python code execution in a sandboxed environment with virtual file system management and pip package installation capabilities.
    -
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables LLMs to safely execute code in isolated Docker containers with resource limits and security controls, supporting session management and automatic dependency installation.
    MIT

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/lu-zhengda/mcp-python-exec-sandbox'

If you have feedback or need assistance with the MCP directory API, please join our Discord server