@pyrokine/mcp-ssh 1.2.0 → 1.2.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/dist/file-ops.js CHANGED
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import { execSync } from 'child_process';
5
5
  import * as fs from 'fs';
6
+ import * as os from 'os';
6
7
  import * as path from 'path';
7
8
  import { sessionManager } from './session-manager.js';
8
9
  // 文件类型 mode 常量
@@ -273,7 +274,8 @@ async function syncWithRsync(alias, localPath, remotePath, direction, options) {
273
274
  // 检查本地是否有 rsync
274
275
  let hasLocalRsync = false;
275
276
  try {
276
- execSync('which rsync', { stdio: 'pipe' });
277
+ const cmd = os.platform() === 'win32' ? 'where rsync' : 'which rsync';
278
+ execSync(cmd, { stdio: 'pipe' });
277
279
  hasLocalRsync = true;
278
280
  }
279
281
  catch {
@@ -114,7 +114,8 @@ export class ForwardManager {
114
114
  try {
115
115
  state.client.removeListener('tcp connection', state.handler);
116
116
  }
117
- catch { /* client 可能已关闭 */ }
117
+ catch { /* client 可能已关闭 */
118
+ }
118
119
  this.dispatchers.delete(alias);
119
120
  }
120
121
  }
@@ -8,6 +8,7 @@
8
8
  * - 会话持久化
9
9
  */
10
10
  import * as fs from 'fs';
11
+ import * as os from 'os';
11
12
  import * as path from 'path';
12
13
  import { Client } from 'ssh2';
13
14
  import { ForwardManager } from './forward-manager.js';
@@ -24,7 +25,7 @@ export class SessionManager {
24
25
  defaultMaxOutputSize = 10 * 1024 * 1024; // 10MB
25
26
  reconnectDelay = 5000; // 5秒
26
27
  constructor(persistPath) {
27
- this.persistPath = persistPath || path.join(process.env.HOME || '/tmp', '.ssh-mcp-pro', 'sessions.json');
28
+ this.persistPath = persistPath || path.join(os.homedir(), '.ssh-mcp-pro', 'sessions.json');
28
29
  this.ensurePersistDir();
29
30
  }
30
31
  /**
@@ -100,6 +101,9 @@ export class SessionManager {
100
101
  const session = this.sessions.get(alias);
101
102
  if (session && session.client === client) {
102
103
  session.connected = false;
104
+ // 清理绑定旧 client 的 forward/PTY 资源
105
+ this.forwardManager.closeByAlias(alias);
106
+ this.ptyManager.closeByAlias(alias);
103
107
  if (!session.manualClose) {
104
108
  this.scheduleReconnect(alias);
105
109
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyrokine/mcp-ssh",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "description": "A comprehensive SSH MCP Server for Claude Code",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -11,7 +11,7 @@
11
11
  "build": "tsc",
12
12
  "start": "node dist/index.js",
13
13
  "dev": "tsc && node dist/index.js",
14
- "clean": "rm -rf dist",
14
+ "clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
15
15
  "prepublishOnly": "npm run build"
16
16
  },
17
17
  "keywords": [
@@ -28,7 +28,7 @@
28
28
  "url": "https://github.com/Pyrokine/claude-mcp-tools.git"
29
29
  },
30
30
  "dependencies": {
31
- "@modelcontextprotocol/sdk": "^1.25.3",
31
+ "@modelcontextprotocol/sdk": "^1.27.1",
32
32
  "@xterm/headless": "^6.0.0",
33
33
  "ssh2": "^1.17.0",
34
34
  "zod": "^3.25.76"
package/src/file-ops.ts CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import {execSync} from 'child_process'
6
6
  import * as fs from 'fs'
7
+ import * as os from 'os'
7
8
  import * as path from 'path'
8
9
  import {SFTPWrapper, Stats} from 'ssh2'
9
10
  import {sessionManager} from './session-manager.js'
@@ -71,7 +72,7 @@ function pipeWithProgress(
71
72
  if (!settled) {
72
73
  settled = true
73
74
  sftp.end()
74
- resolve({success: true, size: totalSize})
75
+ resolve({ success: true, size: totalSize })
75
76
  }
76
77
  })
77
78
 
@@ -117,7 +118,7 @@ export async function downloadFile(
117
118
  // 确保本地目录存在
118
119
  const localDir = path.dirname(localPath)
119
120
  if (!fs.existsSync(localDir)) {
120
- fs.mkdirSync(localDir, {recursive: true})
121
+ fs.mkdirSync(localDir, { recursive: true })
121
122
  }
122
123
 
123
124
  return pipeWithProgress(
@@ -142,7 +143,7 @@ export async function readFile(
142
143
  // 处理空文件
143
144
  if (actualSize === 0) {
144
145
  sftp.end()
145
- return {content: '', size: 0, truncated: false}
146
+ return { content: '', size: 0, truncated: false }
146
147
  }
147
148
 
148
149
  const readSize = Math.min(actualSize, maxBytes)
@@ -189,11 +190,11 @@ export async function writeFile(
189
190
  const flags = append ? 'a' : 'w'
190
191
 
191
192
  return new Promise((resolve, reject) => {
192
- const writeStream = sftp.createWriteStream(remotePath, {flags})
193
+ const writeStream = sftp.createWriteStream(remotePath, { flags })
193
194
 
194
195
  writeStream.on('close', () => {
195
196
  sftp.end()
196
- resolve({success: true, size: content.length})
197
+ resolve({ success: true, size: content.length })
197
198
  })
198
199
 
199
200
  writeStream.on('error', (err: Error) => {
@@ -382,7 +383,8 @@ async function syncWithRsync(
382
383
  // 检查本地是否有 rsync
383
384
  let hasLocalRsync = false
384
385
  try {
385
- execSync('which rsync', {stdio: 'pipe'})
386
+ const cmd = os.platform() === 'win32' ? 'where rsync' : 'which rsync'
387
+ execSync(cmd, { stdio: 'pipe' })
386
388
  hasLocalRsync = true
387
389
  } catch {
388
390
  }
@@ -511,20 +513,20 @@ async function syncWithSftp(
511
513
  if (direction === 'upload') {
512
514
  const stats = fs.statSync(localPath)
513
515
  if (stats.isDirectory() && options.recursive !== false) {
514
- const {fileCount, totalSize} = await uploadDirectory(alias, localPath, remotePath, options.exclude)
516
+ const { fileCount, totalSize } = await uploadDirectory(alias, localPath, remotePath, options.exclude)
515
517
  return buildSyncResult(fileCount, totalSize, warnings)
516
518
  }
517
- const {size} = await uploadFile(alias, localPath, remotePath)
519
+ const { size } = await uploadFile(alias, localPath, remotePath)
518
520
  return buildSyncResult(1, size, warnings)
519
521
  }
520
522
 
521
523
  // download
522
524
  const info = await getFileInfo(alias, remotePath)
523
525
  if (info.isDirectory && options.recursive !== false) {
524
- const {fileCount, totalSize} = await downloadDirectory(alias, remotePath, localPath, options.exclude)
526
+ const { fileCount, totalSize } = await downloadDirectory(alias, remotePath, localPath, options.exclude)
525
527
  return buildSyncResult(fileCount, totalSize, warnings)
526
528
  }
527
- const {size} = await downloadFile(alias, remotePath, localPath)
529
+ const { size } = await downloadFile(alias, remotePath, localPath)
528
530
  return buildSyncResult(1, size, warnings)
529
531
  } catch (err: any) {
530
532
  return {
@@ -572,7 +574,7 @@ async function uploadDirectory(
572
574
  }
573
575
  }
574
576
 
575
- return {fileCount, totalSize}
577
+ return { fileCount, totalSize }
576
578
  }
577
579
 
578
580
  /**
@@ -589,7 +591,7 @@ async function downloadDirectory(
589
591
 
590
592
  // 确保本地目录存在
591
593
  if (!fs.existsSync(localPath)) {
592
- fs.mkdirSync(localPath, {recursive: true})
594
+ fs.mkdirSync(localPath, { recursive: true })
593
595
  }
594
596
 
595
597
  const items = await listDir(alias, remotePath, true)
@@ -612,7 +614,7 @@ async function downloadDirectory(
612
614
  }
613
615
  }
614
616
 
615
- return {fileCount, totalSize}
617
+ return { fileCount, totalSize }
616
618
  }
617
619
 
618
620
  /**
@@ -178,7 +178,8 @@ export class ForwardManager {
178
178
  if (state) {
179
179
  try {
180
180
  state.client.removeListener('tcp connection', state.handler)
181
- } catch { /* client 可能已关闭 */ }
181
+ } catch { /* client 可能已关闭 */
182
+ }
182
183
  this.dispatchers.delete(alias)
