Skip to main content
Glama
mcp-interactive-terminal

mcp-interactive-terminal

by hugo94z
README.md
# mcp-interactive-terminal

[![CI](https://github.com/hugo94z/mcp-interactive-terminal/actions/workflows/ci.yml/badge.svg)](https://github.com/hugo94z/mcp-interactive-terminal)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](pyproject.toml)

A [Model Context Protocol](https://modelcontextprotocol.io) 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.

## 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

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

Or from a clone:

```powershell
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`)

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

### Claude Desktop (`claude_desktop_config.json`)

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

### Cursor (`.cursor/mcp.json`)

```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:

```json
{
  "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

```text
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](https://github.com/selectel/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

```powershell
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](LICENSE).

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