@pyrokine/mcp-ssh 2.3.0 → 2.3.2

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 CHANGED
@@ -5,7 +5,7 @@ English | [中文](README_zh.md)
5
5
  SSH MCP Server for AI assistants (Claude, Cursor, Windsurf, etc.)
6
6
 
7
7
  [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
8
- [![Node](https://img.shields.io/badge/node-%3E%3D18-green.svg)](https://nodejs.org/)
8
+ [![Node](https://img.shields.io/badge/node-%3E%3D20.19-green.svg)](https://nodejs.org/)
9
9
  [![MCP](https://img.shields.io/badge/MCP-compatible-purple.svg)](https://modelcontextprotocol.io/)
10
10
 
11
11
  ![Linux](https://img.shields.io/badge/Linux-tested-success)
@@ -48,10 +48,13 @@ SSH MCP Server for AI assistants (Claude, Cursor, Windsurf, etc.)
48
48
 
49
49
  ## Installation
50
50
 
51
+ Requires Node.js 20.19 or newer.
52
+
51
53
  ### npm (Recommended)
52
54
 
53
55
  ```bash
54
56
  npm install -g @pyrokine/mcp-ssh
57
+ claude mcp add ssh -- mcp-ssh
55
58
  ```
56
59
 
57
60
  ### From Source
@@ -61,6 +64,7 @@ git clone https://github.com/Pyrokine/claude-tools.git
61
64
  cd claude-tools/mcp-ssh
62
65
  npm install
63
66
  npm run build
67
+ claude mcp add ssh -- node "$PWD/dist/index.js"
64
68
  ```
65
69
 
66
70
  ## Configuration
@@ -68,6 +72,10 @@ npm run build
68
72
  ### Claude Code
69
73
 
70
74
  ```bash
75
+ # npm installation
76
+ claude mcp add ssh -- mcp-ssh
77
+
78
+ # source build
71
79
  claude mcp add ssh -- node /path/to/mcp-ssh/dist/index.js
72
80
  ```
73
81
 
package/README_zh.md CHANGED
@@ -5,7 +5,7 @@
5
5
  一个功能完善的 SSH MCP 服务器,适用于 AI 助手(Claude、Cursor、Windsurf 等)
6
6
 
7
7
  [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
8
- [![Node](https://img.shields.io/badge/node-%3E%3D18-green.svg)](https://nodejs.org/)
8
+ [![Node](https://img.shields.io/badge/node-%3E%3D20.19-green.svg)](https://nodejs.org/)
9
9
  [![MCP](https://img.shields.io/badge/MCP-compatible-purple.svg)](https://modelcontextprotocol.io/)
10
10
 
11
11
  ![Linux](https://img.shields.io/badge/Linux-tested-success)
@@ -48,10 +48,13 @@
48
48
 
49
49
  ## 安装
50
50
 
51
+ 需要 Node.js 20.19 或更新版本。
52
+
51
53
  ### npm(推荐)
52
54
 
53
55
  ```bash
54
56
  npm install -g @pyrokine/mcp-ssh
57
+ claude mcp add ssh -- mcp-ssh
55
58
  ```
56
59
 
57
60
  ### 从源码安装
@@ -61,6 +64,7 @@ git clone https://github.com/Pyrokine/claude-tools.git
61
64
  cd claude-tools/mcp-ssh
62
65
  npm install
63
66
  npm run build
67
+ claude mcp add ssh -- node "$PWD/dist/index.js"
64
68
  ```
65
69
 
66
70
  ## 配置
@@ -68,6 +72,10 @@ npm run build
68
72
  ### Claude Code
69
73
 
70
74
  ```bash
75
+ # npm 安装
76
+ claude mcp add ssh -- mcp-ssh
77
+
78
+ # 源码构建
71
79
  claude mcp add ssh -- node /path/to/mcp-ssh/dist/index.js
72
80
  ```
73
81
 
package/dist/file-ops.js CHANGED
@@ -336,13 +336,21 @@ export async function downloadFile(alias, remotePath, localPath, onProgress, sha
336
336
  localPath = expandTilde(localPath);
337
337
  validateLocalPathAgainstAllowList(localPath);
338
338
  const sftp = sharedSftp ?? (await sessionManager.getSftp(alias));
339
- const totalSize = (await sftpStat(sftp, remotePath)).size;
340
- // 确保本地目录存在
341
- const localDir = path.dirname(localPath);
342
- if (!fs.existsSync(localDir)) {
343
- fs.mkdirSync(localDir, { recursive: true });
339
+ try {
340
+ const totalSize = (await sftpStat(sftp, remotePath)).size;
341
+ // 确保本地目录存在
342
+ const localDir = path.dirname(localPath);
343
+ if (!fs.existsSync(localDir)) {
344
+ fs.mkdirSync(localDir, { recursive: true });
345
+ }
346
+ return await pipeWithProgress(sftp.createReadStream(remotePath), fs.createWriteStream(localPath), sftp, totalSize, onProgress, !sharedSftp);
347
+ }
348
+ catch (error) {
349
+ if (!sharedSftp) {
350
+ sftp.end();
351
+ }
352
+ throw error;
344
353
  }
345
- return pipeWithProgress(sftp.createReadStream(remotePath), fs.createWriteStream(localPath), sftp, totalSize, onProgress, !sharedSftp);
346
354
  }
347
355
  export const DEFAULT_READ_FILE_MAX_BYTES = 1024 * 1024;
348
356
  export const HARD_READ_FILE_MAX_BYTES = 16 * 1024 * 1024;
@@ -393,21 +401,29 @@ function emptyReadResult(totalSize, sampleKind, readOffset = 0) {
393
401
  }
394
402
  async function readLineRange(alias, remotePath, totalSize, maxBytes, lineRange) {
395
403
  const { start, end } = parseLineRange(lineRange);
396
- const command = [
397
- `awk 'NR>=${start} && NR<=${end} { print } NR>${end} { exit }'`,
398
- escapeShellArg(remotePath),
399
- '|',
400
- 'head',
401
- '-c',
402
- String(maxBytes),
404
+ const awkProgram = [
405
+ 'BEGIN { written = 0 }',
406
+ `NR>=${start} && NR<=${end} {`,
407
+ 'line = $0 "\\n"',
408
+ 'remaining = max - written',
409
+ 'if (remaining <= 0) { exit }',
410
+ 'if (length(line) > remaining) { printf "%s", substr(line, 1, remaining); exit }',
411
+ 'printf "%s", line',
412
+ 'written += length(line)',
413
+ '}',
414
+ `NR>${end} { exit }`,
403
415
  ].join(' ');
416
+ const command = `LC_ALL=C awk -v max=${maxBytes} ${escapeShellArg(awkProgram)} ${escapeShellArg(remotePath)}`;
404
417
  const result = await sessionManager.exec(alias, command, {
405
418
  timeout: 30000,
406
419
  useLoginUser: true,
407
420
  maxOutputSize: maxBytes + 4096,
408
421
  });
409
- if (!result.success && result.stderr.trim().length > 0) {
410
- throw new Error(result.stderr.trim());
422
+ if (!result.success) {
423
+ const message = result.stderr.trim() ||
424
+ result.stdout.trim() ||
425
+ `remote lineRange command failed with exit code ${result.exitCode}`;
426
+ throw new Error(message);
411
427
  }
412
428
  const readBytes = Buffer.byteLength(result.stdout, 'utf-8');
413
429
  return {
@@ -430,7 +446,14 @@ export async function readFile(alias, remotePath, options) {
430
446
  const readOptions = normalizeReadFileOptions(options);
431
447
  validateReadFileOptions(readOptions);
432
448
  const sftp = await sessionManager.getSftp(alias);
433
- const actualSize = (await sftpStat(sftp, remotePath)).size;
449
+ let actualSize;
450
+ try {
451
+ actualSize = (await sftpStat(sftp, remotePath)).size;
452
+ }
453
+ catch (error) {
454
+ sftp.end();
455
+ throw error;
456
+ }
434
457
  if (readOptions.lineRange) {
435
458
  sftp.end();
436
459
  return readLineRange(alias, remotePath, actualSize, readOptions.maxBytes, readOptions.lineRange);
@@ -490,17 +513,18 @@ export async function readFile(alias, remotePath, options) {
490
513
  export async function writeFile(alias, remotePath, content, append = false) {
491
514
  const sftp = await sessionManager.getSftp(alias);
492
515
  const flags = append ? 'a' : 'w';
516
+ const contentBuffer = Buffer.from(content, 'utf-8');
493
517
  return new Promise((resolve, reject) => {
494
518
  const writeStream = sftp.createWriteStream(remotePath, { flags });
495
519
  writeStream.on('close', () => {
496
520
  sftp.end();
497
- resolve({ success: true, size: content.length });
521
+ resolve({ success: true, size: contentBuffer.length });
498
522
  });
499
523
  writeStream.on('error', (err) => {
500
524
  sftp.end();
501
525
  reject(err);
502
526
  });
503
- writeStream.write(content);
527
+ writeStream.write(contentBuffer);
504
528
  writeStream.end();
505
529
  });
506
530
  }
@@ -927,6 +951,7 @@ async function syncWithSftp(alias, localPath, remotePath, direction, options) {
927
951
  recursive: options.recursive !== false,
928
952
  followSymlinks: options.followSymlinks === true,
929
953
  deleteRequested: options.delete === true,
954
+ deleteSupported: options.delete ? false : undefined,
930
955
  excludeCount: options.exclude?.length ?? 0,
931
956
  localExists,
932
957
  localIsDirectory: localStats?.isDirectory(),
@@ -938,6 +963,14 @@ async function syncWithSftp(alias, localPath, remotePath, direction, options) {
938
963
  (warnings.length ? `. Warning: ${warnings.join('; ')}` : ''),
939
964
  };
940
965
  }
966
+ if (options.delete) {
967
+ return {
968
+ success: false,
969
+ method: 'sftp',
970
+ stats: { added: 0, updated: 0, deleted: 0, skipped: 0, failed: 1 },
971
+ output: 'delete option is not supported in SFTP mode (requires rsync)',
972
+ };
973
+ }
941
974
  try {
942
975
  if (direction === 'upload') {
943
976
  const stats = options.followSymlinks ? fs.statSync(localPath) : fs.lstatSync(localPath);
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import type { ClientChannel } from 'ssh2';
7
7
  import type { PtyOptions, PtySessionInfo } from './types.js';
8
+ export declare const HARD_PTY_BUFFER_SIZE: number;
8
9
  /** PTY 创建所需的外部依赖 */
9
10
  export interface PtyDependencies {
10
11
  /** 通过 alias 获取 SSH client 并执行命令 */
@@ -39,6 +40,7 @@ export declare class PtyManager {
39
40
  /** 关闭指定 alias 的所有 PTY 会话 */
40
41
  closeByAlias(alias: string): void;
41
42
  list(): PtySessionInfo[];
43
+ private normalizeBufferSize;
42
44
  private startIdleSweeper;
43
45
  private sweepIdle;
44
46
  private getSession;
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import xterm from '@xterm/headless';
7
7
  const Terminal = xterm.Terminal;
8
+ export const HARD_PTY_BUFFER_SIZE = 16 * 1024 * 1024;
8
9
  export class PtyManager {
9
10
  sessions = new Map();
10
11
  idCounter = 0;
@@ -19,7 +20,7 @@ export class PtyManager {
19
20
  const ptyId = this.generateId();
20
21
  const rows = options.rows || 24;
21
22
  const cols = options.cols || 80;
22
- const maxBufferSize = options.bufferSize || this.defaultBufferSize;
23
+ const maxBufferSize = this.normalizeBufferSize(options.bufferSize);
23
24
  const stream = await deps.execPty(alias, command, options);
24
25
  // 创建 xterm headless 终端仿真器
25
26
  const terminal = new Terminal({ rows, cols, allowProposedApi: true });
@@ -173,6 +174,15 @@ export class PtyManager {
173
174
  }
174
175
  return result;
175
176
  }
177
+ normalizeBufferSize(bufferSize) {
178
+ if (bufferSize === undefined) {
179
+ return this.defaultBufferSize;
180
+ }
181
+ if (!Number.isSafeInteger(bufferSize) || bufferSize <= 0 || bufferSize > HARD_PTY_BUFFER_SIZE) {
182
+ throw new Error(`bufferSize 必须是 1 到 ${HARD_PTY_BUFFER_SIZE} 之间的整数`);
183
+ }
184
+ return bufferSize;
185
+ }
176
186
  startIdleSweeper() {
177
187
  if (this.idleSweeper) {
178
188
  return;
@@ -438,6 +438,7 @@ export class SessionManager {
438
438
  let stdoutTruncated = false;
439
439
  let stderrTruncated = false;
440
440
  let settled = false;
441
+ let activeStream = null;
441
442
  const execOptions = {};
442
443
  if (options.pty) {
443
444
  execOptions.pty = {
@@ -446,39 +447,51 @@ export class SessionManager {
446
447
  term: options.term || 'xterm-256color',
447
448
  };
448
449
  }
450
+ const outputPreview = () => ({
451
+ stdout,
452
+ stderr,
453
+ stdoutTail,
454
+ stderrTail,
455
+ stdoutBytes,
456
+ stderrBytes,
457
+ stdoutTruncated,
458
+ stderrTruncated,
459
+ maxOutputSize,
460
+ });
461
+ const clearTimer = () => {
462
+ if (timeoutId) {
463
+ clearTimeout(timeoutId);
464
+ timeoutId = null;
465
+ }
466
+ };
467
+ const rejectOnce = (error) => {
468
+ if (settled) {
469
+ return;
470
+ }
471
+ settled = true;
472
+ clearTimer();
473
+ activeStream?.close();
474
+ reject(error);
475
+ };
476
+ timeoutId = setTimeout(() => {
477
+ rejectOnce(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
478
+ }, timeout);
449
479
  session.client.exec(fullCommand, execOptions, (err, stream) => {
450
480
  if (err) {
451
- settled = true;
452
- reject(new Error(`Exec failed: ${err.message}`));
481
+ rejectOnce(new Error(`Exec failed: ${err.message}`));
453
482
  return;
454
483
  }
455
- const outputPreview = () => ({
456
- stdout,
457
- stderr,
458
- stdoutTail,
459
- stderrTail,
460
- stdoutBytes,
461
- stderrBytes,
462
- stdoutTruncated,
463
- stderrTruncated,
464
- maxOutputSize,
465
- });
466
- timeoutId = setTimeout(() => {
467
- if (settled) {
468
- return;
469
- }
470
- settled = true;
484
+ if (settled) {
471
485
  stream.close();
472
- reject(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
473
- }, timeout);
486
+ return;
487
+ }
488
+ activeStream = stream;
474
489
  stream.on('close', (code) => {
475
- if (timeoutId) {
476
- clearTimeout(timeoutId);
477
- }
478
490
  if (settled) {
479
491
  return;
480
492
  }
481
493
  settled = true;
494
+ clearTimer();
482
495
  resolve({
483
496
  success: code === 0,
484
497
  stdout: stdoutTruncated ? stdout + '\n... [truncated]' : stdout,
@@ -122,7 +122,7 @@ function classifyCommandRisk(command) {
122
122
  if (pipeCount >= 3) {
123
123
  pushRisk(categories, signals, 'long-running', 'long_pipeline');
124
124
  }
125
- if (/(^|[^&])&(?!&)/.test(command)) {
125
+ if (/(?:^|[^&])&(?!&)/.test(command)) {
126
126
  pushRisk(categories, signals, 'process-control', 'background_task');
127
127
  }
128
128
  if (/\b(?:rm\s+-[a-zA-Z]*r|dd\s+if=|mkfs|fdisk|parted|shutdown|reboot)\b/.test(lowerCommand)) {
@@ -237,7 +237,7 @@ async function buildUploadVerification(args, local) {
237
237
  const expectedMode = normalizeExpectedMode(args.verifyMode);
238
238
  checks.mode = expectedMode !== undefined && remote.mode === expectedMode;
239
239
  }
240
- if (args.verifyOwner && remote.exists) {
240
+ if (args.verifyOwner !== undefined && remote.exists) {
241
241
  const expectedOwner = String(args.verifyOwner);
242
242
  checks.owner = String(remote.ownerId) === expectedOwner || remote.ownerName === expectedOwner;
243
243
  }
package/dist/tools/pty.js CHANGED
@@ -4,6 +4,7 @@
4
4
  * ssh_pty_start, ssh_pty_write, ssh_pty_read, ssh_pty_resize, ssh_pty_close, ssh_pty_list
5
5
  */
6
6
  import { z } from 'zod';
7
+ import { HARD_PTY_BUFFER_SIZE } from '../pty-manager.js';
7
8
  import { sessionManager } from '../session-manager.js';
8
9
  import { formatError, formatResult } from './utils.js'; // ========== Schemas ==========
9
10
  // ========== Schemas ==========
@@ -15,7 +16,13 @@ const ptyStartSchema = z.object({
15
16
  term: z.string().optional().describe('终端类型,默认 xterm-256color'),
16
17
  cwd: z.string().optional().describe('工作目录'),
17
18
  env: z.record(z.string(), z.string()).optional().describe('环境变量'),
18
- bufferSize: z.number().optional().describe('输出缓冲区大小(字节),默认 1MB'),
19
+ bufferSize: z
20
+ .number()
21
+ .int()
22
+ .positive()
23
+ .max(HARD_PTY_BUFFER_SIZE)
24
+ .optional()
25
+ .describe('输出缓冲区大小(字节),默认 1MB'),
19
26
  });
20
27
  const ptyWriteSchema = z.object({
21
28
  ptyId: z.string().describe('PTY 会话 ID'),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyrokine/mcp-ssh",
3
- "version": "2.3.0",
3
+ "version": "2.3.2",
4
4
  "description": "A comprehensive SSH MCP Server for Claude Code",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -29,7 +29,7 @@
29
29
  "license": "MIT",
30
30
  "repository": {
31
31
  "type": "git",
32
- "url": "https://github.com/Pyrokine/claude-tools.git"
32
+ "url": "git+https://github.com/Pyrokine/claude-tools.git"
33
33
  },
34
34
  "dependencies": {
35
35
  "@modelcontextprotocol/sdk": "^1.29.0",
@@ -47,7 +47,7 @@
47
47
  "typescript-eslint": "^8.61.0"
48
48
  },
49
49
  "engines": {
50
- "node": ">=18.0.0"
50
+ "node": ">=20.19.0"
51
51
  },
52
52
  "files": [
53
53
  "dist",