MCP Code Executor

repository·master·Indexed 42 days ago

https://github.com/bazinga012/mcp_code_executor

An MCP server that enables LLMs to execute Python code within controlled environments such as Conda, venv, or UV. It supports running short snippets via `execute_code` and managing large code generation tasks through an incremental file-based workflow using tools like `initialize_code_file`, `append_to_code_file`, and `execute_code_file`. It also provides utilities for dependency management via `install_dependencies` and `check_installed_packages`.

Tokens
2.7K
Snippets
10
Records
14
Agent score
3%

What's inside MCP Code Executor

  1. Handle large code blocks using incremental generation

    master

    To overcome LLM token limits when generating large Python scripts, follow this incremental workflow:

    1. Initialize: Create the file structure using initialize_code_file.
    2. Append: Add logic in chunks using append_to_code_file.
    3. Verify (Optional): Use read_code_file to check the current content.
    4. Execute: Run the final complete file using execute_code_file.
    // 1. Initialize
    {
      "name": "initialize_code_file",
      "arguments": {
        "content": "def main():\n    print('Hello, world!')\n\nif __name__ == '__main__':\n    main()",
        "filename": "my_script"
      }
    }
    
    // 2. Append
    {
      "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"
      }
    }
    
    // 3. Execute
    {
      "name": "execute_code_file",
      "arguments": {
        "file_path": "/path/to/code/storage/my_script_abc123.py"
      }
    }
  2. Build and run large Python projects using file tools

    master

    For codebases that exceed token limits or require multiple steps, use the file-based workflow instead of execute_code:

    1. initialize_code_file: Create a new file with initial content. Optionally provide a filename.
    2. append_to_code_file: Add more code to an existing file using its file_path.
    3. read_code_file: Read the current content of a file to verify its state.
    4. execute_code_file: Run the completed Python file using its file_path.

    This pattern allows you to incrementally build up large scripts and then execute them as a single unit.

    /* Workflow Example */
    // 1. Initialize
    const init = await callTool('initialize_code_file', { content: 'import math\n', filename: 'calc' });
    const path = JSON.parse(init.text).file_path;
    
    // 2. Append
    await callTool('append_to_code_file', { file_path: path, content: 'print(math.sqrt(16))' });
    
    // 3. Execute
    const result = await callTool('execute_code_file', { file_path: path });
  3. Configure the Python execution environment

    master

    The MCP Code Executor requires a Python environment to run code. You can configure the environment using environment variables during startup or via the configure_environment tool.

    Supported environment types:

    • conda: Requires CONDA_ENV_NAME.
    • venv: Requires VENV_PATH.
    • venv-uv: Requires UV_VENV_PATH.

    All code files are stored in the directory specified by the CODE_STORAGE_DIR environment variable. This variable is mandatory.

    export CODE_STORAGE_DIR="/path/to/storage"
    export ENV_TYPE="conda"
    export CONDA_ENV_NAME="my_env"
  4. Install and build MCP Code Executor

    master

    To use the MCP Code Executor locally, you must clone the repository, install Node.js dependencies, and build the project using npm.

    Prerequisites:

    • Node.js installed
    • A Python environment ready (Conda, virtualenv, or UV virtualenv)
    # Clone the repository
    git clone https://github.com/bazinga012/mcp_code_executor.git
    
    # Navigate to the project directory
    cd mcp_code_executor
    
    # Install dependencies
    npm install
    
    # Build the project
    npm run build
  5. Configure MCP Code Executor via Node.js

    master

    Add the server to your MCP configuration file. You must provide the absolute path to the built index.js and set the required environment variables for code storage and your Python environment type.

    {
      "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"
          }
        }
      }
    }
  6. Configure MCP Code Executor via Docker

    master

    You can run the server using Docker. Note that the Dockerfile is currently tested specifically with the venv-uv environment type; other environment types may require additional configuration.

    {
      "mcpServers": {
        "mcp-code-executor": {
          "command": "docker",
          "args": [
            "run",
            "-i",
            "--rm",
            "mcp-code-executor"
          ]
        }
      }
    }
  7. Manage environment configuration with `configure_environment` and `get_environment_config`

    master

    These tools allow for dynamic runtime changes to the Python environment.

    • configure_environment: Changes the environment type or name.
    • get_environment_config: Retrieves the current configuration settings.
    // Change to a new Conda environment
    {
      "name": "configure_environment",
      "arguments": {
        "type": "conda",
        "conda_name": "new_env_name"
      }
    }
  8. Execute Python code with `execute_code`

    master

    Use the execute_code tool to run short Python code snippets directly. This is best for simple tasks that do not require complex file management.

    {
      "name": "execute_code",
      "arguments": {
        "code": "import numpy as np\nprint(np.random.rand(3,3))",
        "filename": "matrix_gen"
      }
    }
  9. File-based code tools: initialize, append, read, and execute

    master

    These tools provide granular control over Python files stored in the CODE_STORAGE_DIR.

    • initialize_code_file: Creates a new file with initial content.
    • append_to_code_file: Adds content to the end of an existing file.
    • read_code_file: Reads the content of a file.
    • execute_code_file: Runs an existing Python file.
  10. Manage Python dependencies with `install_dependencies` and `check_installed_packages`

    master

    Use these tools to manage the Python environment used by the LLM.

    • install_dependencies: Installs a list of packages.
    • check_installed_packages: Verifies if specific packages are already present in the environment.
    // Install packages
    {
      "name": "install_dependencies",
      "arguments": {
        "packages": ["numpy", "pandas", "matplotlib"]
      }
    }
    
    // Check packages
    {
      "name": "check_installed_packages",
      "arguments": {
        "packages": ["numpy", "pandas", "non_existent_package"]
      }
    }
  11. Manage Python dependencies

    master

    You can manage the environment's packages using the following tools:

    • install_dependencies: Installs a list of packages. The command used depends on the environment type (conda install, pip install, or uv pip install).
      • Argument: packages (array of strings).
    • check_installed_packages: Verifies if specific packages are installed and returns their version and location.
      • Argument: packages (array of strings).

    Returns for check_installed_packages: A JSON object containing all_installed (boolean), not_installed (array of names), and package_details (mapping of package names to status/version/location).

  12. Execute short Python code snippets with `execute_code`

    master

    Use the execute_code tool to run short snippets of Python code directly. The tool writes the code to a temporary file in the CODE_STORAGE_DIR and executes it within the configured environment.

    Arguments:

    • code (string, required): The Python code to run.
    • filename (string, optional): A preferred name for the file. The server will append a random hex suffix to ensure uniqueness (e.g., myscript_a1b2c3d4.py).

    Returns: A JSON string containing status ('success' or 'error'), output (stdout/stderr), and file_path or generated_filename.

    {
      "name": "execute_code",
      "arguments": {
        "code": "print('Hello World')",
        "filename": "hello"
      }
    }