@pyrokine/mcp-ssh 2.0.2 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,14 +4,24 @@
4
4
  * ssh_upload, ssh_download, ssh_read_file, ssh_write_file,
5
5
  * ssh_list_dir, ssh_file_info, ssh_mkdir, ssh_sync
6
6
  */
7
+ import { createHash } from 'crypto';
8
+ import * as fs from 'fs';
9
+ import * as path from 'path';
7
10
  import { z } from 'zod';
8
11
  import * as fileOps from '../file-ops.js';
9
- import { formatError, formatResult } from './utils.js';
12
+ import { sessionManager } from '../session-manager.js';
13
+ import { escapeShellArg, formatError, formatResult } from './utils.js';
10
14
  // ========== Schemas ==========
11
15
  const uploadSchema = z.object({
12
16
  alias: z.string().describe('连接别名'),
13
17
  localPath: z.string().describe('本地文件路径'),
14
18
  remotePath: z.string().describe('远程目标路径'),
19
+ atomic: z.boolean().optional().describe('是否先上传到同目录临时文件,校验后 rename 到目标路径'),
20
+ verifyOwner: z.union([z.string(), z.number()]).optional().describe('上传后校验远端 owner(用户名或 uid)'),
21
+ verifyMode: z.string().optional().describe('上传后校验远端权限,例如 0644 或 -rw-r--r--'),
22
+ verifyMd5: z.boolean().optional().describe('上传后比对本地和远端 MD5'),
23
+ verifySize: z.boolean().optional().describe('上传后校验文件大小'),
24
+ verifyMtime: z.boolean().optional().describe('上传后返回并比较本地和远端 mtime'),
15
25
  });
