Skip to main content
Glama
bazinga012

MCP Code Executor

execute_code

Execute Python code snippets in a Conda environment to test and run short programs with necessary libraries.

Instructions

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.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesPython code to execute
filenameNoOptional: Name of the file to save the code (default: generated UUID)

Implementation Reference

  • Core handler function that writes the Python code to a temporary file and executes it in the configured environment (conda/venv/uv) using child_process.exec, returning JSON-formatted stdout/stderr results.
    async function executeCode(code: string, filePath: string) {
        try {
            // Write code to file
            await writeFile(filePath, code, 'utf-8');
    
            // Get platform-specific command with unbuffered output
            const pythonCmd = platform() === 'win32' ? `python -u "${filePath}"` : `python3 -u "${filePath}"`;
            const { command, options } = getPlatformSpecificCommand(pythonCmd);
    
            // Execute code
            const { stdout, stderr } = await execAsync(command, {
                cwd: CODE_STORAGE_DIR,
                env: { ...process.env, PYTHONUNBUFFERED: '1' },
                ...options
            });
    
            const response = {
                status: stderr ? 'error' : 'success',
                output: stderr || stdout,
                file_path: filePath
            };
    
            return {
                type: 'text',
                text: JSON.stringify(response),
                isError: !!stderr
            };
        } catch (error) {
            const response = {
                status: 'error',
                error: error instanceof Error ? error.message : String(error),
                file_path: filePath
            };
    
            return {
                type: 'text',
                text: JSON.stringify(response),
                isError: true
            };
        }
    }
  • src/index.ts:534-551 (registration)
    Registers the 'execute_code' tool in the ListTools response, defining its name, description, and input schema.
    {
        name: "execute_code",
        description: `Execute Python code in the ${ENV_CONFIG.type} environment. For short code snippets only. For longer code, use initialize_code_file and append_to_code_file instead.`,
        inputSchema: {
            type: "object",
            properties: {
                code: {
                    type: "string",
                    description: "Python code to execute"
                },
                filename: {
                    type: "string",
                    description: "Optional: Name of the file to save the code (default: generated UUID)"
                }
            },
            required: ["code"]
        }
    },
  • MCP CallTool request handler dispatch for 'execute_code': validates args, generates unique temp file path, calls executeCode, augments response with generated filename.
    case "execute_code": {
        const args = request.params.arguments as ExecuteCodeArgs;
        if (!args?.code) {
            throw new Error("Code is required");
        }
    
        // Generate a filename with both user-provided name and a random component for uniqueness
        let filename;
        if (args.filename && typeof args.filename === 'string') {
            // Extract base name without extension
            const baseName = args.filename.replace(/\.py$/, '');
            // Add a random suffix to ensure uniqueness
            filename = `${baseName}_${randomBytes(4).toString('hex')}.py`;
        } else {
            // Default filename if none provided
            filename = `code_${randomBytes(4).toString('hex')}.py`;
        }
        
        const filePath = join(CODE_STORAGE_DIR, filename);
    
        // Execute the code and include the generated filename in the response
        const result = await executeCode(args.code, filePath);
    
        // Parse the result to add the filename info if it's a success response
        try {
            const resultData = JSON.parse(result.text);
            resultData.generated_filename = filename;
            result.text = JSON.stringify(resultData);
        } catch (e) {
            // In case of parsing error, continue with original result
            console.error("Error adding filename to result:", e);
        }
    
        return {
            content: [{
                type: "text",
                text: result.text,
                isError: result.isError
            }]
        };
    }
  • TypeScript interface defining the input arguments for the execute_code tool.
    interface ExecuteCodeArgs {
        code?: string;
        filename?: string;
    }
  • Helper function to generate platform-specific shell commands for activating the Python environment (conda/venv/uv) and running the provided pythonCommand.
    function getPlatformSpecificCommand(pythonCommand: string): { command: string, options: ExecOptions } {
        const isWindows = platform() === 'win32';
        let command = '';
        let options: ExecOptions = {};
        
        switch (ENV_CONFIG.type) {
            case 'conda':
                if (!ENV_CONFIG.conda_name) {
                    throw new Error("conda_name is required for conda environment");
                }
                if (isWindows) {
                    command = `conda run -n ${ENV_CONFIG.conda_name} ${pythonCommand}`;
                    options = { shell: 'cmd.exe' };
                } else {
                    command = `source $(conda info --base)/etc/profile.d/conda.sh && conda activate ${ENV_CONFIG.conda_name} && ${pythonCommand}`;
                    options = { shell: '/bin/bash' };
                }
                break;
                
            case 'venv':
                if (!ENV_CONFIG.venv_path) {
                    throw new Error("venv_path is required for virtualenv");
                }
                if (isWindows) {
                    command = `${join(ENV_CONFIG.venv_path, 'Scripts', 'activate')} && ${pythonCommand}`;
                    options = { shell: 'cmd.exe' };
                } else {
                    command = `source ${join(ENV_CONFIG.venv_path, 'bin', 'activate')} && ${pythonCommand}`;
                    options = { shell: '/bin/bash' };
                }
                break;
                
            case 'venv-uv':
                if (!ENV_CONFIG.uv_venv_path) {
                    throw new Error("uv_venv_path is required for uv virtualenv");
                }
                if (isWindows) {
                    command = `${join(ENV_CONFIG.uv_venv_path, 'Scripts', 'activate')} && ${pythonCommand}`;
                    options = { shell: 'cmd.exe' };
                } else {
                    command = `source ${join(ENV_CONFIG.uv_venv_path, 'bin', 'activate')} && ${pythonCommand}`;
                    options = { shell: '/bin/bash' };
                }
                break;
                
            default:
                throw new Error(`Unsupported environment type: ${ENV_CONFIG.type}`);
        }
        
        return { command, options };
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It mentions the environment ('conda environment') and a constraint on code length, but lacks details on execution behavior (e.g., timeout, output handling, error propagation) or safety considerations. It adds some context but is incomplete for a code execution tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences with zero waste: the first states the purpose and constraint, the second provides alternative guidance. It is front-loaded with essential information and appropriately sized for the tool's complexity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations and no output schema, the description covers basic purpose and usage but lacks details on execution behavior, return values, or error handling. It is minimally viable for a code execution tool but has clear gaps in contextual information needed for reliable use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents both parameters ('code' and 'filename'). The description does not add any meaning beyond the schema, such as explaining what 'short code snippets' entail or how the filename is used. Baseline 3 is appropriate as the schema handles parameter documentation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Execute Python code') and resource ('in the conda environment'), and explicitly distinguishes it from sibling tools by mentioning 'initialize_code_file and append_to_code_file' for longer code, making the purpose unambiguous and differentiated.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool ('For short code snippets only') and when to use alternatives ('For longer code, use initialize_code_file and append_to_code_file instead'), offering clear context and exclusions without being misleading.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/bazinga012/mcp_code_executor'

If you have feedback or need assistance with the MCP directory API, please join our Discord server