Skip to main content
Glama
mcp-interactive-terminal

mcp-interactive-terminal

by hugo94z

mcp-interactive-terminal

CI License: MIT Python 3.10+

A Model Context Protocol server that gives AI agents a real interactive terminal: launch PowerShell, PowerShell 7, CMD, bash or sh; type into it, read what happens, answer prompts, interrupt processes and resize the window — across multiple sessions that stay alive between tool calls.

Most "terminal" tools for LLMs run a command and return its output. That is not a terminal. Anything that asks a question, shows a menu, draws a progress bar or waits for a keypress is out of reach. This server runs the shell inside a pseudo-console (ConPTY on Windows, pty elsewhere), so the agent talks to a genuine terminal session, exactly like a human.

agent ── MCP (stdio) ──> session manager ── ConPTY / pty ──> powershell / pwsh / cmd / bash
                             │
                             ├─ raw output ring buffer (cursor based reads)
                             └─ VT emulator (rendered screen + scrollback)

Features

  • Real PTY sessions — ConPTY on Windows, ptyprocess on Linux and macOS. Prompts, TUIs, colors and interactive programs work.

  • Prompt-aware waits — terminal_wait(prompt=true) returns when the shell is idle again, instead of guessing from echo text.

  • One-call commands — terminal_run types a command, waits for the prompt and returns the resulting screen.

  • Live interaction — send text and named keys (enter, tab, ctrl-c, up, f1…), read incrementally.

  • Rendered screen + scrollback — the VT emulator turns cursor movements and repaints into clean, readable text; terminal_screen(history=N) adds the lines that scrolled off.

  • Blocking waits — wait for a prompt, for a regex, for output to go quiet, for the process to exit, or for a timeout. No polling.

  • Multiple sessions — independent shells running in parallel, each with its own buffer, screen and size.

  • One-shot shortcut — terminal_exec for commands that only need output and an exit code; oversized output is saved to a file.

  • UTF-8 everywhere — accents and non-ASCII output are handled on every supported shell.

  • Token friendly — incremental reads, grep/tail filters, head+tail truncation with an explicit omission marker.

  • Guardrails — optional allow/deny regexes, a working-directory jail and an idle reaper.

Related MCP server: Interactive Terminal MCP Server

Requirements

  • Windows 10 (1809+) or Windows 11 for ConPTY; Linux or macOS with ptyprocess.

  • Python 3.10+.

  • An MCP client (Claude Desktop, Cursor, opencode, Cline, any SDK-based agent).

Install

pip install git+https://github.com/hugo94z/mcp-interactive-terminal

Or from a clone:

git clone https://github.com/hugo94z/mcp-interactive-terminal
cd mcp-interactive-terminal
uv venv .venv
uv pip install --python .venv\Scripts\python.exe -e .

On Linux/macOS, use .venv/bin/python instead. The mcp-interactive-terminal command starts the server on stdio.

Configure your MCP client

opencode (~/.config/opencode/opencode.jsonc)

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "servers": {
      "interactive-terminal": {
        "type": "local",
        "command": ["mcp-interactive-terminal"]
      }
    }
  }
}

Claude Desktop (claude_desktop_config.json)

{
  "mcpServers": {
    "interactive-terminal": {
      "command": "mcp-interactive-terminal"
    }
  }
}

Cursor (.cursor/mcp.json)

{
  "mcpServers": {
    "interactive-terminal": {
      "command": "mcp-interactive-terminal"
    }
  }
}

If the command is not on your PATH, use the absolute path to the entry point, for example:

{
  "command": "C:\\Users\\you\\project\\.venv\\Scripts\\mcp-interactive-terminal.exe"
}

Tools

Tool

Description

terminal_start

Start a session (powershell, pwsh, cmd, bash, sh, or any executable), with cwd, env, cols, rows, name, replace, args. Returns the id, pid, prompt and initial screen.

terminal_run

Type a command, wait for the prompt (or until/quiet_ms) and return the screen — one round trip instead of three.

terminal_send

Send text, named keys, enter=true, repeat.

terminal_read

Incremental raw output since the last read (or an explicit since cursor). Optional grep, tail, strip_ansi.

terminal_wait

Block until prompt=true, an until regex matches, output is quiet for quiet_ms, the session exits, or timeout_ms.

terminal_screen

Rendered VT screen with cursor position and optional history (scrollback).

terminal_interrupt

Ctrl+C, then terminate the child process tree if the command is still running. The shell survives. Reports the pids that were killed.

terminal_resize

Resize the pseudo-terminal (columns × rows) without losing the next write.

terminal_list

Active sessions, state, pid, shell, cwd, size, prompt, idle time.

terminal_stop

Close a session (force to kill the tree).

