Skip to main content
Glama
MCP Code Executor

MCP Code Executor

Исполнитель кода MCP

значок кузнеца

MCP Code Executor — это сервер MCP, который позволяет LLM выполнять код Python в указанной среде Python. Это позволяет LLM запускать код с доступом к библиотекам и зависимостям, определенным в среде. Он также поддерживает инкрементальную генерацию кода для обработки больших блоков кода, которые могут превышать ограничения токенов.

Функции

  • Выполнение кода Python из подсказок LLM

  • Поддержка инкрементальной генерации кода для преодоления ограничений токенов

  • Запустить код в указанной среде (Conda, virtualenv или UV virtualenv)

  • Устанавливайте зависимости при необходимости

  • Проверьте, установлены ли уже пакеты

  • Динамически настраивать среду во время выполнения

  • Настраиваемый каталог хранения кодов

Related MCP server: MCP Python Interpreter

Предпосылки

  • Node.js установлен

  • Один из следующих вариантов:

    • Conda установлена с созданием желаемой среды Conda

    • Виртуальное окружение Python

    • УФ виртуальное окружение

Настраивать

  1. Клонируйте этот репозиторий:

git clone https://github.com/bazinga012/mcp_code_executor.git
  1. Перейдите в каталог проекта:

cd mcp_code_executor
  1. Установите зависимости Node.js:

npm install
  1. Создайте проект:

npm run build

Конфигурация

Чтобы настроить сервер MCP Code Executor, добавьте следующее в файл конфигурации серверов MCP:

Использование Node.js

{
  "mcpServers": {
    "mcp-code-executor": {
      "command": "node",
      "args": [
        "/path/to/mcp_code_executor/build/index.js" 
      ],
      "env": {
        "CODE_STORAGE_DIR": "/path/to/code/storage",
        "ENV_TYPE": "conda",
        "CONDA_ENV_NAME": "your-conda-env"
      }
    }
  }
}

Использование Докера

{
  "mcpServers": {
    "mcp-code-executor": {
      "command": "docker",
      "args": [
        "run",
        "-i",
        "--rm",
        "mcp-code-executor"
      ]
    }
  }
}

Примечание: Dockerfile был протестирован только с типом среды venv-uv. Другие типы среды могут потребовать дополнительной настройки.

Переменные среды

Требуемые переменные

  • CODE_STORAGE_DIR : Каталог, в котором будет сохранен сгенерированный код.

Тип среды (выберите одну настройку)

  • Для Конды:

    • ENV_TYPE : Установить значение conda

    • CONDA_ENV_NAME : Имя используемой среды Conda

  • Для стандартного Virtualenv:

    • ENV_TYPE : Установить на venv

    • VENV_PATH : Путь к каталогу virtualenv

  • Для UV Virtualenv:

    • ENV_TYPE : Установить venv-uv

    • UV_VENV_PATH : Путь к каталогу UV virtualenv

Доступные инструменты

MCP Code Executor предоставляет следующие инструменты для LLM:

1. execute_code

Выполняет код Python в настроенной среде. Лучше всего подходит для коротких фрагментов кода.

{
  "name": "execute_code",
  "arguments": {
    "code": "import numpy as np\nprint(np.random.rand(3,3))",
    "filename": "matrix_gen"
  }
}

2. install_dependencies

Устанавливает пакеты Python в среду.

{
  "name": "install_dependencies",
  "arguments": {
    "packages": ["numpy", "pandas", "matplotlib"]
  }
}

3. check_installed_packages

Проверяет, установлены ли уже пакеты в среде.

{
  "name": "check_installed_packages",
  "arguments": {
    "packages": ["numpy", "pandas", "non_existent_package"]
  }
}

4. configure_environment

Динамически изменяет конфигурацию среды.

{
  "name": "configure_environment",
  "arguments": {
    "type": "conda",
    "conda_name": "new_env_name"
  }
}

5. get_environment_config

Получает текущую конфигурацию среды.

{
  "name": "get_environment_config",
  "arguments": {}
}

6. initialize_code_file

Создает новый файл Python с начальным содержимым. Используйте это как первый шаг для более длинного кода, который может превысить лимиты токенов.

{
  "name": "initialize_code_file",
  "arguments": {
    "content": "def main():\n    print('Hello, world!')\n\nif __name__ == '__main__':\n    main()",
    "filename": "my_script"
  }
}

