Provides safe, persistent SSH access to remote machines with maintained shell sessions that preserve environment state, working directory, and process state across multiple commands
SSH MCP Server
A Model Context Protocol (MCP) server that gives LLM clients safe, persistent SSH access to remote machines.
Table of Contents
Overview
ssh-mcp
lets MCP-compatible clients (such as Claude Code, Cursor, or custom MCP inspectors) control remote machines through SSH. Once hosts are registered, the server maintains persistent shell sessions that retain environment state between commands—ideal for multi-step workflows, long-running processes, or interactive diagnostics.
The server is implemented in TypeScript on top of the official @modelcontextprotocol/sdk.
Key Features
MCP-compliant: exposes functionality through standard MCP tool definitions.
Persistent sessions: keep shell sessions alive, preserving working directory, environment variables, and process state across multiple commands.
Stored host profiles: manage SSH targets through durable JSON configuration (
~/.ssh-mcp/hosts.json
).Flexible authentication: supports passwords, private keys, and SSH agent forwarding (fallback).
Timeout & cleanup safeguards: sessions auto-close after prolonged inactivity; commands are marked and monitored for completion.
Structured listings: query active sessions and saved hosts directly from the MCP client.
Architecture
Each active session maintains:
SSH connection via
ssh2
Interactive shell (
conn.shell
) to support multi-command pipelinesBuffered output with unique UUID markers to detect command completion
Inactivity timer (defaults to 2 hours)
Installation
The build step compiles TypeScript into ./build/index.js
and marks it executable.
Running the Server
The server is purely stdio-based. Once running it prints:
You can register it with Claude Code or any other MCP client:
Note: The server no longer accepts CLI arguments for host/user/password. Everything is configured dynamically via MCP tools.
Host Configuration
Host Storage
Hosts are persisted in
~/.ssh-mcp/hosts.json
.The directory is created automatically if it does not exist.
File format:
Fields:
id
(string) — unique identifier used by all session commands.host
(string) — hostname or IP.port
(number, default 22) — SSH port.username
(string) — SSH user.password
(optional string) — password auth.keyPath
(optional string) — private key path; tilde expansion supported.If neither
password
norkeyPath
is provided, the server attempts to use the local SSH agent viaSSH_AUTH_SOCK
(with agent forwarding enabled).
The MCP tools ensure this file remains well-formed; never edit it manually unless you know what you’re doing.
Adding Hosts
Tool: add-host
host_id
: new identifier. Must be unique.host
: hostname or IP.port
: optional (defaults to 22); provide integer > 0.username
: SSH user.password
orkeyPath
: optional; configure one or rely on agent.
Example (Claude Code command palette or inspector):
Listing Hosts
Tool: list-hosts
Returns text with one host per line:
auth
values:
password
— password field presentkey
— keyPath presentagent
— neither password nor keyPath; agent fallback active
Editing Hosts
Tool: edit-host
Only supply the properties you want to change. Omitted fields remain unchanged; providing null
to a field is not supported—set an empty string or remove the host instead.
Removing Hosts
Tool: remove-host
Deletes the entry from hosts.json
. Active sessions using that host must be closed manually.
Session Management
Starting a Session
Tool: start-session
Optionally you can supply sessionId
; otherwise, a UUID is returned.
Example response:
Listing Sessions
Tool: list-sessions
Shows all active sessions with metadata:
Executing Commands
Tool: exec
Commands are sanitized (trimmed, length-limited).
Output is captured from the persistent shell and returned as plain text.
Non-zero exit codes raise
McpError
with stderr in the message.
Example output:
Closing Sessions
Tool: close-session
Note: session IDs for
close-session
usesessionId
(camelCase) to remain backwards compatible with the underlying tool definition.
Legacy Helper
Function execSshCommand(hostId, command, sessionId?)
remains exported for programmatic use and simply delegates through the session machinery described above.
Authentication Modes
Password — stored in
hosts.json
; transmitted tossh2
during connection.Private key —
keyPath
read at runtime; supports encrypted keys (prompt user to setSSH_MCP_KEY_PASSPHRASE
before launch if needed).SSH agent (fallback) — if neither password nor key is set and
SSH_AUTH_SOCK
is present, the agent is passed tossh2
(agentForward: true
).
Timeouts & Inactivity Handling
Each session has a global inactivity timeout (default 2 hours). Timer resets whenever a command executes successfully.
If the timer elapses, the session cleans up the SSH connection, shell, and resolver buffer, and removes itself from
activeSessions
.Command completion uses a UUID marker:
printf '__MCP_DONE__{uuid}%d\n' $?
. Output before the marker is returned; numeric code after the marker becomes the exit status.
Directory Structure
Using the MCP Tools
Below is a typical workflow using Claude Code (commands start with /mcp
), but the same JSON payloads apply to any MCP inspector.
Add host
/mcp mcp-remote-ssh add-host {"host_id":"host","host":"host.local","username":"user"}Start session
/mcp mcp-remote-ssh start-session {"host_id":"host"}→ returns
session_id
Run commands
/mcp mcp-remote-ssh exec {"session_id":"<id>","command":"pwd"} /mcp mcp-remote-ssh exec {"session_id":"<id>","command":"ls -la"}Inspect
/mcp mcp-remote-ssh list-sessions /mcp mcp-remote-ssh list-hostsClose session
/mcp mcp-remote-ssh close-session {"sessionId":"<id>"}
Testing
Unit tests (Vitest):
Integration smoke tests for SSH are not included by default because they require external infrastructure. You can manually validate with the workflow above.
Troubleshooting
Symptom | Possible Cause | Suggested Action |
| Duplicate
| Use
or pick a new ID. |
| Missing entry | Run
to confirm; add host again if needed. |
| Remote command returned non-zero | Inspect the command output. The session remains open. |
Session disappears from
| Inactivity timeout reached | Start a new session or reduce idle periods. |
Permission denied (publickey) | Missing credentials | Ensure
or agent has the right key. |
|
resolved to undefined or missing file | Provide an absolute/tilde path that exists. |
Security Considerations
Treat
~/.ssh-mcp/hosts.json
as sensitive; it may contain passwords or key paths.Prefer key-based or agent authentication where possible.
Limit
hosts.json
permissions:chmod 600 ~/.ssh-mcp/hosts.json
.Sessions inherit all privileges of the configured SSH user.
Long-running sessions can be closed manually or rely on the inactivity timeout.
Contributing
Fork the repo and create a branch.
Make your changes with tests and documentation updates.
Run
npm run build
andnpm run test
before submitting a PR.Follow the Code of Conduct.
Issues and feature requests are welcome via GitHub.
License
Happy automating! If this project improves your workflow, please star the repository or share feedback. Your contributions help make remote development safer and simpler for everyone.
This server cannot be installed
local-only server
The server can only run on the client's local machine because it depends on local resources.
Provides 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.