Skip to main content
Glama

shell_ls

List directory contents to view files and folders. Use command arguments to customize output for specific directory exploration needs.

Instructions

List directory contents

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
argsNoCommand arguments

Implementation Reference

  • Configuration defining the 'shell.ls' tool: maps to 'ls' command, provides description, allowed arguments, and execution timeout.
    'shell.ls': {
      command: 'ls',
      description: 'List directory contents',
      allowedArgs: ['-l', '-a', '-h', '-R', '--help', '*'],
      timeout: 5000
    },
  • Dynamically registers 'shell.ls' from allowedCommands as MCP tool 'ls' with description and input schema during ListTools processing.
    Object.entries(allowedCommands).forEach(([name, config]) => {
      const toolName = name.replace('shell.', '');
      this.logger.debug('Processing command', { 
        originalName: name,
        toolName,
        isProcessed: processedNames.has(toolName)
      });
    
      if (!processedNames.has(toolName)) {
        processedNames.add(toolName);
        tools.push({
          name: toolName,
          description: config.description,
          inputSchema: {
            type: "object",
            properties: {
              args: {
                type: "array",
                items: { type: "string" },
                description: "Command arguments"
              }
            }
          }
        });
      }
  • Defines the input schema for the 'ls' tool: object with 'args' array of strings.
      type: "object",
      properties: {
        args: {
          type: "array",
          items: { type: "string" },
          description: "Command arguments"
        }
      }
    }
  • MCP CallTool handler: maps tool name 'ls' to 'shell.ls' config, validates, executes via executor, collects and returns stdout.
    const command = String(request.params.name);
    const fullCommand = command.startsWith('shell.') ? command : `shell.${command}`;
    
    if (!(fullCommand in allowedCommands)) {
      throw new ToolError('COMMAND_NOT_FOUND', 'Command not found', { command });
    }
    
    const config = allowedCommands[fullCommand];
    const args = Array.isArray(request.params.arguments?.args)
      ? request.params.arguments.args.map(String)
      : [];
    
    const context: CommandContext = {
      requestId: ext.id || 'unknown',
      command,
      args,
      timeout: config.timeout,
      workDir: config.workDir,
      env: config.env
    };
    
    this.logger.info('Starting command execution', context);
    
    try {
      this.validator.validateCommand(command, args);
      
      this.logger.debug('Command validation passed', {
        ...context,
        config
      });
    
      const stream = await this.executor.execute(command, args, {
        timeout: config.timeout,
        cwd: config.workDir,
        env: config.env
      });
    
      ext.onCancel?.(() => {
        this.logger.info('Received cancel request', context);
        this.executor.interrupt();
      });
    
      const output = await this.collectOutput(stream);
    
      this.logger.info('Command execution completed', {
        ...context,
        outputLength: output.length
      });
    
      return {
        content: [{
          type: "text",
          text: output
        }]
      };
  • Executes the shell command ('ls') by spawning child_process.spawn(baseCommand='ls', args), returns stdout stream.
      command: string,
      args: string[] = [],
      options: ExecuteOptions = {}
    ): Promise<{ stdout: Readable }> {
      const commandKey = `${command} ${args.join(' ')}`;
      
      try {
        // Check security
        await this.securityChecker.validateCommand(command, args, options);
    
        // Check cache
        const cached = this.cache.get(commandKey);
        if (cached) {
          this.logger.debug('Using cached command result', { command, args });
          return this.createStreamFromCache(cached);
        }
    
        // Remove 'shell.' prefix for execution
        const baseCommand = command.replace('shell.', '');
    
        // Execute command
        this.logger.debug('Starting command execution', { command, args, options });
        const childProcess = spawn(baseCommand, args, {
          stdio: ['ignore', 'pipe', 'pipe'],
          timeout: options.timeout,
          cwd: options.cwd,
          env: {
            ...process.env,
            ...options.env
          },
          signal: options.signal
        });
    
        this.currentProcess = childProcess;
    
        // Error handling
        childProcess.on('error', (error: Error) => {
          this.logger.error('Command execution error', {
            command,
            args,
            error: error.message
          });
          throw new ToolError(
            'PROCESS_ERROR',
            'Command execution error',
            { command, args, error: error.message }
          );
        });
    
        // Timeout handling
        if (options.timeout) {
          setTimeout(() => {
            if (childProcess.exitCode === null) {
              this.logger.warn('Command execution timeout', {
                command,
                args,
                timeout: options.timeout
              });
              childProcess.kill();
              throw new ToolError(
                'TIMEOUT',
                'Command execution timeout',
                { command, args, timeout: options.timeout }
              );
            }
          }, options.timeout);
        }
    
        if (!childProcess.stdout) {
          throw new ToolError(
            'STREAM_ERROR',
            'Unable to get command output stream',
            { command, args }
          );
        }
    
        // Monitor process status
        childProcess.on('exit', (code, signal) => {
          this.logger.debug('Command execution completed', {
            command,
            args,
            exitCode: code,
            signal
          });
        });
    
        return {
          stdout: childProcess.stdout
        };
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. 'List directory contents' implies a read-only operation, but it doesn't specify permissions needed, output format (e.g., list vs. detailed), error handling, or system-specific behaviors (e.g., hidden files). This is a significant gap for a tool with no annotation coverage.

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

Conciseness5/5

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

The description is a single, efficient phrase: 'List directory contents'. It's front-loaded with the core action and resource, with zero wasted words, making it highly concise and well-structured for quick understanding.

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?

Given the complexity (a shell command tool with no annotations and no output schema), the description is incomplete. It lacks details on behavioral traits, output expectations, and usage context relative to siblings. For a tool that interacts with the file system, more information is needed to guide effective use by an AI agent.

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?

The input schema has 100% description coverage, with the 'args' parameter documented as 'Command arguments'. The description doesn't add any meaning beyond this, such as examples of common arguments (e.g., '-l' for long format). Since schema coverage is high, the baseline score of 3 is appropriate, as the description doesn't compensate but doesn't detract either.

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

Purpose3/5

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

The description 'List directory contents' clearly states the tool's function with a specific verb ('List') and resource ('directory contents'), avoiding tautology. However, it doesn't distinguish this tool from its siblings (e.g., shell_find, shell_whereis) which also deal with file system exploration, making it somewhat vague in context.

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 provides no guidance on when to use this tool versus alternatives. It doesn't mention scenarios like checking file existence, exploring directories, or how it differs from siblings like shell_find for searching or shell_pwd for current directory, leaving the agent without usage context.

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/kevinwatt/shell-mcp'

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