@pyrokine/mcp-ssh 3.2.0 → 3.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +84 -22
- package/README_zh.md +45 -12
- package/dist/command-risk.js +1 -1
- package/dist/directory-verification.js +10 -10
- package/dist/file-ops.d.ts +9 -5
- package/dist/file-ops.js +165 -58
- package/dist/known-hosts.d.ts +2 -2
- package/dist/known-hosts.js +110 -59
- package/dist/openssh.d.ts +5 -5
- package/dist/openssh.js +92 -38
- package/dist/remote-platform.js +2 -2
- package/dist/session-manager.d.ts +7 -1
- package/dist/session-manager.js +140 -23
- package/dist/sftp-timeout.d.ts +1 -1
- package/dist/sftp-timeout.js +12 -2
- package/dist/tools/connection.js +14 -10
- package/dist/tools/exec.js +66 -35
- package/dist/tools/file.js +93 -21
- package/dist/transfer-outcome.js +1 -1
- package/dist/types.d.ts +4 -1
- package/dist/windows-acl.d.ts +3 -2
- package/dist/windows-acl.js +23 -10
- package/package.json +5 -5
package/dist/tools/exec.js
CHANGED
|
@@ -8,14 +8,14 @@ import { randomUUID } from 'crypto';
|
|
|
8
8
|
import { z } from 'zod';
|
|
9
9
|
import { classifyCommandRisk } from '../command-risk.js';
|
|
10
10
|
import * as fileOps from '../file-ops.js';
|
|
11
|
-
import { sftpOperationOutcome } from '../sftp-timeout.js';
|
|
12
11
|
import { OpenSshError } from '../openssh.js';
|
|
13
12
|
import { encodedPowershell, quotePowershell, sftpPath } from '../remote-platform.js';
|
|
14
13
|
import { sessionManager } from '../session-manager.js';
|
|
14
|
+
import { sftpOperationOutcome } from '../sftp-timeout.js';
|
|
15
15
|
import { DEFAULT_EXEC_MAX_OUTPUT_SIZE, DEFAULT_EXEC_TIMEOUT_MS, HARD_EXEC_MAX_OUTPUT_SIZE, } from '../types.js';
|
|
16
16
|
import { utf8SafeEnd } from '../utf8.js';
|
|
17
17
|
import { windowsTemporaryPathScript } from '../windows-acl.js';
|
|
18
|
-
import { sshPortSchema } from './schema.js';
|
|
18
|
+
import { operationTimeoutSchema, sshPortSchema } from './schema.js';
|
|
19
19
|
import { escapeShellArg, formatError, formatResult } from './utils.js'; // ========== Schemas ==========
|
|
20
20
|
// ========== Schemas ==========
|
|
21
21
|
const maxOutputSizeSchema = z
|
|
@@ -26,6 +26,10 @@ const maxOutputSizeSchema = z
|
|
|
26
26
|
.optional()
|
|
27
27
|
.describe('stdout/stderr 各自的 UTF-8 字节上限,超过后截断并返回提示');
|
|
28
28
|
const execSchema = z.object({
|
|
29
|
+
stdin: z
|
|
30
|
+
.string()
|
|
31
|
+
.optional()
|
|
32
|
+
.describe('以 UTF-8 写入命令标准输入并发送 EOF,省略时保持原输入行为;输入不加入命令、日志或错误'),
|
|
29
33
|
alias: z.string().describe('连接别名'),
|
|
30
34
|
command: z.string().describe('要执行的命令'),
|
|
31
35
|
timeout: z
|
|
@@ -110,14 +114,18 @@ const execScriptSchema = z.object({
|
|
|
110
114
|
runAs: z.string().optional().describe('本次脚本使用的目标用户'),
|
|
111
115
|
cwd: z.string().optional().describe('工作目录(可选)'),
|
|
112
116
|
env: z.record(z.string(), z.string()).optional().describe('额外环境变量'),
|
|
113
|
-
timeout:
|
|
117
|
+
timeout: operationTimeoutSchema
|
|
118
|
+
.optional()
|
|
119
|
+
.describe('上传、准备、执行各阶段的独立超时,最大 3600000 ms;清理独立计时,使用该值与 30000 ms 中的较小值,省略时为 30000 ms;未传时命令默认 30000 ms、SFTP 默认 600000 ms;宿主请求期限单独生效,长任务用 ssh_operation_start'),
|
|
114
120
|
keepScript: z.boolean().optional().describe('是否保留远端临时脚本,默认 false'),
|
|
115
121
|
maxOutputSize: maxOutputSizeSchema,
|
|
116
122
|
});
|
|
117
123
|
// ========== Handlers ==========
|
|
118
|
-
async function handleExec(args) {
|
|
124
|
+
async function handleExec(args, extra) {
|
|
119
125
|
try {
|
|
120
126
|
const result = await sessionManager.exec(args.alias, args.command, {
|
|
127
|
+
stdin: args.stdin,
|
|
128
|
+
signal: extra?.signal,
|
|
121
129
|
timeout: args.timeout,
|
|
122
130
|
cwd: args.cwd,
|
|
123
131
|
env: args.env,
|
|
@@ -136,12 +144,13 @@ async function handleExec(args) {
|
|
|
136
144
|
return formatError(error);
|
|
137
145
|
}
|
|
138
146
|
}
|
|
139
|
-
async function handleExecAsUser(args) {
|
|
147
|
+
async function handleExecAsUser(args, extra) {
|
|
140
148
|
try {
|
|
141
149
|
sessionManager.requirePosixPrivilege(args.alias);
|
|
142
150
|
if (args.targetUser) {
|
|
143
151
|
const result = await sessionManager.execAsUser(args.alias, args.command, args.targetUser, {
|
|
144
152
|
timeout: args.timeout,
|
|
153
|
+
signal: extra?.signal,
|
|
145
154
|
cwd: args.cwd,
|
|
146
155
|
env: args.env,
|
|
147
156
|
maxOutputSize: args.maxOutputSize,
|
|
@@ -154,6 +163,7 @@ async function handleExecAsUser(args) {
|
|
|
154
163
|
}
|
|
155
164
|
const result = await sessionManager.exec(args.alias, args.command, {
|
|
156
165
|
timeout: args.timeout,
|
|
166
|
+
signal: extra?.signal,
|
|
157
167
|
cwd: args.cwd,
|
|
158
168
|
env: args.env,
|
|
159
169
|
maxOutputSize: args.maxOutputSize,
|
|
@@ -168,10 +178,11 @@ async function handleExecAsUser(args) {
|
|
|
168
178
|
return formatError(error);
|
|
169
179
|
}
|
|
170
180
|
}
|
|
171
|
-
async function handleExecSudo(args) {
|
|
181
|
+
async function handleExecSudo(args, extra) {
|
|
172
182
|
try {
|
|
173
183
|
const result = await sessionManager.execSudo(args.alias, args.command, args.sudoPassword, {
|
|
174
184
|
timeout: args.timeout,
|
|
185
|
+
signal: extra?.signal,
|
|
175
186
|
maxOutputSize: args.maxOutputSize,
|
|
176
187
|
runAs: args.runAs,
|
|
177
188
|
useLoginUser: args.useLoginUser,
|
|
@@ -216,15 +227,17 @@ function executionFailure(error) {
|
|
|
216
227
|
error: error instanceof Error ? error.message : String(error),
|
|
217
228
|
};
|
|
218
229
|
}
|
|
219
|
-
async function handleExecBatch(args) {
|
|
230
|
+
async function handleExecBatch(args, extra) {
|
|
220
231
|
try {
|
|
221
232
|
const stopOnError = args.stopOnError !== false;
|
|
222
233
|
const results = [];
|
|
223
234
|
const budget = { remaining: REQUEST_OUTPUT_LIMIT, truncated: false };
|
|
224
235
|
for (let i = 0; i < args.commands.length; i++) {
|
|
236
|
+
extra?.signal.throwIfAborted();
|
|
225
237
|
try {
|
|
226
238
|
const execResult = await sessionManager.exec(args.alias, args.commands[i], {
|
|
227
239
|
timeout: args.timeout,
|
|
240
|
+
signal: extra?.signal,
|
|
228
241
|
maxOutputSize: Math.max(1, Math.min(DEFAULT_EXEC_MAX_OUTPUT_SIZE, budget.remaining)),
|
|
229
242
|
});
|
|
230
243
|
results.push({
|
|
@@ -247,7 +260,7 @@ async function handleExecBatch(args) {
|
|
|
247
260
|
: undefined,
|
|
248
261
|
...boundExecOutput(failure, budget),
|
|
249
262
|
});
|
|
250
|
-
if (stopOnError) {
|
|
263
|
+
if (stopOnError || extra?.signal.aborted) {
|
|
251
264
|
break;
|
|
252
265
|
}
|
|
253
266
|
}
|
|
@@ -266,9 +279,10 @@ async function handleExecBatch(args) {
|
|
|
266
279
|
return formatError(error);
|
|
267
280
|
}
|
|
268
281
|
}
|
|
269
|
-
async function handleQuickExec(args) {
|
|
282
|
+
async function handleQuickExec(args, extra) {
|
|
270
283
|
const tempAlias = `_quick_${randomUUID()}`;
|
|
271
284
|
try {
|
|
285
|
+
extra?.signal.throwIfAborted();
|
|
272
286
|
await sessionManager.connect({
|
|
273
287
|
host: args.host,
|
|
274
288
|
port: args.port ?? 22,
|
|
@@ -280,8 +294,12 @@ async function handleQuickExec(args) {
|
|
|
280
294
|
commandShell: args.commandShell,
|
|
281
295
|
alias: tempAlias,
|
|
282
296
|
readyTimeout: args.readyTimeout,
|
|
297
|
+
}, undefined, extra?.signal);
|
|
298
|
+
extra?.signal.throwIfAborted();
|
|
299
|
+
const result = await sessionManager.exec(tempAlias, args.command, {
|
|
300
|
+
timeout: args.timeout,
|
|
301
|
+
signal: extra?.signal,
|
|
283
302
|
});
|
|
284
|
-
const result = await sessionManager.exec(tempAlias, args.command, { timeout: args.timeout });
|
|
285
303
|
return formatResult(result);
|
|
286
304
|
}
|
|
287
305
|
catch (error) {
|
|
@@ -291,11 +309,12 @@ async function handleQuickExec(args) {
|
|
|
291
309
|
sessionManager.disconnect(tempAlias);
|
|
292
310
|
}
|
|
293
311
|
}
|
|
294
|
-
async function mapWithConcurrency(items, limit, worker) {
|
|
312
|
+
async function mapWithConcurrency(items, limit, worker, signal) {
|
|
295
313
|
const results = new Array(items.length);
|
|
296
314
|
let nextIndex = 0;
|
|
297
315
|
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
298
316
|
while (nextIndex < items.length) {
|
|
317
|
+
signal?.throwIfAborted();
|
|
299
318
|
const index = nextIndex++;
|
|
300
319
|
results[index] = await worker(items[index], index);
|
|
301
320
|
}
|
|
@@ -303,7 +322,7 @@ async function mapWithConcurrency(items, limit, worker) {
|
|
|
303
322
|
await Promise.all(runners);
|
|
304
323
|
return results;
|
|
305
324
|
}
|
|
306
|
-
async function handleExecParallel(args) {
|
|
325
|
+
async function handleExecParallel(args, extra) {
|
|
307
326
|
try {
|
|
308
327
|
const concurrency = Math.min(args.maxConcurrency ?? EXEC_PARALLEL_DEFAULT_CONCURRENCY, args.aliases.length);
|
|
309
328
|
const budget = { remaining: REQUEST_OUTPUT_LIMIT, truncated: false };
|
|
@@ -311,6 +330,7 @@ async function handleExecParallel(args) {
|
|
|
311
330
|
try {
|
|
312
331
|
const execResult = await sessionManager.exec(alias, args.command, {
|
|
313
332
|
timeout: args.timeout,
|
|
333
|
+
signal: extra?.signal,
|
|
314
334
|
maxOutputSize: Math.max(1, Math.min(args.maxOutputSize ?? DEFAULT_EXEC_MAX_OUTPUT_SIZE, budget.remaining)),
|
|
315
335
|
});
|
|
316
336
|
return { alias, ...boundExecOutput(execResult, budget) };
|
|
@@ -318,7 +338,7 @@ async function handleExecParallel(args) {
|
|
|
318
338
|
catch (err) {
|
|
319
339
|
return { alias, ...boundExecOutput(executionFailure(err), budget) };
|
|
320
340
|
}
|
|
321
|
-
});
|
|
341
|
+
}, extra?.signal);
|
|
322
342
|
return formatResult({
|
|
323
343
|
success: results.every((r) => r.success),
|
|
324
344
|
total: args.aliases.length,
|
|
@@ -335,7 +355,7 @@ async function handleExecParallel(args) {
|
|
|
335
355
|
}
|
|
336
356
|
async function cleanupRemoteScript(alias, remotePath, timeout) {
|
|
337
357
|
try {
|
|
338
|
-
await fileOps.removeRemoteFile(alias, remotePath, timeout);
|
|
358
|
+
await fileOps.removeRemoteFile(alias, remotePath, Math.min(timeout ?? DEFAULT_EXEC_TIMEOUT_MS, DEFAULT_EXEC_TIMEOUT_MS));
|
|
339
359
|
return undefined;
|
|
340
360
|
}
|
|
341
361
|
catch (error) {
|
|
@@ -355,17 +375,18 @@ function resolveScriptUsers(args) {
|
|
|
355
375
|
};
|
|
356
376
|
}
|
|
357
377
|
export function windowsScriptContent(script, interpreter) {
|
|
358
|
-
const bom = String.fromCharCode(
|
|
378
|
+
const bom = String.fromCharCode(65279);
|
|
359
379
|
if (interpreter.toLowerCase().startsWith('cmd')) {
|
|
360
380
|
return `@chcp 65001>nul || exit /b 1\r\n${script.startsWith(bom) ? script.slice(1) : script}`;
|
|
361
381
|
}
|
|
362
382
|
return script.startsWith(bom) ? script : bom + script;
|
|
363
383
|
}
|
|
364
|
-
async function prepareRemoteScript(alias, remotePath, effectiveUser, loginUser, timeout) {
|
|
384
|
+
async function prepareRemoteScript(alias, remotePath, effectiveUser, loginUser, timeout, signal) {
|
|
365
385
|
const quotedPath = escapeShellArg(remotePath);
|
|
366
386
|
const ownershipCommand = effectiveUser && effectiveUser !== loginUser ? `chown ${escapeShellArg(effectiveUser)} ${quotedPath} && ` : '';
|
|
367
387
|
const result = await sessionManager.exec(alias, `${ownershipCommand}chmod 700 ${quotedPath}`, {
|
|
368
388
|
timeout,
|
|
389
|
+
signal,
|
|
369
390
|
useLoginUser: true,
|
|
370
391
|
maxOutputSize: 4096,
|
|
371
392
|
});
|
|
@@ -374,19 +395,20 @@ async function prepareRemoteScript(alias, remotePath, effectiveUser, loginUser,
|
|
|
374
395
|
throw new Error(`prepare remote script failed: ${reason}`);
|
|
375
396
|
}
|
|
376
397
|
}
|
|
377
|
-
async function handleExecScript(args) {
|
|
398
|
+
async function handleExecScript(args, extra) {
|
|
378
399
|
let remotePath;
|
|
379
400
|
let remoteSftpPath;
|
|
380
401
|
let ownsRemotePath = false;
|
|
381
402
|
let executionStarted = false;
|
|
382
403
|
try {
|
|
404
|
+
extra?.signal.throwIfAborted();
|
|
383
405
|
if (sessionManager.getOpenSshConnection(args.alias)) {
|
|
384
|
-
|
|
406
|
+
return formatError(new OpenSshError('The OpenSSH backend does not support temporary script uploads; use ssh_exec for inline commands', {
|
|
385
407
|
code: 'unsupported_backend',
|
|
386
408
|
backend: 'openssh',
|
|
387
409
|
capability: 'script_upload',
|
|
388
410
|
retryable: false,
|
|
389
|
-
});
|
|
411
|
+
}));
|
|
390
412
|
}
|
|
391
413
|
const windows = sessionManager.getRemotePlatform(args.alias) === 'windows';
|
|
392
414
|
const interpreter = args.interpreter ?? (windows ? sessionManager.getCommandShell(args.alias) : 'bash');
|
|
@@ -397,34 +419,37 @@ async function handleExecScript(args) {
|
|
|
397
419
|
}
|
|
398
420
|
validateScriptUser(effectiveUser);
|
|
399
421
|
if (windows && !['powershell', 'powershell.exe', 'cmd', 'cmd.exe'].includes(interpreter.toLowerCase())) {
|
|
400
|
-
|
|
422
|
+
return formatError(new Error('Windows script interpreter must be cmd or powershell'));
|
|
401
423
|
}
|
|
402
424
|
if (windows) {
|
|
403
425
|
const suffix = interpreter.toLowerCase().startsWith('cmd') ? '.cmd' : '.ps1';
|
|
404
426
|
const name = `mcp-ssh-script-${randomUUID()}${suffix}`;
|
|
405
427
|
const tempResult = await sessionManager.exec(args.alias, encodedPowershell(windowsTemporaryPathScript(name)), {
|
|
406
428
|
timeout: args.timeout,
|
|
429
|
+
signal: extra?.signal,
|
|
407
430
|
useLoginUser: true,
|
|
408
431
|
maxOutputSize: 4096,
|
|
409
432
|
});
|
|
410
433
|
if (!tempResult.success) {
|
|
411
|
-
|
|
434
|
+
return formatError(new Error(tempResult.stderr.includes('privacy_not_enforced_on_windows')
|
|
412
435
|
? 'privacy_not_enforced_on_windows: remote temporary directory ACL was not verified'
|
|
413
|
-
:
|
|
436
|
+
: 'Remote Windows temporary directory lookup failed: ' +
|
|
437
|
+
(tempResult.stderr || tempResult.stdout)));
|
|
414
438
|
}
|
|
415
439
|
remotePath = tempResult.stdout.trim();
|
|
416
440
|
if (!remotePath ||
|
|
417
441
|
/[\r\n\0]/.test(remotePath) ||
|
|
418
442
|
!(remotePath.endsWith(`\\${name}`) || remotePath.endsWith(`/${name}`))) {
|
|
419
|
-
|
|
443
|
+
return formatError(new Error('Remote Windows temporary directory lookup failed'));
|
|
420
444
|
}
|
|
421
445
|
remoteSftpPath = sftpPath(remotePath, sessionManager.getRemotePathStyle(args.alias));
|
|
422
|
-
await fileOps.prepareWindowsRemotePrivateFile(args.alias, remoteSftpPath, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, remotePath);
|
|
446
|
+
await fileOps.prepareWindowsRemotePrivateFile(args.alias, remoteSftpPath, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, remotePath, extra?.signal);
|
|
423
447
|
ownsRemotePath = true;
|
|
424
448
|
}
|
|
425
449
|
else {
|
|
426
450
|
const tempResult = await sessionManager.exec(args.alias, 'mktemp /tmp/mcp-ssh-script.XXXXXX', {
|
|
427
451
|
timeout: args.timeout,
|
|
452
|
+
signal: extra?.signal,
|
|
428
453
|
useLoginUser: true,
|
|
429
454
|
maxOutputSize: 4096,
|
|
430
455
|
});
|
|
@@ -436,11 +461,12 @@ async function handleExecScript(args) {
|
|
|
436
461
|
remoteSftpPath = remotePath;
|
|
437
462
|
}
|
|
438
463
|
if (!remoteSftpPath) {
|
|
439
|
-
|
|
464
|
+
return formatError(new Error('Remote temporary script path was not created'));
|
|
440
465
|
}
|
|
441
|
-
await fileOps.writeFile(args.alias, remoteSftpPath, windows ? windowsScriptContent(args.script, interpreter) : args.script, false, args.timeout);
|
|
466
|
+
await fileOps.writeFile(args.alias, remoteSftpPath, windows ? windowsScriptContent(args.script, interpreter) : args.script, false, args.timeout, extra?.signal);
|
|
467
|
+
extra?.signal.throwIfAborted();
|
|
442
468
|
if (!windows) {
|
|
443
|
-
await prepareRemoteScript(args.alias, remotePath, effectiveUser, loginUser, args.timeout);
|
|
469
|
+
await prepareRemoteScript(args.alias, remotePath, effectiveUser, loginUser, args.timeout, extra?.signal);
|
|
444
470
|
}
|
|
445
471
|
const command = windows
|
|
446
472
|
? interpreterArgs.length > 0
|
|
@@ -455,11 +481,14 @@ async function handleExecScript(args) {
|
|
|
455
481
|
: [interpreter, ...interpreterArgs, remotePath].map(escapeShellArg).join(' ');
|
|
456
482
|
const execOptions = {
|
|
457
483
|
timeout: args.timeout,
|
|
484
|
+
signal: extra?.signal,
|
|
458
485
|
cwd: args.cwd,
|
|
459
486
|
env: args.env,
|
|
460
487
|
maxOutputSize: args.maxOutputSize,
|
|
461
488
|
runAs: args.targetUser ?? args.runAs,
|
|
462
489
|
};
|
|
490
|
+
extra?.signal.throwIfAborted();
|
|
491
|
+
// noinspection JSUnusedAssignment -- read by the failure cleanup path
|
|
463
492
|
executionStarted = true;
|
|
464
493
|
const result = args.targetUser
|
|
465
494
|
? await sessionManager.execAsUser(args.alias, command, args.targetUser, execOptions)
|
|
@@ -488,7 +517,7 @@ export function registerExecTools(server) {
|
|
|
488
517
|
|
|
489
518
|
返回: stdout, stderr, exitCode, duration`,
|
|
490
519
|
inputSchema: execSchema,
|
|
491
|
-
}, (args) => handleExec(args));
|
|
520
|
+
}, (args, extra) => handleExec(args, extra));
|
|
492
521
|
server.registerTool('ssh_exec_as_user', {
|
|
493
522
|
description: `以其他用户身份执行命令(通过 su 切换)
|
|
494
523
|
|
|
@@ -499,21 +528,21 @@ export function registerExecTools(server) {
|
|
|
499
528
|
|
|
500
529
|
示例: ssh_exec_as_user(alias="server", command="whoami", targetUser="appuser")`,
|
|
501
530
|
inputSchema: execAsUserSchema,
|
|
502
|
-
}, (args) => handleExecAsUser(args));
|
|
531
|
+
}, (args, extra) => handleExecAsUser(args, extra));
|
|
503
532
|
server.registerTool('ssh_exec_sudo', {
|
|
504
533
|
description: '使用 sudo 执行命令。runAs、useLoginUser 与 loadProfile 的身份优先级与 ssh_exec 相同。',
|
|
505
534
|
inputSchema: execSudoSchema,
|
|
506
|
-
}, (args) => handleExecSudo(args));
|
|
535
|
+
}, (args, extra) => handleExecSudo(args, extra));
|
|
507
536
|
server.registerTool('ssh_exec_batch', {
|
|
508
537
|
description: `批量执行多条命令,每条命令在独立 SSH channel 中执行,环境变量不共享
|
|
509
538
|
|
|
510
539
|
如需命令间共享环境(如 export 变量),用分号拼接为单条命令通过 ssh_exec 执行`,
|
|
511
540
|
inputSchema: execBatchSchema,
|
|
512
|
-
}, (args) => handleExecBatch(args));
|
|
541
|
+
}, (args, extra) => handleExecBatch(args, extra));
|
|
513
542
|
server.registerTool('ssh_quick_exec', {
|
|
514
543
|
description: '一次性执行命令(自动连接、执行、断开)。readyTimeout 只限制建立 SSH 连接,timeout 只限制命令执行,适用于单次命令。',
|
|
515
544
|
inputSchema: quickExecSchema,
|
|
516
|
-
}, (args) => handleQuickExec(args));
|
|
545
|
+
}, (args, extra) => handleQuickExec(args, extra));
|
|
517
546
|
server.registerTool('ssh_exec_parallel', {
|
|
518
547
|
description: `在多个已连接的会话上并行执行同一命令
|
|
519
548
|
|
|
@@ -522,9 +551,11 @@ export function registerExecTools(server) {
|
|
|
522
551
|
|
|
523
552
|
返回每个主机的执行结果`,
|
|
524
553
|
inputSchema: execParallelSchema,
|
|
525
|
-
}, (args) => handleExecParallel(args));
|
|
554
|
+
}, (args, extra) => handleExecParallel(args, extra));
|
|
526
555
|
server.registerTool('ssh_exec_script', {
|
|
527
|
-
description: '上传远端临时脚本并执行,默认执行后清理脚本;timeout
|
|
556
|
+
description: '上传远端临时脚本并执行,默认执行后清理脚本;timeout 分别限制上传、准备和执行阶段,最大 3600000 ms;' +
|
|
557
|
+
'清理独立计时,使用请求值与 30000 ms 中的较小值,省略时为 30000 ms;' +
|
|
558
|
+
'宿主中止后远端进程停止状态未知,长任务用 ssh_operation_start/status/read/cancel',
|
|
528
559
|
inputSchema: execScriptSchema,
|
|
529
|
-
}, (args) => handleExecScript(args));
|
|
560
|
+
}, (args, extra) => handleExecScript(args, extra));
|
|
530
561
|
}
|
package/dist/tools/file.js
CHANGED
|
@@ -13,7 +13,7 @@ import { FILE_CREATE_MODE_MASK, formatFileMode, parseExpectedFileMode } from '..
|
|
|
13
13
|
import * as fileOps from '../file-ops.js';
|
|
14
14
|
import { encodedPowershell, quotePowershell, remoteDirname, remoteJoin, remotePathModule, remoteShellPath, sftpPath, } from '../remote-platform.js';
|
|
15
15
|
import { sessionManager } from '../session-manager.js';
|
|
16
|
-
import {
|
|
16
|
+
import { normalizeSftpOperationTimeout, sftpOperationOutcome, SftpOperationTimeoutError, 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';
|
|
@@ -77,7 +77,7 @@ function compareDirectoryTimes(left, right) {
|
|
|
77
77
|
return milliseconds;
|
|
78
78
|
}
|
|
79
79
|
// 保留 ISO 8601 的亚毫秒部分,避免 Date.parse 截断时间边界
|
|
80
|
-
const [leftFraction, rightFraction] = [left, right].map((value) => (value.match(/\.(?<fraction>\d+)/)?.
|
|
80
|
+
const [leftFraction, rightFraction] = [left, right].map((value) => (value.match(/\.(?<fraction>\d+)/)?.groups?.fraction.slice(3) ?? '').replace(/0+$/, ''));
|
|
81
81
|
return leftFraction < rightFraction ? -1 : leftFraction > rightFraction ? 1 : 0;
|
|
82
82
|
}
|
|
83
83
|
const listDirSchema = z
|
|
@@ -133,7 +133,19 @@ const syncSchema = z.object({
|
|
|
133
133
|
.describe('upload 时是否跟随本地 symlink,默认 false(跳过 symlink 并 warn,避免上传链接目标内容)'),
|
|
134
134
|
preflightTimeout: z.number().int().positive().max(60000).optional().describe('传输能力预检超时,默认 10000ms'),
|
|
135
135
|
connectTimeout: z.number().int().positive().max(120000).optional().describe('rsync SSH 连接超时,默认 30000ms'),
|
|
136
|
-
operationTimeout: z
|
|
136
|
+
operationTimeout: z
|
|
137
|
+
.number()
|
|
138
|
+
.int()
|
|
139
|
+
.positive()
|
|
140
|
+
.max(3600000)
|
|
141
|
+
.optional()
|
|
142
|
+
.describe('同步总期限(含预检、传输、校验),默认 600000 ms;宿主请求期限独立生效'),
|
|
143
|
+
bandwidthLimitKiBps: z
|
|
144
|
+
.number()
|
|
145
|
+
.int()
|
|
146
|
+
.positive()
|
|
147
|
+
.optional()
|
|
148
|
+
.describe('本次同步的总传输速率上限,单位 KiB/s(1 KiB = 1024 bytes),适用于 rsync/SFTP,默认不限速'),
|
|
137
149
|
verifyOwner: z
|
|
138
150
|
.union([z.string(), z.number()])
|
|
139
151
|
.optional()
|
|
@@ -861,6 +873,7 @@ async function handleUpload(args) {
|
|
|
861
873
|
privateTempCreated = true;
|
|
862
874
|
}
|
|
863
875
|
const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath, undefined, undefined, createMode, undefined, false, args.atomic === true && !privateTempCreated, args.timeout);
|
|
876
|
+
// noinspection JSUnusedAssignment -- read by the failure cleanup path
|
|
864
877
|
uploadedTempCreated = args.atomic === true;
|
|
865
878
|
let verification;
|
|
866
879
|
let verificationError;
|
|
@@ -1009,10 +1022,17 @@ async function handleUpload(args) {
|
|
|
1009
1022
|
});
|
|
1010
1023
|
}
|
|
1011
1024
|
}
|
|
1012
|
-
async function handleDownload(args) {
|
|
1025
|
+
async function handleDownload(args, extra) {
|
|
1026
|
+
const deadline = Date.now() + normalizeSftpOperationTimeout(args.timeout);
|
|
1013
1027
|
try {
|
|
1028
|
+
extra?.signal.throwIfAborted();
|
|
1014
1029
|
args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
|
|
1015
|
-
const
|
|
1030
|
+
const remaining = deadline - Date.now();
|
|
1031
|
+
if (remaining <= 0) {
|
|
1032
|
+
// noinspection ExceptionCaughtLocallyJS — 超时经统一错误响应返回并共享剩余诊断期限
|
|
1033
|
+
throw new SftpOperationTimeoutError(args.timeout ?? 600_000);
|
|
1034
|
+
}
|
|
1035
|
+
const downloadResult = await fileOps.downloadFile(args.alias, args.remotePath, args.localPath, undefined, undefined, extra?.signal, remaining);
|
|
1016
1036
|
return formatResult({ ...downloadResult, message: `Downloaded to ${args.localPath}` });
|
|
1017
1037
|
}
|
|
1018
1038
|
catch (error) {
|
|
@@ -1023,7 +1043,9 @@ async function handleDownload(args) {
|
|
|
1023
1043
|
diagnostics: {
|
|
1024
1044
|
local: summarizeLocalPathProbe(fileOps.probeLocalPath(args.localPath)),
|
|
1025
1045
|
localParent: summarizeLocalPathProbe(fileOps.probeLocalPath(path.dirname(args.localPath))),
|
|
1026
|
-
remoteParent:
|
|
1046
|
+
remoteParent: !extra?.signal.aborted && Date.now() < deadline
|
|
1047
|
+
? await probeRemoteParent(args.alias, args.remotePath, deadline - Date.now(), extra?.signal)
|
|
1048
|
+
: undefined,
|
|
1027
1049
|
},
|
|
1028
1050
|
});
|
|
1029
1051
|
}
|
|
@@ -1046,10 +1068,10 @@ async function handleReadFile(args) {
|
|
|
1046
1068
|
return formatFileOperationError(error);
|
|
1047
1069
|
}
|
|
1048
1070
|
}
|
|
1049
|
-
async function handleWriteFile(args) {
|
|
1071
|
+
async function handleWriteFile(args, extra) {
|
|
1050
1072
|
try {
|
|
1051
1073
|
args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
|
|
1052
|
-
const result = await fileOps.writeFile(args.alias, args.remotePath, args.content, args.append, args.timeout);
|
|
1074
|
+
const result = await fileOps.writeFile(args.alias, args.remotePath, args.content, args.append, args.timeout, extra?.signal);
|
|
1053
1075
|
return formatResult(result);
|
|
1054
1076
|
}
|
|
1055
1077
|
catch (error) {
|
|
@@ -1140,7 +1162,33 @@ async function handleMkdir(args) {
|
|
|
1140
1162
|
try {
|
|
1141
1163
|
args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
|
|
1142
1164
|
const success = await fileOps.mkdir(args.alias, args.remotePath, args.recursive, undefined, args.timeout, sessionManager.getRemotePathStyle(args.alias));
|
|
1143
|
-
|
|
1165
|
+
const session = sessionManager.listSessionDetails().find((item) => item.alias === args.alias);
|
|
1166
|
+
const result = {
|
|
1167
|
+
success,
|
|
1168
|
+
path: args.remotePath,
|
|
1169
|
+
loginUser: session?.username,
|
|
1170
|
+
runAs: session?.runAs,
|
|
1171
|
+
creationIdentity: 'sftp_login',
|
|
1172
|
+
};
|
|
1173
|
+
try {
|
|
1174
|
+
const info = await fileOps.getFileInfo(args.alias, args.remotePath, args.timeout);
|
|
1175
|
+
return formatResult({
|
|
1176
|
+
...result,
|
|
1177
|
+
owner: info.owner,
|
|
1178
|
+
group: info.group,
|
|
1179
|
+
mode: info.mode,
|
|
1180
|
+
permissions: info.permissions,
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
catch (error) {
|
|
1184
|
+
return formatResult({
|
|
1185
|
+
...result,
|
|
1186
|
+
operationStatus: 'completed',
|
|
1187
|
+
retryable: false,
|
|
1188
|
+
metadataStatus: 'unavailable',
|
|
1189
|
+
metadataError: JSON.parse(formatFileOperationError(error).content[0].text),
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1144
1192
|
}
|
|
1145
1193
|
catch (error) {
|
|
1146
1194
|
return formatFileOperationError(error);
|
|
@@ -1176,7 +1224,8 @@ async function handleSync(args, extra) {
|
|
|
1176
1224
|
success: false,
|
|
1177
1225
|
transferSuccess: false,
|
|
1178
1226
|
code: 'UNSUPPORTED_SYNC_VERIFICATION',
|
|
1179
|
-
error: 'verifyOwner/verifyMode require a non-dryRun single-file upload;
|
|
1227
|
+
error: 'verifyOwner/verifyMode require a non-dryRun single-file upload; ' +
|
|
1228
|
+
'use verify.owner/verify.mode for directory or download verification',
|
|
1180
1229
|
});
|
|
1181
1230
|
}
|
|
1182
1231
|
if (args.verify?.deletions && args.delete !== true) {
|
|
@@ -1213,7 +1262,8 @@ async function handleSync(args, extra) {
|
|
|
1213
1262
|
success: false,
|
|
1214
1263
|
transferSuccess: false,
|
|
1215
1264
|
code: 'UNSUPPORTED_SYNC_VERIFICATION',
|
|
1216
|
-
error: 'verifyOwner/verifyMode require a single-file upload;
|
|
1265
|
+
error: 'verifyOwner/verifyMode require a single-file upload; ' +
|
|
1266
|
+
'use verify.owner/verify.mode for directory verification',
|
|
1217
1267
|
diagnostics,
|
|
1218
1268
|
});
|
|
1219
1269
|
}
|
|
@@ -1247,12 +1297,16 @@ async function handleSync(args, extra) {
|
|
|
1247
1297
|
params: {
|
|
1248
1298
|
progressToken,
|
|
1249
1299
|
progress: current,
|
|
1250
|
-
message: `${args.direction === 'upload' ? '上传' : '下载'}
|
|
1300
|
+
message: `${args.direction === 'upload' ? '上传' : '下载'}:` +
|
|
1301
|
+
`${update.transferred} bytes,` +
|
|
1302
|
+
`${update.percent}%` +
|
|
1251
1303
|
(update.total > 0 ? `,当前文件共 ${update.total} bytes` : ''),
|
|
1252
1304
|
},
|
|
1253
1305
|
}))
|
|
1254
1306
|
.catch((error) => {
|
|
1255
|
-
progressWarning =
|
|
1307
|
+
progressWarning =
|
|
1308
|
+
'MCP progress notification failed: ' +
|
|
1309
|
+
(error instanceof Error ? error.message : String(error));
|
|
1256
1310
|
console.warn(`[ssh_sync] ${progressWarning}`);
|
|
1257
1311
|
})
|
|
1258
1312
|
.finally(() => {
|
|
@@ -1264,10 +1318,12 @@ async function handleSync(args, extra) {
|
|
|
1264
1318
|
control.signal?.throwIfAborted();
|
|
1265
1319
|
const probeTimeout = remainingTimeout();
|
|
1266
1320
|
if (probeTimeout <= 0) {
|
|
1321
|
+
// noinspection ExceptionCaughtLocallyJS — 超时仍保留传输诊断
|
|
1267
1322
|
throw new Error('sync operation timeout was exhausted before remote probing');
|
|
1268
1323
|
}
|
|
1269
1324
|
diagnostics.remoteParent = await probeRemoteParent(args.alias, args.remotePath, probeTimeout, control.signal);
|
|
1270
1325
|
if (remainingTimeout() <= 0) {
|
|
1326
|
+
// noinspection ExceptionCaughtLocallyJS — 超时仍保留传输诊断
|
|
1271
1327
|
throw new Error('sync operation timeout was exhausted before transfer started');
|
|
1272
1328
|
}
|
|
1273
1329
|
const remoteSource = args.direction === 'download'
|
|
@@ -1284,8 +1340,8 @@ async function handleSync(args, extra) {
|
|
|
1284
1340
|
transferSuccess: false,
|
|
1285
1341
|
operationStatus: 'failed',
|
|
1286
1342
|
failureStage: 'remote_prepare',
|
|
1287
|
-
code: remoteParent.exists
|
|
1288
|
-
error: remoteParent.exists
|
|
1343
|
+
code: !remoteParent.exists ? 'REMOTE_PARENT_NOT_FOUND' : 'REMOTE_PARENT_NOT_DIRECTORY',
|
|
1344
|
+
error: !remoteParent.exists
|
|
1289
1345
|
? '远端父目录不存在,请先用 ssh_mkdir 创建后重新上传'
|
|
1290
1346
|
: '远端父路径是文件,请改用目录作为父路径',
|
|
1291
1347
|
diagnostics,
|
|
@@ -1358,7 +1414,9 @@ async function handleSync(args, extra) {
|
|
|
1358
1414
|
exclude: args.exclude,
|
|
1359
1415
|
recursive: args.recursive,
|
|
1360
1416
|
followSymlinks: args.followSymlinks,
|
|
1361
|
-
|
|
1417
|
+
// 工具层负责带预算和文件稳定性检查的摘要,传输层只返回元数据
|
|
1418
|
+
verifySha256: false,
|
|
1419
|
+
bandwidthLimitKiBps: args.bandwidthLimitKiBps,
|
|
1362
1420
|
preflightTimeout: args.preflightTimeout,
|
|
1363
1421
|
connectTimeout: args.connectTimeout,
|
|
1364
1422
|
operationTimeout: transferTimeout,
|
|
@@ -1375,10 +1433,11 @@ async function handleSync(args, extra) {
|
|
|
1375
1433
|
const verificationRequested = Boolean(args.verifyOwner !== undefined || args.verifyMode !== undefined || args.verify !== undefined);
|
|
1376
1434
|
let verification;
|
|
1377
1435
|
let verificationError;
|
|
1436
|
+
let contentVerification;
|
|
1378
1437
|
if (verificationRequested && syncResult.success) {
|
|
1379
1438
|
try {
|
|
1380
1439
|
const ownerModeVerification = await buildSyncUploadVerification(args, args.direction === 'upload' ? localBefore : localAfter, control);
|
|
1381
|
-
|
|
1440
|
+
contentVerification = sourceIsDirectory
|
|
1382
1441
|
? await buildDirectorySyncVerification(args, args.direction === 'upload' ? localBefore : localAfter, control, deletionBaseline)
|
|
1383
1442
|
: await buildSingleFileSyncVerification(args, args.direction === 'upload' ? localBefore : transferredLocal, control);
|
|
1384
1443
|
remainingVerificationTimeout(control);
|
|
@@ -1390,6 +1449,19 @@ async function handleSync(args, extra) {
|
|
|
1390
1449
|
}
|
|
1391
1450
|
}
|
|
1392
1451
|
const outcome = buildTransferOutcome(syncResult.success, verificationRequested, verification, verificationError);
|
|
1452
|
+
if (syncResult.verification && args.verify?.sha256) {
|
|
1453
|
+
const local = contentVerification?.local;
|
|
1454
|
+
const remote = contentVerification?.remote;
|
|
1455
|
+
syncResult.verification = {
|
|
1456
|
+
...syncResult.verification,
|
|
1457
|
+
status: verificationError ? 'error' : contentVerification?.skipped ? 'skipped' : 'completed',
|
|
1458
|
+
hashAlgorithm: 'sha256',
|
|
1459
|
+
hashMatch: contentVerification?.checks?.sha256,
|
|
1460
|
+
local: { ...syncResult.verification.local, sha256: local?.sha256 },
|
|
1461
|
+
remote: { ...syncResult.verification.remote, sha256: remote?.sha256 },
|
|
1462
|
+
...(verificationError ? verificationErrorDetails(verificationError) : {}),
|
|
1463
|
+
};
|
|
1464
|
+
}
|
|
1393
1465
|
const verificationMessage = verificationError instanceof Error ? verificationError.message : String(verificationError);
|
|
1394
1466
|
return formatResult({
|
|
1395
1467
|
...syncResult,
|
|
@@ -1425,9 +1497,9 @@ export function registerFileTools(server) {
|
|
|
1425
1497
|
}, (args) => handleUpload(args));
|
|
1426
1498
|
server.registerTool('ssh_download', {
|
|
1427
1499
|
description: '从远程服务器原子下载文件。新文件使用 0600,替换普通文件时保留其 rwx 权限;symlink、目录和其他非普通目标会被拒绝。timeout ' +
|
|
1428
|
-
'
|
|
1500
|
+
'限制下载与失败诊断的总期限,取消或超期后停止远端探测。',
|
|
1429
1501
|
inputSchema: downloadSchema,
|
|
1430
|
-
}, (args) => handleDownload(args));
|
|
1502
|
+
}, (args, extra) => handleDownload(args, extra));
|
|
1431
1503
|
server.registerTool('ssh_read_file', {
|
|
1432
1504
|
description: '读取远程文件内容。文本读取只返回完整 UTF-8 字符;后续读取使用响应中的 next_offset。',
|
|
1433
1505
|
inputSchema: readFileSchema,
|
|
@@ -1435,7 +1507,7 @@ export function registerFileTools(server) {
|
|
|
1435
1507
|
server.registerTool('ssh_write_file', {
|
|
1436
1508
|
description: '写入内容到远程文件。timeout 限制单个 SFTP 操作,超时后远端写入状态可能未知。',
|
|
1437
1509
|
inputSchema: writeFileSchema,
|
|
1438
|
-
}, (args) => handleWriteFile(args));
|
|
1510
|
+
}, (args, extra) => handleWriteFile(args, extra));
|
|
1439
1511
|
server.registerTool('ssh_list_dir', {
|
|
1440
1512
|
description: '列出远程目录内容,返回数值 mode 和 permissions 文本;名称与修改时间条件取交集,使用筛选或分页参数时默认最多 100 ' +
|
|
1441
1513
|
'条、65536 UTF-8 字节,使用 next_offset 续查;完整 readdir 后分页,目录变化时不保证快照一致性',
|
|
@@ -1446,7 +1518,7 @@ export function registerFileTools(server) {
|
|
|
1446
1518
|
inputSchema: fileInfoSchema,
|
|
1447
1519
|
}, (args) => handleFileInfo(args));
|
|
1448
1520
|
server.registerTool('ssh_mkdir', {
|
|
1449
|
-
description: '
|
|
1521
|
+
description: '以 SFTP 登录身份创建远程目录,连接 runAs 仅影响命令执行;返回实际 owner、group 和 mode,不自动修改权限;创建已确认后元信息读取失败时保持 success=true,metadataStatus=unavailable,可用 ssh_file_info 重新读取元信息',
|
|
1450
1522
|
inputSchema: mkdirSchema,
|
|
1451
1523
|
}, (args) => handleMkdir(args));
|
|
1452
1524
|
server.registerTool('ssh_sync', {
|
package/dist/transfer-outcome.js
CHANGED
|
@@ -8,7 +8,7 @@ function collectChecks(value, prefix, failed, skipped) {
|
|
|
8
8
|
}
|
|
9
9
|
if (record.checks && typeof record.checks === 'object') {
|
|
10
10
|
for (const [name, matched] of Object.entries(record.checks)) {
|
|
11
|
-
if (matched !== true) {
|
|
11
|
+
if (matched !== true && matched !== null) {
|
|
12
12
|
failed.push(prefix ? `${prefix}.${name}` : name);
|
|
13
13
|
}
|
|
14
14
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* SSH MCP Pro - 类型定义
|
|
3
3
|
*/
|
|
4
|
-
import type { Readable } from 'stream';
|
|
4
|
+
import type { Readable, Writable } from 'stream';
|
|
5
5
|
export interface CommandChannel extends Readable {
|
|
6
6
|
readonly stderr: Readable;
|
|
7
7
|
readonly ready?: Promise<void>;
|
|
8
|
+
readonly stdin?: Writable;
|
|
8
9
|
close(): void;
|
|
9
10
|
}
|
|
10
11
|
export interface OpenSshMasterInfo {
|
|
@@ -116,6 +117,8 @@ export interface ConnectionFailureDetails {
|
|
|
116
117
|
};
|
|
117
118
|
}
|
|
118
119
|
export interface ExecOptions {
|
|
120
|
+
stdin?: string;
|
|
121
|
+
signal?: AbortSignal;
|
|
119
122
|
timeout?: number;
|
|
120
123
|
env?: Record<string, string>;
|
|
121
124
|
cwd?: string;
|
package/dist/windows-acl.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export type AclStatus = 'key_path_usable' | 'key_acl_insecure' | 'key_acl_unverified';
|
|
2
|
+
export declare function getWindowsPowerShellEnv(): NodeJS.ProcessEnv;
|
|
2
3
|
export declare function windowsAclScript(filePath: string, apply: boolean): string;
|
|
3
4
|
export declare function windowsTemporaryPathScript(name: string): string;
|
|
4
|
-
export declare function checkWindowsKnownHostsIntegrity(filePath: string): void;
|
|
5
|
-
export declare function checkWindowsAcl(filePath: string, apply?: boolean): AclStatus;
|
|
5
|
+
export declare function checkWindowsKnownHostsIntegrity(filePath: string, deadline?: number): void;
|
|
6
|
+
export declare function checkWindowsAcl(filePath: string, apply?: boolean, deadline?: number): AclStatus;
|