py-sandbox

py-sandbox

Enables AI agents to execute arbitrary Python code securely in a sandboxed environment with resource limits and security constraints via MCP protocol.

Category
访问服务器

README

py-sandbox

A cross-platform sandboxed Python code executor with MCP (Model Context Protocol) server support.

Overview

py-sandbox provides a secure environment for executing arbitrary Python code with strict resource limits and security constraints. It is designed for use in AI agent systems, code evaluation platforms, and any scenario where untrusted Python code needs to be run safely.

The sandbox operates through a multi-layered security model:

  1. AST Validation — Rejects dangerous code patterns before execution
  2. Restricted Builtins — Limits available built-in functions inside the sandbox
  3. Import Whitelist — Only safe modules (math, json, re, etc.) can be imported
  4. Subprocess Isolation — Code runs in a separate process, not the host
  5. Resource Limits — Timeout, memory, and output size are all enforced

Features

  • Cross-platform — Works on Windows, macOS, and Linux
    • Windows: Job Objects + watchdog for memory/timeout enforcement
    • Unix: setrlimit via preexec_fn + watchdog
  • MCP Server — Expose run_python tool to AI agents via stdio or SSE transport
  • CLI Tool — Direct sandbox execution from the command line
  • Variable Inspection — Inspect named variables after execution
  • Output Limiting — Truncate excessive stdout to prevent resource abuse
  • No External Dependencies — Core sandbox uses only Python stdlib (ctypes on Windows)

Installation

# Core sandbox (no MCP server)
pip install py-sandbox

# With MCP server support
pip install py-sandbox[mcp]

# Using uv
uv pip install py-sandbox
uv pip install py-sandbox[mcp]

For development:

git clone https://github.com/nobody/py-sandbox-mcp.git
cd py-sandbox-mcp
uv sync

Usage

CLI

# Execute inline code
py-sandbox "print('hello world')"

# Execute from a file
py-sandbox -f script.py

# With resource limits
py-sandbox -t 10 -m 128 "import math; print(math.pi)"

# Inspect variables
py-sandbox -v x -v y "x = 42; y = [1, 2, 3]"

Options:

Option Default Max Description
-t / --timeout 30 60 Timeout in seconds
-m / --memory 256 1024 Memory limit in MB
-o / --output-limit 65536 262144 Output limit in bytes
-v / --variables — — Variable names to inspect

Python API

from py_sandbox import execute

result = execute("import math; print(math.sqrt(16))")
print(result["stdout"])      # "4.0"
print(result["return_code"]) # 0

result = execute("x = 42", inspect_variables=["x"])
print(result["variables"])   # {"x": 42}

result = execute("import os")
print(result["error"])       # "Import of module 'os' is not allowed..."
print(result["return_code"]) # -1

MCP Server

Start the MCP server for AI agent integration:

# stdio transport (default, for CLI-based agents)
py-sandbox-mcp

# SSE transport (for HTTP-based agents)
py-sandbox-mcp sse

The server exposes a run_python tool with the same parameters as the execute() function.

Example MCP client configuration (for Claude Code, Cursor, etc.):

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

Security Model

Layer 1: AST Validation

The AST validator rejects code before it ever reaches execution. Blocked patterns include:

  • Dangerous imports — os, sys, subprocess, socket, ctypes, pickle, etc.
  • Dangerous builtins — exec, eval, compile, open, __import__, getattr, etc.
  • Dunder escapes — __class__, __subclasses__, __globals__, __builtins__, etc.
  • Dynamic class creation — type() with 3 arguments
  • Relative imports — Not allowed (sandbox code has no package context)
  • String-based dunder references — hasattr(obj, "__class__") is blocked

Layer 2: Restricted Builtins

The sandbox worker replaces __builtins__ with a safe subset. Only essential functions like len, range, print, sorted, isinstance, etc. are available. Dangerous builtins like open, exec, eval, getattr are removed.

Layer 3: Import Whitelist

Only these modules can be imported inside the sandbox:

  • Math: math, cmath, decimal, fractions, statistics
  • Data: json, re, string, textwrap, unicodedata, difflib
  • Time: datetime, calendar
  • Collections: collections, itertools, functools, operator, enum, dataclasses, typing, copy
  • Encoding: hashlib, base64, random, uuid, struct
  • Utility: pprint

All other imports raise ImportError.

Layer 4: Subprocess Isolation

Code executes in a separate subprocess, not the host process. This means:

  • The sandbox process cannot access the host's memory or state
  • When the host kills the sandbox process, all its resources are reclaimed
  • No shared file descriptors, no signal leakage

Layer 5: Resource Limits

Resource Enforcement
Timeout Watchdog thread + Unix RLIMIT_CPU / Windows Job Object time limit
Memory Watchdog polling + Unix RLIMIT_AS / Windows Job Object memory limit
Output Byte-counted stdout truncation inside the worker
File descriptors Unix RLIMIT_NOFILE (limited to 64)

Architecture

flowchart TB
    subgraph host["Host Process"]
        entry["CLI / MCP Server"]
        executor["Executor (Orchestrator)"]
        ast["AST Validator\n(reject or accept)"]
        platform["Platform Utils\n(Job Object / setrlimit)"]
        watchdog["ResourceWatchdog\n(timeout / memory)"]
    end

    subgraph worker["Sandbox Worker (subprocess)"]
        builtins["Restricted __builtins__\n+ Import Whitelist"]
        exec_code["exec(code, namespace)"]
        output["Output limiting (byte count)\nVariable serialization"]
    end

    entry --> executor
    executor --> ast
    executor --> platform
    executor --> watchdog
    executor -- "spawn subprocess\nstdin: JSON envelope" --> worker
    worker -- "stdout: JSON result" --> executor

Execution Flow

  1. CLI or MCP Server receives code to execute
  2. Executor validates code through the AST Validator — if rejected, returns error immediately
  3. Platform Utils sets up OS-level resource limits (Job Object on Windows, setrlimit on Unix)
  4. Executor spawns a Sandbox Worker subprocess, sending a JSON envelope via stdin
  5. ResourceWatchdog monitors the subprocess for timeout and memory violations
  6. Inside the subprocess, the Sandbox Worker runs code with restricted builtins and import whitelist
  7. Results (stdout, variables, errors) are serialized as JSON and sent back via stdout

Project Structure

py-sandbox-mcp/
├── LICENSE
├── README.md
├── pyproject.toml
├── src/
│   └── py_sandbox/
│       ├── __init__.py          # Package entry, exports execute() and ExecutionResult
│       ├── ast_validator.py     # AST-based security gate
│       ├── builtin_policy.py    # Safe builtins dict and import whitelist
│       ├── cli.py               # CLI entry point (py-sandbox command)
│       ├── config.py            # Default limits and blocked/allowed lists
│       ├── executor.py          # Orchestrator: validation → spawn → capture
│       ├── platform_utils.py    # Windows Job Object / Unix setrlimit + watchdog
│       ├── sandbox_worker.py    # Subprocess worker: restricted exec environment
│       └── server.py            # MCP server (py-sandbox-mcp command)
├── tests/
│   ├── __init__.py
│   ├── test_ast_validator.py
│   ├── test_builtin_policy.py
│   └── test_executor.py

Running Tests

uv run pytest

License

MIT

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选