mcp-ssh-manager 3.5.1 → 3.6.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,43 @@ All notable changes to MCP SSH Manager will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [3.6.1] - 2026-06-09
9
+
10
+ ### Fixed
11
+
12
+ - **Module-level monitor/cleanup intervals pinned the Node event loop** (follow-up to [#41](https://github.com/bvisible/mcp-ssh-manager/pull/41))
13
+ - `tunnel-manager.js` (`monitorTunnels`, every 30 s) and `session-manager.js` (inactive-session cleanup, every 5 min) registered module-level `setInterval` timers that were never `unref()`'d, so importing either module kept the event loop alive on its own.
14
+ - Both are now `unref()`'d, matching the keepalive and cleanup timers fixed in #41. The forced-exit added in #41 already made these harmless for the orphan-process bug; this restores proper teardown hygiene so process lifetime tracks the stdio transport, not a background timer.
15
+ - Verified: before, importing either module never exits on its own; after, both exit naturally. Full `npm test` (including `test:lifecycle`) stays green.
16
+
17
+ ## [3.6.0] - 2026-06-09
18
+
19
+ ### Added
20
+
21
+ - **Live configuration hot reload** ([#40](https://github.com/bvisible/mcp-ssh-manager/pull/40) — thanks [@EnjoySR](https://github.com/EnjoySR))
22
+ - The MCP server now reloads its server configuration when the `.env` or TOML file changes on disk, so tools like `ssh_list_servers` see newly added or edited servers **without restarting the MCP process**.
23
+ - A new `ServerConfigManager` tracks a lightweight signature (path + `mtime` + size) of both config files and reloads **lazily** — only when that signature changes, on the next config access. No file watcher, no polling thread, no background timer.
24
+ - **Fail-safe:** if a reload throws (e.g. a malformed file caught mid-edit), the last known-good configuration is kept in memory and the error is logged — the server never ends up with an empty or broken config.
25
+ - `.env` parsing no longer permanently mutates `process.env` (`dotenv` is now read with `processEnv: {}`), and real process environment variables keep the **highest priority** over file values, matching the documented loading order.
26
+
27
+ ### Fixed
28
+
29
+ - **stdio server orphaned on session teardown — one leaked node process per session** ([#41](https://github.com/bvisible/mcp-ssh-manager/pull/41) — thanks [@LegendaryGatz](https://github.com/LegendaryGatz))
30
+ - A stdio MCP server is torn down by its host closing **stdin (EOF)** and/or sending **SIGTERM** — not `SIGINT`, which only arrives on an interactive Ctrl-C. The only shutdown handler was `SIGINT`, so on normal teardown the process was never signalled, got reparented to init, and leaked (~83 MB plus live keepalive timers each, accumulating one process per session).
31
+ - Shutdown is now an **idempotent** `shutdown(reason)` registered on `SIGINT`, `SIGTERM`, `SIGHUP` and stdin `'end'`/`'close'`. The per-connection keepalive interval and the 10-minute cleanup interval are `unref()`'d so process lifetime tracks the transport, not a timer. `ssh.dispose()` is wrapped in try/catch so one bad connection can't block the rest, and a short `unref`'d timer forces exit so teardown can never hang if the host has already stopped reading.
32
+ - Measured: exits cleanly **~10 ms** after stdin EOF, versus staying alive indefinitely before.
33
+
34
+ ### Tests
35
+
36
+ - **New `tests/test-lifecycle.js`** (wired into `npm test` as `test:lifecycle`) — black-box teardown coverage asserting a clean exit on stdin EOF, SIGTERM, SIGINT and overlapping signals. Regression guard for the orphan-process bug.
37
+ - **`tests/test-server-config-manager.js` extended to 9 checks** — laziness (no reload while files are unchanged, exactly one reload after a change), reload-failure-keeps-last-valid-config plus recovery, and deleted-file robustness, in addition to the original TOML/`.env` hot-reload paths.
38
+
39
+ ### Backward compatibility
40
+
41
+ - **Zero impact on existing setups.** Hot reload is transparent — if your config files don't change, behavior is identical to v3.5.x. No new config field, no new prompt, no new file is ever created.
42
+ - The lifecycle fix is pure teardown hygiene: no change to any tool's behavior or output.
43
+ - All pre-existing test suites pass unmodified.
44
+
8
45
  ## [3.5.1] - 2026-05-26
9
46
 
10
47
  ### Fixed
package/README.md CHANGED
@@ -20,21 +20,27 @@ A Model Context Protocol (MCP) server that enables **Claude Code** and **OpenAI
20
20
 
21
21
  ---
22
22
 
23
- ## 🎉 What's New in v3.5.1
23
+ ## 🎉 What's New in v3.6.1
24
24
 
25
- **Robust SSH ping health-check on Windows/OpenSSH** (Released: May 26, 2026)
25
+ **Teardown hygiene follow-up** (Released: June 9, 2026)
26
26
 
27
- - **🪟 Healthy Windows sessions are no longer reported as `Dead`** ([#39](https://github.com/bvisible/mcp-ssh-manager/pull/39) — thanks [@username77](https://github.com/username77))
28
- - `ssh_connection_status` ran `echo "ping"` and compared the output with a strict `=== 'ping'`. On `cmd.exe` the surrounding quotes are echoed literally (output `"ping"`), so the check failed and a live pooled connection was torn down and rebuilt for nothing.
29
- - The probe now runs `echo ping` (no quotes) — a bare `ping` across bash, `cmd.exe` and PowerShell — fixing the root cause rather than only the symptom.
30
- - Output parsing moved to an exported, null-safe `isPingAlive(stdout)` helper (CRLF / quote / case-normalized). `includes('ping')` is intentional: a liveness probe should err toward "alive". New `tests/test-ssh-ping.js` is wired into `npm test`. Validated against a real Windows/OpenSSH host.
27
+ - **🔌 Module-level timers no longer pin the event loop** (follow-up to [#41](https://github.com/bvisible/mcp-ssh-manager/pull/41)) — `tunnel-manager.js` (`monitorTunnels`, 30 s) and `session-manager.js` (session cleanup, 5 min) registered module-level `setInterval`s that were never `unref()`'d, so importing either module kept Node's event loop alive on its own. Both are now `unref()`'d, matching the timers fixed in #41. Already covered by #41's forced-exit for the orphan bug — this restores clean teardown so process lifetime tracks the stdio transport. `npm test` (incl. `test:lifecycle`) stays green.
31
28
 
32
- [Read full changelog →](CHANGELOG.md#351---2026-05-26)
29
+ [Read full changelog →](CHANGELOG.md#361---2026-06-09)
33
30
 
34
31
  ---
35
32
 
36
33
  ## Previous Releases
37
34
 
35
+ ### v3.6.0 - Live config hot reload + stdio lifecycle fix (June 9, 2026)
36
+
37
+ - **♻️ Configuration hot reload** ([#40](https://github.com/bvisible/mcp-ssh-manager/pull/40) — thanks [@EnjoySR](https://github.com/EnjoySR)) — add or edit a server in your `.env`/TOML and the running MCP server picks it up on the next call, no restart. A `ServerConfigManager` reloads lazily on file-signature change (path + `mtime` + size); a failed reload keeps the last known-good config; real `process.env` vars keep top priority. No watcher, no polling.
38
+ - **🔌 No more orphaned stdio processes** ([#41](https://github.com/bvisible/mcp-ssh-manager/pull/41) — thanks [@LegendaryGatz](https://github.com/LegendaryGatz)) — a stdio MCP server is torn down by stdin EOF / SIGTERM, not SIGINT; with only a `SIGINT` handler every session leaked a ~83 MB node process. Shutdown is now idempotent across `SIGINT`/`SIGTERM`/`SIGHUP`/stdin-close, timers are `unref()`'d, and the process exits **~10 ms** after teardown instead of never. [Full changelog →](CHANGELOG.md#360---2026-06-09)
39
+
40
+ ### v3.5.1 - Robust SSH ping health-check on Windows/OpenSSH (May 26, 2026)
41
+
42
+ - **🪟 Healthy Windows sessions no longer reported as `Dead`** ([#39](https://github.com/bvisible/mcp-ssh-manager/pull/39) — thanks [@username77](https://github.com/username77)) — the liveness probe ran `echo "ping"` and `cmd.exe` echoed the quotes literally, failing a strict `=== 'ping'` check and needlessly rebuilding live connections. Now uses `echo ping` parsed by a null-safe `isPingAlive(stdout)` helper (CRLF/quote/case-normalized), covered by `tests/test-ssh-ping.js`. [Full changelog →](CHANGELOG.md#351---2026-05-26)
43
+
38
44
  ### v3.5.0 - Per-server security modes — `readonly` / `restricted` + audit log (May 18, 2026)
39
45
 
40
46
  A second authorization layer that filters tool invocations **inside the MCP server**, complementing the existing client-side `autoApprove`. Useful when sharing the MCP with a third-party agent, a CI bot, or any client where `ssh_execute` shouldn't be unconditionally trusted.
@@ -1026,10 +1032,4 @@ Made with ❤️ for the Claude Code community
1026
1032
  <img width="380" height="200" src="https://glama.ai/mcp/servers/@bvisible/mcp-ssh-manager/badge" alt="SSH Manager MCP server" />
1027
1033
  </a>
1028
1034
 
1029
- <br/>
1030
-
1031
- <a href="https://mseep.ai/app/bvisible-mcp-ssh-manager">
1032
- <img src="https://mseep.net/pr/bvisible-mcp-ssh-manager-badge.png" alt="MseeP.ai Security Assessment Badge" />
1033
- </a>
1034
-
1035
1035
  </div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-ssh-manager",
3
- "version": "3.5.1",
3
+ "version": "3.6.1",
4
4
  "description": "MCP SSH Manager: Model Context Protocol server for SSH remote server management. Control SSH connections from Claude Code and OpenAI Codex - execute commands, transfer files, database operations, backups, health monitoring, and DevOps automation. NEW: Tool activation system reduces context usage by 92%",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -13,13 +13,15 @@
13
13
  "setup": "npm install && pip install -r tools/requirements.txt",
14
14
  "configure": "python tools/server-manager.py",
15
15
  "test-connection": "python tools/test-connection.py",
16
- "test": "npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:ping",
16
+ "test": "npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:ping && npm run test:config && npm run test:lifecycle",
17
17
  "test:profiles": "node tests/test-profiles.js",
18
18
  "test:aliases": "node tests/test-command-aliases.js",
19
19
  "test:hooks": "node tests/test-hooks.js",
20
20
  "test:tools": "node tests/test-tool-registry.js",
21
21
  "test:policy": "node tests/test-policy.js",
22
22
  "test:ping": "node tests/test-ssh-ping.js",
23
+ "test:config": "node tests/test-server-config-manager.js",
24
+ "test:lifecycle": "node tests/test-lifecycle.js",
23
25
  "test:all": "npm test && ./scripts/validate.sh",
24
26
  "validate": "./scripts/validate.sh",
25
27
  "lint": "eslint src/*.js",
@@ -152,8 +152,15 @@ export class ConfigLoader {
152
152
  * Load configuration from .env file
153
153
  */
154
154
  loadEnvConfig(envPath) {
155
- dotenv.config({ path: envPath });
156
- this.parseEnvVariables(process.env);
155
+ const result = dotenv.config({ path: envPath, processEnv: {} });
156
+ if (result.error) {
157
+ throw result.error;
158
+ }
159
+
160
+ this.parseEnvVariables({
161
+ ...process.env,
162
+ ...(result.parsed || {})
163
+ });
157
164
  }
158
165
 
159
166
  /**
package/src/index.js CHANGED
@@ -9,7 +9,7 @@ import fs from 'fs';
9
9
  import path from 'path';
10
10
  import os from 'os';
11
11
  import { fileURLToPath } from 'url';
12
- import { configLoader } from './config-loader.js';
12
+ import { ServerConfigManager } from './server-config-manager.js';
13
13
  import {
14
14
  getTempFilename,
15
15
  buildDeploymentStrategy,
@@ -192,27 +192,30 @@ function resolveEnvFilePath() {
192
192
  }
193
193
 
194
194
  const envFilePath = resolveEnvFilePath();
195
- dotenv.config({ path: envFilePath });
195
+ const envFile = dotenv.config({ path: envFilePath, processEnv: {} });
196
+ const envFileValues = envFile.parsed || {};
197
+
198
+ function getRuntimeEnv(name) {
199
+ return process.env[name] ?? envFileValues[name];
200
+ }
196
201
 
197
202
  // Initialize logger
198
203
  logger.info('MCP SSH Manager starting', {
199
- logLevel: process.env.SSH_LOG_LEVEL || 'INFO',
200
- verbose: process.env.SSH_VERBOSE === 'true',
204
+ logLevel: getRuntimeEnv('SSH_LOG_LEVEL') || 'INFO',
205
+ verbose: getRuntimeEnv('SSH_VERBOSE') === 'true',
201
206
  envFilePath
202
207
  });
203
208
 
204
209
  // Load SSH server configuration
205
- let servers = {};
210
+ const serverConfigManager = new ServerConfigManager({
211
+ envPath: envFilePath,
212
+ tomlPath: getRuntimeEnv('SSH_CONFIG_PATH'),
213
+ preferToml: getRuntimeEnv('PREFER_TOML_CONFIG') === 'true'
214
+ });
215
+
206
216
  try {
207
- const loadedServers = await configLoader.load({
208
- envPath: envFilePath,
209
- tomlPath: process.env.SSH_CONFIG_PATH,
210
- preferToml: process.env.PREFER_TOML_CONFIG === 'true'
211
- });
212
- for (const [name, config] of loadedServers) {
213
- servers[name] = config;
214
- }
215
- logger.info(`Loaded ${loadedServers.size} SSH server configurations from ${configLoader.configSource}`);
217
+ const loadedServers = await serverConfigManager.loadInitial();
218
+ logger.info(`Loaded ${Object.keys(loadedServers).length} SSH server configurations`);
216
219
  } catch (error) {
217
220
  logger.error('Failed to load server configuration', { error: error.message });
218
221
  }
@@ -261,10 +264,9 @@ const WRAPPED_COMMAND_TIMEOUT_GRACE_MS = 5000;
261
264
  const jumpDependencies = new Map();
262
265
 
263
266
  // Load server configuration (backward compatibility wrapper)
264
- function loadServerConfig() {
267
+ async function loadServerConfig() {
265
268
  // This function is kept for backward compatibility
266
- // The actual loading is done by configLoader during initialization
267
- return servers;
269
+ return serverConfigManager.getServers();
268
270
  }
269
271
 
270
272
  // ── Per-server security policy plumbing (v3.5.0+) ──────────────────────────────
@@ -275,15 +277,16 @@ function loadServerConfig() {
275
277
  // early-returns { allowed: true } and auditLog() is a no-op when AUDIT_LOG is
276
278
  // absent — so pre-v3.5.0 configs see zero behavior change.
277
279
 
278
- function getServerConfig(serverName) {
280
+ async function getServerConfig(serverName) {
279
281
  if (!serverName) return null;
282
+ const servers = await loadServerConfig();
280
283
  return servers[String(serverName).toLowerCase()] || null;
281
284
  }
282
285
 
283
286
  // Apply policy + audit a denial in one shot. Returns null when allowed; returns
284
287
  // an MCP error response object when denied (handler should `return` it directly).
285
- function applyServerPolicy(serverName, toolName, args, command) {
286
- const serverConfig = getServerConfig(serverName);
288
+ async function applyServerPolicy(serverName, toolName, args, command) {
289
+ const serverConfig = await getServerConfig(serverName);
287
290
  const policy = evaluatePolicy(serverConfig, toolName, command);
288
291
  if (!policy.allowed) {
289
292
  auditLog(serverConfig, toolName, args, policy);
@@ -308,8 +311,8 @@ function applyServerPolicy(serverName, toolName, args, command) {
308
311
 
309
312
  // Convenience for the success-path audit: handlers call this after execution to
310
313
  // record the outcome. No-op when AUDIT_LOG is not configured.
311
- function auditOk(serverName, toolName, args, executionResult) {
312
- const serverConfig = getServerConfig(serverName);
314
+ async function auditOk(serverName, toolName, args, executionResult) {
315
+ const serverConfig = await getServerConfig(serverName);
313
316
  auditLog(serverConfig, toolName, args, { allowed: true }, executionResult);
314
317
  }
315
318
 
@@ -419,6 +422,11 @@ function setupKeepalive(serverName, ssh) {
419
422
  }
420
423
  }, KEEPALIVE_INTERVAL);
421
424
 
425
+ // Don't let the keepalive timer keep the process alive on its own. As a stdio
426
+ // MCP server we must exit when our transport closes; an active interval would
427
+ // otherwise pin the event loop and leave the process orphaned.
428
+ if (typeof interval.unref === 'function') interval.unref();
429
+
422
430
  keepaliveIntervals.set(serverName, interval);
423
431
  }
424
432
 
@@ -511,7 +519,7 @@ async function createProxyCommandSocket(proxyCommand, host, port) {
511
519
 
512
520
  // Get or create SSH connection with reconnection support
513
521
  async function getConnection(serverName) {
514
- const servers = loadServerConfig();
522
+ const servers = await loadServerConfig();
515
523
 
516
524
  // Execute pre-connect hook
517
525
  await executeHook('pre-connect', { server: serverName });
@@ -670,7 +678,7 @@ registerToolConditional(
670
678
  // regex by hiding a destructive command behind an alias.
671
679
  const expandedCommand = expandCommandAlias(command);
672
680
 
673
- const denied = applyServerPolicy(serverName, 'ssh_execute', { command, cwd }, expandedCommand);
681
+ const denied = await applyServerPolicy(serverName, 'ssh_execute', { command, cwd }, expandedCommand);
674
682
  if (denied) return denied;
675
683
 
676
684
  try {
@@ -686,7 +694,7 @@ registerToolConditional(
686
694
  }
687
695
 
688
696
  // Use provided cwd, or default_dir from config, or no cwd
689
- const servers = loadServerConfig();
697
+ const servers = await loadServerConfig();
690
698
  const serverConfig = servers[serverName.toLowerCase()];
691
699
  const workingDir = cwd || serverConfig?.default_dir;
692
700
  const platform = serverConfig?.platform || 'linux';
@@ -725,7 +733,7 @@ registerToolConditional(
725
733
  const stdout = truncateOutput(result.stdout);
726
734
  const stderr = truncateOutput(result.stderr);
727
735
 
728
- auditOk(serverName, 'ssh_execute', { command, cwd }, {
736
+ await auditOk(serverName, 'ssh_execute', { command, cwd }, {
729
737
  code: result.code,
730
738
  success: result.code === 0,
731
739
  });
@@ -746,7 +754,7 @@ registerToolConditional(
746
754
  ],
747
755
  };
748
756
  } catch (error) {
749
- auditOk(serverName, 'ssh_execute', { command, cwd }, {
757
+ await auditOk(serverName, 'ssh_execute', { command, cwd }, {
750
758
  success: false,
751
759
  error: error.message,
752
760
  });
@@ -784,7 +792,7 @@ registerToolConditional(
784
792
  }
785
793
  },
786
794
  async ({ server: serverName, localPath, remotePath }) => {
787
- const denied = applyServerPolicy(serverName, 'ssh_upload', { localPath, remotePath });
795
+ const denied = await applyServerPolicy(serverName, 'ssh_upload', { localPath, remotePath });
788
796
  if (denied) return denied;
789
797
 
790
798
  try {
@@ -802,7 +810,7 @@ registerToolConditional(
802
810
  duration: `${Date.now() - startTime}ms`
803
811
  });
804
812
 
805
- auditOk(serverName, 'ssh_upload', { localPath, remotePath }, { success: true });
813
+ await auditOk(serverName, 'ssh_upload', { localPath, remotePath }, { success: true });
806
814
 
807
815
  return {
808
816
  content: [
@@ -813,7 +821,7 @@ registerToolConditional(
813
821
  ],
814
822
  };
815
823
  } catch (error) {
816
- auditOk(serverName, 'ssh_upload', { localPath, remotePath }, {
824
+ await auditOk(serverName, 'ssh_upload', { localPath, remotePath }, {
817
825
  success: false,
818
826
  error: error.message,
819
827
  });
@@ -902,12 +910,12 @@ registerToolConditional(
902
910
  }
903
911
  },
904
912
  async ({ server: serverName, source, destination, exclude = [], dryRun = false, delete: deleteFiles = false, compress = true, verbose = false, checksum = false, timeout = 30000 }) => {
905
- const denied = applyServerPolicy(serverName, 'ssh_sync', { source, destination, dryRun, delete: deleteFiles });
913
+ const denied = await applyServerPolicy(serverName, 'ssh_sync', { source, destination, dryRun, delete: deleteFiles });
906
914
  if (denied) return denied;
907
915
 
908
916
  try {
909
917
  const ssh = await getConnection(serverName);
910
- const servers = loadServerConfig();
918
+ const servers = await loadServerConfig();
911
919
  const serverConfig = servers[serverName.toLowerCase()];
912
920
 
913
921
  // Check if sshpass is available for password authentication
@@ -1291,7 +1299,7 @@ registerToolConditional(
1291
1299
  };
1292
1300
  } else {
1293
1301
  // Non-follow mode - just get the output
1294
- const tailServers = loadServerConfig();
1302
+ const tailServers = await loadServerConfig();
1295
1303
  const tailServerConfig = tailServers[serverName.toLowerCase()];
1296
1304
  const result = await execCommandWithTimeout(ssh, command, { platform: tailServerConfig?.platform }, 15000);
1297
1305
 
@@ -1400,7 +1408,7 @@ registerToolConditional(
1400
1408
 
1401
1409
  // Execute all monitoring commands
1402
1410
  const startTime = Date.now();
1403
- const monServers = loadServerConfig();
1411
+ const monServers = await loadServerConfig();
1404
1412
  const monServerConfig = monServers[serverName.toLowerCase()];
1405
1413
 
1406
1414
  for (const [key, cmd] of Object.entries(commands)) {
@@ -1671,7 +1679,7 @@ registerToolConditional(
1671
1679
  const session = getSession(sessionId);
1672
1680
 
1673
1681
  // Resolve the session's underlying server to its policy.
1674
- const denied = applyServerPolicy(session.serverName, 'ssh_session_send', { session: sessionId, command }, command);
1682
+ const denied = await applyServerPolicy(session.serverName, 'ssh_session_send', { session: sessionId, command }, command);
1675
1683
  if (denied) return denied;
1676
1684
 
1677
1685
  const startTime = Date.now();
@@ -1908,7 +1916,7 @@ registerToolConditional(
1908
1916
  // A server in readonly/restricted mode refuses the command; others
1909
1917
  // execute normally. Refusal is surfaced as a per-server failure rather
1910
1918
  // than aborting the whole group (group execution is best-effort).
1911
- const denied = applyServerPolicy(serverName, 'ssh_execute_group', { group: groupName, command, cwd }, command);
1919
+ const denied = await applyServerPolicy(serverName, 'ssh_execute_group', { group: groupName, command, cwd }, command);
1912
1920
  if (denied) {
1913
1921
  const errorText = denied.content?.[0]?.text || 'Policy denied';
1914
1922
  return { stdout: '', stderr: errorText, code: -2, success: false };
@@ -1918,7 +1926,7 @@ registerToolConditional(
1918
1926
  // Build full command with cwd if provided.
1919
1927
  // Use platform-appropriate syntax: Set-Location for Windows (cmd.exe
1920
1928
  // does not support `cd && `) vs cd && for Linux/macOS.
1921
- const servers = loadServerConfig();
1929
+ const servers = await loadServerConfig();
1922
1930
  const serverConfig = servers[serverName.toLowerCase()];
1923
1931
  const workingDir = cwd || serverConfig?.default_dir;
1924
1932
  const platform = serverConfig?.platform || 'linux';
@@ -2153,7 +2161,7 @@ registerToolConditional(
2153
2161
  inputSchema: {}
2154
2162
  },
2155
2163
  async () => {
2156
- const servers = loadServerConfig();
2164
+ const servers = await loadServerConfig();
2157
2165
  const serverInfo = Object.entries(servers).map(([name, config]) => ({
2158
2166
  name,
2159
2167
  host: config.host,
@@ -2196,7 +2204,7 @@ registerToolConditional(
2196
2204
  }
2197
2205
  },
2198
2206
  async ({ server, files, options = {} }) => {
2199
- const denied = applyServerPolicy(server, 'ssh_deploy', {
2207
+ const denied = await applyServerPolicy(server, 'ssh_deploy', {
2200
2208
  files: files.map((f) => ({ local: f.local, remote: f.remote })),
2201
2209
  options,
2202
2210
  });
@@ -2233,7 +2241,7 @@ registerToolConditional(
2233
2241
  results.push(`✅ Uploaded ${path.basename(file.local)} to temp location`);
2234
2242
 
2235
2243
  // Execute deployment strategy
2236
- const deployServers = loadServerConfig();
2244
+ const deployServers = await loadServerConfig();
2237
2245
  const deployServerConfig = deployServers[server.toLowerCase()];
2238
2246
  for (const step of strategy.steps) {
2239
2247
  const command = step.command.replace('{{tempFile}}', tempFile);
@@ -2301,12 +2309,12 @@ registerToolConditional(
2301
2309
  // ssh_execute_sudo is in READONLY_BLOCKED_TOOLS, so readonly mode blocks
2302
2310
  // it at the tool level. In restricted mode the command itself is matched
2303
2311
  // against ALLOW/DENY patterns.
2304
- const denied = applyServerPolicy(server, 'ssh_execute_sudo', { command, cwd }, command);
2312
+ const denied = await applyServerPolicy(server, 'ssh_execute_sudo', { command, cwd }, command);
2305
2313
  if (denied) return denied;
2306
2314
 
2307
2315
  try {
2308
2316
  const ssh = await getConnection(server);
2309
- const servers = loadServerConfig();
2317
+ const servers = await loadServerConfig();
2310
2318
  const resolvedName = resolveServerName(server, servers);
2311
2319
  const serverConfig = servers[resolvedName];
2312
2320
 
@@ -2776,7 +2784,7 @@ registerToolConditional(
2776
2784
  },
2777
2785
  async ({ server, type, localHost, localPort, remoteHost, remotePort }) => {
2778
2786
  try {
2779
- const servers = loadServerConfig();
2787
+ const servers = await loadServerConfig();
2780
2788
  const resolvedName = resolveServerName(server, servers);
2781
2789
 
2782
2790
  if (!resolvedName) {
@@ -2854,7 +2862,7 @@ registerToolConditional(
2854
2862
  },
2855
2863
  async ({ server }) => {
2856
2864
  try {
2857
- const servers = loadServerConfig();
2865
+ const servers = await loadServerConfig();
2858
2866
  let resolvedName = null;
2859
2867
 
2860
2868
  if (server) {
@@ -2951,7 +2959,7 @@ registerToolConditional(
2951
2959
  logger.info('SSH tunnel closed', { id: tunnelId });
2952
2960
  } else if (server) {
2953
2961
  // Close all tunnels for server
2954
- const servers = loadServerConfig();
2962
+ const servers = await loadServerConfig();
2955
2963
  const resolvedName = resolveServerName(server, servers);
2956
2964
 
2957
2965
  if (!resolvedName) {
@@ -3005,11 +3013,11 @@ registerToolConditional(
3005
3013
  // tool level. Pure-read actions (verify, list, check) are allowed regardless,
3006
3014
  // so we only gate when the action would modify state.
3007
3015
  if (server && (action === 'accept' || action === 'remove')) {
3008
- const denied = applyServerPolicy(server, 'ssh_key_manage', { action, autoAccept });
3016
+ const denied = await applyServerPolicy(server, 'ssh_key_manage', { action, autoAccept });
3009
3017
  if (denied) return denied;
3010
3018
  }
3011
3019
  try {
3012
- const servers = loadServerConfig();
3020
+ const servers = await loadServerConfig();
3013
3021
  let resolvedName, serverConfig, host, port;
3014
3022
 
3015
3023
  // Resolve server details for actions that need them
@@ -3260,7 +3268,7 @@ registerToolConditional(
3260
3268
  throw new Error('Both alias and server are required for add action');
3261
3269
  }
3262
3270
 
3263
- const servers = loadServerConfig();
3271
+ const servers = await loadServerConfig();
3264
3272
  const resolvedName = resolveServerName(server, servers);
3265
3273
 
3266
3274
  if (!resolvedName) {
@@ -3296,7 +3304,7 @@ registerToolConditional(
3296
3304
 
3297
3305
  case 'list': {
3298
3306
  const aliases = listAliases();
3299
- const servers = loadServerConfig();
3307
+ const servers = await loadServerConfig();
3300
3308
 
3301
3309
  const aliasInfo = aliases.map(({ alias, target }) => {
3302
3310
  const server = servers[target];
@@ -3364,7 +3372,7 @@ registerToolConditional(
3364
3372
  }
3365
3373
  },
3366
3374
  async ({ server: serverName, type, name, database, dbUser, dbPassword, dbHost, dbPort, paths, exclude, backupDir, retention = 7, compress = true }) => {
3367
- const denied = applyServerPolicy(serverName, 'ssh_backup_create', { type, name, database, paths });
3375
+ const denied = await applyServerPolicy(serverName, 'ssh_backup_create', { type, name, database, paths });
3368
3376
  if (denied) return denied;
3369
3377
 
3370
3378
  try {
@@ -3651,7 +3659,7 @@ registerToolConditional(
3651
3659
  }
3652
3660
  },
3653
3661
  async ({ server: serverName, backupId, database, dbUser, dbPassword, dbHost, dbPort, targetPath, backupDir }) => {
3654
- const denied = applyServerPolicy(serverName, 'ssh_backup_restore', { backupId, database, targetPath });
3662
+ const denied = await applyServerPolicy(serverName, 'ssh_backup_restore', { backupId, database, targetPath });
3655
3663
  if (denied) return denied;
3656
3664
 
3657
3665
  try {
@@ -3770,7 +3778,7 @@ registerToolConditional(
3770
3778
  }
3771
3779
  },
3772
3780
  async ({ server: serverName, schedule, type, name, database, paths, retention = 7 }) => {
3773
- const denied = applyServerPolicy(serverName, 'ssh_backup_schedule', { schedule, type, name, database, paths });
3781
+ const denied = await applyServerPolicy(serverName, 'ssh_backup_schedule', { schedule, type, name, database, paths });
3774
3782
  if (denied) return denied;
3775
3783
 
3776
3784
  try {
@@ -4075,7 +4083,7 @@ registerToolConditional(
4075
4083
  // Only the `kill` action mutates remote state — gate just that branch so
4076
4084
  // operators on readonly servers can still `list` / `info` processes.
4077
4085
  if (action === 'kill') {
4078
- const denied = applyServerPolicy(serverName, 'ssh_process_manager', { action, pid, signal });
4086
+ const denied = await applyServerPolicy(serverName, 'ssh_process_manager', { action, pid, signal });
4079
4087
  if (denied) return denied;
4080
4088
  }
4081
4089
  try {
@@ -4227,7 +4235,7 @@ registerToolConditional(
4227
4235
  async ({ server: serverName, action, cpuThreshold, memoryThreshold, diskThreshold, enabled = true }) => {
4228
4236
  // `set` writes config on the remote; `get` and `check` are read-only.
4229
4237
  if (action === 'set') {
4230
- const denied = applyServerPolicy(serverName, 'ssh_alert_setup', { action, cpuThreshold, memoryThreshold, diskThreshold, enabled });
4238
+ const denied = await applyServerPolicy(serverName, 'ssh_alert_setup', { action, cpuThreshold, memoryThreshold, diskThreshold, enabled });
4231
4239
  if (denied) return denied;
4232
4240
  }
4233
4241
  try {
@@ -4414,7 +4422,7 @@ registerToolConditional(
4414
4422
  }
4415
4423
  },
4416
4424
  async ({ server: serverName, type, database, outputFile, dbUser, dbPassword, dbHost, dbPort, compress = true, tables }) => {
4417
- const denied = applyServerPolicy(serverName, 'ssh_db_dump', { type, database, outputFile, tables });
4425
+ const denied = await applyServerPolicy(serverName, 'ssh_db_dump', { type, database, outputFile, tables });
4418
4426
  if (denied) return denied;
4419
4427
 
4420
4428
  try {
@@ -4528,7 +4536,7 @@ registerToolConditional(
4528
4536
  }
4529
4537
  },
4530
4538
  async ({ server: serverName, type, database, inputFile, dbUser, dbPassword, dbHost, dbPort, drop = true }) => {
4531
- const denied = applyServerPolicy(serverName, 'ssh_db_import', { type, database, inputFile, drop });
4539
+ const denied = await applyServerPolicy(serverName, 'ssh_db_import', { type, database, inputFile, drop });
4532
4540
  if (denied) return denied;
4533
4541
 
4534
4542
  try {
@@ -4858,22 +4866,51 @@ registerToolConditional(
4858
4866
  }
4859
4867
  );
4860
4868
 
4861
- // Clean up connections on shutdown
4862
- process.on('SIGINT', async () => {
4863
- console.error('\n🔌 Closing SSH connections...');
4869
+ // Clean up connections on shutdown.
4870
+ //
4871
+ // A stdio MCP server is torn down by its host (e.g. Claude Code) closing our
4872
+ // stdin — not by SIGINT, which only arrives on an interactive Ctrl-C. Handling
4873
+ // SIGINT alone meant the process was never signalled on normal teardown and was
4874
+ // reparented to init as an orphan, leaking one node process per session. Listen
4875
+ // for SIGTERM and stdin EOF as well, and make shutdown idempotent so overlapping
4876
+ // signals can't double-dispose.
4877
+ let isShuttingDown = false;
4878
+ function shutdown(reason) {
4879
+ if (isShuttingDown) return;
4880
+ isShuttingDown = true;
4881
+ console.error(`\n🔌 Closing SSH connections (${reason})...`);
4864
4882
  for (const [name, ssh] of connections) {
4865
- ssh.dispose();
4866
- console.error(` Closed connection to ${name}`);
4883
+ try {
4884
+ ssh.dispose();
4885
+ console.error(` Closed connection to ${name}`);
4886
+ } catch (error) {
4887
+ console.error(` Error closing ${name}: ${error.message}`);
4888
+ }
4867
4889
  }
4868
- process.exit(0);
4869
- });
4890
+ // Best-effort flush of any final stdout the host may still read, but never
4891
+ // hang if it has already stopped reading: a short unref'd timer forces exit
4892
+ // regardless, so this can't reintroduce a stuck process.
4893
+ const force = setTimeout(() => process.exit(0), 250);
4894
+ if (typeof force.unref === 'function') force.unref();
4895
+ process.stdout.write('', () => process.exit(0));
4896
+ }
4897
+
4898
+ process.on('SIGINT', () => shutdown('SIGINT'));
4899
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
4900
+ process.on('SIGHUP', () => shutdown('SIGHUP'));
4901
+ // When launched as a stdio MCP server the host closes our stdin to signal
4902
+ // teardown; treat that EOF as a shutdown request. 'end' fires when the readable
4903
+ // side is fully consumed; 'close' covers the fd being torn down without a clean
4904
+ // 'end'. The idempotent guard above makes the overlap harmless.
4905
+ process.stdin.on('end', () => shutdown('stdin ended'));
4906
+ process.stdin.on('close', () => shutdown('stdin closed'));
4870
4907
 
4871
4908
  // Start the server
4872
4909
  async function main() {
4873
4910
  const transport = new StdioServerTransport();
4874
4911
  await server.connect(transport);
4875
4912
 
4876
- const servers = loadServerConfig();
4913
+ const servers = await loadServerConfig();
4877
4914
  const serverList = Object.keys(servers);
4878
4915
  const activeProfile = getActiveProfileName();
4879
4916
 
@@ -4883,10 +4920,13 @@ async function main() {
4883
4920
  console.error('💡 Use server-manager.py to configure servers');
4884
4921
  console.error('🔄 Connection management: Auto-reconnect enabled, 30min timeout');
4885
4922
 
4886
- // Set up periodic cleanup of old connections (every 10 minutes)
4887
- setInterval(() => {
4923
+ // Set up periodic cleanup of old connections (every 10 minutes).
4924
+ // unref() so this timer alone never keeps the process alive after the
4925
+ // stdio transport has closed.
4926
+ const cleanupTimer = setInterval(() => {
4888
4927
  cleanupOldConnections();
4889
4928
  }, 10 * 60 * 1000);
4929
+ if (typeof cleanupTimer.unref === 'function') cleanupTimer.unref();
4890
4930
  }
4891
4931
 
4892
4932
  main().catch(console.error);
@@ -0,0 +1,75 @@
1
+ import fs from 'fs';
2
+ import { ConfigLoader } from './config-loader.js';
3
+ import { logger } from './logger.js';
4
+
5
+ export class ServerConfigManager {
6
+ constructor({ envPath, tomlPath, preferToml = false, configLoader = new ConfigLoader() }) {
7
+ this.envPath = envPath;
8
+ this.tomlPath = tomlPath;
9
+ this.preferToml = preferToml;
10
+ this.configLoader = configLoader;
11
+ this.servers = {};
12
+ this.fileSignature = null;
13
+ }
14
+
15
+ async loadInitial() {
16
+ await this.reload();
17
+ return this.servers;
18
+ }
19
+
20
+ async getServers() {
21
+ if (this.hasFileBackedConfigChanged()) {
22
+ await this.reload();
23
+ }
24
+
25
+ return this.servers;
26
+ }
27
+
28
+ hasFileBackedConfigChanged() {
29
+ const currentSignature = this.getFileSignature();
30
+ return this.fileSignature !== currentSignature;
31
+ }
32
+
33
+ async reload() {
34
+ const previousServers = this.servers;
35
+ const previousSignature = this.fileSignature;
36
+
37
+ try {
38
+ const loadedServers = await this.configLoader.load({
39
+ envPath: this.envPath,
40
+ tomlPath: this.tomlPath,
41
+ preferToml: this.preferToml
42
+ });
43
+
44
+ const nextServers = {};
45
+ for (const [name, config] of loadedServers) {
46
+ nextServers[name] = config;
47
+ }
48
+
49
+ this.servers = nextServers;
50
+ this.fileSignature = this.getFileSignature();
51
+ return this.servers;
52
+ } catch (error) {
53
+ this.servers = previousServers;
54
+ this.fileSignature = previousSignature;
55
+ logger.error('Failed to reload server configuration', { error: error.message });
56
+ return this.servers;
57
+ }
58
+ }
59
+
60
+ getFileSignature() {
61
+ return [
62
+ this.getSingleFileSignature(this.tomlPath),
63
+ this.getSingleFileSignature(this.envPath)
64
+ ].join('|');
65
+ }
66
+
67
+ getSingleFileSignature(filePath) {
68
+ if (!filePath || !fs.existsSync(filePath)) {
69
+ return `${filePath || ''}:missing`;
70
+ }
71
+
72
+ const stats = fs.statSync(filePath);
73
+ return `${filePath}:${stats.mtimeMs}:${stats.size}`;
74
+ }
75
+ }
@@ -393,13 +393,16 @@ export function cleanupSessions(maxAge = 30 * 60 * 1000) { // 30 minutes default
393
393
  return cleanedCount;
394
394
  }
395
395
 
396
- // Periodic cleanup of inactive sessions
397
- setInterval(() => {
396
+ // Periodic cleanup of inactive sessions.
397
+ // unref() so this interval never keeps the process alive on its own (a stdio MCP
398
+ // server must exit when its transport closes, not be pinned by a background timer).
399
+ const sessionCleanup = setInterval(() => {
398
400
  const cleaned = cleanupSessions();
399
401
  if (cleaned > 0) {
400
402
  logger.info(`Cleaned up ${cleaned} inactive sessions`);
401
403
  }
402
404
  }, 5 * 60 * 1000); // Every 5 minutes
405
+ if (typeof sessionCleanup.unref === 'function') sessionCleanup.unref();
403
406
 
404
407
  export default {
405
408
  createSession,
@@ -562,8 +562,12 @@ export function monitorTunnels() {
562
562
  }
563
563
  }
564
564
 
565
- // Monitor tunnels periodically
566
- setInterval(monitorTunnels, 30 * 1000); // Every 30 seconds
565
+ // Monitor tunnels periodically.
566
+ // unref() so this interval never keeps the process alive on its own: as part of
567
+ // a stdio MCP server we must exit when the transport closes, not stay pinned by
568
+ // a background timer.
569
+ const tunnelMonitor = setInterval(monitorTunnels, 30 * 1000); // Every 30 seconds
570
+ if (typeof tunnelMonitor.unref === 'function') tunnelMonitor.unref();
567
571
 
568
572
  export default {
569
573
  createTunnel,
@@ -1,143 +0,0 @@
1
- # Troubleshooting Guide
2
-
3
- ## Claude Code Crashes / Interruptions
4
-
5
- ### Symptoms
6
- - Claude Code shows "Interrupted: What should Claude do instead?"
7
- - MCP tool responses cause Claude to stop working
8
- - Commands execute successfully but Claude crashes
9
-
10
- ### Root Causes
11
-
12
- 1. **Large Output Responses**
13
- - Long stdout/stderr outputs overwhelm Claude's context window
14
- - JSON responses with thousands of characters
15
- - Solution: Output is now automatically truncated to prevent crashes
16
-
17
- 2. **Timeout Issues**
18
- - Default 30s timeout too short for some operations
19
- - Commands killed prematurely
20
- - Solution: Default timeout increased to 2 minutes, max 5 minutes
21
-
22
- 3. **Unstructured Error Responses**
23
- - Inconsistent error formatting
24
- - Solution: Standardized JSON error responses
25
-
26
- ### Configuration
27
-
28
- You can customize limits via environment variables in your `.env` file:
29
-
30
- ```bash
31
- # Maximum output length (default: 10000 characters)
32
- MCP_SSH_MAX_OUTPUT_LENGTH=10000
33
-
34
- # Default command timeout (default: 120000ms = 2 minutes)
35
- MCP_SSH_DEFAULT_TIMEOUT=120000
36
-
37
- # Maximum command timeout (default: 300000ms = 5 minutes)
38
- MCP_SSH_MAX_TIMEOUT=300000
39
-
40
- # Use compact JSON responses (no formatting, saves tokens)
41
- MCP_SSH_COMPACT_JSON=true
42
-
43
- # Enable debug information in responses
44
- MCP_SSH_DEBUG=true
45
- ```
46
-
47
- ### Best Practices
48
-
49
- 1. **For Long-Running Commands**
50
- - Specify a custom timeout when calling `ssh_execute`:
51
- ```json
52
- {
53
- "server": "myserver",
54
- "command": "long-running-task",
55
- "timeout": 300000
56
- }
57
- ```
58
-
59
- 2. **For Commands with Large Output**
60
- - Redirect output to a file on the server
61
- - Use grep/awk to filter output before returning
62
- - Example:
63
- ```bash
64
- # Instead of: cat huge-log.txt
65
- # Use: tail -n 100 huge-log.txt
66
- # Or: grep ERROR huge-log.txt | tail -n 50
67
- ```
68
-
69
- 3. **Monitor Resource Usage**
70
- - Use `ssh_monitor` tool for system metrics
71
- - Check disk space before operations
72
- - Monitor process memory usage
73
-
74
- ### Debugging Steps
75
-
76
- 1. **Check MCP Server Logs**
77
- ```bash
78
- # Server logs to stderr
79
- # Check Claude Code console for detailed errors
80
- ```
81
-
82
- 2. **Test Connection**
83
- ```bash
84
- ssh-manager server test <server-name>
85
- ```
86
-
87
- 3. **Verify Configuration**
88
- ```bash
89
- ssh-manager server show <server-name>
90
- ```
91
-
92
- 4. **Test Direct SSH**
93
- ```bash
94
- ssh user@host "command"
95
- ```
96
-
97
- ### Known Issues
98
-
99
- 1. **Commands with Interactive Prompts**
100
- - SSH sessions don't support interactive input
101
- - Solution: Use non-interactive flags or pre-configure
102
-
103
- 2. **Supervisor Not Running**
104
- - Some deployments expect supervisor
105
- - Check: `supervisorctl status`
106
- - Solution: Start supervisor or use alternative process manager
107
-
108
- 3. **Permission Denied**
109
- - SSH user lacks permissions
110
- - Solution: Configure sudo password in server config or use `ssh_execute_sudo`
111
-
112
- ### Recovery Steps
113
-
114
- If Claude Code crashes:
115
-
116
- 1. Restart Claude Code
117
- 2. Check last command in logs
118
- 3. Re-run with lower timeout or filtered output
119
- 4. Report issue with error message
120
-
121
- ### Performance Optimization
122
-
123
- 1. **Reduce Token Usage**
124
- - Set `MCP_SSH_COMPACT_JSON=true`
125
- - Limit output with grep/head/tail
126
- - Use specific queries instead of broad commands
127
-
128
- 2. **Connection Pooling**
129
- - Server maintains persistent connections
130
- - Connections auto-close after 30 minutes idle
131
- - Manual disconnect: use `ssh_connection_manage` tool
132
-
133
- 3. **Batch Operations**
134
- - Use `ssh_group_execute` for multiple servers
135
- - Combine commands with `&&` or `;`
136
- - Example: `cd /app && git pull && npm install`
137
-
138
- ### Getting Help
139
-
140
- 1. Check logs: `~/.config/claude-code/logs/`
141
- 2. Test manually: `node src/index.js` (requires stdin)
142
- 3. Open issue: https://github.com/yourusername/mcp-ssh-manager/issues
143
- 4. Include: error message, command executed, server type