Skip to main content
Glama

run_command

Execute CLI commands like pwd, ls, and cat within the /app directory to manage files and directories. Supports flags such as -l and -a for detailed output.

Instructions

Allows command (CLI) execution in the directory: /app

Available commands: pwd, ls, cat Available flags: -l, --help, -a

Shell operators (&&, ||, |, >, >>, <, <<, ;) are not supported. Set ALLOW_SHELL_OPERATORS=true to enable.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesSingle command to execute (example: 'ls -l' or 'cat file.txt')

Implementation Reference

  • Handler for the 'run_command' tool call. Validates arguments, executes the command via CommandExecutor, and returns stdout, stderr, and return code in MCP TextContent format.
    if name == "run_command":
        if not arguments or "command" not in arguments:
            return [
                types.TextContent(type="text", text="No command provided", error=True)
            ]
    
        try:
            result = executor.execute(arguments["command"])
    
            response = []
            if result.stdout:
                response.append(types.TextContent(type="text", text=result.stdout))
            if result.stderr:
                response.append(
                    types.TextContent(type="text", text=result.stderr, error=True)
                )
    
            response.append(
                types.TextContent(
                    type="text",
                    text=f"\nCommand completed with return code: {result.returncode}",
                )
            )
    
            return response
    
        except CommandSecurityError as e:
            return [
                types.TextContent(
                    type="text", text=f"Security violation: {str(e)}", error=True
                )
            ]
        except subprocess.TimeoutExpired:
            return [
                types.TextContent(
                    type="text",
                    text=f"Command timed out after {executor.security_config.command_timeout} seconds",
                    error=True,
                )
            ]
        except Exception as e:
            return [types.TextContent(type="text", text=f"Error: {str(e)}", error=True)]
  • JSON schema defining the input for the 'run_command' tool: an object with a required 'command' string property.
    inputSchema={
        "type": "object",
        "properties": {
            "command": {
                "type": "string",
                "description": "Single command to execute (example: 'ls -l' or 'cat file.txt')",
            }
        },
        "required": ["command"],
    },
  • Registration of the 'run_command' tool in the list_tools() handler, including name, security-aware description, and input schema.
    types.Tool(
        name="run_command",
        description=(
            f"Allows command (CLI) execution in the directory: {executor.allowed_dir}\n\n"
            f"Available commands: {commands_desc}\n"
            f"Available flags: {flags_desc}\n\n"
            f"Shell operators (&&, ||, |, >, >>, <, <<, ;) are {'supported' if executor.security_config.allow_shell_operators else 'not supported'}. Set ALLOW_SHELL_OPERATORS=true to enable."
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Single command to execute (example: 'ls -l' or 'cat file.txt')",
                }
            },
            "required": ["command"],
        },
    ),
  • The core helper method in CommandExecutor that validates the command (checking length, security rules, shell operators) and executes it using subprocess.run, with appropriate shell=True/False, timeout, and cwd restrictions.
    def execute(self, command_string: str) -> subprocess.CompletedProcess:
        """
        Executes a command string in a secure, controlled environment.
    
        Runs the command after validating it against security constraints including length limits
        and shell operator restrictions. Executes with controlled parameters for safety.
    
        Args:
            command_string (str): The command string to execute.
    
        Returns:
            subprocess.CompletedProcess: The result of the command execution containing
                stdout, stderr, and return code.
    
        Raises:
            CommandSecurityError: If the command:
                - Exceeds maximum length
                - Fails security validation
                - Fails during execution
    
        Notes:
            - Uses shell=True for commands with shell operators, shell=False otherwise
            - Uses timeout and working directory constraints
            - Captures both stdout and stderr
        """
        if len(command_string) > self.security_config.max_command_length:
            raise CommandSecurityError(
                f"Command exceeds maximum length of {self.security_config.max_command_length}"
            )
    
        try:
            command, args = self.validate_command(command_string)
    
            # Check if this is a command with shell operators
            shell_operators = ["&&", "||", "|", ">", ">>", "<", "<<", ";"]
            use_shell = any(operator in command_string for operator in shell_operators)
    
            # Double-check that shell operators are allowed if they are present
            if use_shell and not self.security_config.allow_shell_operators:
                for operator in shell_operators:
                    if operator in command_string:
                        raise CommandSecurityError(
                            f"Shell operator '{operator}' is not supported. Set ALLOW_SHELL_OPERATORS=true to enable."
                        )
    
            if use_shell:
                # For commands with shell operators, execute with shell=True
                return subprocess.run(
                    command,  # command is the full command string in this case
                    shell=True,
                    text=True,
                    capture_output=True,
                    timeout=self.security_config.command_timeout,
                    cwd=self.allowed_dir,
                )
            else:
                # For regular commands, execute with shell=False
                return subprocess.run(
                    [command] + args,
                    shell=False,
                    text=True,
                    capture_output=True,
                    timeout=self.security_config.command_timeout,
                    cwd=self.allowed_dir,
                )
        except subprocess.TimeoutExpired:
            raise CommandTimeoutError(
                f"Command timed out after {self.security_config.command_timeout} seconds"
            )
        except CommandError:
            raise
        except Exception as e:
            raise CommandExecutionError(f"Command execution failed: {str(e)}")
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by disclosing: execution directory constraint (/app), available commands (pwd, ls, cat), available flags (-l, --help, -a), shell operator restrictions, and how to enable operators. It doesn't mention security implications, permission requirements, or output format details.

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?

Four sentences with zero waste - each provides essential information: purpose, available commands/flags, restrictions, and how to lift restrictions. The structure is front-loaded with the core purpose first, followed by operational details.

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

Completeness4/5

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

For a single-parameter command execution tool with no annotations and no output schema, the description provides substantial context: execution environment, command/flag constraints, and operator restrictions. It doesn't describe return values or error behavior, but given the tool's relative simplicity, this is reasonably 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% with the parameter 'command' well-documented in the schema. The description adds context about what constitutes valid commands (specific examples and restrictions), but doesn't provide additional parameter-specific semantics beyond what the schema already covers. Baseline 3 is appropriate when schema does heavy lifting.

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

Purpose5/5

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

The description explicitly states 'Allows command (CLI) execution in the directory: /app' - a specific verb ('execute') with clear resource ('command/CLI') and location constraint ('/app'). It distinguishes from the only sibling tool 'show_security_rules' which appears unrelated to command execution.

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

Usage Guidelines4/5

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

The description provides clear context about what commands and flags are available, and when shell operators are/aren't supported. However, it doesn't explicitly state when to use this tool versus alternatives (though the sibling tool appears unrelated) or provide exclusion guidance beyond the shell operator limitation.

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/MladenSU/cli-mcp-server'

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