16
26
  const downloadSchema = z.object({
17
27
  alias: z.string().describe('连接别名'),
@@ -21,7 +31,16 @@ const downloadSchema = z.object({
21
31
  const readFileSchema = z.object({
22
32
  alias: z.string().describe('连接别名'),
23
33
  remotePath: z.string().describe('远程文件路径'),
24
- maxBytes: z.number().optional().describe('最大读取字节数,默认 1MB'),
34
+ maxBytes: z
35
+ .number()
36
+ .int()
37
+ .positive()
38
+ .max(fileOps.HARD_READ_FILE_MAX_BYTES)
39
+ .optional()
40
+ .describe('最大读取字节数,默认 1MB,最大 16MB'),
41
+ offset: z.number().optional().describe('从指定字节偏移开始读取,与 tail/lineRange 互斥'),
42
+ tail: z.boolean().optional().describe('读取文件尾部 maxBytes 字节,与 offset/lineRange 互斥'),
43
+ lineRange: z.string().optional().describe('按行号读取,格式为 "start-end" 或 "start",与 offset/tail 互斥'),
25
44
  });
26
45
  const writeFileSchema = z.object({
27
46
  alias: z.string().describe('连接别名'),
@@ -58,13 +77,261 @@ const syncSchema = z.object({
58
77
  .describe('upload 时是否跟随本地 symlink,默认 false(跳过 symlink 并 warn,避免上传链接目标内容)'),
59
78
  });
60
79
  // ========== Handlers ==========
80
+ const LARGE_UPLOAD_THRESHOLD = 100 * 1024 * 1024;
81
+ function summarizeLocalPathProbe(probe) {
82
+ const summary = {
83
+ exists: probe.exists,
84
+ allowList: probe.allowList,
85
+ };
86
+ if ('size' in probe) {
87
+ summary.size = probe.size;
88
+ }
89
+ if ('mode' in probe) {
90
+ summary.mode = probe.mode;
91
+ }
92
+ if ('mtimeMs' in probe) {
93
+ summary.mtimeMs = probe.mtimeMs;
94
+ }
95
+ if ('isSymlink' in probe) {
96
+ summary.isSymlink = probe.isSymlink;
97
+ }
98
+ if ('isDirectory' in probe) {
99
+ summary.isDirectory = probe.isDirectory;
100
+ }
101
+ if ('isFile' in probe) {
102
+ summary.isFile = probe.isFile;
103
+ }
104
+ return summary;
105
+ }
106
+ function uploadPathError(code, message, diagnostics) {
107
+ return formatResult({
108
+ success: false,
109
+ code,
110
+ error: message,
111
+ diagnostics,
112
+ });
113
+ }
114
+ async function probeRemoteParent(alias, remotePath) {
115
+ const parent = path.posix.dirname(remotePath);
116
+ const escapedParent = escapeShellArg(parent);
117
+ const command = [
118
+ `if [ -d ${escapedParent} ]; then`,
119
+ `if [ -w ${escapedParent} ]; then printf writable; else printf not-writable; fi;`,
120
+ 'else printf missing; fi',
121
+ ].join(' ');
122
+ try {
123
+ const result = await sessionManager.exec(alias, command, {
124
+ timeout: 10000,
125
+ useLoginUser: true,
126
+ maxOutputSize: 4096,
127
+ });
128
+ const status = result.stdout.trim();
129
+ return { exists: status !== 'missing', writable: status === 'writable' };
130
+ }
131
+ catch (error) {
132
+ return { error: error instanceof Error ? error.message : String(error) };
133
+ }
134
+ }
135
+ function hashLocalFileMd5(filePath) {
136
+ return new Promise((resolve, reject) => {
137
+ const hash = createHash('md5');
138
+ const stream = fs.createReadStream(filePath);
139
+ stream.on('data', (chunk) => hash.update(chunk));
140
+ stream.on('error', reject);
141
+ stream.on('end', () => resolve(hash.digest('hex')));
142
+ });
143
+ }
144
+ async function hashRemoteFileMd5(alias, remotePath) {
145
+ const result = await sessionManager.exec(alias, `md5sum ${escapeShellArg(remotePath)} | awk '{print $1}'`, {
146
+ timeout: 30000,
147
+ useLoginUser: true,
148
+ maxOutputSize: 4096,
149
+ });
150
+ const digest = result.stdout.trim().split(/\s+/)[0];
151
+ return /^[a-fA-F0-9]{32}$/.test(digest) ? digest : undefined;
152
+ }
153
+ function permissionStringToOctal(permissions) {
154
+ const bits = permissions.slice(-9);
155
+ if (bits.length !== 9) {
156
+ return undefined;
157
+ }
158
+ const values = [bits.slice(0, 3), bits.slice(3, 6), bits.slice(6, 9)].map((part) => {
159
+ let value = 0;
160
+ if (part[0] === 'r') {
161
+ value += 4;
162
+ }
163
+ if (part[1] === 'w') {
164
+ value += 2;
165
+ }
166
+ if (part[2] === 'x' || part[2] === 's' || part[2] === 't') {
167
+ value += 1;
168
+ }
169
+ return value;
170
+ });
171
+ return `0${values.join('')}`;
172
+ }
173
+ async function probeRemoteFile(alias, remotePath) {
174
+ const escapedRemotePath = escapeShellArg(remotePath);
175
+ const command = [
176
+ `if [ -e ${escapedRemotePath} ]; then`,
177
+ `stat -c '%U\t%u\t%G\t%g\t%a\t%s\t%Y' ${escapedRemotePath};`,
178
+ 'else printf missing; fi',
179
+ ].join(' ');
180
+ try {
181
+ const result = await sessionManager.exec(alias, command, {
182
+ timeout: 10000,
183
+ useLoginUser: true,
184
+ maxOutputSize: 4096,
185
+ });
186
+ if (result.stdout.trim() === 'missing') {
187
+ return { exists: false, remotePath };
188
+ }
189
+ const [ownerName, ownerId, groupName, groupId, mode, size, mtimeSeconds] = result.stdout.trim().split('\t');
190
+ return {
191
+ exists: true,
192
+ remotePath,
193
+ ownerName,
194
+ ownerId: Number(ownerId),
195
+ groupName,
196
+ groupId: Number(groupId),
197
+ mode: mode ? `0${mode}` : undefined,
198
+ size: Number(size),
199
+ mtimeMs: Number(mtimeSeconds) * 1000,
200
+ };
201
+ }
202
+ catch {
203
+ const info = await fileOps.getFileInfo(alias, remotePath);
204
+ return {
205
+ exists: true,
206
+ remotePath,
207
+ ownerId: info.owner,
208
+ groupId: info.group,
209
+ mode: permissionStringToOctal(info.permissions),
210
+ permissions: info.permissions,
211
+ size: info.size,
212
+ mtimeMs: info.mtime.getTime(),
213
+ };
214
+ }
215
+ }
216
+ async function buildUploadVerification(args, local) {
217
+ const remote = await probeRemoteFile(args.alias, args.remotePath);
218
+ const checks = {};
219
+ if (args.verifySize) {
220
+ checks.size = local.exists && remote.exists ? local.size === remote.size : false;
221
+ }
222
+ if (args.verifyMtime) {
223
+ const mtimeDelta = local.exists && remote.exists ? Math.abs((local.mtimeMs ?? 0) - (remote.mtimeMs ?? 0)) : undefined;
224
+ checks.mtime = mtimeDelta !== undefined ? mtimeDelta < 2000 : false;
225
+ }
226
+ if (args.verifyMode && remote.exists) {
227
+ checks.mode = remote.mode === args.verifyMode || remote.mode === args.verifyMode.replace(/^0?/, '0');
228
+ }
229
+ if (args.verifyOwner && remote.exists) {
230
+ const expectedOwner = String(args.verifyOwner);
231
+ checks.owner = String(remote.ownerId) === expectedOwner || remote.ownerName === expectedOwner;
232
+ }
233
+ if (args.verifyMd5 && local.exists) {
234
+ const [localMd5, remoteMd5] = await Promise.all([
235
+ hashLocalFileMd5(local.resolvedPath),
236
+ hashRemoteFileMd5(args.alias, args.remotePath),
237
+ ]);
238
+ checks.md5 = remoteMd5 ? localMd5 === remoteMd5 : undefined;
239
+ return {
240
+ local: { ...summarizeLocalPathProbe(local), md5: localMd5 },
241
+ remote: { ...remote, md5: remoteMd5 },
242
+ checks,
243
+ };
244
+ }
245
+ return { local: summarizeLocalPathProbe(local), remote, checks };
246
+ }
247
+ async function cleanupRemotePath(alias, remotePath) {
248
+ await sessionManager.exec(alias, `rm -f ${escapeShellArg(remotePath)}`, {
249
+ timeout: 10000,
250
+ useLoginUser: true,
251
+ maxOutputSize: 4096,
252
+ });
253
+ }
254
+ async function applyRemoteMode(alias, remotePath, mode) {
255
+ const result = await sessionManager.exec(alias, `chmod ${escapeShellArg(mode)} ${escapeShellArg(remotePath)}`, {
256
+ timeout: 10000,
257
+ useLoginUser: true,
258
+ maxOutputSize: 4096,
259
+ });
260
+ if (!result.success) {
261
+ throw new Error(result.stderr || result.stdout || `chmod failed with exit code ${result.exitCode}`);
262
+ }
263
+ }
61
264
  async function handleUpload(args) {
265
+ const local = fileOps.probeLocalPath(args.localPath);
266
+ if (local.exists && local.isDirectory) {
267
+ return uploadPathError('UPLOAD_PATH_IS_DIRECTORY', 'localPath is a directory', {
268
+ local: summarizeLocalPathProbe(local),
269
+ suggestion: '使用 ssh_sync 上传目录,或把 localPath 指向具体文件',
270
+ });
271
+ }
272
+ const largeFileSuggestion = local.exists && typeof local.size === 'number' && local.size >= LARGE_UPLOAD_THRESHOLD
273
+ ? '大文件优先使用 ssh_sync,让 rsync 做增量传输'
274
+ : undefined;
275
+ const recommendedSync = largeFileSuggestion && local.exists
276
+ ? [
277
+ `ssh_sync(alias=${JSON.stringify(args.alias)}`,
278
+ `localPath=${JSON.stringify(args.localPath)}`,
279
+ `remotePath=${JSON.stringify(args.remotePath)}`,
280
+ 'direction="upload")',
281
+ ].join(', ')
282
+ : undefined;
283
+ const remoteParent = await probeRemoteParent(args.alias, args.remotePath);
284
+ const tempRemotePath = args.atomic
285
+ ? `${args.remotePath}.mcp-tmp-${process.pid}-${Date.now().toString(36)}`
286
+ : args.remotePath;
62
287
  try {
63
- const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, args.remotePath);
64
- return formatResult({ ...uploadResult, message: `Uploaded to ${args.remotePath}` });
288
+ const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath);
289
+ if (local.exists && 'mode' in local && typeof local.mode === 'string') {
290
+ await applyRemoteMode(args.alias, tempRemotePath, local.mode);
291
+ }
292
+ if (args.atomic) {
293
+ const rename = await sessionManager.exec(args.alias, `mv -f -- ${escapeShellArg(tempRemotePath)} ${escapeShellArg(args.remotePath)}`, { timeout: 30000, useLoginUser: true, maxOutputSize: 4096 });
294
+ if (!rename.success) {
295
+ const renameError = rename.stderr || rename.stdout || `atomic rename failed with exit code ${rename.exitCode}`;
296
+ await cleanupRemotePath(args.alias, tempRemotePath).catch(() => undefined);
297
+ return formatResult({
298
+ success: false,
299
+ error: renameError,
300
+ diagnostics: {
301
+ local: summarizeLocalPathProbe(local),
302
+ remoteParent,
303
+ atomic: true,
304
+ },
305
+ });
306
+ }
307
+ }
308
+ return formatResult({
309
+ ...uploadResult,
310
+ message: `Uploaded to ${args.remotePath}`,
311
+ atomic: args.atomic === true,
312
+ suggestion: largeFileSuggestion,
313
+ recommendedSync,
314
+ diagnostics: {
315
+ local: summarizeLocalPathProbe(local),
316
+ remoteParent,
317
+ atomic: args.atomic === true,
318
+ },
319
+ verification: await buildUploadVerification(args, local),
320
+ });
65
321
  }
66
322
  catch (error) {
67
- return formatError(error);
323
+ if (args.atomic) {
324
+ await cleanupRemotePath(args.alias, tempRemotePath).catch(() => undefined);
325
+ }
326
+ return formatResult({
327
+ success: false,
328
+ error: error instanceof Error ? error.message : String(error),
329
+ diagnostics: {
330
+ local: summarizeLocalPathProbe(local),
331
+ remoteParent,
332
+ atomic: args.atomic === true,
333
+ },
334
+ });
68
335
  }
69
336
  }
70
337
  async function handleDownload(args) {
@@ -73,12 +340,25 @@ async function handleDownload(args) {
73
340
  return formatResult({ ...downloadResult, message: `Downloaded to ${args.localPath}` });
74
341
  }
75
342
  catch (error) {
76
- return formatError(error);
343
+ return formatResult({
344
+ success: false,
345
+ error: error instanceof Error ? error.message : String(error),
346
+ diagnostics: {
347
+ local: summarizeLocalPathProbe(fileOps.probeLocalPath(args.localPath)),
348
+ localParent: summarizeLocalPathProbe(fileOps.probeLocalPath(path.dirname(args.localPath))),
349
+ remoteParent: await probeRemoteParent(args.alias, args.remotePath),
350
+ },
351
+ });
77
352
  }
78
353
  }
79
354
  async function handleReadFile(args) {
80
355
  try {
81
- const readResult = await fileOps.readFile(args.alias, args.remotePath, args.maxBytes);
356
+ const readResult = await fileOps.readFile(args.alias, args.remotePath, {
357
+ maxBytes: args.maxBytes,
358
+ offset: args.offset,
359
+ tail: args.tail,
360
+ lineRange: args.lineRange,
361
+ });
82
362
  return formatResult({ success: true, ...readResult });
83
363
  }
84
364
  catch (error) {
@@ -127,6 +407,10 @@ async function handleMkdir(args) {
127
407
  }
128
408
  }
129
409
  async function handleSync(args) {
410
+ const diagnostics = {
411
+ local: summarizeLocalPathProbe(fileOps.probeLocalPath(args.localPath)),
412
+ remoteParent: await probeRemoteParent(args.alias, args.remotePath),
413
+ };
130
414
  try {
131
415
  const syncResult = await fileOps.syncFiles(args.alias, args.localPath, args.remotePath, args.direction, {
132
416
  delete: args.delete,
@@ -140,10 +424,15 @@ async function handleSync(args) {
140
424
  direction: args.direction,
141
425
  localPath: args.localPath,
142
426
  remotePath: args.remotePath,
427
+ diagnostics,
143
428
  });
144
429
  }
145
430
  catch (error) {
146
- return formatError(error);
431
+ return formatResult({
432
+ success: false,
433
+ error: error instanceof Error ? error.message : String(error),
434
+ diagnostics,
435
+ });
147
436
  }
148
437
  }
149
438
  // ========== Register ==========
@@ -95,8 +95,8 @@ export function registerForwardTools(server) {
95
95
  本地监听指定端口,将连接转发到远程主机
96
96
 
97
97
  用途:访问远程内网服务
98
- 示例:ssh_forward_local(alias="server", localPort=8080, remoteHost="10.0.0.1", remotePort=80)
99
- 效果:访问本地 localhost:8080 会转发到远程内网的 10.0.0.1:80`,
98
+ 示例:ssh_forward_local(alias="server", localPort=8080, remoteHost="<service-host>", remotePort=80)
99
+ 效果:访问本地 localhost:8080 会转发到远程服务 <service-host>:80`,
100
100
  inputSchema: forwardLocalSchema,
101
101
  }, (args) => handleForwardLocal(args));
102
102
  server.registerTool('ssh_forward_remote', {
package/dist/tools/pty.js CHANGED
@@ -14,7 +14,7 @@ const ptyStartSchema = z.object({
14
14
  cols: z.number().optional().describe('终端列数,默认 80'),
15
15
  term: z.string().optional().describe('终端类型,默认 xterm-256color'),
16
16
  cwd: z.string().optional().describe('工作目录'),
17
- env: z.record(z.string()).optional().describe('环境变量'),
17
+ env: z.record(z.string(), z.string()).optional().describe('环境变量'),
18
18
  bufferSize: z.number().optional().describe('输出缓冲区大小(字节),默认 1MB'),
19
19
  });
20
20
  const ptyWriteSchema = z.object({
@@ -30,8 +30,16 @@ export function formatResult(data) {
30
30
  */
31
31
  export function formatError(error) {
32
32
  const message = error instanceof Error ? error.message : String(error);
33
+ const details = typeof error === 'object' && error !== null && 'details' in error
34
+ ? error.details
35
+ : undefined;
33
36
  return {
34
- content: [{ type: 'text', text: JSON.stringify({ success: false, error: message }, null, 2) }],
37
+ content: [
38
+ {
39
+ type: 'text',
40
+ text: JSON.stringify({ success: false, error: message, ...(details ? { details } : {}) }, null, 2),
41
+ },
42
+ ],
35
43
  isError: true,
36
44
  };
37
45
  }
package/dist/types.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * SSH MCP Pro - 类型定义
3
3
  */
4
+ export declare const DEFAULT_EXEC_MAX_OUTPUT_SIZE: number;
5
+ export declare const HARD_EXEC_MAX_OUTPUT_SIZE: number;
4
6
  export interface SSHConnectionConfig {
5
7
  host: string;
6
8
  port: number;
@@ -10,6 +12,9 @@ export interface SSHConnectionConfig {
10
12
  privateKey?: string;
11
13
  passphrase?: string;
12
14
  alias?: string;
15
+ template?: string;
16
+ runAs?: string;
17
+ defaultEnv?: Record<string, string>;
13
18
  keepaliveInterval?: number;
14
19
  keepaliveCountMax?: number;
15
20
  readyTimeout?: number;
@@ -20,9 +25,13 @@ export interface SSHConnectionConfig {
20
25
  }
21
26
  export interface SSHSessionInfo {
22
27
  alias: string;
28
+ identity: string;
23
29
  host: string;
24
30
  port: number;
25
31
  username: string;
32
+ runAs?: string;
33
+ keyPath?: string;
34
+ authMethod: 'key' | 'password' | 'agent';
26
35
  connected: boolean;
27
36
  connectedAt: number;
28
37
  lastUsedAt: number;
@@ -36,6 +45,10 @@ export interface ExecOptions {
36
45
  rows?: number;
37
46
  cols?: number;
38
47
  term?: string;
48
+ runAs?: string;
49
+ useLoginUser?: boolean;
50
+ loadProfile?: boolean;
51
+ skipSessionEnv?: boolean;
39
52
  }
40
53
  export interface ExecResult {
41
54
  success: boolean;
@@ -43,6 +56,27 @@ export interface ExecResult {
43
56
  stderr: string;
44
57
  exitCode: number;
45
58
  duration: number;
59
+ failureKind?: 'remote_command' | 'ssh_transport' | 'timeout';
60
+ stdoutTruncated?: boolean;
61
+ stderrTruncated?: boolean;
62
+ maxOutputSize?: number;
63
+ stdoutHead?: string;
64
+ stdoutTail?: string;
65
+ stderrHead?: string;
66
+ stderrTail?: string;
67
+ stdoutBytes?: number;
68
+ stderrBytes?: number;
69
+ recommendedReadCommand?: string;
70
+ suggestion?: string;
71
+ loginUser?: string;
72
+ effectiveUser?: string;
73
+ identity?: string;
74
+ cwd?: string;
75
+ resolvedCwd?: string;
76
+ shell?: string;
77
+ profileLoaded?: boolean;
78
+ envInjectedKeys?: string[];
79
+ timedOut?: boolean;
46
80
  }
47
81
  export interface FileInfo {
48
82
  name: string;
@@ -67,6 +101,7 @@ export interface PersistedSession {
67
101
  host: string;
68
102
  port: number;
69
103
  username: string;
104
+ runAs?: string;
70
105
  connectedAt: number;
71
106
  }
72
107
  export interface PtyOptions {
@@ -84,8 +119,13 @@ export interface PtySessionInfo {
84
119
  rows: number;
85
120
  cols: number;
86
121
  createdAt: number;
122
+ lastInputAt: number | null;
123
+ lastOutputAt: number | null;
87
124
  lastReadAt: number;
88
125
  bufferSize: number;
126
+ unreadRawBytes: number;
127
+ rawBufferLimit: number;
128
+ foregroundProcess: string;
89
129
  active: boolean;
90
130
  }
91
131
  export type ForwardType = 'local' | 'remote';
package/dist/types.js CHANGED
@@ -1,4 +1,5 @@
1
1
  /**
2
2
  * SSH MCP Pro - 类型定义
3
3
  */
4
- export {};
4
+ export const DEFAULT_EXEC_MAX_OUTPUT_SIZE = 10 * 1024 * 1024;
5
+ export const HARD_EXEC_MAX_OUTPUT_SIZE = 50 * 1024 * 1024;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyrokine/mcp-ssh",
3
- "version": "2.0.2",
3
+ "version": "2.2.0",
4
4
  "description": "A comprehensive SSH MCP Server for Claude Code",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -35,16 +35,16 @@
35
35
  "@modelcontextprotocol/sdk": "^1.29.0",
36
36
  "@xterm/headless": "^6.0.0",
37
37
  "ssh2": "^1.17.0",
38
- "zod": "^3.25.76"
38
+ "zod": "^4.4.3"
39
39
  },
40
40
  "devDependencies": {
41
- "@eslint/js": "^9.39.4",
42
- "@types/node": "^25.0.9",
41
+ "@eslint/js": "^10.0.1",
42
+ "@types/node": "^25.9.3",
43
43
  "@types/ssh2": "^1.15.5",
44
- "eslint": "9.26.0",
45
- "prettier": "^3.8.3",
46
- "typescript": "^5.9.3",
47
- "typescript-eslint": "^8.59.0"
44
+ "eslint": "^10.5.0",
45
+ "prettier": "^3.8.4",
46
+ "typescript": "^6.0.3",
47
+ "typescript-eslint": "^8.61.0"
48
48
  },
49
49
  "engines": {
50
50
  "node": ">=18.0.0"