Loads and manages environment variables from .env files, including listing and setting environment variables for sessions.
Detects and analyzes FastAPI projects to understand endpoints and framework patterns for intelligent project interaction.
Executes git commands within the project context for version control operations.
Introspects Pydantic models and Settings classes, including generation of .env.example templates from Settings definitions.
Executes tests with test discovery, coverage reporting, and detailed test output.
Provides an interactive Python REPL with session management, code execution, variable persistence, and introspection capabilities for Python development projects.
Provides rich text and formatted output for REPL results and complex objects.
Lints and formats Python files using Ruff with auto-fix capabilities and comprehensive Python checks.
Parses pyproject.toml files for project configuration and dependency management.
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,.envfiles,alembic.ini, and framework importsIntelligent 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
.venvdirectoriesUV 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
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 implementationpydantic: Data validation and settings managementasyncio: Asynchronous programming supportsubprocess: Process management for uv commands
Python Execution
code: Interactive Python interpretersys: System-specific parameters and functionsimportlib: Dynamic import utilitiesast: Abstract syntax tree utilities for code parsing
Project Management
pathlib: Modern path handlingtomllib: TOML file parsing (Python 3.11+)packaging: Version parsing and comparisonpython-dotenv: .env file loading and management
Development Tools
black: Code formattingruff: Fast linting and formattingpytest: Testing frameworkrich: Rich text and beautiful formatting
Installation & Setup
Prerequisites
Python 3.11+
uvpackage manager (install withpip install uv)
Installing the MCP Server
Clone and setup the project:
Install the server globally (optional):
Configuring Claude Code to Use the Server
Add this configuration to your Claude Code MCP settings:
Option 1: Using uv run (recommended for development):
Option 2: Using installed package:
Option 3: Direct execution:
Verifying Installation
Start Claude Code with the MCP server configured
Create a Python session in your project directory:
Create a Python session in my current project directoryTest 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
.venvdirectories in your projectAuto-creation: Creates new virtual environments with
uv venvif none existAuto-sync: Installs dependencies with
uv syncwhen creating new environmentsSession 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
or
Project Integration Examples
Virtual Environment Management
The server automatically:
Detects existing in your project directory
Creates new virtual environments with
uv venvif none existInstalls dependencies with
uv syncfor new environmentsActivates the environment for each session so imports work correctly
Session-Based Workflow
Advanced Usage
Once installed and configured, Claude Code can:
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
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
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:
Pydantic & SQLModel Integration
Enhanced support for pydantic and SQLModel workflows:
Model Introspection:
inspect_model(model_class)- Show schema, fields, validators, examplesData Validation:
validate_data(model, data)- Test data against models interactivelySample Data Generation:
generate_sample_data(model, count=5)- Create realistic test dataSchema Export:
model_to_json_schema(model)- Export OpenAPI/JSON schemasTable Management:
create_test_tables(models)- Generate SQLite tables from SQLModel classesTest Data Seeding:
seed_test_data(model, count=10)- Populate test DB with realistic dataTable Inspection:
inspect_table(table_name)- Show schema, relationships, sample dataQuery Builder: Interactive SQL query building with model awareness
Example usage:
Alembic Integration
Database migration management for SQLModel projects:
Migration Creation:
create_migration(message)- Generate new migration filesAuto-generation:
auto_generate_migration(message)- Create migrations from SQLModel changesMigration Status:
migration_status()- Show current revision and pending migrationsMigration Execution:
run_migrations(target="head", database_url=None)- Apply migrations safelyDatabase Reset:
reset_test_db()- Reset test database to clean stateMigration History:
migration_history()- Show migration timeline and changes
Example usage:
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
.venvexists or was created automaticallyVerify
uv syncran 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
uvis installed and available in your PATH
Virtual environment issues:
The server auto-creates
.venvwithuv venvif missingDependencies are installed with
uv syncEach session is isolated to its project directory