pty-mcp
pty-mcp is an MCP server that gives AI agents interactive terminal sessions for real shell, SSH, serial port, and persistent remote session management.
Create sessions:
create_local_session— Start local shells (bash, python, node, etc.)create_ssh_session— Connect to remote hosts via SSH with key/password auth, SSH config alias support, and optional persistent mode viaai-tmuxcreate_serial_session— Connect to serial devices (IoT, embedded, network gear) at configurable baud rates
Interact with sessions:
send_input— Send commands and wait for output to settleread_output— Read current screen output; usewait_forto block until a regex pattern appears (e.g., await reboot or error)send_control— Send special keys (Ctrl+C, Ctrl+D, Tab, arrow keys, etc.)send_secret— Prompt a human operator via GUI dialog; the secret goes directly to the PTY without ever entering AI context or logs
Manage sessions:
list_sessions— View all active sessionslist_remote_sessions— Query anai-tmuxserver for persistent sessions to reattach todetach_session— Disconnect while keeping the remote process runningclose_session— Terminate a session and its remote PTY
Additional features:
Persistent sessions — Tasks survive agent disconnects via the
ai-tmuxdaemonSettle detection — Automatically waits for output to stabilize before returning, reducing unnecessary polling
Bounded memory — Ring buffer prevents OOM on long-running sessions
Audit logging — Optionally records
send_inputcommands, operator identity, and output snippets to a central collector (best-effortorstrictmodes); secrets are never logged
Allows AI agents to interact with Python REPLs and execute Python code in an interactive terminal session, maintaining state across commands.
pty-mcp
An MCP (Model Context Protocol) server that gives AI agents interactive terminal sessions — local shells, SSH, serial ports, and persistent remote sessions that survive disconnects.
Built for sysadmins and network engineers who want AI to help with real server and device management, not just code generation.

