@pyrokine/mcp-ssh 2.4.3 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,6 +11,26 @@ SSH MCP Server for AI assistants (Claude, Cursor, Windsurf, etc.)
11
11
  ![Linux](https://img.shields.io/badge/Linux-tested-success) ![macOS](https://img.shields.io/badge/macOS-untested-yellow)
12
12
  ![Windows](https://img.shields.io/badge/Windows-untested-yellow)
13
13
 
14
+ ## Migrating to 3.0
15
+
16
+ `maxOutputSize` now limits each exec stdout/stderr response by UTF-8 bytes instead of JavaScript string length.
17
+ Recalculate budgets for non-ASCII output and check `stdoutTruncated` / `stderrTruncated`; `maxOutputSize=3` can return
18
+ one Chinese character, not three. Text responses end at a complete character boundary.
19
+
20
+ PTY `bufferSize` and list-result `bufferSize`, together with `unreadRawBytes` and `rawBufferLimit` in read/list results,
21
+ now count raw bytes. A raw read with `clear=true` returns the counts and `rawBufferTruncated` state before clearing; the
22
+ next read reflects the cleared buffer. Use `dataBase64` for exact ANSI or binary output and `data` for a UTF-8 preview.
23
+
24
+ File reads accept `encoding` (`auto`, `utf8`, `utf16le`, `utf16be`, `gbk`) and lossless `binary=true`. Keep offsets in
25
+ bytes and continue with `next_offset`; choose an explicit UTF-16 encoding for nonzero offsets. A budget too small for
26
+ the next complete text character returns an error instead of an empty page; malformed encoding at EOF also fails. Binary
27
+ reads advance byte by byte. `lineRange` metadata describes only the returned prefix, including whether its last line
28
+ ends with a newline.
29
+
30
+ Windows connections require `remotePlatform="windows"`; local Windows does not change the remote default. Set
31
+ `commandShell` and `remotePathStyle` for the host, and an explicit `rsyncProfile` when using rsync with Windows. The
32
+ Windows behavior and examples below remain available.
33
+
14
34
  ## Features
15
35
 
16
36
  - **Multiple Authentication**: Password, SSH key
@@ -108,6 +128,9 @@ Add to your MCP settings (e.g., `~/.claude/settings.json` or client-specific con
108
128
  `ssh_list_sessions()` returns only `alias`, canonical `identity`, `runAs`, `connected`, and `lastUsedAt`. Use
109
129
  `detail=true` for connection details or `fields=[...]` to select fields. Neither mode returns `keyPath`.
110
130
 
131
+ Connections enable TCP_NODELAY to reduce waiting between interactive commands and small-file SFTP requests. Direct,
132
+ jump-host, and replacement connections share this behavior without an additional option.
133
+
111
134
  `ssh_reconnect` invalidates operations, PTYs, forwards, and cached transfer capability bound to the old client before
112
135
  the replacement connection is published. Automatic reconnect timers are bound to the session and client that scheduled
113
136
  them, so an old timer cannot disconnect a newer session with the same alias. A delayed `close` from the old client
@@ -126,6 +149,10 @@ pending, a channel returned by the delayed callback is destroyed before the conn
126
149
  | `ssh_quick_exec` | One-shot: connect, execute, disconnect |
127
150
  | `ssh_exec_script` | Upload and run a temporary remote script |
128
151
 
152
+ For a Windows remote, `ssh_exec_script` saves PowerShell scripts as UTF-8 with BOM so Windows PowerShell reads Unicode
153
+ correctly. CMD scripts switch to code page 65001 before running UTF-8 commands; an unavailable code page stops
154
+ execution. POSIX scripts retain their original content.
155
+
129
156
  ### Tracked operations
130
157
 
131
158
  | Tool | Description |
@@ -133,7 +160,7 @@ pending, a channel returned by the delayed callback is destroyed before the conn
133
160
  | `ssh_operation_start` | Start a tracked long-running remote command |
134
161
  | `ssh_operation_status` | Read status, PID, exit code, and output counters |
135
162
  | `ssh_operation_read` | Read bounded stdout and stderr by byte offset |
136
- | `ssh_operation_cancel` | Verify the operation marker, then send TERM |
163
+ | `ssh_operation_cancel` | Verify process identity before cancellation |
137
164
  | `ssh_operation_list` | List unexpired operations, optionally by alias |
138
165
 
139
166
  ### File Operations
@@ -169,6 +196,60 @@ pending, a channel returned by the delayed callback is destroyed before the conn
169
196
  | `ssh_forward_close` | Close port forwarding |
170
197
  | `ssh_forward_list` | List all port forwards |
171
198
 
199
+ ## Windows and cross-platform SSH
200
+
201
+ Set `remotePlatform="windows"` on connections to a Windows host. The default is `posix`, regardless of the client's OS.
202
+ Use `commandShell="powershell"` (default on Windows) or `"cmd"`, and set `remotePathStyle="win32"` (default) or
203
+ `"sftp-posix"` if the server exposes `/C:/...` paths. `cwd` and `env` are grouped with the command in the selected
204
+ shell; unsupported cmd expansion in injected values is rejected. `ssh_quick_exec` also accepts `remotePlatform`,
205
+ `commandShell`, and `agent`. Windows `runAs`, `ssh_exec_as_user`, and `ssh_exec_sudo` return
206
+ `unsupported_remote_platform` before issuing a remote command.
207
+
208
+ ```text
209
+ ssh_connect(host="example.com", user="tester", agent="\\\\.\\pipe\\openssh-ssh-agent", remotePlatform="windows", commandShell="powershell", remotePathStyle="win32", rsyncProfile="native-win32")
210
+ ssh_exec(alias="tester@example.com:22", command="Get-Location", cwd="C:\\Test Data", env={REGION:"test"})
211
+ ssh_read_file(alias="tester@example.com:22", remotePath="C:\\Test Data\\report.txt", lineRange="1-20", encoding="utf16le")
212
+ ```
213
+
214
+ `ssh_connect(agent="...")` passes the socket or pipe to ssh2, including OpenSSH named pipes and ssh2's `agent="pageant"`
215
+ on Windows. SSH config `IdentityAgent` supplies a socket when there is no explicit agent or private key.
216
+ `IdentityAgent none` (or `agent="none"`) disables agent authentication and environment socket fallback, including with a
217
+ private key and on ProxyJump hosts; password and key authentication remain available. An explicit argument or template
218
+ `agent` takes precedence over SSH config. Reconnect preserves this choice, and external OpenSSH/rsync also disables the
219
+ environment agent when `none` is selected. The connection result reports `remotePlatform`, `commandShell`,
220
+ `remotePathStyle`, and `keyAclStatus` for Windows private keys. Existing private keys are checked but never modified:
221
+ `key_acl_insecure` and `key_acl_unverified` reject authentication. Windows session files and temporary downloads receive
222
+ and verify private DACLs before they contain data. Windows scripts and atomic uploads create an empty temporary file
223
+ through SFTP, verify its DACL, then write content; cleanup uses SFTP. Windows tracked operations report the PID and
224
+ creation time. Cancellation checks the process command line for its random marker and creation time before
225
+ `taskkill /T /F`; `cancellationStatus` reports `requested`, `unknown`, or `unsupported` without treating a closed SSH
226
+ channel as proof of cancellation. Windows ACL and process behavior need a native Windows or Windows SSH host for
227
+ end-to-end verification.
228
+
229
+ `ssh_read_file` reads `lineRange` through SFTP, including CRLF and UTF-8, UTF-16LE/BE, or GBK (`encoding="auto"` detects
230
+ a BOM at the start). `binary=true` returns the bytes as base64 in `content` and `content_base64`. Byte offsets apply to
231
+ the remote file. GBK byte-offset reads and tails are rejected because a random byte offset cannot prove a GBK character
232
+ boundary; use `lineRange` or `binary=true`. Use an explicit UTF-16 encoding for nonzero offsets. `maxOutputSize` for
233
+ exec caps each stdout/stderr text body by UTF-8 bytes; `stdoutTruncated` and `stderrTruncated` signal truncation
234
+ separately. PTY raw reads include `dataBase64` containing the unmodified buffered bytes; `data` remains a text preview.
235
+
236
+ Directory verification traverses SFTP with entry, depth, file-size, and total-hash budgets; POSIX `verify.owner` and
237
+ `verify.mode` are rejected on Windows. For a Windows directory, `verify.aclSddl` compares the expected DACL SDDL of the
238
+ remote root separately. `ssh_upload(atomic=true)` checks the SFTP `posix-rename@openssh.com` capability before
239
+ transferring data to replace an existing target; unsupported or unverified replacement leaves that target untouched.
240
+ `ssh_sync` uses `rsyncProfile` (`posix`, `native-win32`, `msys2`, `cygwin`) and optional `rsyncExecutable` on the
241
+ remote. A Windows local client or remote host requires an explicit profile for rsync; unavailable probes use SFTP with
242
+ `selectedTransport` and `decisionReason` reported. Transfer errors after rsync starts do not imply the remote state is
243
+ known.
244
+
245
+ Before either upload transport starts, Windows directory sync checks source names after `exclude` and `followSymlinks`
246
+ are applied. Potential collisions are compared using Windows ordinal case rules and the existing destination parent
247
+ directory's case-sensitive flag. A confirmed collision returns `windows_filename_collision`; a missing parent,
248
+ unavailable shell, timeout, or incomplete query returns `case_semantics_unverified` before any upload or directory
249
+ creation, including in dry-run mode. Already-existing case-sensitive directories can keep case-distinct names. The check
250
+ does not infer rules for new directories from their ancestors. No candidate means no additional PowerShell or exec
251
+ requirement, so SFTP-only uploads remain supported; POSIX uploads retain their name semantics.
252
+
172
253
  ## Usage Examples
173
254
 
174
255
  ### Using SSH Config (Recommended)
@@ -301,9 +382,16 @@ user; otherwise a per-call `runAs` overrides the session `runAs`; otherwise the
301
382
  `ssh_exec` and `ssh_exec_as_user` return execution metadata: `loginUser`, `effectiveUser`, `identity`, `cwd`,
302
383
  `resolvedCwd`, `shell`, `profileLoaded`, `envInjectedKeys`, `failureKind`, `stdoutBytes`, `stderrBytes`, and truncation
303
384
  hints. Large output returns `stdoutHead`, `stdoutTail`, `stderrHead`, `stderrTail`, and `recommendedReadCommand`.
304
- Timeout errors include the same head/tail fields from output produced before the timeout. Commands with destructive,
305
- process-control, service-control, credential-bearing, unbounded `find`, recursive `grep`, long pipelines, background
306
- tasks, direct `su - user -c`, or long-running patterns return a `commandRisk` block with `categories` and `signals`.
385
+ Timeout errors include the same head/tail fields from output produced before the timeout. Stdout and stderr are decoded
386
+ incrementally, so a UTF-8 character split across SSH data chunks is returned intact. `commandRisk` reports
387
+ shell-specific destructive, privilege, credential-argument, process-control, and resource-use signals; read-only
388
+ searches containing a credential word and ordinary Python/Node commands are not flagged solely for those words.
389
+
390
+ `commandRisk` is diagnostic metadata and does not change command execution or its result. POSIX classification treats
391
+ here-doc bodies as input, supports quoted and partially quoted delimiters, backslash quoting, `<<-`, and multiple
392
+ here-docs, and resumes after an exact, case-sensitive delimiter. Unquoted here-docs and double-quoted arguments still
393
+ expose active command substitutions. A Shell background `&` at EOF is reported; `&&`, redirections, escaped ampersands,
394
+ and quoted input are not background operators.
307
395
 
308
396
  ### Tracked long-running commands
309
397
 
@@ -333,6 +421,12 @@ command that emits its marker and closes immediately still enters a terminal sta
333
421
  set. If the SSH session disconnects while a tracked command is active, its status becomes `unknown`; the server does not
334
422
  claim that the remote process stopped. `ssh_exec` keeps its existing synchronous timeout behavior.
335
423
 
424
+ Tracked POSIX commands use `setsid -w` when available to wait for the command, including when `setsid` forks. Nonzero
425
+ command exits produce `failed`; a zero exit can still have stderr output. Commands execute under `sh`, so Bash-only
426
+ options such as `pipefail` require an explicit `bash -lc` command. Without `setsid`, `processGroup` is false and
427
+ cancellation targets the PID. POSIX cancellation validates the marker before sending TERM with signal syntax supported
428
+ by `sh` and Bash. System diagnostics produced during termination are retained as stderr output.
429
+
336
430
  ### Interactive Commands (PTY mode)
337
431
 
338
432
  For commands that need a terminal:
@@ -363,7 +457,9 @@ ssh_exec_script(alias="server", script=<script-above>, timeout=30000)
363
457
  ssh_read_file(alias="server", remotePath="/tmp/mcp-log-errors.txt", maxBytes=65536)
364
458
  ```
365
459
 
366
- This keeps log querying in the general command and file tools instead of adding a separate log-specific MCP surface.
460
+ This keeps log querying in the general command and file tools instead of adding a separate log-specific MCP surface. The
461
+ `ssh_exec_script.timeout` value applies while uploading the temporary script, preparing its permissions, and running it.
462
+ A stalled SFTP upload therefore ends on the requested timeout instead of using the default SFTP budget.
367
463
 
368
464
  ### With Environment Variables
369
465
 
@@ -431,24 +527,31 @@ committed it, so the response reports `operationStatus="unknown"`, `targetReplac
431
527
  cases. `verifySize`, `verifyMd5`, `verifyMode`, `verifyOwner`, and `verifyMtime` add explicit transfer checks. Parent
432
528
  and target probes, recursive directory creation, file hashing, rename, and temporary-file cleanup use SFTP. The standard
433
529
  upload path works on SFTP-only servers and does not require GNU `stat`, `md5sum`, `sha256sum`, `mkdir`, `mv`, or `rm`
434
- commands. Explicit directory manifest verification still runs remote shell commands.
530
+ commands. Directory manifest verification also reads the remote tree through SFTP.
435
531
 
436
- `ssh_download` writes to a same-directory temporary file and renames it over the requested local path after the SFTP
437
- stream closes and the transferred byte count matches the size reported by SFTP `stat`. A failed, truncated, or aborted
438
- download removes the temporary file and leaves an existing local target unchanged. SFTP directory listings reject empty
439
- names, `.` and `..`, NUL bytes, and path separators before constructing child paths.
532
+ `ssh_download` writes to a same-directory temporary file with mode `0600`, then renames it over the requested local path
533
+ after the SFTP stream closes and the transferred byte count matches the size reported by SFTP `stat`. A new target keeps
534
+ mode `0600`. Replacing a regular file preserves its `rwx` bits but does not copy setuid, setgid, or sticky bits. A
535
+ symlink, directory, or other non-regular target is rejected before the remote read starts. A failed, truncated, or
536
+ aborted download removes the temporary file and leaves an existing local target unchanged. SFTP directory listings
537
+ reject empty names, `.` and `..`, NUL bytes, and path separators before constructing child paths.
440
538
 
441
539
  Command execution results include `emptyOutputFailure=true` when the remote command exits non-zero without
442
540
  stdout/stderr, with the effective user, cwd, and a suggested follow-up read command when available. `ssh_read_file`
443
541
  defaults to 1 MiB and rejects `maxBytes` above 16 MiB before remote transfer. It returns `total_size`, `read_offset`,
444
542
  `requested_offset`, `read_bytes`, `read_end`, `next_offset`, `remaining_bytes`, `sample_kind`, and `truncated` so
445
543
  callers can distinguish a full read, head, tail, byte-range, or line-range sample. Text reads never split a UTF-8
446
- character. Use `next_offset` for the next range request.
544
+ character. Use `next_offset` for the next range request. `lineRange` scans via SFTP without running remote shell tools.
447
545
 
448
546
  `ssh_upload`, `ssh_download`, `ssh_read_file`, `ssh_write_file`, `ssh_list_dir`, `ssh_file_info`, and `ssh_mkdir` accept
449
547
  `timeout` for one SFTP operation. It defaults to 10 minutes and accepts up to one hour. A timeout returns
450
548
  `operationStatus="unknown"` and `retryable=true`; check the affected remote or local path before retrying.
451
549
 
550
+ `ssh_list_dir` and `ssh_file_info` return `mode` as the numeric `07777` permission mask and `permissions` as display
551
+ text. The text uses `s`/`S` for setuid and setgid and `t`/`T` for sticky. `verifyMode` accepts four-digit octal values
552
+ such as `4755` and permission text such as `-rwsr-xr-x`; checks compare the numeric mask rather than reconstructing it
553
+ from the display text.
554
+
452
555
  ### Directory sync with rsync or SFTP
453
556
 
454
557
  Smart sync selects rsync only for a direct connection with a validated key path or usable SSH agent. Password,
@@ -502,19 +605,22 @@ mode. Directory sources reject `recursive=false`. Relative exclude patterns are
502
605
  source root; patterns without `/` match each basename.
503
606
 
504
607
  Directory verification builds bounded local and remote manifests. It can compare entry count, an SHA-256 root manifest,
505
- owner, mode, stale entries, and deletion results. `verify.deletions=true` requires `delete=true`; it records the
506
- destination before transfer and only checks whether those deletion candidates disappeared. `staleFiles` independently
507
- checks every extra destination entry. The response contains summaries and at most 20 mismatch samples, not the full
508
- manifest. The default limits are 10,000 entries, 256 MiB per hashed file, and 1 GiB total hashed bytes. Set
509
- `verify.maxEntries`, `verify.maxFileBytes`, and `verify.maxTotalBytes` to raise them, up to 50,000 entries, 4 GiB per
510
- file, and 16 GiB total. Symlinks or unsupported filesystem entries that were skipped make verification explicitly
511
- `skipped` instead of reporting a partial match.
608
+ owner, all four octal mode digits (including setuid, setgid, and sticky), stale entries, and deletion results.
609
+ `verify.deletions=true` requires `delete=true`; it records the destination before transfer and only checks whether those
610
+ deletion candidates disappeared. `staleFiles` independently checks every extra destination entry. The response contains
611
+ summaries and at most 20 mismatch samples, not the full manifest. The default limits are 10,000 entries, 256 MiB per
612
+ hashed file, and 1 GiB total hashed bytes. Set `verify.maxEntries`, `verify.maxFileBytes`, and `verify.maxTotalBytes` to
613
+ raise them, up to 50,000 entries, 4 GiB per file, and 16 GiB total. Symlinks or unsupported filesystem entries that were
614
+ skipped make verification explicitly `skipped` instead of reporting a partial match.
512
615
 
513
616
  If verification is requested, a mismatch, skipped check, or verification error sets top-level `success=false` while
514
617
  `transferSuccess` still reports whether transfer completed. `verificationStatus`, `verificationSuccess`, and
515
618
  `failedChecks` describe the verification outcome. SFTP single-file transfers also include local and remote size, mode or
516
619
  permissions, mtime, owner/group, and a streamed SFTP SHA-256 comparison. `verifyOwner` and `verifyMode` apply to upload
517
- single-file sync; use `verify.owner` and `verify.mode` for directory manifests.
620
+ single-file sync; use `verify.owner` and `verify.mode` for directory manifests. Verification does not run `chown` or
621
+ `chmod`. New SFTP directories use destination-side default permissions, and new SFTP downloads use `0600`; replacing an
622
+ existing local regular file preserves its `rwx` bits. These permissions can differ from the source even when content and
623
+ owner match, so a requested mode check can fail after a completed transfer.
518
624
 
519
625
  Rsync is selected only for a direct connection with a validated key path or usable SSH agent. Password, inline-key, and
520
626
  jump-host sessions use SFTP because their route or credentials cannot be passed safely to a separate OpenSSH process.
@@ -561,8 +667,12 @@ ssh_pty_write(ptyId="pty_1_xxx", data="\x02d")
561
667
  ```
562
668
 
563
669
  `ssh_pty_read` and `ssh_pty_list` expose `lastInputAt`, `lastOutputAt`, `lastReadAt`, `unreadRawBytes`,
564
- `rawBufferLimit`, and `foregroundProcess` so long-running sessions can be monitored without reading the full raw stream.
565
- When a finite command exits naturally, its final screen remains readable with `active=false` until explicit close or the
670
+ `rawBufferLimit`, `rawBufferTruncated`, and `foregroundProcess`. List entries also expose `bufferSize`. These size
671
+ fields count bytes. PTY screen output is decoded incrementally. Raw output preserves the original bytes in `dataBase64`,
672
+ including invalid or partial UTF-8; `data` is a text preview. `rawBufferTruncated=true` means older raw output since the
673
+ last clear was discarded at the byte limit. A raw read uses `clear=true` by default: its response reports the pre-clear
674
+ byte count and truncation flag, then resets the raw buffer and flag. Screen reads do not clear raw state. When a finite
675
+ command exits naturally, its final screen remains readable with `active=false` until explicit close or the
566
676
  closed-session retention expires (5 minutes by default, configurable with `SSH_MCP_PTY_CLOSED_RETENTION_MS`).
567
677
  `ssh_pty_write` returns `accepted=true` when the local stream accepts data. `backpressured=true` only reports a full
568
678
  buffer and does not mean the input was discarded. `ssh_pty_close` reports `closed`, `not_found`, `failed`, or `unknown`;
@@ -614,10 +724,11 @@ stops accepting new local or remote connections as soon as close begins. Delayed
614
724
  callbacks check the same lifecycle record before changing state, so a closed forward cannot reappear in
615
725
  `ssh_forward_list`. Each local connection tracks both the local socket and the SSH `forwardOut` channel. Closing or
616
726
  failing either side destroys the other, and force close returns only after both sides are destroyed and
617
- `activeConnections` reaches zero. Pending `forwardOut` requests are limited to 32 per alias, and a close waits for every
618
- callback. If the SSH server never answers a channel-open request, close times out, keeps the forward retryable, and
619
- rejects another local forward on the same alias so pending ssh2 channels cannot accumulate. Disconnect the alias to
620
- release a channel request that never completes.
727
+ `activeConnections` reaches zero. Remote force close uses the same drain rule after `unforwardIn`; close and error
728
+ events from both ends of one connection decrement the count only once. Pending `forwardOut` requests are limited to 32
729
+ per alias, and a close waits for every callback. If the SSH server never answers a channel-open request, close times
730
+ out, keeps the forward retryable, and rejects another local forward on the same alias so pending ssh2 channels cannot
731
+ accumulate. Disconnect the alias to release a channel request that never completes.
621
732
 
622
733
  ## Configuration Options
623
734
 
@@ -651,7 +762,7 @@ Connection failures return `failureStage`, `retryable`, and a bounded suggestion
651
762
  | `cwd` | string | - | Working directory |
652
763
  | `env` | object | - | Additional environment variables |
653
764
  | `pty` | boolean | false | Enable PTY mode for interactive commands |
654
- | `maxOutputSize` | number | 10 MB chars | Output truncation limit |
765
+ | `maxOutputSize` | number | 10 MiB bytes | UTF-8 byte limit for each output stream |
655
766
  | `runAs` | string | session runAs | Per-command execution user |
656
767
  | `useLoginUser` | boolean | false | Skip session-level runAs |
657
768
  | `loadProfile` | boolean | true | Load target user's shell profile for runAs |
package/README_zh.md CHANGED
@@ -11,6 +11,23 @@
11
11
  ![Linux](https://img.shields.io/badge/Linux-tested-success) ![macOS](https://img.shields.io/badge/macOS-untested-yellow)
12
12
  ![Windows](https://img.shields.io/badge/Windows-untested-yellow)
13
13
 
14
+ ## 迁移到 3.0
15
+
16
+ `maxOutputSize`
17
+ 现在按 UTF-8 字节分别限制 exec 的 stdout/stderr 返回正文,原来按 JavaScript 字符串长度计量;非 ASCII 输出需要重新计算预算,并检查
18
+ `stdoutTruncated` / `stderrTruncated`;`maxOutputSize=3` 可返回一个汉字,不能返回三个,文本只返回完整字符
19
+
20
+ PTY 的 `bufferSize` 参数与列表结果中的 `bufferSize`,以及 read/list 中的 `unreadRawBytes` 和 `rawBufferLimit`
21
+ 均按原始字节计量;raw 读取使用 `clear=true` 时,响应中的计数和 `rawBufferTruncated`
22
+ 描述清理前的状态,下次读取才反映清理后的缓冲区;精确读取 ANSI 或二进制输出用 `dataBase64`,`data` 是 UTF-8 文本预览
23
+
24
+ 文件读取支持 `encoding`(`auto`、`utf8`、`utf16le`、`utf16be`、`gbk`)和无损 `binary=true`;偏移按字节计量,分页使用
25
+ `next_offset`,非零偏移读取 UTF-16 时显式指定编码;预算不足以容纳下一个完整字符时返回错误,不再成功返回空页,EOF 处编码无效也会失败;binary 读取按实际字节前移;`lineRange`
26
+ 的行号和末行换行状态只描述已返回的前缀
27
+
28
+ 连接 Windows 主机须设置 `remotePlatform="windows"`,本机为 Windows 不会改变远端默认值;按主机设置 `commandShell` 和
29
+ `remotePathStyle`,使用 Windows rsync 时显式设置 `rsyncProfile`;下文 Windows 功能和示例继续适用
30
+
14
31
  ## 功能特性
15
32
 
16
33
  - **多种认证方式**:密码、SSH 密钥
@@ -108,6 +125,8 @@ claude mcp add ssh -- node /path/to/mcp-ssh/dist/index.js
108
125
  `ssh_list_sessions()` 默认只返回 `alias`、规范化 `identity`、`runAs`、`connected` 和 `lastUsedAt`,使用 `detail=true`
109
126
  获取连接详情,或通过 `fields=[...]` 选择字段,任何模式都不返回 `keyPath`
110
127
 
128
+ 连接启用 TCP_NODELAY,减少交互命令和小文件 SFTP 请求之间的等待,直连、跳板和替代连接使用相同行为,无需新增选项
129
+
111
130
  `ssh_reconnect` 会在发布替代连接前,使绑定旧 client 的 operation、PTY、forward 和传输能力缓存失效。
112
131
 
113
132
  自动重连 timer 绑定发起调度的 session 和 client,不会断开同一 alias 下后来发布的新会话。
@@ -127,6 +146,9 @@ claude mcp add ssh -- node /path/to/mcp-ssh/dist/index.js
127
146
  | `ssh_quick_exec` | 一次性执行:连接、执行、断开 |
128
147
  | `ssh_exec_script` | 上传并执行远端临时脚本 |
129
148
 
149
+ 远端为 Windows 时,`ssh_exec_script` 给 PowerShell 脚本写入 UTF-8 BOM,避免 Windows
150
+ PowerShell 将 Unicode 脚本误读为系统编码;CMD 脚本先切换到代码页 65001 再执行 UTF-8 内容,切换失败则终止。POSIX 脚本内容保持不变
151
+
130
152
  ### 可跟踪任务
131
153
 
132
154
  | 工具 | 描述 |
@@ -134,7 +156,7 @@ claude mcp add ssh -- node /path/to/mcp-ssh/dist/index.js
134
156
  | `ssh_operation_start` | 启动可跟踪的长时间远端命令 |
135
157
  | `ssh_operation_status` | 读取状态、PID、退出码和输出计数 |
136
158
  | `ssh_operation_read` | 按字节偏移读取有上限的 stdout 和 stderr |
137
- | `ssh_operation_cancel` | 校验任务 marker 后发送 TERM |
159
+ | `ssh_operation_cancel` | 校验进程身份后取消任务 |
138
160
  | `ssh_operation_list` | 列出未过期任务,可按 alias 过滤 |
139
161
 
140
162
  ### 文件操作
@@ -170,6 +192,53 @@ claude mcp add ssh -- node /path/to/mcp-ssh/dist/index.js
170
192
  | `ssh_forward_close` | 关闭端口转发 |
171
193
  | `ssh_forward_list` | 列出所有端口转发 |
172
194
 
195
+ ## Windows 与跨平台 SSH
196
+
197
+ 连接 Windows 主机时设置 `remotePlatform="windows"`;默认值始终是 `posix`,与客户端操作系统无关;Windows 默认使用
198
+ `commandShell="powershell"` 和 `remotePathStyle="win32"`;远端 SFTP 若使用 `/C:/...`,设置
199
+ `remotePathStyle="sftp-posix"`;还可选择 `commandShell="cmd"`,`cwd` 和 `env`
200
+ 与完整命令放在同一个 shell 命令组中,cmd 注入值含无法安全处理的展开字符时会拒绝;`ssh_quick_exec` 同样支持
201
+ `remotePlatform`、`commandShell` 和 `agent`;Windows 的 `runAs`、`ssh_exec_as_user` 和 `ssh_exec_sudo` 在发送命令前返回
202
+ `unsupported_remote_platform`
203
+
204
+ ```text
205
+ ssh_connect(host="example.com", user="tester", agent="\\\\.\\pipe\\openssh-ssh-agent", remotePlatform="windows", commandShell="powershell", remotePathStyle="win32", rsyncProfile="native-win32")
206
+ ssh_exec(alias="tester@example.com:22", command="Get-Location", cwd="C:\\Test Data", env={REGION:"test"})
207
+ ssh_read_file(alias="tester@example.com:22", remotePath="C:\\Test Data\\report.txt", lineRange="1-20", encoding="utf16le")
208
+ ```
209
+
210
+ `ssh_connect(agent="...")` 会将 agent socket 或 Windows OpenSSH named pipe 传给 ssh2;Windows 还支持 ssh2 的
211
+ `agent="pageant"`;未显式设置 agent 和私钥时,SSH config 的 `IdentityAgent` 可提供路径;`IdentityAgent none` 或
212
+ `agent="none"`
213
+ 明确禁用 agent 和环境 socket 回退,即使配置私钥也保留禁用状态,ProxyJump 主机同样适用;密码和密钥认证仍可使用;显式参数或模板中的
214
+ `agent` 优先于 SSH config;重连保留该选择,外部 OpenSSH/rsync 在 `none`
215
+ 下也禁用环境 agent;连接结果返回远端平台、shell、路径格式,以及 Windows 私钥的
216
+ `keyAclStatus`;已有私钥只校验权限,不自动修改;`key_acl_insecure`、`key_acl_unverified`
217
+ 均拒绝读取;Windows 会话文件和临时下载文件在写入正文前设置并验证私有 DACL;Windows 脚本和 atomic 上传的临时文件先由 SFTP 独占创建空文件,DACL 验证后才写入正文,清理也使用 SFTP
218
+
219
+ Windows tracked operation 返回 PID 与创建时间;取消时检查进程命令行中的随机 marker 和创建时间,匹配后才执行
220
+ `taskkill /T /F`;`cancellationStatus` 分别返回 `requested`、`unknown` 或 `unsupported`,关闭 SSH
221
+ channel 不代表取消成功;DACL 和进程行为仍需原生 Windows 环境验收
222
+
223
+ `ssh_read_file.lineRange` 只通过 SFTP 扫描,支持 CRLF、UTF-8、UTF-16LE/BE 和 GBK;`encoding="auto"`
224
+ 在文件起始处识别 BOM;`binary=true` 返回无损 base64,`content` 和 `content_base64`
225
+ 均含编码结果;偏移仍指向远端文件字节;GBK 的随机字节偏移与 tail 无法证明字符边界,需使用 `lineRange` 或
226
+ `binary=true`;非零偏移读取 UTF-16 时须显式指定编码;`ssh_exec.maxOutputSize`
227
+ 分别限制 stdout/stderr 正文的 UTF-8 字节数,截断由 `stdoutTruncated`、`stderrTruncated` 单独提示;PTY raw 的
228
+ `dataBase64` 保存原始字节,`data` 是文本预览
229
+
230
+ 目录校验通过 SFTP 有界遍历与流式哈希;Windows 上不接受 POSIX `verify.owner`、`verify.mode`;`verify.aclSddl`
231
+ 可单独比较 Windows 远端根目录的 DACL SDDL;覆盖已有目标时,`ssh_upload(atomic=true)` 在传输前检查 SFTP
232
+ `posix-rename@openssh.com` 扩展,无法确认支持时不覆盖旧文件;`ssh_sync` 支持
233
+ `rsyncProfile`(`posix`、`native-win32`、`msys2`、`cygwin`)和远端
234
+ `rsyncExecutable`;本机或远端为 Windows 时须显式设置 profile 才探测 rsync;预检失败时改用 SFTP 并返回
235
+ `selectedTransport` 与 `decisionReason`;rsync 传输开始后失败时远端状态标为未知,不自动重新传输
236
+
237
+ Windows 目录上传会在两种传输开始前,按 `exclude` 和 `followSymlinks` 筛选后的源名称检查候选碰撞;名称比较使用 Windows
238
+ ordinal 大小写规则,并查询已存在目标父目录的大小写敏感标志;确认碰撞返回
239
+ `windows_filename_collision`,父目录不存在、shell 不可用、查询超时或响应不完整则返回
240
+ `case_semantics_unverified`,此时没有上传或创建目录,dry-run 也不写入;已存在且启用大小写敏感的目录允许保留仅大小写不同的名称,不从祖先目录推断新目录的规则;没有候选时不增加 PowerShell 或 exec 要求,普通 SFTP-only 上传继续可用,POSIX 上传保留其名称语义
241
+
173
242
  ## 使用示例
174
243
 
175
244
  ### 使用 SSH Config(推荐)
@@ -302,10 +371,16 @@ ssh_connect(
302
371
  `profileLoaded`、`envInjectedKeys`、`failureKind`、`stdoutBytes`、`stderrBytes` 和截断提示,大输出会返回 `stdoutHead`、
303
372
  `stdoutTail`、`stderrHead`、`stderrTail` 和 `recommendedReadCommand`。
304
373
 
305
- timeout 错误也包含超时前已经产生的 head/tail 输出。
374
+ timeout 错误也包含超时前已经产生的 head/tail 输出。stdout 和 stderr 使用增量解码,UTF-8 字符即使跨越多个 SSH data
375
+ chunk,也会完整返回。
376
+
377
+ `commandRisk`
378
+ 按所选 shell 报告破坏性、提权、凭据参数、进程控制及资源使用风险,只读搜索中的敏感词和普通 Python/Node 命令不会仅凭词语触发风险提示
306
379
 
307
- 包含 destructive、process-control、service-control、credential-bearing、未限制 `find`、递归
308
- `grep`、长管道、后台任务、直接 `su - user -c` 或长运行模式的命令会返回带 `categories` 和 `signals` 的 `commandRisk`
380
+ `commandRisk`
381
+ 仅提供诊断,不改变命令执行或执行结果 POSIX 分类将 here-doc 正文视为输入,支持引用及部分引用 delimiter、反斜杠引用、`<<-`
382
+ 和多个 here-doc 在大小写精确匹配的 delimiter 后恢复命令检查;未引用正文与双引号参数内的有效命令替换仍会检查 EOF 的后台
383
+ `&` 会报告;`&&`、重定向、转义 `&` 和引用输入不会误报为后台操作
309
384
 
310
385
  ### 可跟踪的长时间命令
311
386
 
@@ -332,6 +407,11 @@ listener 会在 SSH exec callback 返回前安装,极短命令即使立即输
332
407
  `expiresAt`;SSH 会话在 tracked command 运行期间断开后状态变为 `unknown`,不会声称远端进程已经停止,`ssh_exec`
333
408
  保持原有同步 timeout 行为
334
409
 
410
+ POSIX tracked 命令使用可用的 `setsid -w` 等待实际命令,包括 `setsid` 派生子进程的情况;非零退出为
411
+ `failed`,零退出仍可含 stderr 输出命令在 `sh` 下执行,`pipefail` 等 Bash 选项须显式使用 `bash -lc`;没有 `setsid`
412
+ 时,`processGroup=false`,取消只针对 PID POSIX 取消先校验 marker,再使用 `sh`
413
+ 与 Bash 支持的信号参数发送 TERM,终止期间产生的系统诊断保留在 stderr
414
+
335
415
  ### 交互式命令(PTY 模式)
336
416
 
337
417
  用于需要终端的命令:
@@ -362,7 +442,8 @@ ssh_exec_script(alias="server", script=<script-above>, timeout=30000)
362
442
  ssh_read_file(alias="server", remotePath="/tmp/mcp-log-errors.txt", maxBytes=65536)
363
443
  ```
364
444
 
365
- 日志查询由通用命令和文件工具组合完成,不再提供独立的日志专用 MCP 工具
445
+ 日志查询由通用命令和文件工具组合完成,不再提供独立的日志专用 MCP 工具。`ssh_exec_script.timeout`
446
+ 同时用于临时脚本上传、权限准备和执行阶段;SFTP 上传停滞时按请求的 timeout 结束,不再使用默认 SFTP 预算
366
447
 
367
448
  ### 设置环境变量
368
449
 
@@ -428,23 +509,27 @@ ssh_read_file(alias="server", remotePath="/var/log/app.log", lineRange="120-180"
428
509
  `verifySize`、`verifyMd5`、`verifyMode`、`verifyOwner`、`verifyMtime`
429
510
  会追加显式传输校验,父目录和目标探测、递归建目录、文件哈希、rename、临时文件清理都使用 SFTP,普通上传不依赖 GNU
430
511
  `stat`、`md5sum`、`sha256sum`、`mkdir`、`mv` 或
431
- `rm`,可用于禁用 exec 的 SFTP-only 服务和 BSD 系统,显式目录 manifest 校验仍会执行远端 shell 命令
512
+ `rm`,可用于禁用 exec 的 SFTP-only 服务和 BSD 系统,目录 manifest 校验也通过 SFTP 读取远端目录树
432
513
 
433
- `ssh_download` 先写入目标同目录的临时文件,SFTP 流关闭且传输字节数与 SFTP `stat`
434
- 报告的大小一致后再 rename 到本地目标;下载失败、提前截断或取消时会删除临时文件,已有本地目标保持原内容,SFTP 目录列表在构造子路径前会拒绝空名称、`.`、
435
- `..`、NUL 和路径分隔符
514
+ `ssh_download` 先以 `0600` mode 写入目标同目录的临时文件,SFTP 流关闭且传输字节数与 SFTP `stat`
515
+ 报告的大小一致后再 rename 到本地目标。新文件保持 `0600`;替换普通文件时保留其 `rwx`
516
+ 位,但不复制 setuid、setgid 或 sticky 位。目标是 symlink、目录或其他非普通对象时,在远端读取开始前拒绝。下载失败、提前截断或取消时会删除临时文件,已有本地目标保持原内容。SFTP 目录列表在构造子路径前会拒绝空名称、`.`、`..`、NUL 和路径分隔符
436
517
 
437
518
  命令执行结果在远端命令非零退出且没有 stdout/stderr 时返回 `emptyOutputFailure=true`,同时给出 effective
438
519
  user、cwd 和可用的后续读取建议,`ssh_read_file` 默认读取 1 MiB,`maxBytes` 超过 16 MiB 时会在远端传输前拒绝,返回
439
520
  `total_size`、
440
521
  `read_offset`、`requested_offset`、`read_bytes`、`read_end`、`next_offset`、`remaining_bytes`、`sample_kind` 和
441
522
  `truncated`,调用方可以区分完整读取、头部样本、尾部样本、字节范围和行范围。文本读取不会截断 UTF-8 字符,后续分段应使用
442
- `next_offset`。
523
+ `next_offset`。行范围读取不执行远端 shell 工具。
443
524
 
444
525
  `ssh_upload`、`ssh_download`、`ssh_read_file`、`ssh_write_file`、`ssh_list_dir`、`ssh_file_info` 和 `ssh_mkdir`
445
526
  支持单个 SFTP 操作的 `timeout`,默认 10 分钟,最大 1 小时。超时返回 `operationStatus="unknown"` 和
446
527
  `retryable=true`,重试前应检查受影响的远端或本地路径
447
528
 
529
+ `ssh_list_dir` 和 `ssh_file_info` 返回按 `07777` 掩码提取的数值 `mode`,`permissions` 用作展示,其中 setuid/setgid 使用
530
+ `s`/`S`,sticky 使用 `t`/`T`。`verifyMode` 支持 `4755` 等四位八进制值和 `-rwsr-xr-x`
531
+ 等权限文本;校验直接比较数值 mode,不从展示文本反向推导
532
+
448
533
  ### 使用 rsync 或 SFTP 同步目录
449
534
 
450
535
  智能同步只在直连且存在已校验 key path 或可用 SSH agent 时选择 rsync,password、inline key、jump
@@ -496,8 +581,9 @@ ssh_sync(..., delete=true, verify={deletions: true})
496
581
  目录源路径在 rsync 和 SFTP 模式下都表示“把源目录内容同步到目标根目录”,目录源使用 `recursive=false`
497
582
  会被明确拒绝,相对排除模式按源目录下的相对路径匹配,不含 `/` 的模式匹配每一级 basename
498
583
 
499
- 目录校验会生成有界的本地和远端 manifest,可比较条目数、SHA-256 root manifest、owner、mode、旧文件和删除结果,
500
- `verify.deletions=true` 必须同时设置 `delete=true`,工具会在传输前记录目标目录,只检查这些删除候选是否消失,`staleFiles`
584
+ 目录校验会生成有界的本地和远端 manifest,可比较条目数、SHA-256 root
585
+ manifest、owner、包括 setuid、setgid、sticky 在内的四位八进制 mode、旧文件和删除结果。`verify.deletions=true`
586
+ 必须同时设置 `delete=true`,工具会在传输前记录目标目录,只检查这些删除候选是否消失,`staleFiles`
501
587
  则独立检查目标端全部额外条目,响应只返回摘要和最多 20 个 mismatch 样本,不返回完整 manifest,默认上限为 10000 个条目、单文件 256
502
588
  MiB、总哈希字节 1 GiB,可通过 `verify.maxEntries`、`verify.maxFileBytes` 和 `verify.maxTotalBytes`
503
589
  提高到最多 50000 个条目、单文件 4 GiB、总哈希字节 16 GiB,遇到被跳过的 symlink 或不支持的文件系统条目时,校验会明确返回
@@ -506,7 +592,9 @@ MiB、总哈希字节 1 GiB,可通过 `verify.maxEntries`、`verify.maxFileByt
506
592
  请求校验后,mismatch、skipped 或校验错误都会令顶层 `success=false`,`transferSuccess` 仍单独表示传输是否完成,
507
593
  `verificationStatus`、`verificationSuccess` 和 `failedChecks`
508
594
  描述校验结果,SFTP 单文件同步还会返回本地和远端的 size、mode 或 permissions、mtime、owner/group,以及通过 SFTP 流读取计算的 SHA-256 对比,upload 单文件使用
509
- `verifyOwner` 和 `verifyMode` ,目录逐项校验使用 `verify.owner` 和 `verify.mode`
595
+ `verifyOwner` 和 `verifyMode`,目录逐项校验使用 `verify.owner` 和 `verify.mode`
596
+ 校验不会自动执行 chown/chmod,SFTP 新目录使用目标端默认权限,新下载文件使用
597
+ `0600`,覆盖既有本地普通文件保留其 rwx 内容和 owner 匹配不代表 mode 匹配,请求 mode 校验时,已完成的传输仍会因权限不同而返回校验失败
510
598
 
511
599
  只有直连且存在已校验 key path 或可用 SSH agent 时才选择 rsync,password、inline key 和 jump
512
600
  host 会使用 SFTP,因为独立 OpenSSH 进程无法安全继承对应路由或认证材料,`preflightTimeout`、`connectTimeout` 和
@@ -551,10 +639,14 @@ ssh_pty_read(ptyId="pty_1_xxx")
551
639
  ssh_pty_write(ptyId="pty_1_xxx", data="\x02d")
552
640
  ```
553
641
 
554
- `ssh_pty_read` 和 `ssh_pty_list` 返回 `lastInputAt`、`lastOutputAt`、`lastReadAt`、`unreadRawBytes`、`rawBufferLimit`、
555
- `foregroundProcess`,便于观察长时间运行的会话,无需读取完整 raw 流,有限命令自然结束后仍可读取最终 screen,返回
642
+ `ssh_pty_read` 和 `ssh_pty_list` 返回 `lastInputAt`、`lastOutputAt`、`lastReadAt`、
643
+ `unreadRawBytes`、`rawBufferLimit`、`rawBufferTruncated`、`foregroundProcess`,列表项还返回
644
+ `bufferSize`,这些 size 字段都按字节计数,screen 输出使用增量解码;raw 的 `dataBase64`
645
+ 无损保存原始字节,包括不完整的 UTF-8 序列,`data` 是文本预览。`rawBufferTruncated=true`
646
+ 表示从上次 clear 起已有更早的 raw 输出因字节上限被丢弃。raw 读取默认
647
+ `clear=true`,响应返回清理前的字节数和截断标志,随后重置 raw 缓冲区和标志;screen 读取不清理 raw 状态。有限命令自然结束后仍可读取最终 screen,返回
556
648
  `active=false`,直到显式 close 或 closed session 保留期结束,默认 5 分钟,可通过 `SSH_MCP_PTY_CLOSED_RETENTION_MS`
557
- 调整。`ssh_pty_write` 返回 `accepted=true` 表示本地 stream 已接收输入,`backpressured=true`
649
+ 调整。`ssh_pty_write` 返回 `accepted=true` 表示本地 stream 已接收输入, `backpressured=true`
558
650
  只表示缓冲区达到高水位,不代表输入丢失。`ssh_pty_close` 返回 `closed`、`not_found`、`failed` 或
559
651
  `unknown`,可重试的失败会保留 PTY 状态
560
652
 
@@ -601,8 +693,9 @@ forward 在 `listen` 或 `forwardIn` 完成前就进入生命周期管理,disc
601
693
  creation。延迟返回的本地 listener 会被关闭,延迟分配的远端 listener 会被移除;close 开始后立即拒绝新的本地或远端连接。
602
694
  `forwardOut`、close 和 unforward 的延迟 callback 修改状态前会检查同一生命周期记录,已关闭的 forward 不会重新出现在
603
695
  `ssh_forward_list`;每条本地转发连接同时跟踪本地 socket 和 SSH `forwardOut`
604
- channel,任一端关闭或失败都会销毁另一端,force close 只在两端都销毁且 `activeConnections`
605
- 归零后返回;每个 alias 最多允许 32 个 pending `forwardOut`
696
+ channel,任一端关闭或失败都会销毁另一端,force close 只在两端都销毁且 `activeConnections` 归零后返回。remote force
697
+ close 在 `unforwardIn`
698
+ 后遵循相同的连接排空规则,同一连接两端的 close/error 事件只递减一次计数。每个 alias 最多允许 32 个 pending `forwardOut`
606
699
  请求,close 会等待全部 callback;如果 SSH 服务端始终不回应 channel-open,请求会超时并保留可重试的 forward,同时拒绝同 alias 新建 local
607
700
  forward,避免 ssh2 pending channel 继续累积,此时断开 alias 才能释放始终不返回的底层请求
608
701
 
@@ -632,16 +725,16 @@ forward,避免 ssh2 pending channel 继续累积,此时断开 alias 才能
632
725
 
633
726
  ### 执行选项
634
727
 
635
- | 选项 | 类型 | 默认值 | 描述 |
636
- | --------------- | ------- | ------------ | ------------------------------- |
637
- | `timeout` | number | 30000 | 命令超时(毫秒) |
638
- | `cwd` | string | - | 工作目录 |
639
- | `env` | object | - | 额外环境变量 |
640
- | `pty` | boolean | false | 启用 PTY 模式(用于交互式命令) |
641
- | `maxOutputSize` | number | 10 MB 字符 | 输出截断上限 |
642
- | `runAs` | string | 连接级 runAs | 本次命令执行用户 |
643
- | `useLoginUser` | boolean | false | 跳过连接级 runAs |
644
- | `loadProfile` | boolean | true | runAs 时加载目标用户 shell 配置 |
728
+ | 选项 | 类型 | 默认值 | 描述 |
729
+ | --------------- | ------- | ------------ | ----------------------------------- |
730
+ | `timeout` | number | 30000 | 命令超时(毫秒) |
731
+ | `cwd` | string | - | 工作目录 |
732
+ | `env` | object | - | 额外环境变量 |
733
+ | `pty` | boolean | false | 启用 PTY 模式(用于交互式命令) |
734
+ | `maxOutputSize` | number | 10 MiB 字节 | stdout/stderr 各自的 UTF-8 字节上限 |
735
+ | `runAs` | string | 连接级 runAs | 本次命令执行用户 |
736
+ | `useLoginUser` | boolean | false | 跳过连接级 runAs |
737
+ | `loadProfile` | boolean | true | runAs 时加载目标用户 shell 配置 |
645
738
 
646
739
  传入 `cwd` 或 `env` 时,生成的 shell 命令会用 `&&` 连接 `cd` 和每个通过校验的
647
740
  `export`,再把完整用户命令作为当前登录 shell 的一个转义后 `eval`
@@ -1,7 +1,8 @@
1
+ import type { CommandShell } from './types.js';
1
2
  export type CommandRisk = {
2
3
  level: 'medium' | 'high';
3
4
  categories: string[];
4
5
  signals: string[];
5
6
  suggestion: string;
6
7
  };
7
- export declare function classifyCommandRisk(command: string, timeout?: number): CommandRisk | undefined;
8
+ export declare function classifyCommandRisk(command: string, timeout?: number, shell?: CommandShell): CommandRisk | undefined;