@pyrokine/mcp-ssh 2.0.2 → 2.1.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,252 @@ 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
+ throw new Error(renameError);
297
+ }
298
+ }
299
+ return formatResult({
300
+ ...uploadResult,
301
+ message: `Uploaded to ${args.remotePath}`,
302
+ atomic: args.atomic === true,
303
+ suggestion: largeFileSuggestion,
304
+ recommendedSync,
305
+ diagnostics: {
306
+ local: summarizeLocalPathProbe(local),
307
+ remoteParent,
308
+ atomic: args.atomic === true,
309
+ },
310
+ verification: await buildUploadVerification(args, local),
311
+ });
65
312
  }
66
313
  catch (error) {
67
- return formatError(error);
314
+ if (args.atomic) {
315
+ await cleanupRemotePath(args.alias, tempRemotePath).catch(() => undefined);
316
+ }
317
+ return formatResult({
318
+ success: false,
319
+ error: error instanceof Error ? error.message : String(error),
320
+ diagnostics: {
321
+ local: summarizeLocalPathProbe(local),
322
+ remoteParent,
323
+ atomic: args.atomic === true,
324
+ },
325
+ });
68
326
  }
69
327
  }
70
328
  async function handleDownload(args) {
@@ -73,12 +331,25 @@ async function handleDownload(args) {
73
331
  return formatResult({ ...downloadResult, message: `Downloaded to ${args.localPath}` });
74
332
  }
75
333
  catch (error) {
76
- return formatError(error);
334
+ return formatResult({
335
+ success: false,
336
+ error: error instanceof Error ? error.message : String(error),
337
+ diagnostics: {
338
+ local: summarizeLocalPathProbe(fileOps.probeLocalPath(args.localPath)),
339
+ localParent: summarizeLocalPathProbe(fileOps.probeLocalPath(path.dirname(args.localPath))),
340
+ remoteParent: await probeRemoteParent(args.alias, args.remotePath),
341
+ },
342
+ });
77
343
  }
78
344
  }
79
345
  async function handleReadFile(args) {
80
346
  try {
81
- const readResult = await fileOps.readFile(args.alias, args.remotePath, args.maxBytes);
347
+ const readResult = await fileOps.readFile(args.alias, args.remotePath, {
348
+ maxBytes: args.maxBytes,
349
+ offset: args.offset,
350
+ tail: args.tail,
351
+ lineRange: args.lineRange,
352
+ });
82
353
  return formatResult({ success: true, ...readResult });
83
354
  }
84
355
  catch (error) {
@@ -127,6 +398,10 @@ async function handleMkdir(args) {
127
398
  }
128
399
  }
129
400
  async function handleSync(args) {
401
+ const diagnostics = {
402
+ local: summarizeLocalPathProbe(fileOps.probeLocalPath(args.localPath)),
403
+ remoteParent: await probeRemoteParent(args.alias, args.remotePath),
404
+ };
130
405
  try {
131
406
  const syncResult = await fileOps.syncFiles(args.alias, args.localPath, args.remotePath, args.direction, {
132
407
  delete: args.delete,
@@ -140,10 +415,15 @@ async function handleSync(args) {
140
415
  direction: args.direction,
141
416
  localPath: args.localPath,
142
417
  remotePath: args.remotePath,
418
+ diagnostics,
143
419
  });
144
420
  }
145
421
  catch (error) {
146
- return formatError(error);
422
+ return formatResult({
423
+ success: false,
424
+ error: error instanceof Error ? error.message : String(error),
425
+ diagnostics,
426
+ });
147
427
  }
148
428
  }
149
429
  // ========== 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
@@ -10,6 +10,9 @@ export interface SSHConnectionConfig {
10
10
  privateKey?: string;
11
11
  passphrase?: string;
12
12
  alias?: string;
13
+ template?: string;
14
+ runAs?: string;
15
+ defaultEnv?: Record<string, string>;
13
16
  keepaliveInterval?: number;
14
17
  keepaliveCountMax?: number;
15
18
  readyTimeout?: number;
@@ -20,9 +23,13 @@ export interface SSHConnectionConfig {
20
23
  }
21
24
  export interface SSHSessionInfo {
22
25
  alias: string;
26
+ identity: string;
23
27
  host: string;
24
28
  port: number;
25
29
  username: string;
30
+ runAs?: string;
31
+ keyPath?: string;
32
+ authMethod: 'key' | 'password' | 'agent';
26
33
  connected: boolean;
27
34
  connectedAt: number;
28
35
  lastUsedAt: number;
@@ -36,6 +43,10 @@ export interface ExecOptions {
36
43
  rows?: number;
37
44
  cols?: number;
38
45
  term?: string;
46
+ runAs?: string;
47
+ useLoginUser?: boolean;
48
+ loadProfile?: boolean;
49
+ skipSessionEnv?: boolean;
39
50
  }
40
51
  export interface ExecResult {
41
52
  success: boolean;
@@ -43,6 +54,27 @@ export interface ExecResult {
43
54
  stderr: string;
44
55
  exitCode: number;
45
56
  duration: number;
57
+ failureKind?: 'remote_command' | 'ssh_transport' | 'timeout';
58
+ stdoutTruncated?: boolean;
59
+ stderrTruncated?: boolean;
60
+ maxOutputSize?: number;
61
+ stdoutHead?: string;
62
+ stdoutTail?: string;
63
+ stderrHead?: string;
64
+ stderrTail?: string;
65
+ stdoutBytes?: number;
66
+ stderrBytes?: number;
67
+ recommendedReadCommand?: string;
68
+ suggestion?: string;
69
+ loginUser?: string;
70
+ effectiveUser?: string;
71
+ identity?: string;
72
+ cwd?: string;
73
+ resolvedCwd?: string;
74
+ shell?: string;
75
+ profileLoaded?: boolean;
76
+ envInjectedKeys?: string[];
77
+ timedOut?: boolean;
46
78
  }
47
79
  export interface FileInfo {
48
80
  name: string;
@@ -67,6 +99,7 @@ export interface PersistedSession {
67
99
  host: string;
68
100
  port: number;
69
101
  username: string;
102
+ runAs?: string;
70
103
  connectedAt: number;
71
104
  }
72
105
  export interface PtyOptions {
@@ -84,8 +117,13 @@ export interface PtySessionInfo {
84
117
  rows: number;
85
118
  cols: number;
86
119
  createdAt: number;
120
+ lastInputAt: number | null;
121
+ lastOutputAt: number | null;
87
122
  lastReadAt: number;
88
123
  bufferSize: number;
124
+ unreadRawBytes: number;
125
+ rawBufferLimit: number;
126
+ foregroundProcess: string;
89
127
  active: boolean;
90
128
  }
91
129
  export type ForwardType = 'local' | 'remote';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyrokine/mcp-ssh",
3
- "version": "2.0.2",
3
+ "version": "2.1.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.1",
43
43
  "@types/ssh2": "^1.15.5",
44
- "eslint": "9.26.0",
44
+ "eslint": "^10.4.0",
45
45
  "prettier": "^3.8.3",
46
- "typescript": "^5.9.3",
47
- "typescript-eslint": "^8.59.0"
46
+ "typescript": "^6.0.3",
47
+ "typescript-eslint": "^8.60.0"
48
48
  },
49
49
  "engines": {
50
50
  "node": ">=18.0.0"