@pyrokine/mcp-ssh 3.1.0 → 3.2.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.
@@ -8,12 +8,12 @@ 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, 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';
11
+ import { compareDirectoryManifests, createEmptyDirectoryManifest, createLocalDirectoryManifest, createOpenSshDirectoryManifest, createRemoteDirectoryManifest, DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES, DIRECTORY_VERIFY_DEFAULT_MAX_TOTAL_BYTES, DIRECTORY_VERIFY_MAX_ENTRIES, DIRECTORY_VERIFY_MAX_FILE_BYTES, DIRECTORY_VERIFY_MAX_TOTAL_BYTES, matchesDirectoryExclude, remainingVerificationTimeout, } 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
- import { sessionManager } from '../session-manager.js';
15
- import { withSftpOperationTimeout } from '../sftp-timeout.js';
16
14
  import { encodedPowershell, quotePowershell, remoteDirname, remoteJoin, remotePathModule, remoteShellPath, sftpPath, } from '../remote-platform.js';
15
+ import { sessionManager } from '../session-manager.js';
16
+ import { SftpOperationTimeoutError, sftpOperationOutcome, withSftpOperationTimeout } from '../sftp-timeout.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';
@@ -73,10 +73,11 @@ const writeFileSchema = z.object({
73
73
  });
74
74
  function compareDirectoryTimes(left, right) {
75
75
  const milliseconds = Date.parse(left) - Date.parse(right);
76
- if (milliseconds !== 0)
76
+ if (milliseconds !== 0) {
77
77
  return milliseconds;
78
+ }
78
79
  // 保留 ISO 8601 的亚毫秒部分,避免 Date.parse 截断时间边界
79
- const [leftFraction, rightFraction] = [left, right].map((value) => (value.match(/\.(\d+)/)?.[1].slice(3) ?? '').replace(/0+$/, ''));
80
+ const [leftFraction, rightFraction] = [left, right].map((value) => (value.match(/\.(?<fraction>\d+)/)?.[1].slice(3) ?? '').replace(/0+$/, ''));
80
81
  return leftFraction < rightFraction ? -1 : leftFraction > rightFraction ? 1 : 0;
81
82
  }
82
83
  const listDirSchema = z
@@ -85,13 +86,11 @@ const listDirSchema = z
85
86
  remotePath: z.string().describe('远程目录路径'),
86
87
  showHidden: z.boolean().optional().describe('是否显示隐藏文件'),
87
88
  namePattern: z.string().optional().describe('名称通配模式,复用同步 exclude 的 * 和 ? 规则,区分大小写'),
88
- modifiedAfter: z
89
- .string()
89
+ modifiedAfter: z.iso
90
90
  .datetime({ offset: true })
91
91
  .optional()
92
92
  .describe('修改时间下界,包含;使用带时区的 ISO 8601 时间'),
93
- modifiedBefore: z
94
- .string()
93
+ modifiedBefore: z.iso
95
94
  .datetime({ offset: true })
96
95
  .optional()
97
96
  .describe('修改时间上界,不包含;使用带时区的 ISO 8601 时间'),
