Skip to main content

Universal Python code execution MCP server - one tool to rule them all

Project description

MCP Code Mode ๐Ÿโšก

Universal Python code execution MCP server - one tool to rule them all.

Inspired by Cloudflare's Code Mode: LLMs are better at writing code than making tool calls because they've trained on millions of real repositories.

Why Code Mode?

Traditional approach (many tools):

User: "Get weather for Austin and save to file"

LLM: [tool_call: get_weather(location="Austin")]
     โ†’ waits for response...
LLM: [tool_call: write_file(path="weather.txt", content=...)]
     โ†’ waits for response...

Code Mode approach (one tool):

User: "Get weather for Austin and save to file"

LLM: [run_python]
import requests
weather = requests.get("https://wttr.in/Austin?format=j1").json()
temp = weather['current_condition'][0]['temp_F']
with open("weather.txt", "w") as f:
    f.write(f"Austin: {temp}ยฐF")
print(f"Saved! Temperature: {temp}ยฐF")

Benefits

Traditional Tools Code Mode
โŒ LLMs struggle with synthetic tool-call format โœ… LLMs excel at writing real code
โŒ Each tool call = round trip to LLM โœ… Complex workflows in one execution
โŒ Managing 20+ extensions โœ… One universal tool
โŒ Token waste passing data between calls โœ… Efficient data flow in code
โŒ Limited to pre-built capabilities โœ… Anything Python can do

