Skip to main content
Glama
ssh-sftp-mcp

ssh-sftp-mcp

by endjoker

ssh-sftp-mcp

独立的 SSH / SFTP MCP Server,走标准 MCP 协议(stdio)。任何兼容 MCP 的客户端(Claude Desktop、Cursor、DSH、自研 Agent…)都能直接拉起使用,不依赖任何特定客户端框架。

  • 远端命令:短命令同步返回,长命令后台任务 + 轮询 + 取消

  • SFTP:列目录、stat、流式上传/下载(文件内容不进模型上下文)

  • 连接复用:一次 ssh_connect,后续 exec / SFTP 共用一个 SSH 会话

  • 认证:私钥、SSH Agent、本机环境变量里的密码(工具参数中不出现明文密码)

  • 主机密钥强制校验:未知或变更的 key 一律拒绝,不自动信任首次连接

⚠️ 高权限工具:允许连接任意可达主机,并读写运行账号有权访问的任意本地路径。请用专用低权限账号运行,只在可信的 MCP 会话中启用。

环境要求

  • Node.js ≥ 24

  • 远端 SSH 服务端已启用 SFTP subsystem(OpenSSH 默认启用)

  • 上传默认使用 hardlink@openssh.com(OpenSSH ≥ 5.7 均支持);其他实现见覆盖与原子性

Related MCP server: Personal Linux Remote MCP Gateway

安装

git clone https://github.com/endjoker/ssh-sftp-mcp.git
cd ssh-sftp-mcp
npm ci
npm run build
node dist/src/index.js --version

想直接用命令名,可以 npm link,之后把 ssh-sftp-mcp 当作 MCP 的 command。

npm 12+ 默认拦截依赖安装脚本;ssh2 的 install.js 只构建可选原生加速模块,被拦截不影响使用(纯 JS 回退路径已验证)。

配置到 MCP 客户端

服务不监听端口,由 MCP 客户端以子进程方式启动。下面是通用形式,字段名按你的客户端调整:

{
  "mcpServers": {
    "ssh-sftp": {
      "command": "node",
      "args": ["/absolute/path/to/ssh-sftp-mcp/dist/src/index.js"],
      "env": {
        "SSH_MCP_KNOWN_HOSTS": "/home/me/.ssh/known_hosts"
      }
    }
  }
}

Windows 示例(路径用正斜杠或双反斜杠):

{
  "mcpServers": {
    "ssh-sftp": {
      "command": "node",
      "args": ["C:/tools/ssh-sftp-mcp/dist/src/index.js"],
      "env": {
        "SSH_MCP_KNOWN_HOSTS": "C:/Users/me/.ssh/known_hosts"
      }
    }
  }
}

密码认证时,把密码放进客户端配置的 env(不要写进仓库):

"env": {
  "SSH_MCP_KNOWN_HOSTS": "C:/Users/me/.ssh/known_hosts",
  "SSH_MCP_PASSWORD_PROD": "your-password"
}

快速开始

1. 准备 known_hosts

服务不会自动信任新主机。首次连接前,用独立可信渠道核对指纹后写入:

ssh-keyscan -p 22 10.0.0.5 >> ~/.ssh/known_hosts   # 只是草稿,指纹要另外核对
# 或直接 ssh 登录一次并人工确认
ssh 10.0.0.5

非 22 端口必须写 [host]:port 形式,ssh -p 2222 host 首次连接会自动这样记录。本服务也支持 OpenSSH 的 hashed host(|1|salt|hash)、通配符、! 否定与 @revoked。

2. 连接

{
  "host": "10.0.0.5",
  "port": 22,
  "username": "ops",
  "auth": { "type": "keyPath", "keyPath": "C:/Users/me/.ssh/id_ed25519" }
}

返回 connectionId,后续调用都带上它。

3. 执行命令

{ "connectionId": "c_...", "command": "uptime && df -h /" }

4. 传输文件

// 小文件:同步,直接等结果
{ "connectionId": "c_...", "localPath": "D:/tmp/app.log", "remotePath": "/var/log/app.log" }

