MCP代码执行工具

一个展示如何使用模型上下文协议(MCP)进行代码执行的工具,集成了天气API和FAISS RAG系统,用于高效AI代理开发。

  • by s1v4-d
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 s1v4-d/mcp-code-exec

使用说明

代理MCP代码执行PoC

概念证明,演示了使用模型上下文协议(MCP)执行代码,以实现高效的AI代理,并增强了 天气API 和 基于FAISS的RAG 能力。

天气API集成

  • 使用OpenWeatherMap的实时天气数据
  • 具有时区感知的5天天气预报
  • 灵活的位置搜索(城市名称或邮政编码)
  • 集成为MCP工具 -代理可以生成代码来使用天气数据
  • 基于 langchain天气工具调用

基于FAISS的RAG系统

  • 使用向量嵌入进行文档索引
  • 快速语义相似度搜索
  • 多种嵌入选项(HuggingFace或OpenAI)
  • 文本文档的文件上传支持
  • 集成为MCP工具 -Agent可以存储和检索知识
  • 具有源跟踪功能的持久存储

MCP工具集成

天气和RAG都暴露在 MCP工具 代理可以通过生成Python代码来使用:

  • 代理接收用户请求
  • LLM生成调用MCP工具的代码
  • 代码在具有工具访问权限的沙盒中执行
  • 处理和总结结果

概述

本PoC实现了Anthropic关于 使用MCP执行代码,演示了代理如何使用代码执行更有效地与MCP服务器交互。

关键利益

  • 渐进呈现:按需加载工具定义,而不是预先加载
  • 上下文高效:在传递给LLM之前,在代码中过滤和转换数据
  • 强大的控制流:在代码中使用循环和条件语句,而不是链接工具调用
  • 隐私保护:中间结果留在执行环境中
  • 状态持久性:保存结果和技能以供重用

建筑

User Request → FastAPI → LangChain Orchestrator → Code Generator (LLM)
                                ↓
                        Generated Python Code
                                ↓
                        Code Executor (Sandbox)
                                ↓
                        MCP Client → MCP Tool Servers
                                ↓
                        Results → Workspace Files
                                ↓
                        Summary → User

快速开始

先决条件

  • Python 3.12+
  • OpenAI API密钥
  • OpenWeatherMap API密钥(可选,用于天气功能)
  • PostgreSQL数据库(可选,用于postgres-mcp功能)

快速开始

# 1. Clone and setup
git clone <repository>
cd mcp-code-exec
make setup

# 2. Configure environment
cp .env.example .env
# Edit .env with your API keys

# 3. Generate MCP tool wrappers
make wrappers

# 4. Start the server
make start

PostgreSQL MCP服务器

此项目现在使用 postgres mcp (从 crystaldba/postgres mcp)作为MCP服务器,提供:

  • 架构检查:浏览数据库、表、视图和序列
  • 安全查询执行:只读和无限制模式,带验证
  • 解释计划:使用假设索引分析查询性能
  • 索引调整:用于查询优化的人工智能索引建议
  • 数据库运行状况:监控连接、真空、复制等
  • 热门查询:识别慢速和资源密集型查询

代理可以按照MCP模式生成使用这些工具的代码。

设置PostgreSQL数据库

您有几个选择:

选项1:Docker(推荐)

docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=postgres --name postgres-mcp postgres:14
uv run python scripts/setup_pg.py  # Creates sample database

选项2:本地PostgreSQL

# Ubuntu/Debian
sudo apt-get install postgresql

# macOS
brew install postgresql@14

# Then create sample database
uv run python scripts/setup_pg.py

选项3:使用现有数据库 刚刚设置 DATABASE_URL 在 .env 到您现有的PostgreSQL实例。

特性

  • 代码执行:用于代理生成代码的安全Python沙盒
  • MCP集成:天气API和FAISS RAG作为MCP工具
  • PostgreSQL MCP:通过postgres mcp进行高级数据库操作
  • 渐进呈现:按需加载工具
  • 上下文效率:执行环境中的数据过滤
  • 状态持久性:保存结果和可重复使用的技能

包含内容