183
184
  }
184
185
  }
@@ -228,7 +229,7 @@ export class ForwardManager {
228
229
  rejectConn()
229
230
  }
230
231
 
231
- this.dispatchers.set(alias, {handler, client})
232
+ this.dispatchers.set(alias, { handler, client })
232
233
  client.on('tcp connection', handler)
233
234
  }
234
235
 
package/src/index.ts CHANGED
@@ -25,8 +25,8 @@ import {
25
25
  } from './tools/index.js'
26
26
 
27
27
  const server = new McpServer(
28
- {name: 'ssh-mcp-pro', version: '1.1.2'},
29
- {capabilities: {tools: {}}},
28
+ { name: 'ssh-mcp-pro', version: '1.1.2' },
29
+ { capabilities: { tools: {} } },
30
30
  )
31
31
 
32
32
  registerConnectionTools(server)
@@ -51,7 +51,7 @@ export class PtyManager {
51
51
  const stream = await deps.execPty(alias, command, options)
52
52
 
53
53
  // 创建 xterm headless 终端仿真器
54
- const terminal = new Terminal({rows, cols, allowProposedApi: true})
54
+ const terminal = new Terminal({ rows, cols, allowProposedApi: true })
55
55
 
56
56
  const ptySession: PtySession = {
57
57
  id: ptyId,
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import * as fs from 'fs'
12
+ import * as os from 'os'
12
13
  import * as path from 'path'
13
14
  import {Client, ClientChannel, ConnectConfig, SFTPWrapper} from 'ssh2'
14
15
  import {ForwardManager} from './forward-manager.js'
@@ -48,9 +49,9 @@ export class SessionManager {
48
49
 
49
50
  constructor(persistPath?: string) {
50
51
  this.persistPath = persistPath || path.join(
51
- process.env.HOME || '/tmp',
52
- '.ssh-mcp-pro',
53
- 'sessions.json',
52
+ os.homedir(),
53
+ '.ssh-mcp-pro',
54
+ 'sessions.json',
54
55
  )
55
56
  this.ensurePersistDir()
56
57
  }
@@ -140,6 +141,9 @@ export class SessionManager {
140
141
  const session = this.sessions.get(alias)
141
142
  if (session && session.client === client) {
142
143
  session.connected = false
144
+ // 清理绑定旧 client 的 forward/PTY 资源
145
+ this.forwardManager.closeByAlias(alias)
146
+ this.ptyManager.closeByAlias(alias)
143
147
  if (!session.manualClose) {
144
148
  this.scheduleReconnect(alias)
145
149
  }
@@ -329,7 +333,7 @@ export class SessionManager {
329
333
  throw new Error(`Invalid username: ${targetUser}`)
330
334
  }
331
335
 
332
- const {loadProfile = true, ...execOpts} = options
336
+ const { loadProfile = true, ...execOpts } = options
333
337
 
334
338
  const wrappedCommand = loadProfile
335
339
  ? `${this.getLoadProfileCommand()}${command}`
@@ -415,7 +419,7 @@ export class SessionManager {
415
419
  localHost: string = '127.0.0.1',
416
420
  ): Promise<string> {
417
421
  return this.forwardManager.forwardLocal(
418
- {getClient: (a) => this.getSession(a).client},
422
+ { getClient: (a) => this.getSession(a).client },
419
423
  alias, localPort, remoteHost, remotePort, localHost,
420
424
  )
421
425
  }
@@ -428,7 +432,7 @@ export class SessionManager {
428
432
  remoteHost: string = '127.0.0.1',
429
433
  ): Promise<string> {
430
434
  return this.forwardManager.forwardRemote(
431
- {getClient: (a) => this.getSession(a).client},
435
+ { getClient: (a) => this.getSession(a).client },
432
436
  alias, remotePort, localHost, localPort, remoteHost,
433
437
  )
434
438
  }
@@ -452,7 +456,7 @@ export class SessionManager {
452
456
  options: PtyOptions,
453
457
  ): Promise<ClientChannel> {
454
458
  const session = this.getSession(alias)
455
- const fullCommand = this.buildCommand(command, session, {env: options.env, cwd: options.cwd})
459
+ const fullCommand = this.buildCommand(command, session, { env: options.env, cwd: options.cwd })
456
460
 
457
461
  return new Promise((resolve, reject) => {
458
462
  session.client.exec(fullCommand, {
@@ -474,7 +478,7 @@ export class SessionManager {
474
478
  private ensurePersistDir(): void {
475
479
  const dir = path.dirname(this.persistPath)
476
480
  if (!fs.existsSync(dir)) {
477
- fs.mkdirSync(dir, {recursive: true})
481
+ fs.mkdirSync(dir, { recursive: true })
478
482
  }
479
483
  }
480
484
 
@@ -598,7 +602,7 @@ export class SessionManager {
598
602
  options: { env?: Record<string, string>; cwd?: string },
599
603
  ): string {
600
604
  let fullCommand = command
601
- const env = {...session.config.env, ...options.env}
605
+ const env = { ...session.config.env, ...options.env }
602
606
 
603
607
  if (Object.keys(env).length > 0) {
604
608
  const validEntries = Object.entries(env).filter(([k]) => this.isValidEnvKey(k))
package/src/ssh-config.ts CHANGED
@@ -48,17 +48,17 @@ function parseHostPort(s: string): { host: string; port?: number } {
48
48
  if (rest.startsWith(':')) {
49
49
  const parsedPort = parseInt(rest.slice(1), 10)
50
50
  if (!isNaN(parsedPort)) {
51
- return {host, port: parsedPort}
51
+ return { host, port: parsedPort }
52
52
  }
53
53
  }
54
- return {host}
54
+ return { host }
55
55
  }
56
56
  }
57
57
 
58
58
  // 检测裸 IPv6(多个冒号但无方括号):安全失败,当作 host-only
59
59
  const colonCount = (s.match(/:/g) || []).length
60
60
  if (colonCount >= 2) {
61
- return {host: s}
61
+ return { host: s }
62
62
  }
63
63
 
64
64
  // 普通格式: host:port 或 host
@@ -68,10 +68,10 @@ function parseHostPort(s: string): { host: string; port?: number } {
68
68
  const portStr = s.slice(colonIndex + 1)
69
69
  const parsedPort = parseInt(portStr, 10)
70
70
  if (!isNaN(parsedPort)) {
71
- return {host, port: parsedPort}
71
+ return { host, port: parsedPort }
72
72
  }
73
73
  }
74
- return {host: s}
74
+ return { host: s }
75
75
  }
76
76
 
77
77
  /**
@@ -95,14 +95,14 @@ export function parseProxyJump(proxyJump: string): ParsedProxyJump | null {
95
95
  // 解析 user@... 格式
96
96
  const atIndex = firstJump.indexOf('@')
97
97
  if (atIndex !== -1) {
98
- user = firstJump.slice(0, atIndex)
99
- const rest = firstJump.slice(atIndex + 1)
100
- const {host, port} = parseHostPort(rest)
101
- return {user, host, port}
98
+ user = firstJump.slice(0, atIndex)
99
+ const rest = firstJump.slice(atIndex + 1)
100
+ const { host, port } = parseHostPort(rest)
101
+ return { user, host, port }
102
102
  }
103
103
 
104
- const {host, port} = parseHostPort(firstJump)
105
- return {host, port}
104
+ const { host, port } = parseHostPort(firstJump)
105
+ return { host, port }
106
106
  }
107
107
 
108
108
  /**
@@ -187,7 +187,7 @@ export function parseSSHConfig(configPath?: string): SSHConfigHost[] {
187
187
 
188
188
  // Host 行可能有多个别名/模式,用空格分隔
189
189
  const patterns = value.split(/\s+/).filter(p => p.length > 0)
190
- currentBlock = {patterns, config: {}}
190
+ currentBlock = { patterns, config: {} }
191
191
  } else if (keyLower === 'match') {
192
192
  // Match 块开始,跳过直到下一个 Host
193
193
  inMatchBlock = true
@@ -226,7 +226,7 @@ export function parseSSHConfig(configPath?: string): SSHConfigHost[] {
226
226
  // 第二遍:提取 Host * 的全局默认配置
227
227
  for (const block of blocks) {
228
228
  if (block.patterns.length === 1 && block.patterns[0] === '*') {
229
- globalDefaults = {...block.config}
229
+ globalDefaults = { ...block.config }
230
230
  break
231
231
  }
232
232
  }
@@ -71,7 +71,7 @@ async function handleConnect(args: z.infer<typeof connectSchema>) {
71
71
  const allHosts = parseSSHConfig(args.configPath)
72
72
  const hostConfig = allHosts.find(h => h.host === args.configHost)
73
73
  if (!hostConfig) {
74
- return formatResult({success: false, error: `Host '${args.configHost}' not found in SSH config`})
74
+ return formatResult({ success: false, error: `Host '${args.configHost}' not found in SSH config` })
75
75
  }
76
76
  // 显式参数优先于 config 值
77
77
  host = host || hostConfig.hostName || hostConfig.host
@@ -174,7 +174,7 @@ async function handleListSessions() {
174
174
  async function handleReconnect(args: z.infer<typeof reconnectSchema>) {
175
175
  try {
176
176
  await sessionManager.reconnect(args.alias)
177
- return formatResult({success: true, message: `Reconnected to ${args.alias}`})
177
+ return formatResult({ success: true, message: `Reconnected to ${args.alias}` })
178
178
  } catch (error) {
179
179
  return formatError(error)
180
180
  }
package/src/tools/exec.ts CHANGED
@@ -102,7 +102,7 @@ async function handleExecSudo(args: z.infer<typeof execSudoSchema>) {
102
102
  args.alias,
103
103
  args.command,
104
104
  args.sudoPassword,
105
- {timeout: args.timeout},
105
+ { timeout: args.timeout },
106
106
  )
107
107
  return formatResult(result)
108
108
  } catch (error) {
@@ -120,7 +120,7 @@ async function handleExecBatch(args: z.infer<typeof execBatchSchema>) {
120
120
  const execResult = await sessionManager.exec(
121
121
  args.alias,
122
122
  args.commands[i],
123
- {timeout: args.timeout},
123
+ { timeout: args.timeout },
124
124
  )
125
125
  results.push({
126
126
  index: i,
@@ -168,7 +168,7 @@ async function handleQuickExec(args: z.infer<typeof quickExecSchema>) {
168
168
  const result = await sessionManager.exec(
169
169
  tempAlias,
170
170
  args.command,
171
- {timeout: args.timeout},
171
+ { timeout: args.timeout },
172
172
  )
173
173
  return formatResult(result)
174
174
  } catch (error) {
@@ -182,7 +182,7 @@ async function handleExecParallel(args: z.infer<typeof execParallelSchema>) {
182
182
  try {
183
183
  const execPromises = args.aliases.map(async (alias) => {
184
184
  try {
185
- const execResult = await sessionManager.exec(alias, args.command, {timeout: args.timeout})
185
+ const execResult = await sessionManager.exec(alias, args.command, { timeout: args.timeout })
186
186
  return {
187
187
  alias,
188
188
  success: execResult.success,
package/src/tools/file.ts CHANGED
@@ -71,7 +71,7 @@ const syncSchema = z.object({
71
71
  async function handleUpload(args: z.infer<typeof uploadSchema>) {
72
72
  try {
73
73
  const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, args.remotePath)
74
- return formatResult({...uploadResult, message: `Uploaded to ${args.remotePath}`})
74
+ return formatResult({ ...uploadResult, message: `Uploaded to ${args.remotePath}` })
75
75
  } catch (error) {
76
76
  return formatError(error)
77
77
  }
@@ -80,7 +80,7 @@ async function handleUpload(args: z.infer<typeof uploadSchema>) {
80
80
  async function handleDownload(args: z.infer<typeof downloadSchema>) {
81
81
  try {
82
82
  const downloadResult = await fileOps.downloadFile(args.alias, args.remotePath, args.localPath)
83
- return formatResult({...downloadResult, message: `Downloaded to ${args.localPath}`})
83
+ return formatResult({ ...downloadResult, message: `Downloaded to ${args.localPath}` })
84
84
  } catch (error) {
85
85
  return formatError(error)
86
86
  }
@@ -89,7 +89,7 @@ async function handleDownload(args: z.infer<typeof downloadSchema>) {
89
89
  async function handleReadFile(args: z.infer<typeof readFileSchema>) {
90
90
  try {
91
91
  const readResult = await fileOps.readFile(args.alias, args.remotePath, args.maxBytes)
92
- return formatResult({success: true, ...readResult})
92
+ return formatResult({ success: true, ...readResult })
93
93
  } catch (error) {
94
94
  return formatError(error)
95
95
  }
@@ -121,7 +121,7 @@ async function handleListDir(args: z.infer<typeof listDirSchema>) {
121
121
  async function handleFileInfo(args: z.infer<typeof fileInfoSchema>) {
122
122
  try {
123
123
  const info = await fileOps.getFileInfo(args.alias, args.remotePath)
124
- return formatResult({success: true, ...info})
124
+ return formatResult({ success: true, ...info })
125
125
  } catch (error) {
126
126
  return formatError(error)
127
127
  }
@@ -130,7 +130,7 @@ async function handleFileInfo(args: z.infer<typeof fileInfoSchema>) {
130
130
  async function handleMkdir(args: z.infer<typeof mkdirSchema>) {
131
131
  try {
132
132
  const success = await fileOps.mkdir(args.alias, args.remotePath, args.recursive)
133
- return formatResult({success, path: args.remotePath})
133
+ return formatResult({ success, path: args.remotePath })
134
134
  } catch (error) {
135
135
  return formatError(error)
136
136
  }
package/src/tools/pty.ts CHANGED
@@ -77,7 +77,7 @@ async function handlePtyStart(args: z.infer<typeof ptyStartSchema>) {
77
77
  async function handlePtyWrite(args: z.infer<typeof ptyWriteSchema>) {
78
78
  try {
79
79
  const success = sessionManager.ptyWrite(args.ptyId, args.data)
80
- return formatResult({success, ptyId: args.ptyId})
80
+ return formatResult({ success, ptyId: args.ptyId })
81
81
  } catch (error) {
82
82
  return formatError(error)
83
83
  }
@@ -106,7 +106,7 @@ async function handlePtyRead(args: z.infer<typeof ptyReadSchema>) {
106
106
  async function handlePtyResize(args: z.infer<typeof ptyResizeSchema>) {
107
107
  try {
108
108
  const success = sessionManager.ptyResize(args.ptyId, args.rows, args.cols)
109
- return formatResult({success, ptyId: args.ptyId})
109
+ return formatResult({ success, ptyId: args.ptyId })
110
110
  } catch (error) {
111
111
  return formatError(error)
112
112
  }
@@ -7,7 +7,7 @@
7
7
  */
8
8
  export function formatResult(data: unknown) {
9
9
  return {
10
- content: [{type: 'text' as const, text: JSON.stringify(data, null, 2)}],
10
+ content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }],
11
11
  }
12
12
  }
13
13
 
@@ -17,7 +17,7 @@ export function formatResult(data: unknown) {
17
17
  export function formatError(error: unknown) {
18
18
  const message = error instanceof Error ? error.message : String(error)
19
19
  return {
20
- content: [{type: 'text' as const, text: JSON.stringify({success: false, error: message}, null, 2)}],
20
+ content: [{ type: 'text' as const, text: JSON.stringify({ success: false, error: message }, null, 2) }],
21
21
  isError: true,
22
22
  }
23
23
  }