Skip to main content
Glama

execute_read_command

Execute read-only Unix/macOS terminal commands like ls, cat, and grep to retrieve system information without modifying files or directories.

Instructions

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

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesThe read-only command to execute
session_idNoOptional session ID for permission management

Implementation Reference

  • The execute_read_command tool handler validates the command type, checks directory permissions (whitelisted or approved), and executes the read command using _execute_command.
    async def execute_read_command(
        command: str, session_id: Optional[str] = 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
        )
Behavior3/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 the 'read-only' constraint (critical for safety), but lacks details on enforcement (what happens if 'rm' is passed?), output format, exit codes, timeout behavior, or sandbox boundaries expected for shell execution tools.

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?

Single sentence with efficient parenthetical examples. No wasted words. However, given the high-stakes nature of shell execution, it is slightly too terse—one additional sentence on safety or output would improve utility without bloating.

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 tool executing arbitrary shell commands, the description is minimally adequate. With no output schema and no annotations, it should disclose behavioral specifics like error handling, return structure, or command validation rules. Currently relies entirely on the 'read-only' keyword for safety signaling.

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

Parameters4/5

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

Schema coverage is 100%, establishing a baseline of 3. The description adds value by providing concrete examples (ls, cat, grep) that clarify the expected syntax and nature of the 'command' parameter beyond the schema's generic description.

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?

Specific verb 'Execute' + resource 'Unix/macOS terminal command' with clear scope restriction 'read-only'. The parenthetical examples (ls, cat, grep) concrete the intent. Effectively distinguishes from sibling 'execute_command' by emphasizing the read-only constraint.

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 'read-only' descriptor provides clear context for when to use this tool (inspection/reading) versus when to avoid it (modification/writing). However, it does not explicitly name the sibling alternative 'execute_command' for non-read operations.

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/wwqdrh/MCPcmd'

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