@@ -135,12 +134,21 @@ const syncSchema = z.object({
135
134
  preflightTimeout: z.number().int().positive().max(60000).optional().describe('传输能力预检超时,默认 10000ms'),
136
135
  connectTimeout: z.number().int().positive().max(120000).optional().describe('rsync SSH 连接超时,默认 30000ms'),
137
136
  operationTimeout: z.number().int().positive().max(3600000).optional().describe('同步操作超时,默认 600000ms'),
138
- verifyOwner: z.union([z.string(), z.number()]).optional().describe('upload 后校验远端 owner(用户名或 uid)'),
139
- verifyMode: z.string().optional().describe('upload 后校验远端权限,例如 0644、4755 或 -rwsr-xr-x'),
137
+ verifyOwner: z
138
+ .union([z.string(), z.number()])
139
+ .optional()
140
+ .describe('仅非 dryRun 单文件 upload 校验远端 owner(用户名或 uid),目录用 verify.owner'),
141
+ verifyMode: z
142
+ .string()
143
+ .optional()
144
+ .describe('仅非 dryRun 单文件 upload 校验远端权限,例如 0644、4755 或 -rwsr-xr-x,目录用 verify.mode'),
140
145
  verify: z
141
146
  .object({
142
147
  count: z.boolean().optional().describe('校验目录条目数'),
143
- sha256: z.boolean().optional().describe('校验文件 SHA-256 或目录 SHA-256 root manifest'),
148
+ sha256: z
149
+ .boolean()
150
+ .optional()
151
+ .describe('显式启用文件 SHA-256 或目录 SHA-256 root manifest 校验,默认 false'),
144
152
  owner: z.boolean().optional().describe('逐项校验 owner'),
145
153
  mode: z.boolean().optional().describe('逐项校验 POSIX mode;Windows 不支持'),
146
154
  aclSddl: z
@@ -190,17 +198,6 @@ class VerificationStageError extends Error {
190
198
  this.name = 'VerificationStageError';
191
199
  }
192
200
  }
193
- function sftpOperationOutcome(error) {
194
- if (!error || typeof error !== 'object') {
195
- return {};
196
- }
197
- const details = 'details' in error ? error.details : undefined;
198
- if (details && typeof details === 'object' && 'operationStatus' in details) {
199
- return details;
200
- }
201
- const cause = 'cause' in error ? error.cause : undefined;
202
- return sftpOperationOutcome(cause);
203
- }
204
201
  function formatFileOperationError(error) {
205
202
  const operationOutcome = sftpOperationOutcome(error);
206
203
  if (Object.keys(operationOutcome).length === 0) {
@@ -232,6 +229,12 @@ function verificationErrorDetails(error) {
232
229
  retryable: false,
233
230
  };
234
231
  }
232
+ function syncVerificationError(error, control) {
233
+ if (!control.signal.aborted && Date.now() < control.deadline) {
234
+ return error;
235
+ }
236
+ return new VerificationStageError('verification_timeout', 'Sync verification exceeded the operation timeout', true, { status: 'unknown', timedOut: true, cause: error instanceof Error ? error.message : String(error) });
237
+ }
235
238
  function summarizeLocalPathProbe(probe) {
236
239
  const summary = {
237
240
  exists: probe.exists,
@@ -271,11 +274,11 @@ function uploadPathError(code, message, diagnostics) {
271
274
  function normalizeRemotePath(alias, remotePath) {
272
275
  return sftpPath(remotePath, sessionManager.getRemotePathStyle(alias));
273
276
  }
274
- async function probeRemoteParent(alias, remotePath, timeout) {
277
+ async function probeRemoteParent(alias, remotePath, timeout, signal) {
275
278
  const parent = remoteDirname(sessionManager.getRemotePathStyle(alias), remotePath);
276
279
  const probeMethod = sessionManager.getOpenSshConnection(alias) ? 'openssh' : 'sftp';
277
280
  try {
278
- const result = await probeRemoteFile(alias, parent, timeout);
281
+ const result = await probeRemoteFile(alias, parent, timeout, signal);
279
282
  return {
280
283
  exists: result.exists,
281
284
  isDirectory: result.exists ? result.isDirectory : false,
@@ -346,19 +349,19 @@ function isRemoteMissingError(error) {
346
349
  }
347
350
  const code = 'code' in error ? error.code : undefined;
348
351
  const message = error instanceof Error ? error.message : String(error);
349
- return code === 2 || code === 'ENOENT' || /no such file|not found/i.test(message);
352
+ return code === 2 || code === 'ENOENT' || /no such file|^(?:file |remote path )?not found$/i.test(message);
350
353
  }
351
- async function probeRemoteFile(alias, remotePath, timeout = 10000) {
354
+ async function probeRemoteFile(alias, remotePath, timeout = 10000, signal) {
352
355
  const probeMethod = sessionManager.getOpenSshConnection(alias) ? 'openssh' : 'sftp';
353
356
  let info;
354
357
  try {
355
- info = await fileOps.getFileInfo(alias, remotePath, timeout);
358
+ info = await fileOps.getFileInfo(alias, remotePath, timeout, undefined, signal);
356
359
  }
357
360
  catch (error) {
358
361
  if (isRemoteMissingError(error)) {
359
362
  return { exists: false, remotePath, probeMethod };
360
363
  }
361
- throw new VerificationStageError('remote_probe', `Remote file stat failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'stat', probeMethod });
364
+ throw new VerificationStageError('remote_probe', `Remote file stat failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'stat', probeMethod, ...sftpOperationOutcome(error) });
362
365
  }
363
366
  return {
364
367
  exists: true,
@@ -442,10 +445,10 @@ function displayExpectedMode(mode) {
442
445
  const parsed = normalizeExpectedMode(mode);
443
446
  return parsed === undefined ? undefined : formatFileMode(parsed);
444
447
  }
445
- async function buildSyncVerificationChecks(args, remote) {
448
+ async function buildSyncVerificationChecks(args, remote, timeout) {
446
449
  const checks = {};
447
450
  if (args.verifyOwner !== undefined) {
448
- const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner);
451
+ const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner, timeout);
449
452
  checks.owner = remote.exists && String(remote.ownerId) === expectedOwnerId;
450
453
  }
451
454
  if (args.verifyMode !== undefined) {
@@ -464,7 +467,7 @@ async function resolveSyncUploadVerificationPath(args, local, timeout) {
464
467
  }
465
468
  return args.remotePath;
466
469
  }
467
- async function buildSyncUploadVerification(args, local, timeout) {
470
+ async function buildSyncUploadVerification(args, local, control) {
468
471
  if (args.verifyOwner === undefined && args.verifyMode === undefined) {
469
472
  return undefined;
470
473
  }
@@ -483,12 +486,10 @@ async function buildSyncUploadVerification(args, local, timeout) {
483
486
  suggestion: '目录权限校验请使用 verify.owner 或 verify.mode',
484
487
  };
485
488
  }
486
- if (timeout <= 0) {
487
- throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before owner/mode verification started', true);
488
- }
489
- const verificationRemotePath = await resolveSyncUploadVerificationPath(args, local, timeout);
490
- const remote = await probeRemoteFile(args.alias, verificationRemotePath, timeout);
491
- const checks = await buildSyncVerificationChecks(args, remote);
489
+ const verificationRemotePath = await resolveSyncUploadVerificationPath(args, local, remainingVerificationTimeout(control));
490
+ const remote = await probeRemoteFile(args.alias, verificationRemotePath, remainingVerificationTimeout(control));
491
+ const checks = await buildSyncVerificationChecks(args, remote, remainingVerificationTimeout(control));
492
+ remainingVerificationTimeout(control);
492
493
  const matched = Object.values(checks).every(Boolean);
493
494
  return {
494
495
  kind: 'owner_mode',
@@ -506,16 +507,19 @@ async function buildSyncUploadVerification(args, local, timeout) {
506
507
  : '同步已完成,但远端 owner/mode 与期望不一致;工具不会自动 chown/chmod,请按需用 ssh_exec 显式处理权限',
507
508
  };
508
509
  }
509
- async function captureRemoteDirectoryManifest(alias, remotePath, request, exclude, followSymlinks, timeout) {
510
+ async function captureRemoteDirectoryManifest(alias, remotePath, request, exclude, followSymlinks, control) {
510
511
  const connection = sessionManager.getOpenSshConnection(alias);
511
- if (connection)
512
- return createOpenSshDirectoryManifest(connection, remotePath, request, timeout, exclude, followSymlinks);
512
+ if (connection) {
513
+ return createOpenSshDirectoryManifest(connection, remotePath, request, remainingVerificationTimeout(control), exclude, followSymlinks, control);
514
+ }
515
+ const timeout = remainingVerificationTimeout(control);
513
516
  const requestSftp = sessionManager.getSftp(alias);
514
517
  const sftp = await withSftpOperationTimeout(requestSftp, timeout, () => {
515
518
  void requestSftp.then((late) => late.end(), () => undefined);
516
- });
519
+ }, control.signal);
517
520
  try {
518
- return await withSftpOperationTimeout(createRemoteDirectoryManifest(sftp, remotePath, request, exclude, followSymlinks, sessionManager.getRemotePathStyle(alias)), timeout, () => sftp.end());
521
+ const remaining = remainingVerificationTimeout(control);
522
+ return await withSftpOperationTimeout(createRemoteDirectoryManifest(sftp, remotePath, request, exclude, followSymlinks, sessionManager.getRemotePathStyle(alias), control), remaining, () => sftp.end(), control.signal);
519
523
  }
520
524
  catch (error) {
521
525
  throw new VerificationStageError('remote_manifest_output', error instanceof Error ? error.message : String(error), true);
@@ -538,28 +542,21 @@ function deletionManifestRequest(request) {
538
542
  staleFiles: false,
539
543
  };
540
544
  }
541
- async function captureDeletionBaseline(args, remainingTimeout) {
545
+ async function captureDeletionBaseline(args, control) {
542
546
  if (!args.verify?.deletions || args.dryRun) {
543
547
  return undefined;
544
548
  }
549
+ remainingVerificationTimeout(control);
545
550
  const request = deletionManifestRequest(args.verify);
546
551
  if (args.direction === 'upload') {
547
- const probeTimeout = remainingTimeout();
548
- if (probeTimeout <= 0) {
549
- throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before deletion baseline capture started', true);
550
- }
551
- const remote = await probeRemoteFile(args.alias, args.remotePath, probeTimeout);
552
+ const remote = await probeRemoteFile(args.alias, args.remotePath, remainingVerificationTimeout(control));
552
553
  if (!remote.exists) {
553
554
  return createEmptyDirectoryManifest();
554
555
  }
555
556
  if (!remote.isDirectory) {
556
557
  throw new VerificationStageError('remote_probe', 'deletion verification requires the remote destination to be a directory', false, { remotePath: args.remotePath, fileType: remote.fileType });
557
558
  }
558
- const manifestTimeout = remainingTimeout();
559
- if (manifestTimeout <= 0) {
560
- throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before deletion baseline manifest started', true);
561
- }
562
- return captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), manifestTimeout);
559
+ return captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), control);
563
560
  }
564
561
  const local = fileOps.probeLocalPath(args.localPath);
565
562
  if (!local.exists) {
@@ -569,26 +566,23 @@ async function captureDeletionBaseline(args, remainingTimeout) {
569
566
  throw new VerificationStageError('local_manifest', 'deletion verification requires the local destination to be a directory', false, { localPath: args.localPath });
570
567
  }
571
568
  try {
572
- return await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args));
569
+ return await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args), control);
573
570
  }
574
571
  catch (error) {
575
572
  throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
576
573
  }
577
574
  }
578
- async function buildSingleFileSyncVerification(args, local, timeout) {
579
- if (!args.verify)
575
+ async function buildSingleFileSyncVerification(args, local, control) {
576
+ if (!args.verify) {
580
577
  return undefined;
581
- if (args.dryRun)
578
+ }
579
+ if (args.dryRun) {
582
580
  return { kind: 'single_file', skipped: true, reason: 'file verification is not executed during dryRun' };
583
- if (!local.exists || !local.isFile)
581
+ }
582
+ if (!local.exists || !local.isFile) {
584
583
  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
- };
584
+ }
585
+ const remaining = () => remainingVerificationTimeout(control);
592
586
  const remotePath = args.direction === 'upload'
593
587
  ? await resolveSyncUploadVerificationPath(args, local, remaining())
594
588
  : args.remotePath;
@@ -597,22 +591,26 @@ async function buildSingleFileSyncVerification(args, local, timeout) {
597
591
  file: remote.exists && remote.isFile,
598
592
  size: remote.exists && remote.size === local.size,
599
593
  };
600
- if (args.verify.owner)
594
+ if (args.verify.owner) {
601
595
  checks.owner = remote.exists && String(remote.ownerId) === String(fs.statSync(local.resolvedPath).uid);
602
- if (args.verify.mode)
596
+ }
597
+ if (args.verify.mode) {
603
598
  checks.mode = remote.exists && remote.modeValue === local.modeValue;
599
+ }
604
600
  let localSha256;
605
601
  let remoteSha256;
606
602
  if (args.verify.sha256 && remote.exists && remote.isFile) {
607
603
  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)
604
+ if (local.size > maxBytes || remote.size > maxBytes) {
609
605
  return { kind: 'single_file', skipped: true, reason: 'file verification byte budget exceeded', maxBytes };
606
+ }
607
+ ;
610
608
  [localSha256, remoteSha256] = await Promise.all([
611
- fileOps.hashLocalFile(local.resolvedPath, 'sha256', remaining(), { maxBytes, expectedSize: local.size }),
612
- fileOps.hashRemoteFileDigest(args.alias, remotePath, 'sha256', remaining(), {
609
+ Promise.resolve().then(() => fileOps.hashLocalFile(local.resolvedPath, 'sha256', remaining(), { maxBytes, expectedSize: local.size })),
610
+ Promise.resolve().then(() => fileOps.hashRemoteFileDigest(args.alias, remotePath, 'sha256', remaining(), {
613
611
  maxBytes,
614
612
  expectedSize: remote.size,
615
- }),
613
+ }, control.signal)),
616
614
  ]);
617
615
  checks.sha256 = localSha256 === remoteSha256;
618
616
  const after = await probeRemoteFile(args.alias, remotePath, remaining());
@@ -624,19 +622,25 @@ async function buildSingleFileSyncVerification(args, local, timeout) {
624
622
  throw new VerificationStageError('remote_probe', 'Remote file changed during sync verification', true);
625
623
  }
626
624
  }
627
- else if (args.verify.sha256)
625
+ else if (args.verify.sha256) {
628
626
  checks.sha256 = false;
627
+ }
629
628
  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)`);
629
+ const command = encodedPowershell('$acl = Get-Acl -LiteralPath ' +
630
+ `${quotePowershell(remoteShellPath(remotePath, sessionManager.getRemotePathStyle(args.alias)))}` +
631
+ '; $acl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.Acce' +
632
+ 'ssControlSections]::Access)');
631
633
  const result = await sessionManager.exec(args.alias, command, {
632
634
  timeout: remaining(),
633
635
  useLoginUser: true,
634
636
  maxOutputSize: 8192,
635
637
  });
636
- if (!result.success || result.stdoutTruncated)
638
+ if (!result.success || result.stdoutTruncated) {
637
639
  throw new VerificationStageError('remote_probe', 'Windows remote ACL could not be verified', true);
640
+ }
638
641
  checks.acl = result.stdout.trim() === args.verify.aclSddl;
639
642
  }
643
+ remaining();
640
644
  return {
641
645
  kind: 'single_file',
642
646
  matched: Object.values(checks).every(Boolean),
@@ -648,7 +652,7 @@ async function buildSingleFileSyncVerification(args, local, timeout) {
648
652
  remote: { ...remote, sha256: remoteSha256 },
649
653
  };
650
654
  }
651
- async function buildDirectorySyncVerification(args, local, timeout, deletionBaseline) {
655
+ async function buildDirectorySyncVerification(args, local, control, deletionBaseline) {
652
656
  if (!args.verify) {
653
657
  return undefined;
654
658
  }
@@ -658,14 +662,12 @@ async function buildDirectorySyncVerification(args, local, timeout, deletionBase
658
662
  if (!local.exists || !local.isDirectory) {
659
663
  return { kind: 'directory', skipped: true, reason: 'bounded directory verification requires a local directory' };
660
664
  }
661
- if (timeout <= 0) {
662
- throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before directory verification started', true);
663
- }
665
+ remainingVerificationTimeout(control);
664
666
  const request = args.verify;
665
- const remoteManifest = await captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), timeout);
667
+ const remoteManifest = await captureRemoteDirectoryManifest(args.alias, args.remotePath, request, args.exclude, directoryVerificationFollowsSymlinks(args), control);
666
668
  let localManifest;
667
669
  try {
668
- localManifest = await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args));
670
+ localManifest = await createLocalDirectoryManifest(local.resolvedPath, request, args.exclude, directoryVerificationFollowsSymlinks(args), control);
669
671
  }
670
672
  catch (error) {
671
673
  throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
@@ -682,9 +684,12 @@ async function buildDirectorySyncVerification(args, local, timeout, deletionBase
682
684
  : '排除符号链接后重新同步和校验;download 保持跳过链接目标,followSymlinks 仅适用于 upload';
683
685
  }
684
686
  if (request.aclSddl && !('skipped' in comparison)) {
685
- const command = encodedPowershell(`$acl = Get-Acl -LiteralPath ${quotePowershell(remoteShellPath(args.remotePath, sessionManager.getRemotePathStyle(args.alias)))}; $acl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)`);
687
+ const command = encodedPowershell('$acl = Get-Acl -LiteralPath ' +
688
+ `${quotePowershell(remoteShellPath(args.remotePath, sessionManager.getRemotePathStyle(args.alias)))}` +
689
+ '; $acl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.Acce' +
690
+ 'ssControlSections]::Access)');
686
691
  const result = await sessionManager.exec(args.alias, command, {
687
- timeout,
692
+ timeout: remainingVerificationTimeout(control),
688
693
  useLoginUser: true,
689
694
  maxOutputSize: 8192,
690
695
  });
@@ -697,6 +702,7 @@ async function buildDirectorySyncVerification(args, local, timeout, deletionBase
697
702
  comparison.matched = comparison.matched === true && aclMatch;
698
703
  comparison.acl = { matched: aclMatch, expected: request.aclSddl, actual: result.stdout.trim() };
699
704
  }
705
+ remainingVerificationTimeout(control);
700
706
  return comparison;
701
707
  }
702
708
  function mergeSyncVerification(existing, ownerMode, content) {
@@ -751,7 +757,8 @@ async function handleUpload(args) {
751
757
  return formatResult({
752
758
  success: false,
753
759
  code: 'unsupported_remote_platform',
754
- error: 'Windows SFTP owner/mode metadata cannot verify POSIX permissions; use Windows ACL verification',
760
+ error: 'Windows SFTP owner/mode metadata cannot verify POSIX permissions; use ' +
761
+ 'Windows ACL verification',
755
762
  });
756
763
  }
757
764
  }
@@ -794,9 +801,11 @@ async function handleUpload(args) {
794
801
  remoteBefore = await probeRemoteFile(args.alias, args.remotePath, args.timeout);
795
802
  }
796
803
  catch (error) {
797
- return formatResult({
798
- success: false,
799
- error: error instanceof Error ? error.message : String(error),
804
+ return formatError(error, {
805
+ ...sftpOperationOutcome(error),
806
+ operationStatus: 'failed',
807
+ failureStage: 'preflight',
808
+ acknowledgedBytes: 0,
800
809
  diagnostics: {
801
810
  local: summarizeLocalPathProbe(local),
802
811
  remoteParent,
@@ -821,12 +830,14 @@ async function handleUpload(args) {
821
830
  }
822
831
  }
823
832
  catch (error) {
824
- return formatResult({
825
- success: false,
833
+ return formatError(error, {
834
+ ...sftpOperationOutcome(error),
835
+ operationStatus: 'failed',
836
+ failureStage: 'preflight',
837
+ acknowledgedBytes: 0,
826
838
  code: 'atomic_replace_unverified',
827
839
  atomicReplaceSupported: null,
828
840
  targetReplaced: false,
829
- error: error instanceof Error ? error.message : String(error),
830
841
  });
831
842
  }
832
843
  }
@@ -904,7 +915,8 @@ async function handleUpload(args) {
904
915
  await fileOps.renameRemoteFile(args.alias, tempRemotePath, args.remotePath, remoteBefore.exists, args.timeout);
905
916
  }
906
917
  catch (error) {
907
- const renameNotStarted = error instanceof fileOps.RemoteRenameNotStartedError;
918
+ const renameOutcome = sftpOperationOutcome(error);
919
+ const renameNotStarted = renameOutcome.operationStatus === 'failed' || error instanceof fileOps.RemoteRenameNotStartedError;
908
920
  const renameError = error instanceof Error ? error.message : String(error);
909
921
  let cleanupWarning;
910
922
  try {
@@ -916,11 +928,14 @@ async function handleUpload(args) {
916
928
  return formatResult({
917
929
  success: false,
918
930
  transferSuccess: true,
931
+ ...renameOutcome,
932
+ acknowledgedBytes: uploadResult.size,
919
933
  operationStatus: renameNotStarted ? 'failed' : 'unknown',
920
- retryable: true,
934
+ retryable: false,
921
935
  error: renameNotStarted
922
936
  ? `Atomic SFTP rename request was not sent; target was not replaced: ${renameError}`
923
- : `Atomic SFTP rename response failed; target replacement state is unknown: ${renameError}`,
937
+ : 'Atomic SFTP rename response failed; target replacement state is unknown: ' +
938
+ `${renameError}`,
924
939
  cleanupWarning,
925
940
  atomic: true,
926
941
  atomicReplaceSupported,
@@ -978,11 +993,10 @@ async function handleUpload(args) {
978
993
  cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
979
994
  }
980
995
  }
981
- return formatResult({
982
- success: false,
996
+ return formatError(error, {
983
997
  ...sftpOperationOutcome(error),
984
- error: error instanceof Error ? error.message : String(error),
985
998
  cleanupWarning,
999
+ targetReplaced: args.atomic ? false : undefined,
986
1000
  atomicReplaceSupported,
987
1001
  finalRemotePath: args.remotePath,
988
1002
  diagnostics: {
@@ -1002,10 +1016,10 @@ async function handleDownload(args) {
1002
1016
  return formatResult({ ...downloadResult, message: `Downloaded to ${args.localPath}` });
1003
1017
  }
1004
1018
  catch (error) {
1005
- return formatResult({
1006
- success: false,
1019
+ return formatError(error, {
1007
1020
  ...sftpOperationOutcome(error),
1008
- error: error instanceof Error ? error.message : String(error),
1021
+ operationStatus: 'failed',
1022
+ targetReplaced: false,
1009
1023
  diagnostics: {
1010
1024
  local: summarizeLocalPathProbe(fileOps.probeLocalPath(args.localPath)),
1011
1025
  localParent: summarizeLocalPathProbe(fileOps.probeLocalPath(path.dirname(args.localPath))),
@@ -1097,7 +1111,7 @@ async function handleListDir(args) {
1097
1111
  ...formatResult({
1098
1112
  success: false,
1099
1113
  code: 'LIST_DIR_MAX_BYTES_TOO_SMALL',
1100
- error: 'maxBytes is too small for directory page metadata and the next complete entry, if any',
1114
+ error: 'maxBytes is too small for directory page metadata and the next complete ' + 'entry, if any',
1101
1115
  offset,
1102
1116
  next_offset: offset,
1103
1117
  maxBytes,
@@ -1132,7 +1146,7 @@ async function handleMkdir(args) {
1132
1146
  return formatFileOperationError(error);
1133
1147
  }
1134
1148
  }
1135
- async function handleSync(args) {
1149
+ async function handleSync(args, extra) {
1136
1150
  const startedAt = Date.now();
1137
1151
  try {
1138
1152
  args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
@@ -1156,6 +1170,15 @@ async function handleSync(args) {
1156
1170
  catch (error) {
1157
1171
  return formatError(error);
1158
1172
  }
1173
+ const ownerModeRequested = args.verifyOwner !== undefined || args.verifyMode !== undefined;
1174
+ if (ownerModeRequested && (args.direction !== 'upload' || args.dryRun)) {
1175
+ return formatResult({
1176
+ success: false,
1177
+ transferSuccess: false,
1178
+ code: 'UNSUPPORTED_SYNC_VERIFICATION',
1179
+ error: 'verifyOwner/verifyMode require a non-dryRun single-file upload; use verify.owner/verify.mode for directory or download verification',
1180
+ });
1181
+ }
1159
1182
  if (args.verify?.deletions && args.delete !== true) {
1160
1183
  return formatResult({
1161
1184
  success: false,
@@ -1164,7 +1187,8 @@ async function handleSync(args) {
1164
1187
  });
1165
1188
  }
1166
1189
  const operationTimeout = args.operationTimeout ?? 600_000;
1167
- const remainingTimeout = () => operationTimeout - (Date.now() - startedAt);
1190
+ const deadline = startedAt + operationTimeout;
1191
+ const remainingTimeout = () => deadline - Date.now();
1168
1192
  try {
1169
1193
  if (args.direction === 'upload') {
1170
1194
  fileOps.validateSyncUploadSource(args.localPath, args.followSymlinks === true);
@@ -1183,15 +1207,90 @@ async function handleSync(args) {
1183
1207
  });
1184
1208
  }
1185
1209
  const localBefore = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
1186
- const diagnostics = {
1187
- localBefore: summarizeLocalPathProbe(localBefore),
1188
- remoteParent: await probeRemoteParent(args.alias, args.remotePath),
1210
+ const diagnostics = { localBefore: summarizeLocalPathProbe(localBefore) };
1211
+ if (ownerModeRequested && localBefore.exists && localBefore.isDirectory) {
1212
+ return formatResult({
1213
+ success: false,
1214
+ transferSuccess: false,
1215
+ code: 'UNSUPPORTED_SYNC_VERIFICATION',
1216
+ error: 'verifyOwner/verifyMode require a single-file upload; use verify.owner/verify.mode for directory verification',
1217
+ diagnostics,
1218
+ });
1219
+ }
1220
+ const controller = new AbortController();
1221
+ const control = {
1222
+ deadline,
1223
+ signal: extra?.signal ? AbortSignal.any([controller.signal, extra.signal]) : controller.signal,
1189
1224
  };
1225
+ let progressWarning;
1226
+ let lastProgressAt = -Infinity;
1227
+ let progress = 0;
1228
+ let progressPending = false;
1229
+ const progressToken = extra?._meta?.progressToken;
1230
+ const onProgress = progressToken === undefined
1231
+ ? undefined
1232
+ : (update) => {
1233
+ if (control.signal?.aborted ||
1234
+ progressPending ||
1235
+ progressWarning ||
1236
+ Date.now() - lastProgressAt < 1000) {
1237
+ return;
1238
+ }
1239
+ lastProgressAt = Date.now();
1240
+ progressPending = true;
1241
+ const current = ++progress;
1242
+ void Promise.resolve()
1243
+ .then(() => control.signal?.aborted
1244
+ ? undefined
1245
+ : extra.sendNotification({
1246
+ method: 'notifications/progress',
1247
+ params: {
1248
+ progressToken,
1249
+ progress: current,
1250
+ message: `${args.direction === 'upload' ? '上传' : '下载'}:${update.transferred} bytes,${update.percent}%` +
1251
+ (update.total > 0 ? `,当前文件共 ${update.total} bytes` : ''),
1252
+ },
1253
+ }))
1254
+ .catch((error) => {
1255
+ progressWarning = `MCP progress notification failed: ${error instanceof Error ? error.message : String(error)}`;
1256
+ console.warn(`[ssh_sync] ${progressWarning}`);
1257
+ })
1258
+ .finally(() => {
1259
+ progressPending = false;
1260
+ });
1261
+ };
1262
+ const timer = setTimeout(() => controller.abort(new SftpOperationTimeoutError(operationTimeout)), Math.max(0, remainingTimeout()));
1190
1263
  try {
1264
+ control.signal?.throwIfAborted();
1265
+ const probeTimeout = remainingTimeout();
1266
+ if (probeTimeout <= 0) {
1267
+ throw new Error('sync operation timeout was exhausted before remote probing');
1268
+ }
1269
+ diagnostics.remoteParent = await probeRemoteParent(args.alias, args.remotePath, probeTimeout, control.signal);
1270
+ if (remainingTimeout() <= 0) {
1271
+ throw new Error('sync operation timeout was exhausted before transfer started');
1272
+ }
1191
1273
  const remoteSource = args.direction === 'download'
1192
- ? await fileOps.getFileInfo(args.alias, args.remotePath, remainingTimeout())
1274
+ ? await fileOps.getFileInfo(args.alias, args.remotePath, remainingTimeout(), undefined, control.signal)
1193
1275
  : undefined;
1194
1276
  const sourceIsDirectory = args.direction === 'upload' ? localBefore.exists && localBefore.isDirectory : remoteSource.isDirectory;
1277
+ const remoteParent = diagnostics.remoteParent;
1278
+ if (args.direction === 'upload' &&
1279
+ !sourceIsDirectory &&
1280
+ !args.dryRun &&
1281
+ (remoteParent.exists === false || (remoteParent.exists === true && remoteParent.isDirectory === false))) {
1282
+ return formatResult({
1283
+ success: false,
1284
+ transferSuccess: false,
1285
+ operationStatus: 'failed',
1286
+ failureStage: 'remote_prepare',
1287
+ code: remoteParent.exists === false ? 'REMOTE_PARENT_NOT_FOUND' : 'REMOTE_PARENT_NOT_DIRECTORY',
1288
+ error: remoteParent.exists === false
1289
+ ? '远端父目录不存在,请先用 ssh_mkdir 创建后重新上传'
1290
+ : '远端父路径是文件,请改用目录作为父路径',
1291
+ diagnostics,
1292
+ });
1293
+ }
1195
1294
  if (!sourceIsDirectory && (args.verify?.count || args.verify?.deletions || args.verify?.staleFiles)) {
1196
1295
  return formatResult({
1197
1296
  success: false,
@@ -1217,7 +1316,7 @@ async function handleSync(args) {
1217
1316
  }
1218
1317
  let deletionBaseline;
1219
1318
  try {
1220
- deletionBaseline = await captureDeletionBaseline(args, remainingTimeout);
1319
+ deletionBaseline = await captureDeletionBaseline(args, control);
1221
1320
  if (deletionBaseline) {
1222
1321
  diagnostics.deletionBaseline = {
1223
1322
  count: deletionBaseline.count,
@@ -1230,7 +1329,8 @@ async function handleSync(args) {
1230
1329
  }
1231
1330
  }
1232
1331
  catch (error) {
1233
- const verification = verificationErrorDetails(error);
1332
+ const failure = syncVerificationError(error, control);
1333
+ const verification = verificationErrorDetails(failure);
1234
1334
  return formatResult({
1235
1335
  success: false,
1236
1336
  transferSuccess: false,
@@ -1238,7 +1338,8 @@ async function handleSync(args) {
1238
1338
  verificationSuccess: false,
1239
1339
  verificationStatus: 'error',
1240
1340
  failedChecks: ['deletions'],
1241
- error: `Deletion baseline capture failed: ${error instanceof Error ? error.message : String(error)}`,
1341
+ error: 'Deletion baseline capture failed: ' +
1342
+ `${failure instanceof Error ? failure.message : String(failure)}`,
1242
1343
  verification,
1243
1344
  diagnostics,
1244
1345
  });
@@ -1257,10 +1358,14 @@ async function handleSync(args) {
1257
1358
  exclude: args.exclude,
1258
1359
  recursive: args.recursive,
1259
1360
  followSymlinks: args.followSymlinks,
1361
+ verifySha256: args.verify?.sha256 === true,
1260
1362
  preflightTimeout: args.preflightTimeout,
1261
1363
  connectTimeout: args.connectTimeout,
1262
1364
  operationTimeout: transferTimeout,
1365
+ deadline,
1366
+ signal: control.signal,
1263
1367
  remotePathStyle: sessionManager.getRemotePathStyle(args.alias),
1368
+ onProgress,
1264
1369
  });
1265
1370
  const localAfter = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
1266
1371
  diagnostics.localAfter = summarizeLocalPathProbe(localAfter);
@@ -1272,15 +1377,16 @@ async function handleSync(args) {
1272
1377
  let verificationError;
1273
1378
  if (verificationRequested && syncResult.success) {
1274
1379
  try {
1275
- const ownerModeVerification = await buildSyncUploadVerification(args, args.direction === 'upload' ? localBefore : localAfter, remainingTimeout());
1380
+ const ownerModeVerification = await buildSyncUploadVerification(args, args.direction === 'upload' ? localBefore : localAfter, control);
1276
1381
  const contentVerification = sourceIsDirectory
1277
- ? await buildDirectorySyncVerification(args, args.direction === 'upload' ? localBefore : localAfter, remainingTimeout(), deletionBaseline)
1278
- : await buildSingleFileSyncVerification(args, args.direction === 'upload' ? localBefore : transferredLocal, remainingTimeout());
1382
+ ? await buildDirectorySyncVerification(args, args.direction === 'upload' ? localBefore : localAfter, control, deletionBaseline)
1383
+ : await buildSingleFileSyncVerification(args, args.direction === 'upload' ? localBefore : transferredLocal, control);
1384
+ remainingVerificationTimeout(control);
1279
1385
  verification = mergeSyncVerification(undefined, ownerModeVerification, contentVerification);
1280
1386
  }
1281
1387
  catch (error) {
1282
- verificationError = error;
1283
- verification = mergeSyncVerification(undefined, verificationErrorDetails(error), undefined);
1388
+ verificationError = syncVerificationError(error, control);
1389
+ verification = mergeSyncVerification(undefined, verificationErrorDetails(verificationError), undefined);
1284
1390
  }
1285
1391
  }
1286
1392
  const outcome = buildTransferOutcome(syncResult.success, verificationRequested, verification, verificationError);
@@ -1297,15 +1403,19 @@ async function handleSync(args) {
1297
1403
  localPath: args.localPath,
1298
1404
  remotePath: args.remotePath,
1299
1405
  diagnostics,
1406
+ ...(progressWarning ? { progressWarning } : {}),
1300
1407
  });
1301
1408
  }
1302
1409
  catch (error) {
1303
- return formatResult({
1304
- success: false,
1305
- error: error instanceof Error ? error.message : String(error),
1410
+ return formatError(error, {
1411
+ ...sftpOperationOutcome(error),
1306
1412
  diagnostics,
1413
+ ...(progressWarning ? { progressWarning } : {}),
1307
1414
  });
1308
1415
  }
1416
+ finally {
1417
+ clearTimeout(timer);
1418
+ }
1309
1419
  }
1310
1420
  // ========== Register ==========
1311
1421
  export function registerFileTools(server) {
@@ -1314,7 +1424,8 @@ export function registerFileTools(server) {
1314
1424
  inputSchema: uploadSchema,
1315
1425
  }, (args) => handleUpload(args));
1316
1426
  server.registerTool('ssh_download', {
1317
- description: '从远程服务器原子下载文件。新文件使用 0600,替换普通文件时保留其 rwx 权限;symlink、目录和其他非普通目标会被拒绝。timeout 限制单个 SFTP 操作,超时后远端传输状态可能未知。',
1427
+ description: '从远程服务器原子下载文件。新文件使用 0600,替换普通文件时保留其 rwx 权限;symlink、目录和其他非普通目标会被拒绝。timeout ' +
1428
+ '限制单个 SFTP 操作,超时后远端传输状态可能未知。',
1318
1429
  inputSchema: downloadSchema,
1319
1430
  }, (args) => handleDownload(args));
1320
1431
  server.registerTool('ssh_read_file', {
@@ -1326,7 +1437,8 @@ export function registerFileTools(server) {
1326
1437
  inputSchema: writeFileSchema,
1327
1438
  }, (args) => handleWriteFile(args));
1328
1439
  server.registerTool('ssh_list_dir', {
1329
- description: '列出远程目录内容,返回数值 mode 和 permissions 文本;名称与修改时间条件取交集,使用筛选或分页参数时默认最多 100 条、65536 UTF-8 字节,使用 next_offset 续查;完整 readdir 后分页,目录变化时不保证快照一致性',
1440
+ description: '列出远程目录内容,返回数值 mode 和 permissions 文本;名称与修改时间条件取交集,使用筛选或分页参数时默认最多 100 ' +
1441
+ '条、65536 UTF-8 字节,使用 next_offset 续查;完整 readdir 后分页,目录变化时不保证快照一致性',
1330
1442
  inputSchema: listDirSchema,
1331
1443
  }, (args) => handleListDir(args));
1332
1444
  server.registerTool('ssh_file_info', {
@@ -1338,21 +1450,24 @@ export function registerFileTools(server) {
1338
1450
  inputSchema: mkdirSchema,
1339
1451
  }, (args) => handleMkdir(args));
1340
1452
  server.registerTool('ssh_sync', {
1341
- description: `智能文件同步(支持目录递归)
1342
-
1343
- 只有直连且使用已校验 key path 或可用 SSH agent 的 session 才探测 rsync;password、inline key 和 jump host session 使用 SFTP
1344
- 满足 rsync 条件且本地、远端均可用 rsync 时使用 rsync,否则使用 SFTP
1345
- rsync 可实现增量传输,对大目录同步效率更高
1346
-
1347
- 用途:
1348
- - 同步本地目录到远程
1349
- - 从远程同步目录到本地
1350
- - 支持排除特定文件/目录
1351
-
1352
- 示例:
1353
- - 上传目录: ssh_sync(alias="server", localPath="/local/dir", remotePath="/remote/dir", direction="upload")
1354
- - 下载目录: ssh_sync(alias="server", localPath="/local/dir", remotePath="/remote/dir", direction="download")
1355
- - 排除文件: ssh_sync(..., exclude=["*.log", "node_modules"])`,
1453
+ description: '智能文件同步(支持目录递归)\n' +
1454
+ '\n' +
1455
+ '只有直连且使用已校验 key path 或可用 SSH agent 的 session 才探测 rsync;password、inline ' +
1456
+ 'key 和 jump host session 使用 SFTP\n' +
1457
+ '满足 rsync 条件且本地、远端均可用 rsync 时使用 rsync,否则使用 SFTP\n' +
1458
+ 'rsync 可实现增量传输,对大目录同步效率更高\n' +
1459
+ '\n' +
1460
+ '用途:\n' +
1461
+ '- 同步本地目录到远程\n' +
1462
+ '- 从远程同步目录到本地\n' +
1463
+ '- 支持排除特定文件/目录\n' +
1464
+ '\n' +
1465
+ '示例:\n' +
1466
+ '- 上传目录: ssh_sync(alias="server", localPath="/local/dir", ' +
1467
+ 'remotePath="/remote/dir", direction="upload")\n' +
1468
+ '- 下载目录: ssh_sync(alias="server", localPath="/local/dir", ' +
1469
+ 'remotePath="/remote/dir", direction="download")\n' +
1470
+ '- 排除文件: ssh_sync(..., exclude=["*.log", "node_modules"])',
1356
1471
  inputSchema: syncSchema,
1357
- }, (args) => handleSync(args));
1472
+ }, (args, extra) => handleSync(args, extra));
1358
1473
  }