Skip to content

A secure, cross-platform MCP server for syntax checking and safe execution of Python code generated by local LLMs.

License

Notifications You must be signed in to change notification settings

vuguzum/python-mcp-sandbox

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Python Code Sandbox MCP Server

A secure, cross-platform MCP server for syntax checking and safe execution of Python code generated by local LLMs.

for seamless integration with LLM tools in VS Code, LM Studio, and other MCP-compatible interfaces.

🌟 Overview

A lightweight, secure MCP server for safe interaction between local Large Language Models (LLMs) and Python code. Two critical functions:

  1. Syntax Validation — Checks Python code for syntax errors using AST parsing, without executing it.
  2. Sandboxed Execution — Runs code in a hardened, isolated environment with CPU, memory, and I/O restrictions.

Safety is the top priority, the server prevents malicious or unstable code from affecting your system, ideal for AI-assisted development workflows.

✨ Features

  • Syntax Checker — Uses Python’s ast module to validate code structure safely
  • Security Scanner — Blocks dangerous functions (eval, exec, open, __import__, etc.) and modules (os, subprocess, sys, etc.)
  • Cross-Platform Sandbox — Works on Windows and Linux/macOS with OS-level resource limits:
    • Unix: Uses resource.setrlimit() for CPU and memory caps
    • Windows: Uses Job Objects (via pywin32) for process isolation
  • Time & Memory Limits — Configurable timeouts and memory caps (default: 15s, 100MB)
  • JSON Output — Standardized responses for easy integration with LLM tools
  • MCP-Ready — Fully compatible with MCP protocol via fastmcp
  • Editable Install — Install in development mode (pip install -e .) for live code editing
  • No External Dependencies — Pure Python, minimal dependencies

📁 Project Structure

python-mcp-sandbox/
├── python_code_sandbox/
│   ├── __init__.py
│   ├── python_code_sandbox.py     # Main MCP server (check_syntax, test_code)
│   ├── safe_executor.py           # Core sandbox execution engine
│   └── test_safe_executor.py      # Test module for the sandbox execution engine
├── pyproject.toml                 # Python packaging config
├── requirements.txt               # Dependencies
└── README.md                      # This file

📦 Installation

Prerequisites

  • Python 3.8+
  • pip

Install the Server

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

# Install in editable mode
pip install -e .

💡 Windows users: For full resource isolation, install pywin32:

pip install pywin32

Verify the source code

Run tests for safe_executor.py from the command line, make sure all 6 tests passed ok:

python test_safe_executor.py

🛠️ Integration with LLM Tools (LM Studio)

This server integrates with any MCP-compatible interface (LM Studio, etc.) via the mcp.json configuration file.

{
  "mcpServers": {
    "python-code-sandbox": {
      "command": "python",
      "args": [
        "-m",
        "python_code_sandbox.python_code_sandbox"
      ]
    }
  }
}

✅ Tip: The python-code-sandbox entry above points to the installed module. You can also use the full path to the script if preferred.

Once configured, your LLM tool can call two functions:

  • check_syntax(code: str) — Returns syntax validity and error details
  • test_code(code: str, timeout: float = 15.0, cpu_limit_sec: float = 10.0, memory_limit_mb: int = 100) — Executes code safely and returns output

🔍 How It Works

  1. Syntax Check (check_syntax)
  • Parses code using ast.parse() — no execution occurs
  • Returns structured JSON with:
    • valid: true/false
    • error, line, offset, context — if invalid
  1. Safe Execution (test_code)
  • Step 1: Validates syntax
  • Step 2: Scans for dangerous imports and function calls
  • Step 3: Writes code to a temporary file
  • Step 4: Launches a child process with:
    • Restricted environment (no open, no imports, no sys access)
    • CPU and memory limits
    • Output captured via io.StringIO
  • Step 5: Returns JSON result:
{
  "stdout": "...",
  "stderr": "...",
  "exit_code": 0,
  "phase": "execution"
}

All dangerous modules (os, subprocess, ctypes, etc.) are removed from sys.modules before execution.

🧪 Example Usage

Request from LLM Tool:

{
  "method": "test_code",
  "params": {
    "code": "print('Hello, world!')\nx = 1 / 0",
    "timeout": 10,
    "memory_limit_mb": 50
  }
}

Response:

{
  "stdout": "Hello, world!\n",
  "stderr": "ZeroDivisionError: division by zero\n",
  "exit_code": 1,
  "phase": "execution"
}

🚫 Security Design

This server follows the principle of defense in depth:

LAYER PROTECTION
1. AST Parsing No code execution during syntax check
2. Static Analysis Blocks known dangerous functions and modules
3. Environment Sanitization Removes dangerous modules, overrides __import__, disables open()
4. Process Isolation Uses OS-level limits (Job Objects on Windows, resource on Unix)
5. Time & Memory Caps Prevents infinite loops or memory exhaustion
6. Output Sandboxing All output captured via buffers, no direct filesystem access

Log files are written to your system’s temp directory:

  • mcp_sandbox.log
  • mcp_sandbox_executor.log

📌 Notes

  • Windows: For full resource limits, install pywin32. Without it, only timeout is enforced.
  • Linux/macOS: Full resource control via resource module is available by default.
  • No internet access is allowed — the sandbox blocks all network calls.
  • No file system access — open() and pathlib are disabled.

📜 License

Apache 2.0 — see LICENSE for details.

📧 Author:

Alexander Kazantsev (akazant@gmail.com )

About

A secure, cross-platform MCP server for syntax checking and safe execution of Python code generated by local LLMs.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages