mcp-ssh-manager 3.6.2 → 3.6.4

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,32 @@ 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.4] - 2026-06-18
9
+
10
+ ### Changed
11
+
12
+ - **Internal dead-code cleanup — no behavioral change.** Removed 27 unused exports and 2 duplicate exports across the codebase (−343 lines): fully-unused helper functions deleted, internally-used symbols un-exported, and redundant `export default`s removed. The public surface (the MCP server + CLI) is unchanged — command builders and parsers are byte-identical before/after (verified by a differential test of `main` vs the change), and all 37 tools were exercised end-to-end against a live SSH server (Ubuntu + MariaDB) with no regression.
13
+
14
+ ### Tooling
15
+
16
+ - **Dead-code quality gate.** Added a calibrated `knip.json` and a **blocking** `knip` step to the `quality` CI workflow, so unused exports/files/dependencies now fail the build and can't creep back in. `eslint src/` is clean (0 errors, 0 warnings).
17
+
18
+ ## [3.6.3] - 2026-06-18
19
+
20
+ ### Fixed
21
+
22
+ - **`ssh_sync` falsely reported "No files needed to be transferred" even when files were synced** ([#42](https://github.com/bvisible/mcp-ssh-manager/pull/42) — thanks [@MakksSh](https://github.com/MakksSh))
23
+ - Two bugs in the rsync `--stats` scraper kept `filesTransferred` at `0`: `--stats` was only passed when `verbose` was enabled (so rsync produced no statistics lines at all), and the count regex only matched rsync 2.x wording (`Number of files transferred`) while rsync 3.x — standard on modern distros — emits `Number of regular files transferred`. Agents would mistrust the result, run redundant checks, or retry the sync.
24
+ - `--stats` is now always passed, and the count regex matches both rsync 2.x and 3.x.
25
+ - **`totalSize` stayed `0` on macOS, and locale-formatted numbers were mis-parsed** (follow-up hardening)
26
+ - openrsync (the default `/usr/bin/rsync` on recent macOS) suffixes byte counts with `B`, not `bytes`, so the size regex never matched. Both suffixes are now accepted — openrsync keeps raw byte counts even for large files (verified at 5 MB), so no `K/M/G` handling is needed.
27
+ - Numbers grouped with locale-specific separators (`,` or `.` for thousands, the opposite char for the decimal) are now parsed correctly for the file count, transferred size, and speed, instead of only stripping commas.
28
+ - The `--stats` parsing was extracted into `src/rsync-stats.js` so it is unit-testable without booting the MCP server.
29
+
30
+ ### Tests
31
+
32
+ - **New `tests/test-sync-stats.js`** (wired into `npm test` as `test:sync`) — 46 assertions covering openrsync output captured from a live macOS run, GNU rsync 3.x/2.x, US/EU locale number formats, the zero-files case, and a missing `--stats` block.
33
+
8
34
  ## [3.6.2] - 2026-06-09
9
35
 
10
36
  ### Changed
package/README.md CHANGED
@@ -6,7 +6,7 @@ A Model Context Protocol (MCP) server that enables **Claude Code** and **OpenAI
6
6
 
7
7
  [![npm version](https://img.shields.io/npm/v/mcp-ssh-manager.svg?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/mcp-ssh-manager)
8
8
  [![npm downloads](https://img.shields.io/npm/dt/mcp-ssh-manager.svg?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/mcp-ssh-manager)
9
- [![Version](https://img.shields.io/badge/Version-3.5.1-brightgreen?style=for-the-badge)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.5.1)
9
+ [![Version](https://img.shields.io/badge/Version-3.6.4-brightgreen?style=for-the-badge)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.6.4)
10
10
  [![Claude Code](https://img.shields.io/badge/Claude_Code-Compatible-5A67D8?style=for-the-badge&logo=anthropic)](https://claude.ai/code)
11
11
  [![OpenAI Codex](https://img.shields.io/badge/OpenAI_Codex-Compatible-00A67E?style=for-the-badge&logo=openai)](https://openai.com/codex)
12
12
  [![MCP](https://img.shields.io/badge/MCP-Server-orange?style=for-the-badge)](https://modelcontextprotocol.io)
@@ -20,20 +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.6.2
23
+ ## 🎉 What's New in v3.6.4
24
24
 
25
- **Richer tool descriptions — better AI tool-calling** (Released: June 9, 2026)
25
+ **Internal cleanup + a dead-code quality gate** (Released: June 18, 2026)
26
26
 
27
- - **📝 All 37 tool descriptions rewritten** — every MCP tool now states its real behavior: side effects, destructive vs read-only nature, idempotency, sudo/auth needs, security-mode gating, and parameter semantics (mutually-exclusive params, defaults, edge cases). Average description length went from ~6 words to ~70, with no weak outliers.
28
- - Agents now know the consequences **before** calling a tool — e.g. `ssh_db_import` and `ssh_backup_restore` are destructive, `ssh_db_query` is SELECT-only, and `ssh_upload`/`ssh_deploy` are blocked on `readonly` servers.
29
- - **No behavioral change** — only `description` strings changed; logic, parameters, and tool names are identical. All tests pass unmodified.
27
+ - **🧹 Dead-code removal (−343 lines), zero behavioral change** — removed 27 unused exports and 2 duplicate exports. The MCP server and CLI behave identically: command builders/parsers are byte-identical before/after, and all 37 tools were verified end-to-end against a live SSH server.
28
+ - **🛡️ Dead-code CI gate** — a calibrated `knip.json` plus a **blocking** `knip` step in CI keep unused code and dependencies from creeping back. `eslint src/` is now clean (0 errors, 0 warnings).
30
29
 
31
- [Read full changelog →](CHANGELOG.md#362---2026-06-09)
30
+ [Read full changelog →](CHANGELOG.md#364---2026-06-18)
32
31
 
33
32
  ---
34
33
 
35
34
  ## Previous Releases
36
35
 
36
+ ### v3.6.3 - `ssh_sync` reports the real transfer count (June 18, 2026)
37
+
38
+ - **📊 No more false "No files needed to be transferred"** ([#42](https://github.com/bvisible/mcp-ssh-manager/pull/42) — thanks [@MakksSh](https://github.com/MakksSh)) — fixed rsync `--stats` parsing: `--stats` is always passed now, and rsync 2.x/3.x wording, openrsync's `B` suffix, and locale separators are all handled. [Full changelog →](CHANGELOG.md#363---2026-06-18)
39
+
40
+ ### v3.6.2 - Richer tool descriptions (June 9, 2026)
41
+
42
+ - **📝 All 37 tool descriptions rewritten** — every MCP tool now documents its real behavior (side effects, destructive vs read-only nature, idempotency, sudo/auth requirements, security-mode gating, parameter semantics) instead of a 4-to-10-word summary. Agents now know the consequences before invoking a tool; no behavioral change — only `description` strings changed. [Full changelog →](CHANGELOG.md#362---2026-06-09)
43
+
37
44
  ### v3.6.1 - Teardown hygiene follow-up (June 9, 2026)
38
45
 
39
46
  - **🔌 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` and `session-manager.js` registered module-level `setInterval`s that were never `unref()`'d, so importing either module kept Node's event loop alive. Both are now `unref()`'d. [Full changelog →](CHANGELOG.md#361---2026-06-09)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-ssh-manager",
3
- "version": "3.6.2",
3
+ "version": "3.6.4",
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,7 +13,7 @@
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 && npm run test:config && npm run test:lifecycle",
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 && npm run test:sync",
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",
@@ -22,6 +22,7 @@
22
22
  "test:ping": "node tests/test-ssh-ping.js",
23
23
  "test:config": "node tests/test-server-config-manager.js",
24
24
  "test:lifecycle": "node tests/test-lifecycle.js",
25
+ "test:sync": "node tests/test-sync-stats.js",
25
26
  "test:all": "npm test && ./scripts/validate.sh",
26
27
  "validate": "./scripts/validate.sh",
27
28
  "lint": "eslint src/*.js",
@@ -86,6 +87,7 @@
86
87
  },
87
88
  "devDependencies": {
88
89
  "eslint": "^8.56.0",
90
+ "knip": "^5.0.0",
89
91
  "prettier": "^3.2.4"
90
92
  },
91
93
  "engines": {
@@ -296,7 +296,6 @@ function buildPostgreSQLRestoreCommand(backupFile, options) {
296
296
  */
297
297
  function buildMongoDBRestoreCommand(backupFile, options) {
298
298
  const {
299
- database,
300
299
  user,
301
300
  password,
302
301
  host = 'localhost',
@@ -439,31 +438,3 @@ export function buildCronScheduleCommand(schedule, backupCommand, cronComment) {
439
438
  const cronLine = `${schedule} ${backupCommand} # ${cronComment}`;
440
439
  return `(crontab -l 2>/dev/null; echo '${cronLine}') | crontab -`;
441
440
  }
442
-
443
- /**
444
- * Parse cron list output
445
- */
446
- export function parseCronJobs(output) {
447
- if (!output || !output.trim()) {
448
- return [];
449
- }
450
-
451
- const jobs = [];
452
- const lines = output.split('\n');
453
-
454
- for (const line of lines) {
455
- if (line.trim() && !line.startsWith('#') && line.includes('ssh-manager-backup')) {
456
- const parts = line.split('#');
457
- const schedule = parts[0].trim();
458
- const comment = parts[1] ? parts[1].trim() : '';
459
-
460
- jobs.push({
461
- schedule,
462
- comment,
463
- command: schedule.split(/\s+/).slice(5).join(' ')
464
- });
465
- }
466
- }
467
-
468
- return jobs;
469
- }
@@ -46,7 +46,7 @@ export function loadCommandAliases() {
46
46
  /**
47
47
  * Save command aliases to file
48
48
  */
49
- export function saveCommandAliases(aliases) {
49
+ function saveCommandAliases(aliases) {
50
50
  try {
51
51
  // Only save custom aliases (not from profile)
52
52
  const customAliases = {};
@@ -381,6 +381,3 @@ export class ConfigLoader {
381
381
  return this.servers.size;
382
382
  }
383
383
  }
384
-
385
- // Export singleton instance
386
- export const configLoader = new ConfigLoader();
package/src/config.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Configuration constants for MCP SSH Manager
2
2
 
3
3
  // Output limits to prevent Claude Code crashes
4
- export const OUTPUT_LIMITS = {
4
+ const OUTPUT_LIMITS = {
5
5
  // Maximum length of stdout/stderr in responses (characters)
6
6
  MAX_OUTPUT_LENGTH: process.env.MCP_SSH_MAX_OUTPUT_LENGTH
7
7
  ? parseInt(process.env.MCP_SSH_MAX_OUTPUT_LENGTH)
@@ -42,7 +42,7 @@ export const TIMEOUTS = {
42
42
  };
43
43
 
44
44
  // Response formatting
45
- export const RESPONSE_FORMAT = {
45
+ const RESPONSE_FORMAT = {
46
46
  // Whether to use compact JSON (no formatting)
47
47
  COMPACT_JSON: process.env.MCP_SSH_COMPACT_JSON === 'true',
48
48
 
@@ -10,13 +10,6 @@ export const DB_TYPES = {
10
10
  MONGODB: 'mongodb'
11
11
  };
12
12
 
13
- // Default ports
14
- export const DB_PORTS = {
15
- mysql: 3306,
16
- postgresql: 5432,
17
- mongodb: 27017
18
- };
19
-
20
13
  /**
21
14
  * Build MySQL dump command
22
15
  */
@@ -206,7 +199,6 @@ export function buildPostgreSQLImportCommand(options) {
206
199
  */
207
200
  export function buildMongoDBRestoreCommand(options) {
208
201
  const {
209
- database,
210
202
  user,
211
203
  password,
212
204
  host = 'localhost',
@@ -470,53 +462,6 @@ export function parseTableList(output) {
470
462
  return output.trim().split('\n').filter(l => l.trim());
471
463
  }
472
464
 
473
- /**
474
- * Estimate dump size command
475
- */
476
- export function buildEstimateSizeCommand(type, database, options = {}) {
477
- const { user, password, host = 'localhost', port } = options;
478
-
479
- switch (type) {
480
- case DB_TYPES.MYSQL: {
481
- let command = 'mysql';
482
- if (user) command += ` -u${user}`;
483
- if (password) command += ` -p'${password}'`;
484
- if (host) command += ` -h ${host}`;
485
- if (port) command += ` -P ${port}`;
486
- command += ` -e "SELECT SUM(data_length + index_length) FROM information_schema.TABLES WHERE table_schema='${database}';" | tail -n 1`;
487
- return command;
488
- }
489
-
490
- case DB_TYPES.POSTGRESQL: {
491
- let command = '';
492
- if (password) {
493
- command = `PGPASSWORD='${password}' `;
494
- }
495
- command += 'psql';
496
- if (user) command += ` -U ${user}`;
497
- if (host) command += ` -h ${host}`;
498
- if (port) command += ` -p ${port}`;
499
- command += ` -d ${database}`;
500
- command += ` -t -c "SELECT pg_database_size('${database}');" | sed 's/^[ \\t]*//'`;
501
- return command;
502
- }
503
-
504
- case DB_TYPES.MONGODB: {
505
- let command = 'mongo';
506
- if (host) command += ` --host ${host}`;
507
- if (port) command += ` --port ${port}`;
508
- if (user) command += ` --username ${user}`;
509
- if (password) command += ` --password '${password}'`;
510
- command += ` ${database}`;
511
- command += ' --quiet --eval "db.stats().dataSize"';
512
- return command;
513
- }
514
-
515
- default:
516
- throw new Error(`Unknown database type: ${type}`);
517
- }
518
- }
519
-
520
465
  /**
521
466
  * Parse size output to bytes
522
467
  */
@@ -535,19 +480,3 @@ export function formatBytes(bytes) {
535
480
  const i = Math.floor(Math.log(bytes) / Math.log(k));
536
481
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
537
482
  }
538
-
539
- /**
540
- * Get database connection info
541
- */
542
- export function getConnectionInfo(type, options) {
543
- const { host = 'localhost', port, user, database } = options;
544
- const defaultPort = DB_PORTS[type];
545
-
546
- return {
547
- type,
548
- host,
549
- port: port || defaultPort,
550
- user: user || 'default',
551
- database: database || 'all'
552
- };
553
- }
@@ -144,32 +144,3 @@ export function detectDeploymentNeeds(remotePath) {
144
144
 
145
145
  return needs;
146
146
  }
147
-
148
- /**
149
- * Create batch deployment script for multiple files
150
- */
151
- export function createBatchDeployScript(deployments) {
152
- const script = ['#!/bin/bash', 'set -e', ''];
153
-
154
- script.push('# Batch deployment script');
155
- script.push(`# Generated at ${new Date().toISOString()}`);
156
- script.push('');
157
-
158
- deployments.forEach((deploy, index) => {
159
- script.push(`# File ${index + 1}: ${deploy.localPath} -> ${deploy.remotePath}`);
160
- deploy.strategy.steps.forEach(step => {
161
- if (step.type !== 'cleanup') {
162
- script.push(step.command.replace('{{tempFile}}', deploy.tempFile));
163
- }
164
- });
165
- script.push('');
166
- });
167
-
168
- // Cleanup all temp files at the end
169
- script.push('# Cleanup temporary files');
170
- deployments.forEach(deploy => {
171
- script.push(`rm -f ${deploy.tempFile}`);
172
- });
173
-
174
- return script.join('\n');
175
- }
@@ -14,7 +14,7 @@ export const HEALTH_STATUS = {
14
14
  };
15
15
 
16
16
  // Common services to monitor
17
- export const COMMON_SERVICES = {
17
+ const COMMON_SERVICES = {
18
18
  nginx: { systemd: 'nginx', sysv: 'nginx' },
19
19
  apache: { systemd: 'apache2', sysv: 'apache2' },
20
20
  mysql: { systemd: 'mysql', sysv: 'mysql' },
@@ -28,7 +28,7 @@ export const COMMON_SERVICES = {
28
28
  /**
29
29
  * Build command to check CPU usage
30
30
  */
31
- export function buildCPUCheckCommand() {
31
+ function buildCPUCheckCommand() {
32
32
  // Get CPU usage using top, show idle percentage, calculate used
33
33
  return 'top -bn1 | grep "Cpu(s)" | sed "s/.*, *\\([0-9.]*\\)%* id.*/\\1/" | awk \'{print 100 - $1}\'';
34
34
  }
@@ -36,7 +36,7 @@ export function buildCPUCheckCommand() {
36
36
  /**
37
37
  * Build command to check memory usage
38
38
  */
39
- export function buildMemoryCheckCommand() {
39
+ function buildMemoryCheckCommand() {
40
40
  // Returns: total, used, free, available in MB and percentage
41
41
  return 'free -m | awk \'NR==2{printf "{\\"total\\":%s,\\"used\\":%s,\\"free\\":%s,\\"percent\\":%.2f}", $2,$3,$4,$3*100/$2}\'';
42
42
  }
@@ -44,7 +44,7 @@ export function buildMemoryCheckCommand() {
44
44
  /**
45
45
  * Build command to check disk usage
46
46
  */
47
- export function buildDiskCheckCommand(mountPoint = '/') {
47
+ function buildDiskCheckCommand(mountPoint = '/') {
48
48
  // Returns JSON with disk usage for specific mount point or all
49
49
  if (mountPoint === 'all') {
50
50
  return 'df -h | awk \'NR>1 {gsub(/%/,"",$5); printf "{\\"mount\\":\\"%s\\",\\"size\\":\\"%s\\",\\"used\\":\\"%s\\",\\"avail\\":\\"%s\\",\\"percent\\":%s}\\n", $6,$2,$3,$4,$5}\'';
@@ -55,7 +55,7 @@ export function buildDiskCheckCommand(mountPoint = '/') {
55
55
  /**
56
56
  * Build command to check network statistics
57
57
  */
58
- export function buildNetworkCheckCommand() {
58
+ function buildNetworkCheckCommand() {
59
59
  // Get basic network stats (RX/TX bytes)
60
60
  return 'cat /proc/net/dev | awk \'NR>2 {printf "{\\"interface\\":\\"%s\\",\\"rx_bytes\\":%s,\\"tx_bytes\\":%s}\\n", $1,$2,$10}\' | grep -v "lo:"';
61
61
  }
@@ -63,21 +63,21 @@ export function buildNetworkCheckCommand() {
63
63
  /**
64
64
  * Build command to check load average
65
65
  */
66
- export function buildLoadAverageCommand() {
66
+ function buildLoadAverageCommand() {
67
67
  return 'uptime | awk -F\'load average:\' \'{print $2}\' | sed \'s/^[ \\t]*//\'';
68
68
  }
69
69
 
70
70
  /**
71
71
  * Build command to check system uptime
72
72
  */
73
- export function buildUptimeCommand() {
73
+ function buildUptimeCommand() {
74
74
  return 'uptime -p 2>/dev/null || uptime | awk \'{print $3,$4}\' | sed \'s/,//\'';
75
75
  }
76
76
 
77
77
  /**
78
78
  * Parse CPU usage output
79
79
  */
80
- export function parseCPUUsage(output) {
80
+ function parseCPUUsage(output) {
81
81
  const usage = parseFloat(output.trim());
82
82
  return {
83
83
  usage: usage.toFixed(2),
@@ -89,7 +89,7 @@ export function parseCPUUsage(output) {
89
89
  /**
90
90
  * Parse memory usage output
91
91
  */
92
- export function parseMemoryUsage(output) {
92
+ function parseMemoryUsage(output) {
93
93
  try {
94
94
  const mem = JSON.parse(output.trim());
95
95
  return {
@@ -108,7 +108,7 @@ export function parseMemoryUsage(output) {
108
108
  /**
109
109
  * Parse disk usage output
110
110
  */
111
- export function parseDiskUsage(output) {
111
+ function parseDiskUsage(output) {
112
112
  const lines = output.trim().split('\n').filter(l => l);
113
113
  const disks = [];
114
114
 
@@ -128,7 +128,7 @@ export function parseDiskUsage(output) {
128
128
  /**
129
129
  * Parse network statistics
130
130
  */
131
- export function parseNetworkStats(output) {
131
+ function parseNetworkStats(output) {
132
132
  const lines = output.trim().split('\n').filter(l => l);
133
133
  const interfaces = [];
134
134
 
@@ -150,7 +150,7 @@ export function parseNetworkStats(output) {
150
150
  /**
151
151
  * Determine overall health status
152
152
  */
153
- export function determineOverallHealth(cpu, memory, disks) {
153
+ function determineOverallHealth(cpu, memory, disks) {
154
154
  const statuses = [cpu.status, memory.status, ...disks.map(d => d.status)];
155
155
 
156
156
  if (statuses.includes(HEALTH_STATUS.CRITICAL)) {
@@ -412,13 +412,6 @@ export function parseComprehensiveHealthCheck(output) {
412
412
  return result;
413
413
  }
414
414
 
415
- /**
416
- * Get common service names for detection
417
- */
418
- export function getCommonServices() {
419
- return Object.keys(COMMON_SERVICES);
420
- }
421
-
422
415
  /**
423
416
  * Resolve service name (handle both systemd and sysv names)
424
417
  */
@@ -123,7 +123,7 @@ export function loadHooksConfig() {
123
123
  /**
124
124
  * Save hooks configuration
125
125
  */
126
- export function saveHooksConfig(config) {
126
+ function saveHooksConfig(config) {
127
127
  try {
128
128
  fs.writeFileSync(HOOKS_CONFIG_FILE, JSON.stringify(config, null, 2));
129
129
  return true;
@@ -310,18 +310,3 @@ export function listHooks() {
310
310
  actionCount: hook.actions ? hook.actions.length : 0
311
311
  }));
312
312
  }
313
-
314
- /**
315
- * Create a custom hook script
316
- */
317
- export async function createHookScript(scriptName, scriptContent) {
318
- const scriptPath = path.join(HOOKS_DIR, scriptName);
319
-
320
- try {
321
- fs.writeFileSync(scriptPath, scriptContent);
322
- fs.chmodSync(scriptPath, '755');
323
- return scriptPath;
324
- } catch (error) {
325
- throw new Error(`Failed to create hook script: ${error.message}`);
326
- }
327
- }
package/src/index.js CHANGED
@@ -29,7 +29,6 @@ import {
29
29
  suggestAliases
30
30
  } from './command-aliases.js';
31
31
  import {
32
- OUTPUT_LIMITS,
33
32
  TIMEOUTS,
34
33
  truncateOutput,
35
34
  formatJSONResponse
@@ -47,31 +46,27 @@ import {
47
46
  getActiveProfileName
48
47
  } from './profile-loader.js';
49
48
  import { logger } from './logger.js';
49
+ import { parseRsyncStats } from './rsync-stats.js';
50
50
  import {
51
51
  createSession,
52
52
  getSession,
53
53
  listSessions,
54
- closeSession,
55
- SESSION_STATES
54
+ closeSession
56
55
  } from './session-manager.js';
57
56
  import {
58
- getGroup,
59
57
  createGroup,
60
58
  updateGroup,
61
59
  deleteGroup,
62
60
  addServersToGroup,
63
61
  removeServersFromGroup,
64
62
  listGroups,
65
- executeOnGroup,
66
- EXECUTION_STRATEGIES
63
+ executeOnGroup
67
64
  } from './server-groups.js';
68
65
  import {
69
66
  createTunnel,
70
- getTunnel,
71
67
  listTunnels,
72
68
  closeTunnel,
73
- closeServerTunnels,
74
- TUNNEL_TYPES
69
+ closeServerTunnels
75
70
  } from './tunnel-manager.js';
76
71
  import {
77
72
  getHostKeyFingerprint,
@@ -101,23 +96,10 @@ import {
101
96
  buildListBackupsCommand,
102
97
  parseBackupsList,
103
98
  buildCleanupCommand,
104
- buildCronScheduleCommand,
105
- parseCronJobs
99
+ buildCronScheduleCommand
106
100
  } from './backup-manager.js';
107
101
  import {
108
102
  HEALTH_STATUS,
109
- COMMON_SERVICES,
110
- buildCPUCheckCommand,
111
- buildMemoryCheckCommand,
112
- buildDiskCheckCommand,
113
- buildNetworkCheckCommand,
114
- buildLoadAverageCommand,
115
- buildUptimeCommand,
116
- parseCPUUsage,
117
- parseMemoryUsage,
118
- parseDiskUsage,
119
- parseNetworkStats,
120
- determineOverallHealth,
121
103
  buildServiceStatusCommand,
122
104
  parseServiceStatus,
123
105
  buildProcessListCommand,
@@ -130,12 +112,10 @@ import {
130
112
  checkAlertThresholds,
131
113
  buildComprehensiveHealthCheckCommand,
132
114
  parseComprehensiveHealthCheck,
133
- getCommonServices,
134
115
  resolveServiceName
135
116
  } from './health-monitor.js';
136
117
  import {
137
118
  DB_TYPES,
138
- DB_PORTS,
139
119
  buildMySQLDumpCommand as buildDBMySQLDumpCommand,
140
120
  buildPostgreSQLDumpCommand as buildDBPostgreSQLDumpCommand,
141
121
  buildMongoDBDumpCommand as buildDBMongoDBDumpCommand,
@@ -154,10 +134,8 @@ import {
154
134
  isSafeQuery,
155
135
  parseDatabaseList,
156
136
  parseTableList,
157
- buildEstimateSizeCommand,
158
137
  parseSize,
159
- formatBytes,
160
- getConnectionInfo
138
+ formatBytes
161
139
  } from './database-manager.js';
162
140
  import { loadToolConfig, isToolEnabled } from './tool-config-manager.js';
163
141
  import { evaluatePolicy } from './policy.js';
@@ -328,7 +306,7 @@ async function execCommandWithTimeout(ssh, command, options = {}, timeoutMs = 30
328
306
  // pipes, etc. Base64 sidesteps all escape issues entirely.
329
307
  if (platform === 'windows' && !rawCommand) {
330
308
  // Suppress progress (avoids CLIXML sentinels in stderr) + force UTF-8 stdout
331
- const prelude = `$ProgressPreference='SilentlyContinue'; [Console]::OutputEncoding=[System.Text.Encoding]::UTF8;`;
309
+ const prelude = '$ProgressPreference=\'SilentlyContinue\'; [Console]::OutputEncoding=[System.Text.Encoding]::UTF8;';
332
310
  const fullPSCommand = `${prelude} ${command}`;
333
311
  const utf16le = Buffer.from(fullPSCommand, 'utf16le');
334
312
  const b64 = utf16le.toString('base64');
@@ -703,7 +681,7 @@ registerToolConditional(
703
681
  let fullCommand;
704
682
  if (workingDir) {
705
683
  if (platform === 'windows') {
706
- const escapedDir = workingDir.replace(/'/g, "''");
684
+ const escapedDir = workingDir.replace(/'/g, '\'\'');
707
685
  fullCommand = `Set-Location '${escapedDir}'; ${expandedCommand}`;
708
686
  } else {
709
687
  fullCommand = `cd ${workingDir} && ${expandedCommand}`;
@@ -914,7 +892,7 @@ registerToolConditional(
914
892
  if (denied) return denied;
915
893
 
916
894
  try {
917
- const ssh = await getConnection(serverName);
895
+ await getConnection(serverName);
918
896
  const servers = await loadServerConfig();
919
897
  const serverConfig = servers[serverName.toLowerCase()];
920
898
 
@@ -973,10 +951,8 @@ registerToolConditional(
973
951
  rsyncOptions.push('--dry-run');
974
952
  }
975
953
 
976
- if (verbose || logger.verbose) {
977
- // Only add stats, not progress to avoid blocking with too much output
978
- rsyncOptions.push('--stats');
979
- }
954
+ // Always include --stats so we can parse transfer counts
955
+ rsyncOptions.push('--stats');
980
956
 
981
957
  // Add exclude patterns
982
958
  exclude.forEach(pattern => {
@@ -1153,21 +1129,9 @@ registerToolConditional(
1153
1129
  return;
1154
1130
  }
1155
1131
 
1156
- // Parse rsync output for statistics
1157
- let stats = {
1158
- filesTransferred: 0,
1159
- totalSize: 0,
1160
- totalTime: duration
1161
- };
1162
-
1163
- // Extract statistics from rsync output
1164
- const filesMatch = output.match(/Number of files transferred: (\d+)/);
1165
- const sizeMatch = output.match(/Total transferred file size: ([\d,]+) bytes/);
1166
- const speedMatch = output.match(/([\d.]+) bytes\/sec/);
1167
-
1168
- if (filesMatch) stats.filesTransferred = parseInt(filesMatch[1]);
1169
- if (sizeMatch) stats.totalSize = parseInt(sizeMatch[1].replace(/,/g, ''));
1170
- if (speedMatch) stats.speed = parseFloat(speedMatch[1]);
1132
+ // Parse rsync output for statistics. Handles rsync 2.x/3.x wording,
1133
+ // GNU "bytes" vs openrsync "B" suffixes, and locale separators.
1134
+ const stats = parseRsyncStats(output, duration);
1171
1135
 
1172
1136
  logger.info(`Rsync ${direction} completed`, {
1173
1137
  server: serverName,
@@ -1279,7 +1243,7 @@ registerToolConditional(
1279
1243
  const sessionId = `tail_${Date.now()}`;
1280
1244
 
1281
1245
  // Store the SSH stream for later cleanup
1282
- const stream = await ssh.execCommandStream(command, {
1246
+ await ssh.execCommandStream(command, {
1283
1247
  onStdout: (chunk) => {
1284
1248
  // In a real implementation, this would stream to the client
1285
1249
  console.error(`[${serverName}:${file}] ${chunk}`);
@@ -1934,7 +1898,7 @@ registerToolConditional(
1934
1898
  if (workingDir) {
1935
1899
  if (platform === 'windows') {
1936
1900
  // Single-quote escaping: replace ' with '' (PowerShell convention)
1937
- const escapedDir = workingDir.replace(/'/g, "''");
1901
+ const escapedDir = workingDir.replace(/'/g, '\'\'');
1938
1902
  fullCommand = `Set-Location '${escapedDir}'; ${command}`;
1939
1903
  } else {
1940
1904
  fullCommand = `cd ${workingDir} && ${command}`;
@@ -2338,14 +2302,14 @@ registerToolConditional(
2338
2302
  const platform = serverConfig?.platform || 'linux';
2339
2303
  if (cwd) {
2340
2304
  if (platform === 'windows') {
2341
- const escapedDir = cwd.replace(/'/g, "''");
2305
+ const escapedDir = cwd.replace(/'/g, '\'\'');
2342
2306
  fullCommand = `Set-Location '${escapedDir}'; ${fullCommand}`;
2343
2307
  } else {
2344
2308
  fullCommand = `cd ${cwd} && ${fullCommand}`;
2345
2309
  }
2346
2310
  } else if (serverConfig?.default_dir) {
2347
2311
  if (platform === 'windows') {
2348
- const escapedDir = serverConfig.default_dir.replace(/'/g, "''");
2312
+ const escapedDir = serverConfig.default_dir.replace(/'/g, '\'\'');
2349
2313
  fullCommand = `Set-Location '${escapedDir}'; ${fullCommand}`;
2350
2314
  } else {
2351
2315
  fullCommand = `cd ${serverConfig.default_dir} && ${fullCommand}`;
package/src/logger.js CHANGED
@@ -270,7 +270,3 @@ class Logger {
270
270
 
271
271
  // Export singleton instance
272
272
  export const logger = new Logger();
273
-
274
- // Export for convenience
275
- export const { debug, info, warn, error } = logger;
276
- export default logger;
package/src/policy.js CHANGED
@@ -56,7 +56,7 @@ export const COMMAND_BEARING_TOOLS = new Set([
56
56
  //
57
57
  // The user can layer their own DENY_PATTERNS on top via restricted mode for
58
58
  // finer control.
59
- export const READONLY_DENY_REGEX = [
59
+ const READONLY_DENY_REGEX = [
60
60
  /(^|[\s;&|])rm(\s|$)/,
61
61
  /(^|[\s;&|])rmdir(\s|$)/,
62
62
  /(^|[\s;&|])mv(\s|$)/,
@@ -139,49 +139,3 @@ export function setActiveProfile(profileName) {
139
139
  return false;
140
140
  }
141
141
  }
142
-
143
- /**
144
- * Create a custom profile
145
- */
146
- export function createProfile(name, config) {
147
- try {
148
- const profilePath = path.join(PROFILES_DIR, `${name}.json`);
149
-
150
- // Check if profile already exists
151
- if (fs.existsSync(profilePath)) {
152
- throw new Error(`Profile '${name}' already exists`);
153
- }
154
-
155
- const profile = {
156
- name: name,
157
- description: config.description || `Custom profile: ${name}`,
158
- commandAliases: config.commandAliases || {},
159
- hooks: config.hooks || {}
160
- };
161
-
162
- fs.writeFileSync(profilePath, JSON.stringify(profile, null, 2));
163
- return true;
164
- } catch (error) {
165
- console.error(`Error creating profile: ${error.message}`);
166
- return false;
167
- }
168
- }
169
-
170
- /**
171
- * Merge profiles (useful for extending base profiles)
172
- */
173
- export function mergeProfiles(baseProfileName, extensions) {
174
- const baseProfile = loadProfile(baseProfileName);
175
-
176
- return {
177
- ...baseProfile,
178
- commandAliases: {
179
- ...baseProfile.commandAliases,
180
- ...extensions.commandAliases
181
- },
182
- hooks: {
183
- ...baseProfile.hooks,
184
- ...extensions.hooks
185
- }
186
- };
187
- }
@@ -0,0 +1,72 @@
1
+ // Parsing helpers for `rsync --stats` output.
2
+ //
3
+ // `ssh_sync` runs rsync with `--stats` and scrapes the summary block to report
4
+ // how many files were transferred. Three things make that scraping fragile, and
5
+ // all three are handled here so the tool never falsely claims "no files
6
+ // transferred" when a sync actually moved data:
7
+ //
8
+ // 1. rsync 2.x prints "Number of files transferred: N" while rsync 3.x prints
9
+ // "Number of regular files transferred: N" (the word "regular" was added).
10
+ // 2. Byte counts carry an implementation-specific unit suffix: GNU rsync
11
+ // writes "... bytes", openrsync (the default on recent macOS) writes
12
+ // "... B". Both keep raw byte counts even for large files (no K/M/G).
13
+ // 3. Depending on the rsync host locale the numbers may use "," or "." as a
14
+ // thousands separator (and the opposite char as the decimal separator).
15
+ //
16
+ // Keeping this in its own module makes it unit-testable without booting the MCP
17
+ // server (importing src/index.js starts the stdio server as a side effect).
18
+
19
+ // Parse a number rsync may have grouped with locale-specific separators.
20
+ // Counts and sizes are integers (raw bytes); speed carries an optional
21
+ // fractional part, so `allowDecimal` says whether the last separator may be a
22
+ // decimal point rather than a thousands group.
23
+ export function parseGroupedNumber(raw, { allowDecimal = false } = {}) {
24
+ const separators = raw.match(/[.,]/g) || [];
25
+ if (separators.length === 0) return Number(raw);
26
+
27
+ const distinctSeparators = new Set(separators);
28
+ const lastChar = separators[separators.length - 1];
29
+ const lastIndex = raw.lastIndexOf(lastChar);
30
+ const digitsAfterLast = raw.length - lastIndex - 1;
31
+
32
+ // The last separator is a decimal point only when a fractional part is allowed
33
+ // and it cannot be a thousands group:
34
+ // - two distinct separators ("1.234,56" / "1,234.56") => the last is decimal
35
+ // - a single separator repeated ("1.234.567") => all are thousands groups
36
+ // - a single separator with exactly 3 trailing digits ("1,234") => thousands
37
+ const repeated = separators.length > 1;
38
+ const twoTypes = distinctSeparators.size === 2;
39
+ const isDecimal = allowDecimal && (twoTypes || (!repeated && digitsAfterLast !== 3));
40
+
41
+ if (!isDecimal) {
42
+ // Every separator just groups thousands; strip them all.
43
+ return Number(raw.replace(/[.,]/g, ''));
44
+ }
45
+ const integerPart = raw.slice(0, lastIndex).replace(/[.,]/g, '');
46
+ const fractionPart = raw.slice(lastIndex + 1);
47
+ return Number(`${integerPart}.${fractionPart}`);
48
+ }
49
+
50
+ // Extract the statistics ssh_sync reports from a full rsync stdout capture.
51
+ // Counts default to 0 (never null) when the matching line is absent — e.g. an
52
+ // rsync build that produced no --stats block — so callers can use the result
53
+ // directly. `speed` is only set when present, matching the optional output line.
54
+ export function parseRsyncStats(output, totalTime) {
55
+ const stats = {
56
+ filesTransferred: 0,
57
+ totalSize: 0,
58
+ totalTime,
59
+ };
60
+
61
+ // rsync 2.x: "Number of files transferred", rsync 3.x: "... regular files ...".
62
+ const filesMatch = output.match(/Number of (?:regular )?files transferred:\s*([\d,.]+)/);
63
+ // GNU rsync suffixes byte counts with "bytes", openrsync with "B".
64
+ const sizeMatch = output.match(/Total transferred file size:\s*([\d,.]+)\s*(?:bytes|B)\b/);
65
+ const speedMatch = output.match(/([\d,.]+)\s*bytes\/sec/);
66
+
67
+ if (filesMatch) stats.filesTransferred = parseGroupedNumber(filesMatch[1]);
68
+ if (sizeMatch) stats.totalSize = parseGroupedNumber(sizeMatch[1]);
69
+ if (speedMatch) stats.speed = parseGroupedNumber(speedMatch[1], { allowDecimal: true });
70
+
71
+ return stats;
72
+ }
@@ -15,7 +15,7 @@ const ALIASES_FILE = path.join(__dirname, '..', '.server-aliases.json');
15
15
  /**
16
16
  * Load server aliases from configuration file
17
17
  */
18
- export function loadAliases() {
18
+ function loadAliases() {
19
19
  try {
20
20
  if (fs.existsSync(ALIASES_FILE)) {
21
21
  const content = fs.readFileSync(ALIASES_FILE, 'utf8');
@@ -30,7 +30,7 @@ export function loadAliases() {
30
30
  /**
31
31
  * Save server aliases to configuration file
32
32
  */
33
- export function saveAliases(aliases) {
33
+ function saveAliases(aliases) {
34
34
  try {
35
35
  fs.writeFileSync(ALIASES_FILE, JSON.stringify(aliases, null, 2));
36
36
  return true;
@@ -88,38 +88,6 @@ export function resolveServerName(nameOrAlias, servers) {
88
88
  return null;
89
89
  }
90
90
 
91
- /**
92
- * Create default aliases based on common patterns
93
- */
94
- export function createDefaultAliases(servers) {
95
- const aliases = {};
96
-
97
- Object.entries(servers).forEach(([name, config]) => {
98
- // Create short aliases for common patterns
99
- if (name.includes('production')) {
100
- aliases['prod'] = name;
101
- } else if (name.includes('staging')) {
102
- aliases['stage'] = name;
103
- } else if (name.includes('development')) {
104
- aliases['dev'] = name;
105
- } else if (name.includes('testing')) {
106
- aliases['test'] = name;
107
- }
108
-
109
- // Create aliases from hostname patterns
110
- const host = config.host;
111
- if (host) {
112
- // Extract subdomain as potential alias
113
- const subdomain = host.split('.')[0];
114
- if (subdomain && subdomain !== 'www' && !aliases[subdomain]) {
115
- aliases[subdomain] = name;
116
- }
117
- }
118
- });
119
-
120
- return aliases;
121
- }
122
-
123
91
  /**
124
92
  * Add or update an alias
125
93
  */
@@ -15,7 +15,7 @@ const __dirname = path.dirname(__filename);
15
15
  const GROUPS_FILE = path.join(__dirname, '..', '.server-groups.json');
16
16
 
17
17
  // Group execution strategies
18
- export const EXECUTION_STRATEGIES = {
18
+ const EXECUTION_STRATEGIES = {
19
19
  PARALLEL: 'parallel', // Execute on all servers at once
20
20
  SEQUENTIAL: 'sequential', // Execute one by one
21
21
  ROLLING: 'rolling' // Execute with delay between servers
@@ -115,7 +115,7 @@ class ServerGroups {
115
115
  // This will be populated from the main server config
116
116
  const servers = [];
117
117
 
118
- for (const [key, value] of Object.entries(process.env)) {
118
+ for (const key of Object.keys(process.env)) {
119
119
  if (key.startsWith('SSH_SERVER_') && key.endsWith('_HOST')) {
120
120
  const serverName = key.replace('SSH_SERVER_', '').replace('_HOST', '').toLowerCase();
121
121
  servers.push(serverName);
@@ -395,10 +395,9 @@ class ServerGroups {
395
395
  }
396
396
 
397
397
  // Export singleton instance
398
- export const serverGroups = new ServerGroups();
398
+ const serverGroups = new ServerGroups();
399
399
 
400
400
  // Export convenience functions
401
- export const getGroup = (name) => serverGroups.getGroup(name);
402
401
  export const createGroup = (name, servers, options) => serverGroups.createGroup(name, servers, options);
403
402
  export const updateGroup = (name, updates) => serverGroups.updateGroup(name, updates);
404
403
  export const deleteGroup = (name) => serverGroups.deleteGroup(name);
@@ -406,5 +405,3 @@ export const addServersToGroup = (name, servers) => serverGroups.addServers(name
406
405
  export const removeServersFromGroup = (name, servers) => serverGroups.removeServers(name, servers);
407
406
  export const listGroups = () => serverGroups.listGroups();
408
407
  export const executeOnGroup = (name, executor, options) => serverGroups.executeOnGroup(name, executor, options);
409
-
410
- export default serverGroups;
@@ -14,7 +14,7 @@ function generateMarker(prefix) {
14
14
  }
15
15
 
16
16
  // Session states
17
- export const SESSION_STATES = {
17
+ const SESSION_STATES = {
18
18
  INITIALIZING: 'initializing',
19
19
  READY: 'ready',
20
20
  BUSY: 'busy',
@@ -332,7 +332,7 @@ export function getSession(sessionId) {
332
332
  export function listSessions() {
333
333
  const activeSessions = [];
334
334
 
335
- for (const [id, session] of sessions.entries()) {
335
+ for (const [, session] of sessions.entries()) {
336
336
  if (session.state !== SESSION_STATES.CLOSED) {
337
337
  activeSessions.push(session.getInfo());
338
338
  }
@@ -355,26 +355,10 @@ export function closeSession(sessionId) {
355
355
  return true;
356
356
  }
357
357
 
358
- /**
359
- * Close all sessions for a server
360
- */
361
- export function closeServerSessions(serverName) {
362
- let closedCount = 0;
363
-
364
- for (const [id, session] of sessions.entries()) {
365
- if (session.serverName === serverName) {
366
- session.close();
367
- closedCount++;
368
- }
369
- }
370
-
371
- return closedCount;
372
- }
373
-
374
358
  /**
375
359
  * Cleanup old sessions
376
360
  */
377
- export function cleanupSessions(maxAge = 30 * 60 * 1000) { // 30 minutes default
361
+ function cleanupSessions(maxAge = 30 * 60 * 1000) { // 30 minutes default
378
362
  const now = Date.now();
379
363
  let cleanedCount = 0;
380
364
 
@@ -403,13 +387,3 @@ const sessionCleanup = setInterval(() => {
403
387
  }
404
388
  }, 5 * 60 * 1000); // Every 5 minutes
405
389
  if (typeof sessionCleanup.unref === 'function') sessionCleanup.unref();
406
-
407
- export default {
408
- createSession,
409
- getSession,
410
- listSessions,
411
- closeSession,
412
- closeServerSessions,
413
- cleanupSessions,
414
- SESSION_STATES
415
- };
@@ -345,35 +345,3 @@ export function extractHostFromSSHError(stderr) {
345
345
 
346
346
  return null;
347
347
  }
348
-
349
- /**
350
- * Handle SSH key error automatically
351
- */
352
- export async function handleSSHKeyError(stderr, options = {}) {
353
- const { autoAccept = false, interactive = true } = options;
354
-
355
- const hostInfo = extractHostFromSSHError(stderr);
356
- if (!hostInfo) {
357
- throw new Error('Could not extract host information from SSH error');
358
- }
359
-
360
- logger.warn('SSH host key verification failed', hostInfo);
361
-
362
- if (autoAccept) {
363
- // Automatically update the key
364
- await updateHostKey(hostInfo.host, hostInfo.port);
365
- return { action: 'updated', ...hostInfo };
366
- }
367
-
368
- if (!interactive) {
369
- throw new Error(`Host key verification failed for ${hostInfo.host}:${hostInfo.port}. Use ssh_key_manage tool to update the key.`);
370
- }
371
-
372
- // In interactive mode, we would prompt the user
373
- // For now, just return the error info
374
- return {
375
- action: 'prompt_required',
376
- ...hostInfo,
377
- message: `Host key has changed for ${hostInfo.host}:${hostInfo.port}. Use ssh_key_manage tool to verify and update the key.`
378
- };
379
- }
@@ -1,10 +1,7 @@
1
1
  import { Client } from 'ssh2';
2
2
  import fs from 'fs';
3
3
  import os from 'os';
4
- import { promisify } from 'util';
5
- import crypto from 'crypto';
6
- import { isHostKnown, getCurrentHostKey, addHostKey, updateHostKey } from './ssh-key-manager.js';
7
- import { configLoader } from './config-loader.js';
4
+ import { isHostKnown, addHostKey } from './ssh-key-manager.js';
8
5
  import { logger } from './logger.js';
9
6
 
10
7
  // Validate liveness-probe output across shells (bash, cmd.exe, PowerShell).
@@ -111,7 +108,7 @@ class SSHManager {
111
108
 
112
109
  // Add host key verification callback if enabled
113
110
  if (this.hostKeyVerification) {
114
- connConfig.hostVerifier = (hashedKey) => {
111
+ connConfig.hostVerifier = () => {
115
112
  const port = this.config.port || 22;
116
113
  const host = this.config.host;
117
114
 
@@ -480,7 +477,7 @@ class SSHManager {
480
477
  }
481
478
 
482
479
  async putFiles(files, options = {}) {
483
- const sftp = await this.getSFTP();
480
+ await this.getSFTP();
484
481
  const results = [];
485
482
 
486
483
  for (const file of files) {
@@ -21,7 +21,7 @@ const CONFIG_FILE = path.join(CONFIG_DIR, 'tools-config.json');
21
21
  /**
22
22
  * Tool Configuration Manager Class
23
23
  */
24
- export class ToolConfigManager {
24
+ class ToolConfigManager {
25
25
  constructor() {
26
26
  this.config = null;
27
27
  this.configPath = CONFIG_FILE;
@@ -424,11 +424,3 @@ export function isToolEnabled(toolName) {
424
424
  }
425
425
  return toolConfigInstance.isToolEnabled(toolName);
426
426
  }
427
-
428
- /**
429
- * Get the tool configuration manager instance
430
- * @returns {ToolConfigManager|null} Configuration manager or null if not loaded
431
- */
432
- export function getToolConfigManager() {
433
- return toolConfigInstance;
434
- }
@@ -11,14 +11,14 @@ import { logger } from './logger.js';
11
11
  const tunnels = new Map();
12
12
 
13
13
  // Tunnel types
14
- export const TUNNEL_TYPES = {
14
+ const TUNNEL_TYPES = {
15
15
  LOCAL: 'local', // Local port forwarding (access remote service locally)
16
16
  REMOTE: 'remote', // Remote port forwarding (expose local service remotely)
17
17
  DYNAMIC: 'dynamic' // SOCKS proxy
18
18
  };
19
19
 
20
20
  // Tunnel states
21
- export const TUNNEL_STATES = {
21
+ const TUNNEL_STATES = {
22
22
  CONNECTING: 'connecting',
23
23
  ACTIVE: 'active',
24
24
  RECONNECTING: 'reconnecting',
@@ -182,7 +182,7 @@ class SSHTunnel {
182
182
  });
183
183
 
184
184
  // Handle incoming connections from remote
185
- this.ssh.on('tcp connection', (info, accept, reject) => {
185
+ this.ssh.on('tcp connection', (info, accept) => {
186
186
  if (info.destPort !== remotePort) return;
187
187
 
188
188
  this.stats.connectionsTotal++;
@@ -478,26 +478,13 @@ export async function createTunnel(serverName, ssh, config) {
478
478
  }
479
479
  }
480
480
 
481
- /**
482
- * Get an existing tunnel
483
- */
484
- export function getTunnel(tunnelId) {
485
- const tunnel = tunnels.get(tunnelId);
486
-
487
- if (!tunnel) {
488
- throw new Error(`Tunnel ${tunnelId} not found`);
489
- }
490
-
491
- return tunnel;
492
- }
493
-
494
481
  /**
495
482
  * List all active tunnels
496
483
  */
497
484
  export function listTunnels(serverName = null) {
498
485
  const activeTunnels = [];
499
486
 
500
- for (const [id, tunnel] of tunnels.entries()) {
487
+ for (const [, tunnel] of tunnels.entries()) {
501
488
  if (tunnel.state !== TUNNEL_STATES.CLOSED) {
502
489
  if (!serverName || tunnel.serverName === serverName) {
503
490
  activeTunnels.push(tunnel.getInfo());
@@ -528,7 +515,7 @@ export function closeTunnel(tunnelId) {
528
515
  export function closeServerTunnels(serverName) {
529
516
  let closedCount = 0;
530
517
 
531
- for (const [id, tunnel] of tunnels.entries()) {
518
+ for (const [, tunnel] of tunnels.entries()) {
532
519
  if (tunnel.serverName === serverName) {
533
520
  tunnel.close();
534
521
  closedCount++;
@@ -541,7 +528,7 @@ export function closeServerTunnels(serverName) {
541
528
  /**
542
529
  * Monitor tunnel health
543
530
  */
544
- export function monitorTunnels() {
531
+ function monitorTunnels() {
545
532
  const now = Date.now();
546
533
  const healthTimeout = 60 * 1000; // 1 minute
547
534
 
@@ -568,13 +555,3 @@ export function monitorTunnels() {
568
555
  // a background timer.
569
556
  const tunnelMonitor = setInterval(monitorTunnels, 30 * 1000); // Every 30 seconds
570
557
  if (typeof tunnelMonitor.unref === 'function') tunnelMonitor.unref();
571
-
572
- export default {
573
- createTunnel,
574
- getTunnel,
575
- listTunnels,
576
- closeTunnel,
577
- closeServerTunnels,
578
- TUNNEL_TYPES,
579
- TUNNEL_STATES
580
- };