SSH MCP Server (Rust Implementation)
A high-performance Rust implementation of the SSH Model Context Protocol (MCP) server, optimized for DevOps workflows. This tool allows AI models to securely interact with remote Linux systems over SSH, providing tools for command execution, file operations, and administrative tasks.
✨ Features
- Persistent Connections: Maintains a single SSH session across multiple tool calls for maximum speed.
- Auto-Reconnect: Automatically restores the connection if it drops.
- Interactive Elevation: Supports
suelevation with PTY shell for full root access. - Sudo Integration: Provides a
sudo-exectool with password wrapping. - File Operations: Read, edit, and transfer files with atomic operations and optimistic locking.
- Smart File Reading: Preview mode prevents context overflow with token estimates and pagination.
- Atomic File Editing: Full replacement or partial text replacement with conflict detection.
- Command Sanitization: Built-in safety checks for command inputs.
- Output Control: Configurable output length limits to prevent token overflow.
- Cross-Platform: Compiled binary runs on any system with SSH access.
🛠 Installation
Pre-built Binaries (Recommended)
Download the latest rolling release for your platform from the Releases page.
| Platform | Download Link |
|---|---|
| Linux x86_64 | ssh-mcp-linux-x86_64 |
| Windows x86_64 | ssh-mcp-windows-x86_64.exe |
| macOS ARM64 | ssh-mcp-macos-aarch64 |
Quick install (Linux/macOS):
# Download and install
# Verify installation
Quick install (Windows PowerShell):
# Download
Invoke-WebRequest -Uri "https://github.com/0FL01/ssh-mcp-rs/releases/download/rolling/ssh-mcp-windows-x86_64.exe" -OutFile "ssh-mcp.exe"
# Add to PATH (choose a directory in your PATH or add current directory)
# Verify installation
.\ssh-mcp.exe --version
Build from Source
Prerequisites
- Rust toolchain (cargo, rustc)
pkg-configand OpenSSL headers (usuallylibssl-devon Ubuntu/Debian)
Build
⚙️ Configuration
The server is configured via CLI arguments or environment variables.
| Argument | Environment Variable | Description |
|---|---|---|
--host |
SSH_MCP_HOST |
SSH host (required) |
--user |
SSH_MCP_USER |
SSH username (required) |
--port |
SSH_MCP_PORT |
SSH port (default: 22) |
--password |
SSH_MCP_PASSWORD |
SSH password (alt to key) |
--key |
SSH_MCP_KEY |
Path to private key file |
--su-password |
SSH_MCP_SU_PASSWORD |
Password for su elevation |
--sudo-password |
SSH_MCP_SUDO_PASSWORD |
Password for sudo pipes |
--timeout |
SSH_MCP_TIMEOUT |
Command timeout in ms (default: 300000) |
--maxChars |
SSH_MCP_MAX_CHARS |
Command length limit (default: 64000, "none" to disable) |
--disable-sudo |
SSH_MCP_DISABLE_SUDO |
Disable the sudo-exec tool |
--max-output-tokens |
SSH_MCP_MAX_OUTPUT_TOKENS |
Output token limit for exec/read-file (default: 16000, ~64KB; "none" to disable) |
--log-level |
SSH_MCP_LOG_LEVEL |
Log level: trace, debug, info, warn, error (default: info) |
--log-file |
SSH_MCP_LOG_FILE |
Log file path (base name; daily/hourly adds date suffix) |
--log-format |
SSH_MCP_LOG_FORMAT |
Log file format: text, json (default: text) |
--log-rotation |
SSH_MCP_LOG_ROTATION |
Log rotation: daily, hourly, never (default: daily) |
--strict-host-key-checking |
SSH_MCP_STRICT_HOST_KEY_CHECKING |
Host key policy: accept-new (default), yes, or no |
--known-hosts |
SSH_MCP_KNOWN_HOSTS |
Custom known_hosts file path |
--keepalive-interval |
SSH_MCP_KEEPALIVE_INTERVAL |
Keepalive packet interval in seconds (default: 30) |
--keepalive-max |
SSH_MCP_KEEPALIVE_MAX |
Max keepalive failures before disconnect (default: 3) |
--reconnect-retries |
SSH_MCP_RECONNECT_RETRIES |
Reconnect retries after initial attempt (default: 3) |
--reconnect-backoff-ms |
SSH_MCP_RECONNECT_BACKOFF_MS |
Base reconnect backoff in ms (default: 250) |
--health-probe-timeout-ms |
SSH_MCP_HEALTH_PROBE_TIMEOUT_MS |
Health probe timeout in ms (default: 1500) |
Note: with --log-rotation=daily, the actual file will be /var/log/ssh-mcp/app.log.YYYY-MM-DD.
Use --log-rotation=never to write exactly to /var/log/ssh-mcp/app.log.
SSH Host Key Verification
ssh-mcp verifies the SSH server host key before authentication. This prevents silent man-in-the-middle replacement after a host key has been trusted.
accept-new(default): trust and record an unknown host key on first connection; reject later key changes.yes: require the host key to already exist inknown_hosts; reject unknown or changed keys.no: disable host key verification; use only for local test containers or other disposable environments.
A strict-production example using --strict-host-key-checking=yes with a pre-populated known_hosts file is shown in the Strict production configuration below.
🚀 Adding to MCP Clients
OpenCode
Add this to your opencode.jsonc:
With SSH key (recommended for best transfer performance):
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"ssh-remote": {
"type": "local",
"command": [
"/absolute/path/to/ssh-mcp",
"--host=192.168.1.10",
"--port=22",
"--user=agent-nc",
"--key=/path/to/private/key"
],
"enabled": true
}
}
}
With password (file transfer uses exec-raw transport):
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"ssh-remote": {
"type": "local",
"command": [
"/absolute/path/to/ssh-mcp",
"--host=192.168.1.10",
"--port=22",
"--user=agent-nc",
"--password=your-password"
],
"enabled": true
}
}
}
Add this to your project's .mcp.json (shared via git) or to ~/.claude.json under the top-level mcpServers key (user scope):
With SSH key (recommended for best transfer performance):
With password (file transfer uses exec-raw transport):
For strict production use, set --strict-host-key-checking=yes and point it at a pre-populated known_hosts file. The same flags work in any client config above; the OpenCode example is shown below:
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"ssh-remote": {
"type": "local",
"command": [
"/absolute/path/to/ssh-mcp",
"--host=example.com",
"--user=alice",
"--key=/home/alice/.ssh/id_ed25519",
"--strict-host-key-checking=yes",
"--known-hosts=/home/alice/.ssh/known_hosts"
],
"enabled": true
}
}
}
🛠 Tools
The server exposes the following MCP tools:
exec
Execute a command as the connected user via POSIX-compatible sh.
-
Arguments:
command(string, required): Command string evaluated by POSIX-compatiblesh; use portable shell syntax.background(boolean, default: false): If true, return immediately and continue streaming output to a local log on the MCP server. The job is tracked viajob_idin an in-memory registry and the response includes{job_id, pid, log_path}. Recommended for long-running operations to avoid client timeouts.timeout_ms(integer, optional): Override the default command timeout (ms) for foreground runs. If the foreground command exceeds this timeout, it auto-detaches to background and returns{ok:false, timeout:true, background:true, job_id, pid, log_path}. Whenbackground=true,timeout_msis ignored and NOT validated.log_path(string, optional): Custom local log path on the MCP server for background mode output. Defaults to/tmp/ssh-mcp/<job_id>.log. Whenbackground=false,log_pathis ignored and NOT validated.
-
Background response fields:
log_path(string): Local log path on the MCP server (e.g./tmp/ssh-mcp/<job_id>.log).remote_log_path(string, deprecated): Compatibility field for backward compatibility. Does NOT represent an actual remote log file in the current architecture. Output is streamed locally; uselog_pathfor local log access.
sudo-exec
Execute a command with root privileges using sudo via POSIX-compatible sh.
- Arguments:
command(string, required): Command string evaluated by POSIX-compatibleshunder sudo; use portable shell syntax.background(boolean, default: false): Same behavior asexec- return immediately and stream output to a local log.timeout_ms(integer, optional): Override timeout (ms) for foreground runs. If the foreground command exceeds this timeout on a detach-capable target, it auto-detaches to background and returns{ok:false, timeout:true, background:true, job_id, pid, log_path}. Whenbackground=true,timeout_msis ignored and NOT validated.log_path(string, optional): Custom local log path on the MCP server for background mode output. Whenbackground=false,log_pathis ignored and NOT validated.
- Note: This tool uses the
--sudo-passwordprovided at startup. For long-running sudo tasks, preferbackground=true; foreground timeouts also auto-detach on supported targets.
check-process
Check if a background job is still running and read the tail of its local log (stored on the MCP server).
- Arguments:
job_id(string, required): Job ID returned byexec/sudo-execwhenbackground=true, or byexecforeground timeout auto-detach.tail_lines(integer, default: 50): Number of last lines to read from the local log.
read-file
Read a remote file with smart preview to prevent context overflow.
-
Arguments:
remote_path(string, required): Absolute path to the remote file.mode(string, optional): Read mode -"preview","head","tail", or"full". Default:"preview".lines(integer, optional): Number of lines for preview/head/tail modes. Default: 800, Max: 10000.timeout_ms(integer, optional): Override timeout in milliseconds.
-
Modes:
preview(default): Returns first N lines (default 800) with token estimates and truncation hint. Prevents context bomb from large files.head: Returns first N lines from the beginning of the file.tail: Returns last N lines from the end of the file.full: Returns the entire file content (subject to 1MB size limit).
-
Response:
-
Safety Features:
- Returns error for files larger than 1MB (use
transferfor large files) - Rejects binary/non-UTF8 files with clear error
- Shows approximate token counts to help agents manage context budget
- Returns error for files larger than 1MB (use
Example - Preview first 800 lines:
Example - Get last 50 lines:
Example - Read entire file:
write-file
Atomically overwrite or create a remote file with conflict detection.
-
Arguments:
remote_path(string, required): Absolute path to the remote file.new_content(string, required): Complete new file content (UTF-8, max 1MB).expected_sha256(string, optional): 64-char hex SHA-256 hash for optimistic locking.read_ticket(string, conditionally required): Opaque token fromread-file. Required when editing an existing non-empty file. Not required for file creation or zero-byte files.
-
Response:
-
Error Responses:
conflict: File changed sinceexpected_sha256not_found: Parent directory doesn't existsha256_unavailable: Remote host lackssha256sum/shasumutilitiesinvalid_params: Missing/invalid/expired/wrong-pathread_ticket, or edit attempted on an existing non-empty file without callingread-filefirst
Example - Full replacement with optimistic lock (after calling read-file):
replace-in-file
Atomically replace text within an existing remote file with conflict detection.
-
Arguments:
remote_path(string, required): Absolute path to the remote file (must exist).old_text(string, required): Text to search for and replace.new_text(string, required): Replacement text.replace_all(boolean, default: false): If false and multiple matches are found, returns an error.expected_sha256(string, optional): Expected SHA-256 hash for optimistic locking.
-
Response:
-
Error Responses:
conflict: File changed since expected_sha256 (or baseline hash changed during replace)not_found: File doesn't existsha256_unavailable: Remote host lacks sha256sum/shasum utilitiesinvalid_params: Emptyold_textor invalid hash/timeout input
-
Safety Features:
- Atomic writes via staging + rename (never leaves partially written files)
- Lock directory prevents concurrent edits to same file
- Automatic rollback on failure
- Conflict detection prevents overwriting concurrent changes
replace-in-filealways pins to a read baseline SHA whenexpected_sha256is omitted
Example - Text replacement (single match):
Example - Replace all occurrences:
Workflow for editing without losing changes:
- Read file:
read-filewith mode"preview"or"full" - Capture
read_ticketfrom the read-file response (and optionallysha256) - Make local edits to content
- Apply changes with
write-fileandread_ticketfor full rewrites, or usereplace-in-filefor text substitutions - Optional: also send
expected_sha256for explicit optimistic locking - If conflict error: re-read file (it changed), merge changes, retry
transfer
Transfer a file or directory over SSH.
- Authentication: Supports both SSH key and password authentication. When using password auth, the
exec-rawtransport is used automatically. - Local root:
local_pathcan be relative tolocal_root(the server's current working directory at startup) or an absolute path withinlocal_root. Paths outsidelocal_root,..components, and paths that normalize to.are rejected. - Remote path validation:
remote_pathmust be non-empty, must not contain control characters, must not have leading/trailing whitespace, must not contain NUL, and must not start with-. - Transport:
transport=auto: attempts rsync (most efficient), then sftp, then scp, then falls back to exec-raw deterministically.transport=sftp/transport=scp: use local OpenSSH client binaries (sftp/scp).transport=exec-raw: uses streaming stdin/stdout over the existing SSH session (tar streaming for directories).transport=rsync: uses local rsync binary with SSH transport for efficient delta-sync transfers (requires --key).- Note:
sftp/scptransports require the server to be started with a private key path (--key=/path/to/key). When using password authentication, theexec-rawtransport is used automatically (streaming over the existing SSH session).
Directory transfer (tar)
- Directory transfers use a streamed POSIX
ustararchive. - Each tar header is validated (ustar magic/version + checksum). Invalid archives are rejected.
- Entry path rules:
- must be relative
- must be non-empty and must not normalize to
. - must not contain
..
- Supported entry types: regular files and directories only. Symlinks, device nodes, hardlinks, FIFOs, etc. are rejected.
- Remote requirements: the remote host must provide
tar(orbusybox tar) inPATH.
Overwrite semantics
-
overwrite=false(default - safer)put file: requires sibling staging and installs the final file via a hard-link (ln) to avoid replacement. This requires hard-link support on the remote filesystem; if unavailable the tool fails with an error suggesting to useoverwrite=true.get file: installs the final file via a local hard-link (fs::hard_link). This requires hard-link support on the local filesystem; if unavailable the tool fails with an error suggesting to useoverwrite=true.put dir: fails if the destination exists with a clear error message; useoverwrite=trueto replace existing directories.get dir: fails if the destination exists with a clear error message; useoverwrite=trueto replace existing directories.
-
overwrite=true(explicit opt-in for replacement)put file: stream to a staging file andmvinto place.get file: stream to a local staging file andrenameinto place (best-effort replacement on platforms where rename does not replace).put dir: extract a streamed tar into a staging directory, thenmvinto place; if the destination existed it may be moved to a backup path during the swap.get dir: extract a streamed tar into a local staging directory, then swap into place via rename; if the destination existed it is first renamed to a sibling backup path.
Staging behavior (no /tmp)
- Remote staging prefers a sibling path under the destination parent for better atomicity.
- If that location is not writable,
overwrite=trueoperations fall back to$HOME/.ssh-mcp/staging/<id>/...and then move into place. - For
overwrite=falsefile transfers, fallback staging is not allowed because the finalize step requires a sibling hard-link install; the tool fails if sibling staging is not writable.
Rsync Options
When using transport=rsync, you can customize behavior via rsync_options:
checksum(boolean, default: true): Use checksums instead of file times/sizes for file comparisoncompress(boolean, default: false): Compress data during transferdelete(boolean, default: false): Delete files on destination that don't exist on sourceinplace(boolean, default: true): Update files in-place instead of creating new filespartial(boolean, default: true): Keep partially transferred files for resumebwlimit(integer, optional): Bandwidth limit in KB/s
Monitoring Background Jobs
When using background=true or when a command auto-detaches on timeout:
- The response includes
{job_id, pid, log_path}and ahintfield with monitoring guidance.log_pathis local to the MCP server (default:/tmp/ssh-mcp/<job_id>.log).remote_log_pathmay still be present for backward compatibility but is deprecated; it is compat-only and does not represent a remote log file.
Log Path Restrictions
When providing a custom log_path:
- Must be an absolute path
- Must be directly under
/tmp/ssh-mcp/(no subdirectories) - Invalid custom paths return a tool JSON error rather than an MCP protocol error
- Must have
.logextension - Cannot contain
.or..components - Must not have leading/trailing whitespace
- Must not start with
- - Must not contain control characters (including
\n/\r) - Example:
/tmp/ssh-mcp/my-job.log
Example response:
- Recommended approach: Sleep between checks instead of tight polling.
- Start with 2-5s intervals, then use 10-30s for longer-running jobs.
- To check the status/output of a background job, use the
check-processtool with thejob_id:
Or, if you want to run commands on the target host:
When to Use Background Mode
Typical long-running tasks:
- Database exports/imports (
mysqldump,pg_dump,pg_restore) - Large file transfers (
rsync,scp) - Build processes (
cargo build,make,npm install) - Container operations (
docker build,docker compose up) - System maintenance (
apt update,yum update, log rotation)
Agent workflow:
- Start command with
background=trueor let it auto-detach on timeout - Get
{job_id, pid, log_path}immediately - Sleep 2-5s, then check status/output with
check-processusingjob_id - For long jobs, increase interval to 10-30s
5. Confirm completion when
check-processreportsrunning=falseand anexit_code
When using --log-rotation=daily, log files are suffixed with the date: <log_file>.YYYY-MM-DD (in the same directory as --log-file).
📝 JSON Log Format
When --log-file is specified with --log-format=json, logs are written in structured JSON format:
Use jq for pretty printing:
# Daily rotation writes to a date-suffixed filename
|
# Or disable rotation for a stable filename
# tail -f /var/log/ssh-mcp/app.log | jq
🔒 Security
- Stdio Transport: Communicates using JSON-RPC over stdin/stdout, ensuring no exposed ports.
- Credential Storage: Passwords and keys are only kept in memory and never logged.
- Logging: All internal logs are sent to
stderrto avoid interfering with the MCP protocol. - File Editing Safety: Atomic staging with automatic cleanup, lock directories prevent concurrent edits, conflict detection prevents silent overwrites.
- Path Validation: All paths validated for control characters, traversal attempts (
..), and shell injection. - Binary File Protection: Text-based tools reject non-UTF8 content to prevent data corruption.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.