@pyrokine/mcp-ssh 3.0.0 → 3.1.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.
@@ -4,16 +4,16 @@
4
4
  * ssh_upload, ssh_download, ssh_read_file, ssh_write_file,
5
5
  * ssh_list_dir, ssh_file_info, ssh_mkdir, ssh_sync
6
6
  */
7
- import { createHash, randomBytes } from 'crypto';
7
+ import { randomBytes } from 'crypto';
8
8
  import * as fs from 'fs';
9
9
  import * as path from 'path';
10
10
  import { z } from 'zod';
11
- import { compareDirectoryManifests, createEmptyDirectoryManifest, createLocalDirectoryManifest, createRemoteDirectoryManifest, DIRECTORY_VERIFY_MAX_ENTRIES, DIRECTORY_VERIFY_MAX_FILE_BYTES, DIRECTORY_VERIFY_MAX_TOTAL_BYTES, } from '../directory-verification.js';
11
+ import { compareDirectoryManifests, createEmptyDirectoryManifest, createLocalDirectoryManifest, createRemoteDirectoryManifest, createOpenSshDirectoryManifest, matchesDirectoryExclude, DIRECTORY_VERIFY_MAX_ENTRIES, DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES, DIRECTORY_VERIFY_DEFAULT_MAX_TOTAL_BYTES, DIRECTORY_VERIFY_MAX_FILE_BYTES, DIRECTORY_VERIFY_MAX_TOTAL_BYTES, } from '../directory-verification.js';
12
12
  import { FILE_CREATE_MODE_MASK, formatFileMode, parseExpectedFileMode } from '../file-mode.js';
13
13
  import * as fileOps from '../file-ops.js';
14
14
  import { sessionManager } from '../session-manager.js';
15
15
  import { withSftpOperationTimeout } from '../sftp-timeout.js';
16
- import { encodedPowershell, quotePowershell, remoteDirname, remoteJoin, remoteShellPath, sftpPath, } from '../remote-platform.js';
16
+ import { encodedPowershell, quotePowershell, remoteDirname, remoteJoin, remotePathModule, remoteShellPath, sftpPath, } from '../remote-platform.js';
17
17
  import { buildTransferOutcome } from '../transfer-outcome.js';
18
18
  import { operationTimeoutSchema } from './schema.js';
19
19
  import { escapeShellArg, formatError, formatResult } from './utils.js';
@@ -71,12 +71,43 @@ const writeFileSchema = z.object({
71
71
  append: z.boolean().optional().describe('是否追加模式,默认覆盖'),
72
72
  timeout: operationTimeoutSchema.optional(),
73
73
  });