Works With Any MCP Client

  • โœ… Goose (Block's AI agent)
  • โœ… Claude Desktop
  • โœ… Cursor
  • โœ… VS Code with Copilot
  • โœ… Any MCP-compatible agent

Features

๐Ÿš€ Universal Execution

Write Python to accomplish any task - HTTP requests, file operations, data processing, web scraping, image manipulation, and more.

๐Ÿ“ฆ Auto-Install Dependencies

Missing a package? Code Mode detects ModuleNotFoundError, installs the package, and retries automatically.

๐ŸŒŠ Streaming Output

See results in real-time! run_python_stream shows output line-by-line as your code executes. Perfect for long-running tasks, progress bars, and monitoring live operations.

๐Ÿ–ผ๏ธ Automatic File Display

Generated images, logs, or data files? Code Mode automatically detects and displays them in your MCP client! Supports:

  • Images: PNG, JPG, GIF, SVG, etc. (displayed inline)
  • Text Files: JSON, logs, source code, CSV, etc. (shown with syntax highlighting)
  • Resources: PDFs, archives (available for download)

Just print the file path and Code Mode handles the rest!

๐Ÿ”’ Code Analysis Before Execution

Every code execution is automatically analyzed for security and quality issues:

  • Syntax validation - Catch errors before running
  • Security scanning - Detect eval(), exec(), os.system(), shell injection
  • Risk detection - Warn about file deletion, path traversal, hardcoded secrets
  • Severity levels - Critical (blocks execution), Warning, Info
  • Smart suggestions - Get safer alternatives for risky patterns

Analysis is automatic and configurable - see issues before they cause problems!

๐Ÿ“Š Resource Usage Tracking (NEW!)

Monitor code execution performance in real-time:

  • CPU usage - Track peak CPU utilization
  • Memory consumption - Monitor RAM usage (current + peak)
  • Thread count - See concurrent thread usage
  • Automatic warnings - Get alerts when exceeding configurable thresholds
  • Execution logs - All metrics saved for historical analysis

Perfect for optimizing code performance and detecting resource-heavy operations!

๐Ÿ“š MCP Resources (NEW!)

Expose data as MCP resources for automatic LLM context:

  • learnings://database - All learned error patterns and solutions
  • system://context - System info, Python version, package managers
  • executions://recent - Recent execution history with statistics

Compatible MCP clients can access these resources automatically, improving code generation without manual tool calls!

๐Ÿ“ก Context Injection & Progress Reporting (NEW!)

Real-time progress updates and structured logging during execution:

  • Progress tracking - See execution stages (analyzing, executing, processing) in real-time
  • Structured logging - Detailed logs at each execution step via ctx.info()
  • Smart updates - Progress bars show completion percentage for long-running tasks
  • Error reporting - Immediate notification when issues occur

Tools with context injection: run_python, run_python_stream, run_with_retry

๐Ÿ—๏ธ Structured Output with Type Safety (NEW!)

Type-safe data models using Python dataclasses:

  • ExecutionResult - Strongly-typed execution results with IDE autocomplete
  • CodeAnalysisResult - Structured code analysis reports with issue tracking
  • ResourceMetrics - Typed performance metrics
  • Learning - Type-safe learning storage

Benefits: Better IDE support, type checking, self-documenting contracts, automatic JSON serialization

โœจ MCP Prompts (NEW!)

Reusable prompt templates for common workflows:

  • ๐Ÿ› debug_assistant - Analyze errors with past learnings and step-by-step fixes
  • โšก code_optimizer - Improve performance, memory usage, or readability
  • ๐Ÿ‘€ code_reviewer - Comprehensive code review with security analysis
  • ๐Ÿ“ˆ data_explorer - Data analysis and visualization guidance
  • ๐Ÿ”Œ api_tester - API endpoint testing and validation

Simply invoke prompts with arguments to get expert guidance tailored to your task!

๐ŸŽจ Visual Icons (NEW!)

Every tool, resource, and prompt now has a distinctive icon for easy recognition:

  • Tools: โ–ถ๏ธ run_python, ๐ŸŒŠ stream, ๐Ÿ”„ retry, ๐Ÿ’ก learn, ๐Ÿ“ฆ install, โš™๏ธ configure
  • Resources: ๐Ÿง  learnings, ๐Ÿ–ฅ๏ธ system, ๐Ÿ“Š executions
  • Prompts: ๐Ÿ› debug, โšก optimize, ๐Ÿ‘€ review, ๐Ÿ“ˆ data, ๐Ÿ”Œ api

Improves discoverability and user experience in MCP clients!

๐Ÿ’ฌ Smart Completions (NEW!)

Argument auto-completion for faster workflows:

  • Package names - Suggests popular Python packages when using pip_install
  • Optimization focus - Completion for performance, memory, readability options
  • Review types - Suggests security, quality, or comprehensive review modes
  • HTTP methods - Auto-completes GET, POST, PUT, DELETE, etc.

Type-ahead suggestions make tools easier and faster to use!

๐Ÿง  Learning System

Records error patterns and solutions. Future executions benefit from past learnings. Persists across sessions.

๐Ÿ”„ Intelligent Retry

run_with_retry analyzes failures and suggests fixes based on error patterns and past learnings.

๐Ÿณ Optional Docker Sandbox

Run code in isolated Docker containers for enhanced security.

โš™๏ธ Configurable

Adjust timeouts, execution modes, package restrictions, and more.

Installation

From PyPI (when published)

# Using uv (recommended)
uv tool install mcp-pyrunner

# Using pip
pip install mcp-pyrunner

From Source

git clone https://github.com/anaseqal/codemode.git
cd codemode
uv sync

Configuration

Goose

If installed from PyPI:

Edit ~/.config/goose/config.yaml:

extensions:
  codemode:
    type: stdio
    enabled: true
    cmd: uvx
    args: ["mcp-pyrunner"]

If running from source (local development):

extensions:
  codemode:
    type: stdio
    enabled: true
    cmd: uv
    args: ["run", "--directory", "/path/to/codemode", "mcp-pyrunner"]
    # Replace /path/to/codemode with actual path (e.g., ~/codemode)

Or use the UI: Extensions โ†’ Add Custom Extension โ†’ STDIO โ†’ Command: uv run --directory /path/to/codemode mcp-pyrunner

Claude Desktop

Edit ~/Library/Application Support/Claude/claude_desktop_config.json:

If installed from PyPI:

{
  "mcpServers": {
    "codemode": {
      "command": "uvx",
      "args": ["mcp-pyrunner"]
    }
  }
}

If running from source:

{
  "mcpServers": {
    "codemode": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/codemode", "mcp-pyrunner"]
    }
  }
}

