khshanovskyi/mcp-python-code-interpreter
If you are the rightful owner of mcp-python-code-interpreter and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
The MCP Python Code Interpreter is a stateful Python code execution environment with Jupyter kernel support, built on the Model Context Protocol (MCP).
MCP Python Code Interpreter
A stateful Python code execution environment with Jupyter kernel support, built on the Model Context Protocol (MCP). Execute Python code with persistent state, automatic visualization handling, and secure session management.
Features
- Stateful Execution: Variables, imports, and state persist across multiple code executions within a session
- Jupyter Kernel Backend: Full Jupyter kernel support with IPython features
- Session Management: Secure session IDs with automatic 30-minute timeout
- Visualization Support: Automatic capture and export of matplotlib, seaborn, and Plotly figures
- File Generation: Access generated files (images, data files, plots) via MCP resources
- Scientific Computing: Pre-configured with pandas, numpy, matplotlib, seaborn, plotly, and sympy
- Automatic Cleanup: Background task removes expired sessions and orphaned files
Installation
Using Docker (Recommended)
# Build the image
docker build -t mcp-python-interpreter .
# Run the container
docker run -p 8000:8000 mcp-python-interpreter
Local Installation
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Run the server
python server.py
Usage
The server exposes three tools and a resource endpoint for file access.
1. Execute Code
Execute Python code in a persistent Jupyter kernel environment.
First execution (creates new session):
{
"code": "import pandas as pd\nx = 42\nprint('Hello, World!')",
"session_id": "" # Empty string or "0" for new session
}
Response:
{
"success": true,
"output": ["Hello, World!\n"],
"result": null,
"session_info": {
"session_id": "abc123xyz456",
"instructions": "Use this `session_id` in subsequent requests..."
}
}
Subsequent executions (reuse session):
{
"code": "print(x * 2) # Variable persists from previous execution",
"session_id": "abc123xyz456"
}
2. Create Visualizations
Matplotlib, seaborn, and Plotly figures are automatically captured and saved.
{
"code": """
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.title('Sine Wave')
plt.savefig('sine_wave.png')
plt.show()
""",
"session_id": "abc123xyz456"
}
Response includes file references:
{
"success": true,
"output": ["š File created: sine_wave.png (image/png, 45231 bytes)"],
"files": [
{
"uri": "kernel://abc123xyz456/sine_wave.png",
"mime_type": "image/png",
"name": "sine_wave.png",
"size": 45231
}
]
}
3. List Session Files
{
"session_id": "abc123xyz456"
}
4. Clear Session
Manually remove a session and all its files:
{
"session_id": "abc123xyz456"
}
5. Access Files
Files are accessed via the MCP resource protocol:
kernel://{session_id}/{filename}
Example: kernel://abc123xyz456/sine_wave.png
Session Management
Session Lifecycle
- Creation: First call with empty
session_id
generates a secure 16-character ID - Active: Session remains active while being used
- Timeout: Sessions expire after 30 minutes of inactivity
- Cleanup: Expired sessions are automatically removed (background task runs every 5 minutes)
Session Expiration
If you try to use an expired session, you'll receive a SessionExpiredError
:
{
"success": false,
"error": "SessionExpiredError: Session abc123xyz456 not found or has expired...",
"traceback": []
}
Solution: Create a new session and re-execute your setup code.
Available Libraries
The following libraries are pre-installed:
- Data Science: pandas, numpy
- Visualization: matplotlib, seaborn, plotly, kaleido
- Mathematics: sympy
- Jupyter: ipykernel, jupyter-client
Additional packages can be installed at runtime using !pip install
within your code.
Configuration
Environment Variables
LOG_LEVEL
: Logging level (default:INFO
)JUPYTER_PLATFORM_DIRS
: Set to1
(suppresses Jupyter warnings)
Server Configuration
Edit config.py
to modify:
NOTEBOOKS_FOLDER = ROOT_DIR / 'notebooks' # Session storage location
KERNEL_TIMEOUT = 10 # Kernel operation timeout (seconds)
Edit server.py
to modify:
SESSION_TIMEOUT = 30 * 60 # Session expiration (seconds)
API Reference
Tools
execute_code
Execute Python code in a persistent Jupyter kernel environment.
Parameters:
code
(str): Python code to execute (multi-line supported)session_id
(str, optional): Session identifier (empty or "0" for new session)
Returns:
success
(bool): Execution statusoutput
(list): stdout/stderr textresult
(str|None): Last expression valueerror
(str|None): Error message if failedtraceback
(list): Full traceback if errorfiles
(list): File references with URIssession_info
(dict|None): Session info for new sessions
list_session_files
List all files generated in a session.
Parameters:
session_id
(str): Session identifier
Returns:
session_id
(str): The session IDfiles
(list): List of file referenceserror
(str): Error message if session not found
clear_session
Manually clear a session and shutdown its kernel.
Parameters:
session_id
(str): Session identifier to clear
Returns:
success
(bool): Operation statusmessage
(str): Status message
Resources
kernel://{session_id}/{filename}
Retrieve file content from a session.
URI Format: kernel://session_id/filename
Returns: File content (binary for images, text for text files)
Architecture
āāāāāāāāāāāāāāāāāāā
ā MCP Client ā
ā (Claude, etc) ā
āāāāāāāāāā¬āāāāāāāāā
ā
ā MCP Protocol
ā
āāāāāāāāāā¼āāāāāāāāā
ā MCP Server ā
ā (server.py) ā
āāāāāāāāāā¬āāāāāāāāā
ā
ā Manages
ā
āāāāāāāāāā¼āāāāāāāāā
ā Session Manager ā
ā - Create/Track ā
ā - Cleanup ā
āāāāāāāāāā¬āāāāāāāāā
ā
ā Controls
ā
āāāāāāāāāā¼āāāāāāāāā
ā Jupyter Kernels ā
ā (per session) ā
āāāāāāāāāāāāāāāāāāā
Development
Project Structure
mcp-python-code-interpreter/
āāā config.py # Configuration and initialization
āāā models.py # Pydantic data models
āāā notebook.py # Jupyter kernel management
āāā server.py # MCP server and tools
āāā Dockerfile # Docker configuration
āāā requirements.txt # Python dependencies
āāā notebooks/ # Session storage (auto-created)