@pyrokine/mcp-ssh 2.4.1 → 2.4.3

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.
@@ -9,32 +9,77 @@ import * as path from 'path';
9
9
  import { z } from 'zod';
10
10
  import { sessionManager } from '../session-manager.js';
11
11
  import { parseProxyJump, parseSSHConfig } from '../ssh-config.js';
12
+ import { sshPortSchema } from './schema.js';
12
13
  import { expandTilde, formatError, formatResult } from './utils.js';
14
+ const templateJumpHostSchema = z.object({
15
+ host: z.string(),
16
+ user: z.string(),
17
+ password: z.string().optional(),
18
+ keyPath: z.string().optional(),
19
+ port: sshPortSchema.optional(),
20
+ readyTimeout: z.number().int().positive().max(600000).optional(),
21
+ });
22
+ const connectionTemplateSchema = z.object({
23
+ configHost: z.string().optional(),
24
+ host: z.string().optional(),
25
+ user: z.string().optional(),
26
+ username: z.string().optional(),
27
+ password: z.string().optional(),
28
+ keyPath: z.string().optional(),
29
+ privateKeyPath: z.string().optional(),
30
+ port: sshPortSchema.optional(),
31
+ alias: z.string().optional(),
32
+ env: z.record(z.string(), z.string()).optional(),
33
+ defaultEnv: z.record(z.string(), z.string()).optional(),
34
+ runAs: z.string().optional(),
35
+ keepaliveInterval: z.number().int().positive().optional(),
36
+ readyTimeout: z.number().int().positive().max(600000).optional(),
37
+ jumpHost: templateJumpHostSchema.optional(),
38
+ });
13
39
  function loadTemplates() {
14
40
  const fromEnv = process.env.SSH_MCP_TEMPLATES;
15
- if (fromEnv) {
16
- return JSON.parse(fromEnv);
17
- }
18
- const filePath = path.join(os.homedir(), '.mcp-ssh', 'templates.json');
19
- if (!fs.existsSync(filePath)) {
41
+ const source = fromEnv ??
42
+ (() => {
43
+ const filePath = path.join(os.homedir(), '.mcp-ssh', 'templates.json');
44
+ return fs.existsSync(filePath) ? fs.readFileSync(expandTilde(filePath), 'utf-8') : undefined;
45
+ })();
46
+ if (!source) {
20
47
  return {};
21
48
  }
22
- return JSON.parse(fs.readFileSync(expandTilde(filePath), 'utf-8'));
49
+ const parsed = JSON.parse(source);
50
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
51
+ throw new Error('SSH templates must be an object keyed by template name');
52
+ }
53
+ return parsed;
23
54
  }