Cursor

Add to .cursor/mcp.json:

If installed from PyPI:

{
  "mcpServers": {
    "codemode": {
      "command": "uvx",
      "args": ["mcp-pyrunner"]
    }
  }
}

If running from source:

{
  "mcpServers": {
    "codemode": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/codemode", "mcp-pyrunner"]
    }
  }
}

Available MCP Resources

MCP clients that support resources can automatically access these data sources without calling tools:

Resource URI Description
learnings://database Complete learnings database with all error patterns and solutions
system://context System information, Python version, package managers, configuration
executions://recent Recent execution history with success/failure statistics and resource metrics

Resources provide context to LLMs automatically, improving code generation quality without manual tool calls.

Available Tools

Tool Description
get_system_context Get environment info (OS, Python, pip versions, package managers, learnings)
analyze_code_tool Analyze code for security/quality issues without executing
run_python Execute Python code (auto-analyzes, auto-installs packages, auto-displays files)
run_python_stream Execute with real-time streaming output (auto-analyzes, auto-displays files)
run_with_retry Execute with intelligent retry and error analysis
add_learning Record solutions for future reference
get_learnings View/search past learnings
pip_install Pre-install a specific package
configure View/update settings

Usage Examples

Code Analysis

User: "Analyze this code for security issues"

โ†’ analyze_code_tool:
code = '''
import os
password = "hardcoded123"
os.system(f"rm {user_file}")
result = eval(user_input)
'''

# Result:
๐Ÿ“Š CODE ANALYSIS REPORT
============================================================

๐Ÿšจ CRITICAL ISSUES (2):
   ๐Ÿšจ [CRITICAL] Dangerous operation 'os.system()' detected (line 4)
   ๐Ÿ’ก Suggestion: Use subprocess.run() instead for better security

   ๐Ÿšจ [CRITICAL] Dangerous function 'eval()' detected (line 5)
   ๐Ÿ’ก Suggestion: Executes arbitrary code - use ast.literal_eval() for safe evaluation

โ„น๏ธ  INFORMATION (1):
   โ„น๏ธ [INFO] Potential hardcoded password
   ๐Ÿ’ก Suggestion: Use environment variables or secure vaults instead

============================================================
โš ๏ธ Code has security concerns - review before executing

# Analysis runs automatically on every execution!
# Configure strictness with:
# configure(action="set", key="code_analysis.block_on_critical", value="true")

Resource Tracking

User: "Calculate fibonacci numbers up to 1 million"

โ†’ run_python:
def fibonacci(n):
    a, b = 0, 1
    result = []
    while a < n:
        result.append(a)
        a, b = b, a + b
    return result

fib = fibonacci(1000000)
print(f"Generated {len(fib)} Fibonacci numbers")
print(f"Largest: {fib[-1]:,}")

# Automatic resource tracking output:
๐Ÿ“Š RESOURCE USAGE:
   โœ“ CPU: 45.2%
   โœ“ Memory: 12.4MB (peak: 15.8MB)
   โœ“ Threads: 1
   โœ“ Time: 0.15s

# If resources exceed thresholds:
โš ๏ธ  RESOURCE WARNINGS:
   โ€ข High CPU usage: 92.3% (threshold: 90%)
   โ€ข High memory usage: 520MB (threshold: 500MB)

# Configure thresholds:
# configure(action="set", key="resource_tracking.warn_cpu_percent", value="80")
# configure(action="set", key="resource_tracking.warn_memory_mb", value="1000")

Web Scraping

User: "Scrape the top 10 posts from Hacker News"

โ†’ run_python:
import requests
from bs4 import BeautifulSoup

resp = requests.get("https://news.ycombinator.com")
soup = BeautifulSoup(resp.text, "html.parser")

for i, item in enumerate(soup.select(".titleline > a")[:10], 1):
    print(f"{i}. {item.text}")
    print(f"   {item['href']}\n")