// 大文件:后台任务
{ "connectionId": "c_...", "localPath": "D:/tmp/big.bin", "remotePath": "/tmp/big.bin" }
// → sftp_upload_start,返回 transferId
{ "transferId": "x_..." }   // sftp_transfer_status 查进度/结果

5. 长任务

{ "connectionId": "c_...", "command": "systemctl restart app && journalctl -u app -n 200" }
// → ssh_exec_start 返回 taskId,用 ssh_task_poll 按偏移取增量输出

认证方式

方式

参数

说明

私钥

{"type":"keyPath","keyPath":"..."}

私钥口令用 passphraseEnv 引用环境变量

Agent

{"type":"agent"}

POSIX 用 SSH_AUTH_SOCK;Windows 未设置时尝试 Pageant

密码

{"type":"password","passwordEnv":"SSH_MCP_PASSWORD_X"}

变量名必须以 SSH_MCP_PASSWORD_ 开头,值不进工具参数

认证失败就是失败,不会静默换用其他方式。

工具

工具

作用

ssh_connect

建立连接,返回 connectionId

ssh_exec

执行短时非交互命令(无 PTY)

ssh_exec_start

启动长任务,返回 taskId

ssh_task_poll

按 stdout/stderr 偏移增量取输出

ssh_task_cancel

请求关闭任务通道(不保证远端进程已终止)

ssh_connection_list

列出本进程持有的连接

ssh_disconnect

关闭连接(幂等)

sftp_list

列远端目录(游标分页)

sftp_stat

查看远端元数据(默认 lstat)

sftp_download / sftp_upload

同步传输

sftp_download_start / sftp_upload_start

后台传输,立即返回 transferId

sftp_transfer_status

查询进度、阶段、目标状态与最终结果

sftp_transfer_cancel

取消进行中的传输

sftp_transfer_list

当前与近期传输记录

diagnostics_recent

查看本进程脱敏诊断事件(无需读 stderr)

大文件与超时

MCP 客户端通常对单次工具调用有超时(常见 60 秒),而大文件传输可能更久。大文件请用 *_start + sftp_transfer_status 轮询,不要用同步工具硬等。

  • 进度包含:已处理字节、总字节、校验字节、阶段(preparing / transferring / verifying / publishing / cleaning / done)、目标状态(untouched / published / unknown / may_be_partial)

  • 同步调用在客户端超时被取消时,服务端会中止传输并清理临时文件,不会留下占位任务或一直占用并发槽位

  • 有可信 SHA-256 时传 expectedSha256:单遍核对传输流,不需要回读;未提供时结果里 expectedSha256Matched 为 null

  • verifyAfterWrite=true 会额外回读目的端比对,大文件上会明显增加耗时

  • 取消在 publishing 阶段之后不保证撤销,请继续查询最终状态

实测参考(家用宽带 → 云主机,仅供预期管理):50 MB 上传约 45–90 秒,50 MB 下载约 2 分钟;下行明显慢于上行时以实际链路为准。

覆盖与原子性

  • 默认 overwrite=false:目标已存在返回 FILE_EXISTS

  • 本地发布:同目录临时文件 + 硬链接(目标存在即失败,天然原子)

  • 远端发布:hardlink@openssh.com 原子不覆盖

  • 服务器/文件系统不支持时返回 ATOMIC_NO_OVERWRITE_UNSUPPORTED,不会退化成可能覆盖;确需降级时显式传 allowNonAtomicNoOverwrite=true(排他创建直接写目标,失败或取消可能留下部分文件)

  • overwrite=true:优先 posix-rename@openssh.com 原子替换,否则普通 rename 并在结果中 atomicPublish=false

  • 失败路径会清理临时文件(远端清理最多等 2 秒)

环境变量

变量

默认

说明

SSH_MCP_KNOWN_HOSTS

~/.ssh/known_hosts

主机密钥库,不可关闭校验

SSH_MCP_ENABLE_PASSWORD_AUTH

true

是否允许 passwordEnv 认证

SSH_MCP_PASSWORD_ENV_PREFIX

SSH_MCP_PASSWORD_

允许的密码变量名前缀

SSH_MCP_MAX_CONNECTIONS

8

并发 SSH 连接上限

SSH_MCP_MAX_CHANNELS_PER_CONNECTION

4

每连接活动通道上限