7. append_to_code_file

Добавляет содержимое к существующему файлу кода Python. Используйте это, чтобы добавить больше кода в файл, созданный с помощью initialize_code_file.

{
  "name": "append_to_code_file",
  "arguments": {
    "file_path": "/path/to/code/storage/my_script_abc123.py",
    "content": "\ndef another_function():\n    print('This was appended to the file')\n"
  }
}

8. execute_code_file

Выполняет существующий файл Python. Используйте это как последний шаг после создания кода с помощью initialize_code_file и append_to_code_file.

{
  "name": "execute_code_file",
  "arguments": {
    "file_path": "/path/to/code/storage/my_script_abc123.py"
  }
}

9. read_code_file

Читает содержимое существующего файла кода Python. Используйте это для проверки текущего состояния файла перед добавлением дополнительного содержимого или его выполнением.

{
  "name": "read_code_file",
  "arguments": {
    "file_path": "/path/to/code/storage/my_script_abc123.py"
  }
}

Использование

После настройки MCP Code Executor позволит LLM выполнять код Python, генерируя файл в указанном CODE_STORAGE_DIR и запуская его в настроенной среде.

LLM могут генерировать и выполнять код, ссылаясь на этот сервер MCP в своих подсказках.

Обработка больших блоков кода

Для более крупных блоков кода, которые могут превысить ограничения токенов LLM, используйте подход инкрементной генерации кода:

  1. Инициализируйте файл с базовой структурой, используя initialize_code_file

  2. Добавьте больше кода в последующие вызовы с помощью append_to_code_file

  3. При необходимости проверьте содержимое файла с помощью read_code_file

  4. Выполните весь код с помощью execute_code_file

Такой подход позволяет LLM писать сложный, многокомпонентный код, не сталкиваясь с ограничениями токенов.

Обратная совместимость

Этот пакет поддерживает обратную совместимость с более ранними версиями. Пользователи предыдущих версий, которые указали только среду Conda, продолжат работать без каких-либо изменений в своей конфигурации.

Внося вклад

Вклады приветствуются! Пожалуйста, откройте тему или отправьте запрос на извлечение.

Лицензия

Данный проект лицензирован по лицензии MIT.

Available Tools

9 tools
append_to_code_fileA

Append content to an existing Python code file. Use this to add more code to a file created with initialize_code_file, allowing you to build up larger code bases in parts.

Inputs: file_path (required), content (required).

check_installed_packagesC

Check if packages are installed in the conda environment

Inputs: packages (required).

configure_environmentC

Change the environment configuration settings

Inputs: type (required), conda_name, venv_path, uv_venv_path.

execute_codeA

Execute Python code in the conda environment. For short code snippets only. For longer code, use initialize_code_file and append_to_code_file instead.

Inputs: code (required), filename.

execute_code_fileA

Execute an existing Python file. Use this as the final step after building up code with initialize_code_file and append_to_code_file.

Inputs: file_path (required).

get_environment_configB

Get the current environment configuration

Inputs: no named parameters.

initialize_code_fileA

Create a new Python file with initial content. Use this as the first step for longer code that may exceed token limits. Follow with append_to_code_file for additional code.

Inputs: content (required), filename.

install_dependenciesC

Install Python dependencies in the conda environment

Inputs: packages (required).

read_code_fileA

Read the content of an existing Python code file. Use this to verify the current state of a file before appending more content or executing it.

Inputs: file_path (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.8/5.0

    Scored across 9 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose with no ambiguity. For example, initialize_code_file, append_to_code_file, and read_code_file handle different file operations, while execute_code and execute_code_file target different execution methods. The descriptions explicitly differentiate tools like execute_code (for short snippets) versus the file-based workflow.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern using snake_case, such as append_to_code_file, check_installed_packages, and configure_environment. There are no deviations in naming style or convention across the set, making them predictable and readable.

    Tool Count5/5

    With 9 tools, the count is well-scoped for a code execution server. Each tool earns its place by covering distinct aspects like file management, environment configuration, dependency handling, and code execution, without being overly sparse or bloated.

    Completeness5/5

    The tool set provides complete coverage for the code execution domain, including CRUD-like operations for files (initialize, append, read), environment management (configure, get config, install dependencies), and execution (code snippets, files). There are no obvious gaps, and the workflow from file creation to execution is fully supported.

    Maintenance

    ActivityInactive
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers