Remote SSH MCP
The Remote SSH MCP server provides persistent, stateful SSH sessions for AI agents, enabling long-lived remote shell operations with easy session management.
Key capabilities:
List allowed hosts (
ssh_hosts) – shows safe metadata for permitted Host aliases from SSH config.Open session (
ssh_open) – starts a persistent remote Bash shell for an allowed host, returning a session ID.Run commands (
ssh_run) – executes non-interactive commands in a session, preserving working directory and environment across calls; supports optional wait/timeout and is designed for long-running tasks (returns early withrunningstatus).Peek at output (
ssh_peek) – retrieves recent stdout/stderr and command status; long-polling waits for completion.Interrupt command (
ssh_interrupt) – sends Ctrl‑C to the foreground process, with recovery confirmation; session closed on failure.List sessions (
ssh_list) – shows active sessions with host, cwd, state, exit code, idle time, and capacity.Close session (
ssh_close) – terminates remote shell and SSH connection, cleans up temporary files.
Security & integration:
Enforces host allowlist and destructive-command denylist; idle reaping, output truncation, and audit logging.
Uses the system OpenSSH client, honoring
~/.ssh/config, agent forwarding, ProxyJump; never accepts passwords or keys from tools – credentials remain local.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Remote SSH MCPOpen a session to prod and run 'df -h'"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Why Remote SSH MCP?
Most agents reach remote machines like this:
bash → ssh host "cmd" → disconnect → repeatEvery call pays the same tax:
Pain | What happens |
🔁 Token waste | Banners, MOTD, login noise, and |
🧊 Lost state |
|
🔌 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.
Why pick this over one-shot ssh in bash?
Concrete gains for agent workflows (multi-step remote work: deploy, debug, build, inspect logs):
Dimension | One-shot | Remote SSH MCP |
💰 Tokens | Each step re-pays connect noise + state probes; models often re- | Pay once on |
✅ 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 |
🧳 Portability | Remote needs nothing extra — but every agent machine reimplements the same brittle | 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 ( |
🧠 Model ergonomics | Model invents | Stable tools: |
🔐 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.
┌─────────────────────────┐ SSH (OpenSSH) ┌──────────────────┐
│ Your laptop / CI agent │ ───────────────────────────► │ prod / staging │
│ Claude · Cursor · Grok │ ~/.ssh/config · agent │ no MCP install │
│ + remote-ssh-mcp │ │ plain Bash OK │
└─────────────────────────┘ └──────────────────┘Token sketch (illustrative multi-step remote debug):
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 transportIt 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.
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 connectionRelated MCP server: TerminusAI
Features
🧠 Persistent remote sessions
One stable session ID maps to one long-lived remote Bash
cwdand environment survive acrossssh_runcallsOpen 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
sshbinary — no custom crypto stackHonors
~/.ssh/config,Include, agent sockets, and ProxyJumpForces
BatchMode=yesandStrictHostKeyChecking=yesNever accepts passwords, private-key text, or arbitrary SSH option args from the model
📡 Long-running command friendly
ssh_runwaits up towait_sec(default 10s), then returnsstatus: "running"while the remote command continuesPoll with
ssh_peek(wait_sec=...)long-poll instead of busy-loopingOptional hard
timeout_secsends Ctrl-C; no automatic kill by defaultIdeal for
docker pull, builds, downloads, and deploys that must not block the tool call forever
🛡️ Safety & control plane
Exact Host-alias allowlist from
ssh_config+ optional config / env overridesPatterns with
*,?, or!are ignoredFail-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/stderrstreamsHead-and-tail byte truncation with valid UTF-8 boundaries
ANSI / PTY noise stripped before the model sees output (colors, CSI, bracketed-paste markers, control-only blank lines)
Quiet open-frame:
TERM=dumb,NO_COLOR, bracketed-paste off — less junk at the sourceSlim JSON payloads: omit empty
stderr,falsetruncation flags, and request-echo fields so dualcontent+structuredContentstays cheapssh_hostsreturns only safe metadata:alias,hostname,user,port,proxy_jumpNever leaks
IdentityFile, certificates, agent sockets, orProxyCommand
🔌 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
endTypical agent flow
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 doneMCP tools
Tool | What it does |
🗂️ | List allowed Host aliases (safe metadata only). Pass |
🔓 | Open a clean persistent shell for an allowed Host alias → returns session |
▶️ | Run a non-interactive command in an existing session |
👀 | Latest N lines of output + status; optional |
⛔ | Send Ctrl-C and wait for confirmed shell recovery |
📋 | List sessions, cwd, state, idle countdown, and capacity |
🔒 | Tear down remote temp state and close the connection |
Tool parameters (essentials)
Tool | Key params |
|
|
|
|
|
|
|
|
| optional |
Quick start
Requirements
Requirement | Notes |
Node.js | 20 or newer |
OpenSSH client | System |
Remote host | Bash + |
SSH setup | Host alias in |
⚠️ First-time host-key confirmation and authentication must be completed in a normal terminal. The MCP server never shows password or trust prompts.
Install
git clone https://github.com/the-nine-nation/remote-ssh-mcp.git
cd remote-ssh-mcp
npm install
npm run build
npm testRun the server:
node /absolute/path/to/remote-ssh-mcp/dist/index.jsOr install from npm (once published):
npx @zyluo/remote-ssh-mcp
# or
npm install -g @zyluo/remote-ssh-mcp
remote-ssh-mcpOr, after a local package install from this repo, use the remote-ssh-mcp executable.
MCP host configuration
Most stdio hosts accept a shape like this (outer key may differ by product):
{
"mcpServers": {
"remote-ssh": {
"command": "node",
"args": [
"/absolute/path/to/remote-ssh-mcp/dist/index.js"
],
"env": {
"SSH_MCP_ALLOWED_HOSTS": "prod,staging"
}
}
}
}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_HOSTS adds 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_hostsnever returns key paths, certs, agent sockets, orProxyCommandAgents should call
ssh_openwith a Host alias and must not read~/.sshprivate keys from disk
Configuration
Optional config file (default path):
~/.config/remote-ssh-mcp/config.json{
"allowedHosts": ["prod", "staging"],
"sshConfigPath": "~/.ssh/config",
"sshPath": "ssh",
"maxTimeoutSec": 1800,
"defaultWaitSec": 10,
"maxWaitSec": 30,
"openTimeoutSec": 20,
"idleTimeoutSec": 1800,
"interruptGraceSec": 5,
"maxSessions": 8,
"outputMaxBytes": 32768,
"outputHeadBytes": 4096,
"auditLogPath": "~/.local/state/remote-ssh-mcp/audit.jsonl"
}Environment variables
Variable | Purpose |
| Configuration file path |
| Comma-separated additional Host aliases |
| SSH config path |
| OpenSSH executable |
| Max explicit command timeout |
| How long |
| Max |
| Connect / handshake timeout |
| Idle session lifetime |
| Marker recovery grace after Ctrl-C |
| Maximum live sessions |
| Per-stream retained output limit |
| Retained head bytes when truncating |
| JSONL audit-log path |
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 |
| Limits only how long the MCP call waits. On expiry: |
Do not retry | Never re-issue the same long command after |
Hard timeout | Only an explicit |
| Default last 50 lines (max 1000); byte caps still apply; optional long-poll |
stdin | User commands get |
Interrupt recovery | Ctrl-C + grace period for protocol marker; if recovery fails → session closed (fail-closed) |
Output | stdout / stderr keep head + tail independently; always valid UTF-8 boundaries |
Denylist | 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; |
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
npm run typecheck
npm test
npm run build
npm audit --omit=devThe 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.
Design notes and wire protocol: 远程SSH-MCP设计.md.
Security
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.
Project status
Item | Status |
Version | 0.2.2 |
License | |
Language | TypeScript (Node ≥ 20) |
Protocol | MCP over stdio |
Transport to host | System OpenSSH |
Changelog
0.2.2 — quieter remote output, fewer tokens
PTY-backed interactive bash often injects escape sequences that look like “binary” when JSON-escaped (\u001b[?2004h, color CSI, cursor codes). That noise burned context on every ssh_peek / ssh_run.
Change | What it does |
Present-time sanitize | Strip ANSI/OSC/CSI, honor CR overwrite (progress bars), drop control-only blank lines, then apply the |
Quiet session open | Export |
Slim tool payloads | Drop empty |
Tests | Coverage for sanitize, open-frame quieting, session present path, and slim JSON |
Upgrade: npm i -g @zyluo/remote-ssh-mcp@0.2.2 (or bump the package in your MCP config), then restart the MCP process so the new server binary is loaded.
0.2.1
Fix READY-marker parsing when the open frame is PTY-echoed
0.2.0
Initial public release on npm / GitHub
Star History
If this project saves you tokens and flaky reconnects, a ⭐ on GitHub helps others find it.
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- Flicense-qualityCmaintenanceEnables AI assistants to securely execute shell commands on local machines through an SSH interface with session management, command execution, and sudo support.1
- AlicenseBqualityDmaintenanceExecute terminal commands locally or remotely via SSH with session persistence and environment variable support. Manage terminal sessions that maintain state for up to 20 minutes, enabling efficient command execution workflows. Connect using stdio or SSE for flexible integration with AI models and a12MIT
- Alicense-qualityDmaintenanceProvides LLM clients with safe, persistent SSH access to remote machines through the Model Context Protocol. Maintains shell sessions that preserve environment state between commands, enabling multi-step workflows and interactive diagnostics on remote systems.10216MIT
- Flicense-qualityCmaintenanceEnables AI assistants to run commands on remote SSH-accessible devices via persistent sessions, supporting both POSIX and CLI shells with safety filters.
Related MCP Connectors
Operate Linux, macOS and Windows from your LLM. Every action runs through an auditable allowlist.
Let AI operate servers without SSH. Choose actions, approve risky changes, and audit every step.
Persistent cloud development environments that coding agents create, run and test software in.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/the-nine-nation/remote-ssh-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server