Python代码执行服务器

MCP Code Mode是一个通用的Python代码执行服务器,支持自动安装依赖、实时流输出、文件自动显示等功能,适用于各种开发场景。

  • by anaseqal
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 anaseqal/codemode

使用说明

MCP代码模式🐍⚡

通用Python代码执行MCP服务器-一个管理所有代码的工具。

受...启发 Cloudflare的代码模式LLM更擅长编写代码而不是调用工具,因为他们已经在数百万个真实的存储库上进行了培训。

为什么是代码模式?

传统方法 (许多工具):

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...

代码模式方法 (一个工具):

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")

好处

传统工具 代码模式
❌ LLM难以使用合成工具调用格式 ✅ LLMs擅长编写真正的代码
❌ 每次工具调用=往返LLM ✅ 一次执行中的复杂工作流
❌ 管理20多个扩展 ✅ 一个通用工具
❌ 令牌浪费在调用之间传递数据 ✅ 代码中的高效数据流
❌ 仅限于预构建功能 ✅ Python能做的任何事情

适用于任何MCP客户端

  • ✅ 鹅 (Block的AI代理)
  • ✅ 克劳德桌面版
  • ✅ 光标
  • ✅ VS代码与副本
  • ✅ 任何MCP兼容代理

特性

🚀 通用执行

编写Python来完成任何任务——HTTP请求、文件操作、数据处理、网络抓取、图像操作等等。

📦 自动安装依赖关系

丢失包裹?代码模式检测 ModuleNotFoundError,安装包,并自动重试。

🌊 流输出

实时查看结果! run_python_stream 在代码执行时逐行显示输出。非常适合长时间运行的任务、进度条和监控实时操作。

🖼️ 自动文件显示(Goose兼容!)

生成的图像、日志或数据文件?代码模式会自动检测并在MCP客户端中显示它们!支持:

  • 图像:PNG、JPG、GIF、SVG、HEIC、TIFF等。(内联显示)
  • 文本文件:JSON、日志、源代码(Python、JS、TS、Go、Rust等)、CSV、YAML等。(以语法高亮显示)
  • 资源:PDF、档案、视频(MP4、MOV)、音频(MP3、WAV)、Office文档、数据库(可供下载)

只需打印文件路径,其余部分由代码模式处理!与Goose和其他MCP客户端无缝协作。

🧠 双重学习系统(增强版!)

记录 基于错误和语义的失败:

  • 错误学习:捕获错误(ModuleNotFoundError、SSL错误等)及其解决方案
  • 语义学习:学习代码何时成功运行但未实现目标

未来的执行受益于过去的学习。在会议期间持续存在。

🔄 智能重试

run_with_retry 分析故障,并根据错误模式和类似任务的语义学习提出修复建议。

🐳 可选Docker沙盒

在隔离的Docker容器中运行代码以增强安全性。

⚙️ 可配置的

调整超时、执行模式、包限制等。

安装

来自PyPI(发布时)

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

# Using pip
pip install mcp-pyrunner

来源

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

配置

鹅

如果从PyPI安装:

编辑 ~/.config/goose/config.yaml:

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

如果从源代码运行(本地开发):

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)

或者使用UI:扩展→ 添加自定义扩展名→ 标准输入输出→ 命令: uv run --directory /path/to/codemode mcp-pyrunner

克劳德桌面版

编辑 ~/Library/Application Support/Claude/claude_desktop_config.json:

如果从PyPI安装:

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

如果从源代码运行:

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

光标

增添 .cursor/mcp.json:

如果从PyPI安装:

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

如果从源代码运行:

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

可用工具

工具 说明
get_system_context 获取环境信息(操作系统、Python、pip版本、包管理器、学习)
run_python 执行Python代码(自动安装包,自动显示文件)
run_python_stream 执行 实时流媒体输出 (自动显示文件)
run_with_retry 使用智能重试、错误分析和语义学习建议执行
add_learning 记录基于错误的解决方案以供将来参考
record_semantic_failure 新 记录代码运行但未达到目标的时间
get_learnings 查看/搜索过去的学习(包括错误和语义)
pip_install 预安装特定软件包
configure 查看/更新设置

使用示例

Web剪贴

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")

数据处理

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集成

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")

图像处理

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}")

流输出(实时进度)

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!

自动文件显示

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!

配置选项

查看当前配置:

→ configure()

更新设置:

→ configure(action="set", key="execution_mode", value="docker")
→ configure(action="set", key="default_timeout", value="120")
设置 值 说明
execution_mode direct, docker 如何运行代码
default_timeout integer 默认超时(秒)
max_retries integer 默认重试次数
auto_install true, false 自动安装软件包
docker_image string 沙盒的Docker镜像

双重学习系统

代码模式从中学习 两种类型的故障:

1.基于错误的学习

当你解决一个错误时,记录下来:

→ 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"
)

2.语义学习(新增!)

当代码成功运行但未达到目标时:

→ record_semantic_failure(
    objective="Display image in Goose app",
    failed_approach="Used print() to output file path",
    successful_approach="Returned base64 encoded image as MCP content object",
    context="MCP clients need structured content objects, not just paths",
    tags="goose,mcp,display,images"
)

为什么语义学习很重要:

  • 代码执行无错误≠目标完成
  • 人工智能从“技术上正确但语义上错误”的方法中学习
  • 未来实现类似目标的尝试将受益于过去的语义学习

查看学习内容

→ get_learnings()              # View all learnings (error + semantic)
→ get_learnings(search="ssl")  # Search learnings

学习内容以图标区分:

  • 🔴 基于错误的学习
  • 🔵 语义学习

学习坚持 ~/.mcp-pyrunner/learnings.json 并改善未来的执行情况。

数据存储

代码模式将数据存储在 ~/.mcp-pyrunner/:

~/.mcp-pyrunner/
├── config.json       # User configuration
├── learnings.json    # Error patterns and solutions
└── execution_log.json # Recent execution history

安全考虑

⚠️ 代码模式执行任意Python代码。

直接模式 (默认):

  • 代码以您的用户权限运行
  • 完整的文件系统和网络访问
  • 快速执行

Docker模式 (更安全):

  • 代码在隔离容器中运行
  • 资源有限(512MB RAM,1个CPU)
  • 网络接入可用
  • 启动速度较慢

启用Docker模式:

→ configure(action="set", key="execution_mode", value="docker")

测试

# Run tests
uv run pytest

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

贡献

欢迎投稿!感兴趣的领域:

  • [x] 长时间运行的代码的流式输出✅ 完成!
  • [x] 自动文件显示(图像、文本、资源)✅ 完成!
  • [x] 增强的系统上下文(pip版本、包管理器)✅ 完成!
  • []用于语义学习搜索的矢量数据库
  • []Pyodide/WASM沙盒选项
  • []执行前的代码分析
  • []资源使用情况跟踪
  • []多文件项目支持

许可证

麻省理工学院

致谢