# MCP Python REPL Server
An MCP (Model Context Protocol) server that provides Claude Code with interactive Python REPL capabilities for in-development projects. This server enables seamless Python code execution, dependency management, and project interaction through uv and virtual environments.
## Design Philosophy
This MCP server is **stack-aware but structure-agnostic**. It provides intelligent tools to introspect and interact with Python projects using modern frameworks (FastAPI, pydantic, SQLModel, Alembic) without imposing any specific directory structure. The server discovers your project's architecture through:
- **Automatic Detection**: Scans for `pyproject.toml`, `.env` files, `alembic.ini`, and framework imports
- **Intelligent Introspection**: Analyzes your codebase to understand models, endpoints, and database schemas
- **Adaptive Behavior**: Adjusts tool behavior based on detected frameworks and project patterns
- **Flexible Integration**: Works with any project structure - from monoliths to microservices
Claude Code can then intelligently interact with your project regardless of how you've organized your code, making this MCP server universally applicable to modern Python development workflows.
## Features
### Core REPL Functionality
- **Interactive Python Execution**: Execute Python code in a persistent REPL session
- **Session Management**: Create, manage, and switch between multiple REPL sessions
- **Variable Persistence**: Variables and imports persist across executions within a session
- **Rich Output**: Support for formatted output and complex objects
- **Error Handling**: Comprehensive error reporting with traceback information
### Project Integration
- **Virtual Environment Support**: Automatic detection and activation of `.venv` directories
- **UV Integration**: Add/remove packages using uv with automatic pyproject.toml updates
- **Dependency Management**: Install, upgrade, and remove packages with conflict resolution
- **Project Context**: Automatically load project modules and maintain sys.path
- **Environment Variable Management**: Load .env files and manage environment variables safely
### Advanced Capabilities
- **Code Introspection**: Inspect variables, functions, classes, and modules
- **Documentation Access**: Built-in help() and docstring retrieval
- **Import Management**: Smart import suggestions and auto-imports
- **File Operations**: Read/write project files with proper encoding detection
- **Git Integration**: Execute git commands within the project context
### Development Tools
- **Code Formatting**: Format code using black or ruff
- **Linting**: Run ruff linter with comprehensive Python checks
- **Testing**: Execute pytest with test discovery and reporting
- **Debugging Support**: Set breakpoints and step through code
- **Performance Profiling**: Time execution and memory usage analysis
## High-Level Architecture
```
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Claude Code │◄──►│ MCP Transport │◄──►│ MCP Server │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Python REPL Manager │
├─────────────────────────────────────────────────────────────────┤
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────────┐ │
│ │ Session │ │ Package │ │ Code Execution │ │
│ │ Manager │ │ Manager │ │ Engine │ │
│ └─────────────┘ └─────────────┘ └─────────────────────────┘ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────────┐ │
│ │ Environment │ │ File │ │ Introspection │ │
│ │ Handler │ │ Handler │ │ Tools │ │
│ └─────────────┘ └─────────────┘ └─────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Python Runtime │
├─────────────────────────────────────────────────────────────────┤
│ Virtual Environment (.venv) + Project Dependencies │
└─────────────────────────────────────────────────────────────────┘
```
## MCP Tools
### `python_execute`
Execute Python code in the active REPL session.
- **Parameters**: `code` (string), `session_id` (optional)
- **Returns**: Execution result, output, and any errors
### `python_inspect`
Inspect Python objects, variables, or modules.
- **Parameters**: `object_name` (string), `session_id` (optional)
- **Returns**: Object information, type, docstring, and attributes
### `session_create`
Create a new Python REPL session.
- **Parameters**: `session_name` (optional), `working_directory` (optional)
- **Returns**: Session ID and configuration
### `session_list`
List all active REPL sessions.
- **Returns**: Array of session information
### `session_switch`
Switch to a different REPL session.
- **Parameters**: `session_id` (string)
- **Returns**: Success status and session info
### `package_install`
Install Python packages using uv.
- **Parameters**: `packages` (array), `dev` (boolean, optional)
- **Returns**: Installation status and updated dependencies
### `package_remove`
Remove Python packages using uv.
- **Parameters**: `packages` (array)
- **Returns**: Removal status and updated dependencies
### `package_list`
List installed packages in the current environment.
- **Returns**: Package list with versions
### `file_read_project`
Read a file from the project directory with Python session context and encoding detection.
- **Parameters**: `file_path` (string), `encoding` (optional)
- **Returns**: File contents with metadata
- **Note**: Use built-in Read tool for general file reading - this is optimized for Python project files
### `file_write_project`
Write content to a file in the project directory with encoding detection and safety checks.
- **Parameters**: `file_path` (string), `content` (string), `encoding` (optional)
- **Returns**: Write status with metadata
- **Note**: Use built-in Write tool for general file writing - this provides additional safety and metadata
### `load_env_file`
Load environment variables from .env file.
- **Parameters**: `env_file_path` (optional, defaults to ".env")
- **Returns**: Loaded variables count and any errors
### `set_env_var`
Set an environment variable for the session.
- **Parameters**: `name` (string), `value` (string), `session_id` (optional)
- **Returns**: Success status
### `list_env_vars`
List current environment variables.
- **Parameters**: `session_id` (optional)
- **Returns**: Environment variables
### `create_env_template`
Generate .env.example from pydantic Settings model.
- **Parameters**: `settings_class` (string), `output_path` (optional)
- **Returns**: Generated template content
### `format_file`
Format a Python file using black or ruff.
- **Parameters**: `file_path` (string), `formatter` (optional: "black" or "ruff")
- **Returns**: Formatting status and results
### `lint_file`
Lint a Python file using ruff.
- **Parameters**: `file_path` (string), `fix` (boolean, optional)
- **Returns**: Linting results, errors, and auto-fixes
### `run_tests`
Execute tests using pytest.
- **Parameters**: `test_path` (optional), `pattern` (optional), `verbose` (boolean, optional)
- **Returns**: Test results, coverage, and detailed output
## Required Packages
### Core Dependencies
- **`mcp`**: MCP protocol implementation
- **`pydantic`**: Data validation and settings management
- **`asyncio`**: Asynchronous programming support
- **`subprocess`**: Process management for uv commands
### Python Execution
- **`code`**: Interactive Python interpreter
- **`sys`**: System-specific parameters and functions
- **`importlib`**: Dynamic import utilities
- **`ast`**: Abstract syntax tree utilities for code parsing
### Project Management
- **`pathlib`**: Modern path handling
- **`tomllib`**: TOML file parsing (Python 3.11+)
- **`packaging`**: Version parsing and comparison
- **`python-dotenv`**: .env file loading and management
### Development Tools
- **`black`**: Code formatting
- **`ruff`**: Fast linting and formatting
- **`pytest`**: Testing framework
- **`rich`**: Rich text and beautiful formatting
## Installation & Setup
### Prerequisites
- Python 3.11+
- `uv` package manager (install with `pip install uv`)
### Installing the MCP Server
1. **Clone and setup the project:**
```bash
git clone <repository-url>
cd mcp-py3repl
uv sync
```
2. **Install the server globally (optional):**
```bash
# For development
uv pip install -e .
# Or install from repository
pip install git+<repository-url>
```
### Configuring Claude Code to Use the Server
Add this configuration to your Claude Code MCP settings:
**Option 1: Using uv run (recommended for development):**
```json
{
"mcpServers": {
"mcp-py3repl": {
"command": "uv",
"args": ["run", "--directory", "/path/to/mcp-py3repl", "python", "-m", "mcp_py3repl.server"],
"env": {}
}
}
}
```
**Option 2: Using installed package:**
```json
{
"mcpServers": {
"mcp-py3repl": {
"command": "python",
"args": ["-m", "mcp_py3repl.server"],
"env": {}
}
}
}
```
**Option 3: Direct execution:**
```json
{
"mcpServers": {
"mcp-py3repl": {
"command": "/path/to/mcp-py3repl/.venv/bin/python",
"args": ["/path/to/mcp-py3repl/src/mcp_py3repl/server.py"],
"env": {}
}
}
}
```
### Verifying Installation
1. **Start Claude Code** with the MCP server configured
2. **Create a Python session** in your project directory:
```
Create a Python session in my current project directory
```
3. **Test basic functionality**:
```
Execute this Python code: print("Hello from MCP Python REPL!")
```
If successful, you should see output confirming the server is working with virtual environment activation.
## Configuration
The server automatically detects:
- Virtual environment location (`.venv`)
- Project configuration (`pyproject.toml`)
- Environment files (`.env`, `.env.local`)
- Python version and capabilities
- Available development tools (black, ruff, pytest)
- Pydantic Settings classes requiring environment variables
### Virtual Environment Management
The server provides intelligent virtual environment management:
- **Auto-detection**: Finds existing `.venv` directories in your project
- **Auto-creation**: Creates new virtual environments with `uv venv` if none exist
- **Auto-sync**: Installs dependencies with `uv sync` when creating new environments
- **Session isolation**: Each session is bound to its project directory's virtual environment
- **Monorepo support**: Multiple sessions can have different virtual environments for different subprojects
## Usage with Claude Code
### Getting Started
Once the MCP server is configured, you can interact with it through natural language in Claude Code. Here are common usage patterns:
#### Creating a Python Session
```
Create a Python session in my current project directory
```
or
```
Set up a Python REPL session in /path/to/my/project and activate the virtual environment
```
#### Project Integration Examples
```
# Load my project's environment variables and show me the database URL
Load the .env file and then execute: from app.config import settings; print(settings.database_url)
# Install a new dependency
Install the requests package using uv and add it to my project
# Format and lint my code
Format my main.py file using black
Then lint this code with ruff and show me any issues: [paste your code]
# Run my tests
Execute my project's test suite using pytest with verbose output
# Work with my models
Import my User model and create a sample instance with validation
```
#### Virtual Environment Management
The server automatically:
- **Detects existing `.venv`** in your project directory
- **Creates new virtual environments** with `uv venv` if none exist
- **Installs dependencies** with `uv sync` for new environments
- **Activates the environment** for each session so imports work correctly
#### Session-Based Workflow
```
# Create multiple sessions for different projects
Create a session called "api" in /path/to/my-api-project
Create a session called "frontend" in /path/to/my-frontend-project
# Switch between sessions
Switch to the "api" session
Execute: from api.models import User
# Each session maintains its own virtual environment and variables
```
### Advanced Usage
Once installed and configured, Claude Code can:
```bash
# Load environment variables
load_env_file()
# Execute Python code (with loaded env vars)
python_execute(code="from myapp.config import settings; print(settings.database_url)")
# Install packages
package_install(packages=["requests", "pydantic"])
# Set environment variables safely
set_env_var(name="DEBUG", value="true")
# Generate .env template
create_env_template(settings_class="myapp.config.Settings")
# Format file
format_file(file_path="src/myapp/main.py", formatter="black")
# Lint file
lint_file(file_path="src/myapp/main.py", fix=true)
# Run tests (with env vars loaded)
run_tests(test_path="tests/", verbose=true)
# Inspect objects
python_inspect(object_name="settings")
```
## Environment Variable Management
The server provides environment variable management:
- **Automatic .env Loading**: Detects and loads .env files on session creation
- **Pydantic Integration**: Works seamlessly with pydantic Settings models
- **Template Generation**: Creates .env.example files from Settings classes
- **Session Isolation**: Environment variables are isolated per REPL session
- **Local Overrides**: Supports .env.local for local overrides
## Testing
The MCP server includes comprehensive tests with a complete sample project to validate all functionality. **Important**: This test project structure is used solely for testing the MCP server's capabilities - the server itself is designed to work with any project structure that uses the supported technology stack.
### Test Structure
```
tests/
├── test_mcp_tools.py # Test MCP server tools
├── test_project/ # Complete sample project
│ ├── pyproject.toml # uv dependencies and project config
│ ├── .env # Environment variables for testing
│ ├── .env.example # Template for environment setup
│ ├── alembic.ini # Alembic configuration
│ ├── alembic/
│ │ ├── env.py # Alembic environment setup
│ │ └── versions/ # Database migration files
│ ├── app/
│ │ ├── main.py # FastAPI application entry point
│ │ ├── config.py # pydantic Settings configuration
│ │ ├── database.py # SQLModel database setup
│ │ ├── models/
│ │ │ ├── user.py # SQLModel User class
│ │ │ ├── post.py # SQLModel Post class
│ │ │ └── __init__.py
│ │ ├── api/
│ │ │ ├── users.py # FastAPI user endpoints
│ │ │ ├── posts.py # FastAPI post endpoints
│ │ │ └── __init__.py
│ │ └── services/
│ │ ├── rabbitmq.py # RabbitMQ client (mockable)
│ │ └── __init__.py
│ ├── tests/
│ │ ├── conftest.py # pytest fixtures (TestClient, test DB)
│ │ ├── test_models.py # pydantic validation tests
│ │ ├── test_api.py # FastAPI endpoint tests
│ │ ├── test_database.py # SQLModel database tests
│ │ └── test_services.py # Service layer tests
│ └── test.db # SQLite test database
```
### Test Project Features
The test project validates all MCP server capabilities across different project patterns. This demonstrates the server's ability to intelligently discover and interact with various project structures:
- **Environment Variables**: Tests .env loading and pydantic Settings integration
- **Database Migrations**: Alembic setup with SQLModel table creation
- **API Endpoints**: FastAPI routes with authentication and validation
- **Model Validation**: Complex pydantic models with custom validators
- **Dependency Injection**: Mockable services (database, RabbitMQ)
- **Code Quality**: Black formatting and ruff linting integration
- **Async Operations**: Async FastAPI endpoints and database operations
- **Testing Patterns**: pytest fixtures, TestClient, and dependency overrides
### Running Tests
```bash
# Test the MCP server itself
python -m pytest tests/test_mcp_tools.py -v
# Test using the sample project
cd tests/test_project
load_env_file()
run_tests(test_path="tests/", verbose=true)
# Test specific MCP tools
python_execute(code="from app.models.user import User; user = User(email='test@example.com')")
format_file(file_path="src/main.py")
lint_file(file_path="app/main.py")
```
## Next Steps
### FastAPI Integration
Future versions could include specialized support for FastAPI projects:
- **TestClient Integration**: Automatic setup of FastAPI TestClient for endpoint testing
- **Dependency Override Management**: Configure test dependencies (mock databases, external services)
- **API Endpoint Testing**: Dedicated tools for testing HTTP endpoints with authentication
- **Test Database Setup**: Automated SQLite test database creation and teardown
- **Mock Service Integration**: Support for mocking external services (RabbitMQ, Redis, APIs)
Example future capabilities:
```bash
# Setup test environment with dependency overrides
setup_test_dependencies(overrides={"get_db": "sqlite:///:memory:", "get_queue": "mock_rabbitmq"})
# Test API endpoints with authentication
test_api_endpoint(method="GET", endpoint="/users/me", headers={"Authorization": "Bearer token"})
```
### Pydantic & SQLModel Integration
Enhanced support for pydantic and SQLModel workflows:
- **Model Introspection**: `inspect_model(model_class)` - Show schema, fields, validators, examples
- **Data Validation**: `validate_data(model, data)` - Test data against models interactively
- **Sample Data Generation**: `generate_sample_data(model, count=5)` - Create realistic test data
- **Schema Export**: `model_to_json_schema(model)` - Export OpenAPI/JSON schemas
- **Table Management**: `create_test_tables(models)` - Generate SQLite tables from SQLModel classes
- **Test Data Seeding**: `seed_test_data(model, count=10)` - Populate test DB with realistic data
- **Table Inspection**: `inspect_table(table_name)` - Show schema, relationships, sample data
- **Query Builder**: Interactive SQL query building with model awareness
Example usage:
```bash
# Inspect your User model
inspect_model("User") # Shows fields, types, validators, example data
# Generate and validate test data
sample_users = generate_sample_data("User", count=5)
validate_data("User", {"email": "invalid@"}) # Shows validation errors
# Database operations
create_test_tables(["User", "Post", "Comment"])
seed_test_data("User", count=20)
inspect_table("users") # Shows current table state
```
### Alembic Integration
Database migration management for SQLModel projects:
- **Migration Creation**: `create_migration(message)` - Generate new migration files
- **Auto-generation**: `auto_generate_migration(message)` - Create migrations from SQLModel changes
- **Migration Status**: `migration_status()` - Show current revision and pending migrations
- **Migration Execution**: `run_migrations(target="head", database_url=None)` - Apply migrations safely
- **Database Reset**: `reset_test_db()` - Reset test database to clean state
- **Migration History**: `migration_history()` - Show migration timeline and changes
Example usage:
```bash
# Check current migration state
migration_status() # Shows current revision, pending migrations
# Create new migration from model changes
auto_generate_migration("add user preferences")
# Apply migrations to test database
run_migrations(target="head", database_url="sqlite:///test.db")
# Reset test environment for clean testing
reset_test_db() # Drops tables, re-runs migrations
```
These integrations would make the MCP server particularly powerful for modern Python web development with the FastAPI + SQLModel + Pydantic + Alembic stack.
This MCP server bridges the gap between Claude Code's AI capabilities and Python development workflows, making it an essential tool for Python developers using Claude Code.
## Quick Reference
### Common Claude Code Commands
| What you want to do | Say this to Claude Code |
|---------------------|-------------------------|
| Set up Python environment | "Create a Python session in my current project directory" |
| Install packages | "Install pandas and requests using uv" |
| Load environment variables | "Load my .env file and show me the loaded variables" |
| Run code with project imports | "Execute: from app.models import User; print(User.__fields__)" |
| Format file | "Format my main.py file using black" |
| Run tests | "Run my pytest suite with verbose output" |
| Inspect objects | "Show me details about my settings object" |
| Work with multiple projects | "Create sessions for my api and frontend projects" |
### Key Features Summary
✅ **Virtual Environment Integration** - Automatic `.venv` detection and activation
✅ **Project-Aware Sessions** - Each session bound to a project directory with isolated environments
✅ **Modern Python Stack** - FastAPI, SQLModel, Pydantic, Alembic support
✅ **Package Management** - uv integration for dependency management
✅ **Development Tools** - Code formatting (black/ruff), linting, testing
✅ **Environment Variables** - Secure .env loading and pydantic Settings integration
✅ **Monorepo Support** - Multiple isolated sessions for different subprojects
### Troubleshooting
**"Module not found" errors:**
- Ensure you created the session in your project directory
- Check that `.venv` exists or was created automatically
- Verify `uv sync` ran successfully during session creation
**MCP server not responding:**
- Check Claude Code's MCP server configuration
- Verify the path to the mcp-py3repl directory is correct
- Ensure `uv` is installed and available in your PATH
**Virtual environment issues:**
- The server auto-creates `.venv` with `uv venv` if missing
- Dependencies are installed with `uv sync`
- Each session is isolated to its project directory