@pyrokine/mcp-ssh 2.3.2 → 2.4.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.
@@ -54,7 +54,14 @@ const connectSchema = z.object({
54
54
  env: z.record(z.string(), z.string()).optional().describe('环境变量'),
55
55
  defaultEnv: z.record(z.string(), z.string()).optional().describe('连接级默认环境变量'),
56
56
  runAs: z.string().optional().describe('连接级默认执行用户,后续 ssh_exec 默认以该用户执行'),
57
- keepaliveInterval: z.number().optional().describe('心跳间隔(毫秒),默认 30000'),
57
+ keepaliveInterval: z.number().int().positive().optional().describe('心跳间隔(毫秒),默认 30000'),
58
+ readyTimeout: z
59
+ .number()
60
+ .int()
61
+ .positive()
62
+ .max(600000)
63
+ .optional()
64
+ .describe('等待 SSH ready 的超时(毫秒),默认 30000'),
58
65
  jumpHost: z
59
66
  .object({
60
67
  host: z.string().describe('跳板机地址'),
@@ -62,6 +69,13 @@ const connectSchema = z.object({
62
69
  password: z.string().optional().describe('跳板机密码'),
63
70
  keyPath: z.string().optional().describe('跳板机私钥路径'),
64
71
  port: z.number().optional().describe('跳板机端口,默认 22'),
72
+ readyTimeout: z
73
+ .number()
74
+ .int()
75
+ .positive()
76
+ .max(600000)
77
+ .optional()
78
+ .describe('跳板机等待 SSH ready 的超时(毫秒),默认继承顶层 readyTimeout'),
65
79
  })
66
80
  .optional()
67
81
  .describe('跳板机配置'),
@@ -69,7 +83,23 @@ const connectSchema = z.object({
69
83
  const disconnectSchema = z.object({
70
84
  alias: z.string().describe('连接别名'),
71
85
  });
72
- const listSessionsSchema = z.object({});
86
+ const sessionFieldSchema = z.enum([
87
+ 'alias',
88
+ 'identity',
89
+ 'runAs',
90
+ 'connected',
91
+ 'lastUsedAt',
92
+ 'host',
93
+ 'port',
94
+ 'username',
95
+ 'authMethod',
96
+ 'connectedAt',
97
+ 'hasJumpHost',
98
+ ]);
99
+ const listSessionsSchema = z.object({
100
+ detail: z.boolean().optional().describe('返回不含 keyPath 的连接详情'),
101
+ fields: z.array(sessionFieldSchema).max(12).optional().describe('只返回指定字段;任何模式都不返回 keyPath'),
102
+ });
73
103
  const reconnectSchema = z.object({
74
104
  alias: z.string().describe('连接别名'),
75
105
  });
@@ -91,6 +121,7 @@ async function handleConnect(args) {
91
121
  const defaultEnv = mergeEnv(template.defaultEnv, args.defaultEnv);
92
122
  const env = mergeEnv(template.env, args.env);
93
123
  const keepaliveInterval = args.keepaliveInterval ?? template.keepaliveInterval;
124
+ const readyTimeout = args.readyTimeout ?? template.readyTimeout;
94
125
  let jumpHostResolved;
95
126
  if (configHost) {
96
127
  const allHosts = parseSSHConfig(args.configPath);
@@ -163,12 +194,13 @@ async function handleConnect(args) {
163
194
  username: args.jumpHost.user,
164
195
  password: args.jumpHost.password,
165
196
  privateKeyPath: args.jumpHost.keyPath,
197
+ readyTimeout: args.jumpHost.readyTimeout ?? readyTimeout,
166
198
  }
167
199
  : jumpHostResolved;
168
200
  const finalPort = port || 22;
169
201
  const finalAlias = requestedAlias || `${user}@${host}:${finalPort}`;
170
202
  const identity = `${user}@${host}:${finalPort}`;
171
- const sessionsBeforeConnect = sessionManager.listSessions();
203
+ const sessionsBeforeConnect = sessionManager.listSessionDetails();
172
204
  const reused = sessionsBeforeConnect.some((session) => session.alias === finalAlias && session.connected);
173
205
  const reusableSessions = sessionsBeforeConnect
174
206
  .filter((session) => session.identity === identity && session.alias !== finalAlias && session.connected)
@@ -185,24 +217,26 @@ async function handleConnect(args) {
185
217
  defaultEnv,
186
218
  env,
187
219
  keepaliveInterval,
220
+ readyTimeout,
188
221
  jumpHost,
189
222
  });
223
+ const connected = sessionManager.getSessionConnectionInfo(alias);
190
224
  return formatResult({
191
225
  success: true,
192
- alias,
226
+ alias: connected.alias,
193
227
  reused,
194
- identity,
195
- loginUser: user,
196
- runAs,
197
- host,
198
- port: finalPort,
199
- defaultEnvKeys: defaultEnv ? Object.keys(defaultEnv) : [],
200
- envKeys: env ? Object.keys(env) : [],
228
+ identity: connected.identity,
229
+ loginUser: connected.loginUser,
230
+ runAs: connected.runAs,
231
+ host: connected.host,
232
+ port: connected.port,
233
+ defaultEnvKeys: connected.defaultEnvKeys,
234
+ envKeys: connected.envKeys,
201
235
  reusableSessions,
202
236
  suggestion: reusableSessions.length > 0
203
237
  ? '已有同 identity 的连接,可直接复用 reusableSessions 中的 alias'
204
238
  : undefined,
205
- message: `Connected to ${identity}${jumpHost ? ' via jump host' : ''}`,
239
+ message: `Connected to ${connected.identity}${connected.hasJumpHost ? ' via jump host' : ''}`,
206
240
  });
207
241
  }
208
242
  catch (error) {
@@ -221,13 +255,20 @@ async function handleDisconnect(args) {
221
255
  return formatError(error);
222
256
  }
223
257
  }
224
- async function handleListSessions() {
258
+ async function handleListSessions(args) {
225
259
  try {
226
- const sessions = sessionManager.listSessions();
260
+ const sessions = args.detail || args.fields ? sessionManager.listSessionDetails() : sessionManager.listSessions();
261
+ const selected = args.fields
262
+ ? sessions.map((session) => {
263
+ const record = session;
264
+ return Object.fromEntries(args.fields.filter((field) => field in record).map((field) => [field, record[field]]));
265
+ })
266
+ : sessions;
227
267
  return formatResult({
228
268
  success: true,
229
- count: sessions.length,
230
- sessions,
269
+ count: selected.length,
270
+ detail: args.detail === true || args.fields !== undefined,
271
+ sessions: selected,
231
272
  });
232
273
  }
233
274
  catch (error) {
@@ -286,7 +327,7 @@ export function registerConnectionTools(server) {
286
327
  server.registerTool('ssh_list_sessions', {
287
328
  description: '列出所有活跃的 SSH 会话',
288
329
  inputSchema: listSessionsSchema,
289
- }, () => handleListSessions());
330
+ }, (args) => handleListSessions(args));
290
331
  server.registerTool('ssh_reconnect', {
291
332
  description: '重新连接已断开的会话',
292
333
  inputSchema: reconnectSchema,
@@ -5,6 +5,7 @@
5
5
  * ssh_exec_batch, ssh_quick_exec, ssh_exec_parallel
6
6
  */
7
7
  import { z } from 'zod';
8
+ import { classifyCommandRisk } from '../command-risk.js';
8
9
  import * as fileOps from '../file-ops.js';
9
10
  import { sessionManager } from '../session-manager.js';
10
11
  import { HARD_EXEC_MAX_OUTPUT_SIZE } from '../types.js';
@@ -95,67 +96,7 @@ const execScriptSchema = z.object({
95
96
  keepScript: z.boolean().optional().describe('是否保留远端临时脚本,默认 false'),
96
97
  maxOutputSize: maxOutputSizeSchema,
97
98
  });
98
- function pushRisk(categories, signals, category, signal) {
99
- categories.add(category);
100
- signals.push(signal);
101
- }
102
- function classifyCommandRisk(command) {
103
- const signals = [];
104
- const categories = new Set();
105
- const pipeCount = (command.match(/\|/g) ?? []).length;
106
- const lowerCommand = command.toLowerCase();
107
- if (command.length > 500) {
108
- pushRisk(categories, signals, 'long-running', 'long_command');
109
- }
110
- if (/\bgrep\s+(?:-\S*R|--recursive)\b/.test(command)) {
111
- pushRisk(categories, signals, 'long-running', 'recursive_grep');
112
- }
113
- if (/\bfind\b/.test(command) && !/\s-maxdepth\s+\d+/.test(command)) {
114
- pushRisk(categories, signals, 'long-running', 'unbounded_find');
115
- }
116
- if (/\b(?:python|python3|node|perl|ruby)\b/.test(command)) {
117
- pushRisk(categories, signals, 'script-execution', 'interpreter_script');
118
- }
119
- if (/\bsleep\s+\d{2,}\b/.test(command) || /\b(?:tail\s+-f|journalctl\s+-f|watch|top|htop)\b/.test(command)) {
120
- pushRisk(categories, signals, 'long-running', 'long_running');
121
- }
122
- if (pipeCount >= 3) {
123
- pushRisk(categories, signals, 'long-running', 'long_pipeline');
124
- }
125
- if (/(?:^|[^&])&(?!&)/.test(command)) {
126
- pushRisk(categories, signals, 'process-control', 'background_task');
127
- }
128
- if (/\b(?:rm\s+-[a-zA-Z]*r|dd\s+if=|mkfs|fdisk|parted|shutdown|reboot)\b/.test(lowerCommand)) {
129
- pushRisk(categories, signals, 'destructive', 'destructive_command');
130
- }
131
- if (/\b(?:kill|pkill|killall)\b/.test(lowerCommand)) {
132
- pushRisk(categories, signals, 'process-control', 'process_control');
133
- }
134
- if (/\b(?:systemctl|service|docker|kubectl)\s+(?:restart|stop|kill|delete|rm|down)\b/.test(lowerCommand)) {
135
- pushRisk(categories, signals, 'service-control', 'service_control');
136
- }
137
- if (/\b(?:password|passwd|token|authorization|cookie|secret|private[_-]?key)\b/i.test(command)) {
138
- pushRisk(categories, signals, 'credential-bearing', 'credential_bearing');
139
- }
140
- if (/\bsu\s+-?\s*[a-zA-Z_][a-zA-Z0-9_-]*\s+-c\b/.test(command)) {
141
- pushRisk(categories, signals, 'user-switch', 'direct_su_command');
142
- }
143
- if (signals.length === 0) {
144
- return undefined;
145
- }
146
- const highCategories = new Set(['destructive', 'process-control', 'service-control', 'long-running']);
147
- const level = Array.from(categories).some((category) => highCategories.has(category)) ? 'high' : 'medium';
148
- return {
149
- level,
150
- categories: Array.from(categories),
151
- signals,
152
- suggestion: signals.includes('direct_su_command')
153
- ? '建议使用 ssh_exec 的 runAs 参数或 ssh_exec_as_user,避免手写 su 命令造成引用和环境加载差异'
154
- : level === 'high'
155
- ? '考虑用 ssh_exec_script、ssh_pty_start,或把输出重定向到远端文件后用 ssh_read_file 分块读取'
156
- : '如输出较大,请设置 maxOutputSize 或重定向到远端文件后分块读取',
157
- };
158
- }
99
+ // ========== Handlers ==========
159
100
  async function handleExec(args) {
160
101
  try {
161
102
  const result = await sessionManager.exec(args.alias, args.command, {
@@ -168,7 +109,7 @@ async function handleExec(args) {
168
109
  useLoginUser: args.useLoginUser,
169
110
  loadProfile: args.loadProfile,
170
111
  });
171
- return formatResult({ ...result, commandRisk: classifyCommandRisk(args.command) });
112
+ return formatResult({ ...result, commandRisk: classifyCommandRisk(args.command, args.timeout) });
172
113
  }
173
114
  catch (error) {
174
115
  return formatError(error);
@@ -184,7 +125,7 @@ async function handleExecAsUser(args) {
184
125
  maxOutputSize: args.maxOutputSize,
185
126
  loadProfile: args.loadProfile,
186
127
  });
187
- return formatResult({ ...result, commandRisk: classifyCommandRisk(args.command) });
128
+ return formatResult({ ...result, commandRisk: classifyCommandRisk(args.command, args.timeout) });
188
129
  }
189
130
  const result = await sessionManager.exec(args.alias, args.command, {
190
131
  timeout: args.timeout,
@@ -193,7 +134,7 @@ async function handleExecAsUser(args) {
193
134
  maxOutputSize: args.maxOutputSize,
194
135
  loadProfile: args.loadProfile,
195
136
  });
196
- return formatResult({ ...result, commandRisk: classifyCommandRisk(args.command) });
137
+ return formatResult({ ...result, commandRisk: classifyCommandRisk(args.command, args.timeout) });
197
138
  }
198
139
  catch (error) {
199
140
  return formatError(error);
@@ -216,7 +157,7 @@ async function handleExecBatch(args) {
216
157
  const stopOnError = args.stopOnError !== false;
217
158
  const results = [];
218
159
  for (let i = 0; i < args.commands.length; i++) {
219
- const commandRisk = classifyCommandRisk(args.commands[i]);
160
+ const commandRisk = classifyCommandRisk(args.commands[i], args.timeout);
220
161
  try {
221
162
  const execResult = await sessionManager.exec(args.alias, args.commands[i], { timeout: args.timeout });
222
163
  results.push({
@@ -341,7 +282,7 @@ function validateScriptUser(username) {
341
282
  }
342
283
  }
343
284
  function resolveScriptUsers(args) {
344
- const session = sessionManager.listSessions().find((item) => item.alias === args.alias);
285
+ const session = sessionManager.listSessionDetails().find((item) => item.alias === args.alias);
345
286
  return {
346
287
  effectiveUser: args.targetUser ?? args.runAs ?? session?.runAs,
347
288
  loginUser: session?.username,
@@ -5,4 +5,5 @@
5
5
  * ssh_list_dir, ssh_file_info, ssh_mkdir, ssh_sync
6
6
  */
7
7
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
8
+ export declare function createAtomicUploadPath(remotePath: string): string;
8
9
  export declare function registerFileTools(server: McpServer): void;