Data Processing

User: "Analyze sales.csv and show monthly totals"

โ†’ run_python:
import pandas as pd

df = pd.read_csv("sales.csv")
df["date"] = pd.to_datetime(df["date"])
monthly = df.groupby(df["date"].dt.to_period("M"))["amount"].sum()

print("Monthly Sales:")
for period, total in monthly.items():
    print(f"  {period}: ${total:,.2f}")

API Integration

User: "Get the current Bitcoin price in USD"

โ†’ run_python:
import requests

data = requests.get("https://api.coinbase.com/v2/prices/BTC-USD/spot").json()
price = float(data["data"]["amount"])
print(f"Bitcoin: ${price:,.2f} USD")

Image Processing

User: "Resize all images in ./photos to 800x600"

โ†’ run_python:
from pathlib import Path
from PIL import Image

photos = Path("./photos")
for img_path in photos.glob("*.jpg"):
    img = Image.open(img_path)
    img.thumbnail((800, 600))
    img.save(img_path)
    print(f"Resized: {img_path.name}")

Streaming Output (Real-Time Progress)

User: "Scrape top 20 HN posts with progress updates"

โ†’ run_python_stream:
import requests
from bs4 import BeautifulSoup
import time

print("๐Ÿ” Starting to scrape Hacker News...")

resp = requests.get("https://news.ycombinator.com")
soup = BeautifulSoup(resp.text, "html.parser")
stories = soup.select(".titleline > a")[:20]

print(f"๐Ÿ“Š Found {len(stories)} stories. Processing...\n")

for i, story in enumerate(stories, 1):
    # Show progress in real-time
    progress = "โ–ˆ" * i + "โ–‘" * (20 - i)
    print(f"[{progress}] {i}/20: {story.text}")
    time.sleep(0.5)  # See each item appear live!

print("\nโœ… Scraping complete!")

# Output appears LINE BY LINE as the code runs,
# not all at once at the end!

Automatic File Display

User: "Take a screenshot of example.com and create a summary report"

โ†’ run_python:
from playwright.sync_api import sync_playwright
import json

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("https://example.com")

    # Take screenshot
    screenshot_path = "/tmp/example_screenshot.png"
    page.screenshot(path=screenshot_path)

    # Create report
    report = {
        "url": "https://example.com",
        "title": page.title(),
        "screenshot": screenshot_path,
        "timestamp": "2025-01-26T12:00:00"
    }

    report_path = "/tmp/report.json"
    with open(report_path, "w") as f:
        json.dump(report, f, indent=2)

    browser.close()

    # Print file paths - Code Mode auto-detects and displays them!
    print(f"Screenshot saved to: {screenshot_path}")
    print(f"Report saved to: {report_path}")

# Result: Your MCP client displays the screenshot IMAGE inline
# and shows the JSON content formatted - no manual handling needed!

Configuration Options

View current config:

โ†’ configure()

Update settings:

โ†’ configure(action="set", key="execution_mode", value="docker")
โ†’ configure(action="set", key="default_timeout", value="120")
Setting Values Description
execution_mode direct, docker How to run code
default_timeout integer Default timeout (seconds)
max_retries integer Default retry attempts
auto_install true, false Auto-install packages
docker_image string Docker image for sandbox
code_analysis.enabled true, false Enable code analysis
code_analysis.block_on_critical true, false Block execution on critical issues
code_analysis.show_report true, false Show analysis report in output
resource_tracking.enabled true, false Enable resource usage tracking
resource_tracking.show_in_output true, false Display metrics in output
resource_tracking.warn_cpu_percent integer CPU usage warning threshold (%)
resource_tracking.warn_memory_mb integer Memory usage warning threshold (MB)

Learning System

When you solve an error, record it:

โ†’ add_learning(
    error_pattern="SSL: CERTIFICATE_VERIFY_FAILED",
    solution="Use verify=False or install/update certifi",
    context="HTTPS requests on systems with cert issues",
    tags="ssl,https,certificates"
)

