@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.
@@ -23,13 +23,15 @@ const forwardLocalSchema = z.object({
23
23
  });
24
24
  const forwardRemoteSchema = z.object({
25
25
  alias: z.string().describe('连接别名'),
26
- remotePort: z.number().describe('远程监听端口'),
26
+ remotePort: z.number().int().min(0).max(65535).describe('远程监听端口,传 0 时由服务器动态分配'),
27
27
  localHost: z.string().describe('本地目标地址'),
28
28
  localPort: z.number().describe('本地目标端口'),
29
29
  remoteHost: loopbackHostSchema.describe('远程监听地址,仅允许 loopback(127.0.0.1 / ::1 / localhost),默认 127.0.0.1'),
30
30
  });
31
31
  const forwardCloseSchema = z.object({
32
32
  forwardId: z.string().describe('端口转发 ID'),
33
+ mode: z.enum(['graceful', 'force']).optional().describe('关闭模式,默认 graceful;force 会销毁活跃连接'),
34
+ timeoutMs: z.number().int().positive().max(60000).optional().describe('等待底层 listener 释放的超时,默认 5000ms'),
33
35
  });
34
36
  const forwardListSchema = z.object({});
35
37
  // ========== Handlers ==========
@@ -50,12 +52,13 @@ async function handleForwardLocal(args) {
50
52
  }
