Skip to main content
Glama

execute_command

Execute shell commands in a specified directory using bash or sh shells to automate system tasks and manage files securely.

Instructions

Execute a shell command in a specified directory using a specified shell

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesThe shell command to execute
shellYesShell to use for execution. Available: ['bash', 'sh']
cwdYesWorking directory for command execution

Implementation Reference

  • MCP call_tool handler that checks the tool name is 'execute_command', extracts parameters, calls the execution function, and returns the result as text content.
    @server.call_tool() async def call_tool(name: str, arguments: Dict[str, Any]) -> List[types.TextContent]: """ Handle tool calls for shell command execution. Args: name (str): The name of the tool to call (must be 'execute_command') arguments (Dict[str, Any]): Tool arguments including 'command', 'shell', and 'cwd' Returns: List[types.TextContent]: The command execution results or error message """ if name != "execute_command": return [types.TextContent(type="text", text=f"Error: Unknown tool {name}")] command = arguments["command"] shell = arguments["shell"] cwd = arguments["cwd"] try: result = await run_shell_command(shell, command, cwd) return [types.TextContent(type="text", text=str(result))] except Exception as e: return [types.TextContent(type="text", text=f"Error: {str(e)}")]
  • Core helper function that performs the actual shell command execution with path validation, shell support, timeout handling, and cross-platform compatibility.
    async def run_shell_command(shell: str, command: str, cwd: str) -> Dict[str, Any]: """ Execute a shell command safely and return its output. Args: shell (str): Name of the shell to use command (str): The command to execute cwd (str): Working directory for command execution Returns: Dict[str, Any]: Command execution results including stdout, stderr, and exit code """ if not settings.is_path_allowed(cwd): raise ValueError(f"Directory '{cwd}' is not in the allowed directories list") if shell not in settings.ALLOWED_SHELLS: raise ValueError(f"Shell '{shell}' is not allowed. Available shells: {list(settings.ALLOWED_SHELLS.keys())}") shell_path = settings.ALLOWED_SHELLS[shell] try: if sys.platform == 'win32': shell_cmd = [shell_path, '/c', command] if shell == 'cmd' else [shell_path, '-Command', command] else: shell_cmd = [shell_path, '-c', command] process = await asyncio.create_subprocess_exec( *shell_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=cwd ) try: stdout, stderr = await asyncio.wait_for( process.communicate(), timeout=settings.COMMAND_TIMEOUT ) return { "stdout": stdout.decode() if stdout else "", "stderr": stderr.decode() if stderr else "", "exit_code": process.returncode, "command": command, "shell": shell, "cwd": cwd } except asyncio.TimeoutError: try: process.kill() await process.wait() except ProcessLookupError: pass raise TimeoutError(f"Command execution timed out after {settings.COMMAND_TIMEOUT} seconds") except TimeoutError: raise except Exception as e: return { "stdout": "", "stderr": str(e), "exit_code": -1, "command": command, "shell": shell, "cwd": cwd }
  • Registers the 'execute_command' tool by listing it with @server.list_tools() decorator, including name, description, and input schema.
    @server.list_tools() async def list_tools() -> List[types.Tool]: """List available shell tools.""" return [ types.Tool( name="execute_command", description="Execute a shell command in a specified directory using a specified shell", inputSchema={ "type": "object", "properties": { "command": { "type": "string", "description": "The shell command to execute", }, "shell": { "type": "string", "description": f"Shell to use for execution. Available: {list(settings.ALLOWED_SHELLS.keys())}", }, "cwd": { "type": "string", "description": "Working directory for command execution", }, }, "required": ["command", "shell", "cwd"], }, ) ]
  • Defines the input schema for the 'execute_command' tool, specifying required parameters: command, shell, cwd.
    "type": "object", "properties": { "command": { "type": "string", "description": "The shell command to execute", }, "shell": { "type": "string", "description": f"Shell to use for execution. Available: {list(settings.ALLOWED_SHELLS.keys())}", }, "cwd": { "type": "string", "description": "Working directory for command execution", }, }, "required": ["command", "shell", "cwd"], },
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/blazickjp/shell-mcp-server'

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