SSH_MCP_MAX_ACTIVE_TRANSFERS

2

并发传输上限

SSH_MCP_IDLE_TIMEOUT_MS

600000

空闲连接回收(最长 24h)

SSH_MCP_CONNECT_TIMEOUT_MS

15000

建连超时

SSH_MCP_EXEC_TIMEOUT_MS

30000

命令默认超时

SSH_MCP_MAX_EXEC_TIMEOUT_MS

600000

单次命令超时上限

SSH_MCP_MAX_OUTPUT_BYTES

1048576

同步命令每条流输出上限

SSH_MCP_TASK_OUTPUT_BUFFER_BYTES

4194304

每个长任务输出缓冲

SSH_MCP_TASK_MAX_LIFETIME_MS

3600000

长任务最长存活时间

SSH_MCP_MAX_TASKS

16

在途长任务上限

SSH_MCP_TRANSFER_TIMEOUT_MS

3600000

单次传输服务端时限

SSH_MCP_TRANSFER_RATE_LIMIT_BPS

0

传输限速,0 = 不限

SSH_MCP_LOG_LEVEL

warn

debug/info/warn/error/silent,只写 stderr

安全模型

按设计,本服务不做应用层主机白名单、本地路径根目录限制或文件大小上限:

  • ssh_connect 可连接进程网络层可达的任意地址(含 localhost、内网),可被当作网络探测入口

  • sftp_upload / sftp_download 可读写运行账号有权访问的任意常规文件;路径检查只防语法错误与意外跟随链接,不是访问控制

  • 实际边界是 OS 账户、文件 ACL 与出站防火墙;请用专用低权限账号运行,不要用 root/管理员

  • 不会自动信任主机密钥;密码值不进工具参数与日志;默认不覆盖;不提供远端删除

stdio 模式下每个客户端各自拉起一个 Server 进程,连接与任务不跨进程共享。

已知限制

  • 无 PTY / 交互式 shell / stdin 输入

  • 无 delete / chmod / 递归目录传输 / 断点续传

  • 仅 stdio 传输(HTTP 需另行设计认证与隔离)

  • 不支持 keyboard-interactive / OTP

  • 远程路径默认按 POSIX 处理;Windows OpenSSH 服务端可用 remotePathStyle=windows(如 C:\data\a.txt 会转换为 /C:/data/a.txt)

  • 长任务状态与传输记录只在进程内存中,重启丢失;断线后标记 unknown_after_disconnect,不自动重放

  • 协议版本为 MCP 2025-11-25(固定依赖的 SDK 支持上限);不宣称支持更新的草案版本

常见错误

错误码

含义与处理

HOST_KEY_NOT_TRUSTED

主机不在 known_hosts 或密钥已变;核对指纹后写入,不要跳过

AUTH_FAILED

认证失败 / 密码变量未设置 / 密码认证被禁用

FILE_EXISTS

目标已存在且 overwrite=false

ATOMIC_NO_OVERWRITE_UNSUPPORTED

服务器不支持原子不覆盖发布;换服务器或显式 allowNonAtomicNoOverwrite=true

LIMIT_EXCEEDED

连接/通道/传输/任务数达上限,先释放或调大对应环境变量

TRANSFER_NOT_FOUND

transferId 不存在或已过期(保留 128 条 / 1 小时)

TRANSFER_CANCELLED / TRANSFER_TIMEOUT

传输被取消或超过服务端时限,目标未被发布

开发与测试

npm run build
npm test                 # 单元测试
npm run test:integration # 集成测试(内置 ssh2 测试服务端,无需系统 sshd)
npm run test:all

真实 OpenSSH 的手动验证脚本(需要自备临时 sshd 与测试密钥):

E2E_HOST_KEY="ssh-ed25519 AAAA..." \
E2E_CLIENT_KEY_B64="$(base64 -w0 clientkey)" \
E2E_USERNAME=test E2E_PORT=2222 \
node scripts/e2e-real-openssh.mjs

License

MIT

Available Tools

17 tools
diagnostics_recentB
Read-onlyIdempotent

Shows recent redacted diagnostic events in this process, optionally filtered by transferId.

Inputs: limit, transferId. Returns: events

