Skip to main content
Glama
gabrielmaialva33

MCP Filesystem Server

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
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

  • 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
      }
    }
  • 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,
    },
  • 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}`,
          },
        ],
      }
    }
  • 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
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden. It discloses key behavioral traits: security validation, safety checks, and output detail. However, it lacks specifics on what security restrictions apply, what constitutes 'basic' operations, error handling, or permission requirements. The description adds value but leaves significant behavioral aspects undefined.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately concise with three sentences that each add value: purpose, validation, and scope. It's front-loaded with the core functionality. No redundant or wasted language, though it could be slightly more structured for clarity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a command execution tool with 4 parameters, no annotations, and no output schema, the description provides adequate but incomplete context. It covers purpose and security aspects but lacks details on output format, error responses, exact security limitations, and comparison with sibling tools. Given the complexity and absence of structured fields, it should do more to be fully complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema fully documents all 4 parameters. The description adds no parameter-specific information beyond what's in the schema. According to scoring rules, when schema coverage is high (>80%), the baseline is 3 even with no param info in the description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose as executing system commands with security restrictions and validation. It specifies 'basic system operations' which distinguishes it from more specialized siblings like curl_request or edit_file, though it doesn't explicitly contrast with bash_execute which appears similar.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description mentions 'security restrictions' and 'limited to basic system operations' which provides some context, but offers no explicit guidance on when to use this tool versus alternatives like bash_execute or bash_pipe. No prerequisites, exclusions, or comparative usage scenarios are provided.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

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/gabrielmaialva33/mcp-filesystem'

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