setup命令会自动执行:

  • 安装 uv 如果尚未安装
  • 安装所有Python依赖项(包括postgres-mcp)
  • 创造 .env 模板文件
  • 创建所需的目录(工作区、日志、数据)
  • 使用示例文档设置RAG索引
  • 为PostgreSQL设置提供指导

手动设置(替代)

如果你喜欢手动设置或没有Docker:

# Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh

# Install dependencies
uv sync

# Copy environment template
cp .env.example .env
# Edit .env with your API keys

# Create directories
mkdir -p workspace logs data/rag data/invoices

# Setup RAG
uv run python scripts/setup_rag.py

# Setup PostgreSQL (if you have it installed)
uv run python scripts/setup_pg.py

PostgreSQL MCP服务器

此项目现在使用 postgres mcp (从 crystaldba/postgres mcp)作为MCP服务器,提供:

  • 架构检查:浏览数据库、表、视图和序列
  • 安全查询执行:只读和无限制模式,带验证
  • 解释计划:使用假设索引分析查询性能
  • 索引调整:用于查询优化的人工智能索引建议
  • 数据库运行状况:监控连接、真空、复制等
  • 热门查询:识别慢速和资源密集型查询

代理可以按照MCP模式生成使用这些工具的代码。

设置PostgreSQL数据库

您有几个选择:

选项1:Docker(推荐)

docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=postgres --name postgres-mcp postgres:14
uv run python scripts/setup_pg.py  # Creates sample database

选项2:本地PostgreSQL

# Ubuntu/Debian
sudo apt-get install postgresql

# macOS
brew install postgresql@14

# Then create sample database
uv run python scripts/setup_pg.py

选项3:使用现有数据库 刚刚设置 DATABASE_URL 在 .env 到您现有的PostgreSQL实例。

配置

创建 .env 文件(或复制自 .env.example):

# OpenAI Configuration
OPENAI_API_KEY=your-openai-key-here
OPENAI_MODEL=gpt-4o

# Weather API (get key from https://openweathermap.org/api)
OPEN_WEATHER_API_KEY=your-openweather-key-here

# RAG Configuration
RAG_INDEX_PATH=data/rag_index

# PostgreSQL Configuration (for postgres-mcp MCP server)
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/mcp_demo

# Paths
WORKSPACE_PATH=/workspaces/mcp-code-exec/agent-mcp-codeexec-poc/workspace
LOGS_PATH=/workspaces/mcp-code-exec/agent-mcp-codeexec-poc/logs

运行应用程序

选项1:开始一切(推荐)

# Start both FastAPI server and Streamlit UI
make start

这将启动:

  • FastAPI服务器 在端口8000上(API端点和文档)
  • 流线型UI 在端口8501上(交互式web界面)

在 GitHub代码空间,两个端口都会自动转发:

  • API https://<codespace-name>-8000.preview.app.github.dev
  • UI: https://<codespace-name>-8501.preview.app.github.dev

当地:

  • API http://localhost:8000 (文件在 /docs)
  • UI: http://localhost:8501

选项2:仅限流线型UI🎨

MCP代码执行POC的交互式web界面

# Quick start
make ui

# Or manually with uv
uv run streamlit run ui/app.py --server.port=8501 --server.address=0.0.0.0

# Or using the launch script
./ui/run.sh

特性:

  • 仪表盘:实时MCP状态、服务器概述、执行历史
  • 操场:带有预构建示例的交互式代码编辑器
  • 监视器:分析、服务器详细信息、执行日志
  • 文档:API参考、示例、资源

选项3:脚本执行工具(CLI)

使用MCP工具执行独立的Python脚本:

# Basic usage
python -m app.runtime.script_harness <script_path>

# Example: Test lazy loading
python -m app.runtime.script_harness workspace/test_lazy_loading.py

# Example: Test signal handling
python -m app.runtime.script_harness workspace/test_signal_handling.py

特性:

  • 延迟加载:服务器仅在调用工具时连接
  • 信号处理:SIGINT/SIGTERM用于优雅关机
  • 自动清理:出口时关闭MCP连接
  • 持久事件循环:正确的异步操作处理

选项4:仅API服务器(Web服务)

# Start the FastAPI server
make start

服务器将在以下时间启动 http://localhost:8000 与:

  • 交互式API文档: http://localhost:8000/docs
  • OpenAPI架构: http://localhost:8000/openapi.json

