@pyrokine/mcp-ssh 2.2.0 → 2.3.1

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
@@ -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` 会追加显式传输后校验,`ssh_read_file`
341
- 默认读取 1 MiB,`maxBytes` 超过 16 MiB 时会在远端传输前拒绝,返回 `total_size`、`read_offset`、`read_bytes`、
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
@@ -336,13 +336,21 @@ export async function downloadFile(alias, remotePath, localPath, onProgress, sha
336
336
  localPath = expandTilde(localPath);
337
337
  validateLocalPathAgainstAllowList(localPath);
338
338
  const sftp = sharedSftp ?? (await sessionManager.getSftp(alias));
339
- const totalSize = (await sftpStat(sftp, remotePath)).size;
340
- // 确保本地目录存在
341
- const localDir = path.dirname(localPath);
342
- if (!fs.existsSync(localDir)) {
343
- fs.mkdirSync(localDir, { recursive: true });
339
+ try {
340
+ const totalSize = (await sftpStat(sftp, remotePath)).size;
341
+ // 确保本地目录存在
342
+ const localDir = path.dirname(localPath);
343
+ if (!fs.existsSync(localDir)) {
344
+ fs.mkdirSync(localDir, { recursive: true });
345
+ }
346
+ return await pipeWithProgress(sftp.createReadStream(remotePath), fs.createWriteStream(localPath), sftp, totalSize, onProgress, !sharedSftp);
347
+ }
348
+ catch (error) {
349
+ if (!sharedSftp) {
350
+ sftp.end();
351
+ }
352
+ throw error;
344
353
  }
345
- return pipeWithProgress(sftp.createReadStream(remotePath), fs.createWriteStream(localPath), sftp, totalSize, onProgress, !sharedSftp);
346
354
  }
347
355
  export const DEFAULT_READ_FILE_MAX_BYTES = 1024 * 1024;
348
356
  export const HARD_READ_FILE_MAX_BYTES = 16 * 1024 * 1024;
@@ -393,21 +401,29 @@ function emptyReadResult(totalSize, sampleKind, readOffset = 0) {
393
401
  }
394
402
  async function readLineRange(alias, remotePath, totalSize, maxBytes, lineRange) {
395
403
  const { start, end } = parseLineRange(lineRange);
396
- const command = [
397
- `awk 'NR>=${start} && NR<=${end} { print } NR>${end} { exit }'`,
398
- escapeShellArg(remotePath),
399
- '|',
400
- 'head',
401
- '-c',
402
- String(maxBytes),
404
+ const awkProgram = [
405
+ 'BEGIN { written = 0 }',
406
+ `NR>=${start} && NR<=${end} {`,
407
+ 'line = $0 "\\n"',
408
+ 'remaining = max - written',
409
+ 'if (remaining <= 0) { exit }',
410
+ 'if (length(line) > remaining) { printf "%s", substr(line, 1, remaining); exit }',
411
+ 'printf "%s", line',
412
+ 'written += length(line)',
413
+ '}',
414
+ `NR>${end} { exit }`,
403
415
  ].join(' ');
416
+ const command = `LC_ALL=C awk -v max=${maxBytes} ${escapeShellArg(awkProgram)} ${escapeShellArg(remotePath)}`;
404
417
  const result = await sessionManager.exec(alias, command, {
405
418
  timeout: 30000,
406
419
  useLoginUser: true,
407
420
  maxOutputSize: maxBytes + 4096,
408
421
  });
409
- if (!result.success && result.stderr.trim().length > 0) {
410
- throw new Error(result.stderr.trim());
422
+ if (!result.success) {
423
+ const message = result.stderr.trim() ||
424
+ result.stdout.trim() ||
425
+ `remote lineRange command failed with exit code ${result.exitCode}`;
426
+ throw new Error(message);
411
427
  }
412
428
  const readBytes = Buffer.byteLength(result.stdout, 'utf-8');
413
429
  return {
@@ -430,7 +446,14 @@ export async function readFile(alias, remotePath, options) {
430
446
  const readOptions = normalizeReadFileOptions(options);
431
447
  validateReadFileOptions(readOptions);
432
448
  const sftp = await sessionManager.getSftp(alias);
433
- const actualSize = (await sftpStat(sftp, remotePath)).size;
449
+ let actualSize;
450
+ try {
451
+ actualSize = (await sftpStat(sftp, remotePath)).size;
452
+ }
453
+ catch (error) {
454
+ sftp.end();
455
+ throw error;
456
+ }
434
457
  if (readOptions.lineRange) {
435
458
  sftp.end();
436
459
  return readLineRange(alias, remotePath, actualSize, readOptions.maxBytes, readOptions.lineRange);
@@ -490,17 +513,18 @@ export async function readFile(alias, remotePath, options) {
490
513
  export async function writeFile(alias, remotePath, content, append = false) {
491
514
  const sftp = await sessionManager.getSftp(alias);
492
515
  const flags = append ? 'a' : 'w';
516
+ const contentBuffer = Buffer.from(content, 'utf-8');
493
517
  return new Promise((resolve, reject) => {
494
518
  const writeStream = sftp.createWriteStream(remotePath, { flags });
495
519
  writeStream.on('close', () => {
496
520
  sftp.end();
497
- resolve({ success: true, size: content.length });
521
+ resolve({ success: true, size: contentBuffer.length });
498
522
  });
499
523
  writeStream.on('error', (err) => {
500
524
  sftp.end();
501
525
  reject(err);
502
526
  });
503
- writeStream.write(content);
527
+ writeStream.write(contentBuffer);
504
528
  writeStream.end();
505
529
  });
506
530
  }
@@ -894,6 +918,21 @@ async function buildSingleFileVerification(alias, localPath, remotePath, directi
894
918
  },
895
919
  };
896
920
  }
921
+ async function resolveSftpUploadFileTarget(alias, localPath, remotePath) {
922
+ if (remotePath.endsWith('/')) {
923
+ return path.posix.join(remotePath, path.basename(localPath));
924
+ }
925
+ try {
926
+ const info = await getFileInfo(alias, remotePath);
927
+ if (info.isDirectory) {
928
+ return path.posix.join(remotePath, path.basename(localPath));
929
+ }
930
+ }
931
+ catch {
932
+ // Missing remote targets are handled by uploadFile below.
933
+ }
934
+ return remotePath;
935
+ }
897
936
  async function syncWithSftp(alias, localPath, remotePath, direction, options) {
898
937
  const warnings = [];
899
938
  if (options.delete) {
@@ -912,6 +951,7 @@ async function syncWithSftp(alias, localPath, remotePath, direction, options) {
912
951
  recursive: options.recursive !== false,
913
952
  followSymlinks: options.followSymlinks === true,
914
953
  deleteRequested: options.delete === true,
954
+ deleteSupported: options.delete ? false : undefined,
915
955
  excludeCount: options.exclude?.length ?? 0,
916
956
  localExists,
917
957
  localIsDirectory: localStats?.isDirectory(),
@@ -923,6 +963,14 @@ async function syncWithSftp(alias, localPath, remotePath, direction, options) {
923
963
  (warnings.length ? `. Warning: ${warnings.join('; ')}` : ''),
924
964
  };
925
965
  }
966
+ if (options.delete) {
967
+ return {
968
+ success: false,
969
+ method: 'sftp',
970
+ stats: { added: 0, updated: 0, deleted: 0, skipped: 0, failed: 1 },
971
+ output: 'delete option is not supported in SFTP mode (requires rsync)',
972
+ };
973
+ }
926
974
  try {
927
975
  if (direction === 'upload') {
928
976
  const stats = options.followSymlinks ? fs.statSync(localPath) : fs.lstatSync(localPath);
@@ -938,11 +986,12 @@ async function syncWithSftp(alias, localPath, remotePath, direction, options) {
938
986
  const result = await uploadDirectory(alias, localPath, remotePath, options.exclude, undefined, options.followSymlinks ?? false, { files: 0, directories: 0, bytes: 0 }, 0);
939
987
  return buildDirectorySyncResult(result, warnings);
940
988
  }
941
- const existed = await remoteExists(alias, remotePath);
942
- const { size } = await uploadFile(alias, localPath, remotePath);
989
+ const targetRemotePath = await resolveSftpUploadFileTarget(alias, localPath, remotePath);
990
+ const existed = await remoteExists(alias, targetRemotePath);
991
+ const { size } = await uploadFile(alias, localPath, targetRemotePath);
943
992
  return {
944
993
  ...buildSyncResult(1, size, warnings, 0, { added: existed ? 0 : 1, updated: existed ? 1 : 0 }),
945
- verification: await buildSingleFileVerification(alias, localPath, remotePath, 'upload'),
994
+ verification: await buildSingleFileVerification(alias, localPath, targetRemotePath, 'upload'),
946
995
  };
947
996
  }
948
997
  // download
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import type { ClientChannel } from 'ssh2';
7
7
  import type { PtyOptions, PtySessionInfo } from './types.js';
8
+ export declare const HARD_PTY_BUFFER_SIZE: number;
8
9
  /** PTY 创建所需的外部依赖 */
9
10
  export interface PtyDependencies {
10
11
  /** 通过 alias 获取 SSH client 并执行命令 */
@@ -39,6 +40,7 @@ export declare class PtyManager {
39
40
  /** 关闭指定 alias 的所有 PTY 会话 */
40
41
  closeByAlias(alias: string): void;
41
42
  list(): PtySessionInfo[];
43
+ private normalizeBufferSize;
42
44
  private startIdleSweeper;
43
45
  private sweepIdle;
44
46
  private getSession;
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import xterm from '@xterm/headless';
7
7
  const Terminal = xterm.Terminal;
8
+ export const HARD_PTY_BUFFER_SIZE = 16 * 1024 * 1024;
8
9
  export class PtyManager {
9
10
  sessions = new Map();
10
11
  idCounter = 0;
@@ -19,7 +20,7 @@ export class PtyManager {
19
20
  const ptyId = this.generateId();
20
21
  const rows = options.rows || 24;
21
22
  const cols = options.cols || 80;
22
- const maxBufferSize = options.bufferSize || this.defaultBufferSize;
23
+ const maxBufferSize = this.normalizeBufferSize(options.bufferSize);
23
24
  const stream = await deps.execPty(alias, command, options);
24
25
  // 创建 xterm headless 终端仿真器
25
26
  const terminal = new Terminal({ rows, cols, allowProposedApi: true });
@@ -173,6 +174,15 @@ export class PtyManager {
173
174
  }
174
175
  return result;
175
176
  }
177
+ normalizeBufferSize(bufferSize) {
178
+ if (bufferSize === undefined) {
179
+ return this.defaultBufferSize;
180
+ }
181
+ if (!Number.isSafeInteger(bufferSize) || bufferSize <= 0 || bufferSize > HARD_PTY_BUFFER_SIZE) {
182
+ throw new Error(`bufferSize 必须是 1 到 ${HARD_PTY_BUFFER_SIZE} 之间的整数`);
183
+ }
184
+ return bufferSize;
185
+ }
176
186
  startIdleSweeper() {
177
187
  if (this.idleSweeper) {
178
188
  return;
@@ -113,6 +113,7 @@ export declare class SessionManager {
113
113
  private resultMetadata;
114
114
  private appendOutputTail;
115
115
  private recommendedReadCommand;
116
+ private emptyOutputFailureMetadata;
116
117
  private outputMetadata;
117
118
  private normalizeMaxOutputSize;
118
119
  private execDirect;
@@ -268,6 +268,7 @@ export class SessionManager {
268
268
  stdoutTruncated: stdoutTruncated || undefined,
269
269
  stderrTruncated: stderrTruncated || undefined,
270
270
  ...this.outputMetadata(outputPreview()),
271
+ ...this.emptyOutputFailureMetadata(code, outputPreview()),
271
272
  ...this.resultMetadata(session, options, { cwd: options.cwd }),
272
273
  });
273
274
  });
@@ -382,6 +383,16 @@ export class SessionManager {
382
383
  recommendedReadCommand() {
383
384
  return '将远端命令输出重定向到文件,例如 command > /tmp/mcp-ssh-output.txt 2>&1,然后用 ssh_read_file(remotePath="/tmp/mcp-ssh-output.txt", tail=true, maxBytes=65536) 分块读取';
384
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
+ }
385
396
  outputMetadata(preview) {
386
397
  const truncated = preview.stdoutTruncated || preview.stderrTruncated;
387
398
  return {
@@ -427,6 +438,7 @@ export class SessionManager {
427
438
  let stdoutTruncated = false;
428
439
  let stderrTruncated = false;
429
440
  let settled = false;
441
+ let activeStream = null;
430
442
  const execOptions = {};
431
443
  if (options.pty) {
432
444
  execOptions.pty = {
@@ -435,39 +447,51 @@ export class SessionManager {
435
447
  term: options.term || 'xterm-256color',
436
448
  };
437
449
  }
450
+ const outputPreview = () => ({
451
+ stdout,
452
+ stderr,
453
+ stdoutTail,
454
+ stderrTail,
455
+ stdoutBytes,
456
+ stderrBytes,
457
+ stdoutTruncated,
458
+ stderrTruncated,
459
+ maxOutputSize,
460
+ });
461
+ const clearTimer = () => {
462
+ if (timeoutId) {
463
+ clearTimeout(timeoutId);
464
+ timeoutId = null;
465
+ }
466
+ };
467
+ const rejectOnce = (error) => {
468
+ if (settled) {
469
+ return;
470
+ }
471
+ settled = true;
472
+ clearTimer();
473
+ activeStream?.close();
474
+ reject(error);
475
+ };
476
+ timeoutId = setTimeout(() => {
477
+ rejectOnce(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
478
+ }, timeout);
438
479
  session.client.exec(fullCommand, execOptions, (err, stream) => {
439
480
  if (err) {
440
- settled = true;
441
- reject(new Error(`Exec failed: ${err.message}`));
481
+ rejectOnce(new Error(`Exec failed: ${err.message}`));
442
482
  return;
443
483
  }
444
- const outputPreview = () => ({
445
- stdout,
446
- stderr,
447
- stdoutTail,
448
- stderrTail,
449
- stdoutBytes,
450
- stderrBytes,
451
- stdoutTruncated,
452
- stderrTruncated,
453
- maxOutputSize,
454
- });
455
- timeoutId = setTimeout(() => {
456
- if (settled) {
457
- return;
458
- }
459
- settled = true;
484
+ if (settled) {
460
485
  stream.close();
461
- reject(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
462
- }, timeout);
486
+ return;
487
+ }
488
+ activeStream = stream;
463
489
  stream.on('close', (code) => {
464
- if (timeoutId) {
465
- clearTimeout(timeoutId);
466
- }
467
490
  if (settled) {
468
491
  return;
469
492
  }
470
493
  settled = true;
494
+ clearTimer();
471
495
  resolve({
472
496
  success: code === 0,
473
497
  stdout: stdoutTruncated ? stdout + '\n... [truncated]' : stdout,
@@ -478,6 +502,7 @@ export class SessionManager {
478
502
  stdoutTruncated: stdoutTruncated || undefined,
479
503
  stderrTruncated: stderrTruncated || undefined,
480
504
  ...this.outputMetadata(outputPreview()),
505
+ ...this.emptyOutputFailureMetadata(code, outputPreview()),
481
506
  ...this.resultMetadata(session, options, context),
482
507
  });
483
508
  });
@@ -67,10 +67,21 @@ const quickExecSchema = z.object({
67
67
  port: z.number().optional().describe('端口'),
68
68
  timeout: z.number().optional().describe('超时(毫秒)'),
69
69
  });
70
+ const EXEC_PARALLEL_MAX_ALIASES = 32;
71
+ const EXEC_PARALLEL_DEFAULT_CONCURRENCY = 4;
72
+ const EXEC_PARALLEL_MAX_CONCURRENCY = 8;
70
73
  const execParallelSchema = z.object({
71
- aliases: z.array(z.string()).describe('连接别名列表'),
74
+ aliases: z.array(z.string()).min(1).max(EXEC_PARALLEL_MAX_ALIASES).describe('连接别名列表'),
72
75
  command: z.string().describe('要执行的命令'),
73
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'),
74
85
  });
75
86
  const execScriptSchema = z.object({
76
87
  alias: z.string().describe('连接别名'),
@@ -111,7 +122,7 @@ function classifyCommandRisk(command) {
111
122
  if (pipeCount >= 3) {
112
123
  pushRisk(categories, signals, 'long-running', 'long_pipeline');
113
124
  }
114
- if (/(^|[^&])&(?!&)/.test(command)) {
125
+ if (/(?:^|[^&])&(?!&)/.test(command)) {
115
126
  pushRisk(categories, signals, 'process-control', 'background_task');
116
127
  }
117
128
  if (/\b(?:rm\s+-[a-zA-Z]*r|dd\s+if=|mkfs|fdisk|parted|shutdown|reboot)\b/.test(lowerCommand)) {
@@ -263,18 +274,30 @@ async function handleQuickExec(args) {
263
274
  sessionManager.disconnect(tempAlias);
264
275
  }
265
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
+ }
266
289
  async function handleExecParallel(args) {
267
290
  try {
268
- const execPromises = args.aliases.map(async (alias) => {
291
+ const concurrency = Math.min(args.maxConcurrency ?? EXEC_PARALLEL_DEFAULT_CONCURRENCY, args.aliases.length);
292
+ const results = await mapWithConcurrency(args.aliases, concurrency, async (alias) => {
269
293
  try {
270
- const execResult = await sessionManager.exec(alias, args.command, { timeout: args.timeout });
294
+ const execResult = await sessionManager.exec(alias, args.command, {
295
+ timeout: args.timeout,
296
+ maxOutputSize: args.maxOutputSize,
297
+ });
271
298
  return {
272
299
  alias,
273
- success: execResult.success,
274
- exitCode: execResult.exitCode,
275
- stdout: execResult.stdout,
276
- stderr: execResult.stderr,
277
- duration: execResult.duration,
300
+ ...execResult,
278
301
  };
279
302
  }
280
303
  catch (err) {
@@ -285,10 +308,10 @@ async function handleExecParallel(args) {
285
308
  };
286
309
  }
287
310
  });
288
- const results = await Promise.all(execPromises);
289
311
  return formatResult({
290
312
  success: results.every((r) => r.success),
291
313
  total: args.aliases.length,
314
+ concurrency,
292
315
  results,
293
316
  });
294
317
  }
@@ -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.trim().split('\t');
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,9 +234,10 @@ async function buildUploadVerification(args, local) {
224
234
  checks.mtime = mtimeDelta !== undefined ? mtimeDelta < 2000 : false;
225
235
  }
226
236
  if (args.verifyMode && remote.exists) {
227
- checks.mode = remote.mode === args.verifyMode || remote.mode === args.verifyMode.replace(/^0?/, '0');
237
+ const expectedMode = normalizeExpectedMode(args.verifyMode);
238
+ checks.mode = expectedMode !== undefined && remote.mode === expectedMode;
228
239
  }
229
- if (args.verifyOwner && remote.exists) {
240
+ if (args.verifyOwner !== undefined && remote.exists) {
230
241
  const expectedOwner = String(args.verifyOwner);
231
242
  checks.owner = String(remote.ownerId) === expectedOwner || remote.ownerName === expectedOwner;
232
243
  }
@@ -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,
@@ -407,8 +498,9 @@ async function handleMkdir(args) {
407
498
  }
408
499
  }
409
500
  async function handleSync(args) {
501
+ const local = fileOps.probeLocalPath(args.localPath);
410
502
  const diagnostics = {
411
- local: summarizeLocalPathProbe(fileOps.probeLocalPath(args.localPath)),
503
+ local: summarizeLocalPathProbe(local),
412
504
  remoteParent: await probeRemoteParent(args.alias, args.remotePath),
413
505
  };
414
506
  try {
@@ -419,8 +511,10 @@ async function handleSync(args) {
419
511
  recursive: args.recursive,
420
512
  followSymlinks: args.followSymlinks,
421
513
  });
514
+ const ownerModeVerification = syncResult.success ? await buildSyncUploadVerification(args, local) : undefined;
422
515
  return formatResult({
423
516
  ...syncResult,
517
+ verification: mergeSyncVerification(syncResult.verification, ownerModeVerification),
424
518
  direction: args.direction,
425
519
  localPath: args.localPath,
426
520
  remotePath: args.remotePath,
package/dist/tools/pty.js CHANGED
@@ -4,6 +4,7 @@
4
4
  * ssh_pty_start, ssh_pty_write, ssh_pty_read, ssh_pty_resize, ssh_pty_close, ssh_pty_list
5
5
  */
6
6
  import { z } from 'zod';
7
+ import { HARD_PTY_BUFFER_SIZE } from '../pty-manager.js';
7
8
  import { sessionManager } from '../session-manager.js';
8
9
  import { formatError, formatResult } from './utils.js'; // ========== Schemas ==========
9
10
  // ========== Schemas ==========
@@ -15,7 +16,13 @@ const ptyStartSchema = z.object({
15
16
  term: z.string().optional().describe('终端类型,默认 xterm-256color'),
16
17
  cwd: z.string().optional().describe('工作目录'),
17
18
  env: z.record(z.string(), z.string()).optional().describe('环境变量'),
18
- bufferSize: z.number().optional().describe('输出缓冲区大小(字节),默认 1MB'),
19
+ bufferSize: z
20
+ .number()
21
+ .int()
22
+ .positive()
23
+ .max(HARD_PTY_BUFFER_SIZE)
24
+ .optional()
25
+ .describe('输出缓冲区大小(字节),默认 1MB'),
19
26
  });
20
27
  const ptyWriteSchema = z.object({
21
28
  ptyId: z.string().describe('PTY 会话 ID'),
package/dist/types.d.ts CHANGED
@@ -68,6 +68,7 @@ export interface ExecResult {
68
68
  stderrBytes?: number;
69
69
  recommendedReadCommand?: string;
70
70
  suggestion?: string;
71
+ emptyOutputFailure?: boolean;
71
72
  loginUser?: string;
72
73
  effectiveUser?: string;
73
74
  identity?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyrokine/mcp-ssh",
3
- "version": "2.2.0",
3
+ "version": "2.3.1",
4
4
  "description": "A comprehensive SSH MCP Server for Claude Code",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -29,7 +29,7 @@
29
29
  "license": "MIT",
30
30
  "repository": {
31
31
  "type": "git",
32
- "url": "https://github.com/Pyrokine/claude-tools.git"
32
+ "url": "git+https://github.com/Pyrokine/claude-tools.git"
33
33
  },
34
34
  "dependencies": {
35
35
  "@modelcontextprotocol/sdk": "^1.29.0",