read_screen
Retrieve visible text from an iTerm2 terminal session. Strip ANSI codes and trim blank lines to get clean terminal output.
Instructions
Read the visible contents of an iTerm2 session as plain text.
ANSI escape codes are stripped. Trailing blank lines are trimmed.
:param session_id: Target session UUID. Defaults to the active session. :param max_lines: If set, return only the last N lines.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| session_id | No | ||
| max_lines | No |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
| result | Yes |
Implementation Reference
- src/iterm2_mcp/server.py:192-209 (handler)The main handler function for the 'read_screen' tool. It resolves the target session, fetches screen contents via async_get_screen_contents(), converts to plain text via _screen_text(), optionally truncates to max_lines, and returns the result (or '(screen is empty)').
@mcp.tool() async def read_screen( session_id: str | None = None, max_lines: int | None = None, ) -> str: """Read the visible contents of an iTerm2 session as plain text. ANSI escape codes are stripped. Trailing blank lines are trimmed. :param session_id: Target session UUID. Defaults to the active session. :param max_lines: If set, return only the last N lines. """ sess = await _session(session_id) contents = await sess.async_get_screen_contents() text = _screen_text(contents) if max_lines is not None and max_lines > 0: text = "\n".join(text.splitlines()[-max_lines:]) return text or "(screen is empty)" - src/iterm2_mcp/server.py:72-77 (helper)Helper function _screen_text() that flattens a ScreenContents object into plain text by iterating over all lines and stripping trailing blank lines.
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) - src/iterm2_mcp/server.py:21-21 (registration)The tool is registered via the @mcp.tool() decorator (line 192) on the FastMCP instance created at line 21 ('mcp = FastMCP("iterm2-mcp")').
mcp = FastMCP("iterm2-mcp")