Skip to main content
Glama
GongRzhe

Terminal Controller for MCP

execute_command

Execute terminal commands to automate system tasks, manage files, and control processes through a secure interface for LLMs.

Instructions

Execute terminal command and return results

Args:
    command: Command line command to execute
    timeout: Command timeout in seconds, default is 30 seconds

Returns:
    Output of the command execution

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYes
timeoutNo

Implementation Reference

  • The handler function for the 'execute_command' MCP tool. Decorated with @mcp.tool() for registration. Performs security checks on dangerous commands, calls the run_command helper to execute the shell command with timeout support, and formats the stdout/stderr/output into a user-friendly string response.
    async def execute_command(command: str, timeout: int = 30) -> str:
        """
        Execute terminal command and return results
        
        Args:
            command: Command line command to execute
            timeout: Command timeout in seconds, default is 30 seconds
        
        Returns:
            Output of the command execution
        """
        # Check for dangerous commands (can add more security checks)
        dangerous_commands = ["rm -rf /", "mkfs"]
        if any(dc in command.lower() for dc in dangerous_commands):
            return "For security reasons, this command is not allowed."
        
        result = await run_command(command, timeout)
        
        if result["success"]:
            output = f"Command executed successfully (duration: {result['duration']})\n\n"
            
            if result["stdout"]:
                output += f"Output:\n{result['stdout']}\n"
            else:
                output += "Command had no output.\n"
                
            if result["stderr"]:
                output += f"\nWarnings/Info:\n{result['stderr']}"
                
            return output
        else:
            output = f"Command execution failed (duration: {result['duration']})\n"
            
            if result["stdout"]:
                output += f"\nOutput:\n{result['stdout']}\n"
                
            if result["stderr"]:
                output += f"\nError:\n{result['stderr']}"
                
            output += f"\nReturn code: {result['return_code']}"
            return output
  • Supporting helper function that performs the actual subprocess execution of the command. Handles Windows/Linux differences, timeout with asyncio, decodes output, logs to history, and returns structured dict with success, stdout, stderr, return_code, duration.
    async def run_command(cmd: str, timeout: int = 30) -> Dict:
        """
        Execute command and return results
        
        Args:
            cmd: Command to execute
            timeout: Command timeout in seconds
            
        Returns:
            Dictionary containing command execution results
        """
        start_time = datetime.now()
        
        try:
            # Create command appropriate for current OS
            if platform.system() == "Windows":
                process = await asyncio.create_subprocess_shell(
                    cmd,
                    stdout=asyncio.subprocess.PIPE,
                    stderr=asyncio.subprocess.PIPE,
                    shell=True
                )
            else:
                process = await asyncio.create_subprocess_shell(
                    cmd,
                    stdout=asyncio.subprocess.PIPE,
                    stderr=asyncio.subprocess.PIPE,
                    shell=True,
                    executable="/bin/bash"
                )
            
            try:
                stdout, stderr = await asyncio.wait_for(process.communicate(), timeout)
                stdout = stdout.decode('utf-8', errors='replace')
                stderr = stderr.decode('utf-8', errors='replace')
                return_code = process.returncode
            except asyncio.TimeoutError:
                try:
                    process.kill()
                except:
                    pass
                return {
                    "success": False,
                    "stdout": "",
                    "stderr": f"Command timed out after {timeout} seconds",
                    "return_code": -1,
                    "duration": str(datetime.now() - start_time),
                    "command": cmd
                }
        
            duration = datetime.now() - start_time
            result = {
                "success": return_code == 0,
                "stdout": stdout,
                "stderr": stderr,
                "return_code": return_code,
                "duration": str(duration),
                "command": cmd
            }
            
            # Add to history
            command_history.append({
                "timestamp": datetime.now().isoformat(),
                "command": cmd,
                "success": return_code == 0
            })
            
            # If history is too long, remove oldest record
            if len(command_history) > MAX_HISTORY_SIZE:
                command_history.pop(0)
                
            return result
        
        except Exception as e:
            return {
                "success": False,
                "stdout": "",
                "stderr": f"Error executing command: {str(e)}",
                "return_code": -1,
                "duration": str(datetime.now() - start_time),
                "command": cmd
            }

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/GongRzhe/terminal-controller-mcp'

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