terminal_exec

One-shot command: output, exit_code, timed_out, duration; full output goes to output_file when truncated.

terminal_diagnostics

Version, platform, thread count, buffers, VT errors, write latency, active policy.

Keys accepted by terminal_send

enter tab backtab esc space backspace up down left right home end pageup pagedown insert delete f1…f12 ctrl-a…ctrl-z ctrl-space ctrl-break, plus text:<literal> for arbitrary text.

Example

terminal_start(cwd="C:/work/api")
-> session_id: "t1", prompt: "PS C:\\work\\api>", screen: "PS C:\\work\\api> "

terminal_run(session_id="t1", text="python -m http.server 8080", until="Serving HTTP on", timeout_ms=15000)
-> reason: "matched", screen: "..."

terminal_exec(command="curl.exe -s -o NUL -w '%{http_code}' http://localhost:8080")
-> output: "200", exit_code: 0

terminal_interrupt(session_id="t1")
-> sent: true, killed: [12345], running: true      # back to the prompt

terminal_run(session_id="t1", text="exit")
terminal_stop(session_id="t1")

Prompt detection

At startup the server captures the shell prompt (for example PS C:\work> or user@host:~/work$). terminal_wait(prompt=true) and terminal_run then return when the prompt is visible again, instead of matching the echo of the command you just typed.

  • PowerShell, pwsh, CMD, bash and sh have built-in prompt patterns.

  • Any other executable falls back to the literal prompt learned at startup.

  • If no prompt can be recognised, terminal_run falls back to quiet detection instead of blocking until the timeout.

terminal_wait(until=...) still works as before and can be combined with prompt=true.

Why terminal_screen and terminal_read both exist