View learnings:

โ†’ get_learnings()
โ†’ get_learnings(search="ssl")

Learnings persist in ~/.mcp-pyrunner/learnings.json and improve future executions.

Data Storage

Code Mode stores data in ~/.mcp-pyrunner/:

~/.mcp-pyrunner/
โ”œโ”€โ”€ config.json       # User configuration
โ”œโ”€โ”€ learnings.json    # Error patterns and solutions
โ””โ”€โ”€ execution_log.json # Recent execution history

Security Considerations

โš ๏ธ Code Mode executes arbitrary Python code.

Direct mode (default):

  • Code runs with your user permissions
  • Full filesystem and network access
  • Fast execution

Docker mode (more secure):

  • Code runs in isolated container
  • Limited resources (512MB RAM, 1 CPU)
  • Network access available
  • Slower startup

Enable Docker mode:

โ†’ configure(action="set", key="execution_mode", value="docker")

Testing

# Run tests
uv run pytest

# Test with MCP Inspector
uv run mcp dev src/mcp_codemode/server.py
# Open http://localhost:5173

Contributing

Contributions welcome! Features are prioritized by impact.

โœ… Completed Features

Core Features:

  • Streaming output for long-running code โœ…
  • Automatic file display (images, text, resources) โœ…
  • Enhanced system context (pip version, package managers) โœ…
  • Code analysis before execution โœ…
  • Resource usage tracking โœ…

Advanced MCP SDK Features:

  • MCP Resources โœ… - Expose learnings, system info, and execution logs as MCP resources
  • Context Injection โœ… - Real-time progress reporting and structured logging
  • Structured Output โœ… - Type-safe dataclasses for execution results and metrics
  • MCP Prompts โœ… - Reusable templates for debugging, optimization, review, data analysis, API testing
  • Icons โœ… - Visual identity for all tools, resources, and prompts
  • Completions โœ… - Smart argument auto-completion for faster workflows

๐Ÿš€ Next Priority

All high and medium impact features complete! ๐ŸŽ‰

๐Ÿ“Š Medium Impact (Completed!)

All medium impact features have been implemented!

๐Ÿ”ฎ Future Enhancements (Lower Priority)

Focus areas for future development:

  • Elicitation - Request user input mid-execution for interactive workflows
  • OAuth Authentication - Secure access to protected resources and APIs
  • Lifespan Context - Shared database connections and resource pooling
  • Vector DB for semantic learning search
  • Pyodide/WASM sandboxing option
  • Multi-file project support

License

MIT

Acknowledgments

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

mcp_pyrunner-0.1.8.tar.gz (273.0 kB view details)

Uploaded Source

Built Distribution

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

mcp_pyrunner-0.1.8-py3-none-any.whl (36.2 kB view details)

Uploaded Python 3

File details

Details for the file mcp_pyrunner-0.1.8.tar.gz.

File metadata

  • Download URL: mcp_pyrunner-0.1.8.tar.gz
  • Upload date:
  • Size: 273.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.3

File hashes

Hashes for mcp_pyrunner-0.1.8.tar.gz
Algorithm Hash digest
SHA256 ceccd9ec61f8a14d4a10b32692e435993de7ed2df93e236facd49add796e2d49
MD5 400cc24c2ea42c1bb4d0686bf5c0b81e
BLAKE2b-256 91bc1988689a42bee0804270223b3ec62f07d9aeedfdeb1c6d29d857cf7be099

See more details on using hashes here.

File details

Details for the file mcp_pyrunner-0.1.8-py3-none-any.whl.

File metadata

File hashes

Hashes for mcp_pyrunner-0.1.8-py3-none-any.whl
Algorithm Hash digest
SHA256 649f82e4b6178288a9cc443a9da5970238004a38f9d9ab819aa150ab78564f30
MD5 1af58483eddbf980e50937ac400a7762
BLAKE2b-256 2fca836e0c47135e92ed031d9f0bb18761fab4b0cfb029d17d4b22e9d8bc7b07

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