mcp-secure-sandbox
Provides a secure, containerized Python sandbox for executing LLM-generated code with multi-layer isolation, along with JSON/CSV validation and workspace state snapshots.
README
Secure Python Sandbox & Data Validator MCP Server
A production-ready, highly secure, and containerized Model Context Protocol (MCP) server built in Python using FastMCP. This server isolates code executions within a sandboxed environment, offers automated data validation (JSON Schema and CSV structures), and maintains state snapshots to support deterministic testing pipelines.
🏗️ Architecture & Isolation Model
This server implements four distinct layers of security to ensure that code generated by LLMs cannot execute destructive operations or compromise the host system.
graph TD
Client[Client e.g., Claude Desktop] -->|MCP JSON-RPC| Server[FastMCP Server Process]
Server -->|Tool: run_sandbox_code| AST{AST Safety Checker}
AST -->|Safety Violations| Fail[Reject & return Traceback]
AST -->|Safe AST| Subprocess[Spawn Python Subprocess]
Subprocess -->|Preamble Injection| Closure[Intercept builtins.open]
Closure -->|Access within Workspace| Execute[Run Script]
Closure -->|Access outside Workspace| Block[PermissionError Blocked]
Execute -->|Capture stdout/stderr/time| Server
Server -->|Response| Client
The 4 Layers of Defense:
- Container Isolation (Docker): The server runs as a non-root system user (
mcpuser) inside a minimalpython:3.12-slimcontainer, ensuring zero access to the host's root filesystem or processes. - Static AST Analysis: Prior to execution, code is parsed into an Abstract Syntax Tree (AST). The AST visitor blocks dangerous built-in functions (
exec,eval), double-underscore metadata attributes (__class__,__subclasses__), and unapproved imports (e.g.os,sys,subprocess,socket). - Subprocess Isolation: Code is executed inside a spawned Python subprocess rather than the server's parent process. This isolates the memory context, manages clean execution time-outs, and handles crashes without crashing the MCP server.
- Closure-based Path Interception: The server injects a sandbox preamble that overrides python's built-in
open()function using a closure factory. This factory validates all file paths and blocks directory traversal attempts (using..or absolute paths outside the workspace) with aPermissionError.
🛠️ MCP Specifications
Tools
| Tool Name | Parameters | Description |
|---|---|---|
run_sandbox_code |
code: str, timeout_sec: float |
Validates and executes code in the isolated workspace. |
validate_json_data |
data: dict, schema_name_or_dict: any |
Validates JSON payloads against predefined or custom schemas. |
validate_csv_data |
csv_content: str, required_headers: list, type_constraints: dict |
Enforces column headers and datatype rules on CSV data. |
create_state_snapshot |
description: str |
Saves a snapshot of the workspace (files, hashes, metadata). |
restore_state_snapshot |
snapshot_id: str |
Reverts the workspace filesystem to a saved snapshot. |
list_state_snapshots |
None | Lists all saved snapshots chronologically. |
delete_state_snapshot |
snapshot_id: str |
Permanently deletes a saved snapshot file. |
get_sandbox_metrics |
None | Returns resource usage (memory, CPU) and tool execution statistics. |
Resources
sandbox://status: Returns JSON data outlining active configurations, workspaces, and snapshot counts.sandbox://logs: Retrieves the last 100 execution traces in memory (timestamp, log level, messages, and performance times).sandbox://schemas: Lists all pre-registered validation schemas (config,user,dataset).
Prompts
generate_secure_script: Prompts the LLM client to write a Python script complying with the AST safety and workspace file constraints.diagnose_validation_error: Diagnoses schema validation errors and generates corrected JSON payloads.
🚀 Installation & Setup
Prerequisites
- Python 3.12+ (or Docker installed on the host machine)
- Python virtual environment tools (
venv)
Local Setup & Testing
- Clone or copy the repository files.
- Initialize virtual environment and install requirements:
python -m venv .venv .venv/Scripts/activate # On Windows source .venv/bin/activate # On Linux/macOS pip install -r requirements.txt - Run the unit and integration tests:
python -m pytest -vv - Start the server locally in stdio transport mode:
python -m src.server
Containerized Sandbox Setup (Docker)
To build and run the secure container using Docker:
# Build the Docker image
docker build -t mcp-secure-sandbox .
# Run the container in interactive stdio mode
docker run -i --rm -v "$(pwd)/sandbox_workspace:/sandbox/workspace" mcp-secure-sandbox
Using Docker Compose:
# Start the container with mounted volumes
docker-compose up -d
[!NOTE] The workspace files are persisted locally in the
./sandbox_workspacefolder, and snapshots are saved in the./sandbox_snapshotsfolder. Both paths are automatically synchronized inside the container.
⚙️ Client Integration (Claude Desktop Config)
Add the following block to your Claude Desktop configuration file (typically located at %APPDATA%\Claude\claude_desktop_config.json on Windows or ~/Library/Application Support/Claude/claude_desktop_config.json on macOS):
{
"mcpServers": {
"secure-sandbox": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-v",
"E:/mcp-secure-sandbox/sandbox_workspace:/sandbox/workspace",
"-v",
"E:/mcp-secure-sandbox/sandbox_snapshots:/sandbox/snapshots",
"mcp-secure-sandbox"
]
}
}
}
[!IMPORTANT] Verify that the local folder paths mounted in the
-vargs exist on your host and are formatted correctly as absolute paths.
📦 State Snapshot Details
The snapshot engine saves the state of the workspace inside JSON records. A snapshot contains:
- Snapshot Metadata: UUID, ISO UTC timestamp, and descriptions.
- File Registry: Maps relative paths of all files in
/sandbox/workspaceto:- File size (bytes)
- Modification timestamp (
mtime) - SHA-256 hash of contents
- Content payload (UTF-8 string for text files, Base64 encoding for binaries)
When restore_state_snapshot is triggered:
- It compares the current workspace state with the snapshot registry.
- Files not present in the snapshot registry are deleted.
- Modified files (matching path but differing SHA-256) are rewritten to match.
- Missing files are recreated.
- All file modification times (
mtime) are restored to ensure build tools function deterministically.
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。