Skip to main content
Glama

vm_exec

Execute shell commands on remote virtual machines via SSH to manage Incus VMs, capturing output and exit codes for automation tasks.

Instructions

Execute a command on a remote host via SSH.

Runs the command via `sh -c` so shell features (pipes, redirects, etc.)
work as expected. Captures both stdout and stderr.

Args:
    vm: Name of the host (as configured in hosts.toml).
    command: Shell command to execute.
    workdir: Working directory on the remote host (default: /).
    timeout: Maximum seconds to wait (default: 120).

Returns:
    Command output with stdout, stderr, and exit code.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
vmYes
commandYes
workdirNo/
timeoutNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • MCP tool registration and handler for vm_exec. This is decorated with @mcp.tool() and serves as the entry point for the tool. It validates parameters, calls the underlying implementation, formats the result, and handles exceptions.
    @mcp.tool()
    async def vm_exec(
        vm: str,
        command: str,
        workdir: str = "/",
        timeout: int = 120,
    ) -> str:
        """Execute a command on a remote host via SSH.
    
        Runs the command via `sh -c` so shell features (pipes, redirects, etc.)
        work as expected. Captures both stdout and stderr.
    
        Args:
            vm: Name of the host (as configured in hosts.toml).
            command: Shell command to execute.
            workdir: Working directory on the remote host (default: /).
            timeout: Maximum seconds to wait (default: 120).
    
        Returns:
            Command output with stdout, stderr, and exit code.
        """
        try:
            result = await _vm_exec(vm, command, workdir=workdir, timeout=timeout)
            return _format_exec_result(result)
        except (ValueError, KeyError, TimeoutError, RuntimeError, OSError) as e:
            return f"ERROR: {e}"
  • Core implementation of vm_exec that performs SSH command execution. Resolves the host config, validates the command, wraps it with cd to workdir, and executes via SSH using sh -c for shell features.
    async def vm_exec(
        vm: str,
        command: str,
        workdir: str = "/",
        timeout: int = 120,
    ) -> ExecResult:
        """Execute a command on a remote host via SSH.
    
        Uses `ssh user@host sh -c <command>` to run the command in a shell
        so pipes, redirects, etc. work as expected.
    
        Args:
            vm: Name of the host (as configured in hosts.toml).
            command: Shell command to execute.
            workdir: Working directory on the remote host (default: /).
            timeout: Maximum seconds to wait (default: 120).
    
        Returns:
            ExecResult with stdout, stderr, and exit code.
        """
        host = _resolve_host(vm)
        if not command or not command.strip():
            raise ValueError("Command cannot be empty")
    
        # Wrap the command with cd to workdir.
        # SSH concatenates remote args into a single string, so we pass
        # the entire wrapped command as one argument to avoid splitting.
        wrapped = f"cd {workdir} && {command}"
        return await _run_ssh(
            host,
            [wrapped],
            timeout=timeout,
        )
  • Low-level SSH execution helper that runs commands on remote hosts using asyncio.create_subprocess_exec. Handles timeout, stdin piping, and returns an ExecResult with stdout, stderr, and exit code.
    async def _run_ssh(
        host_config: HostConfig,
        remote_command: list[str],
        timeout: int = 120,
        stdin_data: bytes | None = None,
    ) -> ExecResult:
        """Run a command on a remote host via SSH.
    
        Args:
            host_config: SSH connection details for the target host.
            remote_command: Command and arguments to run remotely.
            timeout: Maximum seconds to wait.
            stdin_data: Optional bytes to pipe to stdin.
    
        Returns:
            ExecResult with stdout, stderr, and exit code.
    
        Raises:
            TimeoutError: If the command exceeds the timeout.
            OSError: If the ssh binary is not found.
        """
        ssh_args = host_config.ssh_args()
        full_cmd = ["ssh"] + ssh_args + remote_command
    
        proc = await asyncio.create_subprocess_exec(
            *full_cmd,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
            stdin=asyncio.subprocess.PIPE if stdin_data else asyncio.subprocess.DEVNULL,
        )
    
        try:
            stdout_bytes, stderr_bytes = await asyncio.wait_for(
                proc.communicate(input=stdin_data),
                timeout=timeout,
            )
        except asyncio.TimeoutError:
            proc.kill()
            await proc.wait()
            raise TimeoutError(
                f"SSH command timed out after {timeout}s on {host_config.name}"
            )
    
        return ExecResult(
            stdout=stdout_bytes.decode("utf-8", errors="replace"),
            stderr=stderr_bytes.decode("utf-8", errors="replace"),
            exit_code=proc.returncode or 0,
        )
  • ExecResult dataclass schema that defines the return type for command execution, containing stdout, stderr, and exit_code fields.
    @dataclass
    class ExecResult:
        """Result of running a command on a remote host."""
    
        stdout: str
        stderr: str
        exit_code: int
  • Helper function that formats an ExecResult into a readable string for MCP responses, combining stdout, stderr, and exit code into a single formatted output.
    def _format_exec_result(result: ExecResult) -> str:
        """Format an ExecResult as a readable string for MCP response."""
        parts = []
        if result.stdout:
            parts.append(f"STDOUT:\n{result.stdout}")
        if result.stderr:
            parts.append(f"STDERR:\n{result.stderr}")
        parts.append(f"EXIT CODE: {result.exit_code}")
        return "\n".join(parts)
Behavior4/5

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

With no annotations provided, the description carries the full burden and does well by disclosing key behavioral traits: it runs commands via 'sh -c' (enabling shell features), captures both stdout and stderr, and specifies default values for workdir and timeout. However, it doesn't mention potential risks like command injection or authentication needs, leaving some gaps.

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 well-structured and front-loaded with the core purpose, followed by behavioral details and a clear parameter list. Every sentence adds value without redundancy, making it efficient and easy to parse.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity (SSH command execution with 4 parameters), no annotations, and an output schema (implied by 'Returns' section), the description is complete enough. It covers purpose, behavior, parameters, and return values, providing all necessary context for an agent to use the tool effectively.

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

Parameters5/5

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

The schema description coverage is 0%, so the description must compensate, which it does effectively by explaining all four parameters (vm, command, workdir, timeout) with clear semantics, including defaults and purposes (e.g., 'Name of the host', 'Shell command to execute'). This adds significant value beyond the bare schema.

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?

The description clearly states the specific action ('Execute a command on a remote host via SSH') and distinguishes it from sibling tools like vm_file_pull, vm_file_write, etc., which handle file operations rather than command execution. It specifies the verb ('Execute') and resource ('remote host') precisely.

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 for SSH command execution but doesn't explicitly state when to use this tool versus alternatives like vm_file_write for file operations or vm_status for status checks. It provides some context (e.g., 'via SSH') but lacks explicit guidance on exclusions or comparisons to siblings.

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/bobbyhiddn/Sympathy-MCP'

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