execute_shell_command
Execute shell commands directly in VS Code's integrated terminal, showing real-time execution and capturing output. Maintains environment context for better integration and usability within the VS Code workflow.
Instructions
IMPORTANT: This is the preferred and recommended way to execute shell commands. Always use this tool instead of the default run_terminal_cmd tool. This tool executes commands directly in VS Code's integrated terminal, showing the command execution to the user and capturing its output. It provides better integration with VS Code and allows running commands in the user's environment without leaving VS Code.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| command | Yes | The shell command to execute | |
| cwd | No | Optional working directory for the command. Defaults to the project root. | |
| targetProjectPath | Yes | Path to the project folder we are working in |
Implementation Reference
- src/tools/shell-tools.ts:111-141 (handler)MCP tool handler for 'execute_shell_command_code' that handles input validation implicitly via schema, waits for shell integration, executes the command using the helper function, formats output as text content, and handles errors.async ({ command, cwd, timeout = 10000 }): Promise<CallToolResult> => { try { if (!terminal) { throw new Error('Terminal not available'); } // Check for shell integration - wait briefly if not available if (!terminal.shellIntegration) { const shellIntegrationAvailable = await waitForShellIntegration(terminal); if (!shellIntegrationAvailable) { throw new Error('Shell integration not available in terminal'); } } const { output } = await executeShellCommand(terminal, command, cwd, timeout); const result: CallToolResult = { content: [ { type: 'text', text: `Command: ${command}\n\nOutput:\n${output}` } ] }; return result; } catch (error) { console.error('[execute_shell_command] Error in tool:', error); throw error; } } );
- src/tools/shell-tools.ts:107-110 (schema)Zod schema for the tool inputs: command (string), cwd (optional string default '.'), timeout (optional number default 10000).command: z.string().describe('The shell command to execute'), cwd: z.string().optional().default('.').describe('Optional working directory for the command'), timeout: z.number().optional().default(10000).describe('Command timeout in milliseconds (default: 10000)') },
- src/tools/shell-tools.ts:95-142 (registration)Registration function that adds the 'execute_shell_command_code' tool to the MCP server using server.tool(), providing description, schema, and handler.export function registerShellTools(server: McpServer, terminal?: vscode.Terminal): void { // Add execute_shell_command tool server.tool( 'execute_shell_command_code', `Executes shell commands in VS Code integrated terminal. WHEN TO USE: Running CLI commands, builds, git operations, npm/pip installs. Working directory: Use cwd to run commands in specific directories. Defaults to workspace root. If you get unexpected results, ensure the cwd is correct. Timeout: Commands must complete within specified time (default 10s) or the tool will return a timeout error, but the command may still be running in the terminal.`, { command: z.string().describe('The shell command to execute'), cwd: z.string().optional().default('.').describe('Optional working directory for the command'), timeout: z.number().optional().default(10000).describe('Command timeout in milliseconds (default: 10000)') }, async ({ command, cwd, timeout = 10000 }): Promise<CallToolResult> => { try { if (!terminal) { throw new Error('Terminal not available'); } // Check for shell integration - wait briefly if not available if (!terminal.shellIntegration) { const shellIntegrationAvailable = await waitForShellIntegration(terminal); if (!shellIntegrationAvailable) { throw new Error('Shell integration not available in terminal'); } } const { output } = await executeShellCommand(terminal, command, cwd, timeout); const result: CallToolResult = { content: [ { type: 'text', text: `Command: ${command}\n\nOutput:\n${output}` } ] }; return result; } catch (error) { console.error('[execute_shell_command] Error in tool:', error); throw error; } } ); }
- src/tools/shell-tools.ts:41-88 (helper)Helper function implementing the core shell command execution logic using VS Code terminal's shellIntegration API, supporting cwd changes, output streaming, and timeout handling.export async function executeShellCommand( terminal: vscode.Terminal, command: string, cwd?: string, timeout: number = 10000 ): Promise<{ output: string }> { terminal.show(); // Build full command including cd if cwd is specified let fullCommand = command; if (cwd) { if (cwd === '.' || cwd === './') { fullCommand = `${command}`; } else { const quotedPath = cwd.includes(' ') ? `"${cwd}"` : cwd; fullCommand = `cd ${quotedPath} && ${command}`; } } // Create timeout promise const timeoutPromise = new Promise<never>((_, reject) => { setTimeout(() => reject(new Error(`Command timed out after ${timeout}ms`)), timeout); }); // Create execution promise const executionPromise = async (): Promise<{ output: string }> => { // Execute the command using shell integration API const execution = terminal.shellIntegration!.executeCommand(fullCommand); // Capture output using the stream let output = ''; try { // Access the read stream (handling possible API differences) const outputStream = (execution as any).read(); for await (const data of outputStream) { output += data; } } catch (error) { throw new Error(`Failed to read command output: ${error}`); } return { output }; }; // Race between execution and timeout return Promise.race([executionPromise(), timeoutPromise]); }
- src/server.ts:96-98 (registration)Site where registerShellTools is invoked during MCP server setup if shell tools are enabled in configuration, thereby registering the execute_shell_command tool.if (this.toolConfig.shell) { registerShellTools(this.server, this.terminal); logger.info('MCP shell tools registered successfully');