74
- const listDirSchema = z.object({
74
+ function compareDirectoryTimes(left, right) {
75
+ const milliseconds = Date.parse(left) - Date.parse(right);
76
+ if (milliseconds !== 0)
77
+ return milliseconds;
78
+ // 保留 ISO 8601 的亚毫秒部分,避免 Date.parse 截断时间边界
79
+ const [leftFraction, rightFraction] = [left, right].map((value) => (value.match(/\.(\d+)/)?.[1].slice(3) ?? '').replace(/0+$/, ''));
80
+ return leftFraction < rightFraction ? -1 : leftFraction > rightFraction ? 1 : 0;
81
+ }
82
+ const listDirSchema = z
83
+ .object({
75
84
  alias: z.string().describe('连接别名'),
76
85
  remotePath: z.string().describe('远程目录路径'),
77
86
  showHidden: z.boolean().optional().describe('是否显示隐藏文件'),
87
+ namePattern: z.string().optional().describe('名称通配模式,复用同步 exclude 的 * 和 ? 规则,区分大小写'),
88
+ modifiedAfter: z
89
+ .string()
90
+ .datetime({ offset: true })
91
+ .optional()
92
+ .describe('修改时间下界,包含;使用带时区的 ISO 8601 时间'),
93
+ modifiedBefore: z
94
+ .string()
95
+ .datetime({ offset: true })
96
+ .optional()
97
+ .describe('修改时间上界,不包含;使用带时区的 ISO 8601 时间'),
98
+ offset: z.number().int().nonnegative().optional().describe('筛选并排序后的条目偏移,默认 0'),
99
+ limit: z.number().int().positive().optional().describe('单页最多条数,使用任一新参数时默认 100'),
100
+ maxBytes: z
101
+ .number()
102
+ .int()
103
+ .positive()
104
+ .optional()
105
+ .describe('响应 JSON 文本的 UTF-8 字节预算,包含分页元数据;使用任一新参数时默认 65536'),
78
106
  timeout: operationTimeoutSchema.optional(),
79
- });
107
+ })
108
+ .refine((args) => args.modifiedAfter === undefined ||
109
+ args.modifiedBefore === undefined ||
110
+ compareDirectoryTimes(args.modifiedAfter, args.modifiedBefore) <= 0, { message: 'modifiedAfter must be at or before modifiedBefore', path: ['modifiedAfter'] });
80
111
  const fileInfoSchema = z.object({
81
112
  alias: z.string().describe('连接别名'),
82
113
  remotePath: z.string().describe('远程路径'),
@@ -109,7 +140,7 @@ const syncSchema = z.object({
109
140
  verify: z
110
141
  .object({
111
142
  count: z.boolean().optional().describe('校验目录条目数'),
112
- sha256: z.boolean().optional().describe('校验 SHA-256 root manifest'),
143
+ sha256: z.boolean().optional().describe('校验文件 SHA-256 或目录 SHA-256 root manifest'),
113
144
  owner: z.boolean().optional().describe('逐项校验 owner'),
114
145
  mode: z.boolean().optional().describe('逐项校验 POSIX mode;Windows 不支持'),
115
146
  aclSddl: z
@@ -117,7 +148,7 @@ const syncSchema = z.object({
117
148
  .min(1)
118
149
  .max(8192)
119
150
  .optional()
120
- .describe('Windows 远端目录根路径的预期 DACL SDDL,独立于 POSIX mode/owner'),
151
+ .describe('Windows 远端文件或目录根路径的预期 DACL SDDL,独立于 POSIX mode/owner'),
121
152
  deletions: z.boolean().optional().describe('校验请求删除后没有额外条目'),
122
153
  staleFiles: z.boolean().optional().describe('校验没有旧文件残留'),
123
154
  maxEntries: z
@@ -143,7 +174,7 @@ const syncSchema = z.object({
143
174
  .describe('SHA-256 校验的总字节上限,默认 1GB,最大 16GB'),
144
175
  })
145
176
  .optional()
146
- .describe('有界目录校验;未传时不执行额外远端扫描'),
177
+ .describe('有界文件或目录校验;count/deletions/staleFiles 仅适用于目录,未传时不执行额外远端扫描'),
147
178
  });
148
179
  // ========== Handlers ==========
149
180
  const LARGE_UPLOAD_THRESHOLD = 100 * 1024 * 1024;
@@ -240,29 +271,21 @@ function uploadPathError(code, message, diagnostics) {
240
271
  function normalizeRemotePath(alias, remotePath) {
241
272
  return sftpPath(remotePath, sessionManager.getRemotePathStyle(alias));
242
273
  }
243
- async function probeRemoteParent(alias, remotePath) {
274
+ async function probeRemoteParent(alias, remotePath, timeout) {
244
275
  const parent = remoteDirname(sessionManager.getRemotePathStyle(alias), remotePath);
276
+ const probeMethod = sessionManager.getOpenSshConnection(alias) ? 'openssh' : 'sftp';
245
277
  try {
246
- const result = await probeRemoteFile(alias, parent);
278
+ const result = await probeRemoteFile(alias, parent, timeout);
247
279
  return {
248
280
  exists: result.exists,
249
281
  isDirectory: result.exists ? result.isDirectory : false,
250
- probeMethod: 'sftp',
282
+ probeMethod,
251
283
  };
252
284
  }
253
285
  catch (error) {
254
- return { error: error instanceof Error ? error.message : String(error), probeMethod: 'sftp' };
286
+ return { error: error instanceof Error ? error.message : String(error), probeMethod };
255
287
  }
256
288
  }
257
- function hashLocalFileMd5(filePath) {
258
- return new Promise((resolve, reject) => {
259
- const hash = createHash('md5');
260
- const stream = fs.createReadStream(filePath);
261
- stream.on('data', (chunk) => hash.update(chunk));
262
- stream.on('error', reject);
263
- stream.on('end', () => resolve(hash.digest('hex')));
264
- });
265
- }
266
289
  function boundedDiagnostic(value, maxBytes = 2048) {
267
290
  const buffer = Buffer.from(value, 'utf8');
268
291
  if (buffer.length <= maxBytes) {
@@ -289,21 +312,21 @@ function commandFailureDetails(result) {
289
312
  stderrTruncated: result.stderrTruncated || stderr.truncated || undefined,
290
313
  };
291
314
  }
292
- async function hashRemoteFileMd5(alias, remotePath) {
315
+ async function hashRemoteFileMd5(alias, remotePath, timeout) {
293
316
  try {
294
- return await fileOps.hashRemoteFileDigest(alias, remotePath, 'md5');
317
+ return await fileOps.hashRemoteFileDigest(alias, remotePath, 'md5', timeout);
295
318
  }
296
319
  catch (error) {
297
320
  throw new VerificationStageError('remote_probe', `Remote SFTP MD5 read failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'md5', probeMethod: 'sftp' });
298
321
  }
299
322
  }
300
- async function resolveExpectedOwnerId(alias, owner) {
323
+ async function resolveExpectedOwnerId(alias, owner, timeout = 10000) {
301
324
  const ownerText = String(owner);
302
325
  if (/^\d+$/.test(ownerText)) {
303
326
  return ownerText;
304
327
  }
305
328
  const result = await sessionManager.exec(alias, `id -u ${escapeShellArg(ownerText)}`, {
306
- timeout: 10000,
329
+ timeout,
307
330
  useLoginUser: true,
308
331
  maxOutputSize: 4096,
309
332
  });
@@ -326,20 +349,21 @@ function isRemoteMissingError(error) {
326
349
  return code === 2 || code === 'ENOENT' || /no such file|not found/i.test(message);
327
350
  }
328
351
  async function probeRemoteFile(alias, remotePath, timeout = 10000) {
352
+ const probeMethod = sessionManager.getOpenSshConnection(alias) ? 'openssh' : 'sftp';
329
353
  let info;
330
354
  try {
331
355
  info = await fileOps.getFileInfo(alias, remotePath, timeout);
332
356
  }
333
357
  catch (error) {
334
358
  if (isRemoteMissingError(error)) {
335
- return { exists: false, remotePath, probeMethod: 'sftp' };
359
+ return { exists: false, remotePath, probeMethod };
336
360
  }
337
- throw new VerificationStageError('remote_probe', `Remote SFTP stat failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'stat', probeMethod: 'sftp' });
361
+ throw new VerificationStageError('remote_probe', `Remote file stat failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'stat', probeMethod });
338
362
  }
339
363
  return {
340
364
  exists: true,
341
365
  remotePath,
342
- probeMethod: 'sftp',
366
+ probeMethod,
343
367
  ownerName: undefined,
344
368
  ownerId: info.owner,
345
369
  groupName: undefined,
@@ -361,7 +385,7 @@ async function probeRemoteFile(alias, remotePath, timeout = 10000) {
361
385
  };
362
386
  }
363
387
  async function buildUploadVerification(args, local, verificationRemotePath = args.remotePath) {
364
- const remote = await probeRemoteFile(args.alias, verificationRemotePath);
388
+ const remote = await probeRemoteFile(args.alias, verificationRemotePath, args.timeout);
365
389
  const checks = {};
366
390
  if (args.verifySize) {
367
391
  checks.size = local.exists && remote.exists ? local.size === remote.size : false;
@@ -375,13 +399,13 @@ async function buildUploadVerification(args, local, verificationRemotePath = arg
375
399
  checks.mode = remote.exists && expectedMode !== undefined && remote.modeValue === expectedMode;
376
400
  }
377
401
  if (args.verifyOwner !== undefined) {
378
- const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner);
402
+ const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner, args.timeout);
379
403
  checks.owner = remote.exists && String(remote.ownerId) === expectedOwnerId;
380
404
  }
381
405
  if (args.verifyMd5 && local.exists) {
382
406
  const [localMd5, remoteMd5] = await Promise.all([
383
- hashLocalFileMd5(local.resolvedPath),
384
- hashRemoteFileMd5(args.alias, verificationRemotePath),
407
+ fileOps.hashLocalFile(local.resolvedPath, 'md5', args.timeout),
408
+ hashRemoteFileMd5(args.alias, verificationRemotePath, args.timeout),
385
409
  ]);
386
410
  checks.md5 = remoteMd5 ? localMd5 === remoteMd5 : undefined;
387
411
  return {
@@ -433,10 +457,10 @@ async function buildSyncVerificationChecks(args, remote) {
433
457
  async function resolveSyncUploadVerificationPath(args, local, timeout) {
434
458
  const requestedRemote = await probeRemoteFile(args.alias, args.remotePath, timeout);
435
459
  if (requestedRemote.exists && requestedRemote.isDirectory) {
436
- return remoteJoin(sessionManager.getRemotePathStyle(args.alias), args.remotePath, path.basename(local.resolvedPath));
460
+ return remoteJoin(sessionManager.getRemotePathStyle(args.alias), args.remotePath, path.basename(local.expandedPath));
437
461
  }
438
462
  if (!requestedRemote.exists && args.remotePath.endsWith('/')) {
439
- return remoteJoin(sessionManager.getRemotePathStyle(args.alias), args.remotePath, path.basename(local.resolvedPath));
463
+ return remoteJoin(sessionManager.getRemotePathStyle(args.alias), args.remotePath, path.basename(local.expandedPath));
440
464
  }
441
465
  return args.remotePath;
442
466
  }
@@ -483,6 +507,9 @@ async function buildSyncUploadVerification(args, local, timeout) {
483
507
  };
484
508
  }
485
509
  async function captureRemoteDirectoryManifest(alias, remotePath, request, exclude, followSymlinks, timeout) {
510
+ const connection = sessionManager.getOpenSshConnection(alias);
511
+ if (connection)
512
+ return createOpenSshDirectoryManifest(connection, remotePath, request, timeout, exclude, followSymlinks);
486
513
  const requestSftp = sessionManager.getSftp(alias);
487
514
  const sftp = await withSftpOperationTimeout(requestSftp, timeout, () => {
488
515
  void requestSftp.then((late) => late.end(), () => undefined);
@@ -548,6 +575,79 @@ async function captureDeletionBaseline(args, remainingTimeout) {
548
575
  throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
549
576
  }
550
577
  }
578
+ async function buildSingleFileSyncVerification(args, local, timeout) {
579
+ if (!args.verify)
580
+ return undefined;
581
+ if (args.dryRun)
582
+ return { kind: 'single_file', skipped: true, reason: 'file verification is not executed during dryRun' };
583
+ if (!local.exists || !local.isFile)
584
+ throw new VerificationStageError('local_manifest', 'File verification requires the transferred local file', false);
585
+ const deadline = Date.now() + timeout;
586
+ const remaining = () => {
587
+ const value = deadline - Date.now();
588
+ if (value <= 0)
589
+ throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted during file verification', true);
590
+ return value;
591
+ };
592
+ const remotePath = args.direction === 'upload'
593
+ ? await resolveSyncUploadVerificationPath(args, local, remaining())
594
+ : args.remotePath;
595
+ const remote = await probeRemoteFile(args.alias, remotePath, remaining());
596
+ const checks = {
597
+ file: remote.exists && remote.isFile,
598
+ size: remote.exists && remote.size === local.size,
599
+ };
600
+ if (args.verify.owner)
601
+ checks.owner = remote.exists && String(remote.ownerId) === String(fs.statSync(local.resolvedPath).uid);
602
+ if (args.verify.mode)
603
+ checks.mode = remote.exists && remote.modeValue === local.modeValue;
604
+ let localSha256;
605
+ let remoteSha256;
606
+ if (args.verify.sha256 && remote.exists && remote.isFile) {
607
+ const maxBytes = Math.min(args.verify.maxFileBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES, args.verify.maxTotalBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_TOTAL_BYTES);
608
+ if (local.size > maxBytes || remote.size > maxBytes)
609
+ return { kind: 'single_file', skipped: true, reason: 'file verification byte budget exceeded', maxBytes };
610
+ [localSha256, remoteSha256] = await Promise.all([
611
+ fileOps.hashLocalFile(local.resolvedPath, 'sha256', remaining(), { maxBytes, expectedSize: local.size }),
612
+ fileOps.hashRemoteFileDigest(args.alias, remotePath, 'sha256', remaining(), {
613
+ maxBytes,
614
+ expectedSize: remote.size,
615
+ }),
616
+ ]);
617
+ checks.sha256 = localSha256 === remoteSha256;
618
+ const after = await probeRemoteFile(args.alias, remotePath, remaining());
619
+ if (!after.exists ||
620
+ after.size !== remote.size ||
621
+ after.mtimeMs !== remote.mtimeMs ||
622
+ after.modeValue !== remote.modeValue ||
623
+ after.ownerId !== remote.ownerId) {
624
+ throw new VerificationStageError('remote_probe', 'Remote file changed during sync verification', true);
625
+ }
626
+ }
627
+ else if (args.verify.sha256)
628
+ checks.sha256 = false;
629
+ if (args.verify.aclSddl) {
630
+ const command = encodedPowershell(`$acl = Get-Acl -LiteralPath ${quotePowershell(remoteShellPath(remotePath, sessionManager.getRemotePathStyle(args.alias)))}; $acl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)`);
631
+ const result = await sessionManager.exec(args.alias, command, {
632
+ timeout: remaining(),
633
+ useLoginUser: true,
634
+ maxOutputSize: 8192,
635
+ });
636
+ if (!result.success || result.stdoutTruncated)
637
+ throw new VerificationStageError('remote_probe', 'Windows remote ACL could not be verified', true);
638
+ checks.acl = result.stdout.trim() === args.verify.aclSddl;
639
+ }
640
+ return {
641
+ kind: 'single_file',
642
+ matched: Object.values(checks).every(Boolean),
643
+ checks,
644
+ direction: args.direction,
645
+ remotePath,
646
+ localPath: local.expandedPath,
647
+ local: { ...summarizeLocalPathProbe(local), sha256: localSha256 },
648
+ remote: { ...remote, sha256: remoteSha256 },
649
+ };
650
+ }
551
651
  async function buildDirectorySyncVerification(args, local, timeout, deletionBaseline) {
552
652
  if (!args.verify) {
553
653
  return undefined;
@@ -573,6 +673,14 @@ async function buildDirectorySyncVerification(args, local, timeout, deletionBase
573
673
  const comparison = args.direction === 'upload'
574
674
  ? compareDirectoryManifests(localManifest, remoteManifest, request, deletionBaseline)
575
675
  : compareDirectoryManifests(remoteManifest, localManifest, request, deletionBaseline);
676
+ if (remoteManifest.skippedSymlinks > 0 ||
677
+ localManifest.skippedSymlinks > 0 ||
678
+ (deletionBaseline?.skippedSymlinks ?? 0) > 0) {
679
+ comparison.suggestion =
680
+ args.direction === 'upload' && !args.followSymlinks
681
+ ? '排除符号链接后重新同步和校验,或显式设置 followSymlinks=true 上传并校验链接目标'
682
+ : '排除符号链接后重新同步和校验;download 保持跳过链接目标,followSymlinks 仅适用于 upload';
683
+ }
576
684
  if (request.aclSddl && !('skipped' in comparison)) {
577
685
  const command = encodedPowershell(`$acl = Get-Acl -LiteralPath ${quotePowershell(remoteShellPath(args.remotePath, sessionManager.getRemotePathStyle(args.alias)))}; $acl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)`);
578
686
  const result = await sessionManager.exec(args.alias, command, {
@@ -591,8 +699,8 @@ async function buildDirectorySyncVerification(args, local, timeout, deletionBase
591
699
  }
592
700
  return comparison;
593
701
  }
594
- function mergeSyncVerification(existing, ownerMode, directory) {
595
- const parts = [existing, ownerMode, directory].filter((part) => Boolean(part));
702
+ function mergeSyncVerification(existing, ownerMode, content) {
703
+ const parts = [existing, ownerMode, content].filter((part) => Boolean(part));
596
704
  if (parts.length === 0) {
597
705
  return undefined;
598
706
  }
@@ -602,12 +710,13 @@ function mergeSyncVerification(existing, ownerMode, directory) {
602
710
  return {
603
711
  transport: existing,
604
712
  ownerMode,
605
- directory,
713
+ directory: content?.kind === 'directory' ? content : undefined,
714
+ singleFile: content?.kind === 'single_file' ? content : undefined,
606
715
  };
607
716
  }
608
- async function cleanupRemotePath(alias, remotePath) {
717
+ async function cleanupRemotePath(alias, remotePath, timeout) {
609
718
  try {
610
- await fileOps.removeRemoteFile(alias, remotePath);
719
+ await fileOps.removeRemoteFile(alias, remotePath, timeout);
611
720
  }
612
721
  catch (error) {
613
722
  throw new Error(`Temporary remote file cleanup failed: ${error instanceof Error ? error.message : String(error)}`, {
@@ -679,10 +788,10 @@ async function handleUpload(args) {
679
788
  'direction="upload")',
680
789
  ].join(', ')
681
790
  : undefined;
682
- const remoteParent = await probeRemoteParent(args.alias, args.remotePath);
791
+ const remoteParent = await probeRemoteParent(args.alias, args.remotePath, args.timeout);
683
792
  let remoteBefore;
684
793
  try {
685
- remoteBefore = await probeRemoteFile(args.alias, args.remotePath);
794
+ remoteBefore = await probeRemoteFile(args.alias, args.remotePath, args.timeout);
686
795
  }
687
796
  catch (error) {
688
797
  return formatResult({
@@ -759,7 +868,7 @@ async function handleUpload(args) {
759
868
  if (args.atomic && !outcome.success) {
760
869
  let cleanupWarning;
761
870
  try {
762
- await cleanupRemotePath(args.alias, tempRemotePath);
871
+ await cleanupRemotePath(args.alias, tempRemotePath, args.timeout);
763
872
  }
764
873
  catch (cleanupError) {
765
874
  cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
@@ -799,7 +908,7 @@ async function handleUpload(args) {
799
908
  const renameError = error instanceof Error ? error.message : String(error);
800
909
  let cleanupWarning;
801
910
  try {
802
- await cleanupRemotePath(args.alias, tempRemotePath);
911
+ await cleanupRemotePath(args.alias, tempRemotePath, args.timeout);
803
912
  }
804
913
  catch (cleanupError) {
805
914
  cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
@@ -863,7 +972,7 @@ async function handleUpload(args) {
863
972
  (error instanceof fileOps.UploadFileError && error.remoteCreated));
864
973
  if (shouldCleanupTemporaryUpload) {
865
974
  try {
866
- await cleanupRemotePath(args.alias, tempRemotePath);
975
+ await cleanupRemotePath(args.alias, tempRemotePath, args.timeout);
867
976
  }
868
977
  catch (cleanupError) {
869
978
  cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
@@ -937,12 +1046,67 @@ async function handleListDir(args) {
937
1046
  try {
938
1047
  args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
939
1048
  const files = await fileOps.listDir(args.alias, args.remotePath, args.showHidden, undefined, args.timeout, sessionManager.getRemotePathStyle(args.alias));
940
- return formatResult({
1049
+ const bounded = [
1050
+ args.namePattern,
1051
+ args.modifiedAfter,
1052
+ args.modifiedBefore,
1053
+ args.offset,
1054
+ args.limit,
1055
+ args.maxBytes,
1056
+ ].some((value) => value !== undefined);
1057
+ if (!bounded) {
1058
+ return formatResult({ success: true, path: args.remotePath, count: files.length, files });
1059
+ }
1060
+ const patterns = args.namePattern === undefined ? undefined : [args.namePattern];
1061
+ const matching = files.filter((file) => (patterns === undefined || matchesDirectoryExclude(file.name, patterns)) &&
1062
+ (args.modifiedAfter === undefined ||
1063
+ compareDirectoryTimes(file.mtime.toISOString(), args.modifiedAfter) >= 0) &&
1064
+ (args.modifiedBefore === undefined ||
1065
+ compareDirectoryTimes(file.mtime.toISOString(), args.modifiedBefore) < 0));
1066
+ const offset = args.offset ?? 0;
1067
+ const limit = args.limit ?? 100;
1068
+ const maxBytes = args.maxBytes ?? 65536;
1069
+ const page = (count) => formatResult({
941
1070
  success: true,
942
1071
  path: args.remotePath,
943
- count: files.length,
944
- files,
1072
+ count,
1073
+ files: matching.slice(offset, offset + count),
1074
+ total_count: matching.length,
1075
+ offset,
1076
+ has_more: offset + count < matching.length,
1077
+ next_offset: offset + count,
945
1078
  });
1079
+ let lower = 0;
1080
+ let upper = Math.min(limit, Math.max(0, matching.length - offset));
1081
+ let response = page(0);
1082
+ while (lower < upper) {
1083
+ const count = Math.ceil((lower + upper) / 2);
1084
+ const candidate = page(count);
1085
+ if (Buffer.byteLength(candidate.content[0].text, 'utf8') <= maxBytes) {
1086
+ lower = count;
1087
+ response = candidate;
1088
+ }
1089
+ else {
1090
+ upper = count - 1;
1091
+ }
1092
+ }
1093
+ if (Buffer.byteLength(response.content[0].text, 'utf8') > maxBytes ||
1094
+ (lower === 0 && offset < matching.length)) {
1095
+ const minimum = page(offset < matching.length ? 1 : 0);
1096
+ return {
1097
+ ...formatResult({
1098
+ success: false,
1099
+ code: 'LIST_DIR_MAX_BYTES_TOO_SMALL',
1100
+ error: 'maxBytes is too small for directory page metadata and the next complete entry, if any',
1101
+ offset,
1102
+ next_offset: offset,
1103
+ maxBytes,
1104
+ requiredBytes: Buffer.byteLength(minimum.content[0].text, 'utf8'),
1105
+ }),
1106
+ isError: true,
1107
+ };
1108
+ }
1109
+ return response;
946
1110
  }
947
1111
  catch (error) {
948
1112
  return formatFileOperationError(error);
@@ -1024,6 +1188,33 @@ async function handleSync(args) {
1024
1188
  remoteParent: await probeRemoteParent(args.alias, args.remotePath),
1025
1189
  };
1026
1190
  try {
1191
+ const remoteSource = args.direction === 'download'
1192
+ ? await fileOps.getFileInfo(args.alias, args.remotePath, remainingTimeout())
1193
+ : undefined;
1194
+ const sourceIsDirectory = args.direction === 'upload' ? localBefore.exists && localBefore.isDirectory : remoteSource.isDirectory;
1195
+ if (!sourceIsDirectory && (args.verify?.count || args.verify?.deletions || args.verify?.staleFiles)) {
1196
+ return formatResult({
1197
+ success: false,
1198
+ transferSuccess: false,
1199
+ code: 'DIRECTORY_VERIFICATION_REQUIRES_DIRECTORY',
1200
+ error: 'verify.count, verify.deletions and verify.staleFiles require a directory source',
1201
+ });
1202
+ }
1203
+ const sourceSize = args.direction === 'upload' && localBefore.exists ? localBefore.size : remoteSource?.size;
1204
+ const maxFileBytes = Math.min(args.verify?.maxFileBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES, args.verify?.maxTotalBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_TOTAL_BYTES);
1205
+ if (!sourceIsDirectory && args.verify?.sha256 && sourceSize !== undefined && sourceSize > maxFileBytes) {
1206
+ return formatResult({
1207
+ success: false,
1208
+ transferSuccess: false,
1209
+ verificationRequested: true,
1210
+ verificationSuccess: false,
1211
+ verificationStatus: 'skipped',
1212
+ code: 'VERIFICATION_BYTE_LIMIT',
1213
+ error: 'file verification byte budget exceeded before transfer',
1214
+ sourceSize,
1215
+ maxBytes: maxFileBytes,
1216
+ });
1217
+ }
1027
1218
  let deletionBaseline;
1028
1219
  try {
1029
1220
  deletionBaseline = await captureDeletionBaseline(args, remainingTimeout);
@@ -1073,14 +1264,19 @@ async function handleSync(args) {
1073
1264
  });
1074
1265
  const localAfter = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
1075
1266
  diagnostics.localAfter = summarizeLocalPathProbe(localAfter);
1267
+ const transferredLocal = args.direction === 'download' && !sourceIsDirectory && localAfter.exists && localAfter.isDirectory
1268
+ ? fileOps.probeLocalPath(path.join(localAfter.expandedPath, remotePathModule(sessionManager.getRemotePathStyle(args.alias)).basename(args.remotePath)))
1269
+ : localAfter;
1076
1270
  const verificationRequested = Boolean(args.verifyOwner !== undefined || args.verifyMode !== undefined || args.verify !== undefined);
1077
1271
  let verification;
1078
1272
  let verificationError;
1079
1273
  if (verificationRequested && syncResult.success) {
1080
1274
  try {
1081
1275
  const ownerModeVerification = await buildSyncUploadVerification(args, args.direction === 'upload' ? localBefore : localAfter, remainingTimeout());
1082
- const directoryVerification = await buildDirectorySyncVerification(args, args.direction === 'upload' ? localBefore : localAfter, remainingTimeout(), deletionBaseline);
1083
- verification = mergeSyncVerification(undefined, ownerModeVerification, directoryVerification);
1276
+ const contentVerification = sourceIsDirectory
1277
+ ? await buildDirectorySyncVerification(args, args.direction === 'upload' ? localBefore : localAfter, remainingTimeout(), deletionBaseline)
1278
+ : await buildSingleFileSyncVerification(args, args.direction === 'upload' ? localBefore : transferredLocal, remainingTimeout());
1279
+ verification = mergeSyncVerification(undefined, ownerModeVerification, contentVerification);
1084
1280
  }
1085
1281
  catch (error) {
1086
1282
  verificationError = error;
@@ -1130,7 +1326,7 @@ export function registerFileTools(server) {
1130
1326
  inputSchema: writeFileSchema,
1131
1327
  }, (args) => handleWriteFile(args));
1132
1328
  server.registerTool('ssh_list_dir', {
1133
- description: '列出远程目录内容,返回包含特殊权限位的数值 mode 和 permissions 文本',
1329
+ description: '列出远程目录内容,返回数值 mode 和 permissions 文本;名称与修改时间条件取交集,使用筛选或分页参数时默认最多 100 条、65536 UTF-8 字节,使用 next_offset 续查;完整 readdir 后分页,目录变化时不保证快照一致性',
1134
1330
  inputSchema: listDirSchema,
1135
1331
  }, (args) => handleListDir(args));
1136
1332
  server.registerTool('ssh_file_info', {
package/dist/types.d.ts CHANGED
@@ -1,6 +1,23 @@
1
1
  /**
2
2
  * SSH MCP Pro - 类型定义
3
3
  */
4
+ import type { Readable } from 'stream';
5
+ export interface CommandChannel extends Readable {
6
+ readonly stderr: Readable;
7
+ readonly ready?: Promise<void>;
8
+ close(): void;
9
+ }
10
+ export interface OpenSshMasterInfo {
11
+ backend: 'openssh';
12
+ masterReused: true;
13
+ identityStatus: 'master_trusted';
14
+ masterPid: number;
15
+ observedLogin?: {
16
+ uid: number;
17
+ username: string;
18
+ sshConnection?: string;
19
+ };
20
+ }
4
21
  export declare const DEFAULT_EXEC_MAX_OUTPUT_SIZE: number;
5
22
  export declare const HARD_EXEC_MAX_OUTPUT_SIZE: number;
6
23
  export type RemotePlatform = 'posix' | 'windows';
@@ -8,6 +25,8 @@ export type CommandShell = 'posix' | 'cmd' | 'powershell';
8
25
  export type RemotePathStyle = 'posix' | 'win32' | 'sftp-posix';
9
26
  export type RsyncProfile = 'posix' | 'native-win32' | 'msys2' | 'cygwin';
10
27
  export interface SSHConnectionConfig {
28
+ backend?: 'ssh2' | 'openssh';
29
+ controlPath?: string;
11
30
  host: string;
12
31
  port: number;
13
32
  username: string;
@@ -34,6 +53,9 @@ export interface SSHConnectionConfig {
34
53
  jumpHost?: SSHConnectionConfig;
35
54
  }
36
55
  export interface SSHSessionBrief {
56
+ backend?: 'ssh2' | 'openssh';
57
+ masterReused?: boolean;
58
+ identityStatus?: 'master_trusted';
37
59
  alias: string;
38
60
  identity: string;
39
61
  runAs?: string;
@@ -44,7 +66,7 @@ export interface SSHSessionDetail extends SSHSessionBrief {
44
66
  host: string;
45
67
  port: number;
46
68
  username: string;
47
- authMethod: 'key' | 'password' | 'agent' | 'inline-key';
69
+ authMethod: 'key' | 'password' | 'agent' | 'inline-key' | 'master';
48
70
  connectedAt: number;
49
71
  hasJumpHost: boolean;
50
72
  remotePlatform: RemotePlatform;
@@ -52,12 +74,14 @@ export interface SSHSessionDetail extends SSHSessionBrief {
52
74
  remotePathStyle: RemotePathStyle;
53
75
  }
54
76
  export interface ExternalTransferCapability {
77
+ backend?: 'ssh2' | 'openssh';
78
+ controlPath?: string;
55
79
  alias: string;
56
80
  identity: string;
57
81
  host: string;
58
82
  port: number;
59
83
  username: string;
60
- authMethod: 'key-path' | 'password' | 'agent' | 'inline-key';
84
+ authMethod: 'key-path' | 'password' | 'agent' | 'inline-key' | 'master';
61
85
  keyPath?: string;
62
86
  hasJumpHost: boolean;
63
87
  routeSafeForOpenSsh: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyrokine/mcp-ssh",
3
- "version": "3.0.0",
3
+ "version": "3.1.0",
4
4
  "description": "A comprehensive SSH MCP Server for Claude Code",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -56,5 +56,6 @@
56
56
  "README.md",
57
57
  "README_zh.md",
58
58
  "LICENSE"
59
- ]
59
+ ],
60
+ "gitHead": "8ecb805b68619692cf9b1a72eb0bc58e5e3f8b26"
60
61
  }