execute_command
Execute system commands and retrieve their output, supporting persistent shell sessions or new instances for isolated operations.
Instructions
Execute a command and return its output. Commands run in a persistent shell session by default. Use newSession: true to run in a new shell instance.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| command | Yes | ||
| newSession | No |
Implementation Reference
- src/index.ts:184-301 (handler)Main handler logic for the 'execute_command' tool. Parses input arguments using the schema, determines whether to use a new shell session or the persistent shell, spawns the process, captures stdout/stderr, handles output markers for persistent sessions, and resolves with the command output and error status.if (name === "execute_command") { const parsed = ExecuteCommandArgsSchema.safeParse(args); if (!parsed.success) { throw new Error(`Invalid arguments for execute_command: ${parsed.error}`); } return new Promise((resolve) => { const useNewSession = parsed.data.newSession || false; const isWindows = platform() === 'win32'; if (useNewSession) { const cmdProcess = spawn(isWindows ? 'cmd' : '/bin/sh', [], { windowsHide: true, }); let output = ''; let errorOutput = ''; cmdProcess.stdout.on('data', (data) => { output += data.toString(); }); cmdProcess.stderr.on('data', (data) => { errorOutput += data.toString(); }); cmdProcess.on('error', (error) => { resolve({ content: [{ type: "text", text: `Failed to execute command: ${error.message}` }], isError: true, }); }); cmdProcess.stdin.write(parsed.data.command + '\n'); cmdProcess.stdin.end(); cmdProcess.on('close', (code) => { const finalOutput = output + (errorOutput ? `\nErrors:\n${errorOutput}` : ''); resolve({ content: [{ type: "text", text: finalOutput || `Command completed with code ${code}` }], isError: code !== 0, }); }); } else { if (!persistentCmd) { initializePersistentCmd(); } if (!persistentCmd) { throw new Error("Failed to initialize persistent CMD session"); } let output = ''; let errorOutput = ''; let commandComplete = false; const outputMarker = `__CMD_OUTPUT_${Date.now()}__`; const markerCommand = isWindows ? `echo ${outputMarker}` : `echo "${outputMarker}"`; const dataHandler = (data: Buffer) => { const str = data.toString(); if (str.includes(outputMarker)) { commandComplete = true; return; } if (!commandComplete) { output += str; } }; const errorHandler = (data: Buffer) => { errorOutput += data.toString(); }; persistentCmd.stdout?.on('data', dataHandler); persistentCmd.stderr?.on('data', errorHandler); persistentCmd.stdin?.write(parsed.data.command + '\n' + markerCommand + '\n'); const checkInterval = setInterval(() => { if (commandComplete) { clearInterval(checkInterval); persistentCmd?.stdout?.removeListener('data', dataHandler); persistentCmd?.stderr?.removeListener('data', errorHandler); const finalOutput = output + (errorOutput ? `\nErrors:\n${errorOutput}` : ''); resolve({ content: [{ type: "text", text: finalOutput || "Command completed" }], isError: false, }); } }, 50); setTimeout(() => { if (!commandComplete) { clearInterval(checkInterval); persistentCmd?.stdout?.removeListener('data', dataHandler); persistentCmd?.stderr?.removeListener('data', errorHandler); resolve({ content: [{ type: "text", text: "Command timed out" }], isError: true, }); } }, 30000); } });
- src/index.ts:13-16 (schema)Zod schema defining the input parameters for the execute_command tool: 'command' (required string) and 'newSession' (optional boolean). Used for validation and JSON schema generation.const ExecuteCommandArgsSchema = z.object({ command: z.string(), newSession: z.boolean().optional(), });
- src/index.ts:163-168 (registration)Tool registration in the ListToolsRequestSchema handler. Specifies the tool name, description, and input schema for the MCP server.name: "execute_command", description: "Execute a command and return its output. " + "Commands run in a persistent shell session by default. " + "Use newSession: true to run in a new shell instance.", inputSchema: zodToJsonSchema(ExecuteCommandArgsSchema), },
- src/index.ts:48-69 (helper)Helper function to initialize the persistent shell process (cmd.exe on Windows or /bin/sh on Unix), used by the execute_command handler for non-newSession executions. Handles process events and error cleanup.function initializePersistentCmd() { const isWindows = platform() === 'win32'; if (persistentCmd) return; const shell = isWindows ? join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'cmd.exe') : '/bin/sh'; persistentCmd = spawn(isWindows ? 'cmd.exe' : '/bin/sh', [], { windowsHide: true, shell: true // This ensures proper path resolution }); persistentCmd.on('error', (error) => { console.error('Error in persistent CMD:', error); persistentCmd = null; }); persistentCmd.on('exit', () => { persistentCmd = null; }); }