Skip to main content
Glama
sichang824

MCP Terminal

by sichang824

execute_command

Execute terminal commands through an AI assistant using the Model Context Protocol to perform system operations and retrieve outputs.

Instructions

Executes a terminal command

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYes
wait_for_outputNo
timeoutNo

Implementation Reference

  • The MCP tool handler function 'execute_command' decorated with @mcp.tool(name="execute_command"). Performs command filtering using CommandFilter, executes via self.controller.execute_command, and maps result to ExecuteCommandResponse.
    @mcp.tool(name="execute_command", description="Executes a terminal command")
    async def execute_command(
        command: str,
        wait_for_output: bool = True,
        timeout: int = 10,
    ) -> ExecuteCommandResponse:
        try:
            # Check if command is allowed
            is_allowed, reason = self.command_filter.is_command_allowed(command)
    
            if not is_allowed:
                logger.warning(
                    f"Command execution denied: {command}. Reason: {reason}"
                )
                return ExecuteCommandResponse(
                    success=False,
                    error=f"Command not allowed: {reason}",
                )
    
            # Ensure we have a controller
            if not self.controller:
                self._init_controller()
    
            # Execute the command
            result = await self.controller.execute_command(
                command, wait_for_output, timeout
            )
    
            # Convert to response model
            return ExecuteCommandResponse(
                success=result.get("success", False),
                output=result.get("output"),
                error=result.get("error"),
                return_code=result.get("return_code"),
                warning=result.get("warning"),
            )
        except Exception as e:
            logger.error(f"Error executing command: {e}")
            return ExecuteCommandResponse(
                success=False, error=f"Error executing command: {str(e)}"
            )
  • ExecuteCommandRequest Pydantic model defining the input parameters: command (str), wait_for_output (bool, default True), timeout (int, default 10).
    class ExecuteCommandRequest(BaseModel):
        """Request model for executing a terminal command."""
    
        command: str = Field(..., description="The command to execute in the terminal")
        wait_for_output: bool = Field(
            True, description="Whether to wait for the command output"
        )
        timeout: int = Field(
            10, description="Timeout in seconds for waiting for the command output"
        )
  • ExecuteCommandResponse Pydantic model defining the output: success (bool), output (str|None), error (str|None), return_code (int|None), warning (str|None).
    class ExecuteCommandResponse(BaseModel):
        """Response model for the executed terminal command."""
    
        success: bool = Field(
            ..., description="Whether the command execution was successful"
        )
        output: Optional[str] = Field(None, description="The command output if available")
        error: Optional[str] = Field(
            None, description="Error message if the command failed"
        )
        return_code: Optional[int] = Field(
            None, description="The command return code if available"
        )
        warning: Optional[str] = Field(None, description="Warning message if any")
  • In MCPTerminalServer.register_tools(): instantiates TerminalTool with config, then calls terminal_tool.register_mcp(self.mcp) which defines and registers the execute_command tool.
    # Create and register the terminal tool
    terminal_tool = TerminalTool(
        self.controller_type,
        whitelist_file=self.whitelist_file,
        blacklist_file=self.blacklist_file,
        whitelist_mode=self.whitelist_mode,
    )
    file_tool = FileTool()
    terminal_tool.register_mcp(self.mcp)
    file_tool.register_mcp(self.mcp)
    self.tools["terminal"] = terminal_tool
    self.tools["file"] = file_tool
    
    self.tools_registered = True
    logger.info("Terminal tool registered with MCP server")
  • SubprocessTerminalController.execute_command: core implementation using asyncio.create_subprocess_shell to execute commands, capture stdout/stderr/returncode with timeout support. Default cross-platform controller.
    async def execute_command(
        self, command: str, wait_for_output: bool = True, timeout: int = 10
    ) -> Dict[str, Any]:
        """
        Execute a command using subprocess.
    
        Args:
            command: The command to execute
            wait_for_output: Whether to wait for output
            timeout: Timeout in seconds
    
        Returns:
            A dictionary with the result of the command execution
        """
        try:
            # Create subprocess
            process = await asyncio.create_subprocess_shell(
                command,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
            )
    
            if wait_for_output:
                try:
                    # Wait for the process to complete with timeout
                    stdout, stderr = await asyncio.wait_for(
                        process.communicate(), timeout=timeout
                    )
    
                    return {
                        "success": process.returncode == 0,
                        "output": stdout.decode("utf-8", errors="replace"),
                        "error": stderr.decode("utf-8", errors="replace"),
                        "return_code": process.returncode,
                    }
                except asyncio.TimeoutError:
                    # Kill the process if it times out
                    try:
                        process.kill()
                    except ProcessLookupError:
                        pass
                    return {
                        "success": False,
                        "error": f"Command timed out after {timeout} seconds",
                    }
            else:
                # Don't wait for output
                return {
                    "success": True,
                    "output": "Command sent (output not captured)",
                }
    
        except Exception as e:
            return {
                "success": False,
                "error": f"Error executing command: {str(e)}",
            }
Behavior2/5

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

With no annotations provided, the description carries full burden but only states the action without disclosing behavioral traits. It doesn't mention permissions needed, side effects (e.g., file changes, system impacts), error handling, or output format, which is critical for a command execution tool.

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 sentence with zero waste. It's appropriately sized and front-loaded, though this brevity contributes to underspecification rather than clarity.

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?

For a 3-parameter tool with no annotations, no output schema, and 0% schema coverage, the description is incomplete. It lacks essential details about execution context, safety, and results, making it inadequate for informed tool selection and invocation.

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

Parameters1/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 but adds no parameter information. It doesn't explain what 'command' should contain, how 'wait_for_output' affects behavior, or what 'timeout' units are (seconds?), leaving all three parameters undocumented.

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 'Executes a terminal command' states the basic action (verb+resource) but is vague about scope and lacks differentiation from siblings like 'get_terminal_info'. It doesn't specify what kind of commands or execution environment, making it minimally adequate but unclear.

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?

No guidance on when to use this tool versus alternatives like 'file_modify' or 'get_terminal_info'. The description implies execution but doesn't mention prerequisites, safety considerations, or typical use cases, leaving the agent with no contextual direction.

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

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