@pyrokine/mcp-ssh 1.1.2 → 1.1.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.
@@ -78,11 +78,13 @@ export class SessionManager {
78
78
  private forwardSessions: Map<string, ForwardSession> = new Map()
79
79
  private ptyIdCounter = 0
80
80
  private forwardIdCounter = 0
81
- private persistPath: string
81
+ private readonly persistPath: string
82
82
  private defaultKeepaliveInterval = 30000 // 30秒
83
83
  private defaultKeepaliveCountMax = 3
84
84
  private defaultTimeout = 30000 // 30秒
85
85
  private maxReconnectAttempts = 3
86
+ private defaultMaxOutputSize = 10 * 1024 * 1024 // 10MB
87
+ private reconnectDelay = 5000 // 5秒
86
88
  private defaultPtyBufferSize = 1024 * 1024 // 1MB
87
89
 
88
90
  constructor(persistPath?: string) {
@@ -139,12 +141,11 @@ export class SessionManager {
139
141
  const jumpSession = this.sessions.get(jumpAlias)
140
142
  if (jumpSession) {
141
143
  // 通过跳板机建立连接
142
- const stream = await this.forwardConnection(
144
+ connectConfig.sock = await this.forwardConnection(
143
145
  jumpSession.client,
144
146
  config.host,
145
147
  config.port || 22,
146
148
  )
147
- connectConfig.sock = stream
148
149
  }
149
150
  }
150
151
 
@@ -179,9 +180,10 @@ export class SessionManager {
179
180
  if (session.reconnectAttempts < this.maxReconnectAttempts) {
180
181
  session.reconnectAttempts++
181
182
  setTimeout(() => {
182
- this.reconnect(alias).catch(() => {
183
+ this.reconnect(alias).catch((err) => {
184
+ console.error(`Auto-reconnect failed for ${alias}:`, err.message)
183
185
  })
184
- }, 5000) // 5 秒后重连
186
+ }, this.reconnectDelay)
185
187
  }
186
188
  }
187
189
  })
@@ -201,7 +203,7 @@ export class SessionManager {
201
203
 
202
204
  try {
203
205
  session.client.end()
204
- } catch {
206
+ } catch { /* 忽略已关闭的连接 */
205
207
  }
206
208
 
207
209
  await this.connect(session.config)
@@ -215,7 +217,7 @@ export class SessionManager {
215
217
  if (session) {
216
218
  try {
217
219
  session.client.end()
218
- } catch {
220
+ } catch { /* 忽略已关闭的连接 */
219
221
  }
220
222
  this.sessions.delete(alias)
221
223
  this.persistSessions()
@@ -224,15 +226,6 @@ export class SessionManager {
224
226
  return false
225
227
  }
226
228
 
227
- /**
228
- * 断开所有连接
229
- */
230
- disconnectAll(): void {
231
- for (const alias of this.sessions.keys()) {
232
- this.disconnect(alias)
233
- }
234
- }
235
-
236
229
  /**
237
230
  * 获取会话
238
231
  */
@@ -278,32 +271,8 @@ export class SessionManager {
278
271
  ): Promise<ExecResult> {
279
272
  const session = this.getSession(alias)
280
273
  const startTime = Date.now()
281
- const maxOutputSize = options.maxOutputSize || 10 * 1024 * 1024 // 默认 10MB
282
-
283
- // 构建完整命令(包含环境变量)
284
- let fullCommand = command
285
- const env = {...session.config.env, ...options.env}
286
-
287
- if (Object.keys(env).length > 0) {
288
- // 校验并过滤环境变量名
289
- const validEnvEntries = Object.entries(env).filter(([k]) => {
290
- if (!this.isValidEnvKey(k)) {
291
- // 静默忽略非法环境变量名
292
- return false
293
- }
294
- return true
295
- })
296
- if (validEnvEntries.length > 0) {
297
- const envStr = validEnvEntries
298
- .map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
299
- .join('; ')
300
- fullCommand = `${envStr}; ${command}`
301
- }
302
- }
303
-
304
- if (options.cwd) {
305
- fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`
306
- }
274
+ const maxOutputSize = options.maxOutputSize || this.defaultMaxOutputSize
275
+ const fullCommand = this.buildCommand(command, session, options)
307
276
 
308
277
  return new Promise((resolve, reject) => {
309
278
  const timeout = options.timeout || this.defaultTimeout
@@ -378,10 +347,11 @@ export class SessionManager {
378
347
 
379
348
  /**
380
349
  * 以其他用户身份执行命令
381
- * @param loadProfile 是否加载用户的 shell 配置(默认 true)。
382
- * su -c 创建非交互式 shell,不会自动执行 rc 文件,
383
- * 但大多数用户的环境变量设置在 rc 文件中,因此默认加载。
384
- * 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)。
350
+ *
351
+ * options.loadProfile 控制是否加载用户的 shell 配置(默认 true)。
352
+ * su -c 创建非交互式 shell,不会自动执行 rc 文件,
353
+ * 但大多数用户的环境变量设置在 rc 文件中,因此默认加载。
354
+ * 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)。
385
355
  */
386
356
  async execAsUser(
387
357
  alias: string,
@@ -439,19 +409,6 @@ export class SessionManager {
439
409
  })
440
410
  }
441
411
 
442
- /**
443
- * 加载持久化的会话信息(仅用于显示,不自动重连)
444
- */
445
- loadPersistedSessions(): PersistedSession[] {
446
- try {
447
- if (fs.existsSync(this.persistPath)) {
448
- return JSON.parse(fs.readFileSync(this.persistPath, 'utf-8'))
449
- }
450
- } catch {
451
- }
452
- return []
453
- }
454
-
455
412
  /**
456
413
  * 启动持久化 PTY 会话
457
414
  */
@@ -467,21 +424,7 @@ export class SessionManager {
467
424
  const cols = options.cols || 80
468
425
  const term = options.term || 'xterm-256color'
469
426
  const maxBufferSize = options.bufferSize || this.defaultPtyBufferSize
470
-
471
- // 构建完整命令
472
- let fullCommand = command
473
- const env = {...session.config.env, ...options.env}
474
-
475
- if (Object.keys(env).length > 0) {
476
- const envStr = Object.entries(env)
477
- .map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
478
- .join('; ')
479
- fullCommand = `${envStr}; ${command}`
480
- }
481
-
482
- if (options.cwd) {
483
- fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`
484
- }
427
+ const fullCommand = this.buildCommand(command, session, options)
485
428
 
486
429
  return new Promise((resolve, reject) => {
487
430
  session.client.exec(
@@ -564,7 +507,8 @@ export class SessionManager {
564
507
 
565
508
  /**
566
509
  * 读取 PTY 输出
567
- * @param mode 'screen' 返回当前屏幕内容,'raw' 返回原始 ANSI 流
510
+ *
511
+ * options.mode: 'screen' 返回当前屏幕内容,'raw' 返回原始 ANSI 流
568
512
  */
569
513
  ptyRead(
570
514
  ptyId: string,
@@ -629,11 +573,11 @@ export class SessionManager {
629
573
  }
630
574
  try {
631
575
  ptySession.stream.close()
632
- } catch {
576
+ } catch { /* 忽略清理异常 */
633
577
  }
634
578
  try {
635
579
  ptySession.terminal.dispose()
636
- } catch {
580
+ } catch { /* 忽略清理异常 */
637
581
  }
638
582
  ptySession.active = false
639
583
  this.ptySessions.delete(ptyId)
@@ -661,19 +605,6 @@ export class SessionManager {
661
605
  return result
662
606
  }
663
607
 
664
- /**
665
- * 关闭所有 PTY 会话
666
- */
667
- ptyCloseAll(): number {
668
- let count = 0
669
- for (const ptyId of this.ptySessions.keys()) {
670
- if (this.ptyClose(ptyId)) {
671
- count++
672
- }
673
- }
674
- return count
675
- }
676
-
677
608
  /**
678
609
  * 创建本地端口转发
679
610
  * 本地监听 localHost:localPort,转发到远程 remoteHost:remotePort
@@ -770,8 +701,6 @@ export class SessionManager {
770
701
  })
771
702
  }
772
703
 
773
- // ========== PTY 会话管理 ==========
774
-
775
704
  /**
776
705
  * 关闭端口转发
777
706
  */
@@ -786,14 +715,14 @@ export class SessionManager {
786
715
  if (fwdSession.type === 'local' && fwdSession.server) {
787
716
  try {
788
717
  fwdSession.server.close()
789
- } catch {
718
+ } catch { /* 忽略清理异常 */
790
719
  }
791
720
  } else if (fwdSession.type === 'remote') {
792
721
  const session = this.sessions.get(fwdSession.alias)
793
722
  if (session) {
794
723
  try {
795
724
  session.client.unforwardIn(fwdSession.remoteHost, fwdSession.remotePort)
796
- } catch {
725
+ } catch { /* 忽略清理异常 */
797
726
  }
798
727
  // 检查是否需要移除共享 dispatcher
799
728
  this.removeTcpDispatcherIfEmpty(session, fwdSession.alias)
@@ -892,7 +821,32 @@ export class SessionManager {
892
821
  return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)
893
822
  }
894
823
 
895
- // ========== 端口转发 ==========
824
+ /**
825
+ * 构建完整命令:注入环境变量 + 切换工作目录
826
+ */
827
+ private buildCommand(
828
+ command: string,
829
+ session: SSHSession,
830
+ options: { env?: Record<string, string>; cwd?: string },
831
+ ): string {
832
+ let fullCommand = command
833
+ const env = {...session.config.env, ...options.env}
834
+
835
+ if (Object.keys(env).length > 0) {
836
+ const validEntries = Object.entries(env).filter(([k]) => this.isValidEnvKey(k))
837
+ if (validEntries.length > 0) {
838
+ const envStr = validEntries
839
+ .map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
840
+ .join('; ')
841
+ fullCommand = `${envStr}; ${command}`
842
+ }
843
+ }
844
+
845
+ if (options.cwd) {
846
+ fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`
847
+ }
848
+ return fullCommand
849
+ }
896
850
 
897
851
  /**
898
852
  * 根据用户 shell 类型生成加载配置文件的命令
@@ -965,7 +919,6 @@ export class SessionManager {
965
919
  /**
966
920
  * 确保 SSH session 有共享的 tcp connection dispatcher
967
921
  * 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
968
- * @param alias - session 的 map key
969
922
  */
970
923
  private ensureTcpDispatcher(session: SSHSession, alias: string): void {
971
924
  if (session.tcpDispatcher) {
@@ -999,7 +952,6 @@ export class SessionManager {
999
952
 
1000
953
  /**
1001
954
  * 移除 SSH session 的 tcp dispatcher(当没有 remote forward 时)
1002
- * @param alias - session 的 map key
1003
955
  */
1004
956
  private removeTcpDispatcherIfEmpty(session: SSHSession, alias: string): void {
1005
957
  if (!session.tcpDispatcher) {
package/src/ssh-config.ts CHANGED
@@ -102,7 +102,7 @@ export function parseProxyJump(proxyJump: string): ParsedProxyJump | null {
102
102
  }
103
103
 
104
104
  const {host, port} = parseHostPort(firstJump)
105
- return {user, host, port}
105
+ return {host, port}
106
106
  }
107
107
 
108
108
  /**
@@ -255,10 +255,3 @@ export function parseSSHConfig(configPath?: string): SSHConfigHost[] {
255
255
  return hosts
256
256
  }
257
257
 
258
- /**
259
- * 根据 Host 名称获取配置
260
- */
261
- export function getHostConfig(hostName: string, configPath?: string): SSHConfigHost | null {
262
- const hosts = parseSSHConfig(configPath)
263
- return hosts.find(h => h.host === hostName) || null
264
- }
@@ -0,0 +1,240 @@
1
+ /**
2
+ * 连接管理工具组
3
+ *
4
+ * ssh_connect, ssh_disconnect, ssh_list_sessions, ssh_reconnect, ssh_config_list
5
+ */
6
+
7
+ import type {McpServer} from '@modelcontextprotocol/sdk/server/mcp.js'
8
+ import {z} from 'zod'
9
+ import {sessionManager} from '../session-manager.js'
10
+ import {parseProxyJump, parseSSHConfig} from '../ssh-config.js'
11
+ import {formatError, formatResult} from './utils.js'
12
+
13
+ // ========== Schemas ==========
14
+
15
+ const connectSchema = z.object({
16
+ configHost: z.string()
17
+ .optional()
18
+ .describe('使用 ~/.ssh/config 中的 Host 配置(推荐)'),
19
+ configPath: z.string().optional().describe('SSH 配置文件路径(默认 ~/.ssh/config)'),
20
+ host: z.string().optional().describe('服务器地址(使用 configHost 时可省略)'),
21
+ user: z.string().optional().describe('用户名(使用 configHost 时可省略)'),
22
+ password: z.string().optional().describe('密码'),
23
+ keyPath: z.string().optional().describe('SSH 私钥路径'),
24
+ port: z.number().optional().describe('SSH 端口,默认 22'),
25
+ alias: z.string().optional().describe('连接别名(可选,默认使用 configHost 或 host)'),
26
+ env: z.record(z.string()).optional().describe('环境变量'),
27
+ keepaliveInterval: z.number().optional().describe('心跳间隔(毫秒),默认 30000'),
28
+ jumpHost: z.object({
29
+ host: z.string().describe('跳板机地址'),
30
+ user: z.string().describe('跳板机用户名'),
31
+ password: z.string().optional().describe('跳板机密码'),
32
+ keyPath: z.string().optional().describe('跳板机私钥路径'),
33
+ port: z.number().optional().describe('跳板机端口,默认 22'),
34
+ }).optional().describe('跳板机配置'),
35
+ })
36
+
37
+ const disconnectSchema = z.object({
38
+ alias: z.string().describe('连接别名'),
39
+ })
40
+
41
+ const listSessionsSchema = z.object({})
42
+
43
+ const reconnectSchema = z.object({
44
+ alias: z.string().describe('连接别名'),
45
+ })
46
+
47
+ const configListSchema = z.object({
48
+ configPath: z.string()
49
+ .optional()
50
+ .describe('SSH 配置文件路径(默认 ~/.ssh/config)'),
51
+ })
52
+
53
+ // ========== Handlers ==========
54
+
55
+ async function handleConnect(args: z.infer<typeof connectSchema>) {
56
+ try {
57
+ // 解析 configHost
58
+ let host = args.host
59
+ let user = args.user
60
+ let port = args.port
61
+ let keyPath = args.keyPath
62
+ let jumpHostResolved: {
63
+ host: string;
64
+ port: number;
65
+ username: string;
66
+ password?: string;
67
+ privateKeyPath?: string
68
+ } | undefined
69
+
70
+ if (args.configHost) {
71
+ const allHosts = parseSSHConfig(args.configPath)
72
+ const hostConfig = allHosts.find(h => h.host === args.configHost)
73
+ if (!hostConfig) {
74
+ return formatResult({success: false, error: `Host '${args.configHost}' not found in SSH config`})
75
+ }
76
+ // 显式参数优先于 config 值
77
+ host = host || hostConfig.hostName || hostConfig.host
78
+ user = user || hostConfig.user
79
+ port = port || hostConfig.port
80
+ keyPath = keyPath || hostConfig.identityFile
81
+
82
+ // 解析 ProxyJump(支持 user@host:port 格式)
83
+ if (hostConfig.proxyJump) {
84
+ const parsed = parseProxyJump(hostConfig.proxyJump)
85
+ if (parsed) {
86
+ // 先尝试在 config 中查找对应的 Host
87
+ const jumpHostConfig = allHosts.find(h => h.host === parsed.host)
88
+ if (jumpHostConfig) {
89
+ // 使用 config 中的配置,但 parsed 的 user/port 优先
90
+ jumpHostResolved = {
91
+ host: jumpHostConfig.hostName || jumpHostConfig.host,
92
+ port: parsed.port || jumpHostConfig.port || 22,
93
+ username: parsed.user || jumpHostConfig.user || 'root',
94
+ privateKeyPath: jumpHostConfig.identityFile,
95
+ }
96
+ } else {
97
+ // 直接使用 parsed 的值
98
+ jumpHostResolved = {
99
+ host: parsed.host,
100
+ port: parsed.port || 22,
101
+ username: parsed.user || 'root',
102
+ }
103
+ }
104
+ }
105
+ }
106
+ }
107
+
108
+ if (!host || !user) {
109
+ return formatResult({
110
+ success: false,
111
+ error: 'host and user are required (either directly or via configHost)',
112
+ })
113
+ }
114
+
115
+ // 手动指定的 jumpHost 优先级高于 ProxyJump
116
+ const jumpHost = args.jumpHost ? {
117
+ host: args.jumpHost.host,
118
+ port: args.jumpHost.port || 22,
119
+ username: args.jumpHost.user,
120
+ password: args.jumpHost.password,
121
+ privateKeyPath: args.jumpHost.keyPath,
122
+ } : jumpHostResolved
123
+
124
+ const alias = await sessionManager.connect({
125
+ host,
126
+ port: port || 22,
127
+ username: user,
128
+ password: args.password,
129
+ privateKeyPath: keyPath,
130
+ alias: args.alias || args.configHost,
131
+ env: args.env,
132
+ keepaliveInterval: args.keepaliveInterval,
133
+ jumpHost,
134
+ })
135
+ return formatResult({
136
+ success: true,
137
+ alias,
138
+ message: `Connected to ${user}@${host}:${port || 22}${jumpHost ?
139
+ ' via jump host' :
140
+ ''}`,
141
+ })
142
+ } catch (error) {
143
+ return formatError(error)
144
+ }
145
+ }
146
+
147
+ async function handleDisconnect(args: z.infer<typeof disconnectSchema>) {
148
+ try {
149
+ const success = sessionManager.disconnect(args.alias)
150
+ return formatResult({
151
+ success,
152
+ message: success
153
+ ? `Disconnected from ${args.alias}`
154
+ : `Session ${args.alias} not found`,
155
+ })
156
+ } catch (error) {
157
+ return formatError(error)
158
+ }
159
+ }
160
+
161
+ async function handleListSessions() {
162
+ try {
163
+ const sessions = sessionManager.listSessions()
164
+ return formatResult({
165
+ success: true,
166
+ count: sessions.length,
167
+ sessions,
168
+ })
169
+ } catch (error) {
170
+ return formatError(error)
171
+ }
172
+ }
173
+
174
+ async function handleReconnect(args: z.infer<typeof reconnectSchema>) {
175
+ try {
176
+ await sessionManager.reconnect(args.alias)
177
+ return formatResult({success: true, message: `Reconnected to ${args.alias}`})
178
+ } catch (error) {
179
+ return formatError(error)
180
+ }
181
+ }
182
+
183
+ async function handleConfigList(args: z.infer<typeof configListSchema>) {
184
+ try {
185
+ const hosts = parseSSHConfig(args.configPath)
186
+ return formatResult({
187
+ success: true,
188
+ count: hosts.length,
189
+ hosts: hosts.map(h => ({
190
+ host: h.host,
191
+ hostName: h.hostName,
192
+ user: h.user,
193
+ port: h.port,
194
+ identityFile: h.identityFile,
195
+ proxyJump: h.proxyJump,
196
+ })),
197
+ })
198
+ } catch (error) {
199
+ return formatError(error)
200
+ }
201
+ }
202
+
203
+ // ========== Register ==========
204
+
205
+ export function registerConnectionTools(server: McpServer): void {
206
+ server.registerTool('ssh_connect', {
207
+ description: `建立 SSH 连接并保持会话。支持密码、密钥认证,支持跳板机。
208
+
209
+ 可通过 configHost 参数使用 ~/.ssh/config 中的配置,无需重复填写连接信息。
210
+ 支持 Host 多别名、Host * 全局默认继承、ProxyJump(user@host:port 格式)。
211
+
212
+ 示例:
213
+ - 使用 ssh config: ssh_connect(configHost="myserver")
214
+ - 密钥认证: ssh_connect(host="192.168.1.1", user="root", keyPath="/home/.ssh/id_rsa")
215
+ - 跳板机: ssh_connect(host="内网IP", user="root", keyPath="...", jumpHost={host:"跳板机IP", user:"root", keyPath:"..."})`,
216
+ inputSchema: connectSchema,
217
+ }, (args) => handleConnect(args))
218
+
219
+ server.registerTool('ssh_disconnect', {
220
+ description: '断开 SSH 连接',
221
+ inputSchema: disconnectSchema,
222
+ }, (args) => handleDisconnect(args))
223
+
224
+ server.registerTool('ssh_list_sessions', {
225
+ description: '列出所有活跃的 SSH 会话',
226
+ inputSchema: listSessionsSchema,
227
+ }, () => handleListSessions())
228
+
229
+ server.registerTool('ssh_reconnect', {
230
+ description: '重新连接已断开的会话',
231
+ inputSchema: reconnectSchema,
232
+ }, (args) => handleReconnect(args))
233
+
234
+ server.registerTool('ssh_config_list', {
235
+ description: `列出 ~/.ssh/config 中配置的所有 Host。
236
+
237
+ 返回每个 Host 的配置信息(别名、地址、用户、端口、密钥路径等)。`,
238
+ inputSchema: configListSchema,
239
+ }, (args) => handleConfigList(args))
240
+ }