Skip to main content
Glama

run_command

Execute a command in an iTerm2 session and wait for it to finish, then return the resulting screen output. Includes a configurable timeout and supports targeting a specific session.

Instructions

Run a command and wait for it to finish, returning the resulting screen.

Completion is detected via iTerm2's PromptMonitor COMMAND_END notification, which requires iTerm2 shell integration to be installed in the target shell. If the prompt-end event does not arrive within timeout_seconds, the current screen is returned with a [timeout] marker.

:param command: The command line to run. :param session_id: Target session UUID. Defaults to the active session. :param timeout_seconds: How long to wait for COMMAND_END before giving up.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYes
session_idNo
timeout_secondsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The run_command tool handler: sends a command line to an iTerm2 session, waits for COMMAND_END via PromptMonitor with a configurable timeout, then returns the screen contents with a reason prefix.
    @mcp.tool()
    async def run_command(
        command: str,
        session_id: str | None = None,
        timeout_seconds: float = 30.0,
    ) -> str:
        """Run a command and wait for it to finish, returning the resulting screen.
    
        Completion is detected via iTerm2's ``PromptMonitor`` ``COMMAND_END``
        notification, which requires iTerm2 shell integration to be installed in
        the target shell. If the prompt-end event does not arrive within
        ``timeout_seconds``, the current screen is returned with a ``[timeout]``
        marker.
    
        :param command: The command line to run.
        :param session_id: Target session UUID. Defaults to the active session.
        :param timeout_seconds: How long to wait for ``COMMAND_END`` before
            giving up.
        """
        sess = await _session(session_id)
        conn = await _connection_singleton()
    
        try:
            async with iterm2.PromptMonitor(
                conn,
                sess.session_id,
                modes=[iterm2.PromptMonitor.Mode.COMMAND_END],
            ) as mon:
                # Subscribe before sending the command to avoid missing fast completions.
                await sess.async_send_text(command + "\n", suppress_broadcast=True)
    
                try:
                    mode, info = await asyncio.wait_for(mon.async_get(), timeout=timeout_seconds)
                    if mode == iterm2.PromptMonitor.Mode.COMMAND_END:
                        # For COMMAND_END, ``info`` is the exit-status int directly;
                        # see PromptMonitor.async_get docstring in the iterm2 package.
                        reason = f"prompt-end (exit {info})"
                    else:
                        reason = f"unexpected monitor mode {mode}"
                except (TimeoutError, asyncio.TimeoutError):
                    reason = f"timeout after {timeout_seconds}s"
        except (TimeoutError, asyncio.TimeoutError):
            # Catches timeouts from PromptMonitor setup itself (distinct from the
            # inner wait_for timeout which covers the command execution).
            reason = f"timeout after {timeout_seconds}s"
        except Exception as exc:  # noqa: BLE001 — surface as reason, don't crash the tool
            reason = f"prompt-monitor error ({exc!r}); is shell integration installed?"
    
        contents = await sess.async_get_screen_contents()
        return f"[{reason}]\n{_screen_text(contents)}"
  • Registration of run_command as an MCP tool via the @mcp.tool() decorator on line 224.
    @mcp.tool()
  • Input schema: command (str, required), session_id (str, optional), timeout_seconds (float, default 30.0). Returns str.
    async def run_command(
        command: str,
        session_id: str | None = None,
        timeout_seconds: float = 30.0,
    ) -> str:
  • Helper function _screen_text used by run_command to convert screen contents to plain text.
    def _screen_text(contents: iterm2.ScreenContents) -> str:
        """Flatten a ``ScreenContents`` into plain text, stripping trailing blank lines."""
        lines = [contents.line(i).string for i in range(contents.number_of_lines)]
        while lines and not lines[-1].strip():
            lines.pop()
        return "\n".join(lines)
  • Helper function _session used by run_command to resolve a session ID or fall back to the active session.
    async def _session(session_id: str | None) -> iterm2.Session:
        """Resolve a session by ID, falling back to the currently active session.
    
        :param session_id: A specific session UUID to target, or ``None`` to use the
            currently focused window/tab/pane.
        """
        app = await _app()
        if session_id:
            sess = app.get_session_by_id(session_id)
            if sess is None:
                raise ValueError(f"No session found with ID {session_id!r}")
            return sess
        win = app.current_terminal_window
        if win is None:
            raise RuntimeError("No active iTerm2 window.")
        tab = win.current_tab
        if tab is None:
            raise RuntimeError("No active tab in the current window.")
        sess = tab.current_session
        if sess is None:
            raise RuntimeError("No active session in the current tab.")
        return sess
Behavior5/5

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

With no annotations, the description fully discloses behavior: blocking wait for completion, dependency on PromptMonitor, timeout handling with a [timeout] marker, and return of the resulting screen. This is comprehensive 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 concise (two paragraphs), with the main purpose front-loaded and parameter details clearly listed. Every sentence adds value without redundancy.

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 tool complexity (3 params, 1 required) and the presence of an output schema, the description covers prerequisites, behavior, and edge cases, making it fully sufficient for correct invocation.

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?

Despite 0% schema description coverage, the description provides meaningful explanations for all three parameters (command, session_id, timeout_seconds), including defaults and purpose. It adds value beyond the schema's bare names and types.

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 tool runs a command and waits for completion, returning the screen output. It specifies the resource (command execution in iTerm2) and the action (run and wait), distinguishing it from siblings like read_screen or write_to_terminal.

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 mentions the prerequisite of iTerm2 shell integration and explains the timeout behavior, but does not explicitly guide when to use this tool versus alternative sibling tools like write_to_terminal or send_control_character.

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/lorencarvalho/iterm2-mcp'

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