Python运行程序MCP服务器
基于FastMCP框架的Python代码执行服务器,专为数据科学和机器学习工作流程而设计。
🚀 特性
- 安全的Python代码执行:在隔离的命名空间中执行Python代码
- 丰富的数据科学图书馆:预装了常用的数据科学和机器学习软件包
- 实时输出捕获:捕获标准输出、错误输出和返回值
- MCP协议支持:与模型上下文协议完全兼容
- 易于使用:提供简单干净的API接口
⚡ 快速入门(推荐)
使用 uvx 无需安装即可直接运行服务器:\[TODO….\]
# Run directly (no pre-installation required)
uvx python-runner在Claude桌面中配置
将以下配置添加到您的Claude Desktop配置文件中:
{
"mcpServers": {
"python-runner": {
"command": "uvx",
"args": ["python-runner"]
}
}
}配置文件位置:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - 视窗:
%APPDATA%\Claude\claude_desktop_config.json
调试和测试
# Use MCP Inspector to debug the server
npx @modelcontextprotocol/inspector uvx python-runner📦 预装库
此项目预装了以下常用的数据科学和机器学习库:
- 数据处理:
numpy,pandas,scipy - 机器学习:
scikit-learn - 数据可视化:
matplotlib,seaborn,plotly - 科学计算:
sympy - 图像处理:
pillow - 网络分析:
networkx - 交互式开发:
jupyter - HTTP请求:
requests
🛠️ 手动安装(用于开发)
先决条件
- Python 3.12或更高版本
- uv包管理器(推荐)或pip
使用紫外线进行安装(推荐)
# Clone the repository
git clone
cd python_runner
# Install dependencies
uv sync使用pip安装
# Clone the repository
git clone
cd python_runner
# Create virtual environment
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# Install dependencies
pip install -e .🚀 用法
与Claude Desktop一起使用
配置后,您可以直接在Claude Desktop中使用Python代码执行功能:
Please help me execute this Python code:
import pandas as pd
import numpy as np
# Create sample data
data = pd.DataFrame({
'sales': [100, 150, 200, 120, 180],
'profit': [20, 30, 50, 25, 40]
})
print("Sales data statistics:")
print(data.describe())作为独立MCP服务器运行
# Using uvx (recommended)
uvx python-runner
# Or run locally
python main.pyAPI直接调用
from main import execute_python
# Execute simple Python code
result = execute_python("""
print("Hello, World!")
x = 1 + 2
print(f"Result: {x}")
""")
print(result)
# Output:
# {
# 'output': 'Hello, World!\nResult: 3\n',
# 'error': '',
# 'success': True
# }数据科学示例
# Data analysis example
code = """
import pandas as pd
import numpy as np
# Create sample data
data = pd.DataFrame({
'x': np.random.randn(100),
'y': np.random.randn(100)
})
print(f"Data shape: {data.shape}")
print(f"Statistical summary:\n{data.describe()}")
"""
result = execute_python(code)
print(result['output'])# Machine learning example
code = """
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
# Generate sample data
X, y = make_classification(n_samples=1000, n_features=20, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train model
clf = RandomForestClassifier(random_state=42)
clf.fit(X_train, y_train)
# Predict and evaluate
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Model accuracy: {accuracy:.4f}")
"""
result = execute_python(code)
print(result['output'])📋 api参考
execute_python(code: str) -> dict
执行Python代码并返回结果。
参数:
code(str):要执行的Python代码字符串
退货:
dict:包含以下键的词典:
- output (str):标准输出内容 - error (str):错误消息(如果有的话) - success (bool):执行是否成功
🔒 安全
- 代码在隔离的命名空间中执行
- 捕获并重定向标准输出和错误输出
- 提供详细的错误跟踪信息
⚠️ 警告:此工具执行任意Python代码。请确保您在受信任的环境中使用它。
🤝 贡献
欢迎问题和拉取请求!
- 分叉此存储库
- 创建要素分支(
git checkout -b feature/AmazingFeature) - 提交您的更改(
git commit -m 'Add some AmazingFeature') - 推到分支(
git push origin feature/AmazingFeature) - 打开拉取请求
📄 许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
🙏 致谢
- FastMCP -优秀的MCP框架
- 预装开源数据科学库的所有维护者
______________________________________________________________________
由以下材料制成❤️ 面向数据科学界
