@pyrokine/mcp-ssh 2.4.0 → 2.4.2
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 +193 -109
- package/README_zh.md +238 -130
- package/dist/directory-verification.js +29 -4
- package/dist/file-ops.d.ts +31 -6
- package/dist/file-ops.js +493 -169
- package/dist/forward-manager.d.ts +17 -1
- package/dist/forward-manager.js +397 -89
- package/dist/operation-manager.d.ts +13 -6
- package/dist/operation-manager.js +200 -99
- package/dist/pty-manager.d.ts +3 -3
- package/dist/pty-manager.js +61 -15
- package/dist/session-manager.d.ts +29 -4
- package/dist/session-manager.js +288 -67
- package/dist/sftp-timeout.d.ts +9 -0
- package/dist/sftp-timeout.js +49 -0
- package/dist/tools/connection.js +85 -38
- package/dist/tools/exec.js +16 -6
- package/dist/tools/file.d.ts +1 -0
- package/dist/tools/file.js +276 -148
- package/dist/tools/forward.js +11 -8
- package/dist/tools/operation.js +12 -3
- package/dist/tools/pty.js +17 -13
- package/dist/tools/schema.d.ts +4 -0
- package/dist/tools/schema.js +9 -0
- package/dist/types.d.ts +16 -0
- package/dist/utf8.d.ts +3 -0
- package/dist/utf8.js +44 -0
- package/package.json +6 -6
package/dist/tools/file.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
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 } from 'crypto';
|
|
7
|
+
import { createHash, randomBytes } from 'crypto';
|
|
8
8
|
import * as fs from 'fs';
|
|
9
9
|
import * as path from 'path';
|
|
10
10
|
import { z } from 'zod';
|
|
@@ -12,6 +12,7 @@ import { buildRemoteDirectoryManifestCommand, compareDirectoryManifests, createE
|
|
|
12
12
|
import * as fileOps from '../file-ops.js';
|
|
13
13
|
import { sessionManager } from '../session-manager.js';
|
|
14
14
|
import { buildTransferOutcome } from '../transfer-outcome.js';
|
|
15
|
+
import { operationTimeoutSchema } from './schema.js';
|
|
15
16
|
import { escapeShellArg, formatError, formatResult } from './utils.js';
|
|
16
17
|
// ========== Schemas ==========
|
|
17
18
|
const uploadSchema = z.object({
|
|
@@ -24,11 +25,13 @@ const uploadSchema = z.object({
|
|
|
24
25
|
verifyMd5: z.boolean().optional().describe('上传后比对本地和远端 MD5'),
|
|
25
26
|
verifySize: z.boolean().optional().describe('上传后校验文件大小'),
|
|
26
27
|
verifyMtime: z.boolean().optional().describe('上传后返回并比较本地和远端 mtime'),
|
|
28
|
+
timeout: operationTimeoutSchema.optional(),
|
|
27
29
|
});
|
|
28
30
|
const downloadSchema = z.object({
|
|
29
31
|
alias: z.string().describe('连接别名'),
|
|
30
32
|
remotePath: z.string().describe('远程文件路径'),
|
|
31
33
|
localPath: z.string().describe('本地保存路径'),
|
|
34
|
+
timeout: operationTimeoutSchema.optional(),
|
|
32
35
|
});
|
|
33
36
|
const readFileSchema = z.object({
|
|
34
37
|
alias: z.string().describe('连接别名'),
|
|
@@ -40,29 +43,39 @@ const readFileSchema = z.object({
|
|
|
40
43
|
.max(fileOps.HARD_READ_FILE_MAX_BYTES)
|
|
41
44
|
.optional()
|
|
42
45
|
.describe('最大读取字节数,默认 1MB,最大 16MB'),
|
|
43
|
-
offset: z
|
|
46
|
+
offset: z
|
|
47
|
+
.number()
|
|
48
|
+
.int()
|
|
49
|
+
.nonnegative()
|
|
50
|
+
.optional()
|
|
51
|
+
.describe('从 UTF-8 字符边界的字节偏移读取,与 tail/lineRange 互斥;使用上次返回的 next_offset'),
|
|
44
52
|
tail: z.boolean().optional().describe('读取文件尾部 maxBytes 字节,与 offset/lineRange 互斥'),
|
|
45
53
|
lineRange: z.string().optional().describe('按行号读取,格式为 "start-end" 或 "start",与 offset/tail 互斥'),
|
|
54
|
+
timeout: operationTimeoutSchema.optional(),
|
|
46
55
|
});
|
|
47
56
|
const writeFileSchema = z.object({
|
|
48
57
|
alias: z.string().describe('连接别名'),
|
|
49
58
|
remotePath: z.string().describe('远程文件路径'),
|
|
50
59
|
content: z.string().describe('要写入的内容'),
|
|
51
60
|
append: z.boolean().optional().describe('是否追加模式,默认覆盖'),
|
|
61
|
+
timeout: operationTimeoutSchema.optional(),
|
|
52
62
|
});
|
|
53
63
|
const listDirSchema = z.object({
|
|
54
64
|
alias: z.string().describe('连接别名'),
|
|
55
65
|
remotePath: z.string().describe('远程目录路径'),
|
|
56
66
|
showHidden: z.boolean().optional().describe('是否显示隐藏文件'),
|
|
67
|
+
timeout: operationTimeoutSchema.optional(),
|
|
57
68
|
});
|
|
58
69
|
const fileInfoSchema = z.object({
|
|
59
70
|
alias: z.string().describe('连接别名'),
|
|
60
71
|
remotePath: z.string().describe('远程路径'),
|
|
72
|
+
timeout: operationTimeoutSchema.optional(),
|
|
61
73
|
});
|
|
62
74
|
const mkdirSchema = z.object({
|
|
63
75
|
alias: z.string().describe('连接别名'),
|
|
64
76
|
remotePath: z.string().describe('远程目录路径'),
|
|
65
77
|
recursive: z.boolean().optional().describe('是否递归创建,默认 false'),
|
|
78
|
+
timeout: operationTimeoutSchema.optional(),
|
|
66
79
|
});
|
|
67
80
|
const syncSchema = z.object({
|
|
68
81
|
alias: z.string().describe('连接别名'),
|
|
@@ -129,6 +142,31 @@ class VerificationStageError extends Error {
|
|
|
129
142
|
this.name = 'VerificationStageError';
|
|
130
143
|
}
|
|
131
144
|
}
|
|
145
|
+
function sftpOperationOutcome(error) {
|
|
146
|
+
if (!error || typeof error !== 'object') {
|
|
147
|
+
return {};
|
|
148
|
+
}
|
|
149
|
+
const details = 'details' in error ? error.details : undefined;
|
|
150
|
+
if (details && typeof details === 'object' && 'operationStatus' in details) {
|
|
151
|
+
return details;
|
|
152
|
+
}
|
|
153
|
+
const cause = 'cause' in error ? error.cause : undefined;
|
|
154
|
+
return sftpOperationOutcome(cause);
|
|
155
|
+
}
|
|
156
|
+
function formatFileOperationError(error) {
|
|
157
|
+
const operationOutcome = sftpOperationOutcome(error);
|
|
158
|
+
if (Object.keys(operationOutcome).length === 0) {
|
|
159
|
+
return formatError(error);
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
...formatResult({
|
|
163
|
+
success: false,
|
|
164
|
+
...operationOutcome,
|
|
165
|
+
error: error instanceof Error ? error.message : String(error),
|
|
166
|
+
}),
|
|
167
|
+
isError: true,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
132
170
|
function verificationErrorDetails(error) {
|
|
133
171
|
if (error instanceof VerificationStageError) {
|
|
134
172
|
return {
|
|
@@ -181,23 +219,16 @@ function uploadPathError(code, message, diagnostics) {
|
|
|
181
219
|
}
|
|
182
220
|
async function probeRemoteParent(alias, remotePath) {
|
|
183
221
|
const parent = path.posix.dirname(remotePath);
|
|
184
|
-
const escapedParent = escapeShellArg(parent);
|
|
185
|
-
const command = [
|
|
186
|
-
`if [ -d ${escapedParent} ]; then`,
|
|
187
|
-
`if [ -w ${escapedParent} ]; then printf writable; else printf not-writable; fi;`,
|
|
188
|
-
'else printf missing; fi',
|
|
189
|
-
].join(' ');
|
|
190
222
|
try {
|
|
191
|
-
const result = await
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
return { exists: status !== 'missing', writable: status === 'writable' };
|
|
223
|
+
const result = await probeRemoteFile(alias, parent);
|
|
224
|
+
return {
|
|
225
|
+
exists: result.exists,
|
|
226
|
+
isDirectory: result.exists ? result.isDirectory : false,
|
|
227
|
+
probeMethod: 'sftp',
|
|
228
|
+
};
|
|
198
229
|
}
|
|
199
230
|
catch (error) {
|
|
200
|
-
return { error: error instanceof Error ? error.message : String(error) };
|
|
231
|
+
return { error: error instanceof Error ? error.message : String(error), probeMethod: 'sftp' };
|
|
201
232
|
}
|
|
202
233
|
}
|
|
203
234
|
function hashLocalFileMd5(filePath) {
|
|
@@ -236,26 +267,32 @@ function commandFailureDetails(result) {
|
|
|
236
267
|
};
|
|
237
268
|
}
|
|
238
269
|
async function hashRemoteFileMd5(alias, remotePath) {
|
|
239
|
-
|
|
240
|
-
|
|
270
|
+
try {
|
|
271
|
+
return await fileOps.hashRemoteFileDigest(alias, remotePath, 'md5');
|
|
272
|
+
}
|
|
273
|
+
catch (error) {
|
|
274
|
+
throw new VerificationStageError('remote_probe', `Remote SFTP MD5 read failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'md5', probeMethod: 'sftp' });
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
async function resolveExpectedOwnerId(alias, owner) {
|
|
278
|
+
const ownerText = String(owner);
|
|
279
|
+
if (/^\d+$/.test(ownerText)) {
|
|
280
|
+
return ownerText;
|
|
281
|
+
}
|
|
282
|
+
const result = await sessionManager.exec(alias, `id -u ${escapeShellArg(ownerText)}`, {
|
|
283
|
+
timeout: 10000,
|
|
241
284
|
useLoginUser: true,
|
|
242
285
|
maxOutputSize: 4096,
|
|
243
286
|
});
|
|
244
|
-
|
|
287
|
+
const ownerId = result.stdout.trim();
|
|
288
|
+
if (!result.success || !/^\d+$/.test(ownerId)) {
|
|
245
289
|
const detail = result.stderr.trim() || result.stdout.trim() || `exit code ${result.exitCode}`;
|
|
246
|
-
throw new VerificationStageError('remote_probe', `Remote
|
|
247
|
-
operation: '
|
|
248
|
-
...commandFailureDetails(result),
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
const digest = result.stdout.trim().split(/\s+/)[0];
|
|
252
|
-
if (!/^[a-fA-F0-9]{32}$/.test(digest)) {
|
|
253
|
-
throw new VerificationStageError('remote_probe', 'Remote MD5 command returned an invalid digest', false, {
|
|
254
|
-
operation: 'md5',
|
|
290
|
+
throw new VerificationStageError('remote_probe', `Remote owner lookup failed: ${detail}`, true, {
|
|
291
|
+
operation: 'owner_lookup',
|
|
255
292
|
...commandFailureDetails(result),
|
|
256
293
|
});
|
|
257
294
|
}
|
|
258
|
-
return
|
|
295
|
+
return ownerId;
|
|
259
296
|
}
|
|
260
297
|
function permissionStringToOctal(permissions) {
|
|
261
298
|
const bits = permissions.slice(-9);
|
|
@@ -277,71 +314,56 @@ function permissionStringToOctal(permissions) {
|
|
|
277
314
|
});
|
|
278
315
|
return `0${values.join('')}`;
|
|
279
316
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
`if [ -e ${escapedRemotePath} ]; then`,
|
|
284
|
-
`stat -c '%U\t%u\t%G\t%g\t%a\t%s\t%Y\t%F' ${escapedRemotePath};`,
|
|
285
|
-
'else printf missing; fi',
|
|
286
|
-
].join(' ');
|
|
287
|
-
const result = await sessionManager.exec(alias, command, {
|
|
288
|
-
timeout,
|
|
289
|
-
useLoginUser: true,
|
|
290
|
-
maxOutputSize: 4096,
|
|
291
|
-
});
|
|
292
|
-
if (!result.success) {
|
|
293
|
-
const detail = result.stderr.trim() || result.stdout.trim() || `exit code ${result.exitCode}`;
|
|
294
|
-
throw new VerificationStageError('remote_probe', `Remote stat command failed: ${detail}`, true, {
|
|
295
|
-
operation: 'stat',
|
|
296
|
-
...commandFailureDetails(result),
|
|
297
|
-
});
|
|
317
|
+
function isRemoteMissingError(error) {
|
|
318
|
+
if (!error || typeof error !== 'object') {
|
|
319
|
+
return false;
|
|
298
320
|
}
|
|
299
|
-
|
|
300
|
-
|
|
321
|
+
const code = 'code' in error ? error.code : undefined;
|
|
322
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
323
|
+
return code === 2 || code === 'ENOENT' || /no such file|not found/i.test(message);
|
|
324
|
+
}
|
|
325
|
+
async function probeRemoteFile(alias, remotePath, timeout = 10000) {
|
|
326
|
+
let info;
|
|
327
|
+
try {
|
|
328
|
+
info = await fileOps.getFileInfo(alias, remotePath, timeout);
|
|
301
329
|
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
});
|
|
330
|
+
catch (error) {
|
|
331
|
+
if (isRemoteMissingError(error)) {
|
|
332
|
+
return { exists: false, remotePath, probeMethod: 'sftp' };
|
|
333
|
+
}
|
|
334
|
+
throw new VerificationStageError('remote_probe', `Remote SFTP stat failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'stat', probeMethod: 'sftp' });
|
|
308
335
|
}
|
|
309
|
-
const
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
const sizeValue = Number(size);
|
|
313
|
-
const mtimeValue = Number(mtimeSeconds);
|
|
314
|
-
if (!Number.isSafeInteger(ownerIdValue) ||
|
|
315
|
-
ownerIdValue < 0 ||
|
|
316
|
-
!Number.isSafeInteger(groupIdValue) ||
|
|
317
|
-
groupIdValue < 0 ||
|
|
318
|
-
!Number.isSafeInteger(sizeValue) ||
|
|
319
|
-
sizeValue < 0 ||
|
|
320
|
-
!Number.isFinite(mtimeValue) ||
|
|
321
|
-
!/^[0-7]{3,4}$/.test(mode)) {
|
|
322
|
-
throw new VerificationStageError('remote_probe', 'Remote stat command returned invalid metadata', false, {
|
|
336
|
+
const mode = permissionStringToOctal(info.permissions);
|
|
337
|
+
if (!mode) {
|
|
338
|
+
throw new VerificationStageError('remote_probe', 'Remote SFTP stat returned invalid mode metadata', false, {
|
|
323
339
|
operation: 'stat',
|
|
324
|
-
|
|
340
|
+
probeMethod: 'sftp',
|
|
325
341
|
});
|
|
326
342
|
}
|
|
327
343
|
return {
|
|
328
344
|
exists: true,
|
|
329
345
|
remotePath,
|
|
330
|
-
probeMethod: '
|
|
331
|
-
ownerName,
|
|
332
|
-
ownerId:
|
|
333
|
-
groupName,
|
|
334
|
-
groupId:
|
|
335
|
-
mode
|
|
336
|
-
size:
|
|
337
|
-
mtimeMs:
|
|
338
|
-
fileType
|
|
339
|
-
|
|
340
|
-
|
|
346
|
+
probeMethod: 'sftp',
|
|
347
|
+
ownerName: undefined,
|
|
348
|
+
ownerId: info.owner,
|
|
349
|
+
groupName: undefined,
|
|
350
|
+
groupId: info.group,
|
|
351
|
+
mode,
|
|
352
|
+
size: info.size,
|
|
353
|
+
mtimeMs: info.mtime.getTime(),
|
|
354
|
+
fileType: info.isDirectory
|
|
355
|
+
? 'directory'
|
|
356
|
+
: info.isFile
|
|
357
|
+
? 'regular file'
|
|
358
|
+
: info.isSymlink
|
|
359
|
+
? 'symbolic link'
|
|
360
|
+
: 'other',
|
|
361
|
+
isDirectory: info.isDirectory,
|
|
362
|
+
isFile: info.isFile,
|
|
341
363
|
};
|
|
342
364
|
}
|
|
343
|
-
async function buildUploadVerification(args, local) {
|
|
344
|
-
const remote = await probeRemoteFile(args.alias,
|
|
365
|
+
async function buildUploadVerification(args, local, verificationRemotePath = args.remotePath) {
|
|
366
|
+
const remote = await probeRemoteFile(args.alias, verificationRemotePath);
|
|
345
367
|
const checks = {};
|
|
346
368
|
if (args.verifySize) {
|
|
347
369
|
checks.size = local.exists && remote.exists ? local.size === remote.size : false;
|
|
@@ -355,13 +377,13 @@ async function buildUploadVerification(args, local) {
|
|
|
355
377
|
checks.mode = remote.exists && expectedMode !== undefined && remote.mode === expectedMode;
|
|
356
378
|
}
|
|
357
379
|
if (args.verifyOwner !== undefined) {
|
|
358
|
-
const
|
|
359
|
-
checks.owner = remote.exists &&
|
|
380
|
+
const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner);
|
|
381
|
+
checks.owner = remote.exists && String(remote.ownerId) === expectedOwnerId;
|
|
360
382
|
}
|
|
361
383
|
if (args.verifyMd5 && local.exists) {
|
|
362
384
|
const [localMd5, remoteMd5] = await Promise.all([
|
|
363
385
|
hashLocalFileMd5(local.resolvedPath),
|
|
364
|
-
hashRemoteFileMd5(args.alias,
|
|
386
|
+
hashRemoteFileMd5(args.alias, verificationRemotePath),
|
|
365
387
|
]);
|
|
366
388
|
checks.md5 = remoteMd5 ? localMd5 === remoteMd5 : undefined;
|
|
367
389
|
return {
|
|
@@ -398,11 +420,11 @@ function normalizeExpectedMode(mode) {
|
|
|
398
420
|
}
|
|
399
421
|
return permissionStringToOctal(trimmed);
|
|
400
422
|
}
|
|
401
|
-
function buildSyncVerificationChecks(args, remote) {
|
|
423
|
+
async function buildSyncVerificationChecks(args, remote) {
|
|
402
424
|
const checks = {};
|
|
403
425
|
if (args.verifyOwner !== undefined) {
|
|
404
|
-
const
|
|
405
|
-
checks.owner = remote.exists &&
|
|
426
|
+
const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner);
|
|
427
|
+
checks.owner = remote.exists && String(remote.ownerId) === expectedOwnerId;
|
|
406
428
|
}
|
|
407
429
|
if (args.verifyMode !== undefined) {
|
|
408
430
|
const expectedMode = normalizeExpectedMode(args.verifyMode);
|
|
@@ -444,7 +466,7 @@ async function buildSyncUploadVerification(args, local, timeout) {
|
|
|
444
466
|
}
|
|
445
467
|
const verificationRemotePath = await resolveSyncUploadVerificationPath(args, local, timeout);
|
|
446
468
|
const remote = await probeRemoteFile(args.alias, verificationRemotePath, timeout);
|
|
447
|
-
const checks = buildSyncVerificationChecks(args, remote);
|
|
469
|
+
const checks = await buildSyncVerificationChecks(args, remote);
|
|
448
470
|
const matched = Object.values(checks).every(Boolean);
|
|
449
471
|
return {
|
|
450
472
|
kind: 'owner_mode',
|
|
@@ -588,22 +610,52 @@ function mergeSyncVerification(existing, ownerMode, directory) {
|
|
|
588
610
|
};
|
|
589
611
|
}
|
|
590
612
|
async function cleanupRemotePath(alias, remotePath) {
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
613
|
+
try {
|
|
614
|
+
await fileOps.removeRemoteFile(alias, remotePath);
|
|
615
|
+
}
|
|
616
|
+
catch (error) {
|
|
617
|
+
throw new Error(`Temporary remote file cleanup failed: ${error instanceof Error ? error.message : String(error)}`, {
|
|
618
|
+
cause: error,
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
export function createAtomicUploadPath(remotePath) {
|
|
623
|
+
return `${remotePath}.mcp-tmp-${process.pid}-${randomBytes(12).toString('hex')}`;
|
|
624
|
+
}
|
|
625
|
+
function uploadPathDetails(args, verificationRemotePath, verification) {
|
|
626
|
+
return {
|
|
627
|
+
finalRemotePath: args.remotePath,
|
|
628
|
+
verifiedRemotePath: verification ? verificationRemotePath : undefined,
|
|
629
|
+
verifiedTempRemotePath: verification && args.atomic ? verificationRemotePath : undefined,
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
function addUploadVerificationPaths(verification, args, verificationRemotePath) {
|
|
633
|
+
if (!verification) {
|
|
634
|
+
return undefined;
|
|
599
635
|
}
|
|
636
|
+
return {
|
|
637
|
+
...verification,
|
|
638
|
+
...uploadPathDetails(args, verificationRemotePath, verification),
|
|
639
|
+
};
|
|
600
640
|
}
|
|
601
641
|
async function handleUpload(args) {
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
642
|
+
let local;
|
|
643
|
+
try {
|
|
644
|
+
fileOps.validateUploadFileSource(args.localPath);
|
|
645
|
+
local = fileOps.probeLocalPath(args.localPath);
|
|
646
|
+
}
|
|
647
|
+
catch (error) {
|
|
648
|
+
local = fileOps.probeLocalPath(args.localPath);
|
|
649
|
+
if (local.exists && local.isDirectory) {
|
|
650
|
+
return uploadPathError('UPLOAD_PATH_IS_DIRECTORY', 'localPath is a directory', {
|
|
651
|
+
local: summarizeLocalPathProbe(local),
|
|
652
|
+
suggestion: '使用 ssh_sync 上传目录,或把 localPath 指向具体文件',
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
return formatResult({
|
|
656
|
+
success: false,
|
|
657
|
+
error: error instanceof Error ? error.message : String(error),
|
|
658
|
+
diagnostics: { local: summarizeLocalPathProbe(local) },
|
|
607
659
|
});
|
|
608
660
|
}
|
|
609
661
|
const largeFileSuggestion = local.exists && typeof local.size === 'number' && local.size >= LARGE_UPLOAD_THRESHOLD
|
|
@@ -639,52 +691,99 @@ async function handleUpload(args) {
|
|
|
639
691
|
: undefined;
|
|
640
692
|
const existingMode = remoteBefore.exists && remoteBefore.mode ? Number.parseInt(remoteBefore.mode, 8) & 0o777 : undefined;
|
|
641
693
|
const createMode = args.atomic && existingMode !== undefined ? existingMode : sourceMode;
|
|
642
|
-
const tempRemotePath = args.atomic
|
|
643
|
-
|
|
644
|
-
|
|
694
|
+
const tempRemotePath = args.atomic ? createAtomicUploadPath(args.remotePath) : args.remotePath;
|
|
695
|
+
const verificationRequested = Boolean(args.verifyOwner !== undefined ||
|
|
696
|
+
args.verifyMode !== undefined ||
|
|
697
|
+
args.verifyMd5 ||
|
|
698
|
+
args.verifySize ||
|
|
699
|
+
args.verifyMtime);
|
|
645
700
|
try {
|
|
646
|
-
const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath, undefined, undefined, createMode);
|
|
701
|
+
const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath, undefined, undefined, createMode, undefined, false, args.atomic === true, args.timeout);
|
|
702
|
+
let verification;
|
|
703
|
+
let verificationError;
|
|
704
|
+
if (verificationRequested) {
|
|
705
|
+
try {
|
|
706
|
+
verification = await buildUploadVerification(args, local, tempRemotePath);
|
|
707
|
+
}
|
|
708
|
+
catch (error) {
|
|
709
|
+
verificationError = error;
|
|
710
|
+
verification = verificationErrorDetails(error);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
verification = addUploadVerificationPaths(verification, args, tempRemotePath);
|
|
714
|
+
const outcome = buildTransferOutcome(uploadResult.success, verificationRequested, verification, verificationError);
|
|
715
|
+
const pathDetails = uploadPathDetails(args, tempRemotePath, verification);
|
|
716
|
+
if (args.atomic && !outcome.success) {
|
|
717
|
+
let cleanupWarning;
|
|
718
|
+
try {
|
|
719
|
+
await cleanupRemotePath(args.alias, tempRemotePath);
|
|
720
|
+
}
|
|
721
|
+
catch (cleanupError) {
|
|
722
|
+
cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
|
|
723
|
+
}
|
|
724
|
+
const verificationMessage = verificationError instanceof Error ? verificationError.message : String(verificationError);
|
|
725
|
+
return formatResult({
|
|
726
|
+
...uploadResult,
|
|
727
|
+
...outcome,
|
|
728
|
+
message: `Atomic upload verification failed; existing target preserved: ${args.remotePath}`,
|
|
729
|
+
error: verificationError === undefined
|
|
730
|
+
? `Atomic upload verification failed: ${args.remotePath}`
|
|
731
|
+
: `Atomic upload verification failed: ${verificationMessage}`,
|
|
732
|
+
cleanupWarning,
|
|
733
|
+
atomic: true,
|
|
734
|
+
targetReplaced: false,
|
|
735
|
+
...pathDetails,
|
|
736
|
+
createMode: uploadResult.createMode,
|
|
737
|
+
existingTargetModePreserved: remoteBefore.exists,
|
|
738
|
+
suggestion: largeFileSuggestion,
|
|
739
|
+
recommendedSync,
|
|
740
|
+
diagnostics: {
|
|
741
|
+
local: summarizeLocalPathProbe(local),
|
|
742
|
+
remoteParent,
|
|
743
|
+
atomic: true,
|
|
744
|
+
tempRemotePath,
|
|
745
|
+
},
|
|
746
|
+
verification,
|
|
747
|
+
});
|
|
748
|
+
}
|
|
647
749
|
if (args.atomic) {
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
750
|
+
try {
|
|
751
|
+
await fileOps.renameRemoteFile(args.alias, tempRemotePath, args.remotePath, remoteBefore.exists, args.timeout);
|
|
752
|
+
}
|
|
753
|
+
catch (error) {
|
|
754
|
+
const renameNotStarted = error instanceof fileOps.RemoteRenameNotStartedError;
|
|
755
|
+
const renameError = error instanceof Error ? error.message : String(error);
|
|
651
756
|
let cleanupWarning;
|
|
652
757
|
try {
|
|
653
758
|
await cleanupRemotePath(args.alias, tempRemotePath);
|
|
654
759
|
}
|
|
655
|
-
catch (
|
|
656
|
-
cleanupWarning =
|
|
760
|
+
catch (cleanupError) {
|
|
761
|
+
cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
|
|
657
762
|
}
|
|
658
763
|
return formatResult({
|
|
659
764
|
success: false,
|
|
660
|
-
|
|
765
|
+
transferSuccess: true,
|
|
766
|
+
operationStatus: renameNotStarted ? 'failed' : 'unknown',
|
|
767
|
+
retryable: true,
|
|
768
|
+
error: renameNotStarted
|
|
769
|
+
? `Atomic SFTP rename request was not sent; target was not replaced: ${renameError}`
|
|
770
|
+
: `Atomic SFTP rename response failed; target replacement state is unknown: ${renameError}`,
|
|
661
771
|
cleanupWarning,
|
|
772
|
+
atomic: true,
|
|
773
|
+
targetReplaced: renameNotStarted ? false : null,
|
|
774
|
+
targetReplacementStatus: renameNotStarted ? 'not_replaced' : 'unknown',
|
|
775
|
+
...pathDetails,
|
|
662
776
|
diagnostics: {
|
|
663
777
|
local: summarizeLocalPathProbe(local),
|
|
664
778
|
remoteParent,
|
|
665
779
|
atomic: true,
|
|
666
780
|
tempRemotePath,
|
|
667
781
|
},
|
|
782
|
+
verification,
|
|
668
783
|
});
|
|
669
784
|
}
|
|
670
785
|
}
|
|
671
|
-
const
|
|
672
|
-
args.verifyMode !== undefined ||
|
|
673
|
-
args.verifyMd5 ||
|
|
674
|
-
args.verifySize ||
|
|
675
|
-
args.verifyMtime);
|
|
676
|
-
let verification;
|
|
677
|
-
let verificationError;
|
|
678
|
-
if (verificationRequested) {
|
|
679
|
-
try {
|
|
680
|
-
verification = await buildUploadVerification(args, local);
|
|
681
|
-
}
|
|
682
|
-
catch (error) {
|
|
683
|
-
verificationError = error;
|
|
684
|
-
verification = verificationErrorDetails(error);
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
const outcome = buildTransferOutcome(uploadResult.success, verificationRequested, verification, verificationError);
|
|
786
|
+
const verificationMessage = verificationError instanceof Error ? verificationError.message : String(verificationError);
|
|
688
787
|
return formatResult({
|
|
689
788
|
...uploadResult,
|
|
690
789
|
...outcome,
|
|
@@ -693,8 +792,10 @@ async function handleUpload(args) {
|
|
|
693
792
|
: `Uploaded but verification failed: ${args.remotePath}`,
|
|
694
793
|
error: verificationError === undefined
|
|
695
794
|
? undefined
|
|
696
|
-
: `Upload completed, but verification failed: ${
|
|
795
|
+
: `Upload completed, but verification failed: ${verificationMessage}`,
|
|
697
796
|
atomic: args.atomic === true,
|
|
797
|
+
targetReplaced: args.atomic ? true : undefined,
|
|
798
|
+
...pathDetails,
|
|
698
799
|
createMode: uploadResult.createMode,
|
|
699
800
|
existingTargetModePreserved: remoteBefore.exists,
|
|
700
801
|
suggestion: largeFileSuggestion,
|
|
@@ -710,7 +811,8 @@ async function handleUpload(args) {
|
|
|
710
811
|
}
|
|
711
812
|
catch (error) {
|
|
712
813
|
let cleanupWarning;
|
|
713
|
-
|
|
814
|
+
const shouldCleanupTemporaryUpload = args.atomic && (!(error instanceof fileOps.UploadFileError) || error.remoteCreated);
|
|
815
|
+
if (shouldCleanupTemporaryUpload) {
|
|
714
816
|
try {
|
|
715
817
|
await cleanupRemotePath(args.alias, tempRemotePath);
|
|
716
818
|
}
|
|
@@ -720,8 +822,10 @@ async function handleUpload(args) {
|
|
|
720
822
|
}
|
|
721
823
|
return formatResult({
|
|
722
824
|
success: false,
|
|
825
|
+
...sftpOperationOutcome(error),
|
|
723
826
|
error: error instanceof Error ? error.message : String(error),
|
|
724
827
|
cleanupWarning,
|
|
828
|
+
finalRemotePath: args.remotePath,
|
|
725
829
|
diagnostics: {
|
|
726
830
|
local: summarizeLocalPathProbe(local),
|
|
727
831
|
remoteParent,
|
|
@@ -734,12 +838,13 @@ async function handleUpload(args) {
|
|
|
734
838
|
}
|
|
735
839
|
async function handleDownload(args) {
|
|
736
840
|
try {
|
|
737
|
-
const downloadResult = await fileOps.downloadFile(args.alias, args.remotePath, args.localPath);
|
|
841
|
+
const downloadResult = await fileOps.downloadFile(args.alias, args.remotePath, args.localPath, undefined, undefined, undefined, args.timeout);
|
|
738
842
|
return formatResult({ ...downloadResult, message: `Downloaded to ${args.localPath}` });
|
|
739
843
|
}
|
|
740
844
|
catch (error) {
|
|
741
845
|
return formatResult({
|
|
742
846
|
success: false,
|
|
847
|
+
...sftpOperationOutcome(error),
|
|
743
848
|
error: error instanceof Error ? error.message : String(error),
|
|
744
849
|
diagnostics: {
|
|
745
850
|
local: summarizeLocalPathProbe(fileOps.probeLocalPath(args.localPath)),
|
|
@@ -756,25 +861,26 @@ async function handleReadFile(args) {
|
|
|
756
861
|
offset: args.offset,
|
|
757
862
|
tail: args.tail,
|
|
758
863
|
lineRange: args.lineRange,
|
|
864
|
+
timeout: args.timeout,
|
|
759
865
|
});
|
|
760
866
|
return formatResult({ success: true, ...readResult });
|
|
761
867
|
}
|
|
762
868
|
catch (error) {
|
|
763
|
-
return
|
|
869
|
+
return formatFileOperationError(error);
|
|
764
870
|
}
|
|
765
871
|
}
|
|
766
872
|
async function handleWriteFile(args) {
|
|
767
873
|
try {
|
|
768
|
-
const result = await fileOps.writeFile(args.alias, args.remotePath, args.content, args.append);
|
|
874
|
+
const result = await fileOps.writeFile(args.alias, args.remotePath, args.content, args.append, args.timeout);
|
|
769
875
|
return formatResult(result);
|
|
770
876
|
}
|
|
771
877
|
catch (error) {
|
|
772
|
-
return
|
|
878
|
+
return formatFileOperationError(error);
|
|
773
879
|
}
|
|
774
880
|
}
|
|
775
881
|
async function handleListDir(args) {
|
|
776
882
|
try {
|
|
777
|
-
const files = await fileOps.listDir(args.alias, args.remotePath, args.showHidden);
|
|
883
|
+
const files = await fileOps.listDir(args.alias, args.remotePath, args.showHidden, undefined, args.timeout);
|
|
778
884
|
return formatResult({
|
|
779
885
|
success: true,
|
|
780
886
|
path: args.remotePath,
|
|
@@ -783,25 +889,25 @@ async function handleListDir(args) {
|
|
|
783
889
|
});
|
|
784
890
|
}
|
|
785
891
|
catch (error) {
|
|
786
|
-
return
|
|
892
|
+
return formatFileOperationError(error);
|
|
787
893
|
}
|
|
788
894
|
}
|
|
789
895
|
async function handleFileInfo(args) {
|
|
790
896
|
try {
|
|
791
|
-
const info = await fileOps.getFileInfo(args.alias, args.remotePath);
|
|
897
|
+
const info = await fileOps.getFileInfo(args.alias, args.remotePath, args.timeout);
|
|
792
898
|
return formatResult({ success: true, ...info });
|
|
793
899
|
}
|
|
794
900
|
catch (error) {
|
|
795
|
-
return
|
|
901
|
+
return formatFileOperationError(error);
|
|
796
902
|
}
|
|
797
903
|
}
|
|
798
904
|
async function handleMkdir(args) {
|
|
799
905
|
try {
|
|
800
|
-
const success = await fileOps.mkdir(args.alias, args.remotePath, args.recursive);
|
|
906
|
+
const success = await fileOps.mkdir(args.alias, args.remotePath, args.recursive, undefined, args.timeout);
|
|
801
907
|
return formatResult({ success, path: args.remotePath });
|
|
802
908
|
}
|
|
803
909
|
catch (error) {
|
|
804
|
-
return
|
|
910
|
+
return formatFileOperationError(error);
|
|
805
911
|
}
|
|
806
912
|
}
|
|
807
913
|
async function handleSync(args) {
|
|
@@ -815,6 +921,23 @@ async function handleSync(args) {
|
|
|
815
921
|
}
|
|
816
922
|
const operationTimeout = args.operationTimeout ?? 600_000;
|
|
817
923
|
const remainingTimeout = () => operationTimeout - (Date.now() - startedAt);
|
|
924
|
+
try {
|
|
925
|
+
if (args.direction === 'upload') {
|
|
926
|
+
fileOps.validateSyncUploadSource(args.localPath, args.followSymlinks === true);
|
|
927
|
+
}
|
|
928
|
+
else {
|
|
929
|
+
fileOps.validateLocalPathPolicy(args.localPath);
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
catch (error) {
|
|
933
|
+
return formatResult({
|
|
934
|
+
success: false,
|
|
935
|
+
error: error instanceof Error ? error.message : String(error),
|
|
936
|
+
diagnostics: {
|
|
937
|
+
localBefore: summarizeLocalPathProbe(fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true)),
|
|
938
|
+
},
|
|
939
|
+
});
|
|
940
|
+
}
|
|
818
941
|
const localBefore = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
|
|
819
942
|
const diagnostics = {
|
|
820
943
|
localBefore: summarizeLocalPathProbe(localBefore),
|
|
@@ -851,7 +974,11 @@ async function handleSync(args) {
|
|
|
851
974
|
}
|
|
852
975
|
const transferTimeout = remainingTimeout();
|
|
853
976
|
if (transferTimeout <= 0) {
|
|
854
|
-
|
|
977
|
+
return formatResult({
|
|
978
|
+
success: false,
|
|
979
|
+
error: 'sync operation timeout was exhausted before transfer started',
|
|
980
|
+
diagnostics,
|
|
981
|
+
});
|
|
855
982
|
}
|
|
856
983
|
const syncResult = await fileOps.syncFiles(args.alias, args.localPath, args.remotePath, args.direction, {
|
|
857
984
|
delete: args.delete,
|
|
@@ -880,12 +1007,13 @@ async function handleSync(args) {
|
|
|
880
1007
|
}
|
|
881
1008
|
}
|
|
882
1009
|
const outcome = buildTransferOutcome(syncResult.success, verificationRequested, verification, verificationError);
|
|
1010
|
+
const verificationMessage = verificationError instanceof Error ? verificationError.message : String(verificationError);
|
|
883
1011
|
return formatResult({
|
|
884
1012
|
...syncResult,
|
|
885
1013
|
...outcome,
|
|
886
1014
|
error: verificationError === undefined
|
|
887
1015
|
? undefined
|
|
888
|
-
: `Sync completed, but verification failed: ${
|
|
1016
|
+
: `Sync completed, but verification failed: ${verificationMessage}`,
|
|
889
1017
|
transportVerification: syncResult.verification,
|
|
890
1018
|
verification,
|
|
891
1019
|
direction: args.direction,
|
|
@@ -905,19 +1033,19 @@ async function handleSync(args) {
|
|
|
905
1033
|
// ========== Register ==========
|
|
906
1034
|
export function registerFileTools(server) {
|
|
907
1035
|
server.registerTool('ssh_upload', {
|
|
908
|
-
description: '
|
|
1036
|
+
description: '上传本地文件到远程服务器。timeout 限制单个 SFTP 操作,超时后远端传输状态可能未知。',
|
|
909
1037
|
inputSchema: uploadSchema,
|
|
910
1038
|
}, (args) => handleUpload(args));
|
|
911
1039
|
server.registerTool('ssh_download', {
|
|
912
|
-
description: '
|
|
1040
|
+
description: '从远程服务器下载文件。timeout 限制单个 SFTP 操作,超时后远端传输状态可能未知。',
|
|
913
1041
|
inputSchema: downloadSchema,
|
|
914
1042
|
}, (args) => handleDownload(args));
|
|
915
1043
|
server.registerTool('ssh_read_file', {
|
|
916
|
-
description: '
|
|
1044
|
+
description: '读取远程文件内容。文本读取只返回完整 UTF-8 字符;后续读取使用响应中的 next_offset。',
|
|
917
1045
|
inputSchema: readFileSchema,
|
|
918
1046
|
}, (args) => handleReadFile(args));
|
|
919
1047
|
server.registerTool('ssh_write_file', {
|
|
920
|
-
description: '
|
|
1048
|
+
description: '写入内容到远程文件。timeout 限制单个 SFTP 操作,超时后远端写入状态可能未知。',
|
|
921
1049
|
inputSchema: writeFileSchema,
|
|
922
1050
|
}, (args) => handleWriteFile(args));
|
|
923
1051
|
server.registerTool('ssh_list_dir', {
|