51
53
  async function handleForwardRemote(args) {
52
54
  try {
53
- const forwardId = await sessionManager.forwardRemote(args.alias, args.remotePort, args.localHost, args.localPort, args.remoteHost);
55
+ const { forwardId, remotePort } = await sessionManager.forwardRemote(args.alias, args.remotePort, args.localHost, args.localPort, args.remoteHost);
54
56
  return formatResult({
55
57
  success: true,
56
58
  forwardId,
57
59
  type: 'remote',
58
- message: `Remote forward: ${args.remoteHost}:${args.remotePort} -> ${args.localHost}:${args.localPort}`,
60
+ remotePort,
61
+ message: `Remote forward: ${args.remoteHost}:${remotePort} -> ${args.localHost}:${args.localPort}`,
59
62
  });
60
63
  }
61
64
  catch (error) {
@@ -64,10 +67,13 @@ async function handleForwardRemote(args) {
64
67
  }
65
68
  async function handleForwardClose(args) {
66
69
  try {
67
- const success = sessionManager.forwardClose(args.forwardId);
70
+ const result = await sessionManager.forwardClose(args.forwardId, {
71
+ mode: args.mode,
72
+ timeoutMs: args.timeoutMs,
73
+ });
68
74
  return formatResult({
69
- success,
70
- message: success ? `Forward closed: ${args.forwardId}` : `Forward not found: ${args.forwardId}`,
75
+ ...result,
76
+ message: result.success ? `Forward closed: ${args.forwardId}` : `Forward close failed: ${args.forwardId}`,
71
77
  });
72
78
  }
73
79
  catch (error) {
@@ -106,11 +112,15 @@ export function registerForwardTools(server) {
106
112
 
107
113
  用途:将本地服务暴露到远程
108
114
  示例:ssh_forward_remote(alias="server", remotePort=8080, localHost="127.0.0.1", localPort=3000)
109
- 效果:远程访问 localhost:8080 会转发到本地的 127.0.0.1:3000`,
115
+ 效果:远程访问 localhost:8080 会转发到本地的 127.0.0.1:3000
116
+ 传 remotePort=0 时由服务器动态分配端口,返回结果中的 remotePort 是实际监听端口`,
110
117
  inputSchema: forwardRemoteSchema,
111
118
  }, (args) => handleForwardRemote(args));
112
119
  server.registerTool('ssh_forward_close', {
113
- description: '关闭端口转发',
120
+ description: `关闭端口转发
121
+
122
+ 默认 graceful 模式,等待底层 listener 确认释放后才返回成功。force 模式会先销毁活跃连接。
123
+ 关闭失败或超时时保留 forward 状态,可使用同一 forwardId 重试。`,
114
124
  inputSchema: forwardCloseSchema,
115
125
  }, (args) => handleForwardClose(args));
116
126
  server.registerTool('ssh_forward_list', {
@@ -4,5 +4,6 @@
4
4
  export { registerConnectionTools } from './connection.js';
5
5
  export { registerExecTools } from './exec.js';
6
6
  export { registerFileTools } from './file.js';
7
+ export { registerOperationTools } from './operation.js';
7
8
  export { registerPtyTools } from './pty.js';
8
9
  export { registerForwardTools } from './forward.js';
@@ -4,5 +4,6 @@
4
4
  export { registerConnectionTools } from './connection.js';
5
5
  export { registerExecTools } from './exec.js';
6
6
  export { registerFileTools } from './file.js';
7
+ export { registerOperationTools } from './operation.js';
7
8
  export { registerPtyTools } from './pty.js';
8
9
  export { registerForwardTools } from './forward.js';
@@ -0,0 +1,2 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ export declare function registerOperationTools(server: McpServer): void;
@@ -0,0 +1,134 @@
1
+ import { z } from 'zod';
2
+ import { DEFAULT_OPERATION_MAX_OUTPUT_BYTES, DEFAULT_OPERATION_READ_BYTES, DEFAULT_OPERATION_RETENTION_MS, DEFAULT_OPERATION_START_TIMEOUT_MS, HARD_OPERATION_MAX_OUTPUT_BYTES, HARD_OPERATION_READ_BYTES, MAX_OPERATION_RETENTION_MS, MAX_OPERATION_START_TIMEOUT_MS, } from '../operation-manager.js';
3
+ import { sessionManager } from '../session-manager.js';
4
+ import { formatError, formatResult } from './utils.js';
5
+ const operationStartSchema = z.object({
6
+ alias: z.string().describe('连接别名'),
7
+ command: z.string().describe('要在远端跟踪执行的命令'),
8
+ cwd: z.string().optional().describe('工作目录(可选)'),
9
+ env: z.record(z.string(), z.string()).optional().describe('额外环境变量'),
10
+ runAs: z.string().optional().describe('本次命令使用的目标用户,覆盖连接级 runAs'),
11
+ useLoginUser: z.boolean().optional().describe('设为 true 时跳过连接级 runAs,直接以登录用户执行'),
12
+ loadProfile: z.boolean().optional().describe('runAs 执行时是否加载目标用户 shell 配置,默认 true'),
13
+ maxOutputBytes: z
14
+ .number()
15
+ .int()
16
+ .positive()
17
+ .max(HARD_OPERATION_MAX_OUTPUT_BYTES)
18
+ .optional()
19
+ .describe(`内存输出硬上限,默认 ${DEFAULT_OPERATION_MAX_OUTPUT_BYTES} 字节,最大 ${HARD_OPERATION_MAX_OUTPUT_BYTES}`),
20
+ retentionMs: z
21
+ .number()
22
+ .int()
23
+ .positive()
24
+ .max(MAX_OPERATION_RETENTION_MS)
25
+ .optional()
26
+ .describe(`完成后的状态保留时间,默认 ${DEFAULT_OPERATION_RETENTION_MS}ms,最大 ${MAX_OPERATION_RETENTION_MS}ms`),
27
+ startTimeoutMs: z
28
+ .number()
29
+ .int()
30
+ .positive()
31
+ .max(MAX_OPERATION_START_TIMEOUT_MS)
32
+ .optional()
33
+ .describe(`等待 SSH operation channel 建立的超时,默认 ${DEFAULT_OPERATION_START_TIMEOUT_MS}ms,最大 ${MAX_OPERATION_START_TIMEOUT_MS}ms`),
34
+ });
35
+ const operationIdSchema = z.object({
36
+ operationId: z.string().describe('tracked operation ID'),
37
+ });
38
+ const operationReadSchema = operationIdSchema.extend({
39
+ stdoutOffset: z.number().int().nonnegative().optional().describe('stdout 起始字节偏移,默认 0'),
40
+ stderrOffset: z.number().int().nonnegative().optional().describe('stderr 起始字节偏移,默认 0'),
41
+ maxBytes: z
42
+ .number()
43
+ .int()
44
+ .positive()
45
+ .max(HARD_OPERATION_READ_BYTES)
46
+ .optional()
47
+ .describe(`本次读取总字节上限,默认 ${DEFAULT_OPERATION_READ_BYTES},最大 ${HARD_OPERATION_READ_BYTES}`),
48
+ });
49
+ const operationListSchema = z.object({
50
+ alias: z.string().optional().describe('按连接别名过滤'),
51
+ });
52
+ async function handleOperationStart(args) {
53
+ try {
54
+ const operation = await sessionManager.operationStart(args.alias, args.command, {
55
+ cwd: args.cwd,
56
+ env: args.env,
57
+ runAs: args.runAs,
58
+ useLoginUser: args.useLoginUser,
59
+ loadProfile: args.loadProfile,
60
+ maxOutputBytes: args.maxOutputBytes,
61
+ retentionMs: args.retentionMs,
62
+ startTimeoutMs: args.startTimeoutMs,
63
+ });
64
+ return formatResult({ success: true, ...operation });
65
+ }
66
+ catch (error) {
67
+ return formatError(error);
68
+ }
69
+ }
70
+ async function handleOperationStatus(args) {
71
+ try {
72
+ return formatResult({ success: true, ...sessionManager.operationStatus(args.operationId) });
73
+ }
74
+ catch (error) {
75
+ return formatError(error);
76
+ }
77
+ }
78
+ async function handleOperationRead(args) {
79
+ try {
80
+ return formatResult({
81
+ success: true,
82
+ ...sessionManager.operationRead(args.operationId, {
83
+ stdoutOffset: args.stdoutOffset,
84
+ stderrOffset: args.stderrOffset,
85
+ maxBytes: args.maxBytes,
86
+ }),
87
+ });
88
+ }
89
+ catch (error) {
90
+ return formatError(error);
91
+ }
92
+ }
93
+ async function handleOperationCancel(args) {
94
+ try {
95
+ return formatResult(await sessionManager.operationCancel(args.operationId));
96
+ }
97
+ catch (error) {
98
+ return formatError(error);
99
+ }
100
+ }
101
+ async function handleOperationList(args) {
102
+ try {
103
+ const operations = sessionManager.operationList(args.alias);
104
+ return formatResult({ success: true, count: operations.length, operations });
105
+ }
106
+ catch (error) {
107
+ return formatError(error);
108
+ }
109
+ }
110
+ export function registerOperationTools(server) {
111
+ server.registerTool('ssh_operation_start', {
112
+ description: `启动可跟踪的长时间远端命令
113
+
114
+ 返回不可预测的 operationId。channel 建立受 startTimeoutMs 限制,等待期间 record 可通过 list 查询;超时 details 返回 operationId。
115
+ 输出保存在有硬上限的内存缓冲区中,完成后按 retentionMs 自动过期。普通 ssh_exec 的同步和 timeout 行为不变。`,
116
+ inputSchema: operationStartSchema,
117
+ }, (args) => handleOperationStart(args));
118
+ server.registerTool('ssh_operation_status', {
119
+ description: '查询 tracked operation 状态、远端 PID、输出计数和过期时间',
120
+ inputSchema: operationIdSchema,
121
+ }, (args) => handleOperationStatus(args));
122
+ server.registerTool('ssh_operation_read', {
123
+ description: '按字节偏移读取 tracked operation 的有界 stdout/stderr 缓冲区',
124
+ inputSchema: operationReadSchema,
125
+ }, (args) => handleOperationRead(args));
126
+ server.registerTool('ssh_operation_cancel', {
127
+ description: '校验远端 operation marker 后发送 TERM;marker 无法证明时拒绝取消',
128
+ inputSchema: operationIdSchema,
129
+ }, (args) => handleOperationCancel(args));
130
+ server.registerTool('ssh_operation_list', {
131
+ description: '列出未过期的 tracked operations,可按 alias 过滤',
132
+ inputSchema: operationListSchema,
133
+ }, (args) => handleOperationList(args));
134
+ }
@@ -12,7 +12,7 @@ export declare function expandTilde(p: string): string;
12
12
  */
13
13
  export declare function formatResult(data: unknown): {
14
14
  content: {
15
- type: "text";
15
+ type: 'text';
16
16
  text: string;
17
17
  }[];
18
18
  };
@@ -21,7 +21,7 @@ export declare function formatResult(data: unknown): {
21
21
  */
22
22
  export declare function formatError(error: unknown): {
23
23
  content: {
24
- type: "text";
24
+ type: 'text';
25
25
  text: string;
26
26
  }[];
27
27
  isError: boolean;
@@ -0,0 +1,12 @@
1
+ export type VerificationStatus = 'not_requested' | 'matched' | 'mismatched' | 'skipped' | 'error';
2
+ export type TransferOutcome = {
3
+ success: boolean;
4
+ transferSuccess: boolean;
5
+ verificationRequested: boolean;
6
+ verificationSuccess?: boolean;
7
+ verificationStatus: VerificationStatus;
8
+ failedChecks: string[];
9
+ expected?: unknown;
10
+ actual?: unknown;
11
+ };
12
+ export declare function buildTransferOutcome(transferSuccess: boolean, verificationRequested: boolean, verification?: Record<string, unknown>, verificationError?: unknown): TransferOutcome;
@@ -0,0 +1,72 @@
1
+ function collectChecks(value, prefix, failed, skipped) {
2
+ if (!value || typeof value !== 'object') {
3
+ return;
4
+ }
5
+ const record = value;
6
+ if (record.skipped === true) {
7
+ skipped.push(prefix || 'verification');
8
+ }
9
+ if (record.checks && typeof record.checks === 'object') {
10
+ for (const [name, matched] of Object.entries(record.checks)) {
11
+ if (matched !== true) {
12
+ failed.push(prefix ? `${prefix}.${name}` : name);
13
+ }
14
+ }
15
+ }
16
+ if ('hashMatch' in record && record.hashMatch !== true) {
17
+ failed.push(prefix ? `${prefix}.sha256` : 'sha256');
18
+ }
19
+ for (const [name, child] of Object.entries(record)) {
20
+ if (name === 'checks' || name === 'expected' || name === 'actual' || name === 'local' || name === 'remote') {
21
+ continue;
22
+ }
23
+ if (child && typeof child === 'object') {
24
+ collectChecks(child, prefix ? `${prefix}.${name}` : name, failed, skipped);
25
+ }
26
+ }
27
+ }
28
+ export function buildTransferOutcome(transferSuccess, verificationRequested, verification, verificationError) {
29
+ if (!verificationRequested) {
30
+ return {
31
+ success: transferSuccess,
32
+ transferSuccess,
33
+ verificationRequested: false,
34
+ verificationStatus: 'not_requested',
35
+ failedChecks: [],
36
+ };
37
+ }
38
+ if (verificationError !== undefined) {
39
+ return {
40
+ success: false,
41
+ transferSuccess,
42
+ verificationRequested: true,
43
+ verificationSuccess: false,
44
+ verificationStatus: 'error',
45
+ failedChecks: ['verification_error'],
46
+ };
47
+ }
48
+ if (!transferSuccess && verification === undefined) {
49
+ return {
50
+ success: false,
51
+ transferSuccess: false,
52
+ verificationRequested: true,
53
+ verificationSuccess: false,
54
+ verificationStatus: 'skipped',
55
+ failedChecks: ['verification'],
56
+ };
57
+ }
58
+ const failedChecks = [];
59
+ const skipped = [];
60
+ collectChecks(verification, '', failedChecks, skipped);
61
+ const verificationSuccess = skipped.length === 0 && failedChecks.length === 0;
62
+ return {
63
+ success: transferSuccess && verificationSuccess,
64
+ transferSuccess,
65
+ verificationRequested: true,
66
+ verificationSuccess,
67
+ verificationStatus: skipped.length > 0 ? 'skipped' : verificationSuccess ? 'matched' : 'mismatched',
68
+ failedChecks: skipped.length > 0 ? [...new Set([...failedChecks, ...skipped])] : [...new Set(failedChecks)],
69
+ expected: verification?.expected,
70
+ actual: verification?.actual ?? verification?.remote,
71
+ };
72
+ }
package/dist/types.d.ts CHANGED
@@ -23,18 +23,41 @@ export interface SSHConnectionConfig {
23
23
  shell?: string;
24
24
  jumpHost?: SSHConnectionConfig;
25
25
  }
26
- export interface SSHSessionInfo {
26
+ export interface SSHSessionBrief {
27
27
  alias: string;
28
28
  identity: string;
29
+ runAs?: string;
30
+ connected: boolean;
31
+ lastUsedAt: number;
32
+ }
33
+ export interface SSHSessionDetail extends SSHSessionBrief {
29
34
  host: string;
30
35
  port: number;
31
36
  username: string;
32
- runAs?: string;
33
- keyPath?: string;
34
- authMethod: 'key' | 'password' | 'agent';
35
- connected: boolean;
37
+ authMethod: 'key' | 'password' | 'agent' | 'inline-key';
36
38
  connectedAt: number;
37
- lastUsedAt: number;
39
+ hasJumpHost: boolean;
40
+ }
41
+ export interface ExternalTransferCapability {
42
+ alias: string;
43
+ identity: string;
44
+ host: string;
45
+ port: number;
46
+ username: string;
47
+ authMethod: 'key-path' | 'password' | 'agent' | 'inline-key';
48
+ keyPath?: string;
49
+ hasJumpHost: boolean;
50
+ routeSafeForOpenSsh: boolean;
51
+ rsyncEligible: boolean;
52
+ decisionReason: string;
53
+ }
54
+ export type ConnectionFailureStage = 'preflight' | 'authentication' | 'ready_timeout' | 'transport_or_handshake' | 'unknown';
55
+ export type ConnectionStep = 'key_read' | 'jump_connect' | 'jump_forward' | 'target_connect';
56
+ export interface ConnectionFailureDetails {
57
+ failureStage: ConnectionFailureStage;
58
+ connectionStep?: ConnectionStep;
59
+ retryable: boolean;
60
+ suggestion?: string;
38
61
  }
39
62
  export interface ExecOptions {
40
63
  timeout?: number;
@@ -79,6 +102,56 @@ export interface ExecResult {
79
102
  envInjectedKeys?: string[];
80
103
  timedOut?: boolean;
81
104
  }
105
+ export type OperationStatus = 'starting' | 'running' | 'completed' | 'failed' | 'cancelled' | 'unknown';
106
+ export interface OperationStartOptions {
107
+ cwd?: string;
108
+ env?: Record<string, string>;
109
+ runAs?: string;
110
+ useLoginUser?: boolean;
111
+ loadProfile?: boolean;
112
+ maxOutputBytes?: number;
113
+ retentionMs?: number;
114
+ startTimeoutMs?: number;
115
+ }
116
+ export interface OperationInfo {
117
+ operationId: string;
118
+ alias: string;
119
+ status: OperationStatus;
120
+ pid: number | null;
121
+ processGroup: boolean;
122
+ markerVerified: boolean;
123
+ cancelRequested: boolean;
124
+ startedAt: number;
125
+ finishedAt: number | null;
126
+ expiresAt: number | null;
127
+ retentionMs: number;
128
+ exitCode: number | null;
129
+ signal: string | null;
130
+ stdoutBytes: number;
131
+ stderrBytes: number;
132
+ stdoutStoredBytes: number;
133
+ stderrStoredBytes: number;
134
+ stdoutTruncated: boolean;
135
+ stderrTruncated: boolean;
136
+ maxOutputBytes: number;
137
+ error?: string;
138
+ }
139
+ export interface OperationReadResult extends OperationInfo {
140
+ stdout: string;
141
+ stderr: string;
142
+ stdoutOffset: number;
143
+ stderrOffset: number;
144
+ nextStdoutOffset: number;
145
+ nextStderrOffset: number;
146
+ readBytes: number;
147
+ maxReadBytes: number;
148
+ }
149
+ export interface OperationCancelResult extends OperationInfo {
150
+ success: boolean;
151
+ cancelRequested: boolean;
152
+ retryable: boolean;
153
+ verificationError?: string;
154
+ }
82
155
  export interface FileInfo {
83
156
  name: string;
84
157
  path: string;
@@ -141,3 +214,19 @@ export interface PortForwardInfo {
141
214
  createdAt: number;
142
215
  active: boolean;
143
216
  }
217
+ export type ForwardCloseMode = 'graceful' | 'force';
218
+ export interface ForwardCloseOptions {
219
+ mode?: ForwardCloseMode;
220
+ timeoutMs?: number;
221
+ }
222
+ export interface ForwardCloseResult {
223
+ success: boolean;
224
+ forwardId: string;
225
+ type?: ForwardType;
226
+ closeMode: ForwardCloseMode;
227
+ listenerReleased: boolean;
228
+ remoteUnforwarded: boolean;
229
+ activeConnections: number;
230
+ retryable: boolean;
231
+ error?: string;
232
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyrokine/mcp-ssh",
3
- "version": "2.3.2",
3
+ "version": "2.4.1",
4
4
  "description": "A comprehensive SSH MCP Server for Claude Code",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -8,13 +8,14 @@
8
8
  "mcp-ssh": "dist/index.js"
9
9
  },
10
10
  "scripts": {
11
- "build": "tsc",
11
+ "build": "node node_modules/typescript7/bin/tsc",
12
12
  "start": "node dist/index.js",
13
- "dev": "tsc && node dist/index.js",
13
+ "dev": "node node_modules/typescript7/bin/tsc && node dist/index.js",
14
14
  "clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
15
15
  "prepublishOnly": "npm run build",
16
16
  "lint": "eslint \"src/**/*.ts\"",
17
17
  "lint:fix": "eslint \"src/**/*.ts\" --fix",
18
+ "test": "npm run build && node test/run-tests.mjs",
18
19
  "format": "prettier --write src/",
19
20
  "format:check": "prettier --check src/"
20
21
  },
@@ -39,12 +40,13 @@
39
40
  },
40
41
  "devDependencies": {
41
42
  "@eslint/js": "^10.0.1",
42
- "@types/node": "^25.9.3",
43
+ "@types/node": "^26.1.1",
43
44
  "@types/ssh2": "^1.15.5",
44
- "eslint": "^10.5.0",
45
- "prettier": "^3.8.4",
46
- "typescript": "^6.0.3",
47
- "typescript-eslint": "^8.61.0"
45
+ "eslint": "^10.7.0",
46
+ "prettier": "^3.9.5",
47
+ "typescript": "npm:@typescript/typescript6@^6.0.2",
48
+ "typescript-eslint": "^8.64.0",
49
+ "typescript7": "npm:typescript@^7.0.2"
48
50
  },
49
51
  "engines": {
50
52
  "node": ">=20.19.0"