24
55
  function getTemplate(name) {
25
56
  if (!name) {
26
57
  return {};
27
58
  }
28
- const templates = loadTemplates();
29
- const template = templates[name];
30
- if (!template) {
59
+ let templates;
60
+ try {
61
+ templates = loadTemplates();
62
+ }
63
+ catch (error) {
64
+ throw new Error(`Template '${name}' could not be loaded: ${error instanceof Error ? error.message : String(error)}`, {
65
+ cause: error,
66
+ });
67
+ }
68
+ const rawTemplate = templates[name];
69
+ if (!rawTemplate) {
31
70
  const available = Object.keys(templates);
32
71
  const suggestion = available.length
33
72
  ? `Available templates: ${available.slice(0, 20).join(', ')}`
34
73
  : 'No templates found. Define SSH_MCP_TEMPLATES or ~/.mcp-ssh/templates.json';
35
74
  throw new Error(`Template '${name}' not found. ${suggestion}`);
36
75
  }
37
- return template;
76
+ const parsed = connectionTemplateSchema.safeParse(rawTemplate);
77
+ if (!parsed.success) {
78
+ const issue = parsed.error.issues[0];
79
+ const field = issue.path.length > 0 ? issue.path.join('.') : '<root>';
80
+ throw new Error(`Template '${name}' is invalid at ${field}: ${issue.message}`);
81
+ }
82
+ return parsed.data;
38
83
  }
39
84
  function mergeEnv(templateEnv, argsEnv) {
40
85
  const merged = { ...templateEnv, ...argsEnv };
@@ -49,7 +94,7 @@ const connectSchema = z.object({
49
94
  user: z.string().optional().describe('用户名(使用 configHost 时可省略)'),
50
95
  password: z.string().optional().describe('密码'),
51
96
  keyPath: z.string().optional().describe('SSH 私钥路径'),
52
- port: z.number().optional().describe('SSH 端口,默认 22'),
97
+ port: sshPortSchema.optional().describe('SSH 端口,默认 22'),
53
98
  alias: z.string().optional().describe('连接别名(可选,默认使用 configHost 或 host)'),
54
99
  env: z.record(z.string(), z.string()).optional().describe('环境变量'),
55
100
  defaultEnv: z.record(z.string(), z.string()).optional().describe('连接级默认环境变量'),
@@ -68,7 +113,7 @@ const connectSchema = z.object({
68
113
  user: z.string().describe('跳板机用户名'),
69
114
  password: z.string().optional().describe('跳板机密码'),
70
115
  keyPath: z.string().optional().describe('跳板机私钥路径'),
71
- port: z.number().optional().describe('跳板机端口,默认 22'),
116
+ port: sshPortSchema.optional().describe('跳板机端口,默认 22'),
72
117
  readyTimeout: z
73
118
  .number()
74
119
  .int()
@@ -135,10 +180,10 @@ async function handleConnect(args) {
135
180
  });
136
181
  }
137
182
  // 显式参数优先于 config 值
138
- host = host || hostConfig.hostName || hostConfig.host;
139
- user = user || hostConfig.user;
140
- port = port || hostConfig.port;
141
- keyPath = keyPath || hostConfig.identityFile;
183
+ host = host ?? hostConfig.hostName ?? hostConfig.host;
184
+ user = user ?? hostConfig.user;
185
+ port = port ?? hostConfig.port;
186
+ keyPath = keyPath ?? hostConfig.identityFile;
142
187
  // 解析 ProxyJump(支持 user@host:port 格式)
143
188
  if (hostConfig.proxyJump) {
144
189
  const parsed = parseProxyJump(hostConfig.proxyJump);
@@ -157,7 +202,7 @@ async function handleConnect(args) {
157
202
  }
158
203
  jumpHostResolved = {
159
204
  host: jumpHostConfig.hostName || jumpHostConfig.host,
160
- port: parsed.port || jumpHostConfig.port || 22,
205
+ port: parsed.port ?? jumpHostConfig.port ?? 22,
161
206
  username: jumpUser,
162
207
  privateKeyPath: jumpHostConfig.identityFile,
163
208
  };
@@ -173,7 +218,7 @@ async function handleConnect(args) {
173
218
  }
174
219
  jumpHostResolved = {
175
220
  host: parsed.host,
176
- port: parsed.port || 22,
221
+ port: parsed.port ?? 22,
177
222
  username: parsed.user,
178
223
  };
179
224
  }
@@ -187,18 +232,19 @@ async function handleConnect(args) {
187
232
  });
188
233
  }
189
234
  // 手动指定的 jumpHost 优先级高于 ProxyJump
190
- const jumpHost = args.jumpHost
235
+ const requestedJumpHost = args.jumpHost ?? template.jumpHost;
236
+ const jumpHost = requestedJumpHost
191
237
  ? {
192
- host: args.jumpHost.host,
193
- port: args.jumpHost.port || 22,
194
- username: args.jumpHost.user,
195
- password: args.jumpHost.password,
196
- privateKeyPath: args.jumpHost.keyPath,
197
- readyTimeout: args.jumpHost.readyTimeout ?? readyTimeout,
238
+ host: requestedJumpHost.host,
239
+ port: requestedJumpHost.port ?? 22,
240
+ username: requestedJumpHost.user,
241
+ password: requestedJumpHost.password,
242
+ privateKeyPath: requestedJumpHost.keyPath,
243
+ readyTimeout: requestedJumpHost.readyTimeout ?? readyTimeout,
198
244
  }
199
245
  : jumpHostResolved;
200
- const finalPort = port || 22;
201
- const finalAlias = requestedAlias || `${user}@${host}:${finalPort}`;
246
+ const finalPort = port ?? 22;
247
+ const finalAlias = requestedAlias ?? `${user}@${host}:${finalPort}`;
202
248
  const identity = `${user}@${host}:${finalPort}`;
203
249
  const sessionsBeforeConnect = sessionManager.listSessionDetails();
204
250
  const reused = sessionsBeforeConnect.some((session) => session.alias === finalAlias && session.connected);
@@ -211,7 +257,7 @@ async function handleConnect(args) {
211
257
  username: user,
212
258
  password,
213
259
  privateKeyPath: keyPath,
214
- alias: requestedAlias,
260
+ alias: finalAlias,
215
261
  template: args.template,
216
262
  runAs,
217
263
  defaultEnv,
@@ -310,7 +356,7 @@ export function registerConnectionTools(server) {
310
356
  description: [
311
357
  '建立 SSH 连接并保持会话,支持密码、密钥认证,支持跳板机',
312
358
  '',
313
- '可通过 configHost 参数使用 ~/.ssh/config 中的配置,无需重复填写连接信息',
359
+ '可通过 configHost 参数使用 ~/.ssh/config 中的配置,无需重复填写连接信息;模板会在连接前校验端口和嵌套 jumpHost 字段',
314
360
  '支持 Host 多别名、Host * 全局默认继承、ProxyJump(user@host:port 格式)',
315
361
  '',
316
362
  '示例',
@@ -4,11 +4,13 @@
4
4
  * ssh_exec, ssh_exec_as_user, ssh_exec_sudo,
5
5
  * ssh_exec_batch, ssh_quick_exec, ssh_exec_parallel
6
6
  */
7
+ import { randomUUID } from 'crypto';
7
8
  import { z } from 'zod';
8
9
  import { classifyCommandRisk } from '../command-risk.js';
9
10
  import * as fileOps from '../file-ops.js';
10
11
  import { sessionManager } from '../session-manager.js';
11
12
  import { HARD_EXEC_MAX_OUTPUT_SIZE } from '../types.js';
13
+ import { sshPortSchema } from './schema.js';
12
14
  import { escapeShellArg, formatError, formatResult } from './utils.js'; // ========== Schemas ==========
13
15
  // ========== Schemas ==========
14
16
  const maxOutputSizeSchema = z
@@ -52,6 +54,9 @@ const execSudoSchema = z.object({
52
54
  sudoPassword: z.string().optional().describe('sudo 密码(如果需要)'),
53
55
  timeout: z.number().optional().describe('超时(毫秒)'),
54
56
  maxOutputSize: maxOutputSizeSchema,
57
+ runAs: z.string().optional().describe('本次命令使用的目标用户,覆盖连接级 runAs'),
58
+ useLoginUser: z.boolean().optional().describe('设为 true 时跳过连接级 runAs,直接以登录用户执行'),
59
+ loadProfile: z.boolean().optional().describe('runAs 执行时是否加载目标用户 shell 配置,默认 true'),
55
60
  });
56
61
  const execBatchSchema = z.object({
57
62
  alias: z.string().describe('连接别名'),
@@ -65,8 +70,9 @@ const quickExecSchema = z.object({
65
70
  command: z.string().describe('要执行的命令'),
66
71
  password: z.string().optional().describe('密码'),
67
72
  keyPath: z.string().optional().describe('密钥路径'),
68
- port: z.number().optional().describe('端口'),
69
- timeout: z.number().optional().describe('超时(毫秒)'),
73
+ port: sshPortSchema.optional().describe('SSH 端口,默认 22'),
74
+ readyTimeout: z.number().int().positive().max(600000).optional().describe('等待 SSH ready 的超时,默认 30000'),
75
+ timeout: z.number().optional().describe('命令执行超时(毫秒),默认 30000'),
70
76
  });
71
77
  const EXEC_PARALLEL_MAX_ALIASES = 32;
72
78
  const EXEC_PARALLEL_DEFAULT_CONCURRENCY = 4;
@@ -145,6 +151,9 @@ async function handleExecSudo(args) {
145
151
  const result = await sessionManager.execSudo(args.alias, args.command, args.sudoPassword, {
146
152
  timeout: args.timeout,
147
153
  maxOutputSize: args.maxOutputSize,
154
+ runAs: args.runAs,
155
+ useLoginUser: args.useLoginUser,
156
+ loadProfile: args.loadProfile,
148
157
  });
149
158
  return formatResult(result);
150
159
  }
@@ -195,15 +204,16 @@ async function handleExecBatch(args) {
195
204
  }
196
205
  }
197
206
  async function handleQuickExec(args) {
198
- const tempAlias = `_quick_${Date.now()}`;
207
+ const tempAlias = `_quick_${randomUUID()}`;
199
208
  try {
200
209
  await sessionManager.connect({
201
210
  host: args.host,
202
- port: args.port || 22,
211
+ port: args.port ?? 22,
203
212
  username: args.user,
204
213
  password: args.password,
205
214
  privateKeyPath: args.keyPath,
206
215
  alias: tempAlias,
216
+ readyTimeout: args.readyTimeout,
207
217
  });
208
218
  const result = await sessionManager.exec(tempAlias, args.command, { timeout: args.timeout });
209
219
  return formatResult(result);
@@ -369,7 +379,7 @@ export function registerExecTools(server) {
369
379
  inputSchema: execAsUserSchema,
370
380
  }, (args) => handleExecAsUser(args));
371
381
  server.registerTool('ssh_exec_sudo', {
372
- description: '使用 sudo 执行命令',
382
+ description: '使用 sudo 执行命令。runAs、useLoginUser 与 loadProfile 的身份优先级与 ssh_exec 相同。',
373
383
  inputSchema: execSudoSchema,
374
384
  }, (args) => handleExecSudo(args));
375
385
  server.registerTool('ssh_exec_batch', {
@@ -379,7 +389,7 @@ export function registerExecTools(server) {
379
389
  inputSchema: execBatchSchema,
380
390
  }, (args) => handleExecBatch(args));
381
391
  server.registerTool('ssh_quick_exec', {
382
- description: '一次性执行命令(自动连接、执行、断开),适用于单次命令,不需要保持连接',
392
+ description: '一次性执行命令(自动连接、执行、断开)。readyTimeout 只限制建立 SSH 连接,timeout 只限制命令执行,适用于单次命令。',
383
393
  inputSchema: quickExecSchema,
384
394
  }, (args) => handleQuickExec(args));
385
395
  server.registerTool('ssh_exec_parallel', {
@@ -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.number().optional().describe('从指定字节偏移开始读取,与 tail/lineRange 互斥'),
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 {
@@ -284,47 +322,45 @@ function isRemoteMissingError(error) {
284
322
  const message = error instanceof Error ? error.message : String(error);
285
323
  return code === 2 || code === 'ENOENT' || /no such file|not found/i.test(message);
286
324
  }
287
- async function probeRemoteFile(alias, remotePath, _timeout = 10000) {
325
+ async function probeRemoteFile(alias, remotePath, timeout = 10000) {
326
+ let info;
288
327
  try {
289
- const info = await fileOps.getFileInfo(alias, remotePath);
290
- const mode = permissionStringToOctal(info.permissions);
291
- if (!mode) {
292
- throw new VerificationStageError('remote_probe', 'Remote SFTP stat returned invalid mode metadata', false, {
293
- operation: 'stat',
294
- probeMethod: 'sftp',
295
- });
296
- }
297
- return {
298
- exists: true,
299
- remotePath,
300
- probeMethod: 'sftp',
301
- ownerName: undefined,
302
- ownerId: info.owner,
303
- groupName: undefined,
304
- groupId: info.group,
305
- mode,
306
- size: info.size,
307
- mtimeMs: info.mtime.getTime(),
308
- fileType: info.isDirectory
309
- ? 'directory'
310
- : info.isFile
311
- ? 'regular file'
312
- : info.isSymlink
313
- ? 'symbolic link'
314
- : 'other',
315
- isDirectory: info.isDirectory,
316
- isFile: info.isFile,
317
- };
328
+ info = await fileOps.getFileInfo(alias, remotePath, timeout);
318
329
  }
319
330
  catch (error) {
320
331
  if (isRemoteMissingError(error)) {
321
332
  return { exists: false, remotePath, probeMethod: 'sftp' };
322
333
  }
323
- if (error instanceof VerificationStageError) {
324
- throw error;
325
- }
326
334
  throw new VerificationStageError('remote_probe', `Remote SFTP stat failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'stat', probeMethod: 'sftp' });
327
335
  }
336
+ const mode = permissionStringToOctal(info.permissions);
337
+ if (!mode) {
338
+ throw new VerificationStageError('remote_probe', 'Remote SFTP stat returned invalid mode metadata', false, {
339
+ operation: 'stat',
340
+ probeMethod: 'sftp',
341
+ });
342
+ }
343
+ return {
344
+ exists: true,
345
+ remotePath,
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,
363
+ };
328
364
  }
329
365
  async function buildUploadVerification(args, local, verificationRemotePath = args.remotePath) {
330
366
  const remote = await probeRemoteFile(args.alias, verificationRemotePath);
@@ -662,7 +698,7 @@ async function handleUpload(args) {
662
698
  args.verifySize ||
663
699
  args.verifyMtime);
664
700
  try {
665
- const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath, undefined, undefined, createMode, undefined, false, args.atomic === true);
701
+ const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath, undefined, undefined, createMode, undefined, false, args.atomic === true, args.timeout);
666
702
  let verification;
667
703
  let verificationError;
668
704
  if (verificationRequested) {
@@ -685,13 +721,14 @@ async function handleUpload(args) {
685
721
  catch (cleanupError) {
686
722
  cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
687
723
  }
724
+ const verificationMessage = verificationError instanceof Error ? verificationError.message : String(verificationError);
688
725
  return formatResult({
689
726
  ...uploadResult,
690
727
  ...outcome,
691
728
  message: `Atomic upload verification failed; existing target preserved: ${args.remotePath}`,
692
729
  error: verificationError === undefined
693
730
  ? `Atomic upload verification failed: ${args.remotePath}`
694
- : `Atomic upload verification failed: ${verificationError instanceof Error ? verificationError.message : String(verificationError)}`,
731
+ : `Atomic upload verification failed: ${verificationMessage}`,
695
732
  cleanupWarning,
696
733
  atomic: true,
697
734
  targetReplaced: false,
@@ -711,7 +748,7 @@ async function handleUpload(args) {
711
748
  }
712
749
  if (args.atomic) {
713
750
  try {
714
- await fileOps.renameRemoteFile(args.alias, tempRemotePath, args.remotePath, remoteBefore.exists);
751
+ await fileOps.renameRemoteFile(args.alias, tempRemotePath, args.remotePath, remoteBefore.exists, args.timeout);
715
752
  }
716
753
  catch (error) {
717
754
  const renameNotStarted = error instanceof fileOps.RemoteRenameNotStartedError;
@@ -746,6 +783,7 @@ async function handleUpload(args) {
746
783
  });
747
784
  }
748
785
  }
786
+ const verificationMessage = verificationError instanceof Error ? verificationError.message : String(verificationError);
749
787
  return formatResult({
750
788
  ...uploadResult,
751
789
  ...outcome,
@@ -754,7 +792,7 @@ async function handleUpload(args) {
754
792
  : `Uploaded but verification failed: ${args.remotePath}`,
755
793
  error: verificationError === undefined
756
794
  ? undefined
757
- : `Upload completed, but verification failed: ${verificationError instanceof Error ? verificationError.message : String(verificationError)}`,
795
+ : `Upload completed, but verification failed: ${verificationMessage}`,
758
796
  atomic: args.atomic === true,
759
797
  targetReplaced: args.atomic ? true : undefined,
760
798
  ...pathDetails,
@@ -784,6 +822,7 @@ async function handleUpload(args) {
784
822
  }
785
823
  return formatResult({
786
824
  success: false,
825
+ ...sftpOperationOutcome(error),
787
826
  error: error instanceof Error ? error.message : String(error),
788
827
  cleanupWarning,
789
828
  finalRemotePath: args.remotePath,
@@ -799,12 +838,13 @@ async function handleUpload(args) {
799
838
  }
800
839
  async function handleDownload(args) {
801
840
  try {
802
- 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);
803
842
  return formatResult({ ...downloadResult, message: `Downloaded to ${args.localPath}` });
804
843
  }
805
844
  catch (error) {
806
845
  return formatResult({
807
846
  success: false,
847
+ ...sftpOperationOutcome(error),
808
848
  error: error instanceof Error ? error.message : String(error),
809
849
  diagnostics: {
810
850
  local: summarizeLocalPathProbe(fileOps.probeLocalPath(args.localPath)),
@@ -821,25 +861,26 @@ async function handleReadFile(args) {
821
861
  offset: args.offset,
822
862
  tail: args.tail,
823
863
  lineRange: args.lineRange,
864
+ timeout: args.timeout,
824
865
  });
825
866
  return formatResult({ success: true, ...readResult });
826
867
  }
827
868
  catch (error) {
828
- return formatError(error);
869
+ return formatFileOperationError(error);
829
870
  }
830
871
  }
831
872
  async function handleWriteFile(args) {
832
873
  try {
833
- 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);
834
875
  return formatResult(result);
835
876
  }
836
877
  catch (error) {
837
- return formatError(error);
878
+ return formatFileOperationError(error);
838
879
  }
839
880
  }
840
881
  async function handleListDir(args) {
841
882
  try {
842
- 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);
843
884
  return formatResult({
844
885
  success: true,
845
886
  path: args.remotePath,
@@ -848,25 +889,25 @@ async function handleListDir(args) {
848
889
  });
849
890
  }
850
891
  catch (error) {
851
- return formatError(error);
892
+ return formatFileOperationError(error);
852
893
  }
853
894
  }
854
895
  async function handleFileInfo(args) {
855
896
  try {
856
- const info = await fileOps.getFileInfo(args.alias, args.remotePath);
897
+ const info = await fileOps.getFileInfo(args.alias, args.remotePath, args.timeout);
857
898
  return formatResult({ success: true, ...info });
858
899
  }
859
900
  catch (error) {
860
- return formatError(error);
901
+ return formatFileOperationError(error);
861
902
  }
862
903
  }
863
904
  async function handleMkdir(args) {
864
905
  try {
865
- 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);
866
907
  return formatResult({ success, path: args.remotePath });
867
908
  }
868
909
  catch (error) {
869
- return formatError(error);
910
+ return formatFileOperationError(error);
870
911
  }
871
912
  }
872
913
  async function handleSync(args) {
@@ -882,7 +923,7 @@ async function handleSync(args) {
882
923
  const remainingTimeout = () => operationTimeout - (Date.now() - startedAt);
883
924
  try {
884
925
  if (args.direction === 'upload') {
885
- fileOps.validateSyncUploadSource(args.localPath, args.followSymlinks === true, args.exclude);
926
+ fileOps.validateSyncUploadSource(args.localPath, args.followSymlinks === true);
886
927
  }
887
928
  else {
888
929
  fileOps.validateLocalPathPolicy(args.localPath);
@@ -933,7 +974,11 @@ async function handleSync(args) {
933
974
  }
934
975
  const transferTimeout = remainingTimeout();
935
976
  if (transferTimeout <= 0) {
936
- throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted before transfer started', true);
977
+ return formatResult({
978
+ success: false,
979
+ error: 'sync operation timeout was exhausted before transfer started',
980
+ diagnostics,
981
+ });
937
982
  }
938
983
  const syncResult = await fileOps.syncFiles(args.alias, args.localPath, args.remotePath, args.direction, {
939
984
  delete: args.delete,
@@ -962,12 +1007,13 @@ async function handleSync(args) {
962
1007
  }
963
1008
  }
964
1009
  const outcome = buildTransferOutcome(syncResult.success, verificationRequested, verification, verificationError);
1010
+ const verificationMessage = verificationError instanceof Error ? verificationError.message : String(verificationError);
965
1011
  return formatResult({
966
1012
  ...syncResult,
967
1013
  ...outcome,
968
1014
  error: verificationError === undefined
969
1015
  ? undefined
970
- : `Sync completed, but verification failed: ${verificationError instanceof Error ? verificationError.message : String(verificationError)}`,
1016
+ : `Sync completed, but verification failed: ${verificationMessage}`,
971
1017
  transportVerification: syncResult.verification,
972
1018
  verification,
973
1019
  direction: args.direction,
@@ -987,19 +1033,19 @@ async function handleSync(args) {
987
1033
  // ========== Register ==========
988
1034
  export function registerFileTools(server) {
989
1035
  server.registerTool('ssh_upload', {
990
- description: '上传本地文件到远程服务器',
1036
+ description: '上传本地文件到远程服务器。timeout 限制单个 SFTP 操作,超时后远端传输状态可能未知。',
991
1037
  inputSchema: uploadSchema,
992
1038
  }, (args) => handleUpload(args));
993
1039
  server.registerTool('ssh_download', {
994
- description: '从远程服务器下载文件',
1040
+ description: '从远程服务器下载文件。timeout 限制单个 SFTP 操作,超时后远端传输状态可能未知。',
995
1041
  inputSchema: downloadSchema,
996
1042
  }, (args) => handleDownload(args));
997
1043
  server.registerTool('ssh_read_file', {
998
- description: '读取远程文件内容',
1044
+ description: '读取远程文件内容。文本读取只返回完整 UTF-8 字符;后续读取使用响应中的 next_offset。',
999
1045
  inputSchema: readFileSchema,
1000
1046
  }, (args) => handleReadFile(args));
1001
1047
  server.registerTool('ssh_write_file', {
1002
- description: '写入内容到远程文件',
1048
+ description: '写入内容到远程文件。timeout 限制单个 SFTP 操作,超时后远端写入状态可能未知。',
1003
1049
  inputSchema: writeFileSchema,
1004
1050
  }, (args) => handleWriteFile(args));
1005
1051
  server.registerTool('ssh_list_dir', {
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { z } from 'zod';
7
7
  import { sessionManager } from '../session-manager.js';
8
+ import { dynamicSshPortSchema, sshPortSchema } from './schema.js';
8
9
  import { formatError, formatResult } from './utils.js';
9
10
  // ========== Schemas ==========
10
11
  // 仅允许 loopback 地址监听,防止把端口暴露到外网
@@ -16,16 +17,16 @@ const loopbackHostSchema = z
16
17
  .default('127.0.0.1');
17
18
  const forwardLocalSchema = z.object({
18
19
  alias: z.string().describe('连接别名'),
19
- localPort: z.number().describe('本地监听端口'),
20
+ localPort: dynamicSshPortSchema.describe('本地监听端口,传 0 时由系统动态分配'),
20
21
  remoteHost: z.string().describe('远程目标主机'),
21
- remotePort: z.number().describe('远程目标端口'),
22
+ remotePort: sshPortSchema.describe('远程目标端口'),
22
23
  localHost: loopbackHostSchema.describe('本地监听地址,仅允许 loopback(127.0.0.1 / ::1 / localhost),默认 127.0.0.1'),
23
24
  });
24
25
  const forwardRemoteSchema = z.object({
25
26
  alias: z.string().describe('连接别名'),
26
- remotePort: z.number().int().min(0).max(65535).describe('远程监听端口,传 0 时由服务器动态分配'),
27
+ remotePort: dynamicSshPortSchema.describe('远程监听端口,传 0 时由服务器动态分配'),
27
28
  localHost: z.string().describe('本地目标地址'),
28
- localPort: z.number().describe('本地目标端口'),
29
+ localPort: sshPortSchema.describe('本地目标端口'),
29
30
  remoteHost: loopbackHostSchema.describe('远程监听地址,仅允许 loopback(127.0.0.1 / ::1 / localhost),默认 127.0.0.1'),
30
31
  });
31
32
  const forwardCloseSchema = z.object({
@@ -124,7 +125,7 @@ export function registerForwardTools(server) {
124
125
  inputSchema: forwardCloseSchema,
125
126
  }, (args) => handleForwardClose(args));
126
127
  server.registerTool('ssh_forward_list', {
127
- description: '列出所有端口转发',
128
+ description: '列出所有端口转发,lifecycle 和 acceptingConnections 表示当前关闭与接流量状态。',
128
129
  inputSchema: forwardListSchema,
129
130
  }, () => handleForwardList());
130
131
  }