execute
Execute code in multiple languages to test hypotheses before implementation, supporting both code snippets and shell commands with auto-runtime detection.
Instructions
Execute code in JS/TS, Go, Rust, Python, C, C++, or bash with auto-runtime detection. Primary tool for testing hypotheses before implementation. Supports both code snippets and shell commands.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| workingDirectory | Yes | Path to working directory for execution. | |
| code | No | Code to execute. Include timeouts for network/async operations to prevent hangs. | |
| commands | No | Bash commands (single or array for planned batch executions) | |
| runtime | No | Execution runtime (default: auto-detect) | |
| timeout | No | Timeout in milliseconds (default: 240000) |
Implementation Reference
- src/core/mcp-tools.js:1-5 (registration)Registers the 'execute' tool by importing executionTools from executor-tool.js and spreading it into the allTools array used by the MCP server.import { executionTools } from '../tools/executor-tool.js'; export const allTools = [ ...executionTools ];
- src/index.js:28-33 (registration)Sets up the MCP server request handlers for listing tools (exposes 'execute') and calling tools by name.const tools = allTools; server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: tools };
- src/tools/executor-tool.js:670-696 (schema)Input schema defining parameters for the 'execute' tool: workingDirectory (required), code, commands, runtime, timeout.inputSchema: { type: "object", properties: { workingDirectory: { type: "string", description: "Path to working directory for execution." }, code: { type: "string", description: "Code to execute. Include timeouts for network/async operations to prevent hangs." }, commands: { type: ["string", "array"], description: "Bash commands (single or array for planned batch executions)" }, runtime: { type: "string", enum: ["nodejs", "deno", "bash", "go", "rust", "python", "c", "cpp", "auto"], description: "Execution runtime (default: auto-detect)" }, timeout: { type: "number", description: "Timeout in milliseconds (default: 240000)" } }, required: ["workingDirectory"] },
- src/tools/executor-tool.js:697-852 (handler)Main execution handler for the 'execute' tool. Validates inputs, suppresses console, executes code/commands via runtime-specific functions like executeWithRuntimeValidation, enhances results with error analysis, generates insights, and updates contexts.handler: withCrossToolAwareness(withConnectionManagement(async ({ code, commands, workingDirectory, runtime = "auto", timeout = 240000 }) => { const consoleRestore = suppressConsoleOutput(); const effectiveWorkingDirectory = workingDirectory; const query = code || commands || ''; try { // Validate required parameters if (!workingDirectory) { throw new ToolError( 'Working directory is required', 'MISSING_PARAMETER', 'execute', false, ['Provide absolute path to working directory', 'Check tool documentation'] ); } // Start execution tracking for all operations const execution = executionState.startExecution({ type: 'execute', code, commands, runtime, workingDirectory: effectiveWorkingDirectory, timeout }); let result; if (code) { let targetRuntime = runtime === "auto" ? "nodejs" : runtime; if (runtime === "auto") { const shellCommands = ['npm ', 'npx ', 'yarn ', 'pip ', 'python ', 'go ', 'rustc ', 'gcc ', 'g++ ', 'git ', 'mkdir ', 'rm ', 'ls ', 'cd ']; const isShellCommand = shellCommands.some(cmd => code.trim().startsWith(cmd)); if (isShellCommand) { targetRuntime = 'bash'; } } try { const executionStart = Date.now(); result = await executeWithRuntimeValidation(code, targetRuntime, { workingDirectory, timeout }); const executionDuration = Date.now() - executionStart; // Complete execution (duration-based logic for cross-tool sharing) executionState.completeExecution(execution.id, result); } catch (executionError) { if (targetRuntime === 'bash') { try { result = await executeWithRuntimeValidation(code, 'nodejs', { workingDirectory, timeout }); } catch (fallbackError) { result = { success: false, stdout: '', stderr: `Failed to execute as both bash and nodejs:\nBash error: ${executionError.message}\nNode.js error: ${fallbackError.message}`, executionTimeMs: 0 }; } } else { result = { success: false, stdout: '', stderr: `Execution failed: ${executionError.message}`, executionTimeMs: 0 }; } executionState.failExecution(execution.id, executionError); } result = enhanceExecutionResult(result, code, targetRuntime, workingDirectory); } else if (commands) { try { const executionStart = Date.now(); result = await executeWithRuntimeValidation(commands, 'bash', { workingDirectory, timeout }); const executionDuration = Date.now() - executionStart; // Complete execution executionState.completeExecution(execution.id, result); } catch (executionError) { result = { success: false, stdout: '', stderr: `Command execution failed: ${executionError.message}`, executionTimeMs: 0 }; executionState.failExecution(execution.id, executionError); } result = enhanceExecutionResult(result, commands, 'bash', workingDirectory); } else { result = { content: [{ type: "text", text: "No code or commands provided" }] }; } const insights = generateExecutionInsights(result, query, effectiveWorkingDirectory); // Format response with enhanced error information let responseContent = result; if (result._errorAnalysis && result._errorAnalysis.isSyntaxError) { // Simple error response responseContent = { ...result, content: [{ type: "text", text: result.error || result.stderr || 'Execution failed' }] }; } else if (!result.success) { // Simple error format responseContent = { ...result, content: [{ type: "text", text: result.error || result.stderr || 'Execution failed' }] }; } else if (!result.content) { // Format successful execution or basic error let outputText = ''; if (result.success) { outputText = result.stdout || 'Execution successful'; } else { outputText = result.error || result.stderr || 'Execution failed'; } responseContent = { ...result, content: [{ type: "text", text: outputText }] }; } const toolContext = createToolContext('execute', effectiveWorkingDirectory, query, { ...responseContent, duration: responseContent.executionTimeMs || 0, filesAccessed: responseContent.filesAccessed || [], patterns: responseContent.patterns || [], insights: insights }); await workingDirectoryContext.updateContext(effectiveWorkingDirectory, 'execute', toolContext); // Clean up old executions executionState.cleanup(); return responseContent; } catch (error) { const errorContext = createToolContext('execute', effectiveWorkingDirectory, query, { error: error.message, duration: 0 }); await workingDirectoryContext.updateContext(effectiveWorkingDirectory, 'execute', errorContext); return { content: [{ type: "text", text: `Execution error: ${error.message}` }], isError: true }; } finally { consoleRestore.restore(); } }, 'execute', {
- src/tools/executor-tool.js:253-325 (helper)Core helper function executeProcess that spawns child processes, handles timeouts, captures output, and manages errors for all executions.export async function executeProcess(command, args = [], options = {}) { const startTime = Date.now(); const { timeout = 240000, cwd, input, encoding = 'utf8' } = options; return new Promise((resolve) => { const child = spawn(command, args, { cwd, stdio: input ? 'pipe' : ['pipe', 'pipe', 'pipe'] }); let stdout = ''; let stderr = ''; let isResolved = false; const timeoutId = setTimeout(() => { if (!isResolved) { child.kill('SIGTERM'); isResolved = true; resolve(createTimeoutError(`${command} ${args.join(' ')}`, timeout, startTime)); } }, timeout); if (child.stdout) { child.stdout.on('data', (data) => { if (data && typeof data === 'object' && Buffer.isBuffer(data)) { stdout += data.toString(encoding); } else if (data && typeof data === 'string') { stdout += data; } }); } if (child.stderr) { child.stderr.on('data', (data) => { if (data && typeof data === 'object' && Buffer.isBuffer(data)) { stderr += data.toString(encoding); } else if (data && typeof data === 'string') { stderr += data; } }); } child.on('close', (code, signal) => { if (!isResolved) { clearTimeout(timeoutId); isResolved = true; if (code === 0) { resolve(createSuccessResponse({ stdout, stderr, code, signal }, startTime)); } else { resolve(createExecutionErrorResponse( stderr || `Process exited with code ${code}`, startTime, { stdout, stderr, code, signal } )); } } }); child.on('error', (error) => { if (!isResolved) { clearTimeout(timeoutId); isResolved = true; resolve(handleProcessError(error, `${command} ${args.join(' ')}`, startTime)); } }); if (input && child.stdin) { child.stdin.write(input); child.stdin.end(); } }); }