@pyrokine/mcp-ssh 2.1.0 → 2.3.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 +12 -0
- package/README_zh.md +14 -3
- package/dist/file-ops.js +125 -34
- package/dist/session-manager.d.ts +2 -0
- package/dist/session-manager.js +28 -3
- package/dist/tools/connection.js +11 -9
- package/dist/tools/exec.js +50 -16
- package/dist/tools/file.js +108 -5
- package/dist/types.d.ts +3 -0
- package/dist/types.js +2 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -194,6 +194,10 @@ Execute the same command on multiple connected hosts:
|
|
|
194
194
|
4. ssh_exec_parallel(aliases=["server1", "server2", "server3"], command="uptime")
|
|
195
195
|
```
|
|
196
196
|
|
|
197
|
+
Each host result keeps the same execution metadata as `ssh_exec`, including `failureKind`, `effectiveUser`, `cwd`,
|
|
198
|
+
truncation fields, and diagnostic suggestions. `ssh_exec_parallel` limits one call to 32 aliases, runs up to 4 hosts at
|
|
199
|
+
a time by default (configurable with `maxConcurrency`, max 8), and accepts `maxOutputSize` to cap each host result.
|
|
200
|
+
|
|
197
201
|
### Basic: Connect and Execute
|
|
198
202
|
|
|
199
203
|
```
|
|
@@ -343,6 +347,9 @@ ssh_read_file(alias="server", remotePath="/var/log/app.log", lineRange="120-180"
|
|
|
343
347
|
`ssh_upload` returns local path policy diagnostics, remote parent probing, remote target metadata, and optional
|
|
344
348
|
verification checks. `atomic=true` uploads to a same-directory temporary file, then renames it to the target path.
|
|
345
349
|
`verifySize`, `verifyMd5`, `verifyMode`, `verifyOwner`, and `verifyMtime` add explicit post-transfer checks.
|
|
350
|
+
Command execution results include `emptyOutputFailure=true` when the remote command exits non-zero without
|
|
351
|
+
stdout/stderr,
|
|
352
|
+
with the effective user, cwd, and a suggested follow-up read command when available.
|
|
346
353
|
`ssh_read_file` defaults to 1 MiB and rejects `maxBytes` above 16 MiB before remote transfer. It returns `total_size`,
|
|
347
354
|
`read_offset`, `read_bytes`, `remaining_bytes`, `sample_kind`, and `truncated` so callers can distinguish a full read
|
|
348
355
|
from a head, tail, byte range, or line range sample.
|
|
@@ -380,11 +387,16 @@ ssh_sync(
|
|
|
380
387
|
|
|
381
388
|
// Dry run (preview without actual transfer)
|
|
382
389
|
ssh_sync(..., dryRun=true)
|
|
390
|
+
|
|
391
|
+
// Upload one file and verify remote owner/mode after transfer
|
|
392
|
+
ssh_sync(..., direction="upload", verifyOwner="appuser", verifyMode="0644")
|
|
383
393
|
```
|
|
384
394
|
|
|
385
395
|
If rsync is not available on remote or local, it automatically falls back to SFTP. Sync responses include `transport`,
|
|
386
396
|
`duration`, `dryRun`, `stats`, and `commandSummary`. SFTP single-file transfers include a `verification` object with
|
|
387
397
|
local and remote size, mode or permissions, mtime, owner/group, and SHA-256 comparison when the remote has `sha256sum`.
|
|
398
|
+
For upload single-file sync, `verifyOwner` and `verifyMode` add an `ownerMode` verification block based on remote file
|
|
399
|
+
metadata. Directory sync does not recursively scan owner/mode; it returns a skipped verification note instead.
|
|
388
400
|
|
|
389
401
|
**Note**: rsync mode uses SSH key/agent authentication and sets `StrictHostKeyChecking=accept-new`.
|
|
390
402
|
If you require strict host key verification and management, use SFTP mode instead.
|
package/README_zh.md
CHANGED
|
@@ -194,6 +194,10 @@ ssh_connect(configHost="myserver", configPath="/custom/path/config")
|
|
|
194
194
|
4. ssh_exec_parallel(aliases=["server1", "server2", "server3"], command="uptime")
|
|
195
195
|
```
|
|
196
196
|
|
|
197
|
+
每台主机的结果保留与 `ssh_exec` 相同的执行元数据,包括 `failureKind`、`effectiveUser`、`cwd`、截断字段和诊断建议。
|
|
198
|
+
`ssh_exec_parallel` 单次最多 32 个 alias,默认最多并发 4 台主机,可用 `maxConcurrency` 调整(最大 8),并支持 `maxOutputSize`
|
|
199
|
+
限制每台主机的输出
|
|
200
|
+
|
|
197
201
|
### 基础:连接和执行
|
|
198
202
|
|
|
199
203
|
```
|
|
@@ -337,8 +341,10 @@ ssh_read_file(alias="server", remotePath="/var/log/app.log", lineRange="120-180"
|
|
|
337
341
|
```
|
|
338
342
|
|
|
339
343
|
`ssh_upload` 返回本地路径策略诊断、远端父目录探测、远端目标元数据和可选校验结果,`atomic=true` 会先上传到同目录临时文件,再
|
|
340
|
-
rename 到目标路径,`verifySize`、`verifyMd5`、`verifyMode`、`verifyOwner`、`verifyMtime`
|
|
341
|
-
|
|
344
|
+
rename 到目标路径,`verifySize`、`verifyMd5`、`verifyMode`、`verifyOwner`、`verifyMtime` 会追加显式传输后校验,命令执行结果在远端命令非零退出且没有
|
|
345
|
+
stdout/stderr 时返回
|
|
346
|
+
`emptyOutputFailure=true`,同时给出 effective user、cwd 和可用的后续读取建议,`ssh_read_file` 默认读取 1 MiB,`maxBytes` 超过
|
|
347
|
+
16 MiB 时会在远端传输前拒绝,返回 `total_size`、`read_offset`、`read_bytes`、
|
|
342
348
|
`remaining_bytes`、`sample_kind` 和 `truncated`,调用方可以区分完整读取、头部样本、尾部样本、字节范围和行范围
|
|
343
349
|
|
|
344
350
|
### 目录同步(rsync)
|
|
@@ -374,11 +380,16 @@ ssh_sync(
|
|
|
374
380
|
|
|
375
381
|
// 试运行(预览,不实际传输)
|
|
376
382
|
ssh_sync(..., dryRun=true)
|
|
383
|
+
|
|
384
|
+
// 上传单文件后校验远端 owner/mode
|
|
385
|
+
ssh_sync(..., direction="upload", verifyOwner="appuser", verifyMode="0644")
|
|
377
386
|
```
|
|
378
387
|
|
|
379
388
|
如果远程或本地没有 rsync,会自动回退到 SFTP,同步响应包含 `transport`、`duration`、`dryRun`、`stats`、`commandSummary` 和
|
|
380
389
|
`diagnostics`,其中 `diagnostics` 包含本地路径策略和远端父目录探测结果,SFTP 单文件传输会返回 `verification`,包含本地和远端的
|
|
381
|
-
size、mode 或 permissions、mtime、owner/group,以及远端支持 `sha256sum` 时的 SHA-256
|
|
390
|
+
size、mode 或 permissions、mtime、owner/group,以及远端支持 `sha256sum` 时的 SHA-256 对比,upload 单文件同步可用
|
|
391
|
+
`verifyOwner` 和 `verifyMode` 追加基于远端元数据的 `ownerMode` 校验,目录同步不递归扫描 owner/mode,会返回 skipped
|
|
392
|
+
verification 说明
|
|
382
393
|
|
|
383
394
|
**注意**:rsync 模式使用 SSH 密钥/代理认证,并设置 `StrictHostKeyChecking=accept-new`(首次连接会自动接受主机密钥),
|
|
384
395
|
如需严格的主机密钥验证与管理,请使用 SFTP 模式
|
package/dist/file-ops.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* SSH File Operations - 文件操作
|
|
3
3
|
*/
|
|
4
|
-
import {
|
|
4
|
+
import { spawn } from 'child_process';
|
|
5
5
|
import { createHash } from 'crypto';
|
|
6
6
|
import * as fs from 'fs';
|
|
7
7
|
import * as os from 'os';
|
|
@@ -15,7 +15,57 @@ const S_IFREG = 0o100000;
|
|
|
15
15
|
const S_IFLNK = 0o120000;
|
|
16
16
|
// rsync 可用性缓存(per alias,连接存续期内不变,disconnect 时由 SessionManager 主动清理)
|
|
17
17
|
const RSYNC_CACHE_TTL_MS = 5 * 60_000;
|
|
18
|
+
const LOCAL_PROCESS_OUTPUT_LIMIT = 200_000;
|
|
18
19
|
const rsyncCache = new Map();
|
|
20
|
+
function appendLimitedOutput(current, chunk) {
|
|
21
|
+
if (current.length >= LOCAL_PROCESS_OUTPUT_LIMIT) {
|
|
22
|
+
return current;
|
|
23
|
+
}
|
|
24
|
+
return (current + chunk).slice(0, LOCAL_PROCESS_OUTPUT_LIMIT);
|
|
25
|
+
}
|
|
26
|
+
function runLocalProcess(command, args, timeout) {
|
|
27
|
+
return new Promise((resolve) => {
|
|
28
|
+
let stdout = '';
|
|
29
|
+
let stderr = '';
|
|
30
|
+
let settled = false;
|
|
31
|
+
let timedOut = false;
|
|
32
|
+
let killTimer;
|
|
33
|
+
const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
34
|
+
const timer = setTimeout(() => {
|
|
35
|
+
timedOut = true;
|
|
36
|
+
child.kill('SIGTERM');
|
|
37
|
+
killTimer = setTimeout(() => child.kill('SIGKILL'), 5000);
|
|
38
|
+
}, timeout);
|
|
39
|
+
child.stdout.on('data', (chunk) => {
|
|
40
|
+
stdout = appendLimitedOutput(stdout, chunk.toString('utf-8'));
|
|
41
|
+
});
|
|
42
|
+
child.stderr.on('data', (chunk) => {
|
|
43
|
+
stderr = appendLimitedOutput(stderr, chunk.toString('utf-8'));
|
|
44
|
+
});
|
|
45
|
+
child.on('error', (error) => {
|
|
46
|
+
if (settled) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
settled = true;
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
if (killTimer) {
|
|
52
|
+
clearTimeout(killTimer);
|
|
53
|
+
}
|
|
54
|
+
resolve({ status: null, stdout, stderr, error, timedOut });
|
|
55
|
+
});
|
|
56
|
+
child.on('close', (status) => {
|
|
57
|
+
if (settled) {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
settled = true;
|
|
61
|
+
clearTimeout(timer);
|
|
62
|
+
if (killTimer) {
|
|
63
|
+
clearTimeout(killTimer);
|
|
64
|
+
}
|
|
65
|
+
resolve({ status, stdout, stderr, timedOut });
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
}
|
|
19
69
|
/** 由 SessionManager.disconnect 调用,防止 alias 重连后读到旧主机的判断 */
|
|
20
70
|
export function clearRsyncCache(alias) {
|
|
21
71
|
if (alias === undefined) {
|
|
@@ -25,8 +75,39 @@ export function clearRsyncCache(alias) {
|
|
|
25
75
|
rsyncCache.delete(alias);
|
|
26
76
|
}
|
|
27
77
|
}
|
|
78
|
+
function positiveIntegerEnv(name, defaultValue) {
|
|
79
|
+
const value = Number(process.env[name]);
|
|
80
|
+
return Number.isInteger(value) && value > 0 ? value : defaultValue;
|
|
81
|
+
}
|
|
28
82
|
/** SFTP 并发上限,避免单 SSH session 上太多 channel */
|
|
29
|
-
const SFTP_PARALLEL_LIMIT =
|
|
83
|
+
const SFTP_PARALLEL_LIMIT = positiveIntegerEnv('SSH_MCP_SFTP_PARALLEL', 8);
|
|
84
|
+
const SFTP_SYNC_MAX_FILES = positiveIntegerEnv('SSH_MCP_SFTP_MAX_FILES', 10_000);
|
|
85
|
+
const SFTP_SYNC_MAX_DIRECTORIES = positiveIntegerEnv('SSH_MCP_SFTP_MAX_DIRECTORIES', 2_000);
|
|
86
|
+
const SFTP_SYNC_MAX_DEPTH = positiveIntegerEnv('SSH_MCP_SFTP_MAX_DEPTH', 64);
|
|
87
|
+
const SFTP_SYNC_MAX_BYTES = positiveIntegerEnv('SSH_MCP_SFTP_MAX_BYTES', 10 * 1024 * 1024 * 1024);
|
|
88
|
+
function assertSftpTraversalBudget(state, depth, currentPath) {
|
|
89
|
+
if (depth > SFTP_SYNC_MAX_DEPTH) {
|
|
90
|
+
throw new Error(`SFTP sync traversal depth exceeded at ${currentPath} (max ${SFTP_SYNC_MAX_DEPTH})`);
|
|
91
|
+
}
|
|
92
|
+
if (state.files > SFTP_SYNC_MAX_FILES) {
|
|
93
|
+
throw new Error(`SFTP sync file count exceeded at ${currentPath} (max ${SFTP_SYNC_MAX_FILES})`);
|
|
94
|
+
}
|
|
95
|
+
if (state.directories > SFTP_SYNC_MAX_DIRECTORIES) {
|
|
96
|
+
throw new Error(`SFTP sync directory count exceeded at ${currentPath} (max ${SFTP_SYNC_MAX_DIRECTORIES})`);
|
|
97
|
+
}
|
|
98
|
+
if (state.bytes > SFTP_SYNC_MAX_BYTES) {
|
|
99
|
+
throw new Error(`SFTP sync byte budget exceeded at ${currentPath} (max ${SFTP_SYNC_MAX_BYTES})`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function recordSftpDirectory(state, depth, currentPath) {
|
|
103
|
+
state.directories++;
|
|
104
|
+
assertSftpTraversalBudget(state, depth, currentPath);
|
|
105
|
+
}
|
|
106
|
+
function recordSftpFile(state, size, depth, currentPath) {
|
|
107
|
+
state.files++;
|
|
108
|
+
state.bytes += size;
|
|
109
|
+
assertSftpTraversalBudget(state, depth, currentPath);
|
|
110
|
+
}
|
|
30
111
|
/**
|
|
31
112
|
* 简单的并发控制:把异步任务限制在 limit 个 in-flight,串行入队
|
|
32
113
|
*/
|
|
@@ -566,17 +647,9 @@ export async function syncFiles(alias, localPath, remotePath, direction, options
|
|
|
566
647
|
* 通过本地执行 rsync 连接到远程(需要密钥认证或 ssh-agent)
|
|
567
648
|
*/
|
|
568
649
|
async function syncWithRsync(alias, localPath, remotePath, direction, options) {
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
const cmd = os.platform() === 'win32' ? 'where rsync' : 'which rsync';
|
|
573
|
-
execSync(cmd, { stdio: 'pipe' });
|
|
574
|
-
hasLocalRsync = true;
|
|
575
|
-
}
|
|
576
|
-
catch {
|
|
577
|
-
// rsync 不可用,由 hasLocalRsync 标记处理
|
|
578
|
-
}
|
|
579
|
-
if (!hasLocalRsync) {
|
|
650
|
+
const checkCommand = os.platform() === 'win32' ? 'where' : 'which';
|
|
651
|
+
const checkResult = await runLocalProcess(checkCommand, ['rsync'], 10_000);
|
|
652
|
+
if (checkResult.status !== 0) {
|
|
580
653
|
// 本地没有 rsync,回退到 SFTP
|
|
581
654
|
return syncWithSftp(alias, localPath, remotePath, direction, options);
|
|
582
655
|
}
|
|
@@ -647,14 +720,12 @@ async function syncWithRsync(alias, localPath, remotePath, direction, options) {
|
|
|
647
720
|
? [...args, '-e', sshCmd, '--', localPath, remoteSpec]
|
|
648
721
|
: [...args, '-e', sshCmd, '--', remoteSpec, localPath];
|
|
649
722
|
try {
|
|
650
|
-
const result =
|
|
651
|
-
encoding: 'utf-8',
|
|
652
|
-
timeout: 600000,
|
|
653
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
654
|
-
});
|
|
723
|
+
const result = await runLocalProcess('rsync', rsyncArgs, 600000);
|
|
655
724
|
if (result.error || result.status !== 0) {
|
|
656
|
-
const stderr =
|
|
657
|
-
const reason = result.
|
|
725
|
+
const stderr = result.stderr.trim();
|
|
726
|
+
const reason = result.timedOut
|
|
727
|
+
? 'timed out after 600000ms'
|
|
728
|
+
: (result.error?.message ?? `exit code ${result.status}`);
|
|
658
729
|
const fallback = await syncWithSftp(alias, localPath, remotePath, direction, options);
|
|
659
730
|
const warning = `rsync 失败原因: ${reason}${stderr ? ` | stderr: ${stderr}` : ''} | 已 fallback 到 SFTP(性能可能较差)`;
|
|
660
731
|
console.warn(`[mcp-ssh] ${warning}`);
|
|
@@ -663,7 +734,7 @@ async function syncWithRsync(alias, localPath, remotePath, direction, options) {
|
|
|
663
734
|
output: fallback.output ? `${warning}\n\n${fallback.output}` : warning,
|
|
664
735
|
};
|
|
665
736
|
}
|
|
666
|
-
const output = result.stdout
|
|
737
|
+
const output = result.stdout;
|
|
667
738
|
const stats = parseRsyncStats(output);
|
|
668
739
|
const filesTransferred = stats.added + stats.updated;
|
|
669
740
|
return {
|
|
@@ -823,6 +894,21 @@ async function buildSingleFileVerification(alias, localPath, remotePath, directi
|
|
|
823
894
|
},
|
|
824
895
|
};
|
|
825
896
|
}
|
|
897
|
+
async function resolveSftpUploadFileTarget(alias, localPath, remotePath) {
|
|
898
|
+
if (remotePath.endsWith('/')) {
|
|
899
|
+
return path.posix.join(remotePath, path.basename(localPath));
|
|
900
|
+
}
|
|
901
|
+
try {
|
|
902
|
+
const info = await getFileInfo(alias, remotePath);
|
|
903
|
+
if (info.isDirectory) {
|
|
904
|
+
return path.posix.join(remotePath, path.basename(localPath));
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
catch {
|
|
908
|
+
// Missing remote targets are handled by uploadFile below.
|
|
909
|
+
}
|
|
910
|
+
return remotePath;
|
|
911
|
+
}
|
|
826
912
|
async function syncWithSftp(alias, localPath, remotePath, direction, options) {
|
|
827
913
|
const warnings = [];
|
|
828
914
|
if (options.delete) {
|
|
@@ -864,20 +950,25 @@ async function syncWithSftp(alias, localPath, remotePath, direction, options) {
|
|
|
864
950
|
};
|
|
865
951
|
}
|
|
866
952
|
if (stats.isDirectory() && options.recursive !== false) {
|
|
867
|
-
const result = await uploadDirectory(alias, localPath, remotePath, options.exclude, undefined, options.followSymlinks ?? false);
|
|
953
|
+
const result = await uploadDirectory(alias, localPath, remotePath, options.exclude, undefined, options.followSymlinks ?? false, { files: 0, directories: 0, bytes: 0 }, 0);
|
|
868
954
|
return buildDirectorySyncResult(result, warnings);
|
|
869
955
|
}
|
|
870
|
-
const
|
|
871
|
-
const
|
|
956
|
+
const targetRemotePath = await resolveSftpUploadFileTarget(alias, localPath, remotePath);
|
|
957
|
+
const existed = await remoteExists(alias, targetRemotePath);
|
|
958
|
+
const { size } = await uploadFile(alias, localPath, targetRemotePath);
|
|
872
959
|
return {
|
|
873
960
|
...buildSyncResult(1, size, warnings, 0, { added: existed ? 0 : 1, updated: existed ? 1 : 0 }),
|
|
874
|
-
verification: await buildSingleFileVerification(alias, localPath,
|
|
961
|
+
verification: await buildSingleFileVerification(alias, localPath, targetRemotePath, 'upload'),
|
|
875
962
|
};
|
|
876
963
|
}
|
|
877
964
|
// download
|
|
878
965
|
const info = await getFileInfo(alias, remotePath);
|
|
879
966
|
if (info.isDirectory && options.recursive !== false) {
|
|
880
|
-
const result = await downloadDirectory(alias, remotePath, localPath, options.exclude
|
|
967
|
+
const result = await downloadDirectory(alias, remotePath, localPath, options.exclude, undefined, {
|
|
968
|
+
files: 0,
|
|
969
|
+
directories: 0,
|
|
970
|
+
bytes: 0,
|
|
971
|
+
}, 0);
|
|
881
972
|
return buildDirectorySyncResult(result, warnings);
|
|
882
973
|
}
|
|
883
974
|
const existed = fs.existsSync(localPath);
|
|
@@ -899,13 +990,12 @@ async function syncWithSftp(alias, localPath, remotePath, direction, options) {
|
|
|
899
990
|
/**
|
|
900
991
|
* 递归上传目录
|
|
901
992
|
*/
|
|
902
|
-
async function uploadDirectory(alias, localPath, remotePath, exclude, sharedSftp, followSymlinks = false) {
|
|
993
|
+
async function uploadDirectory(alias, localPath, remotePath, exclude, sharedSftp, followSymlinks = false, traversal = { files: 0, directories: 0, bytes: 0 }, depth = 0) {
|
|
903
994
|
const accumulator = new DirectoryTransferAccumulator();
|
|
904
|
-
|
|
995
|
+
recordSftpDirectory(traversal, depth, localPath);
|
|
905
996
|
const ownSftp = !sharedSftp;
|
|
906
997
|
const sftp = sharedSftp ?? (await sessionManager.getSftp(alias));
|
|
907
998
|
try {
|
|
908
|
-
// 确保远程目录存在
|
|
909
999
|
await mkdir(alias, remotePath, true);
|
|
910
1000
|
const items = fs.readdirSync(localPath);
|
|
911
1001
|
// 先分类:目录串行(递归会自己并发文件);文件并发上传,避免单 SSH session 上 channel 过多
|
|
@@ -926,6 +1016,7 @@ async function uploadDirectory(alias, localPath, remotePath, exclude, sharedSftp
|
|
|
926
1016
|
subDirItems.push(item);
|
|
927
1017
|
}
|
|
928
1018
|
else if (stats.isFile()) {
|
|
1019
|
+
recordSftpFile(traversal, stats.size, depth, itemLocalPath);
|
|
929
1020
|
fileItems.push({ name: item, stats });
|
|
930
1021
|
}
|
|
931
1022
|
}
|
|
@@ -947,7 +1038,7 @@ async function uploadDirectory(alias, localPath, remotePath, exclude, sharedSftp
|
|
|
947
1038
|
for (const item of subDirItems) {
|
|
948
1039
|
const itemLocalPath = path.join(localPath, item);
|
|
949
1040
|
const itemRemotePath = path.posix.join(remotePath, item);
|
|
950
|
-
const result = await uploadDirectory(alias, itemLocalPath, itemRemotePath, exclude, sftp, followSymlinks);
|
|
1041
|
+
const result = await uploadDirectory(alias, itemLocalPath, itemRemotePath, exclude, sftp, followSymlinks, traversal, depth + 1);
|
|
951
1042
|
accumulator.merge(result);
|
|
952
1043
|
}
|
|
953
1044
|
}
|
|
@@ -961,13 +1052,12 @@ async function uploadDirectory(alias, localPath, remotePath, exclude, sharedSftp
|
|
|
961
1052
|
/**
|
|
962
1053
|
* 递归下载目录
|
|
963
1054
|
*/
|
|
964
|
-
async function downloadDirectory(alias, remotePath, localPath, exclude, sharedSftp) {
|
|
1055
|
+
async function downloadDirectory(alias, remotePath, localPath, exclude, sharedSftp, traversal = { files: 0, directories: 0, bytes: 0 }, depth = 0) {
|
|
965
1056
|
const accumulator = new DirectoryTransferAccumulator();
|
|
966
|
-
|
|
1057
|
+
recordSftpDirectory(traversal, depth, remotePath);
|
|
967
1058
|
const ownSftp = !sharedSftp;
|
|
968
1059
|
const sftp = sharedSftp ?? (await sessionManager.getSftp(alias));
|
|
969
1060
|
try {
|
|
970
|
-
// 确保本地目录存在
|
|
971
1061
|
if (!fs.existsSync(localPath)) {
|
|
972
1062
|
fs.mkdirSync(localPath, { recursive: true });
|
|
973
1063
|
}
|
|
@@ -984,6 +1074,7 @@ async function downloadDirectory(alias, remotePath, localPath, exclude, sharedSf
|
|
|
984
1074
|
dirItems.push(item);
|
|
985
1075
|
}
|
|
986
1076
|
else if (item.isFile) {
|
|
1077
|
+
recordSftpFile(traversal, item.size, depth, item.path);
|
|
987
1078
|
fileItems.push(item);
|
|
988
1079
|
}
|
|
989
1080
|
else if (item.isSymlink) {
|
|
@@ -1007,7 +1098,7 @@ async function downloadDirectory(alias, remotePath, localPath, exclude, sharedSf
|
|
|
1007
1098
|
});
|
|
1008
1099
|
for (const item of dirItems) {
|
|
1009
1100
|
const itemLocalPath = path.join(localPath, item.name);
|
|
1010
|
-
const result = await downloadDirectory(alias, item.path, itemLocalPath, exclude, sftp);
|
|
1101
|
+
const result = await downloadDirectory(alias, item.path, itemLocalPath, exclude, sftp, traversal, depth + 1);
|
|
1011
1102
|
accumulator.merge(result);
|
|
1012
1103
|
}
|
|
1013
1104
|
for (const item of symlinkItems) {
|
|
@@ -113,7 +113,9 @@ export declare class SessionManager {
|
|
|
113
113
|
private resultMetadata;
|
|
114
114
|
private appendOutputTail;
|
|
115
115
|
private recommendedReadCommand;
|
|
116
|
+
private emptyOutputFailureMetadata;
|
|
116
117
|
private outputMetadata;
|
|
118
|
+
private normalizeMaxOutputSize;
|
|
117
119
|
private execDirect;
|
|
118
120
|
private connectInternal;
|
|
119
121
|
/**
|
package/dist/session-manager.js
CHANGED
|
@@ -16,6 +16,7 @@ import { ForwardManager } from './forward-manager.js';
|
|
|
16
16
|
import { PtyManager } from './pty-manager.js';
|
|
17
17
|
import { sanitizeKeyError, validateKeyFile } from './security.js';
|
|
18
18
|
import { escapeShellArg, expandTilde } from './tools/utils.js';
|
|
19
|
+
import { DEFAULT_EXEC_MAX_OUTPUT_SIZE, HARD_EXEC_MAX_OUTPUT_SIZE, } from './types.js';
|
|
19
20
|
const OUTPUT_PREVIEW_CHARS = 4096;
|
|
20
21
|
class CommandError extends Error {
|
|
21
22
|
details;
|
|
@@ -36,7 +37,7 @@ export class SessionManager {
|
|
|
36
37
|
defaultKeepaliveCountMax = 3;
|
|
37
38
|
defaultTimeout = 30000; // 30秒
|
|
38
39
|
maxReconnectAttempts = 3;
|
|
39
|
-
defaultMaxOutputSize =
|
|
40
|
+
defaultMaxOutputSize = DEFAULT_EXEC_MAX_OUTPUT_SIZE;
|
|
40
41
|
reconnectDelay = 5000; // 5秒
|
|
41
42
|
constructor(persistPath) {
|
|
42
43
|
this.persistPath = persistPath || path.join(os.homedir(), '.ssh-mcp-pro', 'sessions.json');
|
|
@@ -203,7 +204,7 @@ export class SessionManager {
|
|
|
203
204
|
const session = this.getSession(alias);
|
|
204
205
|
const startTime = Date.now();
|
|
205
206
|
const timeout = options.timeout ?? this.defaultTimeout;
|
|
206
|
-
const maxOutputSize = options.maxOutputSize
|
|
207
|
+
const maxOutputSize = this.normalizeMaxOutputSize(options.maxOutputSize);
|
|
207
208
|
const fullCommand = this.buildCommand(`sudo -S ${command}`, session, options);
|
|
208
209
|
return new Promise((resolve, reject) => {
|
|
209
210
|
let settled = false;
|
|
@@ -267,6 +268,7 @@ export class SessionManager {
|
|
|
267
268
|
stdoutTruncated: stdoutTruncated || undefined,
|
|
268
269
|
stderrTruncated: stderrTruncated || undefined,
|
|
269
270
|
...this.outputMetadata(outputPreview()),
|
|
271
|
+
...this.emptyOutputFailureMetadata(code, outputPreview()),
|
|
270
272
|
...this.resultMetadata(session, options, { cwd: options.cwd }),
|
|
271
273
|
});
|
|
272
274
|
});
|
|
@@ -381,6 +383,16 @@ export class SessionManager {
|
|
|
381
383
|
recommendedReadCommand() {
|
|
382
384
|
return '将远端命令输出重定向到文件,例如 command > /tmp/mcp-ssh-output.txt 2>&1,然后用 ssh_read_file(remotePath="/tmp/mcp-ssh-output.txt", tail=true, maxBytes=65536) 分块读取';
|
|
383
385
|
}
|
|
386
|
+
emptyOutputFailureMetadata(exitCode, preview) {
|
|
387
|
+
if (exitCode === 0 || preview.stdoutBytes > 0 || preview.stderrBytes > 0) {
|
|
388
|
+
return {};
|
|
389
|
+
}
|
|
390
|
+
return {
|
|
391
|
+
emptyOutputFailure: true,
|
|
392
|
+
recommendedReadCommand: this.recommendedReadCommand(),
|
|
393
|
+
suggestion: '远端命令以非零退出码结束,但没有 stdout/stderr。请检查 cwd、effectiveUser、shell/profile,或用 set -x / 显式重定向输出到文件后再用 ssh_read_file 读取',
|
|
394
|
+
};
|
|
395
|
+
}
|
|
384
396
|
outputMetadata(preview) {
|
|
385
397
|
const truncated = preview.stdoutTruncated || preview.stderrTruncated;
|
|
386
398
|
return {
|
|
@@ -397,10 +409,22 @@ export class SessionManager {
|
|
|
397
409
|
: undefined,
|
|
398
410
|
};
|
|
399
411
|
}
|
|
412
|
+
normalizeMaxOutputSize(value) {
|
|
413
|
+
const maxOutputSize = value ?? this.defaultMaxOutputSize;
|
|
414
|
+
if (!Number.isInteger(maxOutputSize) || maxOutputSize <= 0 || maxOutputSize > HARD_EXEC_MAX_OUTPUT_SIZE) {
|
|
415
|
+
throw new CommandError('Invalid maxOutputSize', {
|
|
416
|
+
maxOutputSize,
|
|
417
|
+
min: 1,
|
|
418
|
+
max: HARD_EXEC_MAX_OUTPUT_SIZE,
|
|
419
|
+
suggestion: '使用 1 到 HARD_EXEC_MAX_OUTPUT_SIZE 之间的整数,超大输出请重定向到远端文件后用 ssh_read_file 分块读取',
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
return maxOutputSize;
|
|
423
|
+
}
|
|
400
424
|
async execDirect(alias, command, options = {}, context = {}) {
|
|
401
425
|
const session = this.getSession(alias);
|
|
402
426
|
const startTime = Date.now();
|
|
403
|
-
const maxOutputSize = options.maxOutputSize
|
|
427
|
+
const maxOutputSize = this.normalizeMaxOutputSize(options.maxOutputSize);
|
|
404
428
|
const fullCommand = this.buildCommand(command, session, options);
|
|
405
429
|
return new Promise((resolve, reject) => {
|
|
406
430
|
const timeout = options.timeout ?? this.defaultTimeout;
|
|
@@ -465,6 +489,7 @@ export class SessionManager {
|
|
|
465
489
|
stdoutTruncated: stdoutTruncated || undefined,
|
|
466
490
|
stderrTruncated: stderrTruncated || undefined,
|
|
467
491
|
...this.outputMetadata(outputPreview()),
|
|
492
|
+
...this.emptyOutputFailureMetadata(code, outputPreview()),
|
|
468
493
|
...this.resultMetadata(session, options, context),
|
|
469
494
|
});
|
|
470
495
|
});
|
package/dist/tools/connection.js
CHANGED
|
@@ -266,15 +266,17 @@ async function handleConfigList(args) {
|
|
|
266
266
|
// ========== Register ==========
|
|
267
267
|
export function registerConnectionTools(server) {
|
|
268
268
|
server.registerTool('ssh_connect', {
|
|
269
|
-
description:
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
-
|
|
277
|
-
-
|
|
269
|
+
description: [
|
|
270
|
+
'建立 SSH 连接并保持会话,支持密码、密钥认证,支持跳板机',
|
|
271
|
+
'',
|
|
272
|
+
'可通过 configHost 参数使用 ~/.ssh/config 中的配置,无需重复填写连接信息',
|
|
273
|
+
'支持 Host 多别名、Host * 全局默认继承、ProxyJump(user@host:port 格式)',
|
|
274
|
+
'',
|
|
275
|
+
'示例',
|
|
276
|
+
'- 使用 ssh config,传入 configHost 为 "myserver"',
|
|
277
|
+
'- 密钥认证,传入 host、user、keyPath',
|
|
278
|
+
'- 跳板机,传入 host、user、keyPath 和 jumpHost 配置',
|
|
279
|
+
].join('\n'),
|
|
278
280
|
inputSchema: connectSchema,
|
|
279
281
|
}, (args) => handleConnect(args));
|
|
280
282
|
server.registerTool('ssh_disconnect', {
|
package/dist/tools/exec.js
CHANGED
|
@@ -7,8 +7,16 @@
|
|
|
7
7
|
import { z } from 'zod';
|
|
8
8
|
import * as fileOps from '../file-ops.js';
|
|
9
9
|
import { sessionManager } from '../session-manager.js';
|
|
10
|
+
import { HARD_EXEC_MAX_OUTPUT_SIZE } from '../types.js';
|
|
10
11
|
import { escapeShellArg, formatError, formatResult } from './utils.js'; // ========== Schemas ==========
|
|
11
12
|
// ========== Schemas ==========
|
|
13
|
+
const maxOutputSizeSchema = z
|
|
14
|
+
.number()
|
|
15
|
+
.int()
|
|
16
|
+
.positive()
|
|
17
|
+
.max(HARD_EXEC_MAX_OUTPUT_SIZE)
|
|
18
|
+
.optional()
|
|
19
|
+
.describe('最大输出字符数,超过后截断并返回提示');
|
|
12
20
|
const execSchema = z.object({
|
|
13
21
|
alias: z.string().describe('连接别名'),
|
|
14
22
|
command: z.string().describe('要执行的命令'),
|
|
@@ -19,7 +27,7 @@ const execSchema = z.object({
|
|
|
19
27
|
cwd: z.string().optional().describe('工作目录(可选)'),
|
|
20
28
|
env: z.record(z.string(), z.string()).optional().describe('额外环境变量'),
|
|
21
29
|
pty: z.boolean().optional().describe('是否使用 PTY 模式(用于 top 等交互式命令)'),
|
|
22
|
-
maxOutputSize:
|
|
30
|
+
maxOutputSize: maxOutputSizeSchema,
|
|
23
31
|
runAs: z.string().optional().describe('本次命令使用的目标用户,覆盖连接级 runAs'),
|
|
24
32
|
useLoginUser: z.boolean().optional().describe('设为 true 时跳过连接级 runAs,直接以登录用户执行'),
|
|
25
33
|
loadProfile: z.boolean().optional().describe('runAs 执行时是否加载目标用户 shell 配置,默认 true'),
|
|
@@ -31,7 +39,7 @@ const execAsUserSchema = z.object({
|
|
|
31
39
|
timeout: z.number().optional().describe('超时(毫秒)'),
|
|
32
40
|
cwd: z.string().optional().describe('工作目录(可选)'),
|
|
33
41
|
env: z.record(z.string(), z.string()).optional().describe('额外环境变量'),
|
|
34
|
-
maxOutputSize:
|
|
42
|
+
maxOutputSize: maxOutputSizeSchema,
|
|
35
43
|
loadProfile: z
|
|
36
44
|
.boolean()
|
|
37
45
|
.optional()
|
|
@@ -42,7 +50,7 @@ const execSudoSchema = z.object({
|
|
|
42
50
|
command: z.string().describe('要执行的命令'),
|
|
43
51
|
sudoPassword: z.string().optional().describe('sudo 密码(如果需要)'),
|
|
44
52
|
timeout: z.number().optional().describe('超时(毫秒)'),
|
|
45
|
-
maxOutputSize:
|
|
53
|
+
maxOutputSize: maxOutputSizeSchema,
|
|
46
54
|
});
|
|
47
55
|
const execBatchSchema = z.object({
|
|
48
56
|
alias: z.string().describe('连接别名'),
|
|
@@ -59,10 +67,21 @@ const quickExecSchema = z.object({
|
|
|
59
67
|
port: z.number().optional().describe('端口'),
|
|
60
68
|
timeout: z.number().optional().describe('超时(毫秒)'),
|
|
61
69
|
});
|
|
70
|
+
const EXEC_PARALLEL_MAX_ALIASES = 32;
|
|
71
|
+
const EXEC_PARALLEL_DEFAULT_CONCURRENCY = 4;
|
|
72
|
+
const EXEC_PARALLEL_MAX_CONCURRENCY = 8;
|
|
62
73
|
const execParallelSchema = z.object({
|
|
63
|
-
aliases: z.array(z.string()).describe('连接别名列表'),
|
|
74
|
+
aliases: z.array(z.string()).min(1).max(EXEC_PARALLEL_MAX_ALIASES).describe('连接别名列表'),
|
|
64
75
|
command: z.string().describe('要执行的命令'),
|
|
65
76
|
timeout: z.number().optional().describe('每个命令的超时(毫秒),默认 30000'),
|
|
77
|
+
maxOutputSize: maxOutputSizeSchema,
|
|
78
|
+
maxConcurrency: z
|
|
79
|
+
.number()
|
|
80
|
+
.int()
|
|
81
|
+
.positive()
|
|
82
|
+
.max(EXEC_PARALLEL_MAX_CONCURRENCY)
|
|
83
|
+
.optional()
|
|
84
|
+
.describe('最大并发执行数,默认 4,最大 8'),
|
|
66
85
|
});
|
|
67
86
|
const execScriptSchema = z.object({
|
|
68
87
|
alias: z.string().describe('连接别名'),
|
|
@@ -74,7 +93,7 @@ const execScriptSchema = z.object({
|
|
|
74
93
|
env: z.record(z.string(), z.string()).optional().describe('额外环境变量'),
|
|
75
94
|
timeout: z.number().optional().describe('超时(毫秒)'),
|
|
76
95
|
keepScript: z.boolean().optional().describe('是否保留远端临时脚本,默认 false'),
|
|
77
|
-
maxOutputSize:
|
|
96
|
+
maxOutputSize: maxOutputSizeSchema,
|
|
78
97
|
});
|
|
79
98
|
function pushRisk(categories, signals, category, signal) {
|
|
80
99
|
categories.add(category);
|
|
@@ -103,7 +122,7 @@ function classifyCommandRisk(command) {
|
|
|
103
122
|
if (pipeCount >= 3) {
|
|
104
123
|
pushRisk(categories, signals, 'long-running', 'long_pipeline');
|
|
105
124
|
}
|
|
106
|
-
if (/(
|
|
125
|
+
if (/(^|[^&])&(?!&)/.test(command)) {
|
|
107
126
|
pushRisk(categories, signals, 'process-control', 'background_task');
|
|
108
127
|
}
|
|
109
128
|
if (/\b(?:rm\s+-[a-zA-Z]*r|dd\s+if=|mkfs|fdisk|parted|shutdown|reboot)\b/.test(lowerCommand)) {
|
|
@@ -197,11 +216,13 @@ async function handleExecBatch(args) {
|
|
|
197
216
|
const stopOnError = args.stopOnError !== false;
|
|
198
217
|
const results = [];
|
|
199
218
|
for (let i = 0; i < args.commands.length; i++) {
|
|
219
|
+
const commandRisk = classifyCommandRisk(args.commands[i]);
|
|
200
220
|
try {
|
|
201
221
|
const execResult = await sessionManager.exec(args.alias, args.commands[i], { timeout: args.timeout });
|
|
202
222
|
results.push({
|
|
203
223
|
index: i,
|
|
204
|
-
|
|
224
|
+
commandRedacted: true,
|
|
225
|
+
commandRisk,
|
|
205
226
|
...execResult,
|
|
206
227
|
});
|
|
207
228
|
if (execResult.exitCode !== 0 && stopOnError) {
|
|
@@ -211,7 +232,8 @@ async function handleExecBatch(args) {
|
|
|
211
232
|
catch (err) {
|
|
212
233
|
results.push({
|
|
213
234
|
index: i,
|
|
214
|
-
|
|
235
|
+
commandRedacted: true,
|
|
236
|
+
commandRisk,
|
|
215
237
|
success: false,
|
|
216
238
|
error: err instanceof Error ? err.message : String(err),
|
|
217
239
|
});
|
|
@@ -252,18 +274,30 @@ async function handleQuickExec(args) {
|
|
|
252
274
|
sessionManager.disconnect(tempAlias);
|
|
253
275
|
}
|
|
254
276
|
}
|
|
277
|
+
async function mapWithConcurrency(items, limit, worker) {
|
|
278
|
+
const results = new Array(items.length);
|
|
279
|
+
let nextIndex = 0;
|
|
280
|
+
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
281
|
+
while (nextIndex < items.length) {
|
|
282
|
+
const index = nextIndex++;
|
|
283
|
+
results[index] = await worker(items[index], index);
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
await Promise.all(runners);
|
|
287
|
+
return results;
|
|
288
|
+
}
|
|
255
289
|
async function handleExecParallel(args) {
|
|
256
290
|
try {
|
|
257
|
-
const
|
|
291
|
+
const concurrency = Math.min(args.maxConcurrency ?? EXEC_PARALLEL_DEFAULT_CONCURRENCY, args.aliases.length);
|
|
292
|
+
const results = await mapWithConcurrency(args.aliases, concurrency, async (alias) => {
|
|
258
293
|
try {
|
|
259
|
-
const execResult = await sessionManager.exec(alias, args.command, {
|
|
294
|
+
const execResult = await sessionManager.exec(alias, args.command, {
|
|
295
|
+
timeout: args.timeout,
|
|
296
|
+
maxOutputSize: args.maxOutputSize,
|
|
297
|
+
});
|
|
260
298
|
return {
|
|
261
299
|
alias,
|
|
262
|
-
|
|
263
|
-
exitCode: execResult.exitCode,
|
|
264
|
-
stdout: execResult.stdout,
|
|
265
|
-
stderr: execResult.stderr,
|
|
266
|
-
duration: execResult.duration,
|
|
300
|
+
...execResult,
|
|
267
301
|
};
|
|
268
302
|
}
|
|
269
303
|
catch (err) {
|
|
@@ -274,10 +308,10 @@ async function handleExecParallel(args) {
|
|
|
274
308
|
};
|
|
275
309
|
}
|
|
276
310
|
});
|
|
277
|
-
const results = await Promise.all(execPromises);
|
|
278
311
|
return formatResult({
|
|
279
312
|
success: results.every((r) => r.success),
|
|
280
313
|
total: args.aliases.length,
|
|
314
|
+
concurrency,
|
|
281
315
|
results,
|
|
282
316
|
});
|
|
283
317
|
}
|
package/dist/tools/file.js
CHANGED
|
@@ -75,6 +75,8 @@ const syncSchema = z.object({
|
|
|
75
75
|
.boolean()
|
|
76
76
|
.optional()
|
|
77
77
|
.describe('upload 时是否跟随本地 symlink,默认 false(跳过 symlink 并 warn,避免上传链接目标内容)'),
|
|
78
|
+
verifyOwner: z.union([z.string(), z.number()]).optional().describe('upload 后校验远端 owner(用户名或 uid)'),
|
|
79
|
+
verifyMode: z.string().optional().describe('upload 后校验远端权限,例如 0644 或 -rw-r--r--'),
|
|
78
80
|
});
|
|
79
81
|
// ========== Handlers ==========
|
|
80
82
|
const LARGE_UPLOAD_THRESHOLD = 100 * 1024 * 1024;
|
|
@@ -174,7 +176,7 @@ async function probeRemoteFile(alias, remotePath) {
|
|
|
174
176
|
const escapedRemotePath = escapeShellArg(remotePath);
|
|
175
177
|
const command = [
|
|
176
178
|
`if [ -e ${escapedRemotePath} ]; then`,
|
|
177
|
-
`stat -c '%U\t%u\t%G\t%g\t%a\t%s\t%Y' ${escapedRemotePath};`,
|
|
179
|
+
`stat -c '%U\t%u\t%G\t%g\t%a\t%s\t%Y\t%F' ${escapedRemotePath};`,
|
|
178
180
|
'else printf missing; fi',
|
|
179
181
|
].join(' ');
|
|
180
182
|
try {
|
|
@@ -186,7 +188,9 @@ async function probeRemoteFile(alias, remotePath) {
|
|
|
186
188
|
if (result.stdout.trim() === 'missing') {
|
|
187
189
|
return { exists: false, remotePath };
|
|
188
190
|
}
|
|
189
|
-
const [ownerName, ownerId, groupName, groupId, mode, size, mtimeSeconds] = result.stdout
|
|
191
|
+
const [ownerName, ownerId, groupName, groupId, mode, size, mtimeSeconds, fileType] = result.stdout
|
|
192
|
+
.trim()
|
|
193
|
+
.split('\t');
|
|
190
194
|
return {
|
|
191
195
|
exists: true,
|
|
192
196
|
remotePath,
|
|
@@ -197,6 +201,9 @@ async function probeRemoteFile(alias, remotePath) {
|
|
|
197
201
|
mode: mode ? `0${mode}` : undefined,
|
|
198
202
|
size: Number(size),
|
|
199
203
|
mtimeMs: Number(mtimeSeconds) * 1000,
|
|
204
|
+
fileType,
|
|
205
|
+
isDirectory: fileType === 'directory',
|
|
206
|
+
isFile: fileType?.startsWith('regular ') ?? false,
|
|
200
207
|
};
|
|
201
208
|
}
|
|
202
209
|
catch {
|
|
@@ -210,6 +217,9 @@ async function probeRemoteFile(alias, remotePath) {
|
|
|
210
217
|
permissions: info.permissions,
|
|
211
218
|
size: info.size,
|
|
212
219
|
mtimeMs: info.mtime.getTime(),
|
|
220
|
+
isDirectory: info.isDirectory,
|
|
221
|
+
isFile: info.isFile,
|
|
222
|
+
isSymlink: info.isSymlink,
|
|
213
223
|
};
|
|
214
224
|
}
|
|
215
225
|
}
|
|
@@ -224,7 +234,8 @@ async function buildUploadVerification(args, local) {
|
|
|
224
234
|
checks.mtime = mtimeDelta !== undefined ? mtimeDelta < 2000 : false;
|
|
225
235
|
}
|
|
226
236
|
if (args.verifyMode && remote.exists) {
|
|
227
|
-
|
|
237
|
+
const expectedMode = normalizeExpectedMode(args.verifyMode);
|
|
238
|
+
checks.mode = expectedMode !== undefined && remote.mode === expectedMode;
|
|
228
239
|
}
|
|
229
240
|
if (args.verifyOwner && remote.exists) {
|
|
230
241
|
const expectedOwner = String(args.verifyOwner);
|
|
@@ -244,6 +255,86 @@ async function buildUploadVerification(args, local) {
|
|
|
244
255
|
}
|
|
245
256
|
return { local: summarizeLocalPathProbe(local), remote, checks };
|
|
246
257
|
}
|
|
258
|
+
function normalizeExpectedMode(mode) {
|
|
259
|
+
const trimmed = mode.trim();
|
|
260
|
+
if (/^[0-7]{3,4}$/.test(trimmed)) {
|
|
261
|
+
return trimmed.length === 3 ? `0${trimmed}` : trimmed;
|
|
262
|
+
}
|
|
263
|
+
return permissionStringToOctal(trimmed);
|
|
264
|
+
}
|
|
265
|
+
function buildSyncVerificationChecks(args, remote) {
|
|
266
|
+
const checks = {};
|
|
267
|
+
if (args.verifyOwner !== undefined) {
|
|
268
|
+
const expectedOwner = String(args.verifyOwner);
|
|
269
|
+
checks.owner = remote.exists && (String(remote.ownerId) === expectedOwner || remote.ownerName === expectedOwner);
|
|
270
|
+
}
|
|
271
|
+
if (args.verifyMode !== undefined) {
|
|
272
|
+
const expectedMode = normalizeExpectedMode(args.verifyMode);
|
|
273
|
+
checks.mode = remote.exists && expectedMode !== undefined && remote.mode === expectedMode;
|
|
274
|
+
}
|
|
275
|
+
return checks;
|
|
276
|
+
}
|
|
277
|
+
async function resolveSyncUploadVerificationPath(args, local) {
|
|
278
|
+
const requestedRemote = await probeRemoteFile(args.alias, args.remotePath);
|
|
279
|
+
if (requestedRemote.exists && requestedRemote.isDirectory) {
|
|
280
|
+
return path.posix.join(args.remotePath, path.basename(local.resolvedPath));
|
|
281
|
+
}
|
|
282
|
+
if (!requestedRemote.exists && args.remotePath.endsWith('/')) {
|
|
283
|
+
return path.posix.join(args.remotePath, path.basename(local.resolvedPath));
|
|
284
|
+
}
|
|
285
|
+
return args.remotePath;
|
|
286
|
+
}
|
|
287
|
+
async function buildSyncUploadVerification(args, local) {
|
|
288
|
+
if (args.verifyOwner === undefined && args.verifyMode === undefined) {
|
|
289
|
+
return undefined;
|
|
290
|
+
}
|
|
291
|
+
if (args.direction !== 'upload' || args.dryRun) {
|
|
292
|
+
return {
|
|
293
|
+
kind: 'owner_mode',
|
|
294
|
+
skipped: true,
|
|
295
|
+
reason: 'verifyOwner/verifyMode 只在非 dryRun 的 upload 场景校验远端 owner/mode',
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
if (!local.exists || !local.isFile) {
|
|
299
|
+
return {
|
|
300
|
+
kind: 'owner_mode',
|
|
301
|
+
skipped: true,
|
|
302
|
+
reason: 'verifyOwner/verifyMode 只对单文件 upload 做后置校验,目录同步不会递归扫描远端权限',
|
|
303
|
+
suggestion: '如需目录权限校验,请同步完成后对目标文件调用 ssh_file_info 或用 ssh_exec 执行显式检查',
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
const verificationRemotePath = await resolveSyncUploadVerificationPath(args, local);
|
|
307
|
+
const remote = await probeRemoteFile(args.alias, verificationRemotePath);
|
|
308
|
+
const checks = buildSyncVerificationChecks(args, remote);
|
|
309
|
+
const matched = Object.values(checks).every(Boolean);
|
|
310
|
+
return {
|
|
311
|
+
kind: 'owner_mode',
|
|
312
|
+
matched,
|
|
313
|
+
expected: {
|
|
314
|
+
owner: args.verifyOwner,
|
|
315
|
+
mode: args.verifyMode,
|
|
316
|
+
normalizedMode: args.verifyMode ? normalizeExpectedMode(args.verifyMode) : undefined,
|
|
317
|
+
},
|
|
318
|
+
requestedRemotePath: args.remotePath,
|
|
319
|
+
remote,
|
|
320
|
+
checks,
|
|
321
|
+
suggestion: matched
|
|
322
|
+
? undefined
|
|
323
|
+
: '同步已完成,但远端 owner/mode 与期望不一致;工具不会自动 chown/chmod,请按需用 ssh_exec 显式处理权限',
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
function mergeSyncVerification(existing, ownerMode) {
|
|
327
|
+
if (!ownerMode) {
|
|
328
|
+
return existing;
|
|
329
|
+
}
|
|
330
|
+
if (!existing) {
|
|
331
|
+
return ownerMode;
|
|
332
|
+
}
|
|
333
|
+
return {
|
|
334
|
+
...existing,
|
|
335
|
+
ownerMode,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
247
338
|
async function cleanupRemotePath(alias, remotePath) {
|
|
248
339
|
await sessionManager.exec(alias, `rm -f ${escapeShellArg(remotePath)}`, {
|
|
249
340
|
timeout: 10000,
|
|
@@ -293,7 +384,16 @@ async function handleUpload(args) {
|
|
|
293
384
|
const rename = await sessionManager.exec(args.alias, `mv -f -- ${escapeShellArg(tempRemotePath)} ${escapeShellArg(args.remotePath)}`, { timeout: 30000, useLoginUser: true, maxOutputSize: 4096 });
|
|
294
385
|
if (!rename.success) {
|
|
295
386
|
const renameError = rename.stderr || rename.stdout || `atomic rename failed with exit code ${rename.exitCode}`;
|
|
296
|
-
|
|
387
|
+
await cleanupRemotePath(args.alias, tempRemotePath).catch(() => undefined);
|
|
388
|
+
return formatResult({
|
|
389
|
+
success: false,
|
|
390
|
+
error: renameError,
|
|
391
|
+
diagnostics: {
|
|
392
|
+
local: summarizeLocalPathProbe(local),
|
|
393
|
+
remoteParent,
|
|
394
|
+
atomic: true,
|
|
395
|
+
},
|
|
396
|
+
});
|
|
297
397
|
}
|
|
298
398
|
}
|
|
299
399
|
return formatResult({
|
|
@@ -398,8 +498,9 @@ async function handleMkdir(args) {
|
|
|
398
498
|
}
|
|
399
499
|
}
|
|
400
500
|
async function handleSync(args) {
|
|
501
|
+
const local = fileOps.probeLocalPath(args.localPath);
|
|
401
502
|
const diagnostics = {
|
|
402
|
-
local: summarizeLocalPathProbe(
|
|
503
|
+
local: summarizeLocalPathProbe(local),
|
|
403
504
|
remoteParent: await probeRemoteParent(args.alias, args.remotePath),
|
|
404
505
|
};
|
|
405
506
|
try {
|
|
@@ -410,8 +511,10 @@ async function handleSync(args) {
|
|
|
410
511
|
recursive: args.recursive,
|
|
411
512
|
followSymlinks: args.followSymlinks,
|
|
412
513
|
});
|
|
514
|
+
const ownerModeVerification = syncResult.success ? await buildSyncUploadVerification(args, local) : undefined;
|
|
413
515
|
return formatResult({
|
|
414
516
|
...syncResult,
|
|
517
|
+
verification: mergeSyncVerification(syncResult.verification, ownerModeVerification),
|
|
415
518
|
direction: args.direction,
|
|
416
519
|
localPath: args.localPath,
|
|
417
520
|
remotePath: args.remotePath,
|
package/dist/types.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* SSH MCP Pro - 类型定义
|
|
3
3
|
*/
|
|
4
|
+
export declare const DEFAULT_EXEC_MAX_OUTPUT_SIZE: number;
|
|
5
|
+
export declare const HARD_EXEC_MAX_OUTPUT_SIZE: number;
|
|
4
6
|
export interface SSHConnectionConfig {
|
|
5
7
|
host: string;
|
|
6
8
|
port: number;
|
|
@@ -66,6 +68,7 @@ export interface ExecResult {
|
|
|
66
68
|
stderrBytes?: number;
|
|
67
69
|
recommendedReadCommand?: string;
|
|
68
70
|
suggestion?: string;
|
|
71
|
+
emptyOutputFailure?: boolean;
|
|
69
72
|
loginUser?: string;
|
|
70
73
|
effectiveUser?: string;
|
|
71
74
|
identity?: string;
|
package/dist/types.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pyrokine/mcp-ssh",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "A comprehensive SSH MCP Server for Claude Code",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -39,12 +39,12 @@
|
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
41
|
"@eslint/js": "^10.0.1",
|
|
42
|
-
"@types/node": "^25.9.
|
|
42
|
+
"@types/node": "^25.9.3",
|
|
43
43
|
"@types/ssh2": "^1.15.5",
|
|
44
|
-
"eslint": "^10.
|
|
45
|
-
"prettier": "^3.8.
|
|
44
|
+
"eslint": "^10.5.0",
|
|
45
|
+
"prettier": "^3.8.4",
|
|
46
46
|
"typescript": "^6.0.3",
|
|
47
|
-
"typescript-eslint": "^8.
|
|
47
|
+
"typescript-eslint": "^8.61.0"
|
|
48
48
|
},
|
|
49
49
|
"engines": {
|
|
50
50
|
"node": ">=18.0.0"
|