@pyrokine/mcp-ssh 1.1.2 → 1.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.
Files changed (43) hide show
  1. package/README.md +3 -1
  2. package/README_zh.md +3 -1
  3. package/dist/file-ops.d.ts +7 -10
  4. package/dist/file-ops.js +74 -172
  5. package/dist/forward-manager.d.ts +33 -0
  6. package/dist/forward-manager.js +185 -0
  7. package/dist/index.js +8 -953
  8. package/dist/pty-manager.d.ts +37 -0
  9. package/dist/pty-manager.js +169 -0
  10. package/dist/session-manager.d.ts +28 -86
  11. package/dist/session-manager.js +131 -441
  12. package/dist/ssh-config.d.ts +0 -4
  13. package/dist/ssh-config.js +1 -8
  14. package/dist/tools/connection.d.ts +7 -0
  15. package/dist/tools/connection.js +215 -0
  16. package/dist/tools/exec.d.ts +8 -0
  17. package/dist/tools/exec.js +221 -0
  18. package/dist/tools/file.d.ts +8 -0
  19. package/dist/tools/file.js +192 -0
  20. package/dist/tools/forward.d.ts +7 -0
  21. package/dist/tools/forward.js +116 -0
  22. package/dist/tools/index.d.ts +8 -0
  23. package/dist/tools/index.js +8 -0
  24. package/dist/tools/pty.d.ts +7 -0
  25. package/dist/tools/pty.js +178 -0
  26. package/dist/tools/utils.d.ts +22 -0
  27. package/dist/tools/utils.js +21 -0
  28. package/dist/types.d.ts +0 -7
  29. package/package.json +3 -2
  30. package/src/file-ops.ts +117 -212
  31. package/src/forward-manager.ts +257 -0
  32. package/src/index.ts +17 -1099
  33. package/src/pty-manager.ts +220 -0
  34. package/src/session-manager.ts +166 -532
  35. package/src/ssh-config.ts +1 -8
  36. package/src/tools/connection.ts +240 -0
  37. package/src/tools/exec.ts +260 -0
  38. package/src/tools/file.ts +219 -0
  39. package/src/tools/forward.ts +141 -0
  40. package/src/tools/index.ts +9 -0
  41. package/src/tools/pty.ts +203 -0
  42. package/src/tools/utils.ts +23 -0
  43. package/src/types.ts +0 -9
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
+ }
@@ -0,0 +1,260 @@
1
+ /**
2
+ * 命令执行工具组
3
+ *
4
+ * ssh_exec, ssh_exec_as_user, ssh_exec_sudo,
5
+ * ssh_exec_batch, ssh_quick_exec, ssh_exec_parallel
6
+ */
7
+
8
+ import type {McpServer} from '@modelcontextprotocol/sdk/server/mcp.js'
9
+ import {z} from 'zod'
10
+ import {sessionManager} from '../session-manager.js'
11
+ import {formatError, formatResult} from './utils.js'
12
+
13
+ // ========== Schemas ==========
14
+
15
+ const execSchema = z.object({
16
+ alias: z.string().describe('连接别名'),
17
+ command: z.string().describe('要执行的命令'),
18
+ timeout: z.number().optional().describe('超时(毫秒),默认 30000'),
19
+ cwd: z.string().optional().describe('工作目录(可选)'),
20
+ env: z.record(z.string()).optional().describe('额外环境变量'),
21
+ pty: z.boolean().optional().describe('是否使用 PTY 模式(用于 top 等交互式命令)'),
22
+ })
23
+
24
+ const execAsUserSchema = z.object({
25
+ alias: z.string().describe('连接别名'),
26
+ command: z.string().describe('要执行的命令'),
27
+ targetUser: z.string().describe('目标用户名'),
28
+ timeout: z.number().optional().describe('超时(毫秒)'),
29
+ loadProfile: z.boolean().optional().describe('是否加载 .bashrc(默认 true)'),
30
+ })
31
+
32
+ const execSudoSchema = z.object({
33
+ alias: z.string().describe('连接别名'),
34
+ command: z.string().describe('要执行的命令'),
35
+ sudoPassword: z.string().optional().describe('sudo 密码(如果需要)'),
36
+ timeout: z.number().optional().describe('超时(毫秒)'),
37
+ })
38
+
39
+ const execBatchSchema = z.object({
40
+ alias: z.string().describe('连接别名'),
41
+ commands: z.array(z.string()).describe('命令列表'),
42
+ stopOnError: z.boolean().optional().describe('遇到错误是否停止,默认 true'),
43
+ timeout: z.number().optional().describe('每条命令的超时(毫秒)'),
44
+ })
45
+
46
+ const quickExecSchema = z.object({
47
+ host: z.string().describe('服务器地址'),
48
+ user: z.string().describe('用户名'),
49
+ command: z.string().describe('要执行的命令'),
50
+ password: z.string().optional().describe('密码'),
51
+ keyPath: z.string().optional().describe('密钥路径'),
52
+ port: z.number().optional().describe('端口'),
53
+ timeout: z.number().optional().describe('超时(毫秒)'),
54
+ })
55
+
56
+ const execParallelSchema = z.object({
57
+ aliases: z.array(z.string()).describe('连接别名列表'),
58
+ command: z.string().describe('要执行的命令'),
59
+ timeout: z.number().optional().describe('每个命令的超时(毫秒),默认 30000'),
60
+ })
61
+
62
+ // ========== Handlers ==========
63
+
64
+ async function handleExec(args: z.infer<typeof execSchema>) {
65
+ try {
66
+ const result = await sessionManager.exec(
67
+ args.alias,
68
+ args.command,
69
+ {
70
+ timeout: args.timeout,
71
+ cwd: args.cwd,
72
+ env: args.env,
73
+ pty: args.pty,
74
+ },
75
+ )
76
+ return formatResult(result)
77
+ } catch (error) {
78
+ return formatError(error)
79
+ }
80
+ }
81
+
82
+ async function handleExecAsUser(args: z.infer<typeof execAsUserSchema>) {
83
+ try {
84
+ const result = await sessionManager.execAsUser(
85
+ args.alias,
86
+ args.command,
87
+ args.targetUser,
88
+ {
89
+ timeout: args.timeout,
90
+ loadProfile: args.loadProfile,
91
+ },
92
+ )
93
+ return formatResult(result)
94
+ } catch (error) {
95
+ return formatError(error)
96
+ }
97
+ }
98
+
99
+ async function handleExecSudo(args: z.infer<typeof execSudoSchema>) {
100
+ try {
101
+ const result = await sessionManager.execSudo(
102
+ args.alias,
103
+ args.command,
104
+ args.sudoPassword,
105
+ {timeout: args.timeout},
106
+ )
107
+ return formatResult(result)
108
+ } catch (error) {
109
+ return formatError(error)
110
+ }
111
+ }
112
+
113
+ async function handleExecBatch(args: z.infer<typeof execBatchSchema>) {
114
+ try {
115
+ const stopOnError = args.stopOnError !== false
116
+ const results: any[] = []
117
+
118
+ for (let i = 0; i < args.commands.length; i++) {
119
+ try {
120
+ const execResult = await sessionManager.exec(
121
+ args.alias,
122
+ args.commands[i],
123
+ {timeout: args.timeout},
124
+ )
125
+ results.push({
126
+ index: i,
127
+ command: args.commands[i],
128
+ ...execResult,
129
+ })
130
+ if (execResult.exitCode !== 0 && stopOnError) {
131
+ break
132
+ }
133
+ } catch (err: any) {
134
+ results.push({
135
+ index: i,
136
+ command: args.commands[i],
137
+ success: false,
138
+ error: err.message,
139
+ })
140
+ if (stopOnError) {
141
+ break
142
+ }
143
+ }
144
+ }
145
+
146
+ return formatResult({
147
+ success: results.every((r) => r.success),
148
+ total: args.commands.length,
149
+ executed: results.length,
150
+ results,
151
+ })
152
+ } catch (error) {
153
+ return formatError(error)
154
+ }
155
+ }
156
+
157
+ async function handleQuickExec(args: z.infer<typeof quickExecSchema>) {
158
+ const tempAlias = `_quick_${Date.now()}`
159
+ try {
160
+ await sessionManager.connect({
161
+ host: args.host,
162
+ port: args.port || 22,
163
+ username: args.user,
164
+ password: args.password,
165
+ privateKeyPath: args.keyPath,
166
+ alias: tempAlias,
167
+ })
168
+ const result = await sessionManager.exec(
169
+ tempAlias,
170
+ args.command,
171
+ {timeout: args.timeout},
172
+ )
173
+ return formatResult(result)
174
+ } catch (error) {
175
+ return formatError(error)
176
+ } finally {
177
+ sessionManager.disconnect(tempAlias)
178
+ }
179
+ }
180
+
181
+ async function handleExecParallel(args: z.infer<typeof execParallelSchema>) {
182
+ try {
183
+ const execPromises = args.aliases.map(async (alias) => {
184
+ try {
185
+ const execResult = await sessionManager.exec(alias, args.command, {timeout: args.timeout})
186
+ return {
187
+ alias,
188
+ success: execResult.success,
189
+ exitCode: execResult.exitCode,
190
+ stdout: execResult.stdout,
191
+ stderr: execResult.stderr,
192
+ duration: execResult.duration,
193
+ }
194
+ } catch (err: any) {
195
+ return {
196
+ alias,
197
+ success: false,
198
+ error: err.message,
199
+ }
200
+ }
201
+ })
202
+
203
+ const results = await Promise.all(execPromises)
204
+ return formatResult({
205
+ success: results.every(r => r.success),
206
+ total: args.aliases.length,
207
+ results,
208
+ })
209
+ } catch (error) {
210
+ return formatError(error)
211
+ }
212
+ }
213
+
214
+ // ========== Register ==========
215
+
216
+ export function registerExecTools(server: McpServer): void {
217
+ server.registerTool('ssh_exec', {
218
+ description: `在远程服务器执行命令。
219
+
220
+ 返回: stdout, stderr, exitCode, duration`,
221
+ inputSchema: execSchema,
222
+ }, (args) => handleExec(args))
223
+
224
+ server.registerTool('ssh_exec_as_user', {
225
+ description: `以其他用户身份执行命令(通过 su 切换)。
226
+
227
+ 适用场景: SSH 以 root 登录,但需要以其他用户(如 caros)执行命令。
228
+
229
+ 默认加载目标用户的 shell 配置以获取环境变量(su -c 创建非交互式 shell,不会自动执行 rc 文件)。
230
+ 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)。
231
+
232
+ 示例: ssh_exec_as_user(alias="server", command="whoami", targetUser="caros")`,
233
+ inputSchema: execAsUserSchema,
234
+ }, (args) => handleExecAsUser(args))
235
+
236
+ server.registerTool('ssh_exec_sudo', {
237
+ description: '使用 sudo 执行命令',
238
+ inputSchema: execSudoSchema,
239
+ }, (args) => handleExecSudo(args))
240
+
241
+ server.registerTool('ssh_exec_batch', {
242
+ description: '批量执行多条命令',
243
+ inputSchema: execBatchSchema,
244
+ }, (args) => handleExecBatch(args))
245
+
246
+ server.registerTool('ssh_quick_exec', {
247
+ description: '一次性执行命令(自动连接、执行、断开)。适用于单次命令,不需要保持连接。',
248
+ inputSchema: quickExecSchema,
249
+ }, (args) => handleQuickExec(args))
250
+
251
+ server.registerTool('ssh_exec_parallel', {
252
+ description: `在多个已连接的会话上并行执行同一命令。
253
+
254
+ 示例:
255
+ - ssh_exec_parallel(aliases=["server1", "server2"], command="uptime")
256
+
257
+ 返回每个主机的执行结果。`,
258
+ inputSchema: execParallelSchema,
259
+ }, (args) => handleExecParallel(args))
260
+ }