sftp_downloadA
Destructive

Downloads to a local path writable by the server account. Publishes atomically and refuses to overwrite by default. This call waits for the transfer to finish. Use the matching *_start tool for long transfers.

Inputs: localPath (required), remotePath (required), connectionId (required), overwrite, +3 more. Returns: bytes, sha256, verified, localPath, +6 more

sftp_download_startA
Destructive

Downloads to a local path writable by the server account. Publishes atomically and refuses to overwrite by default. Returns a transferId immediately; query progress and the final result with sftp_transfer_status.

Inputs: localPath (required), remotePath (required), connectionId (required), overwrite, +3 more. Returns: error, phase, state, result, +10 more

sftp_listList a remote directoryA
Read-onlyIdempotent

Lists remote directory entries sorted by name, with name, type, size, mtime and permission string; file contents are never returned. Large directories are paged with nextCursor; cursors are valid only in this process and are not a consistent snapshot under concurrent changes.

Inputs: remotePath (required), connectionId (required), cursor, pageSize, +1 more. Returns: entries, pageSize, truncated, nextCursor, +2 more

sftp_statStat a remote pathA
Read-onlyIdempotent

Reads remote file/directory metadata. Defaults to lstat without following symlinks; set followSymlink=true to read the link target. File contents are never read.

Inputs: remotePath (required), connectionId (required), followSymlink, remotePathStyle. Returns: gid, uid, mode, note, +7 more

sftp_transfer_cancelA
DestructiveIdempotent

Cancels an in-flight transfer; keep polling until cleanup finishes. Once publishing has started the cancel cannot be guaranteed, so check the final state.

Inputs: transferId (required). Returns: error, phase, state, result, +10 more

sftp_transfer_listA
Read-onlyIdempotent

Lists current and recent transfers, including in-flight legacy synchronous calls and their transferId.

Inputs: no named parameters. Returns: transfers

sftp_transfer_statusA
Read-onlyIdempotent

Returns transfer state, bytes processed, bytes verified and the final result. If the publish acknowledgement was lost, targetState=unknown - check the target before retrying.

Inputs: transferId (required). Returns: error, phase, state, result, +10 more

sftp_uploadA
Destructive

Uploads a local file readable by the server account. Publishes atomically via a remote hardlink and refuses to overwrite by default. allowNonAtomicNoOverwrite=true writes the target directly with exclusive create and may leave a partial file on failure. This call waits for the transfer to finish. Use the matching *_start tool for long transfers.

Inputs: localPath (required), remotePath (required), connectionId (required), overwrite, +4 more. Returns: bytes, sha256, verified, localPath, +6 more

sftp_upload_startA
Destructive

Uploads a local file readable by the server account. Publishes atomically via a remote hardlink and refuses to overwrite by default. allowNonAtomicNoOverwrite=true writes the target directly with exclusive create and may leave a partial file on failure. Returns a transferId immediately; query progress and the final result with sftp_transfer_status.

Inputs: localPath (required), remotePath (required), connectionId (required), overwrite, +4 more. Returns: error, phase, state, result, +10 more

ssh_connectConnect via SSHA

Connects to any host supplied by the caller (no application-level allowlist) and returns a connectionId; later exec/SFTP calls reuse the same SSH session. Auth supports a private key path, SSH Agent, or a password held in a local environment variable; passwords never appear in tool arguments. The host key must already exist in known_hosts; unknown or changed keys are always rejected (first-use keys are never trusted automatically). This tool lets the server process connect to any address reachable on the network (including localhost and private networks); the actual scope is bounded by the host firewall.

Inputs: auth (required), host (required), username (required), port, +1 more. Returns: host, port, state, reused, +4 more

ssh_connection_listList SSH connectionsA
Read-onlyIdempotent

Lists metadata for SSH connections held by this server process (no private keys, passwords, or full command history).

Inputs: no named parameters. Returns: count, connections

ssh_disconnectClose an SSH connectionA
DestructiveIdempotent

Closes the connection and its SFTP/exec channels and releases related task buffers. Idempotent: an already closed or unknown connection returns closed=false. Unfinished tasks on that connection end up as failed or unknown_after_disconnect.

