Skip to main content
Glama
A-Niranjan

MCP Filesystem Server

by A-Niranjan

execute_command

Execute system commands securely with safety validation, detailed output, and predefined time limits. Designed for basic operations within restricted directories, ensuring controlled and safe command execution.

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
NameRequiredDescriptionDefault
captureOutputNoWhether to capture and return command output
commandYesThe command to execute
timeoutNoMaximum execution time in milliseconds (max 30s)
workingDirNoWorking directory for command execution

Implementation Reference

  • Main handler function for execute_command tool: validates input, executes command using child_process.exec with timeout and cwd, handles errors, logs, tracks metrics, returns stdout/stderr/exitCode.
    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 } }
  • Zod schema defining the input parameters for the execute_command tool including command, optional working directory, timeout, and output capture flag.
    * Schema for execute_command arguments */ 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:347-353 (registration)
    Registration of the execute_command tool in the ListTools response, specifying name, description, and input schema.
    { 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,
  • Dispatch handler in CallToolRequestSchema that parses arguments using the schema, calls the executeCommand function, and formats the response content with stdout/stderr/exitCode.
    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}`, }, ], } }
  • Security validation helper that checks for forbidden substrings and unsafe characters in the command before execution.
    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 }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/A-Niranjan/mcp-filesystem'

If you have feedback or need assistance with the MCP directory API, please join our Discord server