execute_command
Run system commands securely on the MCP Filesystem Server. Validates inputs, enforces timeouts, and captures output for controlled, safe execution of basic operations within restricted directories.
Instructions
Execute a system command with security restrictions. Validates commands for safety and provides detailed output. Limited to basic system operations with security checks.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| captureOutput | No | Whether to capture and return command output | |
| command | Yes | The command to execute | |
| timeout | No | Maximum execution time in milliseconds (max 30s) | |
| workingDir | No | Working directory for command execution |
Implementation Reference
- src/utils/exec/index.ts:96-149 (handler)The main handler function that performs security validation on the command, executes it using child_process.exec with configurable working directory and timeout, captures stdout/stderr/exitCode, and handles errors appropriately.export async function executeCommand( args: z.infer<typeof ExecuteCommandArgsSchema>, _config: Config ): Promise<{ stdout: string; stderr: string; exitCode: number }> { const endMetric = metrics.startOperation('execute_command') try { await logger.debug(`Executing command: ${args.command}`, { args }) // Validate the command for security validateCommand(args.command) // Set working directory or use current directory const options = { cwd: args.workingDir || process.cwd(), timeout: args.timeout, encoding: 'utf-8' as const, } try { // Execute the command const { stdout, stderr } = await exec(args.command, options) await logger.debug(`Command executed successfully: ${args.command}`, { stdout: stdout.substring(0, 100) + (stdout.length > 100 ? '...' : ''), }) endMetric() return { stdout, stderr, exitCode: 0, } } catch (error: any) { // Handle command execution errors const stderr = error.stderr || '' const stdout = error.stdout || '' const exitCode = error.code || 1 await logger.warn(`Command execution failed: ${args.command}`, { exitCode, stderr: stderr.substring(0, 100) + (stderr.length > 100 ? '...' : ''), }) endMetric() return { stdout, stderr, exitCode, } } } catch (error) { metrics.recordError('execute_command') throw error } }
- src/utils/exec/index.ts:46-57 (schema)Zod schema defining the input parameters for the execute_command tool: command (required string), workingDir (optional string), timeout (optional number, default 5000, max 30000), captureOutput (optional boolean, default true).export const ExecuteCommandArgsSchema = z.object({ command: z.string().describe('The command to execute'), workingDir: z.string().optional().describe('Working directory for command execution'), timeout: z .number() .int() .positive() .max(30000) .default(5000) .describe('Maximum execution time in milliseconds (max 30s)'), captureOutput: z.boolean().default(true).describe('Whether to capture and return command output'), })
- src/index.ts:348-354 (registration)Tool registration in the list_tools response, specifying name, description, and inputSchema derived from ExecuteCommandArgsSchema.name: 'execute_command', description: 'Execute a system command with security restrictions. ' + 'Validates commands for safety and provides detailed output. ' + 'Limited to basic system operations with security checks.', inputSchema: zodToJsonSchema(ExecuteCommandArgsSchema) as ToolInput, },
- src/index.ts:736-755 (handler)Dispatch handler in the main CallToolRequest switch statement that parses arguments using the schema, calls the executeCommand function, and formats the response with stdout, stderr, and exit code.case 'execute_command': { const parsed = ExecuteCommandArgsSchema.safeParse(a) if (!parsed.success) { throw new FileSystemError(`Invalid arguments for ${name}`, 'INVALID_ARGS', undefined, { errors: parsed.error.format(), }) } const result = await executeCommand(parsed.data, config) endMetric() return { content: [ { type: 'text', text: `Command execution completed with exit code: ${result.exitCode}\n\nSTDOUT:\n${result.stdout}\n\nSTDERR:\n${result.stderr}`, }, ], } }
- src/utils/exec/index.ts:65-87 (helper)Helper function that validates the command for safety by checking against forbidden substrings and a safe character regex, throwing FileSystemError if unsafe.function validateCommand(command: string): boolean { // Check for forbidden commands if (FORBIDDEN_COMMANDS.some((forbidden) => command.includes(forbidden))) { throw new FileSystemError( `Command contains forbidden operations`, 'FORBIDDEN_COMMAND', undefined, { command } ) } // Validate command against safe pattern if (!SAFE_COMMAND_REGEX.test(command)) { throw new FileSystemError( `Command contains potentially unsafe characters`, 'UNSAFE_COMMAND', undefined, { command } ) } return true }