@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.
- package/dist/file-ops.d.ts +7 -10
- package/dist/file-ops.js +74 -172
- package/dist/index.js +8 -953
- package/dist/session-manager.d.ts +15 -21
- package/dist/session-manager.js +42 -87
- package/dist/ssh-config.d.ts +0 -4
- package/dist/ssh-config.js +1 -8
- package/dist/tools/connection.d.ts +7 -0
- package/dist/tools/connection.js +215 -0
- package/dist/tools/exec.d.ts +8 -0
- package/dist/tools/exec.js +221 -0
- package/dist/tools/file.d.ts +8 -0
- package/dist/tools/file.js +192 -0
- package/dist/tools/forward.d.ts +7 -0
- package/dist/tools/forward.js +116 -0
- package/dist/tools/index.d.ts +8 -0
- package/dist/tools/index.js +8 -0
- package/dist/tools/pty.d.ts +7 -0
- package/dist/tools/pty.js +178 -0
- package/dist/tools/utils.d.ts +22 -0
- package/dist/tools/utils.js +21 -0
- package/dist/types.d.ts +0 -7
- package/package.json +3 -2
- package/src/file-ops.ts +117 -212
- package/src/index.ts +17 -1099
- package/src/session-manager.ts +49 -97
- package/src/ssh-config.ts +1 -8
- package/src/tools/connection.ts +240 -0
- package/src/tools/exec.ts +260 -0
- package/src/tools/file.ts +219 -0
- package/src/tools/forward.ts +141 -0
- package/src/tools/index.ts +9 -0
- package/src/tools/pty.ts +203 -0
- package/src/tools/utils.ts +23 -0
- package/src/types.ts +0 -9
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* - 会话持久化
|
|
9
9
|
*/
|
|
10
10
|
import { Client, ClientChannel, SFTPWrapper } from 'ssh2';
|
|
11
|
-
import { ExecOptions, ExecResult,
|
|
11
|
+
import { ExecOptions, ExecResult, PortForwardInfo, PtyOptions, PtySessionInfo, SSHConnectionConfig, SSHSessionInfo } from './types.js';
|
|
12
12
|
interface SSHSession {
|
|
13
13
|
client: Client;
|
|
14
14
|
config: SSHConnectionConfig;
|
|
@@ -30,11 +30,13 @@ export declare class SessionManager {
|
|
|
30
30
|
private forwardSessions;
|
|
31
31
|
private ptyIdCounter;
|
|
32
32
|
private forwardIdCounter;
|
|
33
|
-
private persistPath;
|
|
33
|
+
private readonly persistPath;
|
|
34
34
|
private defaultKeepaliveInterval;
|
|
35
35
|
private defaultKeepaliveCountMax;
|
|
36
36
|
private defaultTimeout;
|
|
37
37
|
private maxReconnectAttempts;
|
|
38
|
+
private defaultMaxOutputSize;
|
|
39
|
+
private reconnectDelay;
|
|
38
40
|
private defaultPtyBufferSize;
|
|
39
41
|
constructor(persistPath?: string);
|
|
40
42
|
/**
|
|
@@ -49,10 +51,6 @@ export declare class SessionManager {
|
|
|
49
51
|
* 断开连接
|
|
50
52
|
*/
|
|
51
53
|
disconnect(alias: string): boolean;
|
|
52
|
-
/**
|
|
53
|
-
* 断开所有连接
|
|
54
|
-
*/
|
|
55
|
-
disconnectAll(): void;
|
|
56
54
|
/**
|
|
57
55
|
* 获取会话
|
|
58
56
|
*/
|
|
@@ -67,10 +65,11 @@ export declare class SessionManager {
|
|
|
67
65
|
exec(alias: string, command: string, options?: ExecOptions): Promise<ExecResult>;
|
|
68
66
|
/**
|
|
69
67
|
* 以其他用户身份执行命令
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
68
|
+
*
|
|
69
|
+
* options.loadProfile 控制是否加载用户的 shell 配置(默认 true)。
|
|
70
|
+
* su -c 创建非交互式 shell,不会自动执行 rc 文件,
|
|
71
|
+
* 但大多数用户的环境变量设置在 rc 文件中,因此默认加载。
|
|
72
|
+
* 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)。
|
|
74
73
|
*/
|
|
75
74
|
execAsUser(alias: string, command: string, targetUser: string, options?: ExecOptions & {
|
|
76
75
|
loadProfile?: boolean;
|
|
@@ -83,10 +82,6 @@ export declare class SessionManager {
|
|
|
83
82
|
* 获取 SFTP 客户端
|
|
84
83
|
*/
|
|
85
84
|
getSftp(alias: string): Promise<SFTPWrapper>;
|
|
86
|
-
/**
|
|
87
|
-
* 加载持久化的会话信息(仅用于显示,不自动重连)
|
|
88
|
-
*/
|
|
89
|
-
loadPersistedSessions(): PersistedSession[];
|
|
90
85
|
/**
|
|
91
86
|
* 启动持久化 PTY 会话
|
|
92
87
|
*/
|
|
@@ -97,7 +92,8 @@ export declare class SessionManager {
|
|
|
97
92
|
ptyWrite(ptyId: string, data: string): boolean;
|
|
98
93
|
/**
|
|
99
94
|
* 读取 PTY 输出
|
|
100
|
-
*
|
|
95
|
+
*
|
|
96
|
+
* options.mode: 'screen' 返回当前屏幕内容,'raw' 返回原始 ANSI 流
|
|
101
97
|
*/
|
|
102
98
|
ptyRead(ptyId: string, options?: {
|
|
103
99
|
mode?: 'screen' | 'raw';
|
|
@@ -120,10 +116,6 @@ export declare class SessionManager {
|
|
|
120
116
|
* 列出所有 PTY 会话
|
|
121
117
|
*/
|
|
122
118
|
ptyList(): PtySessionInfo[];
|
|
123
|
-
/**
|
|
124
|
-
* 关闭所有 PTY 会话
|
|
125
|
-
*/
|
|
126
|
-
ptyCloseAll(): number;
|
|
127
119
|
/**
|
|
128
120
|
* 创建本地端口转发
|
|
129
121
|
* 本地监听 localHost:localPort,转发到远程 remoteHost:remotePort
|
|
@@ -167,6 +159,10 @@ export declare class SessionManager {
|
|
|
167
159
|
* 校验环境变量名(只允许字母、数字、下划线,不能以数字开头)
|
|
168
160
|
*/
|
|
169
161
|
private isValidEnvKey;
|
|
162
|
+
/**
|
|
163
|
+
* 构建完整命令:注入环境变量 + 切换工作目录
|
|
164
|
+
*/
|
|
165
|
+
private buildCommand;
|
|
170
166
|
/**
|
|
171
167
|
* 根据用户 shell 类型生成加载配置文件的命令
|
|
172
168
|
* bash → .bashrc, zsh → .zshrc, 其他 → .profile
|
|
@@ -191,12 +187,10 @@ export declare class SessionManager {
|
|
|
191
187
|
/**
|
|
192
188
|
* 确保 SSH session 有共享的 tcp connection dispatcher
|
|
193
189
|
* 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
|
|
194
|
-
* @param alias - session 的 map key
|
|
195
190
|
*/
|
|
196
191
|
private ensureTcpDispatcher;
|
|
197
192
|
/**
|
|
198
193
|
* 移除 SSH session 的 tcp dispatcher(当没有 remote forward 时)
|
|
199
|
-
* @param alias - session 的 map key
|
|
200
194
|
*/
|
|
201
195
|
private removeTcpDispatcherIfEmpty;
|
|
202
196
|
}
|
package/dist/session-manager.js
CHANGED
|
@@ -24,6 +24,8 @@ export class SessionManager {
|
|
|
24
24
|
defaultKeepaliveCountMax = 3;
|
|
25
25
|
defaultTimeout = 30000; // 30秒
|
|
26
26
|
maxReconnectAttempts = 3;
|
|
27
|
+
defaultMaxOutputSize = 10 * 1024 * 1024; // 10MB
|
|
28
|
+
reconnectDelay = 5000; // 5秒
|
|
27
29
|
defaultPtyBufferSize = 1024 * 1024; // 1MB
|
|
28
30
|
constructor(persistPath) {
|
|
29
31
|
this.persistPath = persistPath || path.join(process.env.HOME || '/tmp', '.ssh-mcp-pro', 'sessions.json');
|
|
@@ -69,8 +71,7 @@ export class SessionManager {
|
|
|
69
71
|
const jumpSession = this.sessions.get(jumpAlias);
|
|
70
72
|
if (jumpSession) {
|
|
71
73
|
// 通过跳板机建立连接
|
|
72
|
-
|
|
73
|
-
connectConfig.sock = stream;
|
|
74
|
+
connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port || 22);
|
|
74
75
|
}
|
|
75
76
|
}
|
|
76
77
|
return new Promise((resolve, reject) => {
|
|
@@ -102,9 +103,10 @@ export class SessionManager {
|
|
|
102
103
|
if (session.reconnectAttempts < this.maxReconnectAttempts) {
|
|
103
104
|
session.reconnectAttempts++;
|
|
104
105
|
setTimeout(() => {
|
|
105
|
-
this.reconnect(alias).catch(() => {
|
|
106
|
+
this.reconnect(alias).catch((err) => {
|
|
107
|
+
console.error(`Auto-reconnect failed for ${alias}:`, err.message);
|
|
106
108
|
});
|
|
107
|
-
},
|
|
109
|
+
}, this.reconnectDelay);
|
|
108
110
|
}
|
|
109
111
|
}
|
|
110
112
|
});
|
|
@@ -122,7 +124,7 @@ export class SessionManager {
|
|
|
122
124
|
try {
|
|
123
125
|
session.client.end();
|
|
124
126
|
}
|
|
125
|
-
catch {
|
|
127
|
+
catch { /* 忽略已关闭的连接 */
|
|
126
128
|
}
|
|
127
129
|
await this.connect(session.config);
|
|
128
130
|
}
|
|
@@ -135,7 +137,7 @@ export class SessionManager {
|
|
|
135
137
|
try {
|
|
136
138
|
session.client.end();
|
|
137
139
|
}
|
|
138
|
-
catch {
|
|
140
|
+
catch { /* 忽略已关闭的连接 */
|
|
139
141
|
}
|
|
140
142
|
this.sessions.delete(alias);
|
|
141
143
|
this.persistSessions();
|
|
@@ -143,14 +145,6 @@ export class SessionManager {
|
|
|
143
145
|
}
|
|
144
146
|
return false;
|
|
145
147
|
}
|
|
146
|
-
/**
|
|
147
|
-
* 断开所有连接
|
|
148
|
-
*/
|
|
149
|
-
disconnectAll() {
|
|
150
|
-
for (const alias of this.sessions.keys()) {
|
|
151
|
-
this.disconnect(alias);
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
148
|
/**
|
|
155
149
|
* 获取会话
|
|
156
150
|
*/
|
|
@@ -190,29 +184,8 @@ export class SessionManager {
|
|
|
190
184
|
async exec(alias, command, options = {}) {
|
|
191
185
|
const session = this.getSession(alias);
|
|
192
186
|
const startTime = Date.now();
|
|
193
|
-
const maxOutputSize = options.maxOutputSize ||
|
|
194
|
-
|
|
195
|
-
let fullCommand = command;
|
|
196
|
-
const env = { ...session.config.env, ...options.env };
|
|
197
|
-
if (Object.keys(env).length > 0) {
|
|
198
|
-
// 校验并过滤环境变量名
|
|
199
|
-
const validEnvEntries = Object.entries(env).filter(([k]) => {
|
|
200
|
-
if (!this.isValidEnvKey(k)) {
|
|
201
|
-
// 静默忽略非法环境变量名
|
|
202
|
-
return false;
|
|
203
|
-
}
|
|
204
|
-
return true;
|
|
205
|
-
});
|
|
206
|
-
if (validEnvEntries.length > 0) {
|
|
207
|
-
const envStr = validEnvEntries
|
|
208
|
-
.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
|
|
209
|
-
.join('; ');
|
|
210
|
-
fullCommand = `${envStr}; ${command}`;
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
if (options.cwd) {
|
|
214
|
-
fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`;
|
|
215
|
-
}
|
|
187
|
+
const maxOutputSize = options.maxOutputSize || this.defaultMaxOutputSize;
|
|
188
|
+
const fullCommand = this.buildCommand(command, session, options);
|
|
216
189
|
return new Promise((resolve, reject) => {
|
|
217
190
|
const timeout = options.timeout || this.defaultTimeout;
|
|
218
191
|
let timeoutId = null;
|
|
@@ -280,10 +253,11 @@ export class SessionManager {
|
|
|
280
253
|
}
|
|
281
254
|
/**
|
|
282
255
|
* 以其他用户身份执行命令
|
|
283
|
-
*
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
*
|
|
256
|
+
*
|
|
257
|
+
* options.loadProfile 控制是否加载用户的 shell 配置(默认 true)。
|
|
258
|
+
* su -c 创建非交互式 shell,不会自动执行 rc 文件,
|
|
259
|
+
* 但大多数用户的环境变量设置在 rc 文件中,因此默认加载。
|
|
260
|
+
* 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)。
|
|
287
261
|
*/
|
|
288
262
|
async execAsUser(alias, command, targetUser, options = {}) {
|
|
289
263
|
// 校验用户名防止注入
|
|
@@ -327,19 +301,6 @@ export class SessionManager {
|
|
|
327
301
|
});
|
|
328
302
|
});
|
|
329
303
|
}
|
|
330
|
-
/**
|
|
331
|
-
* 加载持久化的会话信息(仅用于显示,不自动重连)
|
|
332
|
-
*/
|
|
333
|
-
loadPersistedSessions() {
|
|
334
|
-
try {
|
|
335
|
-
if (fs.existsSync(this.persistPath)) {
|
|
336
|
-
return JSON.parse(fs.readFileSync(this.persistPath, 'utf-8'));
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
catch {
|
|
340
|
-
}
|
|
341
|
-
return [];
|
|
342
|
-
}
|
|
343
304
|
/**
|
|
344
305
|
* 启动持久化 PTY 会话
|
|
345
306
|
*/
|
|
@@ -350,18 +311,7 @@ export class SessionManager {
|
|
|
350
311
|
const cols = options.cols || 80;
|
|
351
312
|
const term = options.term || 'xterm-256color';
|
|
352
313
|
const maxBufferSize = options.bufferSize || this.defaultPtyBufferSize;
|
|
353
|
-
|
|
354
|
-
let fullCommand = command;
|
|
355
|
-
const env = { ...session.config.env, ...options.env };
|
|
356
|
-
if (Object.keys(env).length > 0) {
|
|
357
|
-
const envStr = Object.entries(env)
|
|
358
|
-
.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
|
|
359
|
-
.join('; ');
|
|
360
|
-
fullCommand = `${envStr}; ${command}`;
|
|
361
|
-
}
|
|
362
|
-
if (options.cwd) {
|
|
363
|
-
fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`;
|
|
364
|
-
}
|
|
314
|
+
const fullCommand = this.buildCommand(command, session, options);
|
|
365
315
|
return new Promise((resolve, reject) => {
|
|
366
316
|
session.client.exec(fullCommand, {
|
|
367
317
|
pty: { rows, cols, term },
|
|
@@ -431,7 +381,8 @@ export class SessionManager {
|
|
|
431
381
|
}
|
|
432
382
|
/**
|
|
433
383
|
* 读取 PTY 输出
|
|
434
|
-
*
|
|
384
|
+
*
|
|
385
|
+
* options.mode: 'screen' 返回当前屏幕内容,'raw' 返回原始 ANSI 流
|
|
435
386
|
*/
|
|
436
387
|
ptyRead(ptyId, options = {}) {
|
|
437
388
|
const ptySession = this.ptySessions.get(ptyId);
|
|
@@ -490,12 +441,12 @@ export class SessionManager {
|
|
|
490
441
|
try {
|
|
491
442
|
ptySession.stream.close();
|
|
492
443
|
}
|
|
493
|
-
catch {
|
|
444
|
+
catch { /* 忽略清理异常 */
|
|
494
445
|
}
|
|
495
446
|
try {
|
|
496
447
|
ptySession.terminal.dispose();
|
|
497
448
|
}
|
|
498
|
-
catch {
|
|
449
|
+
catch { /* 忽略清理异常 */
|
|
499
450
|
}
|
|
500
451
|
ptySession.active = false;
|
|
501
452
|
this.ptySessions.delete(ptyId);
|
|
@@ -521,18 +472,6 @@ export class SessionManager {
|
|
|
521
472
|
}
|
|
522
473
|
return result;
|
|
523
474
|
}
|
|
524
|
-
/**
|
|
525
|
-
* 关闭所有 PTY 会话
|
|
526
|
-
*/
|
|
527
|
-
ptyCloseAll() {
|
|
528
|
-
let count = 0;
|
|
529
|
-
for (const ptyId of this.ptySessions.keys()) {
|
|
530
|
-
if (this.ptyClose(ptyId)) {
|
|
531
|
-
count++;
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
return count;
|
|
535
|
-
}
|
|
536
475
|
/**
|
|
537
476
|
* 创建本地端口转发
|
|
538
477
|
* 本地监听 localHost:localPort,转发到远程 remoteHost:remotePort
|
|
@@ -602,7 +541,6 @@ export class SessionManager {
|
|
|
602
541
|
});
|
|
603
542
|
});
|
|
604
543
|
}
|
|
605
|
-
// ========== PTY 会话管理 ==========
|
|
606
544
|
/**
|
|
607
545
|
* 关闭端口转发
|
|
608
546
|
*/
|
|
@@ -616,7 +554,7 @@ export class SessionManager {
|
|
|
616
554
|
try {
|
|
617
555
|
fwdSession.server.close();
|
|
618
556
|
}
|
|
619
|
-
catch {
|
|
557
|
+
catch { /* 忽略清理异常 */
|
|
620
558
|
}
|
|
621
559
|
}
|
|
622
560
|
else if (fwdSession.type === 'remote') {
|
|
@@ -625,7 +563,7 @@ export class SessionManager {
|
|
|
625
563
|
try {
|
|
626
564
|
session.client.unforwardIn(fwdSession.remoteHost, fwdSession.remotePort);
|
|
627
565
|
}
|
|
628
|
-
catch {
|
|
566
|
+
catch { /* 忽略清理异常 */
|
|
629
567
|
}
|
|
630
568
|
// 检查是否需要移除共享 dispatcher
|
|
631
569
|
this.removeTcpDispatcherIfEmpty(session, fwdSession.alias);
|
|
@@ -705,7 +643,26 @@ export class SessionManager {
|
|
|
705
643
|
isValidEnvKey(key) {
|
|
706
644
|
return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key);
|
|
707
645
|
}
|
|
708
|
-
|
|
646
|
+
/**
|
|
647
|
+
* 构建完整命令:注入环境变量 + 切换工作目录
|
|
648
|
+
*/
|
|
649
|
+
buildCommand(command, session, options) {
|
|
650
|
+
let fullCommand = command;
|
|
651
|
+
const env = { ...session.config.env, ...options.env };
|
|
652
|
+
if (Object.keys(env).length > 0) {
|
|
653
|
+
const validEntries = Object.entries(env).filter(([k]) => this.isValidEnvKey(k));
|
|
654
|
+
if (validEntries.length > 0) {
|
|
655
|
+
const envStr = validEntries
|
|
656
|
+
.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
|
|
657
|
+
.join('; ');
|
|
658
|
+
fullCommand = `${envStr}; ${command}`;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
if (options.cwd) {
|
|
662
|
+
fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`;
|
|
663
|
+
}
|
|
664
|
+
return fullCommand;
|
|
665
|
+
}
|
|
709
666
|
/**
|
|
710
667
|
* 根据用户 shell 类型生成加载配置文件的命令
|
|
711
668
|
* bash → .bashrc, zsh → .zshrc, 其他 → .profile
|
|
@@ -773,7 +730,6 @@ export class SessionManager {
|
|
|
773
730
|
/**
|
|
774
731
|
* 确保 SSH session 有共享的 tcp connection dispatcher
|
|
775
732
|
* 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
|
|
776
|
-
* @param alias - session 的 map key
|
|
777
733
|
*/
|
|
778
734
|
ensureTcpDispatcher(session, alias) {
|
|
779
735
|
if (session.tcpDispatcher) {
|
|
@@ -804,7 +760,6 @@ export class SessionManager {
|
|
|
804
760
|
}
|
|
805
761
|
/**
|
|
806
762
|
* 移除 SSH session 的 tcp dispatcher(当没有 remote forward 时)
|
|
807
|
-
* @param alias - session 的 map key
|
|
808
763
|
*/
|
|
809
764
|
removeTcpDispatcherIfEmpty(session, alias) {
|
|
810
765
|
if (!session.tcpDispatcher) {
|
package/dist/ssh-config.d.ts
CHANGED
|
@@ -33,7 +33,3 @@ export declare function parseProxyJump(proxyJump: string): ParsedProxyJump | nul
|
|
|
33
33
|
* 跳过 Match 块(避免条件配置被误应用)
|
|
34
34
|
*/
|
|
35
35
|
export declare function parseSSHConfig(configPath?: string): SSHConfigHost[];
|
|
36
|
-
/**
|
|
37
|
-
* 根据 Host 名称获取配置
|
|
38
|
-
*/
|
|
39
|
-
export declare function getHostConfig(hostName: string, configPath?: string): SSHConfigHost | null;
|
package/dist/ssh-config.js
CHANGED
|
@@ -71,7 +71,7 @@ export function parseProxyJump(proxyJump) {
|
|
|
71
71
|
return { user, host, port };
|
|
72
72
|
}
|
|
73
73
|
const { host, port } = parseHostPort(firstJump);
|
|
74
|
-
return {
|
|
74
|
+
return { host, port };
|
|
75
75
|
}
|
|
76
76
|
/**
|
|
77
77
|
* 展开 ~ 路径
|
|
@@ -207,10 +207,3 @@ export function parseSSHConfig(configPath) {
|
|
|
207
207
|
}
|
|
208
208
|
return hosts;
|
|
209
209
|
}
|
|
210
|
-
/**
|
|
211
|
-
* 根据 Host 名称获取配置
|
|
212
|
-
*/
|
|
213
|
-
export function getHostConfig(hostName, configPath) {
|
|
214
|
-
const hosts = parseSSHConfig(configPath);
|
|
215
|
-
return hosts.find(h => h.host === hostName) || null;
|
|
216
|
-
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 连接管理工具组
|
|
3
|
+
*
|
|
4
|
+
* ssh_connect, ssh_disconnect, ssh_list_sessions, ssh_reconnect, ssh_config_list
|
|
5
|
+
*/
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { sessionManager } from '../session-manager.js';
|
|
8
|
+
import { parseProxyJump, parseSSHConfig } from '../ssh-config.js';
|
|
9
|
+
import { formatError, formatResult } from './utils.js';
|
|
10
|
+
// ========== Schemas ==========
|
|
11
|
+
const connectSchema = z.object({
|
|
12
|
+
configHost: z.string()
|
|
13
|
+
.optional()
|
|
14
|
+
.describe('使用 ~/.ssh/config 中的 Host 配置(推荐)'),
|
|
15
|
+
configPath: z.string().optional().describe('SSH 配置文件路径(默认 ~/.ssh/config)'),
|
|
16
|
+
host: z.string().optional().describe('服务器地址(使用 configHost 时可省略)'),
|
|
17
|
+
user: z.string().optional().describe('用户名(使用 configHost 时可省略)'),
|
|
18
|
+
password: z.string().optional().describe('密码'),
|
|
19
|
+
keyPath: z.string().optional().describe('SSH 私钥路径'),
|
|
20
|
+
port: z.number().optional().describe('SSH 端口,默认 22'),
|
|
21
|
+
alias: z.string().optional().describe('连接别名(可选,默认使用 configHost 或 host)'),
|
|
22
|
+
env: z.record(z.string()).optional().describe('环境变量'),
|
|
23
|
+
keepaliveInterval: z.number().optional().describe('心跳间隔(毫秒),默认 30000'),
|
|
24
|
+
jumpHost: z.object({
|
|
25
|
+
host: z.string().describe('跳板机地址'),
|
|
26
|
+
user: z.string().describe('跳板机用户名'),
|
|
27
|
+
password: z.string().optional().describe('跳板机密码'),
|
|
28
|
+
keyPath: z.string().optional().describe('跳板机私钥路径'),
|
|
29
|
+
port: z.number().optional().describe('跳板机端口,默认 22'),
|
|
30
|
+
}).optional().describe('跳板机配置'),
|
|
31
|
+
});
|
|
32
|
+
const disconnectSchema = z.object({
|
|
33
|
+
alias: z.string().describe('连接别名'),
|
|
34
|
+
});
|
|
35
|
+
const listSessionsSchema = z.object({});
|
|
36
|
+
const reconnectSchema = z.object({
|
|
37
|
+
alias: z.string().describe('连接别名'),
|
|
38
|
+
});
|
|
39
|
+
const configListSchema = z.object({
|
|
40
|
+
configPath: z.string()
|
|
41
|
+
.optional()
|
|
42
|
+
.describe('SSH 配置文件路径(默认 ~/.ssh/config)'),
|
|
43
|
+
});
|
|
44
|
+
// ========== Handlers ==========
|
|
45
|
+
async function handleConnect(args) {
|
|
46
|
+
try {
|
|
47
|
+
// 解析 configHost
|
|
48
|
+
let host = args.host;
|
|
49
|
+
let user = args.user;
|
|
50
|
+
let port = args.port;
|
|
51
|
+
let keyPath = args.keyPath;
|
|
52
|
+
let jumpHostResolved;
|
|
53
|
+
if (args.configHost) {
|
|
54
|
+
const allHosts = parseSSHConfig(args.configPath);
|
|
55
|
+
const hostConfig = allHosts.find(h => h.host === args.configHost);
|
|
56
|
+
if (!hostConfig) {
|
|
57
|
+
return formatResult({ success: false, error: `Host '${args.configHost}' not found in SSH config` });
|
|
58
|
+
}
|
|
59
|
+
// 显式参数优先于 config 值
|
|
60
|
+
host = host || hostConfig.hostName || hostConfig.host;
|
|
61
|
+
user = user || hostConfig.user;
|
|
62
|
+
port = port || hostConfig.port;
|
|
63
|
+
keyPath = keyPath || hostConfig.identityFile;
|
|
64
|
+
// 解析 ProxyJump(支持 user@host:port 格式)
|
|
65
|
+
if (hostConfig.proxyJump) {
|
|
66
|
+
const parsed = parseProxyJump(hostConfig.proxyJump);
|
|
67
|
+
if (parsed) {
|
|
68
|
+
// 先尝试在 config 中查找对应的 Host
|
|
69
|
+
const jumpHostConfig = allHosts.find(h => h.host === parsed.host);
|
|
70
|
+
if (jumpHostConfig) {
|
|
71
|
+
// 使用 config 中的配置,但 parsed 的 user/port 优先
|
|
72
|
+
jumpHostResolved = {
|
|
73
|
+
host: jumpHostConfig.hostName || jumpHostConfig.host,
|
|
74
|
+
port: parsed.port || jumpHostConfig.port || 22,
|
|
75
|
+
username: parsed.user || jumpHostConfig.user || 'root',
|
|
76
|
+
privateKeyPath: jumpHostConfig.identityFile,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
// 直接使用 parsed 的值
|
|
81
|
+
jumpHostResolved = {
|
|
82
|
+
host: parsed.host,
|
|
83
|
+
port: parsed.port || 22,
|
|
84
|
+
username: parsed.user || 'root',
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (!host || !user) {
|
|
91
|
+
return formatResult({
|
|
92
|
+
success: false,
|
|
93
|
+
error: 'host and user are required (either directly or via configHost)',
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
// 手动指定的 jumpHost 优先级高于 ProxyJump
|
|
97
|
+
const jumpHost = args.jumpHost ? {
|
|
98
|
+
host: args.jumpHost.host,
|
|
99
|
+
port: args.jumpHost.port || 22,
|
|
100
|
+
username: args.jumpHost.user,
|
|
101
|
+
password: args.jumpHost.password,
|
|
102
|
+
privateKeyPath: args.jumpHost.keyPath,
|
|
103
|
+
} : jumpHostResolved;
|
|
104
|
+
const alias = await sessionManager.connect({
|
|
105
|
+
host,
|
|
106
|
+
port: port || 22,
|
|
107
|
+
username: user,
|
|
108
|
+
password: args.password,
|
|
109
|
+
privateKeyPath: keyPath,
|
|
110
|
+
alias: args.alias || args.configHost,
|
|
111
|
+
env: args.env,
|
|
112
|
+
keepaliveInterval: args.keepaliveInterval,
|
|
113
|
+
jumpHost,
|
|
114
|
+
});
|
|
115
|
+
return formatResult({
|
|
116
|
+
success: true,
|
|
117
|
+
alias,
|
|
118
|
+
message: `Connected to ${user}@${host}:${port || 22}${jumpHost ?
|
|
119
|
+
' via jump host' :
|
|
120
|
+
''}`,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
return formatError(error);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async function handleDisconnect(args) {
|
|
128
|
+
try {
|
|
129
|
+
const success = sessionManager.disconnect(args.alias);
|
|
130
|
+
return formatResult({
|
|
131
|
+
success,
|
|
132
|
+
message: success
|
|
133
|
+
? `Disconnected from ${args.alias}`
|
|
134
|
+
: `Session ${args.alias} not found`,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
return formatError(error);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async function handleListSessions() {
|
|
142
|
+
try {
|
|
143
|
+
const sessions = sessionManager.listSessions();
|
|
144
|
+
return formatResult({
|
|
145
|
+
success: true,
|
|
146
|
+
count: sessions.length,
|
|
147
|
+
sessions,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
return formatError(error);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
async function handleReconnect(args) {
|
|
155
|
+
try {
|
|
156
|
+
await sessionManager.reconnect(args.alias);
|
|
157
|
+
return formatResult({ success: true, message: `Reconnected to ${args.alias}` });
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
return formatError(error);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
async function handleConfigList(args) {
|
|
164
|
+
try {
|
|
165
|
+
const hosts = parseSSHConfig(args.configPath);
|
|
166
|
+
return formatResult({
|
|
167
|
+
success: true,
|
|
168
|
+
count: hosts.length,
|
|
169
|
+
hosts: hosts.map(h => ({
|
|
170
|
+
host: h.host,
|
|
171
|
+
hostName: h.hostName,
|
|
172
|
+
user: h.user,
|
|
173
|
+
port: h.port,
|
|
174
|
+
identityFile: h.identityFile,
|
|
175
|
+
proxyJump: h.proxyJump,
|
|
176
|
+
})),
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
return formatError(error);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// ========== Register ==========
|
|
184
|
+
export function registerConnectionTools(server) {
|
|
185
|
+
server.registerTool('ssh_connect', {
|
|
186
|
+
description: `建立 SSH 连接并保持会话。支持密码、密钥认证,支持跳板机。
|
|
187
|
+
|
|
188
|
+
可通过 configHost 参数使用 ~/.ssh/config 中的配置,无需重复填写连接信息。
|
|
189
|
+
支持 Host 多别名、Host * 全局默认继承、ProxyJump(user@host:port 格式)。
|
|
190
|
+
|
|
191
|
+
示例:
|
|
192
|
+
- 使用 ssh config: ssh_connect(configHost="myserver")
|
|
193
|
+
- 密钥认证: ssh_connect(host="192.168.1.1", user="root", keyPath="/home/.ssh/id_rsa")
|
|
194
|
+
- 跳板机: ssh_connect(host="内网IP", user="root", keyPath="...", jumpHost={host:"跳板机IP", user:"root", keyPath:"..."})`,
|
|
195
|
+
inputSchema: connectSchema,
|
|
196
|
+
}, (args) => handleConnect(args));
|
|
197
|
+
server.registerTool('ssh_disconnect', {
|
|
198
|
+
description: '断开 SSH 连接',
|
|
199
|
+
inputSchema: disconnectSchema,
|
|
200
|
+
}, (args) => handleDisconnect(args));
|
|
201
|
+
server.registerTool('ssh_list_sessions', {
|
|
202
|
+
description: '列出所有活跃的 SSH 会话',
|
|
203
|
+
inputSchema: listSessionsSchema,
|
|
204
|
+
}, () => handleListSessions());
|
|
205
|
+
server.registerTool('ssh_reconnect', {
|
|
206
|
+
description: '重新连接已断开的会话',
|
|
207
|
+
inputSchema: reconnectSchema,
|
|
208
|
+
}, (args) => handleReconnect(args));
|
|
209
|
+
server.registerTool('ssh_config_list', {
|
|
210
|
+
description: `列出 ~/.ssh/config 中配置的所有 Host。
|
|
211
|
+
|
|
212
|
+
返回每个 Host 的配置信息(别名、地址、用户、端口、密钥路径等)。`,
|
|
213
|
+
inputSchema: configListSchema,
|
|
214
|
+
}, (args) => handleConfigList(args));
|
|
215
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
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
|
+
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
8
|
+
export declare function registerExecTools(server: McpServer): void;
|