Why
AI agents run commands in non-interactive shells. They can't:
SSH into a server and interact with running processes
Connect to routers or switches via serial console
Monitor logs and react when a specific event occurs
Keep session state across multiple commands
Wait for a server to reboot and detect when it's back up
pty-mcp solves all of these by providing real PTY sessions over MCP.
Without pty-mcp, AI agents resort to sleep 30 && check_status loops — burning CPU cycles and API calls waiting for things to happen. With wait_for, the agent blocks server-side until the event occurs. Less polling, less energy, better for polar bears. 🐻❄️
Related MCP server: interactive-cli
Use Cases
Server administration
# Reboot a server and wait until it's back online
create_local_session("ping myserver")
read_output(wait_for: "bytes from", timeout: 300)
→ blocks until server responds after reboot (~80s, one tool call)Network device management
# Connect to a router via serial console
create_serial_session(port: "/dev/ttyUSB0", baud: 9600)
send_input("show interfaces status")
read_output(wait_for: "\\$")Log monitoring and alerting
# Watch logs and act when something happens
create_ssh_session(host: "prod", user: "admin")
send_input("tail -f /var/log/app.log")
read_output(wait_for: "ERROR|CRITICAL", timeout: 3600)
→ returns the error line + context when it appearsLong-running tasks that survive disconnects
create_ssh_session(host: "server", user: "admin", persistent: true)
send_input("apt upgrade -y")
detach_session() → close Claude Code, task continues
# Reconnect later to check resultFeatures
Feature | Description |
Local terminal | Interactive bash/python/node sessions on local machine |
SSH sessions | Connect to remote hosts with key/password auth, SSH config support |
Serial port | Connect to devices via serial (IoT, embedded, network gear) |
Persistent sessions | Sessions survive SSH disconnects via |
Attach/Detach | Detach from a running session, reconnect later |
Control keys | Send ctrl+c, ctrl+d, arrow keys, tab, escape |
Settle detection | Waits for output to settle before returning (smart timeout) |
Pattern matching |
|
Bounded memory | Ring buffer prevents OOM on long-running sessions (v0.2.0) |
Resize terminal | Resize the PTY window for local, SSH, serial, and persistent remote sessions (v0.10.0) |
Audit log | Optional voluntary operation log — record |
Audit redaction | Credentials, auth headers, and PEM keys are automatically scrubbed before being written to the audit log (v0.10.0) |
Architecture
┌─────────────────────────────────────────────────────┐
│ AI Agent (Claude Code, etc.) │
│ │
│ MCP Tools: create_local_session, send_input, │
│ send_control, read_output, close_session │
└──────────────────────┬──────────────────────────────┘
│ JSON-RPC stdio
┌──────────────────────┴──────────────────────────────┐
│ pty-mcp (MCP Server) │
│ │
│ Session Manager │
│ ├── LocalSession (local PTY via creack/pty) │
│ ├── SSHSession (remote PTY via x/crypto/ssh) │
│ ├── SerialSession (serial port via go.bug.st) │
│ └── RemoteSession (persistent via ai-tmux) │
└─────────────────────────────────────────────────────┘
Persistent mode (ai-tmux):
pty-mcp ──SSH──▶ ai-tmux client ──Unix socket──▶ ai-tmux server (daemon)
├── PTY: bash
├── PTY: ssh admin@router
└── PTY: tail -f /var/log/syslogQuick Start
Claude Code Plugin (recommended)
Installs the binary automatically and registers the MCP server:
claude plugin marketplace add raychao-oao/pty-mcp
claude plugin install pty-mcp@pty-mcpRestart Claude Code — the binary downloads automatically on session start, then restart once more to activate it. No manual claude mcp add needed.
Updating:
claude plugin marketplace update pty-mcp
claude plugin update pty-mcp@pty-mcpRestart Claude Code — the new binary downloads automatically on session start, then restart once more to apply the update.
Manual install
One-line install + register (macOS / Linux / WSL2):
curl -fsSL https://raw.githubusercontent.com/raychao-oao/pty-mcp/main/install.sh | sh
claude mcp add pty-mcp -- /usr/local/bin/pty-mcpRestart Claude Code and the tools are available.
Download from GitHub Releases:
Go to Releases, download the binary for your platform, and make it executable:
Platform | Binary |
macOS (Apple Silicon) |
|
macOS (Intel) |
|
Linux (x86_64) / WSL2 |
|
Linux (ARM64) |
|
chmod +x pty-mcp-*
sudo mv pty-mcp-* /usr/local/bin/pty-mcp
claude mcp add pty-mcp -- /usr/local/bin/pty-mcpBuild from source (requires Go 1.25+):
go install github.com/raychao-oao/pty-mcp@latest
claude mcp add pty-mcp -- $(go env GOPATH)/bin/pty-mcpWSL2 Notes
pty-mcp works in WSL2 out of the box. Use the Linux binary:
# Inside WSL2
curl -fsSL https://raw.githubusercontent.com/raychao-oao/pty-mcp/main/install.sh | sh
claude mcp add pty-mcp -- /usr/local/bin/pty-mcpOptional: Install ai-tmux on remote servers
For persistent sessions that survive SSH disconnects, install ai-tmux on your remote server:
# Download for your server's architecture
curl -fsSL https://raw.githubusercontent.com/raychao-oao/pty-mcp/main/install.sh | sh
# Or just copy the binary:
scp /usr/local/bin/ai-tmux your-server:/usr/local/bin/ai-tmuxUsage Examples
Once registered, the AI agent can use these MCP tools:
Local interactive shell:
create_local_session() → {session_id, type: "local"}
send_input(session_id, "cd /tmp && ls") → {output: "...", is_complete: true}
send_input(session_id, "python3") → start Python REPL
send_input(session_id, "print('hello')") → {output: "hello\n>>>"}
send_control(session_id, "ctrl+d") → exit Python
close_session(session_id)SSH to remote server:
create_ssh_session(host: "myserver", user: "admin")
send_input(session_id, "top")
send_control(session_id, "ctrl+c") → stop topWait for pattern (v0.2.0):
create_local_session("ping myserver")
read_output(session_id, wait_for: "bytes from", timeout: 300)
→ blocks until server responds or 5 min timeout
send_input(session_id, "docker-compose up")
read_output(session_id, wait_for: "ready|error", timeout: 60, context_lines: 3)
→ returns matched line + 3 lines of contextSend secret / password (v0.3.0):
# AI detects a password prompt, calls send_secret instead of handling the password itself
create_ssh_session(host: "router", user: "admin")
read_output(session_id, wait_for: "Password:") → session is waiting for input
send_secret(session_id, prompt: "Router admin password:")
→ native GUI dialog appears on the operator's screen (macOS: system dialog,
WSL2: Windows Get-Credential, Linux: zenity/kdialog)
→ operator types password — it is sent directly to the PTY session
→ AI only sees: {success: true, length: 12}
→ password never appears in AI context or logsPersistent session (survives SSH disconnect):
create_ssh_session(host: "server", user: "admin", persistent: true)
send_input(session_id, "make build") → start long build
detach_session(session_id) → disconnect, build continues
# Later (even after restart):
list_remote_sessions(host: "server", user: "admin") → see running sessions
create_ssh_session(host: "server", user: "admin", session_id: "abc123") → reattach
send_input(session_id, "echo $?") → check build resultMCP Tools
Tool | Description |
| Start a local interactive terminal (bash, python3, node, etc.) |
| SSH to a remote host (supports SSH config aliases) |
| Connect to a serial port device |
| Send a command and wait for output to settle |
| Read output, optionally wait for a pattern ( |
| Send control keys (ctrl+c, ctrl+d, arrows, tab, etc.) |
| Prompt the human operator for a secret via GUI dialog; sends it to the PTY session without exposing it to AI context or logs ¹ |
| List all active sessions |
| Close a session (terminates remote PTY) |
| Disconnect but keep remote PTY running |
| Resize the terminal window (rows/cols) for any session type |
| List persistent sessions on a remote host |
¹
send_secretplatform support: macOS uses a native password dialog (osascript). WSL2 usespowershell.exe Get-Credential(Windows GUI dialog). Linux with a display server useszenityorkdialog. Headless Linux falls back to/dev/tty. On macOS/Linux, if the operator doesn't respond within 60 seconds, the dialog is dismissed and the call returns a timeout error instead of falling through to another dialog or waiting again; cancelling the call (e.g. pressing ESC in Claude Code) dismisses the dialog immediately the same way. WSL2 is the exception: its dialog has no timeout and is never force-closed, including on cancellation — killing a WSL-interop-launched process that owns an open Windows GUI window was found to freeze the hosting terminal (unresponsive to input, scrolling, and selection) until the operator closes that terminal, with no way to recover it short of that. The dialog just waits until the operator answers or clicks Cancel themselves, which exits normally.
Audit Log
pty-mcp includes an optional audit log feature that records every send_input command to a central collector. This lets teams review and trace what AI agents did during a session.
Important: This is a voluntary, self-reporting operation log. It relies on operators choosing to enable it and run the collector. Because pty-mcp runs on the operator's own machine, there is no technical mechanism to enforce logging — a non-compliant operator could simply run pty-mcp without audit enabled. This feature provides traceability for teams that want it, but it is not a substitute for system-level audit tools (e.g., auditd, syslog forwarding, SSH session recording) in environments where audit compliance is required.
What it records
Timestamp, operator identity, session ID, session type (local/ssh/serial), target host
The exact input sent via
send_input(includingraw=trueinputs like menu selections)Output snippet (first 2 KB) after each command
A
cmd_idlinking the command to its output
send_secret is never logged — secrets entered via the GUI dialog do not appear in the audit log.
Commands and output snippets are automatically redacted before being written. The following patterns are replaced with [REDACTED] or [PRIVATE KEY REDACTED]:
Key-value credentials:
password=,passwd:,token=,api_key=,access_key=,auth_token=,secret=HTTP Authorization headers:
Authorization: Bearer …,Authorization: Basic …,Authorization: Token …PEM private key blocks:
-----BEGIN RSA PRIVATE KEY-----/-----BEGIN OPENSSH PRIVATE KEY-----
Setup
Each operator runs once to create their config and generate a token:
pty-mcp audit initThis creates ~/.config/pty-mcp/config (chmod 600) with a randomly generated token and prints the token to share with the collector admin.
The collector admin starts the server (using the token from init output):
PTY_MCP_AUDIT_TOKEN=<token-from-init> \
pty-mcp audit serve --port 9099 --log /var/log/pty-mcp-audit.jsonlEnable audit after setting the collector URL in the config:
# Edit config and set: audit-url=http://your-collector:9099
pty-mcp audit enable
# Restart Claude Code to applyTo temporarily stop logging without losing your config:
pty-mcp audit disableOperators without a config file are unaffected — audit is off by default.
Audit modes
Mode | Behaviour |
| Commands execute regardless of whether the log was written; entries are queued and retried in the background |
|
|
Reviewing logs
Logs are stored as JSONL (one JSON object per line), readable with standard tools:
# All commands by operator ray
grep '"user":"ray"' /var/log/pty-mcp-audit.jsonl | jq .
# Commands sent to a specific host
jq 'select(.target == "root@prod01")' /var/log/pty-mcp-audit.jsonlai-tmux: Persistent Terminal Daemon
ai-tmux is a lightweight daemon that runs on remote servers, keeping PTY sessions alive across SSH disconnects. Think of it as tmux designed for AI agents.
Install on remote server
# Cross-compile for Linux
GOOS=linux GOARCH=amd64 go build -o ai-tmux-linux ./cmd/ai-tmux/
# Copy to server
scp ai-tmux-linux server:~/ai-tmux
ssh server "chmod +x ~/ai-tmux && sudo mv ~/ai-tmux /usr/local/bin/ai-tmux"How it works
ai-tmux server— daemon mode, listens on Unix socket, manages PTY sessionsai-tmux client— bridge mode, forwards JSON protocol over stdin/stdout (used by pty-mcp over SSH)ai-tmux list— list active sessions
The daemon auto-starts when pty-mcp connects with persistent: true. Sessions are reaped after 30 minutes of inactivity.
pty-mcp checks ai-tmux --version on the remote host before opening a session and returns a clear error if the binary is missing or below the minimum required version — no cryptic connection errors.
SSH Config Support
pty-mcp reads ~/.ssh/config to resolve host aliases:
# ~/.ssh/config
Host myserver
HostName 192.168.1.100
User admin
Port 2222
IdentityFile ~/.ssh/id_ed25519create_ssh_session(host: "myserver", user: "admin")
# Automatically resolves hostname, port, and identity fileRequirements
Go 1.25+
For serial: appropriate device permissions
For persistent sessions:
ai-tmuxbinary on remote server
Changelog
See CHANGELOG.md for version history.
License
MIT
Available Tools
16 toolsclose_sessionB
Close a session (also terminates remote PTY)
Inputs: session_id (required).
create_local_sessionA
Open a local interactive terminal session (bash, python3, node, etc.). WARNING: Executes as the current user with full local system access — this is by design for legitimate sysadmin automation. Only use on trusted systems.
Inputs: command, log_file, log_max_size, log_max_files.
create_serial_sessionB
Open a serial port session. Device path must start with /dev/tty or /dev/cu. (e.g. /dev/ttyUSB0, /dev/cu.usbserial-XXXX)
Inputs: device (required), log_file, baud_rate, log_max_size, +1 more.
create_ssh_sessionB
Open an interactive SSH session (supports key/password auth and SSH config aliases)
Inputs: host (required), user (required), port, command, +8 more.
detach_sessionA
Detach from a persistent session but keep the remote PTY running (reattach via list_remote_sessions + session_id)
Inputs: session_id (required).
get_credential_bundleA
Generate a signed ConsumerBundle for use with cred-mcp's vault_seal tool. The bundle contains only public keys and is safe to pass to the AI. The session private key is held in memory for a matching inject_secret call. Call this before request_authorization + vault_seal on cred-mcp.
Inputs: consumer_id, ttl_seconds.
get_session_stateB
Get detailed state of a session: type, target, is_alive, cursor, and classified state (at_prompt/password_prompt/confirmation/pager/running/unknown), awaiting_secret, last_prompt. Use cursor with read_output(since_cursor=...) for incremental reads.
Inputs: session_id (required).
inject_secretA
Decrypt a SealedBox from cred-mcp and write the plaintext directly into a PTY session. The plaintext never appears in AI context or tool results — only {success:true} is returned. Call after vault_seal on cred-mcp.
Inputs: sealed_box (required), pty_session_id (required).
list_remote_sessionsB
List persistent sessions on a remote ai-tmux server (use session_id to reattach). Optionally filter by status.
Inputs: host (required), user (required), port, status, +3 more.
list_sessionsB
List all active sessions
prepare_secretA
Pre-stage a secret (password/passphrase) for a session. Shows a GUI dialog NOW so the operator can enter the secret before a password prompt appears. The secret is stored in a buffer and automatically sent when a password prompt is detected — no further agent action needed. Use this before connecting to devices with short password timeouts (e.g. serial console). The buffered secret is never logged.
Inputs: session_id (required), prompt, line_ending.
read_outputA
Read output from a session. Three modes: (1) default: wait for output to settle, (2) since_cursor: incremental read from a cursor position (returns only new output), (3) wait_for: block until a regex pattern matches. Mode 2 response includes has_more (true = more unread data, call again with new cursor) and is_truncated (true = data was overwritten before you read it).
Inputs: session_id (required), timeout, wait_for, max_bytes, +3 more.
resize_sessionA
Resize the terminal window (rows x cols) for a session. Affects how TUI tools (top, less, vim, etc.) lay out output. Serial sessions are not supported.
Inputs: cols (required), rows (required), session_id (required).
send_controlB
Send a control key (ctrl+c, ctrl+d, enter, tab, up, down, etc.)
Inputs: key (required), session_id (required).
send_inputA
Send input and wait for output to settle. Returns cursor_start/cursor_end for command boundary tracking, and is_complete (false = timeout, use read_output for remaining output). If wait_for is set, blocks until the pattern matches (combines send_input + read_output wait_for in one call).
Inputs: input (required), session_id (required), raw, wait_for, +2 more.
send_secretA
Prompt the human user to type a secret (password/passphrase) directly into a GUI dialog. The value is sent to the PTY session without ever appearing in AI context or logs. IMPORTANT: only call this when the session is actively waiting for a password input (echo is off) — e.g. an SSH/sudo/getpass prompt. Do NOT call this on an idle shell prompt. If prepare_secret was called earlier for this session, uses the buffered secret without showing a dialog.
Inputs: session_id (required), prompt.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 16 tools
Each tool has a clearly distinct purpose: session creation (local, SSH, serial), management (list, close, detach, resize), interaction (send_input, send_control, read_output), and secret handling (prepare, inject, send, get credentials). No ambiguity between tools.
All tools follow a consistent verb_noun pattern in snake_case (e.g., create_local_session, send_input, get_session_state). No mixing of conventions, and verbs are uniform.
16 tools is well-scoped for a PTY management server. It covers session creation, lifecycle, input/output, secrets, and state inspection without being excessive or sparse.
The tool surface is comprehensive for the domain: all major session types (local, SSH, serial), full lifecycle (create, close, detach, resize), input/output (send, read with cursors), secret management (prepare, inject, send, credential bundles), and state inspection.
Maintenance
Related MCP Connectors
Persistent memory, hybrid search and a goal graph for AI agents, over stdio or remote HTTP.
Remote shell and detached long-running jobs on your own machines — no SSH, open ports or VPN.
Persistent cloud workspaces for AI agents: run commands, edit files, use git and a browser.
Multi-tenant Telegram gateway for AI agents — HTTP+stdio, 8 tools, MTProto User API
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceProvides AI agents with fully interactive terminal sessions, including TUI support, keyboard control, and screen capture across Windows, Linux, and Mac.MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to interact with interactive CLI processes via a real PTY, allowing them to send keystrokes, read screen output, and handle interactive prompts.6 npm1MIT
- AlicenseAqualityCmaintenanceGive AI agents a persistent, interactive terminal with support for SSH, REPLs, database CLIs, TUI apps, and long-running processes.950 PyPI12MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to drive real interactive terminal sessions—PTYs, TUIs, REPLs, SSH, even another agent's CLI—with a live web view where humans can watch and type in.5 npm2MIT