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.
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.
- 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
- 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
- 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
- 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
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ 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 │
└─────────────────────────────────────────────────────────────────┘
Execute Python code in the active REPL session.
- Parameters:
code
(string),session_id
(optional) - Returns: Execution result, output, and any errors
Inspect Python objects, variables, or modules.
- Parameters:
object_name
(string),session_id
(optional) - Returns: Object information, type, docstring, and attributes
Create a new Python REPL session.
- Parameters:
session_name
(optional),working_directory
(optional) - Returns: Session ID and configuration
List all active REPL sessions.
- Returns: Array of session information
Switch to a different REPL session.
- Parameters:
session_id
(string) - Returns: Success status and session info
Install Python packages using uv.
- Parameters:
packages
(array),dev
(boolean, optional) - Returns: Installation status and updated dependencies
Remove Python packages using uv.
- Parameters:
packages
(array) - Returns: Removal status and updated dependencies
List installed packages in the current environment.
- Returns: Package list with versions
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
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 environment variables from .env file.
- Parameters:
env_file_path
(optional, defaults to ".env") - Returns: Loaded variables count and any errors
Set an environment variable for the session.
- Parameters:
name
(string),value
(string),session_id
(optional) - Returns: Success status
List current environment variables.
- Parameters:
session_id
(optional) - Returns: Environment variables
Generate .env.example from pydantic Settings model.
- Parameters:
settings_class
(string),output_path
(optional) - Returns: Generated template content
Format a Python file using black or ruff.
- Parameters:
file_path
(string),formatter
(optional: "black" or "ruff") - Returns: Formatting status and results
Lint a Python file using ruff.
- Parameters:
file_path
(string),fix
(boolean, optional) - Returns: Linting results, errors, and auto-fixes
Execute tests using pytest.
- Parameters:
test_path
(optional),pattern
(optional),verbose
(boolean, optional) - Returns: Test results, coverage, and detailed output
mcp
: MCP protocol implementationpydantic
: Data validation and settings managementasyncio
: Asynchronous programming supportsubprocess
: Process management for uv commands
code
: Interactive Python interpretersys
: System-specific parameters and functionsimportlib
: Dynamic import utilitiesast
: Abstract syntax tree utilities for code parsing
pathlib
: Modern path handlingtomllib
: TOML file parsing (Python 3.11+)packaging
: Version parsing and comparisonpython-dotenv
: .env file loading and management
black
: Code formattingruff
: Fast linting and formattingpytest
: Testing frameworkrich
: Rich text and beautiful formatting
- Python 3.11+
uv
package manager (install withpip install uv
)
- Clone and setup the project:
git clone <repository-url>
cd mcp-py3repl
uv sync
- Install the server globally (optional):
# For development
uv pip install -e .
# Or install from repository
pip install git+<repository-url>
Add this configuration to your Claude Code MCP settings:
Option 1: Using uv run (recommended for development):
{
"mcpServers": {
"mcp-py3repl": {
"command": "uv",
"args": ["run", "--directory", "/path/to/mcp-py3repl", "python", "-m", "mcp_py3repl.server"],
"env": {}
}
}
}
Option 2: Using installed package:
{
"mcpServers": {
"mcp-py3repl": {
"command": "python",
"args": ["-m", "mcp_py3repl.server"],
"env": {}
}
}
}
Option 3: Direct execution:
{
"mcpServers": {
"mcp-py3repl": {
"command": "/path/to/mcp-py3repl/.venv/bin/python",
"args": ["/path/to/mcp-py3repl/src/mcp_py3repl/server.py"],
"env": {}
}
}
}
- Start Claude Code with the MCP server configured
- Create a Python session in your project directory:
Create a Python session in my current project directory
- 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.
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
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
Once the MCP server is configured, you can interact with it through natural language in Claude Code. Here are common usage patterns:
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
# 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
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
# 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
Once installed and configured, Claude Code can:
# 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")
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
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.
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
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
# 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")
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:
# 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"})
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:
# 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
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:
# 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.
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" |
✅ 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
"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
withuv venv
if missing - Dependencies are installed with
uv sync
- Each session is isolated to its project directory