@pyrokine/mcp-ssh 1.1.3 → 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.
package/README.md CHANGED
@@ -80,7 +80,9 @@ Add to your MCP settings (e.g., `~/.claude/settings.json` or client-specific con
80
80
  "mcpServers": {
81
81
  "ssh": {
82
82
  "command": "node",
83
- "args": ["/path/to/mcp-ssh/dist/index.js"]
83
+ "args": [
84
+ "/path/to/mcp-ssh/dist/index.js"
85
+ ]
84
86
  }
85
87
  }
86
88
  }
package/README_zh.md CHANGED
@@ -80,7 +80,9 @@ claude mcp add ssh -- node /path/to/mcp-ssh/dist/index.js
80
80
  "mcpServers": {
81
81
  "ssh": {
82
82
  "command": "node",
83
- "args": ["/path/to/mcp-ssh/dist/index.js"]
83
+ "args": [
84
+ "/path/to/mcp-ssh/dist/index.js"
85
+ ]
84
86
  }
85
87
  }
86
88
  }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * 端口转发管理器
3
+ *
4
+ * 负责本地/远程端口转发的完整生命周期
5
+ */
6
+ import type { Client } from 'ssh2';
7
+ import type { PortForwardInfo } from './types.js';
8
+ /** 端口转发所需的外部依赖 */
9
+ export interface ForwardDependencies {
10
+ /** 获取 SSH client */
11
+ getClient(alias: string): Client;
12
+ }
13
+ export declare class ForwardManager {
14
+ private sessions;
15
+ private dispatchers;
16
+ private idCounter;
17
+ forwardLocal(deps: ForwardDependencies, alias: string, localPort: number, remoteHost: string, remotePort: number, localHost?: string): Promise<string>;
18
+ forwardRemote(deps: ForwardDependencies, alias: string, remotePort: number, localHost: string, localPort: number, remoteHost?: string): Promise<string>;
19
+ close(forwardId: string, deps?: ForwardDependencies): boolean;
20
+ /** 关闭指定 alias 的所有转发(disconnect 时调用,不需要 unforwardIn) */
21
+ closeByAlias(alias: string): void;
22
+ list(): PortForwardInfo[];
23
+ /**
24
+ * 确保 SSH session 有共享的 tcp connection dispatcher
25
+ * 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
26
+ */
27
+ private ensureTcpDispatcher;
28
+ /**
29
+ * 移除 dispatcher(当没有活跃的 remote forward 时)
30
+ */
31
+ private removeTcpDispatcherIfEmpty;
32
+ private generateId;
33
+ }
@@ -0,0 +1,185 @@
1
+ /**
2
+ * 端口转发管理器
3
+ *
4
+ * 负责本地/远程端口转发的完整生命周期
5
+ */
6
+ import * as net from 'net';
7
+ export class ForwardManager {
8
+ sessions = new Map();
9
+ dispatchers = new Map(); // alias → dispatcher
10
+ idCounter = 0;
11
+ async forwardLocal(deps, alias, localPort, remoteHost, remotePort, localHost = '127.0.0.1') {
12
+ const client = deps.getClient(alias);
13
+ const forwardId = this.generateId();
14
+ return new Promise((resolve, reject) => {
15
+ const server = net.createServer((socket) => {
16
+ client.forwardOut(socket.remoteAddress || '127.0.0.1', socket.remotePort || 0, remoteHost, remotePort, (err, stream) => {
17
+ if (err) {
18
+ socket.end();
19
+ return;
20
+ }
21
+ socket.pipe(stream).pipe(socket);
22
+ });
23
+ });
24
+ server.on('error', (err) => {
25
+ reject(new Error(`Local forward failed: ${err.message}`));
26
+ });
27
+ server.listen(localPort, localHost, () => {
28
+ this.sessions.set(forwardId, {
29
+ id: forwardId,
30
+ alias,
31
+ type: 'local',
32
+ localHost,
33
+ localPort,
34
+ remoteHost,
35
+ remotePort,
36
+ server,
37
+ createdAt: Date.now(),
38
+ active: true,
39
+ });
40
+ resolve(forwardId);
41
+ });
42
+ });
43
+ }
44
+ async forwardRemote(deps, alias, remotePort, localHost, localPort, remoteHost = '127.0.0.1') {
45
+ const client = deps.getClient(alias);
46
+ const forwardId = this.generateId();
47
+ return new Promise((resolve, reject) => {
48
+ client.forwardIn(remoteHost, remotePort, (err) => {
49
+ if (err) {
50
+ reject(new Error(`Remote forward failed: ${err.message}`));
51
+ return;
52
+ }
53
+ this.sessions.set(forwardId, {
54
+ id: forwardId,
55
+ alias,
56
+ type: 'remote',
57
+ localHost,
58
+ localPort,
59
+ remoteHost,
60
+ remotePort,
61
+ createdAt: Date.now(),
62
+ active: true,
63
+ });
64
+ this.ensureTcpDispatcher(alias, client);
65
+ resolve(forwardId);
66
+ });
67
+ });
68
+ }
69
+ close(forwardId, deps) {
70
+ const fwd = this.sessions.get(forwardId);
71
+ if (!fwd) {
72
+ return false;
73
+ }
74
+ fwd.active = false;
75
+ if (fwd.type === 'local' && fwd.server) {
76
+ try {
77
+ fwd.server.close();
78
+ }
79
+ catch (e) {
80
+ console.warn(`Forward ${forwardId} server close failed:`, e.message);
81
+ }
82
+ }
83
+ else if (fwd.type === 'remote' && deps) {
84
+ try {
85
+ const client = deps.getClient(fwd.alias);
86
+ client.unforwardIn(fwd.remoteHost, fwd.remotePort);
87
+ }
88
+ catch { /* session 可能已断开 */
89
+ }
90
+ this.removeTcpDispatcherIfEmpty(fwd.alias);
91
+ }
92
+ this.sessions.delete(forwardId);
93
+ return true;
94
+ }
95
+ /** 关闭指定 alias 的所有转发(disconnect 时调用,不需要 unforwardIn) */
96
+ closeByAlias(alias) {
97
+ for (const [id, fwd] of this.sessions) {
98
+ if (fwd.alias === alias) {
99
+ fwd.active = false;
100
+ if (fwd.type === 'local' && fwd.server) {
101
+ try {
102
+ fwd.server.close();
103
+ }
104
+ catch (e) {
105
+ console.warn(`Forward ${id} server close failed:`, e.message);
106
+ }
107
+ }
108
+ this.sessions.delete(id);
109
+ }
110
+ }
111
+ // 清理该 alias 的 dispatcher
112
+ const state = this.dispatchers.get(alias);
113
+ if (state) {
114
+ try {
115
+ state.client.removeListener('tcp connection', state.handler);
116
+ }
117
+ catch { /* client 可能已关闭 */ }
118
+ this.dispatchers.delete(alias);
119
+ }
120
+ }
121
+ list() {
122
+ const result = [];
123
+ for (const [id, fwd] of this.sessions) {
124
+ result.push({
125
+ id,
126
+ alias: fwd.alias,
127
+ type: fwd.type,
128
+ localHost: fwd.localHost,
129
+ localPort: fwd.localPort,
130
+ remoteHost: fwd.remoteHost,
131
+ remotePort: fwd.remotePort,
132
+ createdAt: fwd.createdAt,
133
+ active: fwd.active,
134
+ });
135
+ }
136
+ return result;
137
+ }
138
+ /**
139
+ * 确保 SSH session 有共享的 tcp connection dispatcher
140
+ * 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
141
+ */
142
+ ensureTcpDispatcher(alias, client) {
143
+ if (this.dispatchers.has(alias)) {
144
+ return;
145
+ }
146
+ const handler = (info, accept, rejectConn) => {
147
+ for (const fwd of this.sessions.values()) {
148
+ if (fwd.type === 'remote' &&
149
+ fwd.active &&
150
+ fwd.alias === alias &&
151
+ fwd.remoteHost === info.destIP &&
152
+ fwd.remotePort === info.destPort) {
153
+ const stream = accept();
154
+ const socket = net.createConnection(fwd.localPort, fwd.localHost);
155
+ socket.pipe(stream).pipe(socket);
156
+ socket.on('error', () => stream.close());
157
+ stream.on('error', () => socket.destroy());
158
+ return;
159
+ }
160
+ }
161
+ rejectConn();
162
+ };
163
+ this.dispatchers.set(alias, { handler, client });
164
+ client.on('tcp connection', handler);
165
+ }
166
+ /**
167
+ * 移除 dispatcher(当没有活跃的 remote forward 时)
168
+ */
169
+ removeTcpDispatcherIfEmpty(alias) {
170
+ const state = this.dispatchers.get(alias);
171
+ if (!state) {
172
+ return;
173
+ }
174
+ for (const fwd of this.sessions.values()) {
175
+ if (fwd.type === 'remote' && fwd.alias === alias && fwd.active) {
176
+ return; // 还有活跃的 remote forward
177
+ }
178
+ }
179
+ state.client.removeListener('tcp connection', state.handler);
180
+ this.dispatchers.delete(alias);
181
+ }
182
+ generateId() {
183
+ return `fwd_${++this.idCounter}_${Date.now()}`;
184
+ }
185
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * PTY 会话管理器
3
+ *
4
+ * 负责 PTY 会话的完整生命周期:创建、读写、调整大小、关闭
5
+ */
6
+ import type { ClientChannel } from 'ssh2';
7
+ import type { PtyOptions, PtySessionInfo } from './types.js';
8
+ /** PTY 创建所需的外部依赖 */
9
+ export interface PtyDependencies {
10
+ /** 通过 alias 获取 SSH client 并执行命令 */
11
+ execPty(alias: string, command: string, options: PtyOptions): Promise<ClientChannel>;
12
+ }
13
+ export declare class PtyManager {
14
+ private sessions;
15
+ private idCounter;
16
+ private readonly defaultBufferSize;
17
+ start(deps: PtyDependencies, alias: string, command: string, options?: PtyOptions): Promise<string>;
18
+ write(ptyId: string, data: string): boolean;
19
+ read(ptyId: string, options?: {
20
+ mode?: 'screen' | 'raw';
21
+ clear?: boolean;
22
+ }): {
23
+ data: string;
24
+ active: boolean;
25
+ rows: number;
26
+ cols: number;
27
+ };
28
+ resize(ptyId: string, rows: number, cols: number): boolean;
29
+ close(ptyId: string): boolean;
30
+ /** 关闭指定 alias 的所有 PTY 会话 */
31
+ closeByAlias(alias: string): void;
32
+ list(): PtySessionInfo[];
33
+ private getSession;
34
+ private generateId;
35
+ /** 从终端仿真器获取当前屏幕内容 */
36
+ private getScreenContent;
37
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * PTY 会话管理器
3
+ *
4
+ * 负责 PTY 会话的完整生命周期:创建、读写、调整大小、关闭
5
+ */
6
+ import xterm from '@xterm/headless';
7
+ const Terminal = xterm.Terminal;
8
+ export class PtyManager {
9
+ sessions = new Map();
10
+ idCounter = 0;
11
+ defaultBufferSize = 1024 * 1024; // 1MB
12
+ async start(deps, alias, command, options = {}) {
13
+ const ptyId = this.generateId();
14
+ const rows = options.rows || 24;
15
+ const cols = options.cols || 80;
16
+ const maxBufferSize = options.bufferSize || this.defaultBufferSize;
17
+ const stream = await deps.execPty(alias, command, options);
18
+ // 创建 xterm headless 终端仿真器
19
+ const terminal = new Terminal({ rows, cols, allowProposedApi: true });
20
+ const ptySession = {
21
+ id: ptyId,
22
+ alias,
23
+ command,
24
+ stream,
25
+ terminal,
26
+ rows,
27
+ cols,
28
+ createdAt: Date.now(),
29
+ lastReadAt: Date.now(),
30
+ rawBuffer: '',
31
+ maxBufferSize,
32
+ active: true,
33
+ };
34
+ // 监听输出数据
35
+ stream.on('data', (data) => {
36
+ if (!ptySession.active) {
37
+ return;
38
+ }
39
+ const chunk = data.toString('utf-8');
40
+ // 写入终端仿真器(解析 ANSI 序列)
41
+ terminal.write(chunk);
42
+ // 同时保留原始流(用于 raw 模式)
43
+ ptySession.rawBuffer += chunk;
44
+ if (ptySession.rawBuffer.length > maxBufferSize) {
45
+ ptySession.rawBuffer = ptySession.rawBuffer.slice(-maxBufferSize);
46
+ }
47
+ });
48
+ stream.on('close', () => {
49
+ ptySession.active = false;
50
+ });
51
+ stream.on('error', (err) => {
52
+ ptySession.active = false;
53
+ terminal.write(`\n[PTY Error: ${err.message}]`);
54
+ });
55
+ this.sessions.set(ptyId, ptySession);
56
+ return ptyId;
57
+ }
58
+ write(ptyId, data) {
59
+ const session = this.getSession(ptyId);
60
+ if (!session.active) {
61
+ throw new Error(`PTY session '${ptyId}' is closed`);
62
+ }
63
+ return session.stream.write(data);
64
+ }
65
+ read(ptyId, options = {}) {
66
+ const session = this.getSession(ptyId);
67
+ const mode = options.mode || 'screen';
68
+ const clear = options.clear !== false;
69
+ let data;
70
+ if (mode === 'screen') {
71
+ data = this.getScreenContent(session.terminal);
72
+ }
73
+ else {
74
+ data = session.rawBuffer;
75
+ if (clear) {
76
+ session.rawBuffer = '';
77
+ }
78
+ }
79
+ session.lastReadAt = Date.now();
80
+ return {
81
+ data,
82
+ active: session.active,
83
+ rows: session.rows,
84
+ cols: session.cols,
85
+ };
86
+ }
87
+ resize(ptyId, rows, cols) {
88
+ const session = this.getSession(ptyId);
89
+ if (!session.active) {
90
+ throw new Error(`PTY session '${ptyId}' is closed`);
91
+ }
92
+ session.stream.setWindow(rows, cols, 0, 0);
93
+ session.terminal.resize(cols, rows);
94
+ session.rows = rows;
95
+ session.cols = cols;
96
+ return true;
97
+ }
98
+ close(ptyId) {
99
+ const session = this.sessions.get(ptyId);
100
+ if (!session) {
101
+ return false;
102
+ }
103
+ try {
104
+ session.stream.close();
105
+ }
106
+ catch (e) {
107
+ console.warn(`PTY ${ptyId} stream close failed:`, e.message);
108
+ }
109
+ try {
110
+ session.terminal.dispose();
111
+ }
112
+ catch (e) {
113
+ console.warn(`PTY ${ptyId} terminal dispose failed:`, e.message);
114
+ }
115
+ session.active = false;
116
+ this.sessions.delete(ptyId);
117
+ return true;
118
+ }
119
+ /** 关闭指定 alias 的所有 PTY 会话 */
120
+ closeByAlias(alias) {
121
+ for (const [id, session] of this.sessions) {
122
+ if (session.alias === alias) {
123
+ this.close(id);
124
+ }
125
+ }
126
+ }
127
+ list() {
128
+ const result = [];
129
+ for (const [id, pty] of this.sessions) {
130
+ result.push({
131
+ id,
132
+ alias: pty.alias,
133
+ command: pty.command,
134
+ rows: pty.rows,
135
+ cols: pty.cols,
136
+ createdAt: pty.createdAt,
137
+ lastReadAt: pty.lastReadAt,
138
+ bufferSize: pty.rawBuffer.length,
139
+ active: pty.active,
140
+ });
141
+ }
142
+ return result;
143
+ }
144
+ getSession(ptyId) {
145
+ const session = this.sessions.get(ptyId);
146
+ if (!session) {
147
+ throw new Error(`PTY session '${ptyId}' not found`);
148
+ }
149
+ return session;
150
+ }
151
+ generateId() {
152
+ return `pty_${++this.idCounter}_${Date.now()}`;
153
+ }
154
+ /** 从终端仿真器获取当前屏幕内容 */
155
+ getScreenContent(terminal) {
156
+ const buffer = terminal.buffer.active;
157
+ const lines = [];
158
+ for (let i = 0; i < terminal.rows; i++) {
159
+ const line = buffer.getLine(i);
160
+ if (line) {
161
+ lines.push(line.translateToString(true));
162
+ }
163
+ }
164
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
165
+ lines.pop();
166
+ }
167
+ return lines.join('\n');
168
+ }
169
+ }
@@ -7,7 +7,7 @@
7
7
  * - 自动重连
8
8
  * - 会话持久化
9
9
  */
10
- import { Client, ClientChannel, SFTPWrapper } from 'ssh2';
10
+ import { Client, SFTPWrapper } from 'ssh2';
11
11
  import { ExecOptions, ExecResult, PortForwardInfo, PtyOptions, PtySessionInfo, SSHConnectionConfig, SSHSessionInfo } from './types.js';
12
12
  interface SSHSession {
13
13
  client: Client;
@@ -16,20 +16,12 @@ interface SSHSession {
16
16
  lastUsedAt: number;
17
17
  reconnectAttempts: number;
18
18
  connected: boolean;
19
- tcpDispatcher?: TcpConnectionHandler;
19
+ manualClose: boolean;
20
20
  }
21
- type TcpConnectionHandler = (info: {
22
- destIP: string;
23
- destPort: number;
24
- srcIP: string;
25
- srcPort: number;
26
- }, accept: () => ClientChannel, reject: () => void) => void;
27
21
  export declare class SessionManager {
28
22
  private sessions;
29
- private ptySessions;
30
- private forwardSessions;
31
- private ptyIdCounter;
32
- private forwardIdCounter;
23
+ private readonly ptyManager;
24
+ private readonly forwardManager;
33
25
  private readonly persistPath;
34
26
  private defaultKeepaliveInterval;
35
27
  private defaultKeepaliveCountMax;
@@ -37,7 +29,6 @@ export declare class SessionManager {
37
29
  private maxReconnectAttempts;
38
30
  private defaultMaxOutputSize;
39
31
  private reconnectDelay;
40
- private defaultPtyBufferSize;
41
32
  constructor(persistPath?: string);
42
33
  /**
43
34
  * 建立 SSH 连接
@@ -82,19 +73,8 @@ export declare class SessionManager {
82
73
  * 获取 SFTP 客户端
83
74
  */
84
75
  getSftp(alias: string): Promise<SFTPWrapper>;
85
- /**
86
- * 启动持久化 PTY 会话
87
- */
88
76
  ptyStart(alias: string, command: string, options?: PtyOptions): Promise<string>;
89
- /**
90
- * 向 PTY 写入数据
91
- */
92
77
  ptyWrite(ptyId: string, data: string): boolean;
93
- /**
94
- * 读取 PTY 输出
95
- *
96
- * options.mode: 'screen' 返回当前屏幕内容,'raw' 返回原始 ANSI 流
97
- */
98
78
  ptyRead(ptyId: string, options?: {
99
79
  mode?: 'screen' | 'raw';
100
80
  clear?: boolean;
@@ -104,36 +84,17 @@ export declare class SessionManager {
104
84
  rows: number;
105
85
  cols: number;
106
86
  };
107
- /**
108
- * 调整 PTY 窗口大小
109
- */
110
87
  ptyResize(ptyId: string, rows: number, cols: number): boolean;
111
- /**
112
- * 关闭 PTY 会话
113
- */
114
88
  ptyClose(ptyId: string): boolean;
115
- /**
116
- * 列出所有 PTY 会话
117
- */
118
89
  ptyList(): PtySessionInfo[];
119
- /**
120
- * 创建本地端口转发
121
- * 本地监听 localHost:localPort,转发到远程 remoteHost:remotePort
122
- */
123
90
  forwardLocal(alias: string, localPort: number, remoteHost: string, remotePort: number, localHost?: string): Promise<string>;
124
- /**
125
- * 创建远程端口转发
126
- * 远程监听 remoteHost:remotePort,转发到本地 localHost:localPort
127
- */
128
91
  forwardRemote(alias: string, remotePort: number, localHost: string, localPort: number, remoteHost?: string): Promise<string>;
129
- /**
130
- * 关闭端口转发
131
- */
132
92
  forwardClose(forwardId: string): boolean;
93
+ forwardList(): PortForwardInfo[];
133
94
  /**
134
- * 列出所有端口转发
95
+ * 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
135
96
  */
136
- forwardList(): PortForwardInfo[];
97
+ private execPtyStream;
137
98
  private ensurePersistDir;
138
99
  /**
139
100
  * 生成连接别名
@@ -147,6 +108,14 @@ export declare class SessionManager {
147
108
  * 检查连接是否存活
148
109
  */
149
110
  private isAlive;
111
+ /**
112
+ * 调度自动重连(支持多次重试)
113
+ */
114
+ private scheduleReconnect;
115
+ /**
116
+ * 根据错误类型生成排查建议
117
+ */
118
+ private diagnoseConnectionError;
150
119
  /**
151
120
  * 转义 shell 参数(使用单引号方式)
152
121
  */
@@ -172,27 +141,6 @@ export declare class SessionManager {
172
141
  * 持久化会话信息
173
142
  */
174
143
  private persistSessions;
175
- /**
176
- * 生成 PTY 会话 ID
177
- */
178
- private generatePtyId;
179
- /**
180
- * 从终端仿真器获取当前屏幕内容
181
- */
182
- private getScreenContent;
183
- /**
184
- * 生成端口转发 ID
185
- */
186
- private generateForwardId;
187
- /**
188
- * 确保 SSH session 有共享的 tcp connection dispatcher
189
- * 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
190
- */
191
- private ensureTcpDispatcher;
192
- /**
193
- * 移除 SSH session 的 tcp dispatcher(当没有 remote forward 时)
194
- */
195
- private removeTcpDispatcherIfEmpty;
196
144
  }
197
145
  export declare const sessionManager: SessionManager;
198
146
  export {};