Skip to content
Back to search

ssh-mcp

MCP server exposing SSH control for Linux servers via Model Context Protocol.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/tufantunc/ssh-mcp with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/tufantunc/ssh-mcp'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/tufantunc--ssh-mcp/badge.svg)](/listings/tufantunc--ssh-mcp)

HTML

<a href="/listings/tufantunc--ssh-mcp"><img src="/api/listings/tufantunc--ssh-mcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

1. Install

npm install -g ssh-mcp

2. Configure

Without a config the server still starts, so a client or directory can complete the MCP handshake and read `tools/list` — but **every tool call is refused** until you configure it, with a message naming the path below. Nothing runs on a host until this step is done.

Create the config file at the path for your platform:

| Platform | Path | |---|---| | Linux | `~/.config/ssh-mcp/config.toml` (or `$XDG_CONFIG_HOME/ssh-mcp/config.toml`) | | macOS | `~/Library/Application Support/ssh-mcp/config.toml` | | Windows | `%APPDATA%\ssh-mcp\config.toml` |

[defaults]
defaultProfile = "dev"
approvalMode = "ask-destructive"

[[profiles]]
name = "dev"
host = "192.168.1.100"
port = 22
user = "deploy"           # NOT root!
auth = "key"
keyRef = "~/.ssh/id_ed25519"
role = "admin"
approvalPolicy = "auto"    # dev is permissive
chmod 700 ~/.config/ssh-mcp && chmod 600 ~/.config/ssh-mcp/config.toml

The config decides which hosts, roles and policy rules this server honours, so it checks that nobody but you can read it — and treats the two platforms differently, because the question has a much clearer answer on one of them.

**Linux and macOS: enforced.** The mode check above, on the file *and* the directory — which is why `chmod 700` is in that command, since `mkdir -p` under the default umask leaves the directory 0755. The server refuses to start otherwise. "Only the owner" is unambiguous here and `chmod` is a one-line fix.

**Windows: split by what the ACL actually allows.** There are no mode bits, so the ACL is read instead — and read exposure and write exposure are not treated alike, because Windows is much clearer about one of them than the other.

| The ACL lets another account… | Default | |---|---| | only **read** the config | reported, and the server starts | | **change** the config | refused | | nothing (no ACL at all) | refused — that is full control for everyone | | …and if the ACL could not be read | refused, except when `icacls` is absent or the check timed out |

