execute_command
Runs a command in a specified shell with optional timeout, enabling terminal control for automation and task execution.
Instructions
Execute command
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| command | Yes | ||
| shell | No | ||
| timeout_ms | No |
Implementation Reference
- src/tools/terminal_tools.js:97-214 (handler)The main handler function for execute_command. It supports both one-shot command execution (waiting for completion) and long-running session-based execution. It checks blocked commands, resolves the shell, executes via execa, and returns structured results including stdout, stderr, exit code, and session info for async commands.
async function executeCommand(command, options = {}) { try { // Check for blocked commands if (isCommandBlocked(command)) { return { success: false, message: `Command blocked for security reasons: ${command}`, blockedCommand: true }; } const shell = options.shell || config.defaultShell; const timeout = options.timeout_ms ? parseInt(options.timeout_ms, 10) : config.commandTimeout; const waitForCompletion = options.waitForCompletion !== false; // Default to true // For simple commands, wait for completion if (waitForCompletion) { try { const { shellCmd, shellArgs } = getShellCommand(shell, command); const result = await execa(shellCmd, shellArgs, { timeout, reject: false }); const output = result.stdout || ''; const error = result.stderr || ''; const success = result.exitCode === 0; return { success, content: output || error || (success ? 'Command completed successfully' : 'Command failed'), command, shell, exitCode: result.exitCode, stdout: output, stderr: error, message: success ? 'Command completed successfully' : `Command failed with exit code ${result.exitCode}` }; } catch (error) { if (error.code === 'ETIMEDOUT') { return { success: false, message: `Command timed out after ${timeout}ms`, command, content: 'Command timed out' }; } throw error; } } // For long-running commands, return session info const sessionId = ++sessionCounter; const session = { id: sessionId, command, shell, startTime: Date.now(), output: [], error: [], status: 'running' }; sessions.set(sessionId, session); // Execute the command const { shellCmd, shellArgs } = getShellCommand(shell, command); const subprocess = execa(shellCmd, shellArgs, { timeout, buffer: false, reject: false, stdio: ['ignore', 'pipe', 'pipe'] }); session.subprocess = subprocess; session.pid = subprocess.pid; // Collect output subprocess.stdout.on('data', (data) => { session.output.push(data.toString()); }); subprocess.stderr.on('data', (data) => { session.error.push(data.toString()); }); // Handle completion subprocess.then((result) => { session.status = result.failed ? 'failed' : 'completed'; session.exitCode = result.exitCode; session.endTime = Date.now(); }).catch((error) => { session.status = 'error'; session.errorMessage = error.message; session.endTime = Date.now(); }); // Return initial response for session-based execution return { success: true, pid: session.pid, sessionId, command, shell, status: session.status, message: `Command started with PID ${session.pid}`, content: `Command started with PID ${session.pid}` }; } catch (error) { logger.error(`Error executing command: ${error.message}`); return { success: false, message: error.message, content: error.message }; } } - src/mcp/server.js:97-97 (registration)Tool schema registration in the tools/list response, defining name 'execute_command', description, and inputSchema with required 'command' property and optional 'shell' and 'timeout_ms'.
{ name:'execute_command', description:'Execute command', inputSchema:{ type:'object', properties:{ command:{type:'string'}, shell:{type:'string'}, timeout_ms:{type:'number'} }, required:['command'] } }, - src/mcp/server.js:254-259 (registration)The tools/call dispatch case for 'execute_command' in the MCP server, which extracts the command and options (shell, timeout_ms, waitForCompletion) and delegates to terminalTools.executeCommand().
case 'execute_command': { const wait = (typeof args.waitForCompletion === 'boolean') ? args.waitForCompletion : true; const r = await terminalTools.executeCommand(args.command, { shell: args.shell, timeout_ms: args.timeout_ms, waitForCompletion: wait }); data = (r && r.success !== undefined) ? r : { success: true, ...r }; break; } - src/tools/terminal_tools.js:87-92 (helper)Helper function isCommandBlocked that checks if a command contains blocked keywords from the BLOCKED_COMMANDS env or config.
function isCommandBlocked(command) { const lowerCommand = command.toLowerCase().trim(); return config.blockedCommands.some(blocked => lowerCommand.includes(blocked.toLowerCase()) ); } - src/tools/terminal_tools.js:470-489 (helper)Helper function getShellCommand that builds the platform-specific shell command and arguments for executing a command string.
// Helper to build shell command per platform function getShellCommand(shell, command) { const isWin = process.platform === 'win32'; const sh = (shell || '').toLowerCase(); if (isWin) { if (sh.includes('powershell')) { return { shellCmd: shell, shellArgs: ['-NoProfile', '-Command', command] }; } if (sh.includes('cmd')) { return { shellCmd: shell, shellArgs: ['/c', command] }; } if (sh.includes('bash')) { return { shellCmd: shell, shellArgs: ['-c', command] }; } // Fallback to powershell return { shellCmd: 'powershell.exe', shellArgs: ['-NoProfile', '-Command', command] }; } // POSIX shells return { shellCmd: shell || '/bin/bash', shellArgs: ['-c', command] }; }