@pyrokine/mcp-ssh 1.3.0 → 2.0.1

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/src/ssh-config.ts DELETED
@@ -1,257 +0,0 @@
1
- /**
2
- * SSH Config Parser
3
- *
4
- * 解析 ~/.ssh/config 文件,提取 Host 配置
5
- * 支持:
6
- * - Host 多别名(Host a b c)
7
- * - Host * 全局默认配置继承
8
- * - ProxyJump 解析(支持 user@host:port 格式)
9
- */
10
-
11
- import * as fs from 'fs'
12
- import * as os from 'os'
13
- import * as path from 'path'
14
-
15
- export interface SSHConfigHost {
16
- host: string; // Host 别名
17
- hostName?: string; // 实际地址
18
- user?: string; // 用户名
19
- port?: number; // 端口
20
- identityFile?: string; // 私钥路径
21
- proxyJump?: string; // 跳板机(原始字符串,可能是 user@host:port 格式)
22
- }
23
-
24
- /** ProxyJump 解析结果 */
25
- export interface ParsedProxyJump {
26
- user?: string;
27
- host: string;
28
- port?: number;
29
- }
30
-
31
- /** 内部使用的配置块 */
32
- interface ConfigBlock {
33
- patterns: string[]; // Host 行的所有模式/别名
34
- config: Omit<SSHConfigHost, 'host'>;
35
- }
36
-
37
- /**
38
- * 解析 host:port 或 [ipv6]:port
39
- * 返回 { host, port },host 不含方括号
40
- */
41
- function parseHostPort(s: string): { host: string; port?: number } {
42
- // IPv6 方括号格式: [addr]:port 或 [addr]
43
- if (s.startsWith('[')) {
44
- const closeBracket = s.indexOf(']')
45
- if (closeBracket !== -1) {
46
- const host = s.slice(1, closeBracket) // 去掉方括号
47
- const rest = s.slice(closeBracket + 1)
48
- if (rest.startsWith(':')) {
49
- const parsedPort = parseInt(rest.slice(1), 10)
50
- if (!isNaN(parsedPort)) {
51
- return { host, port: parsedPort }
52
- }
53
- }
54
- return { host }
55
- }
56
- }
57
-
58
- // 检测裸 IPv6(多个冒号但无方括号):安全失败,当作 host-only
59
- const colonCount = (s.match(/:/g) || []).length
60
- if (colonCount >= 2) {
61
- return { host: s }
62
- }
63
-
64
- // 普通格式: host:port 或 host
65
- const colonIndex = s.lastIndexOf(':')
66
- if (colonIndex !== -1) {
67
- const host = s.slice(0, colonIndex)
68
- const portStr = s.slice(colonIndex + 1)
69
- const parsedPort = parseInt(portStr, 10)
70
- if (!isNaN(parsedPort)) {
71
- return { host, port: parsedPort }
72
- }
73
- }
74
- return { host: s }
75
- }
76
-
77
- /**
78
- * 解析 ProxyJump 字符串
79
- * 支持格式:host, user@host, host:port, user@host:port, [ipv6]:port
80
- * 注意:只解析第一跳,不支持逗号分隔的多跳链路
81
- */
82
- export function parseProxyJump(proxyJump: string): ParsedProxyJump | null {
83
- if (!proxyJump) {
84
- return null
85
- }
86
-
87
- // 取第一跳(如果有逗号分隔)
88
- const firstJump = proxyJump.split(',')[0].trim()
89
- if (!firstJump) {
90
- return null
91
- }
92
-
93
- let user: string | undefined
94
-
95
- // 解析 user@... 格式
96
- const atIndex = firstJump.indexOf('@')
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 }
102
- }
103
-
104
- const { host, port } = parseHostPort(firstJump)
105
- return { host, port }
106
- }
107
-
108
- /**
109
- * 展开 ~ 路径
110
- */
111
- function expandTilde(filePath: string): string {
112
- if (filePath.startsWith('~')) {
113
- return path.join(os.homedir(), filePath.slice(1))
114
- }
115
- return filePath
116
- }
117
-
118
- /**
119
- * 剥离行尾注释
120
- * "value # comment" -> "value"
121
- */
122
- function stripInlineComment(value: string): string {
123
- // 查找不在引号内的 #
124
- let inQuote = false
125
- let quoteChar = ''
126
- for (let i = 0; i < value.length; i++) {
127
- const ch = value[i]
128
- if (!inQuote && (ch === '"' || ch === '\'')) {
129
- inQuote = true
130
- quoteChar = ch
131
- } else if (inQuote && ch === quoteChar) {
132
- inQuote = false
133
- } else if (!inQuote && ch === '#') {
134
- return value.slice(0, i).trim()
135
- }
136
- }
137
- return value.trim()
138
- }
139
-
140
- /**
141
- * 解析 SSH config 文件
142
- * 支持 Host 多别名和 Host * 继承
143
- * 跳过 Match 块(避免条件配置被误应用)
144
- */
145
- export function parseSSHConfig(configPath?: string): SSHConfigHost[] {
146
- const filePath = configPath || path.join(os.homedir(), '.ssh', 'config')
147
-
148
- if (!fs.existsSync(filePath)) {
149
- return []
150
- }
151
-
152
- const content = fs.readFileSync(filePath, 'utf-8')
153
- const lines = content.split('\n')
154
-
155
- // 第一遍:收集所有配置块
156
- const blocks: ConfigBlock[] = []
157
- let currentBlock: ConfigBlock | null = null
158
- let globalDefaults: Omit<SSHConfigHost, 'host'> = {}
159
- let inMatchBlock = false // 跳过 Match 块
160
-
161
- for (const line of lines) {
162
- const trimmed = line.trim()
163
-
164
- // 跳过空行和注释
165
- if (!trimmed || trimmed.startsWith('#')) {
166
- continue
167
- }
168
-
169
- // 解析 key value(支持 = 和空格分隔)
170
- const match = trimmed.match(/^(\S+)\s*[=\s]\s*(.+)$/)
171
- if (!match) {
172
- continue
173
- }
174
-
175
- const [, key, rawValue] = match
176
- const keyLower = key.toLowerCase()
177
- const value = stripInlineComment(rawValue)
178
-
179
- if (keyLower === 'host') {
180
- // Host 块开始,结束 Match 块
181
- inMatchBlock = false
182
-
183
- // 保存上一个 block
184
- if (currentBlock) {
185
- blocks.push(currentBlock)
186
- }
187
-
188
- // Host 行可能有多个别名/模式,用空格分隔
189
- const patterns = value.split(/\s+/).filter(p => p.length > 0)
190
- currentBlock = { patterns, config: {} }
191
- } else if (keyLower === 'match') {
192
- // Match 块开始,跳过直到下一个 Host
193
- inMatchBlock = true
194
- // 保存当前 block(如果有)
195
- if (currentBlock) {
196
- blocks.push(currentBlock)
197
- currentBlock = null
198
- }
199
- } else if (!inMatchBlock && currentBlock) {
200
- // 解析配置项(不在 Match 块内)
201
- switch (keyLower) {
202
- case 'hostname':
203
- currentBlock.config.hostName = value
204
- break
205
- case 'user':
206
- currentBlock.config.user = value
207
- break
208
- case 'port':
209
- currentBlock.config.port = parseInt(value, 10)
210
- break
211
- case 'identityfile':
212
- currentBlock.config.identityFile = expandTilde(value)
213
- break
214
- case 'proxyjump':
215
- currentBlock.config.proxyJump = value
216
- break
217
- }
218
- }
219
- }
220
-
221
- // 保存最后一个 block
222
- if (currentBlock && !inMatchBlock) {
223
- blocks.push(currentBlock)
224
- }
225
-
226
- // 第二遍:提取 Host * 的全局默认配置
227
- for (const block of blocks) {
228
- if (block.patterns.length === 1 && block.patterns[0] === '*') {
229
- globalDefaults = { ...block.config }
230
- break
231
- }
232
- }
233
-
234
- // 第三遍:展开所有 Host,应用继承
235
- const hosts: SSHConfigHost[] = []
236
-
237
- for (const block of blocks) {
238
- for (const pattern of block.patterns) {
239
- // 跳过通配符模式(*, *.example.com 等)
240
- if (pattern.includes('*') || pattern.includes('?')) {
241
- continue
242
- }
243
-
244
- // 合并配置:全局默认 + 当前块配置
245
- const merged: SSHConfigHost = {
246
- host: pattern,
247
- ...globalDefaults,
248
- ...block.config,
249
- }
250
-
251
- hosts.push(merged)
252
- }
253
- }
254
-
255
- return hosts
256
- }
257
-
@@ -1,240 +0,0 @@
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
- }