A config under `%APPDATA%` inherits access for you, `SYSTEM` and `Administrators` and needs nothing done to it. One created elsewhere does not: a file under `C:\` inherits *read* for every local account and *modify* for every authenticated one. The message names the two `icacls` commands that fix it either way.

Read exposure is reported rather than refused because that is where Windows is genuinely muddier than POSIX, and refusing over it blocked a config at the documented location ([#138](https://github.com/tufantunc/ssh-mcp/issues/138)). Write exposure is refused because it is not muddy at all: another account being able to rewrite the file that decides which hosts, roles and approval policy this server honours is an authorization bypass, not a disclosure.

Two flags move the whole thing: `--strictConfigAcl` refuses everything the check objects to, read-only grants included; `--allowUncheckedConfigAcl` reports everything and refuses nothing. Neither combination leaves you without an exit, which is the lesson of #138.

Exit statuses

| Status | Meaning | |---|---| | `0` | Clean shutdown | | `1` | A defect in the server — printed with a stack trace; please report it | | `2` | How it was invoked or configured — printed as a message, no stack |

A supervisor that treats any non-zero status as a failure needs no change. One that matched on `1` to detect a startup problem should match on `2` as well.

Starting with nothing configured is **not** an exit-2 condition, as of the release that added introspection without a config: the server starts so it can be described, and refuses each tool call instead. A supervisor that used a non-zero exit to catch an unconfigured deployment should watch for `starting unconfigured` on stderr, or read `configured` from `GET /health` when running the HTTP transport.

3. Set credentials via environment variables

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,211 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # SSH MCP Server v2
  2. [![NPM Version](https://img.shields.io/npm/v/ssh-mcp)](https://www.npmjs.com/package/ssh-mcp)
  3. [![Downloads](https://img.shields.io/npm/dm/ssh-mcp)](https://www.npmjs.com/package/ssh-mcp)
  4. [![CI](https://github.com/tufantunc/ssh-mcp/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/tufantunc/ssh-mcp/actions/workflows/ci.yml)
  5. [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/tufantunc/ssh-mcp/badge)](https://scorecard.dev/viewer/?uri=github.com/tufantunc/ssh-mcp)
  6. [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/15082/badge)](https://www.bestpractices.dev/projects/15082)
  7. [![codecov](https://codecov.io/gh/tufantunc/ssh-mcp/graph/badge.svg?branch=main)](https://codecov.io/gh/tufantunc/ssh-mcp)
  8. [![License](https://img.shields.io/github/license/tufantunc/ssh-mcp)](./LICENSE)
  9. [![GitHub issues](https://img.shields.io/github/issues/tufantunc/ssh-mcp)](https://github.com/tufantunc/ssh-mcp/issues)
  10. **SSH MCP Server** is a security-first Model Context Protocol server that gives LLM agents controlled SSH access to remote hosts — with command classification, policy-based authorization, human-in-the-loop approval, and full audit logging.
  11. > **The risk this server exists to manage.** Giving an LLM shell access on a remote host puts private data, untrusted input and network egress in one place — Simon Willison's ["lethal trifecta"](https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/). Prompt injection has no general fix, so ssh-mcp assumes any command may be attacker-influenced: it classifies before executing, authorizes against a role × host-group matrix, gates destructive work behind approval, and records the decision either way. That narrows the blast radius; it does not remove the risk. Two things stay yours: **never point it at a root account**, and **never set `auto` approval on a production profile**. [SECURITY.md](./SECURITY.md) has the full threat model.
  12. ---
  13. ## Quick Start
  14. ### 1. Install
  15. ```bash
  16. npm install -g ssh-mcp
  17. ```
  18. ### 2. Configure
  19. Without a config the server still starts, so a client or directory can complete the MCP
  20. handshake and read `tools/list` — but **every tool call is refused** until you configure it,
  21. with a message naming the path below. Nothing runs on a host until this step is done. The
  22. one exception is `reload-config`: write the file, then call it with `action: "reload"` (or
  23. restart the server) to configure a server that is already running — see
  24. [Reloading](#reloading).
  25. Create the config file at the path for your platform:
  26. | Platform | Path |
  27. |---|---|
  28. | Linux | `~/.config/ssh-mcp/config.toml` (or `$XDG_CONFIG_HOME/ssh-mcp/config.toml`) |
  29. | macOS | `~/Library/Application Support/ssh-mcp/config.toml` |
  30. | Windows | `%APPDATA%\ssh-mcp\config.toml` |
  31. ```toml
  32. [defaults]
  33. defaultProfile = "dev"
  34. approvalMode = "ask-destructive"
  35. [[profiles]]
  36. name = "dev"
  37. host = "192.168.1.100"
  38. port = 22
  39. user = "deploy" # NOT root!
  40. auth = "key"
  41. keyRef = "~/.ssh/id_ed25519"
  42. role = "admin"
  43. approvalPolicy = "auto" # dev is permissive
  44. ```
  45. ```bash
  46. chmod 700 ~/.config/ssh-mcp && chmod 600 ~/.config/ssh-mcp/config.toml
  47. ```
  48. The config decides which hosts, roles and policy rules this server honours, so it checks
  49. that nobody but you can read it — and treats the two platforms differently, because the
  50. question has a much clearer answer on one of them.
  51. **Linux and macOS: enforced.** The mode check above, on the file *and* the directory —
  52. which is why `chmod 700` is in that command, since `mkdir -p` under the default umask
  53. leaves the directory 0755. The server refuses to start otherwise. "Only the owner" is
  54. unambiguous here and `chmod` is a one-line fix.
  55. **Windows: split by what the ACL actually allows.** There are no mode bits, so the ACL is
  56. read instead — and read exposure and write exposure are not treated alike, because Windows
  57. is much clearer about one of them than the other.
  58. | The ACL lets another account… | Default |
  59. |---|---|
  60. | only **read** the config | reported, and the server starts |
  61. | **change** the config | refused |
  62. | nothing (no ACL at all) | refused — that is full control for everyone |
  63. | …and if the ACL could not be read | refused, except when `icacls` is absent or the check timed out |
  64. A config under `%APPDATA%` inherits access for you, `SYSTEM` and `Administrators` and needs
  65. nothing done to it. One created elsewhere does not: a file under `C:\` inherits *read* for
  66. every local account and *modify* for every authenticated one. The message names the two
  67. `icacls` commands that fix it either way.
  68. Read exposure is reported rather than refused because that is where Windows is genuinely
  69. muddier than POSIX, and refusing over it blocked a config at the documented location
  70. ([#138](https://github.com/tufantunc/ssh-mcp/issues/138)). Write exposure is refused
  71. because it is not muddy at all: another account being able to rewrite the file that decides
  72. which hosts, roles and approval policy this server honours is an authorization bypass, not
  73. a disclosure.
  74. Two flags move the whole thing: `--strictConfigAcl` refuses everything the check objects
  75. to, read-only grants included; `--allowUncheckedConfigAcl` reports everything and refuses
  76. nothing. Neither combination leaves you without an exit, which is the lesson of #138.
  77. ### Exit statuses
  78. | Status | Meaning |
  79. |---|---|
  80. | `0` | Clean shutdown |
  81. | `1` | A defect in the server — printed with a stack trace; please report it |
  82. | `2` | How it was invoked or configured — printed as a message, no stack |
  83. A supervisor that treats any non-zero status as a failure needs no change. One
  84. that matched on `1` to detect a startup problem should match on `2` as well.
  85. Starting with nothing configured is **not** an exit-2 condition, as of the release that
  86. added introspection without a config: the server starts so it can be described, and
  87. refuses each tool call instead, except `reload-config`. A supervisor that used a non-zero
  88. exit to catch an unconfigured deployment should watch for `starting unconfigured` on
  89. stderr, or read `configured` from `GET /health` when running the HTTP transport.
  90. ### 3. Set credentials via environment variables
  91. ```bash
  92. export SSH_MCP_PASSWORD="your-password" # if using auth=password
  93. # OR use SSH agent (recommended):
  94. export SSH_AUTH_SOCK="$SSH_AUTH_SOCK" # already set if agent running
  95. ```
  96. ### 4. Connect from your MCP client
  97. **Claude Code:**
  98. ```bash
  99. claude mcp add --transport stdio ssh-mcp -- ssh-mcp
  100. ```
  101. **Claude Desktop / Cursor / Windsurf:**
  102. ```json
  103. {
  104. "mcpServers": {
  105. "ssh-mcp": {
  106. "command": "ssh-mcp",
  107. "env": {
  108. "SSH_MCP_PASSWORD": "your-password"
  109. }
  110. }
  111. }
  112. }
  113. ```
  114. **Never pass passwords as CLI arguments** — they're visible via `ps aux`. Use env vars, config files, SSH agent, or OS keychain.
  115. ---
  116. ## Tools (15)
  117. | Tool | Purpose | readOnly | destructive |
  118. |------|---------|:--------:|:----------:|
  119. | `list-connections` | Discover available hosts and connection status | ✅ | — |
  120. | `list-sessions` | List active sessions per host | ✅ | — |
  121. | `open-session` | Create a named interactive (stateful) or background session (`ttlMs` sets that session's idle timeout: it may shorten the profile's, and lengthen it only up to `sessionBackgroundMaxMs` for a background session (the profile's own when that is `0`); `0` = never idle-expire is the profile's to set, not the call's) | — | — |
  122. | `close-session` | Close a session. A background session's command is signalled (INT/TERM/KILL) before its channel is dropped | — | ✅ |
  123. | `read-session-output` | Read output from background sessions (e.g., `tail -f`) | ✅ | — |
  124. | `read-command` | Execute allowlisted read-only commands (`ls`, `cat`, `grep`, ...) | ✅ | — |
  125. | `run-command` | Execute arbitrary commands (destructive/privileged need approval, unless `approvalPolicy = "auto"`) | — | — |
  126. | `privileged-command` | Execute with sudo (needs approval, unless `approvalPolicy = "auto"`) | — | ✅ |
  127. | `sftp-upload` | Upload a file via SFTP (replaces the destination unconditionally) | — | ✅ |
  128. | `sftp-download` | Download a file via SFTP | ✅ | — |
  129. | `sftp-list` | List a remote directory, bounded in entries and bytes | ✅ | — |
  130. | `sftp-upload-file` | Stream a local file to the remote host, never through model context | — | ✅ |
  131. | `sftp-download-file` | Stream a remote file to local disk, never through model context | — | ✅ |
  132. | `signal-process` | Send INT/TERM/KILL to a remote PID | — | ✅ |
  133. | `reload-config` | Show the config file's status, or re-read and apply it without a restart (see [Reloading](#reloading)) | — | ✅ |
  134. ### Streaming file transfer
  135. `sftp-upload`/`sftp-download` move file *contents* through the model's context:
  136. the text is an argument on the way out and a response on the way back. That is
  137. what you want for a config snippet and exactly what you do not want for a 200 MB
  138. tarball or anything binary.
  139. The two also differ on what they do to an existing destination, and the approved
  140. string now says which is which. `sftp-upload` replaces unconditionally and spells
  141. `--overwrite` every time, because that is what it always does; `sftp-upload-file`
  142. refuses unless you pass `overwrite: true`, and only then carries the flag. Since
  143. `sftp-upload` takes its content as an argument rather than naming a local file,
  144. its string also carries `--bytes=<n> --sha256=<32 hex>` — without that, two
  145. uploads to the same path are the same string, which means one approval covers
  146. both and an auditor cannot tell which set of bytes landed. The digest is 128
  147. bits rather than a short prefix because that claim has to hold against a caller
  148. who picks both payloads, not only against an accidental repeat.
  149. `[policy].denylist` patterns are tested against that whole string and, for every
  150. SFTP tool, against the remote path on its own — as given, lexically normalized,
  151. and read the way Windows reads it (see "Policy Engine"). A rule written for the
  152. path, such as `authorized_keys$`, therefore does not depend on where the string
  153. puts it or on how the file is spelled. A rule anchored on the *whole* string
  154. (`^sftp:upload /root/.*$`) still does: that layout is ours to change, so anchor
  155. on the path instead.
  156. `sftp-upload-file` and `sftp-download-file` stream between the remote host and
  157. local disk instead. Neither the bytes nor a base64 encoding of them ever reaches
  158. the model — the response is a byte count and two paths.
  159. The two transfer tools are **off until you configure `defaults.transferRoot`**,
  160. and refuse with an explanation until then. (`sftp-list` has no local side and
  161. needs none of this.) That directory is the whole of their local reach:
  162. ```toml
  163. [defaults]
  164. transferRoot = "/srv/ssh-mcp-transfers"
  165. transferMaxBytes = 268435456 # 256MB per transfer
  166. transferTimeoutMs = 300000 # 5min with no bytes moving
  167. ```
  168. Checked on every call, and refused rather than degraded if any of it fails: the
  169. directory must be `0700` and owned by the account running this server, with no
  170. group- or world-writable parent, and must not overlap the ssh-mcp installation,
  171. the config directory, the audit log directory, or `~/.ssh`. Caller paths are
  172. confined to it, symlinks are refused rather than followed, and a download is
  173. staged as a sibling `.part` file and published atomically, so a failed transfer
  174. never leaves a half-written file at the destination.
  175. `transferTimeoutMs` is an **idle** budget, not a total one: it bounds one
  176. metadata round-trip, or one stretch of the copy with no bytes moving, and is
  177. re-armed on progress. A slow but live transfer of a large file survives it; a
  178. stalled channel still fails within one window. That is why the byte cap above
  179. does not have to be divided by it — a total budget would have made a 256MB cap
  180. mean "only if the link sustains 900 KB/s".
  181. Not available on Windows, where the transfer root cannot yet be verified
  182. private; the two transfer tools refuse there rather than writing into a
  183. directory other accounts may be able to read.
  184. `sftp-upload-file` takes an optional `mode` (1–511; setuid, setgid and the
  185. sticky bit are refused). Omitted, a new remote file is published `0600`; an
  186. overwritten one inherits the replaced file's permission bits — its permission
  187. bits only, not its setuid or setgid.
  188. What a transfer is authorized for includes these arguments: the string the
  189. policy engine classifies, the approval prompt a human reads, and the audit
  190. record all name `--overwrite` and `--mode` when they are given. So approving one
  191. upload to a path does not approve a different one to the same path, and an
  192. approval grant (`approvalGrantTtlMs`) cannot be replayed with a different mode.
  193. ### Interactive Sessions
  194. Sessions maintain state (CWD, environment variables) between commands:
  195. ```
  196. Agent: open-session(name="deploy", type="interactive")
  197. Agent: run-command(session="deploy", command="cd /opt/myapp")
  198. Agent: run-command(session="deploy", command="git pull") # runs in /opt/myapp
  199. Agent: run-command(session="deploy", command="npm ci") # CWD persists
  200. Agent: close-session(name="deploy")
  201. ```
  202. ### Background Sessions
  203. Long-running processes (logs, builds):
  204. ```
  205. Agent: open-session(name="logs", type="background", command="tail -f /var/log/syslog")
  206. Agent: read-session-output(name="logs", lines=20) # poll
  207. Agent: close-session(name="logs")
  208. ```
  209. ### Remote host support
  210. Tested against Linux (Debian/bash, Alpine/busybox ash), Dropbear, and Windows
  211. OpenSSH on Windows 11.
  212. | | Linux / BSD / macOS | Windows OpenSSH |
  213. |---|:---:|:---:|
  214. | `read-command`, `run-command`, `privileged-command`, `signal-process` | ✅ | ✅ |
  215. | `sftp-upload`, `sftp-download` | ✅ | ✅ |
  216. | `sftp-list` | ✅ | ✅ |
  217. | `sftp-upload-file`, `sftp-download-file` | ✅ | ❌ (local side unverifiable) |
  218. | Background sessions | ✅ | ✅ |
  219. | **Interactive sessions** | ✅ | ❌ |
  220. **Interactive sessions require a POSIX shell** (sh, bash, ash, zsh). They work by
  221. bracketing each command with `printf` markers and reading `$?` and `$PWD` from a
  222. trailer — none of which exist in `cmd.exe`, the default shell for Windows
  223. OpenSSH. Opening one against such a host fails immediately with an explicit
  224. error rather than timing out; everything else works normally.
  225. Setting PowerShell as the OpenSSH `DefaultShell` does not help: the protocol is
  226. POSIX-specific, not merely non-`cmd`.
  227. ---
  228. ## Configuration
  229. ### Profile options
  230. ```toml
  231. [defaults]
  232. defaultProfile = "dev"
  233. sessionMaxPerConnection = 5
  234. sessionIdleTimeoutMs = 600000 # 10min; 0 = never idle-expire (and the connection is then never idle-reaped)
  235. sessionBackgroundMaxMs = 3600000 # 1hr absolute cap; 0 = no cap
  236. commandTimeoutMs = 60000
  237. commandMaxChars = 5000 # 0 = unlimited, the config spelling of --maxChars=none
  238. commandMaxOutputBytes = 1048576 # 1MB
  239. commandOutputTruncation = "head" # head | tail; see below
  240. connectionIdleReapMs = 900000 # 15min
  241. commandQuotaPerDay = 0 # 0 = unlimited; circuit breaker for runaway agents
  242. approvalGrantTtlMs = 0 # 0 = always prompt; see "Approval Grants"
  243. approvalMode = "ask-destructive" # auto | ask-destructive | ask-all | deny
  244. # transferRoot = "/srv/ssh-mcp-transfers" # enables the streaming file tools; see above
  245. transferMaxBytes = 268435456 # 256MB per streaming transfer
  246. transferTimeoutMs = 300000 # 5min with no bytes moving (idle, not total)
  247. [[profiles]]
  248. name = "prod-web-1"
  249. host = "10.0.1.50"
  250. port = 22
  251. user = "deploy"
  252. auth = "agent" # agent | key | password | keychain
  253. keyRef = "~/.ssh/id_ed25519" # for auth=key
  254. keychainEntry = "ssh-mcp/prod" # for auth=keychain (requires @napi-rs/keyring)
  255. via = "bastion" # ProxyJump — route through bastion profile
  256. group = "prod" # Policy tier: prod | staging | dev, or your own (see [policy])
  257. workdir = "/var/www"
  258. trustedHostKey = "SHA256:..." # Pin host key (optional)
  259. tty = false
  260. role = "operator" # viewer | operator | admin
  261. readOnly = false
  262. approvalPolicy = "ask-all"
  263. cert = false # SSH CA cert auth — auto-detects keyRef-cert.pub
  264. announceAgent = true # Send AI_AGENT=ssh-mcp to this host (see below); clear it for a host you do not control
  265. sessionMaxPerConnection = 3 # per-profile override
  266. sessionIdleTimeoutMs = 300000 # stricter for prod
  267. commandQuotaPerDay = 200 # per-profile override
  268. maxChars = 2000 # per-profile override; stricter for prod
  269. outputTruncation = "tail" # per-profile override
  270. transferMaxBytes = 16777216 # per-profile override; transferRoot is not per-profile
  271. transferTimeoutMs = 60000 # per-profile override
  272. # Optional. Merged over the built-in role matrix; see "Policy Engine" below.
  273. # roleBindings is keyed by role and then by tier, so the block below changes
  274. # operator on prod and leaves operator's other tiers, and viewer and admin,
  275. # on their defaults.
  276. [policy]
  277. denylist = ["^terraform\\s+destroy", "\\.ssh/authorized_keys$"]
  278. [policy.roleBindings.operator]
  279. prod = ["read-only", "safe", "destructive"]
  280. ```
  281. `commandOutputTruncation` chooses which end of a command's output survives
  282. `commandMaxOutputBytes` (counted in characters, as that cap always has been). The
  283. default, `"head"`, keeps the start — unchanged behaviour, which can run past the cap
  284. by the last chunk read. Set it to `"tail"` when the recent end is the part worth
  285. keeping: `grep pattern /var/log/big.log`, a log window, or any command whose answer
  286. is "what happened last". In head mode an over-cap `grep` returns the oldest matches
  287. and silently drops the rest, which can read as "nothing recent happened"; tail mode
  288. drops from the front instead and returns at most the cap, starting at the first
  289. whole line, so redaction does not see a line whose name was cut off (only output
  290. with no line break inside the cap is cut mid-line). While the command runs, tail
  291. mode holds a few times the cap per stream. Per-profile override:
  292. `outputTruncation`.
  293. Unknown sections and keys are a startup error, not a warning, so a typo cannot
  294. leave you running defaults you thought you had overridden. That extends to role
  295. and tier names: every one you write under `[policy.roleBindings]` has to be
  296. reachable by some profile, and every profile's role and tier has to resolve to
  297. real bindings. Both directions are checked at startup and on every reload.
  298. Every profile needs a `name` of its own. Two profiles with the same name are a startup
  299. error, and a reload refuses them too; the error names the two entries by index
  300. (`profiles[2].name repeats profiles[0].name`), not by the name. Before this release such a
  301. config started, and the first of the two was used.
  302. ### Host-side identification
  303. Every command this server runs announces itself to the host as the environment
  304. variable `AI_AGENT=ssh-mcp`, so an operator can tell an agent's session from a
  305. person's from anything on the host that reads the session environment — a
  306. `/etc/profile` snippet or a `ForceCommand` wrapper, for instance. It covers all
  307. three channels a command can run on: one-shot commands, background sessions and
  308. interactive sessions. SFTP transfers do not carry it, because the SSH library
  309. this server uses offers no way to send an environment request on a subsystem
  310. channel.
  311. **The variable only lands in the session if the host opts in** with
  312. `AcceptEnv AI_AGENT` in `sshd_config`. Without that line sshd ignores it and the
  313. session environment is unchanged — measured against Dropbear, which has no
  314. `AcceptEnv` mechanism at all, and against Windows OpenSSH on a default
  315. configuration: the command runs, the exit code is unchanged, the variable is
  316. simply absent.
  317. **The request is nevertheless sent to every host, opted in or not.** `AcceptEnv`
  318. is the server's policy about what it stores; it is not a gate on what this client
  319. transmits. A host that has not opted in — including one that is hostile — can
  320. still see on the wire that an agent rather than a person is driving the session.
  321. That is why `announceAgent = false` exists on the profile: set it for any host you
  322. do not control and nothing is sent to it. It is on by default, because the
  323. operators who benefit are the ones running the hosts you do control.
  324. No version is sent, deliberately. A version would narrow a hostile host to one
  325. specific build; the tool's name alone does not. (The SSH transport already
  326. discloses the *library* version in its identification string, which is one
  327. library's version across every program that uses it.)
  328. Treat the variable as a courtesy label, not an attestation. Any SSH client can
  329. set it and any agent can omit it, so it is useful for attributing sessions you
  330. already trust and must not be used as an authorization or intrusion-detection
  331. input. Authoritative attribution belongs to the key or principal that
  332. authenticated.
  333. ### ProxyJump (Bastion)
  334. Reach internal hosts behind a bastion/jump server. The `via` field specifies a profile name to tunnel through:
  335. ```toml
  336. [[profiles]]
  337. name = "bastion"
  338. host = "bastion.example.com"
  339. user = "deploy"
  340. auth = "agent"
  341. [[profiles]]
  342. name = "internal-db"
  343. host = "10.0.1.50" # private IP — not directly reachable
  344. user = "dbadmin"
  345. auth = "key"
  346. keyRef = "~/.ssh/db_key"
  347. via = "bastion" # tunnel through bastion
  348. ```
  349. No agent forwarding — only a TCP tunnel via `forwardOut`. The bastion stays connected and reusable for multiple internal hosts.
  350. ### SSH CA Certificates
  351. For enterprise setups with a central SSH Certificate Authority:
  352. ```toml
  353. [[profiles]]
  354. name = "prod-db"
  355. host = "db.internal"
  356. user = "admin"
  357. auth = "key"
  358. keyRef = "~/.ssh/id_ed25519"
  359. cert = true # enable CA cert auth
  360. ```
  361. The certificate file is auto-detected using OpenSSH convention (`keyRef` + `-cert.pub`, e.g. `~/.ssh/id_ed25519-cert.pub`). You can override the path with `SSH_MCP_<NAME>_CERT` env var. The cert is concatenated with the private key per ssh2 convention.
  362. ### Credential Resolution Order
  363. 1. **SSH agent** (`SSH_AUTH_SOCK`) — no key material in process memory
  364. 2. **OS keychain** (macOS Keychain / Windows Credential Manager / Linux Secret Service) — requires `auth = "keychain"` and `@napi-rs/keyring`
  365. 3. **Environment variables** — `SSH_MCP_PASSWORD`, `SSH_MCP_KEY`, `SSH_MCP_SUDO_PASSWORD`, or profile-specific `SSH_MCP_<NAME>_PASSWORD`
  366. 4. **Key file** — `keyRef` path or `SSH_MCP_KEY` env var
  367. **Never CLI arguments.** v2 removes `--password`, `--sudoPassword`, `--suPassword` entirely.
  368. ### Reloading
  369. The config file is read at startup, and again only when you ask: through the
  370. `reload-config` tool with `action: "reload"`, or by sending the process `SIGHUP`
  371. (`kill -HUP <pid>`) on every platform but Windows. On Windows `SIGHUP` means the console
  372. is closing, so it does not reload there; use the tool. Nothing watches the file, so a
  373. half-written file never becomes live policy. A reload reads the same path the server
  374. started with: `--config`, or the default path for your platform.
  375. `reload-config` takes one argument, `action`:
  376. - `"status"` (the default) reports the config path, where the live config came from (`file`,
  377. `unconfigured` or `flags`), when it was loaded, the sha256 of the bytes it was parsed
  378. from, and the result of the last reload. It never shows the file's contents.
  379. - `"reload"` re-reads the file, applies it if every check passes, and reports what changed:
  380. profiles added, removed and changed (by name and field), whether the policy rules changed,
  381. and which connections it closed, why, and with which sessions. The same report goes to
  382. stderr.
  383. The tool asks for no approval and spends no command quota. A caller can only make the
  384. server re-read what the operator wrote; the file is the operator's consent.
  385. **All or nothing.** A reload runs the same checks as startup on the new file before anything
  386. changes: the permission check (mode bits on Linux and macOS, the ACL on Windows, with the
  387. `--strictConfigAcl` or `--allowUncheckedConfigAcl` the server started with), the TOML parse,
  388. the strict schema, the check that no two profiles share a name, the role and tier
  389. cross-check, and compiling the denylist. A file with no
  390. profiles fails the schema, as at startup, so a reload cannot leave a server unconfigured.
  391. Two more refusals belong to reloading alone:
  392. - **`defaults.transferRoot` changed or removed.** A transfer in flight holds the old root,
  393. so this needs a restart. Adding a `transferRoot` where there was none is allowed: with no
  394. root there can be no transfer in flight.
  395. - **The server was started from `--host`/`--user` flags.** Swapping the flag-built profile
  396. for whatever file sits at the default path would change where the server's trust comes
  397. from without the operator choosing it. Restart with a config file instead.
  398. A refused reload changes nothing: the config, the policy, connections, sessions and approval
  399. grants stay as they were. The refusal names the error class and the path, and for a schema
  400. error the field paths and issue codes; it never quotes a value from the file.
  401. **What applies when.** Once every check passes, the new config replaces the old in one step,
  402. so no tool call sees part of each. For each open connection, by profile name:
  403. | Changed on the profile | What happens |
  404. |---|---|
  405. | `role`, `group`, `approvalPolicy`, `readOnly`, `commandQuotaPerDay`, `maxChars`, `transferMaxBytes`, `transferTimeoutMs`, or the `[policy]` section | The connection stays open; the change applies from its next command |
  406. | `workdir`, `tty`, `timeout`, `maxOutputBytes`, `outputTruncation`, `announceAgent`, `sessionMaxPerConnection`, `sessionIdleTimeoutMs`, `sessionBackgroundMaxMs` | The connection stays open; the new values apply to new sessions and commands, and the report names these fields |
  407. | `host`, `port`, `user`, `auth`, `keyRef`, `keychainEntry`, `cert`, `via`, `trustedHostKey` | The connection closes with its sessions; the next call connects with the new profile |
  408. | the profile was removed | The connection closes with its sessions |
  409. A connection that runs through a bastion that is closing closes too, and so does anything
  410. running through it in turn; dependents close before the bastion they run through. A
  411. `[defaults]` value reaches every profile that does not set its own, so changing it counts as
  412. a change to each of those profiles. `defaultProfile`, `connectionIdleReapMs` and
  413. `approvalGrantTtlMs` apply at once. Command quota counts are kept, so a new
  414. `commandQuotaPerDay` applies to what has already been spent. Host keys accepted on first use
  415. are kept too, because the connection registry is updated in place rather than rebuilt. A
  416. new connection that was still being opened when the reload landed is discarded only if the
  417. reload closes its profile (removed, a connection field changed, or its bastion closing); that
  418. call fails with "The configuration was reloaded while connecting; retry the call." Any other
  419. is kept, with the profile as the reload left it, so reloading an unchanged file does not fail
  420. other calls' connects.
  421. **Approvals.** Every applied reload, even of an unchanged file, retires every approval grant
  422. made before it, so the next run of a granted command asks again. An approval answered after
  423. a reload landed is re-checked against the new rules: the command runs only if its connection
  424. is still open and the new rules still allow it or ask for it, in the same command class.
  425. Otherwise it is refused with `CONFIG_RELOADED` and no grant is recorded; retry the call to
  426. be asked under the new rules. A decision that needed no prompt is re-checked the same way
  427. when a reload lands while it is being made (while the connection is resolved, or during an
  428. OPA round-trip): a command the old rules allowed, or a grant reuse, runs only if its
  429. connection is still open and the new rules allow it outright, in the same class; otherwise
  430. it is refused with `CONFIG_RELOADED`. The command quota is charged against the profile as
  431. the reload left it.
  432. **Already running.** A command or transfer that is running when the reload lands finishes
  433. under the rules it started with, unless the reload closes its connection; the next call is
  434. checked under the new ones. Removing a profile and reloading closes its connection, but that
  435. stops less than it sounds: a background session's command is signalled `INT`, then `TERM`,
  436. then `KILL`, while a one-shot command, or one running in an interactive session, is not
  437. signalled at all and may keep running on the host. Stop such a command with
  438. `signal-process` first, while the profile still reaches the host (see
  439. [SECURITY.md](./SECURITY.md#stopping-a-command)).
  440. **Never reloaded.** Command-line flags keep the values the process started with: the
  441. transport and its HTTP options, `--hostKeyMode`, the OPA, audit and OpenTelemetry flags, the
  442. ACL flags and `--config` itself. The flags that stand in for `[defaults]` (`--timeout`,
  443. `--maxChars`, `--sessionMax`, `--sessionTtl`, `--commandQuota`, `--approvalGrantTtl`) apply
  444. only while no file is loaded, as at startup, so a server that started unconfigured takes its
  445. defaults from the file once a reload loads one.
  446. **Audit.** Every reload that runs writes one `config:reload` record, in one of three forms:
  447. | Outcome | `decision` | `ruleId` | `error` |
  448. |---|---|---|---|
  449. | applied | `allow` | `config-reload` | unset |
  450. | refused: a check failed, nothing changed | `deny` | `config-reload` | the refusal |
  451. | failed after the swap began, so possibly partly applied | `deny` | `config-reload-partial` | the error class, and that it may be partly applied |
  452. The other fields are fixed: `command` and `binary` are `config:reload`, `commandClass` is
  453. `safe`, `profile` and `user` are `-`, and `mcpRequestId` is the tool call's request id, or
  454. `sighup` for a reload the signal triggered. Each session a reload closes also writes a
  455. `session:close … (reload)` record, as the `close-session` tool does. A connection that fails
  456. to close is reported, not rolled back: the new config is already in effect.
  457. Reloads run one at a time: one asked for while another is running waits for it and then
  458. reads the file afresh, and any asked for while that one is still waiting join it and share
  459. its report and its record, so a burst of requests or `SIGHUP`s costs at most two reloads.
  460. If something fails after the checks have passed (a defect, not a refusal), the report says
  461. the reload failed after the swap began and may be partly applied; check `reload-config`
  462. status, and restart if it does not show the new config.
  463. **`SIGHUP` no longer stops the server.** Before, its default action ended the process
  464. without flushing the audit log. Now, everywhere but Windows, it triggers a reload and the
  465. server keeps running. A stdio server still exits when its client closes stdin. An HTTP
  466. server started from a terminal is no longer stopped when that terminal closes, since the
  467. hangup it sends is now handled as a reload: stop it with `SIGTERM` or `SIGINT`, or run it
  468. under a supervisor.
  469. ---
  470. ## Policy Engine
  471. ### Roles
  472. | Role | Dev | Staging | Prod |
  473. |------|-----|---------|------|
  474. | **viewer** | read-only | read-only | read-only |
  475. | **operator** | read-only, safe, destructive | read-only, safe, destructive | read-only, safe |
  476. | **admin** | all | all | read-only, safe, destructive |
  477. Which column applies comes from the profile's `group`. Set it explicitly —
  478. without it the tier is guessed from the profile name (`prod`/`staging`/`dev`,
  479. `local`, `test`, `sandbox`), and **an unrecognised name resolves to `prod`**,
  480. the strictest tier. A production host named `web-01` is therefore treated as
  481. production rather than silently getting dev permissions.
  482. Note what this means for `sudo`: **`admin` has no `privileged` on `prod`**, so
  483. `privileged-command` is refused there by design — including on a quick-start
  484. profile, which has no name to infer from and therefore lands on `prod`. If the
  485. host is not production, say so:
  486. ```bash
  487. npx ssh-mcp --host=10.0.0.5 --user=deploy --group=dev
  488. ```
  489. ```toml
  490. [[profiles]]
  491. name = "build-box"
  492. group = "dev"
  493. ```
  494. ### Configuring the matrix
  495. The table above is the default, not a limit. An optional `[policy]` section is
  496. merged over it at startup and on every reload, so granting sudo on a host you have honestly
  497. labelled `prod` is a reviewable line in a config file rather than a relabelling:
  498. ```toml
  499. [policy.roleBindings.admin]
  500. prod = ["read-only", "safe", "destructive", "privileged"]
  501. ```
  502. The merge is at role *and* tier depth. That block changes `admin` on `prod` and
  503. nothing else: `admin` on `staging` and `dev` keep their defaults, and `viewer`
  504. and `operator` are untouched. Roles and tiers the defaults have never heard of
  505. are added rather than rejected, which is what makes a custom `group` resolve to
  506. real bindings instead of falling back to the strictest tier:
  507. ```toml
  508. [[profiles]]
  509. name = "build-box"
  510. role = "admin"
  511. group = "tier-1"
  512. [policy.roleBindings.admin]
  513. "tier-1" = ["read-only", "safe", "destructive"]
  514. ```
  515. Extra deny patterns live in the same section, and are applied on top of the
  516. never-allowed list rather than replacing it:
  517. ```toml
  518. [policy]
  519. denylist = ["^terraform\\s+destroy", "\\.ssh/authorized_keys$"]
  520. ```
  521. Each pattern is a regular expression tested against the command string of every
  522. call. For the five SFTP tools it is also tested against the remote path on its
  523. own, three ways: as given; in a normalized reading, where `//` and `/./`
  524. collapse, `..` resolves against the segment before it, a trailing `/` is
  525. dropped, and `\` is read as `/`; and in a **Windows reading**, tested
  526. case-insensitively. The refusal says which matched.
  527. The Windows reading is what Win32 resolves a path to, measured over SFTP on
  528. Windows 11 (build 26200): the case variants, a trailing run of dots and spaces,
  529. and the `::$DATA` default-stream spelling all reach the same file, so a rule
  530. that caught one spelling and not another was a bypass, not a distinction. On
  531. top of the normalized reading it strips those spellings, roots a
  532. drive-relative path (`C:x/…`) at its drive — where it actually resolves
  533. depends on process state this server cannot see, and rooting is the fail-closed
  534. reading — drops `\\?\` and `\\.\` device prefixes, and keeps a UNC root
  535. (`\\server\share\…` → `//server/share/…`). Tested case-insensitively, it also
  536. catches `Authorized_Keys` with a rule written for `authorized_keys`; on a POSIX
  537. target those are different files, but erring toward refusal is the direction
  538. this engine takes everywhere else too.
  539. What the readings do not do:
  540. - **resolve anything on the target.** A relative path stays relative, so a rule
  541. anchored on `/root/` does not see `.ssh/authorized_keys`; symlinks are not
  542. followed; and an 8.3 short name (`AUTHOR~1`) is not expanded — no lexical
  543. reading can, it takes the target's own directory listing to know the long
  544. name.
  545. - **test the local path** of `sftp-upload-file` or `sftp-download-file` on its
  546. own. That side is confined by `transferRoot`. The local path does end those two
  547. tools' command strings, so a pattern anchored on the end of the string can
  548. still match it there, as it always could.
  549. So anchor a path rule on its trailing segments: `\.ssh/authorized_keys$` matches
  550. the absolute, relative and Windows spellings alike — including the case,
  551. trailing-dot and `::$DATA` variants of each. A pattern written for a command is
  552. tested against SFTP paths too — `^rm` refuses an `sftp-download` of a file
  553. called `rmlist.txt`.
  554. One performance note: patterns are ordinary regular expressions run against
  555. caller-supplied path bytes — bounded by the remote-path length limit, the same
  556. exposure the command string has always had. Prefer anchored, linear patterns; a
  557. catastrophically backtracking one stalls the tool call it matches.
  558. Because role and tier names are free strings, nothing in the merge itself can
  559. tell a new custom role from a misspelling of an existing one. A cross-check at
  560. startup does, and these all fail there rather than at the point of use:
  561. - a command class outside `read-only | safe | destructive | privileged`, so a
  562. `priviledged` typo cannot parse into a grant of nothing and then read as a
  563. policy decision when a command is refused;
  564. - any unrecognised section or key anywhere in the config, so a block the parser
  565. does not understand is an error rather than a clean startup with none of the
  566. behaviour you configured;
  567. - a role or tier under `[policy.roleBindings]` that no profile uses, so
  568. `[policy.roleBindings.operater]` cannot merge in as a fourth role while the
  569. profiles you meant to restrict keep running on defaults;
  570. - a profile whose `role` has no bindings, or whose tier has none under that
  571. role, so a host cannot end up on `read-only` for a reason nobody wrote down.
  572. The last one covers the tier you did not set as well as the one you did. A
  573. profile with no `group` still resolves to one by name, and that inferred tier
  574. has to exist under the profile's role like any other.
  575. A tier with no bindings for a role grants `read-only`, and never another tier's
  576. classes. There is no fallback between tiers: while the matrix was compiled in,
  577. falling back to `prod` meant falling back to a role's strictest cell, but a
  578. `[policy]` block can write that cell now.
  579. An OPA sidecar is not an alternative route to the same grant. OPA is consulted
  580. only for commands the local policy already allows, so it can refuse more but
  581. never widen. Widening happens here or not at all.
  582. ### Command Classification
  583. Every command is classified before execution:
  584. - **read-only**: Allowlisted commands (`ls`, `cat`, `grep`, `df`, `stat`, `systemctl status`, ...),
  585. and only when every argument is provably data under a grammar declared for that binary — see
  586. below
  587. - **safe**: Non-destructive mutations (`npm install`, `git pull`, ...)
  588. - **destructive**: mutations that need approval (`rm -rf /tmp/build`, ...)
  589. - **privileged**: `sudo`, `su`, `doas`, `pkexec`
  590. **`read-only` is granted by argument grammar, not by binary name alone.** An allowlisted
  591. binary's argument list is checked word by word against a grammar declared for it
  592. (`src/policy/reader-grammar.ts`); an option the grammar does not list, an abbreviation of one
  593. it does, a short-option cluster with an unlisted letter, an argument carrying an unquoted
  594. shell glob (`*`, `?`, `[`), or an operand shaped like something
  595. the binary would write to, all fall the whole command to `safe` instead. This is what a
  596. `readOnly` profile is confined to, what `viewer` holds on prod and staging (on dev the viewer
  597. holds `safe` too), and what `read-command`
  598. requires — all of these refuse `safe` except the viewer on dev, so a command that used to
  599. run under the old, name-only
  600. rule can now be refused. The refusal names the rejected word (for example, `` `journalctl` is
  601. read-only only with the options and operands its grammar lists; `--foo` is not accepted
  602. there. ``), so the caller can see which spelling of the same command still works. See
  603. [SECURITY.md](./SECURITY.md) for the residual risks this leaves open.
  604. A reader also falls to `safe` when its command carries a shell metacharacter — `;` `&` `|`
  605. `<` `>` `` ` `` `$` `(` `)` `{` `}`, a newline or a carriage return — quoted or not, because
  606. the allowlist vouches for the binary, never for what a shell might do with the rest of the
  607. line. The refusal names the first such character. For `sftp-list` and `sftp-download` it is
  608. in the remote path, so `/srv/backup(old)` is refused for a `readOnly` profile with
  609. `` The remote path contains `(`, which counts as a shell metacharacter here, so `sftp:list`
  610. is read-only only for a path without one. ``
  611. A separate **forbidden** list is never allowed, whatever the role or approval
  612. policy: `rm -rf /`, `mkfs`, `dd of=/dev/`, `shutdown`, `curl|sh`, fork bombs,
  613. writes naming `/etc/cron`, `/etc/systemd` or any user's `authorized_keys`,
  614. `iptables -F`, and recursive `chmod 777 /` / `chown /`. A write *names* one of
  615. those paths when it is the remote path of an upload tool, the target of a shell
  616. redirect, or a destination of `tee`, `cp`, `mv`, `install` or `dd of=` — in any
  617. spelling the path readings above resolve. The two `/etc` families match by
  618. prefix, so `/etc/crontab` is covered along with everything under `/etc/cron.d`,
  619. and a sibling that merely starts like the directory (say `/etc/cronography`) is
  620. refused too — the fail-closed direction. Writes spelled any other way (`sed -i`,
  621. `rsync`, cmd.exe's `copy`, `move` and `robocopy`, a program handed to an
  622. interpreter, a path the target computes) are not on this list; class and approval
  623. govern them, and the operator denylist can close them. Add your own patterns via
  624. the policy denylist; an invalid pattern fails at
  625. startup rather than degrading silently.
  626. ### Approval Modes
  627. - `auto` — no prompts (dev only!)
  628. - `ask-destructive` — prompt for destructive/privileged (default). Narrower than it sounds:
  629. outside the never-allowed list, `destructive` is a recursive `rm` of an absolute path, `find`
  630. with a write/exec flag, an unresolvable command word, a program this server cannot read
  631. (`python3 -c`, `perl -e`, `node -e`, a program arriving on a pipe, a `make` recipe, the
  632. remote command of `ssh`), an `awk` program that writes a file or cannot be read, and
  633. `sftp-upload`/interactive `open-session` — elevation classifies `privileged`, which also
  634. prompts, including elevation inside an awk `system()` call. Ordinary writes, service control
  635. and signals do not. See
  636. [SECURITY.md](./SECURITY.md) before relying on this in production.
  637. - `ask-all` — prompt for every command
  638. - `deny` — reject destructive/privileged commands outright (no prompt)
  639. ### Approval Grants (just-in-time)
  640. `approvalGrantTtlMs` lets one explicit approval cover repeats of the **exact
  641. same** command on the same profile for a bounded time (e.g. `300000` for five
  642. minutes). It exists because approving `rm -rf /tmp/build` every few seconds
  643. during an iterative task trains you to click through prompts — which is worse
  644. for safety than a grant you chose deliberately.
  645. A grant is bound to the exact command text, the profile and the command class:
  646. approving `rm -rf /tmp/build` does not cover `rm -rf /tmp/build-prod`, the same
  647. command on another host, or the same command escalated to `sudo`. Runs covered
  648. by a grant appear in the audit log with `approver: "jit-grant"`, so they stay
  649. distinguishable from a fresh human answer.
  650. **Off by default** (`0` = always prompt). Auto-approval weakens the gate that
  651. makes destructive commands safe, so turning it on should be a decision.
  652. #### Answering the prompt
  653. Approval goes through the MCP elicitation request, so what you see is your
  654. client's dialog. Accepting it approves the command — there is no second field to
  655. fill in.
  656. You have **10 minutes** to answer. Past that the request expires and the command
  657. is refused rather than left pending, and the refusal says so; the prompt may
  658. still be open in your client, in which case run the command again once you are
  659. ready. If your client does not support elicitation at all, every destructive and
  660. privileged command is refused with `APPROVAL_UNAVAILABLE` naming that cause —
  661. approval fails closed by design.
  662. ### Command Quota
  663. `commandQuotaPerDay` bounds how many commands a profile may run in a rolling
  664. 24-hour window (0 = unlimited). The approval gate stops *destructive* commands
  665. and the HTTP rate limiter caps request rate, but neither bounds total work — a
  666. prompt-injected agent looping over allowed commands stays under both. The quota
  667. is the circuit breaker for that case.
  668. Counted after policy allows a command and before it runs, so a denied command
  669. does not spend budget. The window slides rather than resetting at midnight,
  670. which would let an agent spend a full quota just before the reset and another
  671. immediately after.
  672. ### External Policy Engine (OPA)
  673. For organizations that standardize on Open Policy Agent / Rego:
  674. ```bash
  675. ssh-mcp --opaUrl=http://localhost:8181
  676. ```
  677. When `--opaUrl` is set, commands the built-in engine allows are additionally
  678. evaluated by OPA. **OPA can only narrow.** A command the built-in engine has
  679. already denied returns that denial without OPA being consulted at all, so a
  680. sidecar answering `allow` cannot grant a class the role bindings withhold. To
  681. widen, edit `[policy]`.
  682. An outage falls back to the local decision and logs one warning per minute. That is the
  683. default because OPA is an *additional* deny layer and stopping all work would be the worse
  684. failure — but an operator who deployed OPA *as* the authorization gate loses that gate
  685. during the outage, and the only signal is a stderr line MCP clients usually discard.
  686. `--opaFailClosed` makes the gate being down mean no; the refusal carries `ruleId:
  687. "opa-unavailable"` so the audit record says the gate was down rather than implying a policy
  688. refused the command.
  689. The request shape is modeled on the AuthZEN Access Evaluation contract:
  690. ```json
  691. {
  692. "input": {
  693. "subject": { "role": "operator", "profile": "prod-web-1" },
  694. "action": { "tool": "run-command", "commandClass": "destructive" },
  695. "resource": { "command": "rm -rf /tmp/cache", "binary": "rm", "host": "10.0.1.50" },
  696. "context": { "readOnly": false }
  697. }
  698. }
  699. ```
  700. For the five SFTP tools, `resource` also carries three path keys: `remotePath`,
  701. the path as given; and `remotePathNormalized` and `remotePathWindows`, the same
  702. two readings the local denylist tests, so a rule can match a canonical spelling
  703. without parsing `command` or reimplementing either reading in Rego. The two
  704. upload tools add `remoteWrite: true`, the fact the local policy refuses the
  705. never-allowed write paths on — a rule can gate writes without parsing `command`
  706. either. Other tools omit all four, and so does an empty path. `remotePath` is **as given** —
  707. `/root//.ssh/x` arrives spelled that way, so a `startswith` rule on a directory
  708. misses it: match trailing segments, or match the normalized keys.
  709. `remotePathWindows` keeps the case it was given; `lower()` both sides in the
  710. policy for case-insensitive rules. Match fields rather than the whole
  711. `resource` object — its keys vary by tool.
  712. OPA responds with `{ "result": true/false }`. If OPA denies (`result: false`), the command is blocked even if the built-in engine allows it. If OPA is unreachable, the built-in engine's decision stands by default (fail-open, to avoid locking out access); `--opaFailClosed` refuses instead. A 200 that carries no boolean `result` counts as unreachable — that is what OPA answers for an undefined document, so a misnamed package or an unactivated bundle is an outage rather than consent.
  713. Example Rego policy (`ssh-mcp.rego`):
  714. ```rego
  715. package ssh.mcp
  716. default allow := false
  717. # Admins pass the OPA gate on dev hosts. The built-in policy still applies on
  718. # top: this widens nothing that the role bindings withhold.
  719. allow if {
  720. input.subject.role == "admin"
  721. startswith(input.subject.profile, "dev")
  722. }
  723. # Deny all destructive commands on prod
  724. deny if {
  725. input.action.commandClass == "destructive"
  726. startswith(input.subject.profile, "prod")
  727. }
  728. ```
  729. ---
  730. ## Security
  731. ### Threat Model
  732. See [SECURITY.md](./SECURITY.md) for the full threat model, vulnerability reporting policy, and deployment checklist.
  733. ### Supply chain
  734. Releases carry signed attestations, published through [Sigstore](https://www.sigstore.dev/)
  735. and recorded in its public transparency log. They live in **two different stores**, which is
  736. what decides how each is verified:
  737. | Attestation | Predicate | Stored by | Since |
  738. |---|---|---|---|
  739. | Build provenance — [SLSA](https://slsa.dev/) Build **Level 2** | `slsa.dev/provenance/v1` | npm | every release |
  740. | SBOM — CycloneDX and SPDX | `cyclonedx.org/bom`, `spdx.dev/Document` | GitHub | releases after v2.4.0 |
  741. Provenance comes from npm [trusted publishing](https://docs.npmjs.com/trusted-publishers):
  742. the release workflow authenticates with a short-lived OIDC token and no stored credential,
  743. so there is no long-lived npm token to leak.
  744. ```bash
  745. npm audit signatures # provenance, against an installed tree
  746. npm pack ssh-mcp # the SBOM attestation is bound to the tarball, so fetch it
  747. gh attestation verify ssh-mcp-*.tgz --repo tufantunc/ssh-mcp --predicate-type https://cyclonedx.org/bom
  748. ```
  749. Both flags on the last command are load-bearing. `gh attestation verify` defaults to the
  750. SLSA predicate, so without `--predicate-type` it filters the SBOM out and reports nothing
  751. found — and the provenance it would look for instead is in npm's store, not the GitHub
  752. store `--repo` queries. Use `https://spdx.dev/Document` for the SPDX one.
  753. Both SBOMs are also attached to each
  754. [GitHub release](https://github.com/tufantunc/ssh-mcp/releases), for reading rather than
  755. verifying.
  756. **Level 2, not 3.** Provenance is signed by the generic GitHub-hosted runner —
  757. `builder.id` is `https://github.com/actions/runner/github-hosted` — which the build itself
  758. can influence; Build L3 requires an isolated builder it cannot. Reaching L3 is not
  759. currently compatible with trusted publishing: npm turns on its own provenance whenever that
  760. setting is left at its default, and then ignores any externally generated one. So L3 today
  761. would mean returning to a long-lived npm token — trading the property described above for a
  762. level number.
  763. ### Safe Defaults
  764. - **Non-root** user in all examples
  765. - **TOFU** host key verification (accept on first connect, verify after — within one process; see [SECURITY.md](./SECURITY.md#host-key-trust-does-not-survive-a-restart))
  766. - **RFC 9142** algorithm allow-list (no SHA-1, no CBC, no ssh-rsa)
  767. - **exec()-only for elevation** (`privileged-command` takes no `session`, so sudo never runs in a persistent shell — fixes PTY leak. Interactive sessions exist for ordinary commands; this bullet is about elevation, not about every path being an exec channel)
  768. - **Sudo via stdin** (not argv — fixes process list leak)
  769. - **Sanitizer** strips CR/LF/NUL from all metadata
  770. - **3-layer redaction** (field → regex → entropy) on audit logs
  771. - **No CLI-arg secrets** (use env vars, keychain, or config)
  772. - **Agent announcement is disclosed, not hidden** — every command tells the host `AI_AGENT=ssh-mcp`, including hosts that never opted in to storing it; clear `announceAgent` on a profile pointing at a host you do not control (see [Host-side identification](#host-side-identification))
  773. ### Hardening Checklist
  774. - [ ] Create dedicated low-privilege service account on target hosts
  775. - [ ] Use command-specific `sudoers` instead of `NOPASSWD: ALL`
  776. - [ ] Enable `ask-all` approval for production profiles
  777. - [ ] Restrict network egress on target hosts
  778. - [ ] Use `readOnly = true` for monitoring profiles
  779. - [ ] Review audit logs regularly
  780. - [ ] Run `chmod 700 <config dir> && chmod 600 config.toml` (Windows: the ACL under `%APPDATA%` is already restricted)
  781. ---
  782. ## Transports
  783. ### stdio (default)
  784. For local MCP clients (Claude Code, Cursor, Windsurf). No network exposure.
  785. ```bash
  786. ssh-mcp # reads config from XDG path
  787. ssh-mcp --config=/path/to.toml # custom config path
  788. ```
  789. ### HTTP (optional)
  790. For remote/web clients behind a reverse proxy with TLS:
  791. ```bash
  792. ssh-mcp --transport=http --httpPort=3000 --bearerToken=secret
  793. ssh-mcp --transport=http --httpPort=3000 --bearerToken=secret --rateLimit=60
  794. ```
  795. | Flag | Default | Description |
  796. |------|---------|-------------|
  797. | `--bearerToken` | required | Bearer token for authentication (all routes except `GET /health`) |
  798. | `--httpPort` | 3000 | HTTP listen port |
  799. | `--httpHost` | 127.0.0.1 | Bind address |
  800. | `--rateLimit` | 0 (off) | Max authenticated requests per minute, per client (0 = unlimited) |
  801. | `--httpSessionTtl` | 1800000 | Idle timeout of an MCP client session over HTTP, in ms (a session with a request in flight or an open SSE stream does not expire). At the 64-session cap a new client evicts the least recently active session with no request in flight, one holding an SSE stream only when no other can go |
  802. | `--authFailureLimit` | 10 | Failed bearer-auth attempts allowed per client per minute (0 = off) |
  803. | `--trustProxy` | false | Read the client address from `X-Forwarded-For`, but only when the peer is the proxy — bare means a loopback peer |
  804. | `--trustedProxies` | — | Comma-separated peer addresses allowed to send `X-Forwarded-For`. Empty means loopback only |
  805. Endpoints: `POST /` (MCP Streamable HTTP), `GET /status`, `GET /health`
  806. `GET /health` answers `{"healthy": true, "configured": <bool>}`. It stays `200` either way —
  807. `healthy` is liveness — while `configured` is false when no profile is set, which is the
  808. case of a config bind mount that silently did not attach: the server binds the port and
  809. refuses every tool call except `reload-config`. `configured` turns true once a reload has
  810. loaded a file. `GET /status` carries the profile list itself and stays behind the
  811. bearer token.
  812. `--rateLimit` is a budget per client, keyed the same way as the failed-auth budget below,
  813. and every authenticated request spends from it: `POST /` and the rest of the MCP route,
  814. `GET /status`, and an authenticated request to a path that does not exist. `GET /health`
  815. never does. A wrong token never does either, so unauthenticated traffic cannot spend a
  816. working client's budget. When a client's budget is spent the server returns HTTP 429 with
  817. a JSON-RPC error body, and `Retry-After` gives the seconds until that client's next request
  818. will be accepted.
  819. Failed authentication is throttled separately, and on by default. `--rateLimit` never saw a
  820. wrong bearer token, because the auth check answers before the limiter is reached — so
  821. guessing ran at network speed. `--authFailureLimit` gives each client its own small budget,
  822. spent only on a 401; a correct token never consumes from it, so a working client never
  823. throttles itself. Once an address has spent its budget every request from it waits,
  824. including one with the right token — that is deliberate, since answering the guess would
  825. otherwise tell the caller which token was right. Clients are told apart by socket address,
  826. for this budget and for `--rateLimit` alike. **Behind a reverse proxy that means every
  827. client shares one of each**, so set `--trustProxy` when the proxy is yours — the server
  828. prints a warning the first time it sees `X-Forwarded-For` without it. `--trustProxy` takes
  829. the *rightmost* `X-Forwarded-For` entry, which is the hop the proxy itself appended;
  830. everything to its left came from the client, so reading the leftmost would let a client
  831. choose its own budget or spend a victim's. That only holds if a proxy actually appended
  832. the entry, so the header is read **only when the peer is the proxy** — bare `--trustProxy`
  833. means a loopback peer, which is the deployment above; name a proxy elsewhere with
  834. `--trustedProxies`. When the header cannot be read as an address, or the peer is not
  835. trusted, the server falls back to the socket address and says so once, so a flag that is
  836. not taking effect is not silent. One trusted hop is assumed. A malformed
  837. `--authFailureLimit` is refused at startup rather than silently disabling the check; only
  838. `0` turns it off.
  839. An IPv6 client is told apart by its /64 rather than its full address, for both budgets. A
  840. /64 is usually the smallest block a subscriber is handed, so hosts that share one — a home
  841. or office network, or customers a hosting provider places on one /64 — share a budget, the
  842. way hosts behind one IPv4 NAT do. An IPv6 address that carries an IPv4 address (IPv4-mapped,
  843. or the NAT64 prefix `64:ff9b::/96`) counts as that IPv4 client. A NAT64 or SIIT translator
  844. that uses a prefix of its own is not recognised: every IPv4 client it translates shares that
  845. prefix's /64, and so one budget.
  846. **Always terminate TLS at a reverse proxy** (Caddy/nginx). The server listens on `127.0.0.1` only.
  847. ---
  848. ## Docker
  849. ```bash
  850. # Build
  851. docker build -t ssh-mcp .
  852. # Run (config file + env vars for credentials)
  853. docker run -i \
  854. -v ./config.toml:/home/appuser/.config/ssh-mcp/config.toml:ro \
  855. -e SSH_MCP_PASSWORD=secret \
  856. ssh-mcp
  857. ```
  858. Or with docker-compose:
  859. ```bash
  860. docker-compose --profile app up
  861. ```
  862. The Docker image runs as non-root UID 65532, with a minimal `node:22-slim` base.
  863. ---
  864. ## CLI Flags (v2)
  865. Secrets are **never** passed as CLI arguments. A flag not in this table is refused at startup, with the nearest flag suggested when there is one, rather than ignored.
  866. | Flag | Default | Description |
  867. |------|---------|-------------|
  868. | `--config` | platform config dir (see [Configure](#2-configure)) | Path to TOML config file |
  869. | `--host` | — | Quick start: SSH host (creates single-profile config) |
  870. | `--user` | — | Quick start: SSH username |
  871. | `--port` | 22 | Quick start: SSH port |
  872. | `--key` | — | Quick start: Path to private key |
  873. | `--workdir` | — | Quick start: Working directory for commands and sessions |
  874. | `--group` | prod | Quick start: Policy tier — `prod`, `staging` or `dev` |
  875. | `--timeout` | 60000 | Command timeout in ms |
  876. | `--maxChars` | 5000 | Max command length (`none` or `0` disables the limit; in a config file the same setting is `commandMaxChars = 0`) |
  877. | `--sessionMax` | 5 | Max concurrent sessions per connection |
  878. | `--sessionTtl` | 600000 | Idle timeout of an SSH session in ms |
  879. | `--transport` | stdio | `stdio` or `http` |
  880. | `--httpPort` | 3000 | HTTP transport port |
  881. | `--httpHost` | 127.0.0.1 | HTTP bind address |
  882. | `--bearerToken` | — | Bearer token for HTTP transport auth (required for `--transport=http`) |
  883. | `--rateLimit` | 0 | Max authenticated requests per minute, per client (0 = unlimited) |
  884. | `--httpSessionTtl` | 1800000 | Idle timeout of an MCP client session over HTTP, in ms (a session with a request in flight or an open SSE stream does not expire). At the 64-session cap a new client evicts the least recently active session with no request in flight, one holding an SSE stream only when no other can go |
  885. | `--authFailureLimit` | 10 | Failed bearer-auth attempts allowed per client per minute (0 = off) |
  886. | `--trustProxy` | false | Read the client address from `X-Forwarded-For`, but only when the peer is the proxy — bare means a loopback peer |
  887. | `--trustedProxies` | — | Comma-separated peer addresses allowed to send `X-Forwarded-For`. Empty means loopback only |
  888. | `--allowedHosts` | bind address + localhost | Comma-separated Host headers accepted by the DNS-rebinding guard |
  889. | `--hostKeyMode` | `tofu` | `tofu \| strict \| insecure`. `strict` accepts only hosts pinned with `trustedHostKey`. See [SECURITY.md](./SECURITY.md#host-key-trust-does-not-survive-a-restart) |
  890. | `--insecureHostKey` | false | Disable host key verification for hosts with no `trustedHostKey` — a pin still refuses (test only!) |
  891. | `--allowUncheckedConfigAcl` | false | Windows: report every ACL finding and refuse none |
  892. | `--strictConfigAcl` | false | Windows: refuse on every ACL finding, including a read-only over-grant |
  893. | `--disableApproval` | false | Skip the approval gate (quick start profile only) |
  894. | `--opaUrl` | — | OPA sidecar URL for external policy |
  895. | `--opaFailClosed` | false | Refuse every command while OPA is unreachable, instead of falling back to local policy |
  896. | `--opaTimeoutMs` | 10000 | How long to wait for the OPA sidecar. Lower makes the fail-open cheaper to reach; higher makes an outage slower to notice |
  897. | `--commandQuota` | 0 (off) | Max commands per rolling 24h per profile |
  898. | `--approvalGrantTtl` | 0 (off) | Auto-approve an identical command for this many ms after approval |
  899. | `--auditEntropyScan` | false | Enable entropy-based secret scanning in audit |
  900. | `--auditTamperEvident` | false | Enable hash-chained tamper-evident audit log |
  901. | `--otelEndpoint` | — | OTLP/HTTP endpoint for OpenTelemetry traces |
  902. | `--otelServiceName` | ssh-mcp | Service name reported on trace spans |
  903. | `--dumpToolHashes` | — | Print SHA-256 hashes of the tool descriptions and exit |
  904. ---
  905. ## Migrating from v1
  906. v2 is a breaking release. Passing a removed flag now fails at startup with the
  907. replacement, rather than failing later as a confusing auth error.
  908. ### Tools
  909. | v1 | v2 | Notes |
  910. |----|----|-------|
  911. | `exec` | `read-command` | Allowlisted read-only commands. Prefer this for reads. |
  912. | `exec` | `run-command` | Arbitrary commands. Destructive and privileged ones go through the approval gate, unless `approvalPolicy = "auto"`. |
  913. | `sudo-exec` | `privileged-command` | Requires approval unless `approvalPolicy = "auto"`. Password is piped via stdin. |
  914. | `description` parameter | — | Removed. It was an injection vector (#44) and never reached the host. |
  915. **Command results now carry status.** In v1 a failed command rejected with
  916. `Error (code N)`. In v2 a non-zero exit comes back as an error result including
  917. the exit code and stderr — so an empty response no longer means "it worked".
  918. ### Flags
  919. | v1 flag | Replacement |
  920. |---------|-------------|
  921. | `--password` | `SSH_MCP_PASSWORD` env var (or `SSH_MCP_<PROFILE>_PASSWORD`) |
  922. | `--suPassword` | `SSH_MCP_SUDO_PASSWORD` env var |
  923. | `--sudoPassword` | `SSH_MCP_SUDO_PASSWORD` env var |
  924. | `--disableSudo` | Use a role/policy that disallows the `privileged` class |
  925. Credentials moved off the command line because CLI arguments are world-readable
  926. via `/proc/<pid>/cmdline` on Linux (CWE-214). Credentials now resolve through an
  927. SSH agent → OS keychain → env var → key file cascade.
  928. ### Example
  929. ```jsonc
  930. // v1
  931. { "command": "npx", "args": ["ssh-mcp", "--host=1.2.3.4", "--user=root", "--password=hunter2"] }
  932. // v2 — credentials via env
  933. {
  934. "command": "npx",
  935. "args": ["ssh-mcp", "--host=1.2.3.4", "--user=root"],
  936. "env": { "SSH_MCP_PASSWORD": "hunter2" }
  937. }
  938. ```
  939. For more than one host, move to a TOML config file (see [Configuration](#configuration))
  940. and pass `--config <path>`; profiles carry per-host roles and approval policy.
  941. ### Host key verification
  942. v1 did not verify host keys. v2 defaults to trust-on-first-use and records the
  943. key **in memory, for the life of the process**; a later mismatch in that same
  944. process fails the connection. Nothing is written to disk and `~/.ssh/known_hosts`
  945. is not consulted, so a restart accepts afresh — see
  946. [SECURITY.md](./SECURITY.md#host-key-trust-does-not-survive-a-restart). Pin
  947. explicitly with `trustedHostKey` in a profile, which is the only control here that
  948. survives a restart — and which no host key mode overrides, so `--insecureHostKey`
  949. is an opt-out only for hosts you have not pinned (test environments only).
  950. ---
  951. ## Testing
  952. ```bash
  953. # Start test SSH servers. --build matters: compose reuses an existing image, and a
  954. # fixture change (such as the alpine target's AcceptEnv line) then never lands,
  955. # which shows up as a product failure in the integration suite.
  956. docker compose --profile test up -d --build
  957. # Run all tests
  958. npm test
  959. # Run only unit tests
  960. npm test -- test/unit/
  961. # Run with coverage
  962. npm run coverage
  963. ```
  964. ## MCP Inspector
  965. ```bash
  966. npm run inspect
  967. ```
  968. ---
  969. ## Contributing
  970. See [CONTRIBUTING.md](./CONTRIBUTING.md). Please follow the [security checklist](./SECURITY.md#security-checklist-for-contributors) in all PRs.
  971. ## Support
  972. If you find SSH MCP Server helpful, consider starring the repository or [sponsoring](https://github.com/sponsors/tufantunc)!
  973. ## Listed on
  974. [![SSH MCP Server on Glama](https://glama.ai/mcp/servers/tufantunc/ssh-mcp/badge)](https://glama.ai/mcp/servers/tufantunc/ssh-mcp)
  975. Also on the [official MCP registry](https://registry.modelcontextprotocol.io) as `io.github.tufantunc/ssh-mcp`.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.