Skip to main content
Glama
ssh-remote-mcp
by wcbup
README.md
# ssh-remote-mcp

[![CI](https://github.com/wcbup/ssh-remote-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/wcbup/ssh-remote-mcp/actions/workflows/ci.yml)
[![npm version](https://img.shields.io/npm/v/ssh-remote-mcp.svg)](https://www.npmjs.com/package/ssh-remote-mcp)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)

Production-grade SSH MCP server for coding agents (**Antigravity**, **Claude Code**, **Cursor**, etc.).

Connects your coding agent to multiple remote **Linux/Unix** (Bash, Zsh, POSIX `sh`, Alpine, BusyBox, OpenWrt) and **Windows** (PowerShell 7 / Windows PowerShell 5.1) servers over persistent SSH connections, without leaking file contents or secrets into the LLM context.

## Key Features

- **Multi-host connection pool**: Explicit `target` on every tool call (safe under parallel tool calls, zero hidden-host drift) with automatic idle cleanup.
- **Zero hidden `cwd` state**: File tools require explicit absolute or `~` paths; `ssh_exec` and `ssh_bg_start` require explicit `cwd` (use `"~"` for system-wide commands) and abort cleanly if `cwd` does not exist.
- **Production file safety**: Atomic same-directory temp-file writes, `overwrite: false` by default, CRLF/LF & permission preservation, `ssh_edit` with `expected_sha256` optimistic lock and `dry_run` unified diff preview, binary detection, and remote line-range slicing for large files (>2 MiB).
- **High-throughput SFTP upload / download**: Direct local disk ↔ remote disk transfers (never touches LLM context) using pipelined `ssh2` `fastPut` / `fastGet` (32 concurrent 32 KiB chunks), 60-second inactivity/stall watchdog (no arbitrary wall-clock cap on healthy large transfers), MCP `notifications/progress` streaming, clean `AbortSignal` cancellation with temp-file cleanup, automatic SSH pipe fallback for hosts without `sftp-server`, recursive directories with `exclude`, path-traversal protection, and SHA-256 verification.
- **Dual transport engine**: Persistent `ssh2` primary (resolving `~/.ssh/config` via `ssh -G`, multi-hop `ProxyJump`, strict `known_hosts`, OpenSSH Agent, encrypted key passphrases, and local password credentials) with automatic OpenSSH CLI fallback for `ProxyCommand`, `CertificateFile`, hardware keys, etc.
- **Detached remote background jobs**: Survive SSH disconnects (`setsid` on Unix, hidden detached PowerShell on Windows), support incremental log tailing (`byte_offset`), and terminate the full remote process group / process tree cleanly.
- **Zero-LLM-secret policy, error diagnostics & audit log**: Passwords and passphrases live strictly in local config/env vars (never in MCP tool parameters), optional per-host `readOnly: true` / `allowHosts` / `denyHosts`, structured error categories (`VALIDATION_ERROR`, `POLICY_BLOCKED`, `CONFLICT`, `AUTH_OR_HOSTKEY_ERROR`, `TRANSPORT_LOST_IN_FLIGHT`, `REMOTE_ERROR`, `MCP_INTERNAL_ERROR`) with `req-xxxxxx` correlation IDs, safe single-retry pre-flight reconnect on stale half-open sockets, and rotating redacted JSONL audit logs (10 MiB rotation).

---

## Requirements

- **Node.js >= 20**
- System **OpenSSH client** (`ssh` / `ssh.exe` and `ssh-keygen`) on `PATH`

---

## Quick Start

### Antigravity (`~/.gemini/config/mcp_config.json`)

```json
{
  "mcpServers": {
    "ssh-remote": {
      "command": "npx",
      "args": ["-y", "ssh-remote-mcp"],
      "timeoutSeconds": -1
    }
  }
}
```

> **Why `"timeoutSeconds": -1`?** Antigravity's default 180s MCP tool timeout can cut off healthy long-running commands (`ssh_exec` supports up to 600s) or large SFTP transfers. Every tool in `ssh-remote-mcp` enforces its own strict server-side timeout (or 60s stall watchdog for SFTP transfers), so setting `timeoutSeconds: -1` lets large transfers finish while hung operations still abort cleanly.

### Claude Code

```bash
claude mcp add ssh-remote -- npx -y ssh-remote-mcp
```

Or add to `.mcp.json`:

```json
{
  "mcpServers": {
    "ssh-remote": {
      "command": "npx",
      "args": ["-y", "ssh-remote-mcp"]
    }
  }
}
```

### Cursor (`.cursor/mcp.json`)

```json
{
  "mcpServers": {
    "ssh-remote": {
      "command": "npx",
      "args": ["-y", "ssh-remote-mcp"]
    }
  }
}
```

### Build from Source

```bash
git clone https://github.com/wcbup/ssh-remote-mcp.git
cd ssh-remote-mcp
npm install
npm run build
npm test
```

Then point your MCP client to the compiled entry point:

```json
{
  "mcpServers": {
    "ssh-remote": {
      "command": "node",
      "args": ["/path/to/ssh-remote-mcp/dist/index.js"]
    }
  }
}
```

---

## Authentication & Host Policy

### 1. Zero-config with `~/.ssh/config` + SSH Keys / Agent

Any host alias configured in `~/.ssh/config` (including `Include`, `Match`, `Port`, `IdentityFile`, `ProxyJump`) works out of the box. On Windows, the OpenSSH Authentication Agent (`\\.\pipe\openssh-ssh-agent`) is used automatically when running.

> **Host key verification is strict by default.** Before connecting to a new server, connect once manually with `ssh <target>` to verify its fingerprint and record it in `known_hosts`.

### 2. Passwords, Encrypted Key Passphrases & Production Guardrails (`hosts.json` / `secrets.json`)

Default config location:
- **Linux / macOS**: `~/.config/ssh-remote-mcp/hosts.json`
- **Windows**: `%USERPROFILE%\.config\ssh-remote-mcp\hosts.json`

Override with `SSH_REMOTE_MCP_CONFIG`. See [hosts.example.json](./hosts.example.json) for a starter template:

```json
{
  "defaultSshConfig": "~/.ssh/config",
  "defaultTransport": "auto",
  "idleTimeoutSeconds": 900,
  "auditLogPath": "~/.config/ssh-remote-mcp/audit.jsonl",
  "allowHosts": [],
  "denyHosts": [],
  "hosts": {
    "prod-db": {
      "description": "Production PostgreSQL primary (read-only inspection)",
      "readOnly": true,
      "transport": "ssh2"
    },
    "legacy-box": {
      "description": "Password-authenticated appliance",
      "password": "env:LEGACY_BOX_SSH_PASS"
    },
    "cf-tunnel-host": {
      "description": "Uses ProxyCommand cloudflared",
      "transport": "openssh"
    }
  }
}
```

Optional separate `secrets.json` (same directory, override with `SSH_REMOTE_MCP_SECRETS`; on Linux/macOS must be `chmod 600`):

```json
{
  "hosts": {
    "deploy@10.0.0.5:2201": {
      "password": "env:DEPLOY_SSH_PASS",
      "passphrase": "env:DEPLOY_KEY_PASSPHRASE"
    }
  }
}
```

You can also pass credentials purely via environment variables using the naming convention:
- `SSH_REMOTE_MCP_PASSWORD_<ALIAS>` (e.g. `SSH_REMOTE_MCP_PASSWORD_LEGACY_BOX`)
- `SSH_REMOTE_MCP_PASSPHRASE_<ALIAS>`

**Passwords and passphrases are never accepted as MCP tool arguments and are automatically redacted from error messages and audit logs.**

### Environment Variables

| Variable | Purpose |
|---|---|
| `SSH_REMOTE_MCP_CONFIG` | Custom path to `hosts.json` |
| `SSH_REMOTE_MCP_SECRETS` | Custom path to `secrets.json` |
| `SSH_REMOTE_MCP_SSH_CONFIG` | Override default OpenSSH config file (`-F`) |
| `SSH_REMOTE_MCP_AUDIT_LOG` | Custom audit JSONL path, or `off` to disable |
| `SSH_REMOTE_MCP_DEBUG` | Set to `1` to print diagnostic lifecycle logs to `stderr` |

---

## Tool Reference (15 Tools)

| Group | Tool | Summary |
|---|---|---|
| **Connection** | `ssh_hosts` | List `~/.ssh/config` aliases, local host policies, and active pooled connections |
| | `ssh_connect` | Explicitly connect, reconnect, or health-probe a target |
| | `ssh_disconnect` | Close one target's pooled connection or all connections |
| **Files** | `ssh_read` | Read remote text file with line numbers, EOL, SHA-256 (slices files >2 MiB remotely; rejects binary) |
| | `ssh_write` | Atomic temp-file write (`overwrite: false` default) |
| | `ssh_edit` | Exact-match multi-edit with `expected_sha256` optimistic lock, `dry_run` diff preview, EOL & mode preservation |
| **Search** | `ssh_ls` | List remote directory entries with type, size, mode, and mtime |
| | `ssh_find` | Find remote files by glob (excludes `.git` and `node_modules`; prefers `rg` on Unix) |
| | `ssh_grep` | Regex/literal content search across remote files (prefers `rg` on Unix) |
| **Shell** | `ssh_exec` | Synchronous remote command execution; requires explicit `cwd` (or `"~"`); kills remote process tree on timeout/cancel |
| **Transfer** | `ssh_upload` | Pipelined SFTP upload (with pipe fallback, 60s stall watchdog, progress notifications, `overwrite: false` default, SHA-256 verify) |
| | `ssh_download` | Pipelined SFTP download (path-traversal safe, 60s stall watchdog, progress notifications, `overwrite: false` default, SHA-256 verify, allowed on `readOnly` hosts) |
| **Background** | `ssh_bg_start` | Start detached remote job (`cwd` required); survives SSH disconnects |
| | `ssh_bg_status` | List jobs or inspect live status, exit code, and tail/incremental logs (`byte_offset`) |
| | `ssh_bg_kill` | Signal remote process group (Unix) or validated process tree (Windows `taskkill /T /F`) and clean up |

---

## Acknowledgments

Special thanks to **[@99percentpeople](https://github.com/99percentpeople)** and **[@99percentpeople/pi-ssh-remote](https://github.com/99percentpeople/pi-extensions#ssh-remote)** (MIT License). Portions of this project's `ssh2` / OpenSSH dual-transport architecture, `ssh -G` config and `ProxyJump` resolution, strict `known_hosts` verification, and remote Unix/Windows shell adapter patterns were adapted from or inspired by `pi-ssh-remote`.

---

## License

[MIT](./LICENSE) © 2026 wcbup

TDQS

A3.9/5.0

Scored across 15 tools

Disambiguation4/5

Most tools target clearly distinct resource+action pairs (read vs grep vs find, connect vs disconnect, bg_start vs bg_status vs bg_kill). The only mild overlaps are ssh_read vs ssh_download (text vs binary/streaming) and ssh_write vs ssh_upload (content vs streaming), but the descriptions explicitly disambiguate these ('binary rejected, use ssh_download', 'without passing bytes through LLM context').

Naming Consistency5/5

Every tool follows the ssh_ prefix + verb_noun pattern in consistent snake_case, including the grouped ssh_bg_start/ssh_bg_status/ssh_bg_kill family. No mixing of conventions.

Tool Count5/5

15 tools is a well-scoped set that maps cleanly onto the domain's facets: connection management, file I/O, search, exec, and background jobs. Each tool earns its place with no obvious redundancy.

Completeness4/5

File read/write/edit/list/find/grep/upload/download, exec, connection lifecycle, and full background-job lifecycle are covered. The main gap is a dedicated delete/move/mkdir operation, though these are workable via ssh_exec (rm/mv/mkdir).