@pyrokine/mcp-ssh 1.3.0 → 2.0.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.
@@ -1,258 +0,0 @@
1
- /**
2
- * 端口转发管理器
3
- *
4
- * 负责本地/远程端口转发的完整生命周期
5
- */
6
-
7
- import * as net from 'net'
8
- import type {Client, ClientChannel} from 'ssh2'
9
- import type {PortForwardInfo} from './types.js'
10
-
11
- /** 端口转发所需的外部依赖 */
12
- export interface ForwardDependencies {
13
- /** 获取 SSH client */
14
- getClient(alias: string): Client;
15
- }
16
-
17
- interface ForwardSession {
18
- id: string;
19
- alias: string;
20
- type: 'local' | 'remote';
21
- localHost: string;
22
- localPort: number;
23
- remoteHost: string;
24
- remotePort: number;
25
- server?: net.Server;
26
- createdAt: number;
27
- active: boolean;
28
- }
29
-
30
- // tcp connection 事件处理函数类型
31
- type TcpConnectionHandler = (
32
- info: { destIP: string; destPort: number; srcIP: string; srcPort: number },
33
- accept: () => ClientChannel,
34
- reject: () => void,
35
- ) => void;
36
-
37
- /** 每个 SSH session 的 dispatcher 状态 */
38
- interface DispatcherState {
39
- handler: TcpConnectionHandler;
40
- client: Client;
41
- }
42
-
43
- export class ForwardManager {
44
- private sessions: Map<string, ForwardSession> = new Map()
45
- private dispatchers: Map<string, DispatcherState> = new Map() // alias → dispatcher
46
- private idCounter = 0
47
-
48
- async forwardLocal(
49
- deps: ForwardDependencies,
50
- alias: string,
51
- localPort: number,
52
- remoteHost: string,
53
- remotePort: number,
54
- localHost: string = '127.0.0.1',
55
- ): Promise<string> {
56
- const client = deps.getClient(alias)
57
- const forwardId = this.generateId()
58
-
59
- return new Promise((resolve, reject) => {
60
- const server = net.createServer((socket) => {
61
- client.forwardOut(
62
- socket.remoteAddress || '127.0.0.1',
63
- socket.remotePort || 0,
64
- remoteHost,
65
- remotePort,
66
- (err, stream) => {
67
- if (err) {
68
- socket.end()
69
- return
70
- }
71
- socket.pipe(stream).pipe(socket)
72
- },
73
- )
74
- })
75
-
76
- server.on('error', (err) => {
77
- reject(new Error(`Local forward failed: ${err.message}`))
78
- })
79
-
80
- server.listen(localPort, localHost, () => {
81
- this.sessions.set(forwardId, {
82
- id: forwardId,
83
- alias,
84
- type: 'local',
85
- localHost,
86
- localPort,
87
- remoteHost,
88
- remotePort,
89
- server,
90
- createdAt: Date.now(),
91
- active: true,
92
- })
93
- resolve(forwardId)
94
- })
95
- })
96
- }
97
-
98
- async forwardRemote(
99
- deps: ForwardDependencies,
100
- alias: string,
101
- remotePort: number,
102
- localHost: string,
103
- localPort: number,
104
- remoteHost: string = '127.0.0.1',
105
- ): Promise<string> {
106
- const client = deps.getClient(alias)
107
- const forwardId = this.generateId()
108
-
109
- return new Promise((resolve, reject) => {
110
- client.forwardIn(remoteHost, remotePort, (err) => {
111
- if (err) {
112
- reject(new Error(`Remote forward failed: ${err.message}`))
113
- return
114
- }
115
-
116
- this.sessions.set(forwardId, {
117
- id: forwardId,
118
- alias,
119
- type: 'remote',
120
- localHost,
121
- localPort,
122
- remoteHost,
123
- remotePort,
124
- createdAt: Date.now(),
125
- active: true,
126
- })
127
-
128
- this.ensureTcpDispatcher(alias, client)
129
- resolve(forwardId)
130
- })
131
- })
132
- }
133
-
134
- close(forwardId: string, deps?: ForwardDependencies): boolean {
135
- const fwd = this.sessions.get(forwardId)
136
- if (!fwd) {
137
- return false
138
- }
139
-
140
- fwd.active = false
141
-
142
- if (fwd.type === 'local' && fwd.server) {
143
- try {
144
- fwd.server.close()
145
- } catch (e) {
146
- console.warn(`Forward ${forwardId} server close failed:`, (e as Error).message)
147
- }
148
- } else if (fwd.type === 'remote' && deps) {
149
- try {
150
- const client = deps.getClient(fwd.alias)
151
- client.unforwardIn(fwd.remoteHost, fwd.remotePort)
152
- } catch { /* session 可能已断开 */
153
- }
154
- this.removeTcpDispatcherIfEmpty(fwd.alias)
155
- }
156
-
157
- this.sessions.delete(forwardId)
158
- return true
159
- }
160
-
161
- /** 关闭指定 alias 的所有转发(disconnect 时调用,不需要 unforwardIn) */
162
- closeByAlias(alias: string): void {
163
- for (const [id, fwd] of this.sessions) {
164
- if (fwd.alias === alias) {
165
- fwd.active = false
166
- if (fwd.type === 'local' && fwd.server) {
167
- try {
168
- fwd.server.close()
169
- } catch (e) {
170
- console.warn(`Forward ${id} server close failed:`, (e as Error).message)
171
- }
172
- }
173
- this.sessions.delete(id)
174
- }
175
- }
176
- // 清理该 alias 的 dispatcher
177
- const state = this.dispatchers.get(alias)
178
- if (state) {
179
- try {
180
- state.client.removeListener('tcp connection', state.handler)
181
- } catch { /* client 可能已关闭 */
182
- }
183
- this.dispatchers.delete(alias)
184
- }
185
- }
186
-
187
- list(): PortForwardInfo[] {
188
- const result: PortForwardInfo[] = []
189
- for (const [id, fwd] of this.sessions) {
190
- result.push({
191
- id,
192
- alias: fwd.alias,
193
- type: fwd.type,
194
- localHost: fwd.localHost,
195
- localPort: fwd.localPort,
196
- remoteHost: fwd.remoteHost,
197
- remotePort: fwd.remotePort,
198
- createdAt: fwd.createdAt,
199
- active: fwd.active,
200
- })
201
- }
202
- return result
203
- }
204
-
205
- /**
206
- * 确保 SSH session 有共享的 tcp connection dispatcher
207
- * 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
208
- */
209
- private ensureTcpDispatcher(alias: string, client: Client): void {
210
- if (this.dispatchers.has(alias)) {
211
- return
212
- }
213
-
214
- const handler: TcpConnectionHandler = (info, accept, rejectConn) => {
215
- for (const fwd of this.sessions.values()) {
216
- if (fwd.type === 'remote' &&
217
- fwd.active &&
218
- fwd.alias === alias &&
219
- fwd.remoteHost === info.destIP &&
220
- fwd.remotePort === info.destPort) {
221
- const stream = accept()
222
- const socket = net.createConnection(fwd.localPort, fwd.localHost)
223
- socket.pipe(stream).pipe(socket)
224
- socket.on('error', () => stream.close())
225
- stream.on('error', () => socket.destroy())
226
- return
227
- }
228
- }
229
- rejectConn()
230
- }
231
-
232
- this.dispatchers.set(alias, { handler, client })
233
- client.on('tcp connection', handler)
234
- }
235
-
236
- /**
237
- * 移除 dispatcher(当没有活跃的 remote forward 时)
238
- */
239
- private removeTcpDispatcherIfEmpty(alias: string): void {
240
- const state = this.dispatchers.get(alias)
241
- if (!state) {
242
- return
243
- }
244
-
245
- for (const fwd of this.sessions.values()) {
246
- if (fwd.type === 'remote' && fwd.alias === alias && fwd.active) {
247
- return // 还有活跃的 remote forward
248
- }
249
- }
250
-
251
- state.client.removeListener('tcp connection', state.handler)
252
- this.dispatchers.delete(alias)
253
- }
254
-
255
- private generateId(): string {
256
- return `fwd_${++this.idCounter}_${Date.now()}`
257
- }
258
- }
package/src/index.ts DELETED
@@ -1,62 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * SSH MCP Pro - Main Server Entry
4
- *
5
- * A comprehensive SSH MCP Server for Claude Code
6
- *
7
- * Features:
8
- * - Multiple authentication methods (password, key, agent)
9
- * - Connection pooling with keepalive
10
- * - Session persistence
11
- * - Command execution (exec, sudo, su)
12
- * - File operations (upload, download, read, write)
13
- * - Environment configuration
14
- * - Jump host support
15
- */
16
-
17
- import {McpServer} from '@modelcontextprotocol/sdk/server/mcp.js'
18
- import {StdioServerTransport} from '@modelcontextprotocol/sdk/server/stdio.js'
19
- import {
20
- registerConnectionTools,
21
- registerExecTools,
22
- registerFileTools,
23
- registerForwardTools,
24
- registerPtyTools,
25
- } from './tools/index.js'
26
-
27
- const server = new McpServer(
28
- { name: 'ssh-mcp-pro', version: '1.2.2' },
29
- { capabilities: { tools: {} } },
30
- )
31
-
32
- registerConnectionTools(server)
33
- registerExecTools(server)
34
- registerFileTools(server)
35
- registerPtyTools(server)
36
- registerForwardTools(server)
37
-
38
- async function main() {
39
- // 防止父进程退出后成为孤儿进程持续占用 CPU
40
- process.on('uncaughtException', (error: NodeJS.ErrnoException) => {
41
- if (error.code === 'EPIPE' || error.code === 'ERR_STREAM_DESTROYED') {
42
- process.exit(0)
43
- }
44
- try {
45
- console.error('[MCP] Uncaught exception:', error)
46
- } catch {
47
- process.exit(1)
48
- }
49
- })
50
- process.stdin.on('end', () => process.exit(0))
51
- process.stdout.on('error', () => process.exit(0))
52
- process.stderr.on('error', () => process.exit(0))
53
-
54
- const transport = new StdioServerTransport()
55
- await server.connect(transport)
56
- console.error('SSH MCP Pro server started')
57
- }
58
-
59
- main().catch((error) => {
60
- console.error('Fatal error:', error)
61
- process.exit(1)
62
- })
@@ -1,220 +0,0 @@
1
- /**
2
- * PTY 会话管理器
3
- *
4
- * 负责 PTY 会话的完整生命周期:创建、读写、调整大小、关闭
5
- */
6
-
7
- import xterm from '@xterm/headless'
8
- import type {ClientChannel} from 'ssh2'
9
- import type {PtyOptions, PtySessionInfo} from './types.js'
10
-
11
- const Terminal = xterm.Terminal as typeof import('@xterm/headless').Terminal
12
- type TerminalType = import('@xterm/headless').Terminal;
13
-
14
- /** PTY 创建所需的外部依赖 */
15
- export interface PtyDependencies {
16
- /** 通过 alias 获取 SSH client 并执行命令 */
17
- execPty(alias: string, command: string, options: PtyOptions): Promise<ClientChannel>;
18
- }
19
-
20
- interface PtySession {
21
- id: string;
22
- alias: string;
23
- command: string;
24
- stream: ClientChannel;
25
- terminal: TerminalType;
26
- rows: number;
27
- cols: number;
28
- createdAt: number;
29
- lastReadAt: number;
30
- rawBuffer: string;
31
- maxBufferSize: number;
32
- active: boolean;
33
- }
34
-
35
- export class PtyManager {
36
- private sessions: Map<string, PtySession> = new Map()
37
- private idCounter = 0
38
- private readonly defaultBufferSize = 1024 * 1024 // 1MB
39
-
40
- async start(
41
- deps: PtyDependencies,
42
- alias: string,
43
- command: string,
44
- options: PtyOptions = {},
45
- ): Promise<string> {
46
- const ptyId = this.generateId()
47
- const rows = options.rows || 24
48
- const cols = options.cols || 80
49
- const maxBufferSize = options.bufferSize || this.defaultBufferSize
50
-
51
- const stream = await deps.execPty(alias, command, options)
52
-
53
- // 创建 xterm headless 终端仿真器
54
- const terminal = new Terminal({ rows, cols, allowProposedApi: true })
55
-
56
- const ptySession: PtySession = {
57
- id: ptyId,
58
- alias,
59
- command,
60
- stream,
61
- terminal,
62
- rows,
63
- cols,
64
- createdAt: Date.now(),
65
- lastReadAt: Date.now(),
66
- rawBuffer: '',
67
- maxBufferSize,
68
- active: true,
69
- }
70
-
71
- // 监听输出数据
72
- stream.on('data', (data: Buffer) => {
73
- if (!ptySession.active) {
74
- return
75
- }
76
- const chunk = data.toString('utf-8')
77
- // 写入终端仿真器(解析 ANSI 序列)
78
- terminal.write(chunk)
79
- // 同时保留原始流(用于 raw 模式)
80
- ptySession.rawBuffer += chunk
81
- if (ptySession.rawBuffer.length > maxBufferSize) {
82
- ptySession.rawBuffer = ptySession.rawBuffer.slice(-maxBufferSize)
83
- }
84
- })
85
-
86
- stream.on('close', () => {
87
- ptySession.active = false
88
- })
89
-
90
- stream.on('error', (err: Error) => {
91
- ptySession.active = false
92
- terminal.write(`\n[PTY Error: ${err.message}]`)
93
- })
94
-
95
- this.sessions.set(ptyId, ptySession)
96
- return ptyId
97
- }
98
-
99
- write(ptyId: string, data: string): boolean {
100
- const session = this.getSession(ptyId)
101
- if (!session.active) {
102
- throw new Error(`PTY session '${ptyId}' is closed`)
103
- }
104
- return session.stream.write(data)
105
- }
106
-
107
- read(
108
- ptyId: string,
109
- options: { mode?: 'screen' | 'raw'; clear?: boolean } = {},
110
- ): { data: string; active: boolean; rows: number; cols: number } {
111
- const session = this.getSession(ptyId)
112
- const mode = options.mode || 'screen'
113
- const clear = options.clear !== false
114
-
115
- let data: string
116
- if (mode === 'screen') {
117
- data = this.getScreenContent(session.terminal)
118
- } else {
119
- data = session.rawBuffer
120
- if (clear) {
121
- session.rawBuffer = ''
122
- }
123
- }
124
-
125
- session.lastReadAt = Date.now()
126
- return {
127
- data,
128
- active: session.active,
129
- rows: session.rows,
130
- cols: session.cols,
131
- }
132
- }
133
-
134
- resize(ptyId: string, rows: number, cols: number): boolean {
135
- const session = this.getSession(ptyId)
136
- if (!session.active) {
137
- throw new Error(`PTY session '${ptyId}' is closed`)
138
- }
139
- session.stream.setWindow(rows, cols, 0, 0)
140
- session.terminal.resize(cols, rows)
141
- session.rows = rows
142
- session.cols = cols
143
- return true
144
- }
145
-
146
- close(ptyId: string): boolean {
147
- const session = this.sessions.get(ptyId)
148
- if (!session) {
149
- return false
150
- }
151
- try {
152
- session.stream.close()
153
- } catch (e) {
154
- console.warn(`PTY ${ptyId} stream close failed:`, (e as Error).message)
155
- }
156
- try {
157
- session.terminal.dispose()
158
- } catch (e) {
159
- console.warn(`PTY ${ptyId} terminal dispose failed:`, (e as Error).message)
160
- }
161
- session.active = false
162
- this.sessions.delete(ptyId)
163
- return true
164
- }
165
-
166
- /** 关闭指定 alias 的所有 PTY 会话 */
167
- closeByAlias(alias: string): void {
168
- for (const [id, session] of this.sessions) {
169
- if (session.alias === alias) {
170
- this.close(id)
171
- }
172
- }
173
- }
174
-
175
- list(): PtySessionInfo[] {
176
- const result: PtySessionInfo[] = []
177
- for (const [id, pty] of this.sessions) {
178
- result.push({
179
- id,
180
- alias: pty.alias,
181
- command: pty.command,
182
- rows: pty.rows,
183
- cols: pty.cols,
184
- createdAt: pty.createdAt,
185
- lastReadAt: pty.lastReadAt,
186
- bufferSize: pty.rawBuffer.length,
187
- active: pty.active,
188
- })
189
- }
190
- return result
191
- }
192
-
193
- private getSession(ptyId: string): PtySession {
194
- const session = this.sessions.get(ptyId)
195
- if (!session) {
196
- throw new Error(`PTY session '${ptyId}' not found`)
197
- }
198
- return session
199
- }
200
-
201
- private generateId(): string {
202
- return `pty_${++this.idCounter}_${Date.now()}`
203
- }
204
-
205
- /** 从终端仿真器获取当前屏幕内容 */
206
- private getScreenContent(terminal: TerminalType): string {
207
- const buffer = terminal.buffer.active
208
- const lines: string[] = []
209
- for (let i = 0; i < terminal.rows; i++) {
210
- const line = buffer.getLine(i)
211
- if (line) {
212
- lines.push(line.translateToString(true))
213
- }
214
- }
215
- while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
216
- lines.pop()
217
- }
218
- return lines.join('\n')
219
- }
220
- }