Inputs: connectionId (required). Returns: closed, connectionId, affectedTasks, alreadyClosed

ssh_execRun a short remote commandA
Destructive

Runs a non-interactive command on the remote host (no PTY, no stdin) and returns stdout/stderr/exit code. The command has the full shell privileges of that SSH account and may cause any remote side effect; the server does not block commands by keyword. Output is byte-capped; timeouts and truncation are reported explicitly. Use ssh_exec_start for long-running work.

Inputs: command (required), connectionId (required), timeoutMs, outputFormat. Returns: signal, stderr, stdout, exitCode, +5 more

ssh_exec_startStart a long-running commandA
Destructive

Starts a long-running non-interactive remote command and returns a taskId immediately; poll output increments with ssh_task_poll and stop it with ssh_task_cancel. Task state and output buffers live only in this server process; after a restart or disconnect the remote state cannot be confirmed (marked unknown_after_disconnect), and commands are never replayed automatically. Cancel only closes the SSH channel owned by this server; it does not guarantee that the remote process or its children have terminated.

Inputs: command (required), connectionId (required), timeoutMs. Returns: state, taskId, startedAt, connectionId

ssh_task_cancelCancel a long-running taskA
DestructiveIdempotent

Requests closing the SSH exec channel owned by this task. channelCloseConfirmed reports whether a channel close or a remote exit status was observed; that only means the request was acknowledged by the server or remote side, and does not prove the remote command or its children have terminated.

Inputs: taskId (required). Returns: note, state, signal, taskId, +7 more

ssh_task_pollPoll a long-running taskA
Read-onlyIdempotent

Returns task state and reads stdout/stderr increments from independent byte offsets. Returns running immediately when there is no new output; it never blocks. Pass stdoutAfterOffset / stderrAfterOffset and use the returned nextOffset of each stream; gaps from buffer recycling are reported in the droppedBeforeOffset of that stream.

Inputs: taskId (required), maxBytes, outputFormat, stderrAfterOffset, +1 more. Returns: note, state, buffer, signal, +9 more

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.6/5.0

    Scored across 17 tools

    Disambiguation4/5

    Each tool maps to a distinct resource+action, and the sync/async pairs (ssh_exec vs ssh_exec_start, sftp_download vs sftp_download_start) are separated by the explicit `_start` suffix and by descriptions that say one returns immediately and the other blocks. Minor residual overlap exists between sftp_transfer_list and diagnostics_recent (both surface transfer info) and between ssh_task_cancel and sftp_transfer_cancel, but the SSH-task vs SFTP-transfer domains keep them distinguishable.

    Naming Consistency3/5

    There is a stable prefix scheme (ssh_, sftp_, diagnostics_), but the element order inside names varies: ssh_connection_list and sftp_transfer_list put the noun before the verb, while sftp_list, ssh_disconnect and ssh_task_poll put the verb last, and ssh_task_poll/sftp_transfer_status use different verbs for the same 'check progress' concept. The result is readable but not a single predictable pattern.

    Tool Count4/5

    Seventeen tools is slightly above the comfortable range, but nearly every one is justified by the sync/async split (exec, upload, download each need a start/status/cancel triple) plus lifecycle and diagnostics. There is little obvious dead weight, though the async scaffolding is what pushes the count up.

    Completeness3/5

    Connection lifecycle, command execution, async task control, and file transfer are well covered, including progress, cancel, and diagnostics. However, the SFTP surface has notable gaps: no mkdir, rename/move, delete/remove, or chmod/permission change operations, so an agent cannot do routine remote file management without dropping to ssh_exec. There is also no way to enumerate active tasks (only connections and transfers are listable).

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Enables remote command execution and SFTP file upload or download from any MCP client without a local SSH client, SCP, or PuTTY installed. Supports password or private key authentication with SHA256 host fingerprint verification, timeouts, output limits, and multiple configured server instances.
      5
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables MCP clients to manage remote Linux terminals over SSH, supporting multi-host and jump-host command execution, background task control, and SFTP file writes, edits, and verified uploads.
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables MCP clients to establish interactive-authenticated SSH sessions to explicitly configured targets, run and manage bounded background jobs, and transfer bounded UTF-8 text files over SFTP.
      MIT