MCP代码执行器
MCP 代码执行器是一个 MCP 服务器,允许 LLM 在指定的 Python 环境中执行 Python 代码。这使得 LLM 能够运行代码并访问环境中定义的库和依赖项。它还支持增量代码生成,以处理可能超出令牌限制的大型代码块。
特征
- 从 LLM 提示执行 Python 代码
- 支持增量代码生成以克服令牌限制
- 在指定环境中运行代码(Conda、virtualenv 或 UV virtualenv)
- 在需要时安装依赖项
- 检查软件包是否已安装
- 在运行时动态配置环境
- 可配置代码存储目录
先决条件
- Node.js 已安装
- 以下之一:
- 安装了 Conda 并创建了所需的 Conda 环境
- Python虚拟环境
- UV虚拟环境
设置
- 克隆此存储库:
- 导航到项目目录:
- 安装 Node.js 依赖项:
- 构建项目:
配置
要配置 MCP Code Executor 服务器,请将以下内容添加到 MCP 服务器配置文件中:
使用 Node.js
使用 Docker
注意: Dockerfile 仅针对 venv-uv 环境类型进行了测试。其他环境类型可能需要额外配置。
环境变量
必需变量
CODE_STORAGE_DIR
:存储生成的代码的目录
环境类型(选择一种设置)
- 对于 Conda:
ENV_TYPE
:设置为conda
CONDA_ENV_NAME
:要使用的 Conda 环境的名称
- 对于标准虚拟环境:
ENV_TYPE
:设置为venv
VENV_PATH
:virtualenv 目录的路径
- 对于 UV Virtualenv:
ENV_TYPE
:设置为venv-uv
UV_VENV_PATH
:UV 虚拟环境目录的路径
可用工具
MCP 代码执行器为 LLM 提供以下工具:
1. execute_code
在配置的环境中执行 Python 代码。最适合短代码片段。
2. install_dependencies
在环境中安装 Python 包。
3. check_installed_packages
检查环境中是否已安装包。
4. configure_environment
动态改变环境配置。
5. get_environment_config
获取当前环境配置。
6. initialize_code_file
创建一个新的 Python 文件,其中包含初始内容。对于可能超出 token 限制的较长代码,请将此作为第一步。
7. append_to_code_file
将内容附加到现有的 Python 代码文件。使用此功能可以向使用 initialise_code_file 创建的文件添加更多代码。
8. execute_code_file
执行现有的 Python 文件。此操作是使用 initialize_code_file 和 append_to_code_file 构建代码后的最后一步。
9. read_code_file
读取现有 Python 代码文件的内容。在附加更多内容或执行文件之前,使用此方法验证文件的当前状态。
用法
配置完成后,MCP 代码执行器将允许 LLM 通过在指定的CODE_STORAGE_DIR
中生成文件并在配置的环境中运行它来执行 Python 代码。
LLM 可以通过在其提示中引用此 MCP 服务器来生成和执行代码。
处理大型代码块
对于可能超出 LLM 令牌限制的较大代码块,请使用增量代码生成方法:
- 使用
initialize_code_file
初始化具有基本结构的文件 - 使用
append_to_code_file
在后续调用中添加更多代码 - 如果需要,使用
read_code_file
验证文件内容 - 使用
execute_code_file
执行完整代码
这种方法允许 LLM 编写复杂的、多部分的代码,而不会遇到令牌限制。
向后兼容性
此软件包保持与早期版本的向后兼容性。使用旧版本且仅指定了 Conda 环境的用户无需更改配置即可继续使用。
贡献
欢迎贡献!请打开一个问题或提交一个拉取请求。
执照
该项目已获得 MIT 许可。
Related MCP Servers
- AsecurityFlicenseAqualityA Model Context Protocol server that allows LLMs to interact with Python environments, execute code, and manage files within a specified working directory.Last updated -966
- -securityAlicense-qualityAn interactive Python code execution environment that allows users and LLMs to safely execute Python code and install packages in isolated Docker containers.Last updated -25Apache 2.0
- -securityAlicense-qualityAn interactive Python code execution tool that allows users and LLMs to safely execute Python code and install packages in isolated Docker containers.Last updated -25Apache 2.0
- AsecurityFlicenseAqualityA Model Context Protocol server that allows LLMs to interact with Python environments, enabling code execution, file operations, package management, and development workflows.Last updated -9