@pyrokine/mcp-ssh 3.1.0 → 3.3.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.
- package/README.md +395 -112
- package/README_zh.md +211 -45
- package/dist/command-risk.js +5 -2
- package/dist/directory-verification.d.ts +10 -5
- package/dist/directory-verification.js +161 -74
- package/dist/file-mode.js +25 -13
- package/dist/file-ops.d.ts +22 -11
- package/dist/file-ops.js +605 -230
- package/dist/forward-manager.js +6 -1
- package/dist/known-hosts.d.ts +22 -0
- package/dist/known-hosts.js +563 -0
- package/dist/openssh.d.ts +5 -5
- package/dist/openssh.js +138 -59
- package/dist/operation-manager.js +13 -4
- package/dist/pty-manager.d.ts +2 -1
- package/dist/pty-manager.js +81 -19
- package/dist/remote-platform.d.ts +1 -1
- package/dist/remote-platform.js +82 -50
- package/dist/security.d.ts +2 -0
- package/dist/security.js +39 -3
- package/dist/session-manager.d.ts +29 -3
- package/dist/session-manager.js +367 -67
- package/dist/sftp-timeout.d.ts +16 -1
- package/dist/sftp-timeout.js +114 -12
- package/dist/ssh-config.js +1 -1
- package/dist/tools/connection.js +31 -13
- package/dist/tools/exec.js +147 -71
- package/dist/tools/file.js +333 -146
- package/dist/tools/operation.js +7 -5
- package/dist/tools/pty.js +16 -13
- package/dist/tools/utils.d.ts +1 -1
- package/dist/tools/utils.js +2 -2
- package/dist/transfer-outcome.js +1 -1
- package/dist/types.d.ts +24 -4
- package/dist/types.js +1 -0
- package/dist/utf8.d.ts +1 -1
- package/dist/utf8.js +2 -2
- package/dist/windows-acl.d.ts +1 -0
- package/dist/windows-acl.js +167 -80
- package/package.json +6 -6
package/dist/tools/exec.js
CHANGED
|
@@ -8,12 +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 { sessionManager } from '../session-manager.js';
|
|
12
11
|
import { OpenSshError } from '../openssh.js';
|
|
13
12
|
import { encodedPowershell, quotePowershell, sftpPath } from '../remote-platform.js';
|
|
14
|
-
import {
|
|
13
|
+
import { sessionManager } from '../session-manager.js';
|
|
14
|
+
import { sftpOperationOutcome } from '../sftp-timeout.js';
|
|
15
|
+
import { DEFAULT_EXEC_MAX_OUTPUT_SIZE, DEFAULT_EXEC_TIMEOUT_MS, HARD_EXEC_MAX_OUTPUT_SIZE, } from '../types.js';
|
|
16
|
+
import { utf8SafeEnd } from '../utf8.js';
|
|
15
17
|
import { windowsTemporaryPathScript } from '../windows-acl.js';
|
|
16
|
-
import { sshPortSchema } from './schema.js';
|
|
18
|
+
import { operationTimeoutSchema, sshPortSchema } from './schema.js';
|
|
17
19
|
import { escapeShellArg, formatError, formatResult } from './utils.js'; // ========== Schemas ==========
|
|
18
20
|
// ========== Schemas ==========
|
|
19
21
|
const maxOutputSizeSchema = z
|
|
@@ -24,6 +26,10 @@ const maxOutputSizeSchema = z
|
|
|
24
26
|
.optional()
|
|
25
27
|
.describe('stdout/stderr 各自的 UTF-8 字节上限,超过后截断并返回提示');
|
|
26
28
|
const execSchema = z.object({
|
|
29
|
+
stdin: z
|
|
30
|
+
.string()
|
|
31
|
+
.optional()
|
|
32
|
+
.describe('以 UTF-8 写入命令标准输入并发送 EOF,省略时保持原输入行为;输入不加入命令、日志或错误'),
|
|
27
33
|
alias: z.string().describe('连接别名'),
|
|
28
34
|
command: z.string().describe('要执行的命令'),
|
|
29
35
|
timeout: z
|
|
@@ -99,19 +105,27 @@ const execParallelSchema = z.object({
|
|
|
99
105
|
const execScriptSchema = z.object({
|
|
100
106
|
alias: z.string().describe('连接别名'),
|
|
101
107
|
script: z.string().describe('脚本内容'),
|
|
102
|
-
interpreter: z.string().optional().describe('
|
|
108
|
+
interpreter: z.string().optional().describe('解释器可执行文件名或路径,POSIX 默认 bash,Windows 默认连接 shell'),
|
|
109
|
+
interpreterArgs: z
|
|
110
|
+
.array(z.string().refine((value) => !value.includes('\0'), '解释器参数不能包含 NUL'))
|
|
111
|
+
.optional()
|
|
112
|
+
.describe('解释器参数数组,默认空数组,例如 python3 配合 ["-I"];每项作为独立参数传递'),
|
|
103
113
|
targetUser: z.string().optional().describe('目标用户名,优先级高于 runAs'),
|
|
104
114
|
runAs: z.string().optional().describe('本次脚本使用的目标用户'),
|
|
105
115
|
cwd: z.string().optional().describe('工作目录(可选)'),
|
|
106
116
|
env: z.record(z.string(), z.string()).optional().describe('额外环境变量'),
|
|
107
|
-
timeout:
|
|
117
|
+
timeout: operationTimeoutSchema
|
|
118
|
+
.optional()
|
|
119
|
+
.describe('上传、准备、执行各阶段的独立超时,最大 3600000 ms;清理独立计时,使用该值与 30000 ms 中的较小值,省略时为 30000 ms;未传时命令默认 30000 ms、SFTP 默认 600000 ms;宿主请求期限单独生效,长任务用 ssh_operation_start'),
|
|
108
120
|
keepScript: z.boolean().optional().describe('是否保留远端临时脚本,默认 false'),
|
|
109
121
|
maxOutputSize: maxOutputSizeSchema,
|
|
110
122
|
});
|
|
111
123
|
// ========== Handlers ==========
|
|
112
|
-
async function handleExec(args) {
|
|
124
|
+
async function handleExec(args, extra) {
|
|
113
125
|
try {
|
|
114
126
|
const result = await sessionManager.exec(args.alias, args.command, {
|
|
127
|
+
stdin: args.stdin,
|
|
128
|
+
signal: extra?.signal,
|
|
115
129
|
timeout: args.timeout,
|
|
116
130
|
cwd: args.cwd,
|
|
117
131
|
env: args.env,
|
|
@@ -123,19 +137,20 @@ async function handleExec(args) {
|
|
|
123
137
|
});
|
|
124
138
|
return formatResult({
|
|
125
139
|
...result,
|
|
126
|
-
commandRisk: classifyCommandRisk(args.command, args.timeout,
|
|
140
|
+
commandRisk: classifyCommandRisk(args.command, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, result.shell),
|
|
127
141
|
});
|
|
128
142
|
}
|
|
129
143
|
catch (error) {
|
|
130
144
|
return formatError(error);
|
|
131
145
|
}
|
|
132
146
|
}
|
|
133
|
-
async function handleExecAsUser(args) {
|
|
147
|
+
async function handleExecAsUser(args, extra) {
|
|
134
148
|
try {
|
|
135
149
|
sessionManager.requirePosixPrivilege(args.alias);
|
|
136
150
|
if (args.targetUser) {
|
|
137
151
|
const result = await sessionManager.execAsUser(args.alias, args.command, args.targetUser, {
|
|
138
152
|
timeout: args.timeout,
|
|
153
|
+
signal: extra?.signal,
|
|
139
154
|
cwd: args.cwd,
|
|
140
155
|
env: args.env,
|
|
141
156
|
maxOutputSize: args.maxOutputSize,
|
|
@@ -143,11 +158,12 @@ async function handleExecAsUser(args) {
|
|
|
143
158
|
});
|
|
144
159
|
return formatResult({
|
|
145
160
|
...result,
|
|
146
|
-
commandRisk: classifyCommandRisk(args.command, args.timeout,
|
|
161
|
+
commandRisk: classifyCommandRisk(args.command, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, result.shell),
|
|
147
162
|
});
|
|
148
163
|
}
|
|
149
164
|
const result = await sessionManager.exec(args.alias, args.command, {
|
|
150
165
|
timeout: args.timeout,
|
|
166
|
+
signal: extra?.signal,
|
|
151
167
|
cwd: args.cwd,
|
|
152
168
|
env: args.env,
|
|
153
169
|
maxOutputSize: args.maxOutputSize,
|
|
@@ -155,17 +171,18 @@ async function handleExecAsUser(args) {
|
|
|
155
171
|
});
|
|
156
172
|
return formatResult({
|
|
157
173
|
...result,
|
|
158
|
-
commandRisk: classifyCommandRisk(args.command, args.timeout,
|
|
174
|
+
commandRisk: classifyCommandRisk(args.command, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, result.shell),
|
|
159
175
|
});
|
|
160
176
|
}
|
|
161
177
|
catch (error) {
|
|
162
178
|
return formatError(error);
|
|
163
179
|
}
|
|
164
180
|
}
|
|
165
|
-
async function handleExecSudo(args) {
|
|
181
|
+
async function handleExecSudo(args, extra) {
|
|
166
182
|
try {
|
|
167
183
|
const result = await sessionManager.execSudo(args.alias, args.command, args.sudoPassword, {
|
|
168
184
|
timeout: args.timeout,
|
|
185
|
+
signal: extra?.signal,
|
|
169
186
|
maxOutputSize: args.maxOutputSize,
|
|
170
187
|
runAs: args.runAs,
|
|
171
188
|
useLoginUser: args.useLoginUser,
|
|
@@ -177,33 +194,73 @@ async function handleExecSudo(args) {
|
|
|
177
194
|
return formatError(error);
|
|
178
195
|
}
|
|
179
196
|
}
|
|
180
|
-
|
|
197
|
+
const REQUEST_OUTPUT_LIMIT = 16 * 1024 * 1024;
|
|
198
|
+
function boundExecOutput(result, budget) {
|
|
199
|
+
const bounded = { ...result };
|
|
200
|
+
budget.truncated ||= result.stdoutTruncated === true || result.stderrTruncated === true;
|
|
201
|
+
for (const field of ['stdout', 'stderr', 'stdoutHead', 'stdoutTail', 'stderrHead', 'stderrTail']) {
|
|
202
|
+
const value = bounded[field];
|
|
203
|
+
if (value === undefined) {
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
const bytes = Buffer.from(value);
|
|
207
|
+
const end = utf8SafeEnd(bytes, 0, Math.min(bytes.length, budget.remaining), field, budget.remaining < bytes.length, true);
|
|
208
|
+
bounded[field] = bytes.subarray(0, end).toString('utf8');
|
|
209
|
+
budget.remaining -= end;
|
|
210
|
+
if (end < bytes.length) {
|
|
211
|
+
budget.truncated = true;
|
|
212
|
+
if (field.startsWith('stdout')) {
|
|
213
|
+
bounded.stdoutTruncated = true;
|
|
214
|
+
}
|
|
215
|
+
else {
|
|
216
|
+
bounded.stderrTruncated = true;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return bounded;
|
|
221
|
+
}
|
|
222
|
+
function executionFailure(error) {
|
|
223
|
+
const details = error && typeof error === 'object' && 'details' in error ? error.details : undefined;
|
|
224
|
+
return {
|
|
225
|
+
...(details && typeof details === 'object' ? details : {}),
|
|
226
|
+
success: false,
|
|
227
|
+
error: error instanceof Error ? error.message : String(error),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
async function handleExecBatch(args, extra) {
|
|
181
231
|
try {
|
|
182
232
|
const stopOnError = args.stopOnError !== false;
|
|
183
233
|
const results = [];
|
|
234
|
+
const budget = { remaining: REQUEST_OUTPUT_LIMIT, truncated: false };
|
|
184
235
|
for (let i = 0; i < args.commands.length; i++) {
|
|
185
|
-
|
|
236
|
+
extra?.signal.throwIfAborted();
|
|
186
237
|
try {
|
|
187
|
-
const execResult = await sessionManager.exec(args.alias, args.commands[i], {
|
|
238
|
+
const execResult = await sessionManager.exec(args.alias, args.commands[i], {
|
|
239
|
+
timeout: args.timeout,
|
|
240
|
+
signal: extra?.signal,
|
|
241
|
+
maxOutputSize: Math.max(1, Math.min(DEFAULT_EXEC_MAX_OUTPUT_SIZE, budget.remaining)),
|
|
242
|
+
});
|
|
188
243
|
results.push({
|
|
189
244
|
index: i,
|
|
190
245
|
commandRedacted: true,
|
|
191
|
-
commandRisk,
|
|
192
|
-
...execResult,
|
|
246
|
+
commandRisk: classifyCommandRisk(args.commands[i], args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, execResult.shell),
|
|
247
|
+
...boundExecOutput(execResult, budget),
|
|
193
248
|
});
|
|
194
|
-
if (execResult.
|
|
249
|
+
if (!execResult.success && stopOnError) {
|
|
195
250
|
break;
|
|
196
251
|
}
|
|
197
252
|
}
|
|
198
253
|
catch (err) {
|
|
254
|
+
const failure = executionFailure(err);
|
|
199
255
|
results.push({
|
|
200
256
|
index: i,
|
|
201
257
|
commandRedacted: true,
|
|
202
|
-
commandRisk
|
|
203
|
-
|
|
204
|
-
|
|
258
|
+
commandRisk: failure.shell
|
|
259
|
+
? classifyCommandRisk(args.commands[i], args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, failure.shell)
|
|
260
|
+
: undefined,
|
|
261
|
+
...boundExecOutput(failure, budget),
|
|
205
262
|
});
|
|
206
|
-
if (stopOnError) {
|
|
263
|
+
if (stopOnError || extra?.signal.aborted) {
|
|
207
264
|
break;
|
|
208
265
|
}
|
|
209
266
|
}
|
|
@@ -213,15 +270,19 @@ async function handleExecBatch(args) {
|
|
|
213
270
|
total: args.commands.length,
|
|
214
271
|
executed: results.length,
|
|
215
272
|
results,
|
|
273
|
+
maxOutputBytes: REQUEST_OUTPUT_LIMIT,
|
|
274
|
+
outputBytes: REQUEST_OUTPUT_LIMIT - budget.remaining,
|
|
275
|
+
outputTruncated: budget.truncated || undefined,
|
|
216
276
|
});
|
|
217
277
|
}
|
|
218
278
|
catch (error) {
|
|
219
279
|
return formatError(error);
|
|
220
280
|
}
|
|
221
281
|
}
|
|
222
|
-
async function handleQuickExec(args) {
|
|
282
|
+
async function handleQuickExec(args, extra) {
|
|
223
283
|
const tempAlias = `_quick_${randomUUID()}`;
|
|
224
284
|
try {
|
|
285
|
+
extra?.signal.throwIfAborted();
|
|
225
286
|
await sessionManager.connect({
|
|
226
287
|
host: args.host,
|
|
227
288
|
port: args.port ?? 22,
|
|
@@ -233,8 +294,12 @@ async function handleQuickExec(args) {
|
|
|
233
294
|
commandShell: args.commandShell,
|
|
234
295
|
alias: tempAlias,
|
|
235
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,
|
|
236
302
|
});
|
|
237
|
-
const result = await sessionManager.exec(tempAlias, args.command, { timeout: args.timeout });
|
|
238
303
|
return formatResult(result);
|
|
239
304
|
}
|
|
240
305
|
catch (error) {
|
|
@@ -244,11 +309,12 @@ async function handleQuickExec(args) {
|
|
|
244
309
|
sessionManager.disconnect(tempAlias);
|
|
245
310
|
}
|
|
246
311
|
}
|
|
247
|
-
async function mapWithConcurrency(items, limit, worker) {
|
|
312
|
+
async function mapWithConcurrency(items, limit, worker, signal) {
|
|
248
313
|
const results = new Array(items.length);
|
|
249
314
|
let nextIndex = 0;
|
|
250
315
|
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
251
316
|
while (nextIndex < items.length) {
|
|
317
|
+
signal?.throwIfAborted();
|
|
252
318
|
const index = nextIndex++;
|
|
253
319
|
results[index] = await worker(items[index], index);
|
|
254
320
|
}
|
|
@@ -256,33 +322,31 @@ async function mapWithConcurrency(items, limit, worker) {
|
|
|
256
322
|
await Promise.all(runners);
|
|
257
323
|
return results;
|
|
258
324
|
}
|
|
259
|
-
async function handleExecParallel(args) {
|
|
325
|
+
async function handleExecParallel(args, extra) {
|
|
260
326
|
try {
|
|
261
327
|
const concurrency = Math.min(args.maxConcurrency ?? EXEC_PARALLEL_DEFAULT_CONCURRENCY, args.aliases.length);
|
|
328
|
+
const budget = { remaining: REQUEST_OUTPUT_LIMIT, truncated: false };
|
|
262
329
|
const results = await mapWithConcurrency(args.aliases, concurrency, async (alias) => {
|
|
263
330
|
try {
|
|
264
331
|
const execResult = await sessionManager.exec(alias, args.command, {
|
|
265
332
|
timeout: args.timeout,
|
|
266
|
-
|
|
333
|
+
signal: extra?.signal,
|
|
334
|
+
maxOutputSize: Math.max(1, Math.min(args.maxOutputSize ?? DEFAULT_EXEC_MAX_OUTPUT_SIZE, budget.remaining)),
|
|
267
335
|
});
|
|
268
|
-
return {
|
|
269
|
-
alias,
|
|
270
|
-
...execResult,
|
|
271
|
-
};
|
|
336
|
+
return { alias, ...boundExecOutput(execResult, budget) };
|
|
272
337
|
}
|
|
273
338
|
catch (err) {
|
|
274
|
-
return {
|
|
275
|
-
alias,
|
|
276
|
-
success: false,
|
|
277
|
-
error: err instanceof Error ? err.message : String(err),
|
|
278
|
-
};
|
|
339
|
+
return { alias, ...boundExecOutput(executionFailure(err), budget) };
|
|
279
340
|
}
|
|
280
|
-
});
|
|
341
|
+
}, extra?.signal);
|
|
281
342
|
return formatResult({
|
|
282
343
|
success: results.every((r) => r.success),
|
|
283
344
|
total: args.aliases.length,
|
|
284
345
|
concurrency,
|
|
285
346
|
results,
|
|
347
|
+
maxOutputBytes: REQUEST_OUTPUT_LIMIT,
|
|
348
|
+
outputBytes: REQUEST_OUTPUT_LIMIT - budget.remaining,
|
|
349
|
+
outputTruncated: budget.truncated || undefined,
|
|
286
350
|
});
|
|
287
351
|
}
|
|
288
352
|
catch (error) {
|
|
@@ -291,7 +355,7 @@ async function handleExecParallel(args) {
|
|
|
291
355
|
}
|
|
292
356
|
async function cleanupRemoteScript(alias, remotePath, timeout) {
|
|
293
357
|
try {
|
|
294
|
-
await fileOps.removeRemoteFile(alias, remotePath, timeout);
|
|
358
|
+
await fileOps.removeRemoteFile(alias, remotePath, Math.min(timeout ?? DEFAULT_EXEC_TIMEOUT_MS, DEFAULT_EXEC_TIMEOUT_MS));
|
|
295
359
|
return undefined;
|
|
296
360
|
}
|
|
297
361
|
catch (error) {
|
|
@@ -311,17 +375,18 @@ function resolveScriptUsers(args) {
|
|
|
311
375
|
};
|
|
312
376
|
}
|
|
313
377
|
export function windowsScriptContent(script, interpreter) {
|
|
314
|
-
const bom = String.fromCharCode(
|
|
378
|
+
const bom = String.fromCharCode(65279);
|
|
315
379
|
if (interpreter.toLowerCase().startsWith('cmd')) {
|
|
316
380
|
return `@chcp 65001>nul || exit /b 1\r\n${script.startsWith(bom) ? script.slice(1) : script}`;
|
|
317
381
|
}
|
|
318
382
|
return script.startsWith(bom) ? script : bom + script;
|
|
319
383
|
}
|
|
320
|
-
async function prepareRemoteScript(alias, remotePath, effectiveUser, loginUser, timeout) {
|
|
384
|
+
async function prepareRemoteScript(alias, remotePath, effectiveUser, loginUser, timeout, signal) {
|
|
321
385
|
const quotedPath = escapeShellArg(remotePath);
|
|
322
386
|
const ownershipCommand = effectiveUser && effectiveUser !== loginUser ? `chown ${escapeShellArg(effectiveUser)} ${quotedPath} && ` : '';
|
|
323
387
|
const result = await sessionManager.exec(alias, `${ownershipCommand}chmod 700 ${quotedPath}`, {
|
|
324
388
|
timeout,
|
|
389
|
+
signal,
|
|
325
390
|
useLoginUser: true,
|
|
326
391
|
maxOutputSize: 4096,
|
|
327
392
|
});
|
|
@@ -330,55 +395,61 @@ async function prepareRemoteScript(alias, remotePath, effectiveUser, loginUser,
|
|
|
330
395
|
throw new Error(`prepare remote script failed: ${reason}`);
|
|
331
396
|
}
|
|
332
397
|
}
|
|
333
|
-
async function handleExecScript(args) {
|
|
398
|
+
async function handleExecScript(args, extra) {
|
|
334
399
|
let remotePath;
|
|
335
400
|
let remoteSftpPath;
|
|
336
401
|
let ownsRemotePath = false;
|
|
337
402
|
let executionStarted = false;
|
|
338
403
|
try {
|
|
339
|
-
|
|
340
|
-
|
|
404
|
+
extra?.signal.throwIfAborted();
|
|
405
|
+
if (sessionManager.getOpenSshConnection(args.alias)) {
|
|
406
|
+
return formatError(new OpenSshError('The OpenSSH backend does not support temporary script uploads; use ssh_exec for inline commands', {
|
|
341
407
|
code: 'unsupported_backend',
|
|
342
408
|
backend: 'openssh',
|
|
343
409
|
capability: 'script_upload',
|
|
344
410
|
retryable: false,
|
|
345
|
-
});
|
|
411
|
+
}));
|
|
412
|
+
}
|
|
346
413
|
const windows = sessionManager.getRemotePlatform(args.alias) === 'windows';
|
|
347
414
|
const interpreter = args.interpreter ?? (windows ? sessionManager.getCommandShell(args.alias) : 'bash');
|
|
415
|
+
const interpreterArgs = args.interpreterArgs ?? [];
|
|
348
416
|
const { effectiveUser, loginUser } = resolveScriptUsers(args);
|
|
349
417
|
if (windows && (args.targetUser || args.runAs || effectiveUser)) {
|
|
350
418
|
sessionManager.requirePosixPrivilege(args.alias);
|
|
351
419
|
}
|
|
352
420
|
validateScriptUser(effectiveUser);
|
|
353
421
|
if (windows && !['powershell', 'powershell.exe', 'cmd', 'cmd.exe'].includes(interpreter.toLowerCase())) {
|
|
354
|
-
|
|
422
|
+
return formatError(new Error('Windows script interpreter must be cmd or powershell'));
|
|
355
423
|
}
|
|
356
424
|
if (windows) {
|
|
357
425
|
const suffix = interpreter.toLowerCase().startsWith('cmd') ? '.cmd' : '.ps1';
|
|
358
426
|
const name = `mcp-ssh-script-${randomUUID()}${suffix}`;
|
|
359
427
|
const tempResult = await sessionManager.exec(args.alias, encodedPowershell(windowsTemporaryPathScript(name)), {
|
|
360
428
|
timeout: args.timeout,
|
|
429
|
+
signal: extra?.signal,
|
|
361
430
|
useLoginUser: true,
|
|
362
431
|
maxOutputSize: 4096,
|
|
363
432
|
});
|
|
364
433
|
if (!tempResult.success) {
|
|
365
|
-
|
|
434
|
+
return formatError(new Error(tempResult.stderr.includes('privacy_not_enforced_on_windows')
|
|
366
435
|
? 'privacy_not_enforced_on_windows: remote temporary directory ACL was not verified'
|
|
367
|
-
:
|
|
436
|
+
: 'Remote Windows temporary directory lookup failed: ' +
|
|
437
|
+
(tempResult.stderr || tempResult.stdout)));
|
|
368
438
|
}
|
|
369
439
|
remotePath = tempResult.stdout.trim();
|
|
370
440
|
if (!remotePath ||
|
|
371
441
|
/[\r\n\0]/.test(remotePath) ||
|
|
372
442
|
!(remotePath.endsWith(`\\${name}`) || remotePath.endsWith(`/${name}`))) {
|
|
373
|
-
|
|
443
|
+
return formatError(new Error('Remote Windows temporary directory lookup failed'));
|
|
374
444
|
}
|
|
375
445
|
remoteSftpPath = sftpPath(remotePath, sessionManager.getRemotePathStyle(args.alias));
|
|
376
|
-
await fileOps.prepareWindowsRemotePrivateFile(args.alias, remoteSftpPath, args.timeout, remotePath);
|
|
446
|
+
await fileOps.prepareWindowsRemotePrivateFile(args.alias, remoteSftpPath, args.timeout ?? DEFAULT_EXEC_TIMEOUT_MS, remotePath, extra?.signal);
|
|
377
447
|
ownsRemotePath = true;
|
|
378
448
|
}
|
|
379
449
|
else {
|
|
380
450
|
const tempResult = await sessionManager.exec(args.alias, 'mktemp /tmp/mcp-ssh-script.XXXXXX', {
|
|
381
451
|
timeout: args.timeout,
|
|
452
|
+
signal: extra?.signal,
|
|
382
453
|
useLoginUser: true,
|
|
383
454
|
maxOutputSize: 4096,
|
|
384
455
|
});
|
|
@@ -390,24 +461,34 @@ async function handleExecScript(args) {
|
|
|
390
461
|
remoteSftpPath = remotePath;
|
|
391
462
|
}
|
|
392
463
|
if (!remoteSftpPath) {
|
|
393
|
-
|
|
464
|
+
return formatError(new Error('Remote temporary script path was not created'));
|
|
394
465
|
}
|
|
395
|
-
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();
|
|
396
468
|
if (!windows) {
|
|
397
|
-
await prepareRemoteScript(args.alias, remotePath, effectiveUser, loginUser, args.timeout);
|
|
469
|
+
await prepareRemoteScript(args.alias, remotePath, effectiveUser, loginUser, args.timeout, extra?.signal);
|
|
398
470
|
}
|
|
399
471
|
const command = windows
|
|
400
|
-
?
|
|
401
|
-
?
|
|
402
|
-
|
|
403
|
-
|
|
472
|
+
? interpreterArgs.length > 0
|
|
473
|
+
? encodedPowershell(`& ${[interpreter, ...interpreterArgs].map(quotePowershell).join(' ')} ` +
|
|
474
|
+
(interpreter.toLowerCase().startsWith('cmd')
|
|
475
|
+
? `/D /V:OFF /S /C ${quotePowershell(`"${remotePath.replace(/"/g, '""')}"`)}`
|
|
476
|
+
: `-File ${quotePowershell(remotePath)}`) +
|
|
477
|
+
'; exit $LASTEXITCODE')
|
|
478
|
+
: interpreter.toLowerCase().startsWith('cmd')
|
|
479
|
+
? `cmd.exe /D /C "${remotePath.replace(/"/g, '""')}"`
|
|
480
|
+
: encodedPowershell(`& ${quotePowershell(remotePath)}; if (-not $?) { exit 1 }`)
|
|
481
|
+
: [interpreter, ...interpreterArgs, remotePath].map(escapeShellArg).join(' ');
|
|
404
482
|
const execOptions = {
|
|
405
483
|
timeout: args.timeout,
|
|
484
|
+
signal: extra?.signal,
|
|
406
485
|
cwd: args.cwd,
|
|
407
486
|
env: args.env,
|
|
408
487
|
maxOutputSize: args.maxOutputSize,
|
|
409
488
|
runAs: args.targetUser ?? args.runAs,
|
|
410
489
|
};
|
|
490
|
+
extra?.signal.throwIfAborted();
|
|
491
|
+
// noinspection JSUnusedAssignment -- read by the failure cleanup path
|
|
411
492
|
executionStarted = true;
|
|
412
493
|
const result = args.targetUser
|
|
413
494
|
? await sessionManager.execAsUser(args.alias, command, args.targetUser, execOptions)
|
|
@@ -426,14 +507,7 @@ async function handleExecScript(args) {
|
|
|
426
507
|
const cleanupWarning = remoteSftpPath && ownsRemotePath && (args.keepScript !== true || !executionStarted)
|
|
427
508
|
? await cleanupRemoteScript(args.alias, remoteSftpPath, args.timeout)
|
|
428
509
|
: undefined;
|
|
429
|
-
|
|
430
|
-
return formatResult({
|
|
431
|
-
success: false,
|
|
432
|
-
error: error instanceof Error ? error.message : String(error),
|
|
433
|
-
cleanupWarning,
|
|
434
|
-
});
|
|
435
|
-
}
|
|
436
|
-
return formatError(error);
|
|
510
|
+
return formatError(error, { ...sftpOperationOutcome(error), cleanupWarning });
|
|
437
511
|
}
|
|
438
512
|
}
|
|
439
513
|
// ========== Register ==========
|
|
@@ -443,7 +517,7 @@ export function registerExecTools(server) {
|
|
|
443
517
|
|
|
444
518
|
返回: stdout, stderr, exitCode, duration`,
|
|
445
519
|
inputSchema: execSchema,
|
|
446
|
-
}, (args) => handleExec(args));
|
|
520
|
+
}, (args, extra) => handleExec(args, extra));
|
|
447
521
|
server.registerTool('ssh_exec_as_user', {
|
|
448
522
|
description: `以其他用户身份执行命令(通过 su 切换)
|
|
449
523
|
|
|
@@ -454,21 +528,21 @@ export function registerExecTools(server) {
|
|
|
454
528
|
|
|
455
529
|
示例: ssh_exec_as_user(alias="server", command="whoami", targetUser="appuser")`,
|
|
456
530
|
inputSchema: execAsUserSchema,
|
|
457
|
-
}, (args) => handleExecAsUser(args));
|
|
531
|
+
}, (args, extra) => handleExecAsUser(args, extra));
|
|
458
532
|
server.registerTool('ssh_exec_sudo', {
|
|
459
533
|
description: '使用 sudo 执行命令。runAs、useLoginUser 与 loadProfile 的身份优先级与 ssh_exec 相同。',
|
|
460
534
|
inputSchema: execSudoSchema,
|
|
461
|
-
}, (args) => handleExecSudo(args));
|
|
535
|
+
}, (args, extra) => handleExecSudo(args, extra));
|
|
462
536
|
server.registerTool('ssh_exec_batch', {
|
|
463
537
|
description: `批量执行多条命令,每条命令在独立 SSH channel 中执行,环境变量不共享
|
|
464
538
|
|
|
465
539
|
如需命令间共享环境(如 export 变量),用分号拼接为单条命令通过 ssh_exec 执行`,
|
|
466
540
|
inputSchema: execBatchSchema,
|
|
467
|
-
}, (args) => handleExecBatch(args));
|
|
541
|
+
}, (args, extra) => handleExecBatch(args, extra));
|
|
468
542
|
server.registerTool('ssh_quick_exec', {
|
|
469
543
|
description: '一次性执行命令(自动连接、执行、断开)。readyTimeout 只限制建立 SSH 连接,timeout 只限制命令执行,适用于单次命令。',
|
|
470
544
|
inputSchema: quickExecSchema,
|
|
471
|
-
}, (args) => handleQuickExec(args));
|
|
545
|
+
}, (args, extra) => handleQuickExec(args, extra));
|
|
472
546
|
server.registerTool('ssh_exec_parallel', {
|
|
473
547
|
description: `在多个已连接的会话上并行执行同一命令
|
|
474
548
|
|
|
@@ -477,9 +551,11 @@ export function registerExecTools(server) {
|
|
|
477
551
|
|
|
478
552
|
返回每个主机的执行结果`,
|
|
479
553
|
inputSchema: execParallelSchema,
|
|
480
|
-
}, (args) => handleExecParallel(args));
|
|
554
|
+
}, (args, extra) => handleExecParallel(args, extra));
|
|
481
555
|
server.registerTool('ssh_exec_script', {
|
|
482
|
-
description: '上传远端临时脚本并执行,默认执行后清理脚本;timeout
|
|
556
|
+
description: '上传远端临时脚本并执行,默认执行后清理脚本;timeout 分别限制上传、准备和执行阶段,最大 3600000 ms;' +
|
|
557
|
+
'清理独立计时,使用请求值与 30000 ms 中的较小值,省略时为 30000 ms;' +
|
|
558
|
+
'宿主中止后远端进程停止状态未知,长任务用 ssh_operation_start/status/read/cancel',
|
|
483
559
|
inputSchema: execScriptSchema,
|
|
484
|
-
}, (args) => handleExecScript(args));
|
|
560
|
+
}, (args, extra) => handleExecScript(args, extra));
|
|
485
561
|
}
|