Skip to main content
Glama
A-Niranjan

MCP Filesystem Server

by A-Niranjan

bash_execute

Execute Bash commands directly with output capture through the MCP Filesystem Server. Provides flexible command execution with security restrictions and environment variable support.

Instructions

Execute a Bash command directly with output capture. More flexible than execute_command but still with security restrictions. Allows for direct access to Bash functionality.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesThe bash command to execute
workingDirNoWorking directory for command execution
timeoutNoMaximum execution time in milliseconds (max 60s)
envNoAdditional environment variables for the command

Implementation Reference

  • Core handler function that validates and executes the bash command using child_process.exec, captures stdout/stderr/exitCode, with safety checks and logging.
    export async function bashExecute(
      args: z.infer<typeof BashExecuteArgsSchema>,
      config: Config
    ): Promise<{ stdout: string; stderr: string; exitCode: number }> {
      // Validate the command
      validateCommand(args.command)
    
      // Validate working directory if provided
      // Initialize cwd with the current directory and possibly override it
      const cwd = args.workingDir ? await validatePath(args.workingDir, config) : process.cwd()
    
      // Prepare execution options
      const options = {
        cwd,
        timeout: args.timeout || 30000,
        env: args.env ? { ...process.env, ...args.env } : process.env,
        encoding: 'utf8' as const,
        maxBuffer: 10 * 1024 * 1024, // 10MB buffer for output
      }
    
      try {
        await logger.debug(`Executing bash command: ${args.command}`, {
          workingDir: cwd,
          timeout: options.timeout,
        })
    
        // Execute the command
        const { stdout, stderr } = await execPromise(args.command, options)
    
        await logger.debug(`Command executed successfully: ${args.command}`, {
          exitCode: 0,
          stdoutPreview: stdout.substring(0, 100) + (stdout.length > 100 ? '...' : ''),
        })
    
        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 ? '...' : ''),
        })
    
        return {
          stdout,
          stderr,
          exitCode,
        }
      }
    }
  • Zod schema defining the input parameters for the bash_execute tool: command, workingDir, timeout, env.
    // Schema for bash_execute arguments
    export const BashExecuteArgsSchema = z.object({
      command: z.string().describe('The bash command to execute'),
      workingDir: z.string().optional().describe('Working directory for command execution'),
      timeout: z
        .number()
        .int()
        .positive()
        .max(60000)
        .optional()
        .default(30000)
        .describe('Maximum execution time in milliseconds (max 60s)'),
      env: z.record(z.string()).optional().describe('Additional environment variables for the command'),
    })
  • MCP-specific handler wrapper: parses args with schema, calls core bashExecute, formats MCP response with content array.
    export async function handleBashExecute(args: any, config: Config) {
      const endMetric = metrics.startOperation('bash_execute')
    
      try {
        // Validate arguments
        const parsed = BashExecuteArgsSchema.safeParse(args)
        if (!parsed.success) {
          throw new FileSystemError(`Invalid arguments for bash_execute`, 'INVALID_ARGS', undefined, {
            errors: parsed.error.format(),
          })
        }
    
        // Execute the command
        const result = await bashExecute(parsed.data, config)
    
        // Format the response
        const formattedResponse = formatCommandResult(result, parsed.data.command)
    
        await logger.debug(`Bash command executed: ${args.command}`, {
          exitCode: result.exitCode,
        })
    
        endMetric()
        return {
          content: [
            {
              type: 'text',
              text: formattedResponse,
            },
          ],
        }
      } catch (error) {
        metrics.recordError('bash_execute')
    
        if (error instanceof FileSystemError) {
          await logger.error(`Error in bash_execute:`, error.toJSON())
          return {
            content: [{ type: 'text', text: `Error: ${error.message}` }],
            isError: true,
          }
        }
    
        const errorMessage = error instanceof Error ? error.message : String(error)
        await logger.error(`Unexpected error in bash_execute:`, { error })
    
        return {
          content: [{ type: 'text', text: `Error: ${errorMessage}` }],
          isError: true,
        }
      }
  • src/index.ts:356-361 (registration)
    Tool definition and schema registration in the listTools handler response.
    name: 'bash_execute',
    description:
      'Execute a Bash command directly with output capture. ' +
      'More flexible than execute_command but still with security restrictions. ' +
      'Allows for direct access to Bash functionality.',
    inputSchema: zodToJsonSchema(BashExecuteArgsSchema) as ToolInput,
  • src/index.ts:757-758 (registration)
    Dispatch/handling registration in the callToolRequest switch statement.
    case 'bash_execute': {
      return await handleBashExecute(a, config)
Behavior2/5

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

With no annotations provided, the description carries full burden. It mentions 'output capture' and 'security restrictions' but doesn't disclose critical behavioral traits: what happens on command failure, whether commands run in isolated environments, what output format is returned, or what specific security restrictions exist. For a command execution tool with zero annotation coverage, this leaves significant gaps.

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. The first sentence clearly states the core functionality. However, the second sentence about flexibility compared to 'execute_command' could be more specific, and the third sentence about 'direct access to Bash functionality' is somewhat redundant with the first.

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

Completeness2/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 no annotations and no output schema, the description is insufficient. It doesn't explain what happens on errors, what output format to expect, what security restrictions apply, or how this differs concretely from 'execute_command'. Given the complexity and potential risks of command execution, more behavioral context is needed.

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 already documents all 4 parameters thoroughly. The description doesn't add any parameter-specific information beyond what's in the schema. It mentions 'Bash command' generally but doesn't provide examples or constraints for the 'command' parameter. Baseline 3 is appropriate when schema does the heavy lifting.

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: 'Execute a Bash command directly with output capture.' It specifies the verb (execute), resource (Bash command), and key capability (output capture). However, it doesn't explicitly differentiate from sibling 'execute_command' beyond mentioning 'more flexible' without concrete examples.

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

Usage Guidelines3/5

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

The description mentions 'More flexible than execute_command' which implies a comparison, but doesn't specify when to choose this tool over 'execute_command' or other siblings like 'bash_pipe'. It also notes 'security restrictions' but doesn't detail what those are or when they apply.

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

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