A world-class Python interpreter MCP server with session management, health monitoring, and FastMCP middleware
Project description
Python Interpreter MCP Server
A world-class Python interpreter MCP (Model Context Protocol) server that provides secure, isolated Python code execution with advanced session management and health monitoring. Built with FastMCP for production-grade reliability.
โจ Features
๐ Production-Ready Architecture
- FastMCP Middleware Stack: Professional error handling, timing, and contextual logging
- Session-Based Isolation: Multiple independent Python kernels with complete state separation
- Health Monitoring: Real-time kernel diagnostics with intelligent restart capabilities
- Progressive Timeouts: Resilient execution with smart retry logic
๐ Security & Reliability
- Workspace Sandboxing: Path traversal protection and secure file operations
- Resource Monitoring: CPU, memory, and process health tracking
- State Preservation: Automatic kernel state backup and restoration
- Error Resilience: Graceful handling of kernel failures and timeouts
๐ Developer Experience
- Notebook Surface: One tool to run cells, manage datasets, and export artifacts
- File Management: Read, write, delete operations with safety checks
- Package Installation: Dynamic dependency management with uv/pip
๐ฏ FastMCP Integration
- Native FastMCP Configuration: Built-in
fastmcp.jsonfor easy deployment - CLI Integration: Works seamlessly with FastMCP CLI commands
- Multiple Transport Modes: STDIO, HTTP, Server-Sent Events support
- Claude Desktop Ready: Perfect integration with Claude Desktop
๐ Quick Start
Installation
Method 1: PyPI (Recommended)
pip install python-mcp-server
Method 2: uvx (Isolated)
uvx install python-mcp-server
Method 3: FastMCP CLI (For Claude Desktop)
fastmcp install claude-desktop python-mcp-server
Basic Usage
Standalone Server (HTTP Mode)
# Start HTTP server
python-mcp-server --host 127.0.0.1 --port 8000
# Custom workspace
python-mcp-server --workspace /path/to/workspace --port 8000
FastMCP CLI (Recommended)
# Run with FastMCP (auto-detects fastmcp.json)
fastmcp run
# Run with specific transport
fastmcp run --transport http --port 8000
# For development/testing
fastmcp dev
Client Usage
FastMCP Client
import asyncio
from fastmcp.client import Client
async def main():
async with Client("http://localhost:8000/mcp") as client:
# Execute Python code
result = await client.call_tool("run_python_code", {
"code": """
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2)
plt.title('Sine Wave')
plt.grid(True)
plt.show()
print("Plot created successfully!")
"""
})
print("Output:", result.data["stdout"])
asyncio.run(main())
๐ Architecture
graph TB
A[MCP Client] --> B[FastMCP Server]
B --> C[Session Manager]
C --> D[Kernel Session 1]
C --> E[Kernel Session 2]
C --> F[Default Session]
B --> G[Health Monitor]
G --> H[Resource Tracker]
G --> I[Timeout Handler]
B --> J[Workspace Manager]
J --> K[File Operations]
J --> L[Security Layer]
๐ฆ Package Structure (v1.0.0)
src/python_mcp_server/
โโโ server.py # Main FastMCP server implementation
โโโ __init__.py # Package initialization
โโโ ...
fastmcp.json # FastMCP configuration
pyproject.toml # Package metadata and dependencies
tests/ # Comprehensive test suite
docs/ # Documentation source
๐ง Tools Reference
Notebook (single surface)
notebook(action=..., ...) โ one tool for cells, datasets, and exports.
- Actions:
runโ execute a cell; capture stdout/stderr, figures (PNG/SVG), JSON outputs, and a workspace diff. Writes a manifest per cell underoutputs/notebooks/<id>/.cellsโ list executed cells (from index.json).cellโ fetch one cellโs manifest.exportโ write a.ipynb(and.htmlif available) tooutputs/notebooks/.resetโ clear notebook manifests for the samenotebook_id(kernel is not restarted).datasets.registerโ create/update a DuckDB VIEW over CSV/Parquet files or globs.datasets.listโ show registered datasets.datasets.describeโ schema + head(50).datasets.dropโ remove a registered dataset/view.datasets.sqlโ run SQL across registered views; returns preview and writes full result to Parquet.
Core Execution
run_python_code- Execute Python with output capture (rich display assets saved tooutputs/)restart_kernel- Clean kernel restart with optional state preservation
File Operations
list_files- Browse workspace (flat or tree view)read_file/write_file/delete_file- Safe file operations
Package Management
install_dependencies- Dynamic dependency installation with uv/pip fallback
๐ก Advanced Usage
Notes
- Session isolation, health and concurrency controls run under the hood; the public tool surface is intentionally minimal for agent reliability.
๐งฐ Interpreter / Venv Configuration
The server runs the Jupyter kernel with the same interpreter and environment as the process by default. You can override with flags in both stdio and http modes:
python-mcp-server \
--python /path/to/python \
--venv /path/to/venv \
--pythonpath "/extra/dir1:/extra/dir2" \
--transport http --port 8000
Environment variables honored: PYTHON, MPLBACKEND=Agg (default), MCP_MAX_CONCURRENT_CELLS, MCP_MEMORY_BUDGET_MB, MCP_SOFT_WATERMARK, MCP_HARD_WATERMARK.
๐ Datasets (DuckDB-backed)
Register CSV/Parquet files (or globs) as DuckDB views and query with SQL:
# Register
await client.call_tool("notebook", {
"action": "datasets.register",
"dataset_name": "sales",
"paths": ["data/sales_*.parquet"],
"format": "parquet"
})
# Describe
await client.call_tool("notebook", {"action": "datasets.describe", "dataset_name": "sales"})
# Query (preview + full Parquet result on disk)
await client.call_tool("notebook", {
"action": "datasets.sql",
"query": "select date, sum(amount) as total from sales group by date order by date"
})
๐ง Configuration
FastMCP Configuration (fastmcp.json)
{
"$schema": "https://gofastmcp.com/public/schemas/fastmcp.json/v1.json",
"source": {
"type": "filesystem",
"path": "src/python_mcp_server/server.py",
"entrypoint": "mcp"
},
"environment": {
"type": "uv",
"python": ">=3.10",
"dependencies": [
"fastmcp>=1.0.0",
"jupyter_client>=8.0.0",
"matplotlib>=3.7.0",
"pandas>=2.0.0"
],
"editable": ["."]
},
"deployment": {
"transport": "stdio",
"log_level": "INFO",
"env": {
"MCP_WORKSPACE_DIR": "workspace",
"MPLBACKEND": "Agg",
"PYTHONUNBUFFERED": "1"
}
}
}
Environment Variables
export MCP_WORKSPACE_DIR="./workspace" # Workspace directory
export MPLBACKEND="Agg" # Matplotlib backend
export PYTHONUNBUFFERED="1" # Unbuffered output
Command Line Options
python-mcp-server \
--port 8000 \
--host 0.0.0.0 \
--workspace ./custom_workspace
๐ Workspace Structure
workspace/
โโโ scripts/ # Saved Python scripts
โโโ outputs/ # Generated files (plots, data, etc.)
โโโ uploads/ # Uploaded files via HTTP
โโโ (user files) # Any files created during execution
๐ค Integration Examples
With Claude Desktop (STDIO Mode)
Method 1: Direct Command
{
"mcpServers": {
"python-interpreter": {
"command": "python-mcp-server",
"args": ["--workspace", "/path/to/workspace"]
}
}
}
Method 2: FastMCP CLI (Recommended)
# Install for Claude Desktop
fastmcp install claude-desktop fastmcp.json --name "Python Interpreter"
This generates the correct configuration automatically.
Method 3: Direct Python Path
{
"mcpServers": {
"python-interpreter": {
"command": "python",
"args": [
"/path/to/src/python_mcp_server/server.py",
"--workspace", "/path/to/workspace"
]
}
}
}
With Claude Code
fastmcp install claude-code fastmcp.json --name "Python Interpreter"
With Cursor
fastmcp install cursor fastmcp.json --name "Python Interpreter"
Custom HTTP Client
# Raw HTTP/JSON-RPC
import httpx
async def call_tool(tool_name, arguments):
async with httpx.AsyncClient() as client:
response = await client.post("http://localhost:8000/mcp", json={
"jsonrpc": "2.0",
"method": "tools/call",
"params": {"name": tool_name, "arguments": arguments},
"id": 1
})
return response.json()
With uvx (No Installation)
# Run directly without installing globally
uvx python-mcp-server --port 8000
# With additional dependencies
uvx --with pandas --with numpy python-mcp-server --port 8000
๐งช Development
Setup
git clone https://github.com/deadmeme5441/python-mcp-server.git
cd python-mcp-server
uv sync
Testing
# Run all tests
uv run pytest tests/ -v
# Run specific test
uv run pytest tests/test_sessions.py -v
# With coverage
uv run pytest --cov=src --cov-report=html
Code Quality
# Linting
uvx ruff@latest check .
# Type checking
uv run mypy src/
# Formatting
uvx ruff@latest format .
FastMCP Development
# Run with FastMCP for development
fastmcp dev
# Test different transports
fastmcp run --transport http --port 8000
fastmcp run --transport stdio
๐ Documentation
- Complete Documentation - Full guides and API reference
- Getting Started - Installation and first steps
- Architecture - Technical deep dive
- Examples - Practical usage patterns
- Troubleshooting - Common issues and solutions
๐ Security
- Workspace Sandboxing: All operations restricted to configured workspace
- Path Validation: Protection against directory traversal attacks
- Resource Limits: Configurable memory and CPU constraints
- Process Isolation: Each session runs in isolated Jupyter kernel
- Input Sanitization: All inputs validated via Pydantic models
๐ Use Cases
- AI Agent Environments: Reliable Python execution for AI agents
- Educational Platforms: Safe, isolated code execution for learning
- Data Analysis Workflows: Session-based data processing pipelines
- Research & Prototyping: Quick iteration with state preservation
- Jupyter Alternative: MCP-native Python execution environment
- Claude Desktop Integration: Enhanced Python capabilities for Claude
๐ Changelog (v0.6.0)
๐ Major Changes
- New Package Structure: Migrated to
src/python_mcp_server/layout - FastMCP Integration: Added native
fastmcp.jsonconfiguration - Fixed CLI Command:
python-mcp-servernow works correctly - Enhanced Installation: Multiple installation methods supported
๐ง Improvements
- Better Testing: Fixed all test imports and module structure
- Documentation: Updated for new package structure
- Claude Desktop: Improved integration and configuration
- Code Quality: Full linting compliance and type checking
๐ Bug Fixes
- Entry Point: Fixed package entry point configuration
- Module Imports: Resolved import issues in tests
- Build System: Proper hatchling configuration
๐ค Contributing
We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create your feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- FastMCP - Excellent MCP framework
- Jupyter - Kernel architecture inspiration
- Model Context Protocol - Protocol specification
- uv - Fast Python package manager
๐ Links
- PyPI: python-mcp-server
- Documentation: deadmeme5441.github.io/python-mcp-server
- Issues: GitHub Issues
- Discussions: GitHub Discussions
โญ Star this repo if you find it useful!
Built with โค๏ธ by DeadMeme5441
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file python_mcp_server-1.0.1.tar.gz.
File metadata
- Download URL: python_mcp_server-1.0.1.tar.gz
- Upload date:
- Size: 245.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.8.16
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5a6efcf1867090e0f8a5b023b7a7c0fc8bb4e56fe792ccecb574ad2817cc7a2c
|
|
| MD5 |
c2e615d5d8c3366c9cce069baaf8eb37
|
|
| BLAKE2b-256 |
7d3b3f3c95dfe06ea983ee42dafce634367c4a6b552768a324b88aecbfdc91a8
|
File details
Details for the file python_mcp_server-1.0.1-py3-none-any.whl.
File metadata
- Download URL: python_mcp_server-1.0.1-py3-none-any.whl
- Upload date:
- Size: 23.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.8.16
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
70c47c24500a6955f0435ab5d67c16e3683d6eb6b75133d1191f82ae1bec8536
|
|
| MD5 |
acfed1ca389bda1cf254e000ede1fc39
|
|
| BLAKE2b-256 |
81515ad4e7153b3c9cfd8b6fbcf1e6009f3cfca66dd71b0651e761aa6d198c52
|