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 }; }

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