Skip to main content
Glama
andresthor

Command-Line MCP Server

by andresthor

execute_read_command

Execute read-only Unix/macOS terminal commands like ls, cat, and grep through a controlled interface, returning output and status for safe command execution.

Instructions

Execute a read-only Unix/macOS terminal command (ls, cat, grep, etc.).

Args: command: The read-only command to execute session_id: Optional session ID for permission management

Returns: A dictionary with command output and status

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYes
session_idNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The `execute_read_command` tool handler function that validates the command, performs directory permission checks, and calls `_execute_command` if permitted.
    async def execute_read_command(
        command: str, session_id: str | None = None
    ) -> dict[str, Any]:
        """
        Execute a read-only Unix/macOS terminal command (ls, cat, grep, etc.).
    
        Args:
            command: The read-only command to execute
            session_id: Optional session ID for permission management
    
        Returns:
            A dictionary with command output and status
        """
        # For Claude Desktop compatibility, use the fixed session ID when no session ID provided
        if not session_id:
            session_id = self.claude_desktop_session_id
            logger.info(
                f"Using persistent Claude Desktop session for read command: {session_id}"
            )
    
        # Validate command and check directory permissions in one go
        # Get the latest command lists
        command_lists = self.config.get_effective_command_lists()
        allow_separators = self.config.get(
            "security", "allow_command_separators", True
        )
    
        validation = validate_command(
            command,
            command_lists["read"],
            command_lists["write"],
            command_lists["system"],
            command_lists["blocked"],
            command_lists["dangerous_patterns"],
            allow_command_separators=allow_separators,
        )
    
        if not validation["is_valid"]:
            return {
                "success": False,
                "output": "",
                "error": validation["error"],
            }
    
        if validation["command_type"] != "read":
            return {
                "success": False,
                "output": "",
                "error": "This tool only supports read commands. Use execute_command for other command types.",
            }
    
        # Extract directory and check permissions (apply same directory checks as in _execute_command)
        working_dir = extract_directory_from_command(command)
        logger.info(f"Read command - extracted working directory: {working_dir}")
    
        # Check if directory is whitelisted or has session approval
        directory_allowed = False
    
        if working_dir:
            # Check global whitelist first
            if is_directory_whitelisted(working_dir, self.whitelisted_directories):
                directory_allowed = True
                logger.info(
                    f"Read command - directory '{working_dir}' is globally whitelisted"
                )
            # Check session approvals if we have a session ID
            elif session_id and self.session_manager.has_directory_approval(
                session_id, working_dir
            ):
                directory_allowed = True
                logger.info(
                    f"Read command - directory '{working_dir}' is approved for session {session_id}"
                )
            else:
                logger.warning(
                    f"Read command - directory '{working_dir}' is not whitelisted or approved"
                )
                # For Claude Desktop compatibility mode (require_session_id = False)
                require_session_id = self.config.get(
                    "security", "require_session_id", False
                )
                auto_approve_in_desktop = self.config.get_section("security").get(
                    "auto_approve_directories_in_desktop_mode", False
                )
    
                if not require_session_id:
                    # Check if the directory is approved in the persistent desktop session
                    if self.session_manager.has_directory_approval(
                        self.claude_desktop_session_id, working_dir
                    ):
                        directory_allowed = True
                        logger.info(
                            f"Read command - directory '{working_dir}' is approved in persistent desktop session"
                        )
                    elif auto_approve_in_desktop:
                        # Auto-approve directories in desktop mode if configured
                        directory_allowed = True
                        # Also add to persistent session for future requests
                        self.session_manager.approve_directory(
                            self.claude_desktop_session_id, working_dir
                        )
                        logger.warning(
                            f"Read command - auto-approving directory access in desktop mode: {working_dir}"
                        )
                    else:
                        # Only allow whitelisted directories if auto-approve is off
                        directory_allowed = False
                        logger.warning(
                            f"Read command - directory '{working_dir}' is not whitelisted - restricting access"
                        )
        else:
            # If we couldn't extract a directory, default to requiring permission
            logger.warning(
                "Read command - could not extract working directory from command"
            )
            working_dir = os.getcwd()  # Default to current directory
    
            # Check whitelist for current directory
            if is_directory_whitelisted(working_dir, self.whitelisted_directories):
                directory_allowed = True
            elif session_id and self.session_manager.has_directory_approval(
                session_id, working_dir
            ):
                directory_allowed = True
            else:
                # For Claude Desktop compatibility mode
                require_session_id = self.config.get(
                    "security", "require_session_id", False
                )
                auto_approve_in_desktop = self.config.get_section("security").get(
                    "auto_approve_directories_in_desktop_mode", False
                )
    
                if not require_session_id:
                    # Check if the directory is approved in the persistent desktop session
                    if self.session_manager.has_directory_approval(
                        self.claude_desktop_session_id, working_dir
                    ):
                        directory_allowed = True
                        logger.info(
                            f"Read command - directory '{working_dir}' is approved in persistent desktop session"
                        )
                    elif auto_approve_in_desktop:
                        # Auto-approve directories in desktop mode if configured
                        directory_allowed = True
                        # Also add to persistent session for future requests
                        self.session_manager.approve_directory(
                            self.claude_desktop_session_id, working_dir
                        )
                        logger.warning(
                            f"Read command - auto-approving directory access in desktop mode: {working_dir}"
                        )
                    else:
                        # Only allow whitelisted directories if auto-approve is off
                        directory_allowed = False
    
        # If directory is not allowed
        if not directory_allowed:
            # Check if we're in Claude Desktop mode (no session ID or require_session_id=false)
            require_session_id = self.config.get(
                "security", "require_session_id", False
            )
            if not session_id or not require_session_id:
                # Always use the fixed persistent session ID for Claude Desktop
                desktop_session_id = self.claude_desktop_session_id
    
                # Include approval request information for Claude Desktop
                return {
                    "success": False,
                    "output": "",
                    "error": f"Read command - access to directory '{working_dir}' is not allowed. Only whitelisted directories can be accessed.\n"
                    + f"Whitelisted directories include: {', '.join(self.whitelisted_directories)}\n"
                    + "Note: To request access to this directory, use the approve_directory tool with:\n"
                    + f'  approve_directory(directory="{working_dir}", session_id="{desktop_session_id}", remember=True)',
                    "directory": working_dir,
                    "session_id": desktop_session_id,
                    "requires_directory_approval": True,  # Signal that approval is needed
                }
            else:
                # For normal mode, request approval
                return {
                    "success": False,
                    "output": "",
                    "error": f"Read command - directory '{working_dir}' requires approval. Use approve_directory tool with session_id '{session_id}'.",
                    "requires_directory_approval": True,
                    "directory": working_dir,
                    "session_id": session_id,
                }
    
        # Now that we've validated both the command and directory permissions, execute the command
        return await self._execute_command(
            command, command_type="read", session_id=session_id
        )
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. It discloses that commands are 'read-only' and mentions 'permission management' for session_id, but lacks details on safety (e.g., what commands are allowed, error handling, rate limits, or system impact). For a tool executing terminal commands with zero annotation coverage, this is insufficient to ensure safe and correct usage.

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 sized and front-loaded, starting with the core purpose followed by parameter explanations. Every sentence adds value, but the structure could be slightly improved by integrating parameter details more seamlessly rather than as separate 'Args' and 'Returns' sections.

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?

Given the tool's complexity (executing terminal commands), no annotations, and an output schema exists (implied by 'Returns'), the description is reasonably complete. It covers purpose, parameters, and return value at a high level. However, it lacks depth on behavioral aspects like security or error handling, which could be critical for this type of tool.

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 0%, so the description must compensate. It adds meaning by explaining 'command' as 'The read-only command to execute' and 'session_id' as 'Optional session ID for permission management', which clarifies their roles beyond the schema's basic types. However, it doesn't provide detailed syntax, constraints, or examples for parameters, leaving gaps in understanding.

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 read-only Unix/macOS terminal command (ls, cat, grep, etc.)'. It specifies the verb ('Execute'), resource ('read-only Unix/macOS terminal command'), and provides examples. However, it doesn't explicitly distinguish it from sibling tools like 'execute_command' (which may not be read-only), so it doesn't reach a perfect 5.

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 implies usage by specifying 'read-only' commands and examples like 'ls, cat, grep', but it doesn't explicitly state when to use this tool versus alternatives such as 'execute_command' or other siblings. There's no guidance on exclusions or prerequisites, leaving some ambiguity for the agent.

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/andresthor/cmd-line-mcp'

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