停止服务

# Stop both API server and Streamlit UI
make stop

# Stop only Streamlit UI
make stop-ui

# Clean everything (stop + clear cache)
make clean

启动FastAPI服务器

开始


The server will start at `http://localhost:8000` with:
- Interactive API docs: `http://localhost:8000/docs`
- OpenAPI schema: `http://localhost:8000/openapi.json`

### Available Make Commands

```bash
make help      # Show available commands
make setup     # Complete project setup (uv, deps, env, databases)
make start     # Start both FastAPI server and Streamlit UI
make ui        # Start only Streamlit UI
make stop      # Stop both server and UI
make stop-ui   # Stop only Streamlit UI
make restart   # Restart all services
make clean     # Stop services and clear cache
make wrappers  # Generate MCP tool wrappers

用法

快速演示-MCP代理与天气和RAG

通过MCP使用Weather和RAG工具测试代理:

# Start the server first
uv run fastapi dev app/main.py

# In another terminal, run the agent test
python examples/test_agent_mcp_tools.py

此交互式测试演示了代理生成代码以:

  • 获取任何城市的当前天气
  • 获取天气预报
  • 将文档添加到RAG知识库
  • 使用语义查询搜索RAG
  • 在单一工作流程中结合天气+RAG
  • 上传文件并查询
  • 获取RAG统计数据

MCP代理示例

天气查询:

curl -X POST http://127.0.0.1:8000/api/v1/agent \
  -H "Content-Type: application/json" \
  -d '{
    "request": "Get current weather for Tokyo, Japan and tell me the temperature"
  }'

RAG知识库:

curl -X POST http://127.0.0.1:8000/api/v1/agent \
  -H "Content-Type: application/json" \
  -d '{
    "request": "Add this to knowledge base: Python is a programming language. Then search for Python."
  }'

综合天气+RAG:

curl -X POST http://127.0.0.1:8000/api/v1/agent \
  -H "Content-Type: application/json" \
  -d '{
    "request": "Get weather for London, store it in RAG, then search for London weather"
  }'

API直接示例(非代理)

获取当前天气:

curl -X POST http://127.0.0.1:8000/api/v1/weather/current \
  -H "Content-Type: application/json" \
  -d '{"city_name": "London", "country_name": "UK"}'

获取天气预报:

curl -X POST http://127.0.0.1:8000/api/v1/weather/forecast \
  -H "Content-Type: application/json" \
  -d '{"city_name": "Tokyo", "country_name": "Japan", "days": 2, "hour": 14}'

将文档添加到RAG:

curl -X POST http://127.0.0.1:8000/api/v1/rag/documents/add \
  -H "Content-Type: application/json" \
  -d '{
    "texts": ["Python is a programming language."],
    "source": "my-docs"
  }'

搜索文档:

curl -X POST http://127.0.0.1:8000/api/v1/rag/search \
  -H "Content-Type: application/json" \
  -d '{"query": "What is Python?", "k": 3}'

代理示例请求

curl -X POST http://127.0.0.1:8000/api/v1/agent \
  -H "Content-Type: application/json" \
  -d '{
    "request": "Fetch invoice data, find duplicates and anomalies, then summarize the findings",
    "parameters": {
      "month": "last_month"
    }
  }'

示例响应

{
  "status": "success",
  "summary": "Found 12 duplicate invoices and 5 anomalies. Details saved to workspace.",
  "output_file": "workspace/invoice_analysis_2025-11-08_14-30-22.csv",
  "metrics": {
    "tokens_used": 1250,
    "model_name": "gpt-4o",
    "tool_calls_count": 1,
    "code_exec_time_ms": 450,
    "total_time_ms": 2100
  }
}

项目结构

agent-mcp-codeexec-poc/
├── README.md                 # This file
├── pyproject.toml            # Project metadata and dependencies
├── uv.lock                   # Locked dependencies
├── .env                      # Environment variables
├── .env.example              # Example environment file
├── logs/                     # Execution logs and metrics
├── workspace/                # Output files from agent
├── rag_index/                # FAISS vector index storage
├── examples/
│   ├── weather_and_rag_demo.py  # Direct API demo
│   └── test_agent_mcp_tools.py  # MCP agent tests
├── app/
│   ├── main.py              # FastAPI entry point
│   ├── config.py            # Configuration
│   ├── api/
│   │   └── v1/
│   │       ├── agent.py     # Agent endpoint
│   │       ├── weather.py   # Weather API endpoints
│   │       └── rag.py       # RAG API endpoints
│   ├── agent_core/
│   │   ├── orchestrator.py  # Main agent orchestration
│   │   ├── code_executor.py # Sandboxed code execution
│   │   └── monitoring.py    # Metrics collection
│   ├── mcp_client/
│   │   ├── client.py        # MCP client wrapper
│   │   └── tools/
│   │       ├── invoice_tool.py  # Example invoice tool
│   │       ├── weather_tool.py  # Weather API tool (MCP)
│   │       └── rag_tool.py      # RAG tool (MCP)
│   ├── rag/
│   │   └── document_store.py    # FAISS-based RAG system
│   └── prompts/
│       └── agent_prompt.py  # LLM prompt templates

运作原理

1.请求处理

FastAPI端点接收用户请求并将其传递给LangChain编排器。

2.代码生成

代理没有预先加载所有工具定义,而是:

  • 分析请求
  • 仅按需加载相关工具定义
  • 使用LLM生成Python代码,该代码:
    • 通过客户端包装器调用MCP工具
    • 在本地处理数据(过滤、聚合等)
    • 将结果写入工作区
    • 返回摘要

3.代码执行

生成的代码在沙盒环境中执行,其中:

  • 限制导入(仅允许库)
  • 超时保护
  • 资源限制
  • 捕获的stdout/stderr

4.监测

每次执行都会记录以下内容:

  • 时间戳
  • 使用的代币
  • 工具调用
  • 执行时间
  • 成功/失败状态
  • 错误消息(如有)

示例工具

气象工具(MCP)

作为MCP工具公开,用于生成代理代码:

  • get_current_weather(city_name, country_name) -获取当前天气
  • get_forecast(city_name, country_name, days, hour) -获取天气预报
  • get_geo_data(city_name, zip_code, country_name) -获取地理坐标

代理使用:

# Generated code example
from mcp_client_wrapper import mcp_client

weather = mcp_client.call_tool('get_current_weather', {
    'city_name': 'Tokyo',
    'country_name': 'Japan'
})
print(f"Temperature: {weather['main']['temp']}°F")

RAG系统(MCP)

作为知识管理的MCP工具公开:

  • add_documents(texts, source) -索引文件
  • search_documents(query, k) -语义相似度搜索
  • get_context(query, k) -获取LLM的格式化上下文
  • add_file(file_path, source) -将文件添加到索引
  • get_rag_stats() -获取索引统计信息

代理使用:

# Generated code example
from mcp_client_wrapper import mcp_client

# Add to knowledge base
mcp_client.call_tool('add_documents', {
    'texts': ['Python is a programming language'],
    'source': 'facts'
})

# Search
results = mcp_client.call_tool('search_documents', {
    'query': 'What is Python?',
    'k': 2
})

发票工具(MCP)

PoC包括一个模拟发票工具,该工具模拟:

  • fetch_invoices(month) -获取发票数据
  • update_anomaly_log(anomalies) -日志检测到异常

测试

# Run all tests
uv run pytest

# Run specific test
uv run pytest tests/test_agent_flow.py

# With coverage
uv run pytest --cov=app tests/

监控

指标保存到 logs/run_<timestamp>.json:

{
  "timestamp": "2025-11-08T14:30:22Z",
  "request": "Fetch invoice data...",
  "model_name": "gpt-4o",
  "tokens_used": 1250,
  "tool_calls_count": 1,
  "code_exec_time_ms": 450,
  "total_time_ms": 2100,
  "status": "success",
  "output_file": "workspace/invoice_analysis.csv"
}

未来的增强功能

  • []添加Streamlit UI用于交互式代理交互
  • []实施更多MCP工具服务器
  • []添加Docker容器化
  • []实现技能持久性(保存可重用函数)
  • []添加更复杂的沙盒
  • []多租户支持
  • []身份验证和授权
  • []将Weather API与代理编排器集成
  • []将RAG驱动的上下文添加到代理响应中
  • []实现混合搜索(关键字+语义)

参考文献

许可证

麻省理工学院