Skip to main content

A world-class Python interpreter MCP server with session management, health monitoring, and FastMCP middleware

Project description

Python Interpreter MCP Server

CI PyPI Python 3.10+ License: MIT Documentation

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.json for 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 under outputs/notebooks/<id>/.
    • cells โ€” list executed cells (from index.json).
    • cell โ€” fetch one cellโ€™s manifest.
    • export โ€” write a .ipynb (and .html if available) to outputs/notebooks/.
    • reset โ€” clear notebook manifests for the same notebook_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 to outputs/)
  • 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

๐Ÿ”’ 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.json configuration
  • Fixed CLI Command: python-mcp-server now 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.

  1. Fork the repository
  2. Create your feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

๐Ÿ”— Links


โญ 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

python_mcp_server-1.0.1.tar.gz (245.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

python_mcp_server-1.0.1-py3-none-any.whl (23.1 kB view details)

Uploaded Python 3

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

Hashes for python_mcp_server-1.0.1.tar.gz
Algorithm Hash digest
SHA256 5a6efcf1867090e0f8a5b023b7a7c0fc8bb4e56fe792ccecb574ad2817cc7a2c
MD5 c2e615d5d8c3366c9cce069baaf8eb37
BLAKE2b-256 7d3b3f3c95dfe06ea983ee42dafce634367c4a6b552768a324b88aecbfdc91a8

See more details on using hashes here.

File details

Details for the file python_mcp_server-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for python_mcp_server-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 70c47c24500a6955f0435ab5d67c16e3683d6eb6b75133d1191f82ae1bec8536
MD5 acfed1ca389bda1cf254e000ede1fc39
BLAKE2b-256 81515ad4e7153b3c9cfd8b6fbcf1e6009f3cfca66dd71b0651e761aa6d198c52

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page