PowerShell uses PSReadLine, which redraws the current line with absolute cursor movements every time a character is typed. Raw output therefore contains fragments such as \x1b[1;58He, \x1b[1;58Hec, \x1b[1;58Hech… Stripping ANSI codes gives unreadable text.

terminal_screen feeds that stream into a VT100 emulator (via pyte) and returns what a human would actually see. terminal_read is still useful for exact incremental output (logs, byte streams, detecting events) and never returns the same bytes twice.

terminal_wait matches against the rendered screen and the raw output, and ignores the echo of the command you just typed by default (ignore_echo).

Configuration

Variable

Effect

MCP_TERMINAL_LOG_LEVEL

DEBUG, INFO, WARNING (default), ERROR, CRITICAL. Logs go to stderr.

MCP_TERMINAL_ALLOW

Newline-separated regexes. When set, every terminal_exec command must match at least one.

MCP_TERMINAL_DENY

Newline-separated regexes. A matching terminal_exec command is refused. Wins over ALLOW.

MCP_TERMINAL_ROOT

Working-directory jail. cwd must stay inside; it becomes the default cwd.

MCP_TERMINAL_IDLE_TIMEOUT

Seconds without input or output before a session is closed automatically (0 = disabled).

Guardrails apply to terminal_exec commands and to non-built-in executables started with terminal_start. They do not filter terminal_send: once an interactive shell is running, arbitrary text can be typed into it. terminal_exec and terminal_send remain available when guardrails are configured; only commands that violate ALLOW/DENY are refused.

Design notes

  • One reader thread per session pushes output into a bounded ring buffer and the VT screen under a single lock.

  • Reads are cursor-based (buffer end offset), so nothing is duplicated and nothing is lost silently.

  • terminal_wait sleeps on a condition variable — no busy loop, negligible CPU.

  • Session end is signalled by an event; terminal_exec no longer polls.

  • Resizing pauses the reader, which mitigates the ConPTY write-loss race.

  • Sessions are closed on exit (atexit, EOF on stdio, or explicit terminal_stop); forced stops kill the process tree.

  • PowerShell sessions are started with -NoExit -Command to force UTF-8 console encoding before the first prompt.

  • CMD sessions run chcp 65001 at startup.

  • POSIX sessions use ptyprocess and a TERM=xterm-256color / LANG=C.UTF-8 default.

Notes on Windows behaviour

  • Ctrl+C in a pseudo-console is not delivered as a console control event to native child processes: the control character reaches the console input buffer, but the child process group does not receive CTRL_C_EVENT. terminal_interrupt therefore sends Ctrl+C, waits for the child set to empty, then terminates whatever is left while keeping the shell alive. Processes that trap Ctrl+C gracefully get the chance to run their handler first. On POSIX the control character becomes a real SIGINT.

  • Resizing the pseudo-console used to make some shells drop the next write; the reader is now paused during setwinsize, and a 20-iteration resize test runs on CI.

Known limitations

  • The VT emulator keeps 2000 lines of scrollback per session; terminal_screen(history=N) returns them. The raw ring buffer keeps 500k characters.

  • Interactive programs that require raw mouse events or bracketed paste are not emulated.

  • Session persistence across server restarts is not implemented: sessions die with the server.

  • Long-running commands only return when terminal_wait or terminal_run is called; there is no streaming notification.

  • MCP_TERMINAL_ALLOW/DENY are guardrails, not a sandbox: an interactive shell can execute anything.

Security

This server executes arbitrary commands with the privileges of the user running it. By default there is no sandbox, no allowlist and no confirmation prompt. Only connect it to MCP clients you trust, and treat its tools with the same care as a shell running on your machine. Use MCP_TERMINAL_ALLOW, MCP_TERMINAL_DENY and MCP_TERMINAL_ROOT as guardrails when the client is less trusted.

Development

uv venv .venv
uv pip install --python .venv\Scripts\python.exe -e ".[dev]"
.venv\Scripts\python.exe -m pytest -q

On Linux/macOS use .venv/bin/python. The test suite covers the ring buffer, VT rendering and scrollback, key mapping, truncation, policy, real PowerShell/CMD sessions on Windows, real bash sessions on POSIX, and a full MCP client handshake over stdio.

License

MIT — see LICENSE.

Available Tools

12 tools
terminal_diagnosticsA

Report server diagnostics: version, platform, threads, buffers, VT errors and policy.

Useful when a session misbehaves: it shows write latency, buffer offsets, reader errors and whether an allowlist or cwd jail is active.

Inputs: no named parameters.

terminal_execA

Run a one-shot command to completion and return its output and exit code.

Use this for non-interactive commands. Use terminal_start + terminal_send for programs that need input, a TUI, or a persistent shell.

Args: command: Command line to execute. shell: "powershell", "pwsh", "cmd", "bash" or "sh". cwd: Working directory. Defaults to the server's current directory. env: Extra environment variables. timeout_ms: Kill the command after this long. max_chars: Maximum output characters returned. The full output is written to a temporary file when it is longer; its path is returned as output_file.

Returns: output, output_file, total_chars, exit_code, timed_out, duration_ms, truncated.

Inputs: command (required), cwd, env, shell, +2 more.

terminal_interruptA

Stop the command running in a session, keeping the shell alive.

Sends Ctrl+C first. Processes that ignore the control character are terminated after a grace period; the shell itself is preserved.

Args: session_id: Session returned by terminal_start. force: Skip the grace period and terminate child processes immediately.

Returns: session_id, sent, running, killed (pids terminated) and running_children.

Inputs: session_id (required), force.

terminal_listA

List active sessions with their state, pid, cwd, size, idle time, prompt and buffer size.

Inputs: no named parameters.

terminal_readA

Read incremental raw output from a session, without duplicates.

Each call returns only what arrived after the previous read. Use the returned cursor with since to resume from an explicit position.

Args: session_id: Session returned by terminal_start. since: Absolute character offset to read from. Defaults to the last read position. max_chars: Maximum characters returned (head+tail with an explicit omission marker). grep: Keep only lines matching this regular expression. tail: Keep only the last N lines (applied after grep). strip_ansi: Remove ANSI escape sequences.

Returns: text, cursor (pass as since), dropped, truncated, running, exit_code.

Note: PowerShell (PSReadLine) repaints the current line with cursor movements, so raw output contains fragments. Use terminal_screen for an authoritative view.

Inputs: session_id (required), grep, tail, since, +2 more.

terminal_resizeA

Resize the pseudo-terminal (affects wrapping and full-screen programs).

Args: session_id: Session returned by terminal_start. cols: New width, 2..1000. rows: New height, 2..500.

Inputs: cols (required), rows (required), session_id (required).

terminal_runA

Type a command, wait for it to finish, and return the resulting screen in one call.

By default it waits until the shell is back at its prompt. Provide until to wait for a regex instead, or quiet_ms to wait for output to go quiet.

Args: session_id: Session returned by terminal_start. text: Literal command to type. keys: Named keys to send instead of text (see terminal_send). enter: Append Enter after text/keys (default true). until: Case-insensitive regex to wait for instead of the prompt. quiet_ms: Wait for this long without output instead of the prompt. timeout_ms: Give up after this long. max_chars: Maximum characters returned in the screen. history: Number of scrollback lines to prepend to the screen.

Returns: reason ("prompt" | "matched" | "quiet" | "exited" | "timeout"), matched, sent_chars, screen, cursor, running and exit_code.

Inputs: session_id (required), keys, text, enter, +5 more.

terminal_screenA

Return the rendered terminal screen (VT emulation) with cursor position.

This is the clean view: cursor moves, erases and color codes are applied, so it shows exactly what a human would see, including the current prompt or TUI.

Args: session_id: Session returned by terminal_start. max_chars: Maximum characters returned (head+tail with an omission marker). history: Number of scrollback lines to prepend to the visible screen (0 = viewport only).

Returns: text, cursor {x,y}, cols, rows, running, exit_code, history_lines, history_available.

Inputs: session_id (required), history, max_chars.

terminal_sendA

Send text and/or named keys to a session.

Args: session_id: Session returned by terminal_start. text: Literal text to type (not followed by Enter unless enter=true). keys: Named keys, e.g. ["ctrl-c"], ["up"], ["tab"], ["f5"], ["text:abc"]. Supported: enter, tab, backtab, esc, space, backspace, up, down, left, right, home, end, pageup, pagedown, insert, delete, f1..f12, ctrl-a..ctrl-z, ctrl-space, ctrl-break. enter: Append a carriage return after text/keys. repeat: Repeat the whole sequence 1..100 times.

Returns: session_id, sent_chars and running state.

Inputs: session_id (required), keys, text, enter, +1 more.

terminal_startA

Start an interactive terminal session and return its id plus the initial screen.

Args: shell: "powershell" (Windows PowerShell 5.1), "pwsh" (PowerShell 7), "cmd", "bash" or "sh", or an absolute path to any executable. Defaults to powershell on Windows and bash elsewhere. cwd: Working directory. Defaults to the server's current directory (or MCP_TERMINAL_ROOT when that guardrail is configured). env: Extra environment variables merged into the inherited environment. cols: Terminal width in columns (default 120). rows: Terminal height in rows (default 30). name: Session id. Auto-generated (t1, t2, ...) when omitted. replace: Kill an existing session with the same name and start a fresh one. args: Extra arguments passed to the shell or executable.

Returns: session_id, shell, cwd, pid, size, prompt, ready reason and the rendered screen.

Inputs: cwd, env, args, cols, +4 more.

terminal_stopB

Close a session and free its process.

Args: session_id: Session returned by terminal_start. force: Kill the whole process tree instead of requesting a graceful stop.

Inputs: session_id (required), force.

terminal_waitA

Block until the shell is back at its prompt, output matches a regex, output goes quiet, the session exits, or timeout.

Args: session_id: Session returned by terminal_start. until: Case-insensitive regular expression to wait for, e.g. "PS C:\|>>>|Done". quiet_ms: Return when no output arrived for this long (0 disables quiet detection). Provide at least one of until, quiet_ms or prompt. timeout_ms: Give up after this long. ignore_echo: Ignore the echo of the last command line when matching until (prevents matching the command text itself). prompt: Return as soon as the shell shows its prompt again (recommended after a command). history: Number of scrollback lines included in the returned screen. max_chars: Optional cap on the returned screen (0 = no cap).

Returns: reason: "prompt" | "matched" | "quiet" | "exited" | "timeout", matched, running, exit_code, and the rendered screen.

Inputs: session_id (required), until, prompt, history, +4 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 12 tools

    Disambiguation4/5

    Each tool has a distinct verb targeting a distinct aspect of PTY control, and descriptions explicitly steer between the tricky pairs (terminal_exec vs terminal_run vs terminal_send, terminal_screen vs terminal_read). Residual overlap remains: terminal_run is essentially terminal_send + terminal_wait fused, and an agent must decide among run/wait/screen/read for 'see what happened' — the docs help but the boundary is still judgment-based.

    Naming Consistency5/5

    Every tool uses the same terminal_<verb> pattern with single-word, lowercase verbs: start, run, wait, screen, read, send, interrupt, stop, list, resize, exec, diagnostics. No mixed casing or inconsistent verb styles anywhere in the set.

    Tool Count5/5

    12 tools for a full interactive terminal server is well-scoped: session lifecycle, input, output, waiting, and diagnostics each get a small number of tools. Nothing appears redundant enough to remove, and no obvious capability is crammed into an overloaded tool.

    Completeness4/5

    Coverage is strong: create/list/stop sessions, send keys, interrupt, resize, read raw or rendered output, wait strategies, one-shot exec, and diagnostics. Gaps are minor — no way to clear scrollback, export a session transcript, update env after start, or reattach to a detached/finished session's buffer.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI assistants to fully interact with console applications, monitor output, detect errors, and automate terminal workflows across multiple sessions. Similar to how Playwright works for web browsers but for command-line interfaces.
      54
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides AI agents with fully interactive terminal sessions, including TUI support, keyboard control, and screen capture across Windows, Linux, and Mac.
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      A PTY-based MCP server providing persistent, interactive shell sessions with strong Windows support, enabling AI agents to run commands, handle interactive tools, and manage large output across MCP-compatible clients.
      199 npm
      13
      MIT