Persistent stateful remote SSH sessions for AI agents via MCP + OpenSSH.
The io.github.the-nine-nation/remote-ssh-mcp server provides persistent, stateful remote SSH sessions for AI agents using MCP (Model Context Protocol) and OpenSSH. It is intended to enable remote execution workflows from an agent-driven environment.
๐ ๏ธ Key Features
Persistent SSH sessions
Stateful remote SSH access for AI agents
MCP + OpenSSH integration
๐ Use Cases
Running remote commands via SSH for AI agents
Agent-driven remote execution and terminal-style workflows
DevOps tasks requiring remote access through MCP (e.g., bash execution)
โก Developer Benefits
Compatibility with MCP-server tooling and workflows
Works in a Node.js/TypeScript environment
Supports common agent tooling contexts associated with LLM usage
โ ๏ธ Limitations
Requires OpenSSH and SSH connectivity to remote hosts
Limited to SSH-based remote execution as described in the server purpose
Banners, MOTD, login noise, and pwd / whoami probes flood the context
๐ง Lost state
cwd, export, venv activation, and shell side effects vanish
๐ Unstable
Fresh connects hit timeouts, host-key prompts, ProxyJump, and auth jitter
๐ Error spiral
The model compensates with longer probe commands โ more tokens
Remote SSH MCP turns a long-lived remote Bash into first-class MCP tools. One session ID keeps working directory, environment variables, and shell side effects. Open a new session when you need a clean environment.
Each step re-pays connect noise + state probes; models often re-cd / re-pwd
Pay once on ssh_open; later ssh_run returns mostly command output. Structured tools + head/tail caps cut tool-result bloat. In multi-step sessions this commonly cuts remote-tool context by ~50โ80% vs reconnect-every-time (exact savings depend on MOTD size and how chatty the model is).
โ Success rate
N steps โ N handshakes โ N chances to fail (timeout, jump, agent, host key)
One handshake per session; subsequent commands ride a live shell. Long jobs use running + ssh_peek instead of killing the tool call and restarting. Fewer reconnects โ far fewer false โSSH failedโ loops mid-task.
๐งณ Portability
Remote needs nothing extra โ but every agent machine reimplements the same brittle ssh โฆ patterns
Install once on the machine that runs Claude / Cursor / Grok / etc. Remote hosts install nothing (no Node, no MCP daemon, no agent). Only a normal shell account + tools already required for SSH (bash, base64, stty, โฆ). Keys and jump hosts stay in local~/.ssh/config.
๐ง Model ergonomics
Model invents ssh strings, escapes, and recovery
Stable tools: open โ run โ peek โ close. Session id is the only handle.
๐ Trust boundary
Easy to over-expose keys or prompt for passwords in-band
OpenSSH client only; tools never accept passwords or private-key material
Portability in one line: put the MCP on your dev box / AI host; every server already in your SSH config is reachable โ zero package install on the remote fleet.
text
โโโโโโโโโโโโโโโโโโโโโโโโโโโ SSH (OpenSSH) โโโโโโโโโโโโโโโโโโโโ
โ Your laptop / CI agent โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโบ โ prod / staging โ
โ Claude ยท Cursor ยท Grok โ ~/.ssh/config ยท agent โ no MCP install โ
โ + remote-ssh-mcp โ โ plain Bash OK โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ
One-shot path (per step ร 8):
ssh wrapper + banner/MOTD + pwd/whoami + re-cd + command output
โ noise dominates; context fills with reconnect junk
Session path:
ssh_open โ once (handshake + READY)
ssh_run ร 8 โ mostly the real stdout/stderr (truncated head+tail)
โ context stays on the work product, not the transport
It does not reimplement SSH. Your system OpenSSH client stays in charge โ so ~/.ssh/config, known hosts, the SSH agent, ProxyJump routes, and hardware keys keep working exactly as they already do.
text
ssh_hosts() โ discover allowed Host aliases
ssh_open(host) โ session id
ssh_run(id, command) โ same cwd + env as last time
ssh_peek / ssh_interrupt โ observe or recover long / stuck work
ssh_close(id) โ release the shell and connection
Features
๐ง Persistent remote sessions
One stable session ID maps to one long-lived remote Bash
cwd and environment survive across ssh_run calls
Open a fresh session whenever you need a clean slate
Multiple sessions can target the same or different hosts (up to maxSessions)
๐ง Native OpenSSH integration
Spawns the real ssh binary โ no custom crypto stack
Honors ~/.ssh/config, Include, agent sockets, and ProxyJump
Forces BatchMode=yes and StrictHostKeyChecking=yes
Never accepts passwords, private-key text, or arbitrary SSH option args from the model
๐ก Long-running command friendly
ssh_run waits up to wait_sec (default 10s), then returns status: "running" while the remote command continues
Poll with ssh_peek(wait_sec=...) long-poll instead of busy-looping
Optional hard timeout_sec sends Ctrl-C; no automatic kill by default
Ideal for docker pull, builds, downloads, and deploys that must not block the tool call forever
Fail-closed interrupt: if shell recovery cannot be confirmed after Ctrl-C, the session is closed
Built-in denylist for a few obviously destructive patterns (not a full policy engine)
Idle reaping, session caps, and a JSONL audit log (0600) with hashed commands
๐ฆ Clean tool results for models
Separate stdout / stderr streams
Head-and-tail byte truncation with valid UTF-8 boundaries
ssh_hosts returns only safe metadata: alias, hostname, user, port, proxy_jump
Never leaks IdentityFile, certificates, agent sockets, or ProxyCommand
๐ MCP-native
stdio transport for Claude Desktop, Cursor, and other MCP hosts
Compatible with both legacy and current MCP handshakes
Parent / stdio exit closes every tracked SSH connection
How it works
flowchart LR
A[AI Agent] -->|MCP tools| B[Remote SSH MCP]
B -->|spawn| C[OpenSSH client]
C -->|SSH + PTY| D[Remote Bash]
D --> E[(cwd / env / side effects)]
subgraph Local machine
B
C
F[~/.ssh/config<br/>agent / keys]
C -.-> F
end
subgraph Remote host
D
E
end
Typical agent flow
text
1. ssh_hosts() # pick an alias from the allowlist
2. ssh_open(host="prod") # get session id "s_โฆ"
3. ssh_run(id, "cd app && โฆ") # state sticks to this id
4. ssh_run(id, "npm test") # still in app/, env preserved
5. ssh_peek(id, wait_sec=20) # long-poll a slow job
6. ssh_close(id) # clean up when done
MCP tools
Tool
What it does
๐๏ธ ssh_hosts
List allowed Host aliases (safe metadata only). Pass reload=true after editing ~/.ssh/config
๐ ssh_open
Open a clean persistent shell for an allowed Host alias โ returns session id
โถ๏ธ ssh_run
Run a non-interactive command in an existing session
๐ ssh_peek
Latest N lines of output + status; optional wait_sec long-polls while running
โ ssh_interrupt
Send Ctrl-C and wait for confirmed shell recovery
๐ ssh_list
List sessions, cwd, state, idle countdown, and capacity
๐ ssh_close
Tear down remote temp state and close the connection
id, optional lines (default 50, max 1000), optional wait_sec
ssh_interrupt / ssh_close
id
ssh_hosts
optional reload boolean
Quick start
Requirements
Requirement
Notes
Node.js
20 or newer
OpenSSH client
System ssh on PATH (or set sshPath)
Remote host
Bash + base64, stty, mkdir, cat, rm
SSH setup
Host alias in ~/.ssh/config, host key already trusted
โ ๏ธ First-time host-key confirmation and authentication must be completed in a normal terminal. The MCP server never shows password or trust prompts.
Install
bash
git clone https://github.com/the-nine-nation/remote-ssh-mcp.git
cd remote-ssh-mcp
npm install
npm run build
npm test
Cursor ยท Claude Desktop ยท Claude Code ยท other MCP-capable hosts: point command / args at the built dist/index.js and set SSH_MCP_ALLOWED_HOSTS (or rely on auto-discovery from ~/.ssh/config).
SSH_MCP_ALLOWED_HOSTSadds aliases to the allowlist. By default the server also discovers exact Host entries from ~/.ssh/config and its Include files. Tool inputs accept only safe aliases โ not user@host, ports, or extra SSH options.
After editing ~/.ssh/config, call ssh_hosts(reload=true) instead of restarting the server.
Credential boundary
Authentication stays inside the local OpenSSH client:
Tools never accept passwords or private-key material
ssh_hosts never returns key paths, certs, agent sockets, or ProxyCommand
Agents should call ssh_open with a Host alias and must not read ~/.ssh private keys from disk
Environment variables override the file. The audit log is created with mode 0600 and records session, host, result, duration, command length, command name, and SHA-256 โ not full argument strings (reduces secret leakage).
Execution semantics
Detailed rules the agent (and you) should know:
Topic
Behavior
Concurrency
One session runs one foreground command at a time; extra ssh_run โ busy
wait_sec
Limits only how long the MCP call waits. On expiry: status: "running", remote work continues
Do not retry
Never re-issue the same long command after running โ poll with ssh_peek
Hard timeout
Only an explicit timeout_sec creates a deadline that sends Ctrl-C
ssh_peek
Default last 50 lines (max 1000); byte caps still apply; optional long-poll wait_sec
stdin
User commands get /dev/null โ no vim, top, or interactive installers
Interrupt recovery
Ctrl-C + grace period for protocol marker; if recovery fails โ session closed (fail-closed)
Blocks a few high-risk patterns only โ not a complete policy engine
Trust model
Local trusted developer tool โ not a multi-tenant remote execution service
Host exit
MCP host / stdio death closes all SSH connections; nohup / setsid jobs may survive
Example: start docker pull with wait_sec: 10 and no timeout_sec. A running result means the original pull is still active โ do not start another. Call ssh_peek with a positive wait_sec until idle, interrupt it, or open another session for parallel work.
Development
bash
npm run typecheck
npm test
npm run build
npm audit --omit=dev
The test suite covers MCP stdio discovery and calls, persistent cwd / environment state, stream separation, framing across arbitrary chunk boundaries, timeout fail-closed behavior, shell death, allowlist discovery, output truncation, and the safety denylist.
Please do not report security vulnerabilities through public GitHub issues. Until a private advisory workflow is configured, contact the maintainer via the email on their GitHub profile.
Remote commands can have irreversible side effects even when the MCP transport is healthy. Use least-privilege accounts, keep the allowlist narrow, and review host permissions carefully.