mcp-ssh-manager 3.0.0 → 3.1.0

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/src/index.js CHANGED
@@ -76,7 +76,7 @@ import {
76
76
  hasHostKeyChanged,
77
77
  listKnownHosts,
78
78
  detectSSHKeyError,
79
- handleSSHKeyError
79
+ extractHostFromSSHError
80
80
  } from './ssh-key-manager.js';
81
81
  import {
82
82
  BACKUP_TYPES,
@@ -152,6 +152,7 @@ import {
152
152
  formatBytes,
153
153
  getConnectionInfo
154
154
  } from './database-manager.js';
155
+ import { loadToolConfig, isToolEnabled } from './tool-config-manager.js';
155
156
 
156
157
  const __filename = fileURLToPath(import.meta.url);
157
158
  const __dirname = path.dirname(__filename);
@@ -187,6 +188,20 @@ initializeHooks().catch(error => {
187
188
  logger.error('Failed to initialize hooks', { error: error.message });
188
189
  });
189
190
 
191
+ // Load tool configuration
192
+ let toolConfig = null;
193
+ loadToolConfig().then(config => {
194
+ toolConfig = config;
195
+ const summary = config.getSummary();
196
+ logger.info(`Tool configuration loaded: ${summary.mode} mode, ${summary.enabledCount}/${summary.totalTools} tools enabled`);
197
+ if (summary.mode === 'all') {
198
+ logger.info('💡 Tip: Run "ssh-manager tools configure" to reduce context usage in Claude Code');
199
+ }
200
+ }).catch(error => {
201
+ logger.error('Failed to load tool configuration', { error: error.message });
202
+ logger.info('Using default configuration (all tools enabled)');
203
+ });
204
+
190
205
  // Map to store active connections
191
206
  const connections = new Map();
192
207
 
@@ -213,23 +228,23 @@ function loadServerConfig() {
213
228
  async function execCommandWithTimeout(ssh, command, options = {}, timeoutMs = 30000) {
214
229
  // Pass through rawCommand if specified
215
230
  const { rawCommand, ...otherOptions } = options;
216
-
231
+
217
232
  // For commands that might hang, use the system's timeout command if available
218
233
  const useSystemTimeout = timeoutMs > 0 && timeoutMs < 300000 && !rawCommand; // Max 5 minutes, not for raw commands
219
-
234
+
220
235
  if (useSystemTimeout) {
221
236
  // Wrap command with timeout command (works on Linux/Mac)
222
237
  const timeoutSeconds = Math.ceil(timeoutMs / 1000);
223
- const wrappedCommand = `timeout ${timeoutSeconds} sh -c '${command.replace(/'/g, "'\\''")}'`;
224
-
238
+ const wrappedCommand = `timeout ${timeoutSeconds} sh -c '${command.replace(/'/g, '\'\\\'\'')}'`;
239
+
225
240
  try {
226
241
  const result = await ssh.execCommand(wrappedCommand, otherOptions);
227
-
242
+
228
243
  // Check if timeout occurred (exit code 124 on Linux, 124 or 143 on Mac)
229
244
  if (result.code === 124 || result.code === 143) {
230
245
  throw new Error(`Command timeout after ${timeoutMs}ms: ${command.substring(0, 100)}...`);
231
246
  }
232
-
247
+
233
248
  return result;
234
249
  } catch (error) {
235
250
  // If timeout occurred, remove connection from pool
@@ -406,8 +421,23 @@ const server = new McpServer({
406
421
 
407
422
  logger.info('MCP Server initialized', { version: '1.2.0' });
408
423
 
424
+ /**
425
+ * Helper function to conditionally register tools based on configuration
426
+ * @param {string} toolName - Name of the tool
427
+ * @param {Object} schema - Tool schema
428
+ * @param {Function} handler - Tool handler function
429
+ */
430
+ function registerToolConditional(toolName, schema, handler) {
431
+ if (isToolEnabled(toolName)) {
432
+ server.registerTool(toolName, schema, handler);
433
+ logger.debug(`Registered tool: ${toolName}`);
434
+ } else {
435
+ logger.debug(`Skipped disabled tool: ${toolName}`);
436
+ }
437
+ }
438
+
409
439
  // Register available tools
410
- server.registerTool(
440
+ registerToolConditional(
411
441
  'ssh_execute',
412
442
  {
413
443
  description: 'Execute command on remote SSH server',
@@ -444,7 +474,7 @@ server.registerTool(
444
474
  const startTime = logger.logCommand(serverName, fullCommand, workingDir);
445
475
 
446
476
  const result = await execCommandWithTimeout(ssh, fullCommand, {}, timeout);
447
-
477
+
448
478
  // Log command result
449
479
  logger.logCommandResult(serverName, fullCommand, startTime, result);
450
480
 
@@ -485,7 +515,7 @@ server.registerTool(
485
515
  }
486
516
  );
487
517
 
488
- server.registerTool(
518
+ registerToolConditional(
489
519
  'ssh_upload',
490
520
  {
491
521
  description: 'Upload file to remote SSH server',
@@ -498,12 +528,12 @@ server.registerTool(
498
528
  async ({ server: serverName, localPath, remotePath }) => {
499
529
  try {
500
530
  const ssh = await getConnection(serverName);
501
-
531
+
502
532
  logger.logTransfer('upload', serverName, localPath, remotePath);
503
533
  const startTime = Date.now();
504
-
534
+
505
535
  await ssh.putFile(localPath, remotePath);
506
-
536
+
507
537
  const fileStats = fs.statSync(localPath);
508
538
  logger.logTransfer('upload', serverName, localPath, remotePath, {
509
539
  success: true,
@@ -536,7 +566,7 @@ server.registerTool(
536
566
  }
537
567
  );
538
568
 
539
- server.registerTool(
569
+ registerToolConditional(
540
570
  'ssh_download',
541
571
  {
542
572
  description: 'Download file from remote SSH server',
@@ -549,12 +579,12 @@ server.registerTool(
549
579
  async ({ server: serverName, remotePath, localPath }) => {
550
580
  try {
551
581
  const ssh = await getConnection(serverName);
552
-
582
+
553
583
  logger.logTransfer('download', serverName, remotePath, localPath);
554
584
  const startTime = Date.now();
555
-
585
+
556
586
  await ssh.getFile(localPath, remotePath);
557
-
587
+
558
588
  const fileStats = fs.statSync(localPath);
559
589
  logger.logTransfer('download', serverName, remotePath, localPath, {
560
590
  success: true,
@@ -587,7 +617,7 @@ server.registerTool(
587
617
  }
588
618
  );
589
619
 
590
- server.registerTool(
620
+ registerToolConditional(
591
621
  'ssh_sync',
592
622
  {
593
623
  description: 'Synchronize files/folders between local and remote via rsync',
@@ -609,7 +639,7 @@ server.registerTool(
609
639
  const ssh = await getConnection(serverName);
610
640
  const servers = loadServerConfig();
611
641
  const serverConfig = servers[serverName.toLowerCase()];
612
-
642
+
613
643
  // Check if sshpass is available for password authentication
614
644
  if (!serverConfig.keypath && serverConfig.password) {
615
645
  // Check if sshpass is installed
@@ -627,61 +657,61 @@ server.registerTool(
627
657
  };
628
658
  }
629
659
  }
630
-
660
+
631
661
  // Determine sync direction based on source/destination prefixes
632
662
  const isLocalSource = source.startsWith('local:');
633
663
  const isRemoteSource = source.startsWith('remote:');
634
664
  const isLocalDest = destination.startsWith('local:');
635
665
  const isRemoteDest = destination.startsWith('remote:');
636
-
666
+
637
667
  // Clean paths
638
668
  const cleanSource = source.replace(/^(local:|remote:)/, '');
639
669
  const cleanDest = destination.replace(/^(local:|remote:)/, '');
640
-
670
+
641
671
  // Validate direction
642
672
  if ((isLocalSource && isLocalDest) || (isRemoteSource && isRemoteDest)) {
643
673
  throw new Error('Source and destination must be different (one local, one remote). Use prefixes: local: or remote:');
644
674
  }
645
-
675
+
646
676
  // If no prefixes, assume old format (local source to remote dest)
647
677
  const direction = (isLocalSource || (!isLocalSource && !isRemoteSource)) ? 'push' : 'pull';
648
-
678
+
649
679
  // Build rsync command
650
680
  let rsyncOptions = ['-avz'];
651
-
681
+
652
682
  if (!compress) {
653
683
  rsyncOptions = ['-av'];
654
684
  }
655
-
685
+
656
686
  if (checksum) {
657
687
  rsyncOptions.push('--checksum');
658
688
  }
659
-
689
+
660
690
  if (deleteFiles) {
661
691
  rsyncOptions.push('--delete');
662
692
  }
663
-
693
+
664
694
  if (dryRun) {
665
695
  rsyncOptions.push('--dry-run');
666
696
  }
667
-
697
+
668
698
  if (verbose || logger.verbose) {
669
699
  // Only add stats, not progress to avoid blocking with too much output
670
700
  rsyncOptions.push('--stats');
671
701
  }
672
-
702
+
673
703
  // Add exclude patterns
674
704
  exclude.forEach(pattern => {
675
705
  rsyncOptions.push('--exclude', pattern);
676
706
  });
677
-
707
+
678
708
  let localPath;
679
709
  let remotePath;
680
-
710
+
681
711
  if (direction === 'push') {
682
712
  localPath = cleanSource;
683
713
  remotePath = cleanDest;
684
-
714
+
685
715
  // Check if local path exists
686
716
  if (!fs.existsSync(localPath)) {
687
717
  throw new Error(`Local path does not exist: ${localPath}`);
@@ -690,7 +720,7 @@ server.registerTool(
690
720
  localPath = cleanDest;
691
721
  remotePath = cleanSource;
692
722
  }
693
-
723
+
694
724
  // Add SSH options for non-interactive mode
695
725
  const sshOptions = [];
696
726
 
@@ -707,11 +737,11 @@ server.registerTool(
707
737
  sshOptions.push('-o StrictHostKeyChecking=accept-new'); // Accept new keys, reject changed ones
708
738
  sshOptions.push('-o ConnectTimeout=10');
709
739
  }
710
-
740
+
711
741
  if (serverConfig.port && serverConfig.port !== '22') {
712
742
  sshOptions.push(`-p ${serverConfig.port}`);
713
743
  }
714
-
744
+
715
745
  logger.info(`Starting rsync ${direction}`, {
716
746
  server: serverName,
717
747
  source: direction === 'push' ? localPath : remotePath,
@@ -719,49 +749,49 @@ server.registerTool(
719
749
  dryRun,
720
750
  deleteFiles
721
751
  });
722
-
752
+
723
753
  const startTime = Date.now();
724
-
754
+
725
755
  // Execute rsync via spawn for non-blocking streaming
726
756
  const { spawn } = await import('child_process');
727
-
757
+
728
758
  return new Promise((resolve, reject) => {
729
759
  let output = '';
730
760
  let errorOutput = '';
731
761
  let killed = false;
732
-
762
+
733
763
  // Build command based on authentication method
734
764
  let rsyncCommand;
735
765
  let rsyncArgs = [];
736
766
  let processEnv = { ...process.env };
737
-
767
+
738
768
  if (serverConfig.password) {
739
769
  // Use sshpass for password authentication
740
770
  rsyncCommand = 'sshpass';
741
771
  rsyncArgs.push('-p', serverConfig.password);
742
772
  rsyncArgs.push('rsync');
743
-
773
+
744
774
  // Add rsync options
745
775
  rsyncOptions.forEach(opt => rsyncArgs.push(opt));
746
-
776
+
747
777
  // Add SSH command
748
778
  const sshCmd = `ssh ${sshOptions.join(' ')}`;
749
779
  rsyncArgs.push('-e', sshCmd);
750
780
  } else {
751
781
  // Direct rsync for key authentication
752
782
  rsyncCommand = 'rsync';
753
-
783
+
754
784
  // Add rsync options
755
785
  rsyncOptions.forEach(opt => rsyncArgs.push(opt));
756
-
786
+
757
787
  // Add SSH command with all options
758
788
  const sshCmd = `ssh ${sshOptions.join(' ')}`;
759
789
  rsyncArgs.push('-e', sshCmd);
760
-
790
+
761
791
  processEnv.SSH_ASKPASS = '/bin/false';
762
792
  processEnv.DISPLAY = '';
763
793
  }
764
-
794
+
765
795
  // Add source and destination
766
796
  if (direction === 'push') {
767
797
  rsyncArgs.push(localPath);
@@ -770,19 +800,19 @@ server.registerTool(
770
800
  rsyncArgs.push(`${serverConfig.user}@${serverConfig.host}:${remotePath}`);
771
801
  rsyncArgs.push(localPath);
772
802
  }
773
-
803
+
774
804
  const rsyncProcess = spawn(rsyncCommand, rsyncArgs, {
775
805
  stdio: ['ignore', 'pipe', 'pipe'],
776
806
  env: processEnv
777
807
  });
778
-
808
+
779
809
  // Set timeout
780
810
  const timer = setTimeout(() => {
781
811
  killed = true;
782
812
  rsyncProcess.kill('SIGTERM');
783
813
  reject(new Error(`Rsync timeout after ${timeout}ms`));
784
814
  }, timeout);
785
-
815
+
786
816
  // Collect output with size limit
787
817
  rsyncProcess.stdout.on('data', (data) => {
788
818
  const chunk = data.toString();
@@ -792,7 +822,7 @@ server.registerTool(
792
822
  output = output.slice(-50000);
793
823
  }
794
824
  });
795
-
825
+
796
826
  rsyncProcess.stderr.on('data', (data) => {
797
827
  const chunk = data.toString();
798
828
  errorOutput += chunk;
@@ -800,21 +830,21 @@ server.registerTool(
800
830
  errorOutput = errorOutput.slice(-25000);
801
831
  }
802
832
  });
803
-
833
+
804
834
  rsyncProcess.on('error', (err) => {
805
835
  clearTimeout(timer);
806
836
  reject(new Error(`Failed to start rsync: ${err.message}`));
807
837
  });
808
-
838
+
809
839
  rsyncProcess.on('close', (code) => {
810
840
  clearTimeout(timer);
811
-
841
+
812
842
  if (killed) {
813
843
  return; // Already rejected due to timeout
814
844
  }
815
-
845
+
816
846
  const duration = Date.now() - startTime;
817
-
847
+
818
848
  if (code !== 0) {
819
849
  logger.error(`Rsync ${direction} failed`, {
820
850
  server: serverName,
@@ -832,10 +862,10 @@ server.registerTool(
832
862
  errorMsg += `Host: ${hostInfo.host}:${hostInfo.port}\n`;
833
863
  }
834
864
 
835
- errorMsg += `\n📍 To fix this issue:\n`;
836
- errorMsg += `1. Verify the server identity\n`;
837
- errorMsg += `2. Use 'ssh_key_manage' tool with action 'verify' to check the key\n`;
838
- errorMsg += `3. Use 'ssh_key_manage' tool with action 'accept' to update the key if you trust the server\n`;
865
+ errorMsg += '\n📍 To fix this issue:\n';
866
+ errorMsg += '1. Verify the server identity\n';
867
+ errorMsg += '2. Use \'ssh_key_manage\' tool with action \'verify\' to check the key\n';
868
+ errorMsg += '3. Use \'ssh_key_manage\' tool with action \'accept\' to update the key if you trust the server\n';
839
869
  errorMsg += `\nOriginal error:\n${errorOutput}`;
840
870
 
841
871
  reject(new Error(errorMsg));
@@ -844,23 +874,23 @@ server.registerTool(
844
874
  }
845
875
  return;
846
876
  }
847
-
877
+
848
878
  // Parse rsync output for statistics
849
879
  let stats = {
850
880
  filesTransferred: 0,
851
881
  totalSize: 0,
852
882
  totalTime: duration
853
883
  };
854
-
884
+
855
885
  // Extract statistics from rsync output
856
886
  const filesMatch = output.match(/Number of files transferred: (\d+)/);
857
887
  const sizeMatch = output.match(/Total transferred file size: ([\d,]+) bytes/);
858
888
  const speedMatch = output.match(/([\d.]+) bytes\/sec/);
859
-
889
+
860
890
  if (filesMatch) stats.filesTransferred = parseInt(filesMatch[1]);
861
891
  if (sizeMatch) stats.totalSize = parseInt(sizeMatch[1].replace(/,/g, ''));
862
892
  if (speedMatch) stats.speed = parseFloat(speedMatch[1]);
863
-
893
+
864
894
  logger.info(`Rsync ${direction} completed`, {
865
895
  server: serverName,
866
896
  direction,
@@ -869,14 +899,14 @@ server.registerTool(
869
899
  totalSize: stats.totalSize,
870
900
  dryRun
871
901
  });
872
-
902
+
873
903
  // Format output
874
904
  let resultText = dryRun ? '🔍 Dry run completed\n' : '✅ Sync completed successfully\n';
875
905
  resultText += `Direction: ${direction === 'push' ? 'Local → Remote' : 'Remote → Local'}\n`;
876
906
  resultText += `Server: ${serverName}\n`;
877
907
  resultText += `Source: ${direction === 'push' ? localPath : remotePath}\n`;
878
908
  resultText += `Destination: ${direction === 'push' ? remotePath : localPath}\n`;
879
-
909
+
880
910
  if (stats.filesTransferred > 0) {
881
911
  resultText += `Files transferred: ${stats.filesTransferred}\n`;
882
912
  if (stats.totalSize > 0) {
@@ -890,23 +920,23 @@ server.registerTool(
890
920
  } else {
891
921
  resultText += 'No files needed to be transferred\n';
892
922
  }
893
-
923
+
894
924
  resultText += `Time: ${(duration / 1000).toFixed(2)} seconds\n`;
895
-
925
+
896
926
  if (verbose && output.length < 5000) {
897
927
  resultText += '\n📋 Sync statistics:\n';
898
928
  // Only show relevant stats lines
899
- const statsLines = output.split('\n').filter(line =>
900
- line.includes('Number of') ||
901
- line.includes('Total') ||
902
- line.includes('sent') ||
929
+ const statsLines = output.split('\n').filter(line =>
930
+ line.includes('Number of') ||
931
+ line.includes('Total') ||
932
+ line.includes('sent') ||
903
933
  line.includes('received')
904
934
  );
905
935
  if (statsLines.length > 0) {
906
936
  resultText += statsLines.join('\n');
907
937
  }
908
938
  }
909
-
939
+
910
940
  resolve({
911
941
  content: [
912
942
  {
@@ -930,7 +960,7 @@ server.registerTool(
930
960
  }
931
961
  );
932
962
 
933
- server.registerTool(
963
+ registerToolConditional(
934
964
  'ssh_tail',
935
965
  {
936
966
  description: 'Tail remote log files in real-time',
@@ -945,31 +975,31 @@ server.registerTool(
945
975
  async ({ server: serverName, file, lines = 10, follow = true, grep }) => {
946
976
  try {
947
977
  const ssh = await getConnection(serverName);
948
-
978
+
949
979
  // Build tail command
950
980
  let command = `tail -n ${lines}`;
951
981
  if (follow) {
952
982
  command += ' -f';
953
983
  }
954
984
  command += ` "${file}"`;
955
-
985
+
956
986
  // Add grep filter if specified
957
987
  if (grep) {
958
988
  command += ` | grep "${grep}"`;
959
989
  }
960
-
990
+
961
991
  logger.info(`Starting tail on ${serverName}`, {
962
992
  file,
963
993
  lines,
964
994
  follow,
965
995
  grep
966
996
  });
967
-
997
+
968
998
  // For follow mode, we need to handle streaming
969
999
  if (follow) {
970
1000
  // Create a unique session ID for this tail
971
1001
  const sessionId = `tail_${Date.now()}`;
972
-
1002
+
973
1003
  // Store the SSH stream for later cleanup
974
1004
  const stream = await ssh.execCommandStream(command, {
975
1005
  onStdout: (chunk) => {
@@ -980,7 +1010,7 @@ server.registerTool(
980
1010
  console.error(`[ERROR] ${chunk}`);
981
1011
  }
982
1012
  });
983
-
1013
+
984
1014
  return {
985
1015
  content: [
986
1016
  {
@@ -992,16 +1022,16 @@ server.registerTool(
992
1022
  } else {
993
1023
  // Non-follow mode - just get the output
994
1024
  const result = await execCommandWithTimeout(ssh, command, {}, 15000);
995
-
1025
+
996
1026
  if (result.code !== 0) {
997
1027
  throw new Error(result.stderr || 'Failed to tail file');
998
1028
  }
999
-
1029
+
1000
1030
  logger.info(`Tail completed on ${serverName}`, {
1001
1031
  file,
1002
1032
  lines: result.stdout.split('\n').length
1003
1033
  });
1004
-
1034
+
1005
1035
  return {
1006
1036
  content: [
1007
1037
  {
@@ -1016,7 +1046,7 @@ server.registerTool(
1016
1046
  file,
1017
1047
  error: error.message
1018
1048
  });
1019
-
1049
+
1020
1050
  return {
1021
1051
  content: [
1022
1052
  {
@@ -1029,7 +1059,7 @@ server.registerTool(
1029
1059
  }
1030
1060
  );
1031
1061
 
1032
- server.registerTool(
1062
+ registerToolConditional(
1033
1063
  'ssh_monitor',
1034
1064
  {
1035
1065
  description: 'Monitor system resources (CPU, RAM, disk) on remote server',
@@ -1043,62 +1073,62 @@ server.registerTool(
1043
1073
  async ({ server: serverName, type = 'overview', interval, duration }) => {
1044
1074
  try {
1045
1075
  const ssh = await getConnection(serverName);
1046
-
1076
+
1047
1077
  logger.info(`Starting system monitoring on ${serverName}`, {
1048
1078
  type,
1049
1079
  interval,
1050
1080
  duration
1051
1081
  });
1052
-
1082
+
1053
1083
  let commands = {};
1054
1084
  let output = {};
1055
-
1085
+
1056
1086
  // Define monitoring commands based on type
1057
1087
  switch (type) {
1058
- case 'cpu':
1059
- commands.cpu = "top -bn1 | head -20";
1060
- commands.load = "uptime";
1061
- commands.cores = "nproc";
1062
- break;
1063
-
1064
- case 'memory':
1065
- commands.memory = "free -h";
1066
- commands.swap = "swapon --show";
1067
- commands.top_mem = "ps aux --sort=-%mem | head -10";
1068
- break;
1069
-
1070
- case 'disk':
1071
- commands.disk = "df -h";
1072
- commands.inodes = "df -i";
1073
- commands.io = "iostat -x 1 2 | tail -n +4";
1074
- break;
1075
-
1076
- case 'network':
1077
- commands.interfaces = "ip -s link show";
1078
- commands.connections = "ss -tunap | head -20";
1079
- commands.netstat = "netstat -i";
1080
- break;
1081
-
1082
- case 'process':
1083
- commands.process = "ps aux --sort=-%cpu | head -20";
1084
- commands.count = "ps aux | wc -l";
1085
- commands.zombies = "ps aux | grep -c defunct || echo 0";
1086
- break;
1087
-
1088
- case 'overview':
1089
- default:
1090
- commands.uptime = "uptime";
1091
- commands.cpu = "mpstat 1 1 2>/dev/null || top -bn1 | grep 'Cpu'";
1092
- commands.memory = "free -h";
1093
- commands.disk = "df -h | grep -E '^/dev/' | head -5";
1094
- commands.load = "cat /proc/loadavg";
1095
- commands.processes = "ps aux | wc -l";
1096
- break;
1088
+ case 'cpu':
1089
+ commands.cpu = 'top -bn1 | head -20';
1090
+ commands.load = 'uptime';
1091
+ commands.cores = 'nproc';
1092
+ break;
1093
+
1094
+ case 'memory':
1095
+ commands.memory = 'free -h';
1096
+ commands.swap = 'swapon --show';
1097
+ commands.top_mem = 'ps aux --sort=-%mem | head -10';
1098
+ break;
1099
+
1100
+ case 'disk':
1101
+ commands.disk = 'df -h';
1102
+ commands.inodes = 'df -i';
1103
+ commands.io = 'iostat -x 1 2 | tail -n +4';
1104
+ break;
1105
+
1106
+ case 'network':
1107
+ commands.interfaces = 'ip -s link show';
1108
+ commands.connections = 'ss -tunap | head -20';
1109
+ commands.netstat = 'netstat -i';
1110
+ break;
1111
+
1112
+ case 'process':
1113
+ commands.process = 'ps aux --sort=-%cpu | head -20';
1114
+ commands.count = 'ps aux | wc -l';
1115
+ commands.zombies = 'ps aux | grep -c defunct || echo 0';
1116
+ break;
1117
+
1118
+ case 'overview':
1119
+ default:
1120
+ commands.uptime = 'uptime';
1121
+ commands.cpu = 'mpstat 1 1 2>/dev/null || top -bn1 | grep \'Cpu\'';
1122
+ commands.memory = 'free -h';
1123
+ commands.disk = 'df -h | grep -E \'^/dev/\' | head -5';
1124
+ commands.load = 'cat /proc/loadavg';
1125
+ commands.processes = 'ps aux | wc -l';
1126
+ break;
1097
1127
  }
1098
-
1128
+
1099
1129
  // Execute all monitoring commands
1100
1130
  const startTime = Date.now();
1101
-
1131
+
1102
1132
  for (const [key, cmd] of Object.entries(commands)) {
1103
1133
  try {
1104
1134
  const result = await execCommandWithTimeout(ssh, cmd, {}, 10000);
@@ -1111,69 +1141,69 @@ server.registerTool(
1111
1141
  output[key] = `Error: ${err.message}`;
1112
1142
  }
1113
1143
  }
1114
-
1144
+
1115
1145
  const monitoringDuration = Date.now() - startTime;
1116
-
1146
+
1117
1147
  // Format the output based on type
1118
1148
  let formattedOutput = `📊 System Monitor - ${serverName}\n`;
1119
1149
  formattedOutput += `Type: ${type} | Time: ${new Date().toISOString()}\n`;
1120
1150
  formattedOutput += `Collection time: ${monitoringDuration}ms\n`;
1121
1151
  formattedOutput += '━'.repeat(50) + '\n\n';
1122
-
1152
+
1123
1153
  switch (type) {
1124
- case 'overview':
1125
- formattedOutput += `⏱️ UPTIME\n${output.uptime || 'N/A'}\n\n`;
1126
- formattedOutput += `💻 CPU\n${output.cpu || 'N/A'}\n\n`;
1127
- formattedOutput += `📈 LOAD AVERAGE\n${output.load || 'N/A'}\n\n`;
1128
- formattedOutput += `💾 MEMORY\n${output.memory || 'N/A'}\n\n`;
1129
- formattedOutput += `💿 DISK USAGE\n${output.disk || 'N/A'}\n\n`;
1130
- formattedOutput += `📝 PROCESSES: ${output.processes || 'N/A'}\n`;
1131
- break;
1132
-
1133
- case 'cpu':
1134
- formattedOutput += `🖥️ CPU CORES: ${output.cores || 'N/A'}\n\n`;
1135
- formattedOutput += `📊 LOAD\n${output.load || 'N/A'}\n\n`;
1136
- formattedOutput += `📈 TOP PROCESSES\n${output.cpu || 'N/A'}\n`;
1137
- break;
1138
-
1139
- case 'memory':
1140
- formattedOutput += `💾 MEMORY USAGE\n${output.memory || 'N/A'}\n\n`;
1141
- formattedOutput += `🔄 SWAP\n${output.swap || 'No swap configured'}\n\n`;
1142
- formattedOutput += `📊 TOP MEMORY CONSUMERS\n${output.top_mem || 'N/A'}\n`;
1143
- break;
1144
-
1145
- case 'disk':
1146
- formattedOutput += `💿 DISK SPACE\n${output.disk || 'N/A'}\n\n`;
1147
- formattedOutput += `📁 INODE USAGE\n${output.inodes || 'N/A'}\n\n`;
1148
- formattedOutput += `⚡ I/O STATS\n${output.io || 'N/A'}\n`;
1149
- break;
1150
-
1151
- case 'network':
1152
- formattedOutput += `🌐 NETWORK INTERFACES\n${output.interfaces || 'N/A'}\n\n`;
1153
- formattedOutput += `🔌 CONNECTIONS\n${output.connections || 'N/A'}\n\n`;
1154
- formattedOutput += `📊 INTERFACE STATS\n${output.netstat || 'N/A'}\n`;
1155
- break;
1156
-
1157
- case 'process':
1158
- formattedOutput += `📝 PROCESS COUNT: ${output.count || 'N/A'}\n`;
1159
- formattedOutput += `⚠️ ZOMBIE PROCESSES: ${output.zombies || '0'}\n\n`;
1160
- formattedOutput += `📊 TOP PROCESSES BY CPU\n${output.process || 'N/A'}\n`;
1161
- break;
1154
+ case 'overview':
1155
+ formattedOutput += `⏱️ UPTIME\n${output.uptime || 'N/A'}\n\n`;
1156
+ formattedOutput += `💻 CPU\n${output.cpu || 'N/A'}\n\n`;
1157
+ formattedOutput += `📈 LOAD AVERAGE\n${output.load || 'N/A'}\n\n`;
1158
+ formattedOutput += `💾 MEMORY\n${output.memory || 'N/A'}\n\n`;
1159
+ formattedOutput += `💿 DISK USAGE\n${output.disk || 'N/A'}\n\n`;
1160
+ formattedOutput += `📝 PROCESSES: ${output.processes || 'N/A'}\n`;
1161
+ break;
1162
+
1163
+ case 'cpu':
1164
+ formattedOutput += `🖥️ CPU CORES: ${output.cores || 'N/A'}\n\n`;
1165
+ formattedOutput += `📊 LOAD\n${output.load || 'N/A'}\n\n`;
1166
+ formattedOutput += `📈 TOP PROCESSES\n${output.cpu || 'N/A'}\n`;
1167
+ break;
1168
+
1169
+ case 'memory':
1170
+ formattedOutput += `💾 MEMORY USAGE\n${output.memory || 'N/A'}\n\n`;
1171
+ formattedOutput += `🔄 SWAP\n${output.swap || 'No swap configured'}\n\n`;
1172
+ formattedOutput += `📊 TOP MEMORY CONSUMERS\n${output.top_mem || 'N/A'}\n`;
1173
+ break;
1174
+
1175
+ case 'disk':
1176
+ formattedOutput += `💿 DISK SPACE\n${output.disk || 'N/A'}\n\n`;
1177
+ formattedOutput += `📁 INODE USAGE\n${output.inodes || 'N/A'}\n\n`;
1178
+ formattedOutput += `⚡ I/O STATS\n${output.io || 'N/A'}\n`;
1179
+ break;
1180
+
1181
+ case 'network':
1182
+ formattedOutput += `🌐 NETWORK INTERFACES\n${output.interfaces || 'N/A'}\n\n`;
1183
+ formattedOutput += `🔌 CONNECTIONS\n${output.connections || 'N/A'}\n\n`;
1184
+ formattedOutput += `📊 INTERFACE STATS\n${output.netstat || 'N/A'}\n`;
1185
+ break;
1186
+
1187
+ case 'process':
1188
+ formattedOutput += `📝 PROCESS COUNT: ${output.count || 'N/A'}\n`;
1189
+ formattedOutput += `⚠️ ZOMBIE PROCESSES: ${output.zombies || '0'}\n\n`;
1190
+ formattedOutput += `📊 TOP PROCESSES BY CPU\n${output.process || 'N/A'}\n`;
1191
+ break;
1162
1192
  }
1163
-
1193
+
1164
1194
  // Log monitoring results
1165
1195
  logger.info(`System monitoring completed on ${serverName}`, {
1166
1196
  type,
1167
1197
  duration: `${monitoringDuration}ms`,
1168
1198
  metrics: Object.keys(output).length
1169
1199
  });
1170
-
1200
+
1171
1201
  // If continuous monitoring requested
1172
1202
  if (interval && duration) {
1173
1203
  formattedOutput += `\n\n⏰ Continuous monitoring: Every ${interval}s for ${duration}s\n`;
1174
- formattedOutput += `(Not implemented in this version - would require streaming support)`;
1204
+ formattedOutput += '(Not implemented in this version - would require streaming support)';
1175
1205
  }
1176
-
1206
+
1177
1207
  return {
1178
1208
  content: [
1179
1209
  {
@@ -1187,7 +1217,7 @@ server.registerTool(
1187
1217
  type,
1188
1218
  error: error.message
1189
1219
  });
1190
-
1220
+
1191
1221
  return {
1192
1222
  content: [
1193
1223
  {
@@ -1200,7 +1230,7 @@ server.registerTool(
1200
1230
  }
1201
1231
  );
1202
1232
 
1203
- server.registerTool(
1233
+ registerToolConditional(
1204
1234
  'ssh_history',
1205
1235
  {
1206
1236
  description: 'View SSH command history',
@@ -1215,38 +1245,38 @@ server.registerTool(
1215
1245
  try {
1216
1246
  // Get history from logger
1217
1247
  let history = logger.getHistory(limit * 2); // Get more to account for filtering
1218
-
1248
+
1219
1249
  // Apply filters
1220
1250
  if (server) {
1221
1251
  history = history.filter(h => h.server?.toLowerCase().includes(server.toLowerCase()));
1222
1252
  }
1223
-
1253
+
1224
1254
  if (success !== undefined) {
1225
1255
  history = history.filter(h => h.success === success);
1226
1256
  }
1227
-
1257
+
1228
1258
  if (search) {
1229
1259
  history = history.filter(h => h.command?.toLowerCase().includes(search.toLowerCase()));
1230
1260
  }
1231
-
1261
+
1232
1262
  // Limit results
1233
1263
  history = history.slice(-limit);
1234
-
1264
+
1235
1265
  // Format output
1236
- let output = `📜 SSH Command History\n`;
1266
+ let output = '📜 SSH Command History\n';
1237
1267
  output += `Showing last ${history.length} commands`;
1238
-
1268
+
1239
1269
  const filters = [];
1240
1270
  if (server) filters.push(`server: ${server}`);
1241
1271
  if (success !== undefined) filters.push(success ? 'successful only' : 'failed only');
1242
1272
  if (search) filters.push(`search: ${search}`);
1243
-
1273
+
1244
1274
  if (filters.length > 0) {
1245
1275
  output += ` (filtered: ${filters.join(', ')})`;
1246
1276
  }
1247
-
1277
+
1248
1278
  output += '\n' + '━'.repeat(60) + '\n\n';
1249
-
1279
+
1250
1280
  if (history.length === 0) {
1251
1281
  output += 'No commands found matching the criteria.\n';
1252
1282
  } else {
@@ -1254,7 +1284,7 @@ server.registerTool(
1254
1284
  const time = new Date(entry.timestamp).toLocaleString();
1255
1285
  const status = entry.success ? '✅' : '❌';
1256
1286
  const duration = entry.duration || 'N/A';
1257
-
1287
+
1258
1288
  output += `${history.length - index}. ${status} [${time}]\n`;
1259
1289
  output += ` Server: ${entry.server || 'unknown'}\n`;
1260
1290
  output += ` Command: ${entry.command?.substring(0, 100) || 'N/A'}`;
@@ -1263,24 +1293,24 @@ server.registerTool(
1263
1293
  }
1264
1294
  output += '\n';
1265
1295
  output += ` Duration: ${duration}`;
1266
-
1296
+
1267
1297
  if (!entry.success && entry.error) {
1268
1298
  output += `\n Error: ${entry.error}`;
1269
1299
  }
1270
-
1300
+
1271
1301
  output += '\n\n';
1272
1302
  });
1273
1303
  }
1274
-
1304
+
1275
1305
  output += '━'.repeat(60) + '\n';
1276
1306
  output += `Total commands in history: ${logger.getHistory(1000).length}\n`;
1277
-
1307
+
1278
1308
  logger.info('Command history retrieved', {
1279
1309
  limit,
1280
1310
  filters: filters.length,
1281
1311
  results: history.length
1282
1312
  });
1283
-
1313
+
1284
1314
  return {
1285
1315
  content: [
1286
1316
  {
@@ -1304,7 +1334,7 @@ server.registerTool(
1304
1334
 
1305
1335
  // SSH Session Management Tools
1306
1336
 
1307
- server.registerTool(
1337
+ registerToolConditional(
1308
1338
  'ssh_session_start',
1309
1339
  {
1310
1340
  description: 'Start a persistent SSH session that maintains state and context',
@@ -1317,15 +1347,15 @@ server.registerTool(
1317
1347
  try {
1318
1348
  const ssh = await getConnection(serverName);
1319
1349
  const session = await createSession(serverName, ssh);
1320
-
1350
+
1321
1351
  const sessionName = name || `Session on ${serverName}`;
1322
-
1352
+
1323
1353
  logger.info('SSH session started', {
1324
1354
  id: session.id,
1325
1355
  server: serverName,
1326
1356
  name: sessionName
1327
1357
  });
1328
-
1358
+
1329
1359
  return {
1330
1360
  content: [
1331
1361
  {
@@ -1339,7 +1369,7 @@ server.registerTool(
1339
1369
  server: serverName,
1340
1370
  error: error.message
1341
1371
  });
1342
-
1372
+
1343
1373
  return {
1344
1374
  content: [
1345
1375
  {
@@ -1352,7 +1382,7 @@ server.registerTool(
1352
1382
  }
1353
1383
  );
1354
1384
 
1355
- server.registerTool(
1385
+ registerToolConditional(
1356
1386
  'ssh_session_send',
1357
1387
  {
1358
1388
  description: 'Send a command to an existing SSH session',
@@ -1365,36 +1395,36 @@ server.registerTool(
1365
1395
  async ({ session: sessionId, command, timeout = 30000 }) => {
1366
1396
  try {
1367
1397
  const session = getSession(sessionId);
1368
-
1398
+
1369
1399
  const startTime = Date.now();
1370
1400
  const result = await session.execute(command, { timeout });
1371
1401
  const duration = Date.now() - startTime;
1372
-
1402
+
1373
1403
  logger.info('Session command executed', {
1374
1404
  session: sessionId,
1375
1405
  command: command.substring(0, 50),
1376
1406
  success: result.success,
1377
1407
  duration: `${duration}ms`
1378
1408
  });
1379
-
1409
+
1380
1410
  let output = `📟 Session: ${sessionId}\n`;
1381
1411
  output += `Server: ${session.serverName}\n`;
1382
1412
  output += `Working Directory: ${session.context.cwd}\n`;
1383
1413
  output += `Command: ${command}\n`;
1384
1414
  output += `Duration: ${duration}ms\n`;
1385
1415
  output += '━'.repeat(60) + '\n\n';
1386
-
1416
+
1387
1417
  if (result.success) {
1388
1418
  output += '✅ Output:\n' + result.output;
1389
1419
  } else {
1390
1420
  output += '❌ Error:\n' + (result.error || result.output);
1391
1421
  }
1392
-
1422
+
1393
1423
  // Add session state info
1394
1424
  output += '\n\n' + '━'.repeat(60) + '\n';
1395
1425
  output += `Session State: ${session.state}\n`;
1396
1426
  output += `Commands Executed: ${session.context.history.length}\n`;
1397
-
1427
+
1398
1428
  return {
1399
1429
  content: [
1400
1430
  {
@@ -1409,7 +1439,7 @@ server.registerTool(
1409
1439
  command,
1410
1440
  error: error.message
1411
1441
  });
1412
-
1442
+
1413
1443
  return {
1414
1444
  content: [
1415
1445
  {
@@ -1422,7 +1452,7 @@ server.registerTool(
1422
1452
  }
1423
1453
  );
1424
1454
 
1425
- server.registerTool(
1455
+ registerToolConditional(
1426
1456
  'ssh_session_list',
1427
1457
  {
1428
1458
  description: 'List all active SSH sessions',
@@ -1433,17 +1463,17 @@ server.registerTool(
1433
1463
  async ({ server }) => {
1434
1464
  try {
1435
1465
  let sessions = listSessions();
1436
-
1466
+
1437
1467
  // Filter by server if specified
1438
1468
  if (server) {
1439
- sessions = sessions.filter(s =>
1469
+ sessions = sessions.filter(s =>
1440
1470
  s.server.toLowerCase().includes(server.toLowerCase())
1441
1471
  );
1442
1472
  }
1443
-
1444
- let output = `📋 Active SSH Sessions\n`;
1473
+
1474
+ let output = '📋 Active SSH Sessions\n';
1445
1475
  output += '━'.repeat(60) + '\n\n';
1446
-
1476
+
1447
1477
  if (sessions.length === 0) {
1448
1478
  output += 'No active sessions';
1449
1479
  if (server) {
@@ -1454,7 +1484,7 @@ server.registerTool(
1454
1484
  sessions.forEach((session, index) => {
1455
1485
  const age = Math.floor((Date.now() - new Date(session.created).getTime()) / 1000);
1456
1486
  const idle = Math.floor((Date.now() - new Date(session.lastActivity).getTime()) / 1000);
1457
-
1487
+
1458
1488
  output += `${index + 1}. Session: ${session.id}\n`;
1459
1489
  output += ` Server: ${session.server}\n`;
1460
1490
  output += ` State: ${session.state}\n`;
@@ -1462,23 +1492,23 @@ server.registerTool(
1462
1492
  output += ` Commands Run: ${session.historyCount}\n`;
1463
1493
  output += ` Age: ${formatDuration(age)}\n`;
1464
1494
  output += ` Idle: ${formatDuration(idle)}\n`;
1465
-
1495
+
1466
1496
  if (session.variables.length > 0) {
1467
1497
  output += ` Variables: ${session.variables.join(', ')}\n`;
1468
1498
  }
1469
-
1499
+
1470
1500
  output += '\n';
1471
1501
  });
1472
1502
  }
1473
-
1503
+
1474
1504
  output += '━'.repeat(60) + '\n';
1475
1505
  output += `Total Active Sessions: ${sessions.length}\n`;
1476
-
1506
+
1477
1507
  logger.info('Listed SSH sessions', {
1478
1508
  total: sessions.length,
1479
1509
  filter: server
1480
1510
  });
1481
-
1511
+
1482
1512
  return {
1483
1513
  content: [
1484
1514
  {
@@ -1500,7 +1530,7 @@ server.registerTool(
1500
1530
  }
1501
1531
  );
1502
1532
 
1503
- server.registerTool(
1533
+ registerToolConditional(
1504
1534
  'ssh_session_close',
1505
1535
  {
1506
1536
  description: 'Close an SSH session',
@@ -1513,7 +1543,7 @@ server.registerTool(
1513
1543
  if (sessionId === 'all') {
1514
1544
  const sessions = listSessions();
1515
1545
  const count = sessions.length;
1516
-
1546
+
1517
1547
  sessions.forEach(s => {
1518
1548
  try {
1519
1549
  closeSession(s.id);
@@ -1521,9 +1551,9 @@ server.registerTool(
1521
1551
  // Ignore individual close errors
1522
1552
  }
1523
1553
  });
1524
-
1554
+
1525
1555
  logger.info('Closed all SSH sessions', { count });
1526
-
1556
+
1527
1557
  return {
1528
1558
  content: [
1529
1559
  {
@@ -1534,9 +1564,9 @@ server.registerTool(
1534
1564
  };
1535
1565
  } else {
1536
1566
  closeSession(sessionId);
1537
-
1567
+
1538
1568
  logger.info('SSH session closed', { session: sessionId });
1539
-
1569
+
1540
1570
  return {
1541
1571
  content: [
1542
1572
  {
@@ -1551,7 +1581,7 @@ server.registerTool(
1551
1581
  session: sessionId,
1552
1582
  error: error.message
1553
1583
  });
1554
-
1584
+
1555
1585
  return {
1556
1586
  content: [
1557
1587
  {
@@ -1577,7 +1607,7 @@ function formatDuration(seconds) {
1577
1607
 
1578
1608
  // Server Group Management Tools
1579
1609
 
1580
- server.registerTool(
1610
+ registerToolConditional(
1581
1611
  'ssh_execute_group',
1582
1612
  {
1583
1613
  description: 'Execute command on a group of servers',
@@ -1597,15 +1627,15 @@ server.registerTool(
1597
1627
  groupName,
1598
1628
  async (serverName) => {
1599
1629
  const ssh = await getConnection(serverName);
1600
-
1630
+
1601
1631
  // Build full command with cwd if provided
1602
1632
  const servers = loadServerConfig();
1603
1633
  const serverConfig = servers[serverName.toLowerCase()];
1604
1634
  const workingDir = cwd || serverConfig?.default_dir;
1605
1635
  const fullCommand = workingDir ? `cd ${workingDir} && ${command}` : command;
1606
-
1636
+
1607
1637
  const execResult = await execCommandWithTimeout(ssh, fullCommand, {}, 30000);
1608
-
1638
+
1609
1639
  return {
1610
1640
  stdout: execResult.stdout,
1611
1641
  stderr: execResult.stderr,
@@ -1615,17 +1645,17 @@ server.registerTool(
1615
1645
  },
1616
1646
  { strategy, delay, stopOnError }
1617
1647
  );
1618
-
1648
+
1619
1649
  // Format output
1620
1650
  let output = `🚀 Group Execution: ${groupName}\n`;
1621
1651
  output += `Command: ${command}\n`;
1622
1652
  output += `Strategy: ${result.strategy}\n`;
1623
1653
  output += '━'.repeat(60) + '\n\n';
1624
-
1654
+
1625
1655
  // Show results for each server
1626
1656
  result.results.forEach(({ server, success, result: execResult, error }) => {
1627
1657
  output += `📍 ${server}: ${success ? '✅ SUCCESS' : '❌ FAILED'}\n`;
1628
-
1658
+
1629
1659
  if (success && execResult) {
1630
1660
  if (execResult.stdout) {
1631
1661
  output += ` Output: ${execResult.stdout.substring(0, 200)}`;
@@ -1640,7 +1670,7 @@ server.registerTool(
1640
1670
  }
1641
1671
  output += '\n';
1642
1672
  });
1643
-
1673
+
1644
1674
  // Summary
1645
1675
  output += '━'.repeat(60) + '\n';
1646
1676
  output += `Summary: ${result.summary.successful}/${result.summary.total} successful`;
@@ -1648,13 +1678,13 @@ server.registerTool(
1648
1678
  output += ` (${result.summary.failed} failed)`;
1649
1679
  }
1650
1680
  output += '\n';
1651
-
1681
+
1652
1682
  logger.info('Group command executed', {
1653
1683
  group: groupName,
1654
1684
  command: command.substring(0, 50),
1655
1685
  ...result.summary
1656
1686
  });
1657
-
1687
+
1658
1688
  return {
1659
1689
  content: [
1660
1690
  {
@@ -1668,7 +1698,7 @@ server.registerTool(
1668
1698
  group: groupName,
1669
1699
  error: error.message
1670
1700
  });
1671
-
1701
+
1672
1702
  return {
1673
1703
  content: [
1674
1704
  {
@@ -1681,7 +1711,7 @@ server.registerTool(
1681
1711
  }
1682
1712
  );
1683
1713
 
1684
- server.registerTool(
1714
+ registerToolConditional(
1685
1715
  'ssh_group_manage',
1686
1716
  {
1687
1717
  description: 'Manage server groups (create, update, delete, list)',
@@ -1699,94 +1729,95 @@ server.registerTool(
1699
1729
  try {
1700
1730
  let result;
1701
1731
  let output = '';
1702
-
1732
+
1703
1733
  switch (action) {
1704
- case 'create':
1705
- if (!name) throw new Error('Group name required for create');
1706
- result = createGroup(name, servers || [], {
1707
- description,
1708
- strategy,
1709
- delay,
1710
- stopOnError
1711
- });
1712
- output = `✅ Group '${name}' created\n`;
1713
- output += `Servers: ${result.servers.join(', ') || 'none'}\n`;
1714
- output += `Strategy: ${result.strategy}\n`;
1715
- break;
1716
-
1717
- case 'update':
1718
- if (!name) throw new Error('Group name required for update');
1719
- result = updateGroup(name, {
1720
- servers,
1721
- description,
1722
- strategy,
1723
- delay,
1724
- stopOnError
1725
- });
1726
- output = `✅ Group '${name}' updated\n`;
1727
- output += `Servers: ${result.servers.join(', ')}\n`;
1728
- break;
1729
-
1730
- case 'delete':
1731
- if (!name) throw new Error('Group name required for delete');
1732
- deleteGroup(name);
1733
- output = `✅ Group '${name}' deleted`;
1734
- break;
1735
-
1736
- case 'add-servers':
1737
- if (!name) throw new Error('Group name required');
1738
- if (!servers || servers.length === 0) throw new Error('Servers required');
1739
- result = addServersToGroup(name, servers);
1740
- output = `✅ Added ${servers.length} servers to '${name}'\n`;
1741
- output += `Total servers: ${result.servers.length}\n`;
1742
- output += `Members: ${result.servers.join(', ')}`;
1743
- break;
1744
-
1745
- case 'remove-servers':
1746
- if (!name) throw new Error('Group name required');
1747
- if (!servers || servers.length === 0) throw new Error('Servers required');
1748
- result = removeServersFromGroup(name, servers);
1749
- output = `✅ Removed ${servers.length} servers from '${name}'\n`;
1750
- output += `Remaining: ${result.servers.length}\n`;
1751
- output += `Members: ${result.servers.join(', ') || 'none'}`;
1752
- break;
1753
-
1754
- case 'list':
1755
- const groups = listGroups();
1756
- output = `📋 Server Groups\n`;
1757
- output += '━'.repeat(60) + '\n\n';
1758
-
1759
- groups.forEach(group => {
1760
- output += `📁 ${group.name}`;
1761
- if (group.dynamic) output += ' (dynamic)';
1762
- output += '\n';
1763
- output += ` Description: ${group.description}\n`;
1764
- output += ` Servers: ${group.serverCount} servers\n`;
1765
- if (group.servers.length > 0) {
1766
- output += ` Members: ${group.servers.slice(0, 5).join(', ')}`;
1767
- if (group.servers.length > 5) output += ` ... +${group.servers.length - 5} more`;
1768
- output += '\n';
1769
- }
1770
- output += ` Strategy: ${group.strategy || 'parallel'}\n`;
1771
- if (group.delay) output += ` Delay: ${group.delay}ms\n`;
1772
- if (group.stopOnError) output += ` Stop on error: yes\n`;
1734
+ case 'create':
1735
+ if (!name) throw new Error('Group name required for create');
1736
+ result = createGroup(name, servers || [], {
1737
+ description,
1738
+ strategy,
1739
+ delay,
1740
+ stopOnError
1741
+ });
1742
+ output = `✅ Group '${name}' created\n`;
1743
+ output += `Servers: ${result.servers.join(', ') || 'none'}\n`;
1744
+ output += `Strategy: ${result.strategy}\n`;
1745
+ break;
1746
+
1747
+ case 'update':
1748
+ if (!name) throw new Error('Group name required for update');
1749
+ result = updateGroup(name, {
1750
+ servers,
1751
+ description,
1752
+ strategy,
1753
+ delay,
1754
+ stopOnError
1755
+ });
1756
+ output = `✅ Group '${name}' updated\n`;
1757
+ output += `Servers: ${result.servers.join(', ')}\n`;
1758
+ break;
1759
+
1760
+ case 'delete':
1761
+ if (!name) throw new Error('Group name required for delete');
1762
+ deleteGroup(name);
1763
+ output = `✅ Group '${name}' deleted`;
1764
+ break;
1765
+
1766
+ case 'add-servers':
1767
+ if (!name) throw new Error('Group name required');
1768
+ if (!servers || servers.length === 0) throw new Error('Servers required');
1769
+ result = addServersToGroup(name, servers);
1770
+ output = `✅ Added ${servers.length} servers to '${name}'\n`;
1771
+ output += `Total servers: ${result.servers.length}\n`;
1772
+ output += `Members: ${result.servers.join(', ')}`;
1773
+ break;
1774
+
1775
+ case 'remove-servers':
1776
+ if (!name) throw new Error('Group name required');
1777
+ if (!servers || servers.length === 0) throw new Error('Servers required');
1778
+ result = removeServersFromGroup(name, servers);
1779
+ output = `✅ Removed ${servers.length} servers from '${name}'\n`;
1780
+ output += `Remaining: ${result.servers.length}\n`;
1781
+ output += `Members: ${result.servers.join(', ') || 'none'}`;
1782
+ break;
1783
+
1784
+ case 'list': {
1785
+ const groups = listGroups();
1786
+ output = '📋 Server Groups\n';
1787
+ output += '━'.repeat(60) + '\n\n';
1788
+
1789
+ groups.forEach(group => {
1790
+ output += `📁 ${group.name}`;
1791
+ if (group.dynamic) output += ' (dynamic)';
1792
+ output += '\n';
1793
+ output += ` Description: ${group.description}\n`;
1794
+ output += ` Servers: ${group.serverCount} servers\n`;
1795
+ if (group.servers.length > 0) {
1796
+ output += ` Members: ${group.servers.slice(0, 5).join(', ')}`;
1797
+ if (group.servers.length > 5) output += ` ... +${group.servers.length - 5} more`;
1773
1798
  output += '\n';
1774
- });
1775
-
1776
- output += '━'.repeat(60) + '\n';
1777
- output += `Total groups: ${groups.length}`;
1778
- break;
1779
-
1780
- default:
1781
- throw new Error(`Unknown action: ${action}`);
1799
+ }
1800
+ output += ` Strategy: ${group.strategy || 'parallel'}\n`;
1801
+ if (group.delay) output += ` Delay: ${group.delay}ms\n`;
1802
+ if (group.stopOnError) output += ' Stop on error: yes\n';
1803
+ output += '\n';
1804
+ });
1805
+
1806
+ output += '━'.repeat(60) + '\n';
1807
+ output += `Total groups: ${groups.length}`;
1808
+ break;
1782
1809
  }
1783
-
1810
+
1811
+ default:
1812
+ throw new Error(`Unknown action: ${action}`);
1813
+ }
1814
+
1784
1815
  logger.info('Group management action completed', {
1785
1816
  action,
1786
1817
  name,
1787
1818
  servers: servers?.length
1788
1819
  });
1789
-
1820
+
1790
1821
  return {
1791
1822
  content: [
1792
1823
  {
@@ -1801,7 +1832,7 @@ server.registerTool(
1801
1832
  name,
1802
1833
  error: error.message
1803
1834
  });
1804
-
1835
+
1805
1836
  return {
1806
1837
  content: [
1807
1838
  {
@@ -1814,7 +1845,7 @@ server.registerTool(
1814
1845
  }
1815
1846
  );
1816
1847
 
1817
- server.registerTool(
1848
+ registerToolConditional(
1818
1849
  'ssh_list_servers',
1819
1850
  {
1820
1851
  description: 'List all configured SSH servers',
@@ -1844,7 +1875,7 @@ server.registerTool(
1844
1875
  );
1845
1876
 
1846
1877
  // New deploy tool for automated deployment
1847
- server.registerTool(
1878
+ registerToolConditional(
1848
1879
  'ssh_deploy',
1849
1880
  {
1850
1881
  description: 'Deploy files to remote server with automatic permission handling',
@@ -1945,7 +1976,7 @@ server.registerTool(
1945
1976
  );
1946
1977
 
1947
1978
  // Execute command with sudo support
1948
- server.registerTool(
1979
+ registerToolConditional(
1949
1980
  'ssh_execute_sudo',
1950
1981
  {
1951
1982
  description: 'Execute command with sudo on remote server',
@@ -2014,7 +2045,7 @@ server.registerTool(
2014
2045
  );
2015
2046
 
2016
2047
  // Manage command aliases
2017
- server.registerTool(
2048
+ registerToolConditional(
2018
2049
  'ssh_command_alias',
2019
2050
  {
2020
2051
  description: 'Manage command aliases for frequently used commands',
@@ -2115,7 +2146,7 @@ server.registerTool(
2115
2146
  );
2116
2147
 
2117
2148
  // Manage hooks
2118
- server.registerTool(
2149
+ registerToolConditional(
2119
2150
  'ssh_hooks',
2120
2151
  {
2121
2152
  description: 'Manage automation hooks for SSH operations',
@@ -2207,7 +2238,7 @@ server.registerTool(
2207
2238
  );
2208
2239
 
2209
2240
  // Manage profiles
2210
- server.registerTool(
2241
+ registerToolConditional(
2211
2242
  'ssh_profile',
2212
2243
  {
2213
2244
  description: 'Manage SSH Manager profiles for different project types',
@@ -2287,7 +2318,7 @@ server.registerTool(
2287
2318
  );
2288
2319
 
2289
2320
  // Connection management tool
2290
- server.registerTool(
2321
+ registerToolConditional(
2291
2322
  'ssh_connection_status',
2292
2323
  {
2293
2324
  description: 'Check status of SSH connections and manage connection pool',
@@ -2404,7 +2435,7 @@ server.registerTool(
2404
2435
  );
2405
2436
 
2406
2437
  // SSH Tunnel Management - Create tunnel
2407
- server.registerTool(
2438
+ registerToolConditional(
2408
2439
  'ssh_tunnel_create',
2409
2440
  {
2410
2441
  description: 'Create SSH tunnel (port forwarding or SOCKS proxy)',
@@ -2421,13 +2452,15 @@ server.registerTool(
2421
2452
  try {
2422
2453
  const servers = loadServerConfig();
2423
2454
  const resolvedName = resolveServerName(server, servers);
2424
-
2455
+
2425
2456
  if (!resolvedName) {
2426
2457
  throw new Error(`Server "${server}" not found`);
2427
2458
  }
2428
-
2429
- const ssh = await getSSHConnection(resolvedName);
2430
-
2459
+
2460
+ const serverConfig = servers[resolvedName];
2461
+ const ssh = new SSHManager(serverConfig);
2462
+ await ssh.connect();
2463
+
2431
2464
  const config = {
2432
2465
  type,
2433
2466
  localHost: localHost || '127.0.0.1',
@@ -2435,14 +2468,14 @@ server.registerTool(
2435
2468
  remoteHost,
2436
2469
  remotePort
2437
2470
  };
2438
-
2471
+
2439
2472
  const tunnel = await createTunnel(resolvedName, ssh, config);
2440
-
2441
- let output = `✅ SSH tunnel created\n`;
2473
+
2474
+ let output = '✅ SSH tunnel created\n';
2442
2475
  output += `ID: ${tunnel.id}\n`;
2443
2476
  output += `Type: ${type}\n`;
2444
2477
  output += `Local: ${config.localHost}:${localPort}\n`;
2445
-
2478
+
2446
2479
  if (type === 'local') {
2447
2480
  output += `Remote: ${remoteHost}:${remotePort}\n`;
2448
2481
  output += `\n📌 Access remote ${remoteHost}:${remotePort} via local ${config.localHost}:${localPort}`;
@@ -2454,14 +2487,14 @@ server.registerTool(
2454
2487
  output += `\n📌 SOCKS5 proxy available at ${config.localHost}:${localPort}`;
2455
2488
  output += `\n💡 Configure browser/app: SOCKS5 proxy ${config.localHost}:${localPort}`;
2456
2489
  }
2457
-
2490
+
2458
2491
  logger.info('SSH tunnel created', {
2459
2492
  id: tunnel.id,
2460
2493
  server: resolvedName,
2461
2494
  type,
2462
2495
  local: `${config.localHost}:${localPort}`
2463
2496
  });
2464
-
2497
+
2465
2498
  return {
2466
2499
  content: [
2467
2500
  {
@@ -2485,7 +2518,7 @@ server.registerTool(
2485
2518
  );
2486
2519
 
2487
2520
  // List active tunnels
2488
- server.registerTool(
2521
+ registerToolConditional(
2489
2522
  'ssh_tunnel_list',
2490
2523
  {
2491
2524
  description: 'List active SSH tunnels',
@@ -2497,16 +2530,16 @@ server.registerTool(
2497
2530
  try {
2498
2531
  const servers = loadServerConfig();
2499
2532
  let resolvedName = null;
2500
-
2533
+
2501
2534
  if (server) {
2502
2535
  resolvedName = resolveServerName(server, servers);
2503
2536
  if (!resolvedName) {
2504
2537
  throw new Error(`Server "${server}" not found`);
2505
2538
  }
2506
2539
  }
2507
-
2540
+
2508
2541
  const tunnels = listTunnels(resolvedName);
2509
-
2542
+
2510
2543
  if (tunnels.length === 0) {
2511
2544
  return {
2512
2545
  content: [
@@ -2517,21 +2550,21 @@ server.registerTool(
2517
2550
  ]
2518
2551
  };
2519
2552
  }
2520
-
2521
- let output = `📋 Active SSH Tunnels\n`;
2553
+
2554
+ let output = '📋 Active SSH Tunnels\n';
2522
2555
  output += '━'.repeat(60) + '\n\n';
2523
-
2556
+
2524
2557
  tunnels.forEach(tunnel => {
2525
2558
  output += `🔧 ${tunnel.id}\n`;
2526
2559
  output += ` Server: ${tunnel.server}\n`;
2527
2560
  output += ` Type: ${tunnel.type}\n`;
2528
2561
  output += ` State: ${tunnel.state}\n`;
2529
2562
  output += ` Local: ${tunnel.config.localHost}:${tunnel.config.localPort}\n`;
2530
-
2563
+
2531
2564
  if (tunnel.type !== 'dynamic') {
2532
2565
  output += ` Remote: ${tunnel.config.remoteHost}:${tunnel.config.remotePort}\n`;
2533
2566
  }
2534
-
2567
+
2535
2568
  output += ` Active connections: ${tunnel.activeConnections}\n`;
2536
2569
  output += ` Total connections: ${tunnel.stats.connectionsTotal}\n`;
2537
2570
  output += ` Bytes transferred: ${(tunnel.stats.bytesTransferred / 1024).toFixed(2)} KB\n`;
@@ -2540,10 +2573,10 @@ server.registerTool(
2540
2573
  output += ` Last activity: ${new Date(tunnel.lastActivity).toLocaleString()}\n`;
2541
2574
  output += '\n';
2542
2575
  });
2543
-
2576
+
2544
2577
  output += '━'.repeat(60) + '\n';
2545
2578
  output += `Total tunnels: ${tunnels.length}`;
2546
-
2579
+
2547
2580
  return {
2548
2581
  content: [
2549
2582
  {
@@ -2567,7 +2600,7 @@ server.registerTool(
2567
2600
  );
2568
2601
 
2569
2602
  // Close a tunnel
2570
- server.registerTool(
2603
+ registerToolConditional(
2571
2604
  'ssh_tunnel_close',
2572
2605
  {
2573
2606
  description: 'Close an SSH tunnel',
@@ -2581,33 +2614,33 @@ server.registerTool(
2581
2614
  if (!tunnelId && !server) {
2582
2615
  throw new Error('Either tunnelId or server must be specified');
2583
2616
  }
2584
-
2617
+
2585
2618
  let output = '';
2586
-
2619
+
2587
2620
  if (tunnelId) {
2588
2621
  // Close specific tunnel
2589
2622
  closeTunnel(tunnelId);
2590
2623
  output = `✅ Tunnel ${tunnelId} closed`;
2591
-
2624
+
2592
2625
  logger.info('SSH tunnel closed', { id: tunnelId });
2593
2626
  } else if (server) {
2594
2627
  // Close all tunnels for server
2595
2628
  const servers = loadServerConfig();
2596
2629
  const resolvedName = resolveServerName(server, servers);
2597
-
2630
+
2598
2631
  if (!resolvedName) {
2599
2632
  throw new Error(`Server "${server}" not found`);
2600
2633
  }
2601
-
2634
+
2602
2635
  const count = closeServerTunnels(resolvedName);
2603
2636
  output = `✅ Closed ${count} tunnel(s) for server ${resolvedName}`;
2604
-
2637
+
2605
2638
  logger.info('Server tunnels closed', {
2606
2639
  server: resolvedName,
2607
2640
  count
2608
2641
  });
2609
2642
  }
2610
-
2643
+
2611
2644
  return {
2612
2645
  content: [
2613
2646
  {
@@ -2631,7 +2664,7 @@ server.registerTool(
2631
2664
  );
2632
2665
 
2633
2666
  // Manage SSH host keys
2634
- server.registerTool(
2667
+ registerToolConditional(
2635
2668
  'ssh_key_manage',
2636
2669
  {
2637
2670
  description: 'Manage SSH host keys for security verification',
@@ -2658,207 +2691,207 @@ server.registerTool(
2658
2691
  }
2659
2692
 
2660
2693
  switch (action) {
2661
- case 'verify': {
2662
- // Check if host key has changed
2663
- const verification = await hasHostKeyChanged(host, port);
2664
-
2665
- if (verification.changed) {
2666
- // Execute pre-connect-key-change hook
2667
- await executeHook('pre-connect-key-change', {
2668
- server: resolvedName,
2669
- host,
2670
- port,
2671
- currentFingerprints: verification.currentFingerprints,
2672
- newFingerprints: verification.newFingerprints
2673
- });
2694
+ case 'verify': {
2695
+ // Check if host key has changed
2696
+ const verification = await hasHostKeyChanged(host, port);
2697
+
2698
+ if (verification.changed) {
2699
+ // Execute pre-connect-key-change hook
2700
+ await executeHook('pre-connect-key-change', {
2701
+ server: resolvedName,
2702
+ host,
2703
+ port,
2704
+ currentFingerprints: verification.currentFingerprints,
2705
+ newFingerprints: verification.newFingerprints
2706
+ });
2674
2707
 
2675
- let output = `⚠️ SSH host key has changed for ${server} (${host}:${port})\n\n`;
2676
- output += `Current fingerprints:\n`;
2677
- verification.currentFingerprints.forEach(fp => {
2678
- output += ` ${fp}\n`;
2679
- });
2680
- output += `\nNew fingerprints:\n`;
2681
- verification.newFingerprints.forEach(fp => {
2682
- output += ` ${fp}\n`;
2683
- });
2684
- output += `\n⚠️ This could indicate a security issue or server reinstallation.\n`;
2685
- output += `Use 'ssh_key_manage' with action 'accept' to update the key if you trust this change.`;
2686
-
2687
- return {
2688
- content: [
2689
- {
2690
- type: 'text',
2691
- text: output
2692
- }
2693
- ]
2694
- };
2695
- } else {
2696
- let output = `✅ SSH host key verified for ${server} (${host}:${port})\n`;
2697
- output += `Reason: ${verification.reason}\n`;
2708
+ let output = `⚠️ SSH host key has changed for ${server} (${host}:${port})\n\n`;
2709
+ output += 'Current fingerprints:\n';
2710
+ verification.currentFingerprints.forEach(fp => {
2711
+ output += ` ${fp}\n`;
2712
+ });
2713
+ output += '\nNew fingerprints:\n';
2714
+ verification.newFingerprints.forEach(fp => {
2715
+ output += ` ${fp}\n`;
2716
+ });
2717
+ output += '\n⚠️ This could indicate a security issue or server reinstallation.\n';
2718
+ output += 'Use \'ssh_key_manage\' with action \'accept\' to update the key if you trust this change.';
2698
2719
 
2699
- if (verification.reason === 'not_in_known_hosts') {
2700
- output += `\nℹ️ Host not in known_hosts. Use 'accept' action to add it.`;
2701
- }
2720
+ return {
2721
+ content: [
2722
+ {
2723
+ type: 'text',
2724
+ text: output
2725
+ }
2726
+ ]
2727
+ };
2728
+ } else {
2729
+ let output = `✅ SSH host key verified for ${server} (${host}:${port})\n`;
2730
+ output += `Reason: ${verification.reason}\n`;
2702
2731
 
2703
- return {
2704
- content: [
2705
- {
2706
- type: 'text',
2707
- text: output
2708
- }
2709
- ]
2710
- };
2732
+ if (verification.reason === 'not_in_known_hosts') {
2733
+ output += '\nℹ️ Host not in known_hosts. Use \'accept\' action to add it.';
2711
2734
  }
2712
- }
2713
-
2714
- case 'accept': {
2715
- // Check if key exists
2716
- const isKnown = isHostKnown(host, port);
2717
2735
 
2718
- if (isKnown) {
2719
- // Update existing key
2720
- await updateHostKey(host, port);
2721
-
2722
- // Execute post-key-update hook
2723
- await executeHook('post-key-update', {
2724
- server: resolvedName,
2725
- host,
2726
- port,
2727
- action: 'updated'
2728
- });
2729
-
2730
- logger.info('SSH host key updated', { server: resolvedName, host, port });
2731
-
2732
- return {
2733
- content: [
2734
- {
2735
- type: 'text',
2736
- text: `✅ SSH host key updated for ${server} (${host}:${port})\nThe new key has been accepted and saved.`
2737
- }
2738
- ]
2739
- };
2740
- } else {
2741
- // Add new key
2742
- await addHostKey(host, port);
2743
-
2744
- // Execute post-key-update hook
2745
- await executeHook('post-key-update', {
2746
- server: resolvedName,
2747
- host,
2748
- port,
2749
- action: 'added'
2750
- });
2736
+ return {
2737
+ content: [
2738
+ {
2739
+ type: 'text',
2740
+ text: output
2741
+ }
2742
+ ]
2743
+ };
2744
+ }
2745
+ }
2751
2746
 
2752
- logger.info('SSH host key added', { server: resolvedName, host, port });
2747
+ case 'accept': {
2748
+ // Check if key exists
2749
+ const isKnown = isHostKnown(host, port);
2753
2750
 
2754
- return {
2755
- content: [
2756
- {
2757
- type: 'text',
2758
- text: `✅ SSH host key added for ${server} (${host}:${port})\nThe key has been saved to known_hosts.`
2759
- }
2760
- ]
2761
- };
2762
- }
2763
- }
2751
+ if (isKnown) {
2752
+ // Update existing key
2753
+ await updateHostKey(host, port);
2764
2754
 
2765
- case 'remove': {
2766
- removeHostKey(host, port);
2755
+ // Execute post-key-update hook
2756
+ await executeHook('post-key-update', {
2757
+ server: resolvedName,
2758
+ host,
2759
+ port,
2760
+ action: 'updated'
2761
+ });
2767
2762
 
2768
- logger.info('SSH host key removed', { server: resolvedName, host, port });
2763
+ logger.info('SSH host key updated', { server: resolvedName, host, port });
2769
2764
 
2770
2765
  return {
2771
2766
  content: [
2772
2767
  {
2773
2768
  type: 'text',
2774
- text: `✅ SSH host key removed for ${server} (${host}:${port})`
2769
+ text: `✅ SSH host key updated for ${server} (${host}:${port})\nThe new key has been accepted and saved.`
2775
2770
  }
2776
2771
  ]
2777
2772
  };
2778
- }
2779
-
2780
- case 'check': {
2781
- // Get current fingerprints
2782
- const currentKeys = getCurrentHostKey(host, port);
2783
- const newKeys = await getHostKeyFingerprint(host, port);
2784
-
2785
- let output = `🔑 SSH Host Keys for ${server} (${host}:${port})\n`;
2786
- output += '━'.repeat(60) + '\n\n';
2787
-
2788
- if (currentKeys && currentKeys.length > 0) {
2789
- output += `📋 Keys in known_hosts:\n`;
2790
- currentKeys.forEach(key => {
2791
- output += ` ${key.type}: ${key.fingerprint}\n`;
2792
- });
2793
- } else {
2794
- output += `⚠️ No keys found in known_hosts\n`;
2795
- }
2773
+ } else {
2774
+ // Add new key
2775
+ await addHostKey(host, port);
2776
+
2777
+ // Execute post-key-update hook
2778
+ await executeHook('post-key-update', {
2779
+ server: resolvedName,
2780
+ host,
2781
+ port,
2782
+ action: 'added'
2783
+ });
2796
2784
 
2797
- output += `\n🌐 Keys from server:\n`;
2798
- if (newKeys && newKeys.length > 0) {
2799
- newKeys.forEach(key => {
2800
- output += ` ${key.type}: ${key.fingerprint}\n`;
2801
- });
2802
- } else {
2803
- output += ` ❌ Could not fetch keys from server\n`;
2804
- }
2785
+ logger.info('SSH host key added', { server: resolvedName, host, port });
2805
2786
 
2806
2787
  return {
2807
2788
  content: [
2808
2789
  {
2809
2790
  type: 'text',
2810
- text: output
2791
+ text: `✅ SSH host key added for ${server} (${host}:${port})\nThe key has been saved to known_hosts.`
2811
2792
  }
2812
2793
  ]
2813
2794
  };
2814
2795
  }
2796
+ }
2815
2797
 
2816
- case 'list': {
2817
- const knownHosts = listKnownHosts();
2798
+ case 'remove': {
2799
+ removeHostKey(host, port);
2818
2800
 
2819
- let output = `🔑 Known SSH Hosts\n`;
2820
- output += '━'.repeat(60) + '\n\n';
2801
+ logger.info('SSH host key removed', { server: resolvedName, host, port });
2821
2802
 
2822
- if (knownHosts.length === 0) {
2823
- output += 'No hosts in known_hosts file\n';
2824
- } else {
2825
- // Map server names to known hosts
2826
- const serverMap = new Map();
2827
- for (const [name, config] of Object.entries(servers)) {
2828
- const key = `${config.host}:${config.port || 22}`;
2829
- serverMap.set(key, name);
2803
+ return {
2804
+ content: [
2805
+ {
2806
+ type: 'text',
2807
+ text: `✅ SSH host key removed for ${server} (${host}:${port})`
2830
2808
  }
2809
+ ]
2810
+ };
2811
+ }
2831
2812
 
2832
- knownHosts.forEach(entry => {
2833
- const serverName = serverMap.get(`${entry.host}:${entry.port}`);
2834
- output += `📍 ${entry.host}:${entry.port}`;
2835
- if (serverName) {
2836
- output += ` (${serverName})`;
2837
- }
2838
- output += '\n';
2813
+ case 'check': {
2814
+ // Get current fingerprints
2815
+ const currentKeys = getCurrentHostKey(host, port);
2816
+ const newKeys = await getHostKeyFingerprint(host, port);
2839
2817
 
2840
- entry.keys.forEach(key => {
2841
- output += ` ${key.type}: ${key.fingerprint}\n`;
2842
- });
2843
- output += '\n';
2844
- });
2818
+ let output = `🔑 SSH Host Keys for ${server} (${host}:${port})\n`;
2819
+ output += '━'.repeat(60) + '\n\n';
2820
+
2821
+ if (currentKeys && currentKeys.length > 0) {
2822
+ output += '📋 Keys in known_hosts:\n';
2823
+ currentKeys.forEach(key => {
2824
+ output += ` ${key.type}: ${key.fingerprint}\n`;
2825
+ });
2826
+ } else {
2827
+ output += '⚠️ No keys found in known_hosts\n';
2828
+ }
2829
+
2830
+ output += '\n🌐 Keys from server:\n';
2831
+ if (newKeys && newKeys.length > 0) {
2832
+ newKeys.forEach(key => {
2833
+ output += ` ${key.type}: ${key.fingerprint}\n`;
2834
+ });
2835
+ } else {
2836
+ output += ' ❌ Could not fetch keys from server\n';
2837
+ }
2838
+
2839
+ return {
2840
+ content: [
2841
+ {
2842
+ type: 'text',
2843
+ text: output
2844
+ }
2845
+ ]
2846
+ };
2847
+ }
2848
+
2849
+ case 'list': {
2850
+ const knownHosts = listKnownHosts();
2851
+
2852
+ let output = '🔑 Known SSH Hosts\n';
2853
+ output += '━'.repeat(60) + '\n\n';
2854
+
2855
+ if (knownHosts.length === 0) {
2856
+ output += 'No hosts in known_hosts file\n';
2857
+ } else {
2858
+ // Map server names to known hosts
2859
+ const serverMap = new Map();
2860
+ for (const [name, config] of Object.entries(servers)) {
2861
+ const key = `${config.host}:${config.port || 22}`;
2862
+ serverMap.set(key, name);
2845
2863
  }
2846
2864
 
2847
- output += '━'.repeat(60) + '\n';
2848
- output += `Total: ${knownHosts.length} hosts`;
2865
+ knownHosts.forEach(entry => {
2866
+ const serverName = serverMap.get(`${entry.host}:${entry.port}`);
2867
+ output += `📍 ${entry.host}:${entry.port}`;
2868
+ if (serverName) {
2869
+ output += ` (${serverName})`;
2870
+ }
2871
+ output += '\n';
2849
2872
 
2850
- return {
2851
- content: [
2852
- {
2853
- type: 'text',
2854
- text: output
2855
- }
2856
- ]
2857
- };
2873
+ entry.keys.forEach(key => {
2874
+ output += ` ${key.type}: ${key.fingerprint}\n`;
2875
+ });
2876
+ output += '\n';
2877
+ });
2858
2878
  }
2859
2879
 
2860
- default:
2861
- throw new Error(`Unknown action: ${action}`);
2880
+ output += '━'.repeat(60) + '\n';
2881
+ output += `Total: ${knownHosts.length} hosts`;
2882
+
2883
+ return {
2884
+ content: [
2885
+ {
2886
+ type: 'text',
2887
+ text: output
2888
+ }
2889
+ ]
2890
+ };
2891
+ }
2892
+
2893
+ default:
2894
+ throw new Error(`Unknown action: ${action}`);
2862
2895
  }
2863
2896
  } catch (error) {
2864
2897
  logger.error('SSH key management failed', { action, server, error: error.message });
@@ -2876,7 +2909,7 @@ server.registerTool(
2876
2909
  );
2877
2910
 
2878
2911
  // Manage server aliases
2879
- server.registerTool(
2912
+ registerToolConditional(
2880
2913
  'ssh_alias',
2881
2914
  {
2882
2915
  description: 'Manage server aliases for easier access',
@@ -2966,7 +2999,7 @@ server.registerTool(
2966
2999
  // BACKUP & RESTORE TOOLS
2967
3000
  // ============================================================================
2968
3001
 
2969
- server.registerTool(
3002
+ registerToolConditional(
2970
3003
  'ssh_backup_create',
2971
3004
  {
2972
3005
  description: 'Create backup of database or files on remote server',
@@ -3031,70 +3064,71 @@ server.registerTool(
3031
3064
  let backupCommand;
3032
3065
 
3033
3066
  switch (type) {
3034
- case BACKUP_TYPES.MYSQL:
3035
- if (!database) {
3036
- throw new Error('database parameter required for MySQL backup');
3037
- }
3038
- backupCommand = buildMySQLDumpCommand({
3039
- database,
3040
- user: dbUser,
3041
- password: dbPassword,
3042
- host: dbHost,
3043
- port: dbPort,
3044
- outputFile: backupFile,
3045
- compress
3046
- });
3047
- break;
3067
+ case BACKUP_TYPES.MYSQL:
3068
+ if (!database) {
3069
+ throw new Error('database parameter required for MySQL backup');
3070
+ }
3071
+ backupCommand = buildMySQLDumpCommand({
3072
+ database,
3073
+ user: dbUser,
3074
+ password: dbPassword,
3075
+ host: dbHost,
3076
+ port: dbPort,
3077
+ outputFile: backupFile,
3078
+ compress
3079
+ });
3080
+ break;
3048
3081
 
3049
- case BACKUP_TYPES.POSTGRESQL:
3050
- if (!database) {
3051
- throw new Error('database parameter required for PostgreSQL backup');
3052
- }
3053
- backupCommand = buildPostgreSQLDumpCommand({
3054
- database,
3055
- user: dbUser,
3056
- password: dbPassword,
3057
- host: dbHost,
3058
- port: dbPort,
3059
- outputFile: backupFile,
3060
- compress
3061
- });
3062
- break;
3082
+ case BACKUP_TYPES.POSTGRESQL:
3083
+ if (!database) {
3084
+ throw new Error('database parameter required for PostgreSQL backup');
3085
+ }
3086
+ backupCommand = buildPostgreSQLDumpCommand({
3087
+ database,
3088
+ user: dbUser,
3089
+ password: dbPassword,
3090
+ host: dbHost,
3091
+ port: dbPort,
3092
+ outputFile: backupFile,
3093
+ compress
3094
+ });
3095
+ break;
3063
3096
 
3064
- case BACKUP_TYPES.MONGODB:
3065
- if (!database) {
3066
- throw new Error('database parameter required for MongoDB backup');
3067
- }
3068
- const mongoOutputDir = backupFile.replace('.gz', '');
3069
- backupCommand = buildMongoDBDumpCommand({
3070
- database,
3071
- user: dbUser,
3072
- password: dbPassword,
3073
- host: dbHost,
3074
- port: dbPort,
3075
- outputDir: mongoOutputDir,
3076
- compress
3077
- });
3078
- break;
3097
+ case BACKUP_TYPES.MONGODB: {
3098
+ if (!database) {
3099
+ throw new Error('database parameter required for MongoDB backup');
3100
+ }
3101
+ const mongoOutputDir = backupFile.replace('.gz', '');
3102
+ backupCommand = buildMongoDBDumpCommand({
3103
+ database,
3104
+ user: dbUser,
3105
+ password: dbPassword,
3106
+ host: dbHost,
3107
+ port: dbPort,
3108
+ outputDir: mongoOutputDir,
3109
+ compress
3110
+ });
3111
+ break;
3112
+ }
3079
3113
 
3080
- case BACKUP_TYPES.FILES:
3081
- if (!paths || paths.length === 0) {
3082
- throw new Error('paths parameter required for files backup');
3083
- }
3084
- backupCommand = buildFilesBackupCommand({
3085
- paths,
3086
- outputFile: backupFile,
3087
- exclude: exclude || [],
3088
- compress
3089
- });
3090
- break;
3114
+ case BACKUP_TYPES.FILES:
3115
+ if (!paths || paths.length === 0) {
3116
+ throw new Error('paths parameter required for files backup');
3117
+ }
3118
+ backupCommand = buildFilesBackupCommand({
3119
+ paths,
3120
+ outputFile: backupFile,
3121
+ exclude: exclude || [],
3122
+ compress
3123
+ });
3124
+ break;
3091
3125
 
3092
- case BACKUP_TYPES.FULL:
3093
- // Full backup combines database and files
3094
- throw new Error('Full backup not yet implemented. Use separate mysql/postgresql/files backups.');
3126
+ case BACKUP_TYPES.FULL:
3127
+ // Full backup combines database and files
3128
+ throw new Error('Full backup not yet implemented. Use separate mysql/postgresql/files backups.');
3095
3129
 
3096
- default:
3097
- throw new Error(`Unknown backup type: ${type}`);
3130
+ default:
3131
+ throw new Error(`Unknown backup type: ${type}`);
3098
3132
  }
3099
3133
 
3100
3134
  // Execute backup command
@@ -3185,7 +3219,7 @@ server.registerTool(
3185
3219
  }
3186
3220
  );
3187
3221
 
3188
- server.registerTool(
3222
+ registerToolConditional(
3189
3223
  'ssh_backup_list',
3190
3224
  {
3191
3225
  description: 'List available backups on remote server',
@@ -3257,7 +3291,7 @@ server.registerTool(
3257
3291
  }
3258
3292
  );
3259
3293
 
3260
- server.registerTool(
3294
+ registerToolConditional(
3261
3295
  'ssh_backup_restore',
3262
3296
  {
3263
3297
  description: 'Restore from a backup on remote server',
@@ -3378,7 +3412,7 @@ server.registerTool(
3378
3412
  }
3379
3413
  );
3380
3414
 
3381
- server.registerTool(
3415
+ registerToolConditional(
3382
3416
  'ssh_backup_schedule',
3383
3417
  {
3384
3418
  description: 'Schedule automatic backups using cron',
@@ -3417,30 +3451,30 @@ server.registerTool(
3417
3451
  scriptContent += `BACKUP_TYPE="${type}"\n`;
3418
3452
  scriptContent += `BACKUP_ID="${backupId}"\n`;
3419
3453
  scriptContent += `BACKUP_FILE="${backupFile}"\n\n`;
3420
- scriptContent += `mkdir -p "$BACKUP_DIR"\n\n`;
3454
+ scriptContent += 'mkdir -p "$BACKUP_DIR"\n\n';
3421
3455
 
3422
3456
  // Add backup command based on type
3423
3457
  switch (type) {
3424
- case BACKUP_TYPES.MYSQL:
3425
- scriptContent += `mysqldump --single-transaction --routines --triggers ${database} | gzip > "$BACKUP_FILE"\n`;
3426
- break;
3427
- case BACKUP_TYPES.POSTGRESQL:
3428
- scriptContent += `pg_dump --format=custom --clean --if-exists ${database} | gzip > "$BACKUP_FILE"\n`;
3429
- break;
3430
- case BACKUP_TYPES.MONGODB:
3431
- scriptContent += `mongodump --db ${database} --out /tmp/mongo_\${RANDOM} && tar -czf "$BACKUP_FILE" -C /tmp mongo_*\n`;
3432
- break;
3433
- case BACKUP_TYPES.FILES:
3434
- scriptContent += `tar -czf "$BACKUP_FILE" ${paths.join(' ')}\n`;
3435
- break;
3458
+ case BACKUP_TYPES.MYSQL:
3459
+ scriptContent += `mysqldump --single-transaction --routines --triggers ${database} | gzip > "$BACKUP_FILE"\n`;
3460
+ break;
3461
+ case BACKUP_TYPES.POSTGRESQL:
3462
+ scriptContent += `pg_dump --format=custom --clean --if-exists ${database} | gzip > "$BACKUP_FILE"\n`;
3463
+ break;
3464
+ case BACKUP_TYPES.MONGODB:
3465
+ scriptContent += `mongodump --db ${database} --out /tmp/mongo_\${RANDOM} && tar -czf "$BACKUP_FILE" -C /tmp mongo_*\n`;
3466
+ break;
3467
+ case BACKUP_TYPES.FILES:
3468
+ scriptContent += `tar -czf "$BACKUP_FILE" ${paths.join(' ')}\n`;
3469
+ break;
3436
3470
  }
3437
3471
 
3438
3472
  // Add cleanup command
3439
- scriptContent += `\n# Cleanup old backups\n`;
3473
+ scriptContent += '\n# Cleanup old backups\n';
3440
3474
  scriptContent += `find "$BACKUP_DIR" -name "*_${name}_*" -type f -mtime +${retention} -delete\n`;
3441
3475
 
3442
3476
  // Save script to remote server
3443
- const escapedScript = scriptContent.replace(/'/g, "'\\''");
3477
+ const escapedScript = scriptContent.replace(/'/g, '\'\\\'\'');
3444
3478
  await ssh.execCommand(`echo '${escapedScript}' > "${scriptPath}" && chmod +x "${scriptPath}"`);
3445
3479
 
3446
3480
  // Add to crontab
@@ -3501,7 +3535,7 @@ server.registerTool(
3501
3535
  // HEALTH CHECKS & MONITORING TOOLS
3502
3536
  // ============================================================================
3503
3537
 
3504
- server.registerTool(
3538
+ registerToolConditional(
3505
3539
  'ssh_health_check',
3506
3540
  {
3507
3541
  description: 'Perform comprehensive health check on remote server',
@@ -3596,7 +3630,7 @@ server.registerTool(
3596
3630
  }
3597
3631
  );
3598
3632
 
3599
- server.registerTool(
3633
+ registerToolConditional(
3600
3634
  'ssh_service_status',
3601
3635
  {
3602
3636
  description: 'Check status of services on remote server',
@@ -3638,11 +3672,11 @@ server.registerTool(
3638
3672
  stopped,
3639
3673
  services: serviceStatuses,
3640
3674
  overall_health: stopped === 0 ? HEALTH_STATUS.HEALTHY :
3641
- running > stopped ? HEALTH_STATUS.WARNING :
3642
- HEALTH_STATUS.CRITICAL
3675
+ running > stopped ? HEALTH_STATUS.WARNING :
3676
+ HEALTH_STATUS.CRITICAL
3643
3677
  };
3644
3678
 
3645
- logger.info(`Service check completed`, {
3679
+ logger.info('Service check completed', {
3646
3680
  server: serverName,
3647
3681
  running,
3648
3682
  stopped
@@ -3675,7 +3709,7 @@ server.registerTool(
3675
3709
  }
3676
3710
  );
3677
3711
 
3678
- server.registerTool(
3712
+ registerToolConditional(
3679
3713
  'ssh_process_manager',
3680
3714
  {
3681
3715
  description: 'List, monitor, or kill processes on remote server',
@@ -3708,92 +3742,92 @@ server.registerTool(
3708
3742
  let response;
3709
3743
 
3710
3744
  switch (action) {
3711
- case 'list': {
3712
- const listCommand = buildProcessListCommand({ sortBy, limit, filter });
3713
- const result = await ssh.execCommand(listCommand);
3714
-
3715
- if (result.code !== 0) {
3716
- throw new Error(`Failed to list processes: ${result.stderr}`);
3717
- }
3718
-
3719
- const processes = parseProcessList(result.stdout);
3745
+ case 'list': {
3746
+ const listCommand = buildProcessListCommand({ sortBy, limit, filter });
3747
+ const result = await ssh.execCommand(listCommand);
3720
3748
 
3721
- response = {
3722
- server: serverName,
3723
- action: 'list',
3724
- count: processes.length,
3725
- sorted_by: sortBy,
3726
- processes
3727
- };
3728
- break;
3749
+ if (result.code !== 0) {
3750
+ throw new Error(`Failed to list processes: ${result.stderr}`);
3729
3751
  }
3730
3752
 
3731
- case 'kill': {
3732
- if (!pid) {
3733
- throw new Error('pid parameter required for kill action');
3734
- }
3753
+ const processes = parseProcessList(result.stdout);
3735
3754
 
3736
- // Get process info first
3737
- const infoCommand = buildProcessInfoCommand(pid);
3738
- const infoResult = await ssh.execCommand(infoCommand);
3755
+ response = {
3756
+ server: serverName,
3757
+ action: 'list',
3758
+ count: processes.length,
3759
+ sorted_by: sortBy,
3760
+ processes
3761
+ };
3762
+ break;
3763
+ }
3739
3764
 
3740
- let processInfo = {};
3741
- if (infoResult.code === 0 && infoResult.stdout) {
3742
- try {
3743
- processInfo = JSON.parse(infoResult.stdout);
3744
- } catch (e) {
3745
- // Process might not exist
3746
- }
3747
- }
3765
+ case 'kill': {
3766
+ if (!pid) {
3767
+ throw new Error('pid parameter required for kill action');
3768
+ }
3748
3769
 
3749
- // Kill the process
3750
- const killCommand = buildKillProcessCommand(pid, signal);
3751
- const killResult = await ssh.execCommand(killCommand);
3770
+ // Get process info first
3771
+ const infoCommand = buildProcessInfoCommand(pid);
3772
+ const infoResult = await ssh.execCommand(infoCommand);
3752
3773
 
3753
- if (killResult.code !== 0) {
3754
- throw new Error(`Failed to kill process ${pid}: ${killResult.stderr}`);
3774
+ let processInfo = {};
3775
+ if (infoResult.code === 0 && infoResult.stdout) {
3776
+ try {
3777
+ processInfo = JSON.parse(infoResult.stdout);
3778
+ } catch (e) {
3779
+ // Process might not exist
3755
3780
  }
3781
+ }
3756
3782
 
3757
- response = {
3758
- server: serverName,
3759
- action: 'kill',
3760
- pid,
3761
- signal,
3762
- process: processInfo,
3763
- success: true
3764
- };
3783
+ // Kill the process
3784
+ const killCommand = buildKillProcessCommand(pid, signal);
3785
+ const killResult = await ssh.execCommand(killCommand);
3765
3786
 
3766
- logger.info(`Process killed: ${pid}`, {
3767
- server: serverName,
3768
- signal
3769
- });
3770
- break;
3787
+ if (killResult.code !== 0) {
3788
+ throw new Error(`Failed to kill process ${pid}: ${killResult.stderr}`);
3771
3789
  }
3772
3790
 
3773
- case 'info': {
3774
- if (!pid) {
3775
- throw new Error('pid parameter required for info action');
3776
- }
3791
+ response = {
3792
+ server: serverName,
3793
+ action: 'kill',
3794
+ pid,
3795
+ signal,
3796
+ process: processInfo,
3797
+ success: true
3798
+ };
3777
3799
 
3778
- const infoCommand = buildProcessInfoCommand(pid);
3779
- const result = await ssh.execCommand(infoCommand);
3800
+ logger.info(`Process killed: ${pid}`, {
3801
+ server: serverName,
3802
+ signal
3803
+ });
3804
+ break;
3805
+ }
3780
3806
 
3781
- if (result.code !== 0 || !result.stdout) {
3782
- throw new Error(`Process ${pid} not found`);
3783
- }
3807
+ case 'info': {
3808
+ if (!pid) {
3809
+ throw new Error('pid parameter required for info action');
3810
+ }
3784
3811
 
3785
- const processInfo = JSON.parse(result.stdout);
3812
+ const infoCommand = buildProcessInfoCommand(pid);
3813
+ const result = await ssh.execCommand(infoCommand);
3786
3814
 
3787
- response = {
3788
- server: serverName,
3789
- action: 'info',
3790
- process: processInfo
3791
- };
3792
- break;
3815
+ if (result.code !== 0 || !result.stdout) {
3816
+ throw new Error(`Process ${pid} not found`);
3793
3817
  }
3794
3818
 
3795
- default:
3796
- throw new Error(`Unknown action: ${action}`);
3819
+ const processInfo = JSON.parse(result.stdout);
3820
+
3821
+ response = {
3822
+ server: serverName,
3823
+ action: 'info',
3824
+ process: processInfo
3825
+ };
3826
+ break;
3827
+ }
3828
+
3829
+ default:
3830
+ throw new Error(`Unknown action: ${action}`);
3797
3831
  }
3798
3832
 
3799
3833
  return {
@@ -3824,7 +3858,7 @@ server.registerTool(
3824
3858
  }
3825
3859
  );
3826
3860
 
3827
- server.registerTool(
3861
+ registerToolConditional(
3828
3862
  'ssh_alert_setup',
3829
3863
  {
3830
3864
  description: 'Configure health monitoring alerts and thresholds',
@@ -3854,126 +3888,126 @@ server.registerTool(
3854
3888
  let response;
3855
3889
 
3856
3890
  switch (action) {
3857
- case 'set': {
3858
- // Create alert configuration
3859
- const config = createAlertConfig({
3860
- cpu: cpuThreshold,
3861
- memory: memoryThreshold,
3862
- disk: diskThreshold,
3863
- enabled
3864
- });
3891
+ case 'set': {
3892
+ // Create alert configuration
3893
+ const config = createAlertConfig({
3894
+ cpu: cpuThreshold,
3895
+ memory: memoryThreshold,
3896
+ disk: diskThreshold,
3897
+ enabled
3898
+ });
3865
3899
 
3866
- // Save to server
3867
- const saveCommand = buildSaveAlertConfigCommand(config, configPath);
3868
- const saveResult = await ssh.execCommand(saveCommand);
3900
+ // Save to server
3901
+ const saveCommand = buildSaveAlertConfigCommand(config, configPath);
3902
+ const saveResult = await ssh.execCommand(saveCommand);
3869
3903
 
3870
- if (saveResult.code !== 0) {
3871
- throw new Error(`Failed to save alert config: ${saveResult.stderr}`);
3872
- }
3904
+ if (saveResult.code !== 0) {
3905
+ throw new Error(`Failed to save alert config: ${saveResult.stderr}`);
3906
+ }
3873
3907
 
3874
- response = {
3875
- server: serverName,
3876
- action: 'set',
3877
- config,
3878
- config_path: configPath,
3879
- success: true
3880
- };
3908
+ response = {
3909
+ server: serverName,
3910
+ action: 'set',
3911
+ config,
3912
+ config_path: configPath,
3913
+ success: true
3914
+ };
3881
3915
 
3882
- logger.info('Alert thresholds configured', {
3883
- server: serverName,
3884
- thresholds: config
3885
- });
3886
- break;
3916
+ logger.info('Alert thresholds configured', {
3917
+ server: serverName,
3918
+ thresholds: config
3919
+ });
3920
+ break;
3921
+ }
3922
+
3923
+ case 'get': {
3924
+ // Load configuration
3925
+ const loadCommand = buildLoadAlertConfigCommand(configPath);
3926
+ const result = await ssh.execCommand(loadCommand);
3927
+
3928
+ let config = {};
3929
+ if (result.stdout && result.stdout.trim()) {
3930
+ try {
3931
+ config = JSON.parse(result.stdout);
3932
+ } catch (e) {
3933
+ config = { error: 'Failed to parse config' };
3934
+ }
3887
3935
  }
3888
3936
 
3889
- case 'get': {
3890
- // Load configuration
3891
- const loadCommand = buildLoadAlertConfigCommand(configPath);
3892
- const result = await ssh.execCommand(loadCommand);
3893
-
3894
- let config = {};
3895
- if (result.stdout && result.stdout.trim()) {
3896
- try {
3897
- config = JSON.parse(result.stdout);
3898
- } catch (e) {
3899
- config = { error: 'Failed to parse config' };
3900
- }
3937
+ response = {
3938
+ server: serverName,
3939
+ action: 'get',
3940
+ config,
3941
+ config_path: configPath
3942
+ };
3943
+ break;
3944
+ }
3945
+
3946
+ case 'check': {
3947
+ // Load thresholds
3948
+ const loadCommand = buildLoadAlertConfigCommand(configPath);
3949
+ const loadResult = await ssh.execCommand(loadCommand);
3950
+
3951
+ let thresholds = {};
3952
+ if (loadResult.stdout && loadResult.stdout.trim()) {
3953
+ try {
3954
+ thresholds = JSON.parse(loadResult.stdout);
3955
+ } catch (e) {
3956
+ throw new Error('No alert configuration found. Use action=set to configure.');
3901
3957
  }
3958
+ } else {
3959
+ throw new Error('No alert configuration found. Use action=set to configure.');
3960
+ }
3902
3961
 
3962
+ if (!thresholds.enabled) {
3903
3963
  response = {
3904
3964
  server: serverName,
3905
- action: 'get',
3906
- config,
3907
- config_path: configPath
3965
+ action: 'check',
3966
+ message: 'Alerts are disabled',
3967
+ thresholds
3908
3968
  };
3909
3969
  break;
3910
3970
  }
3911
3971
 
3912
- case 'check': {
3913
- // Load thresholds
3914
- const loadCommand = buildLoadAlertConfigCommand(configPath);
3915
- const loadResult = await ssh.execCommand(loadCommand);
3916
-
3917
- let thresholds = {};
3918
- if (loadResult.stdout && loadResult.stdout.trim()) {
3919
- try {
3920
- thresholds = JSON.parse(loadResult.stdout);
3921
- } catch (e) {
3922
- throw new Error('No alert configuration found. Use action=set to configure.');
3923
- }
3924
- } else {
3925
- throw new Error('No alert configuration found. Use action=set to configure.');
3926
- }
3972
+ // Get current metrics
3973
+ const healthCommand = buildComprehensiveHealthCheckCommand();
3974
+ const healthResult = await ssh.execCommand(healthCommand);
3927
3975
 
3928
- if (!thresholds.enabled) {
3929
- response = {
3930
- server: serverName,
3931
- action: 'check',
3932
- message: 'Alerts are disabled',
3933
- thresholds
3934
- };
3935
- break;
3936
- }
3937
-
3938
- // Get current metrics
3939
- const healthCommand = buildComprehensiveHealthCheckCommand();
3940
- const healthResult = await ssh.execCommand(healthCommand);
3976
+ if (healthResult.code !== 0) {
3977
+ throw new Error('Failed to get current metrics');
3978
+ }
3941
3979
 
3942
- if (healthResult.code !== 0) {
3943
- throw new Error('Failed to get current metrics');
3944
- }
3980
+ const metrics = parseComprehensiveHealthCheck(healthResult.stdout);
3945
3981
 
3946
- const metrics = parseComprehensiveHealthCheck(healthResult.stdout);
3982
+ // Check thresholds
3983
+ const alerts = checkAlertThresholds(metrics, thresholds);
3947
3984
 
3948
- // Check thresholds
3949
- const alerts = checkAlertThresholds(metrics, thresholds);
3985
+ response = {
3986
+ server: serverName,
3987
+ action: 'check',
3988
+ thresholds,
3989
+ current_metrics: {
3990
+ cpu: metrics.cpu,
3991
+ memory: metrics.memory,
3992
+ disks: metrics.disks
3993
+ },
3994
+ alerts,
3995
+ alert_count: alerts.length,
3996
+ status: alerts.length === 0 ? 'ok' : 'alerts_triggered'
3997
+ };
3950
3998
 
3951
- response = {
3999
+ if (alerts.length > 0) {
4000
+ logger.warn('Health alerts triggered', {
3952
4001
  server: serverName,
3953
- action: 'check',
3954
- thresholds,
3955
- current_metrics: {
3956
- cpu: metrics.cpu,
3957
- memory: metrics.memory,
3958
- disks: metrics.disks
3959
- },
3960
- alerts,
3961
4002
  alert_count: alerts.length,
3962
- status: alerts.length === 0 ? 'ok' : 'alerts_triggered'
3963
- };
3964
-
3965
- if (alerts.length > 0) {
3966
- logger.warn('Health alerts triggered', {
3967
- server: serverName,
3968
- alert_count: alerts.length,
3969
- alerts
3970
- });
3971
- }
3972
- break;
4003
+ alerts
4004
+ });
3973
4005
  }
4006
+ break;
4007
+ }
3974
4008
 
3975
- default:
3976
- throw new Error(`Unknown action: ${action}`);
4009
+ default:
4010
+ throw new Error(`Unknown action: ${action}`);
3977
4011
  }
3978
4012
 
3979
4013
  return {
@@ -4008,7 +4042,7 @@ server.registerTool(
4008
4042
  // DATABASE MANAGEMENT TOOLS
4009
4043
  // ============================================================================
4010
4044
 
4011
- server.registerTool(
4045
+ registerToolConditional(
4012
4046
  'ssh_db_dump',
4013
4047
  {
4014
4048
  description: 'Dump database to file (MySQL, PostgreSQL, MongoDB)',
@@ -4049,18 +4083,18 @@ server.registerTool(
4049
4083
  };
4050
4084
 
4051
4085
  switch (type) {
4052
- case DB_TYPES.MYSQL:
4053
- dumpCommand = buildDBMySQLDumpCommand(options);
4054
- break;
4055
- case DB_TYPES.POSTGRESQL:
4056
- dumpCommand = buildDBPostgreSQLDumpCommand(options);
4057
- break;
4058
- case DB_TYPES.MONGODB:
4059
- options.outputDir = outputFile.replace(/\.(tar\.gz|gz)$/, '');
4060
- dumpCommand = buildDBMongoDBDumpCommand(options);
4061
- break;
4062
- default:
4063
- throw new Error(`Unsupported database type: ${type}`);
4086
+ case DB_TYPES.MYSQL:
4087
+ dumpCommand = buildDBMySQLDumpCommand(options);
4088
+ break;
4089
+ case DB_TYPES.POSTGRESQL:
4090
+ dumpCommand = buildDBPostgreSQLDumpCommand(options);
4091
+ break;
4092
+ case DB_TYPES.MONGODB:
4093
+ options.outputDir = outputFile.replace(/\.(tar\.gz|gz)$/, '');
4094
+ dumpCommand = buildDBMongoDBDumpCommand(options);
4095
+ break;
4096
+ default:
4097
+ throw new Error(`Unsupported database type: ${type}`);
4064
4098
  }
4065
4099
 
4066
4100
  // Execute dump
@@ -4120,7 +4154,7 @@ server.registerTool(
4120
4154
  }
4121
4155
  );
4122
4156
 
4123
- server.registerTool(
4157
+ registerToolConditional(
4124
4158
  'ssh_db_import',
4125
4159
  {
4126
4160
  description: 'Import database from SQL file (MySQL, PostgreSQL, MongoDB)',
@@ -4159,18 +4193,18 @@ server.registerTool(
4159
4193
  };
4160
4194
 
4161
4195
  switch (type) {
4162
- case DB_TYPES.MYSQL:
4163
- importCommand = buildMySQLImportCommand(options);
4164
- break;
4165
- case DB_TYPES.POSTGRESQL:
4166
- importCommand = buildPostgreSQLImportCommand(options);
4167
- break;
4168
- case DB_TYPES.MONGODB:
4169
- options.inputPath = inputFile;
4170
- importCommand = buildMongoDBRestoreCommand(options);
4171
- break;
4172
- default:
4173
- throw new Error(`Unsupported database type: ${type}`);
4196
+ case DB_TYPES.MYSQL:
4197
+ importCommand = buildMySQLImportCommand(options);
4198
+ break;
4199
+ case DB_TYPES.POSTGRESQL:
4200
+ importCommand = buildPostgreSQLImportCommand(options);
4201
+ break;
4202
+ case DB_TYPES.MONGODB:
4203
+ options.inputPath = inputFile;
4204
+ importCommand = buildMongoDBRestoreCommand(options);
4205
+ break;
4206
+ default:
4207
+ throw new Error(`Unsupported database type: ${type}`);
4174
4208
  }
4175
4209
 
4176
4210
  // Execute import
@@ -4180,7 +4214,7 @@ server.registerTool(
4180
4214
  throw new Error(`Import failed: ${result.stderr || result.stdout}`);
4181
4215
  }
4182
4216
 
4183
- logger.info(`Database import completed`, {
4217
+ logger.info('Database import completed', {
4184
4218
  server: serverName,
4185
4219
  database
4186
4220
  });
@@ -4222,7 +4256,7 @@ server.registerTool(
4222
4256
  }
4223
4257
  );
4224
4258
 
4225
- server.registerTool(
4259
+ registerToolConditional(
4226
4260
  'ssh_db_list',
4227
4261
  {
4228
4262
  description: 'List databases or tables/collections',
@@ -4261,28 +4295,28 @@ server.registerTool(
4261
4295
  if (database) {
4262
4296
  // List tables/collections
4263
4297
  switch (type) {
4264
- case DB_TYPES.MYSQL:
4265
- listCommand = buildMySQLListTablesCommand(options);
4266
- break;
4267
- case DB_TYPES.POSTGRESQL:
4268
- listCommand = buildPostgreSQLListTablesCommand(options);
4269
- break;
4270
- case DB_TYPES.MONGODB:
4271
- listCommand = buildMongoDBListCollectionsCommand(options);
4272
- break;
4298
+ case DB_TYPES.MYSQL:
4299
+ listCommand = buildMySQLListTablesCommand(options);
4300
+ break;
4301
+ case DB_TYPES.POSTGRESQL:
4302
+ listCommand = buildPostgreSQLListTablesCommand(options);
4303
+ break;
4304
+ case DB_TYPES.MONGODB:
4305
+ listCommand = buildMongoDBListCollectionsCommand(options);
4306
+ break;
4273
4307
  }
4274
4308
  } else {
4275
4309
  // List databases
4276
4310
  switch (type) {
4277
- case DB_TYPES.MYSQL:
4278
- listCommand = buildMySQLListDatabasesCommand(options);
4279
- break;
4280
- case DB_TYPES.POSTGRESQL:
4281
- listCommand = buildPostgreSQLListDatabasesCommand(options);
4282
- break;
4283
- case DB_TYPES.MONGODB:
4284
- listCommand = buildMongoDBListDatabasesCommand(options);
4285
- break;
4311
+ case DB_TYPES.MYSQL:
4312
+ listCommand = buildMySQLListDatabasesCommand(options);
4313
+ break;
4314
+ case DB_TYPES.POSTGRESQL:
4315
+ listCommand = buildPostgreSQLListDatabasesCommand(options);
4316
+ break;
4317
+ case DB_TYPES.MONGODB:
4318
+ listCommand = buildMongoDBListDatabasesCommand(options);
4319
+ break;
4286
4320
  }
4287
4321
  }
4288
4322
 
@@ -4347,7 +4381,7 @@ server.registerTool(
4347
4381
  }
4348
4382
  );
4349
4383
 
4350
- server.registerTool(
4384
+ registerToolConditional(
4351
4385
  'ssh_db_query',
4352
4386
  {
4353
4387
  description: 'Execute SELECT query on database (read-only, SELECT queries only)',
@@ -4392,21 +4426,21 @@ server.registerTool(
4392
4426
 
4393
4427
  // Build query command based on type
4394
4428
  switch (type) {
4395
- case DB_TYPES.MYSQL:
4396
- queryCommand = buildMySQLQueryCommand(options);
4397
- break;
4398
- case DB_TYPES.POSTGRESQL:
4399
- queryCommand = buildPostgreSQLQueryCommand(options);
4400
- break;
4401
- case DB_TYPES.MONGODB:
4402
- if (!collection) {
4403
- throw new Error('collection parameter required for MongoDB queries');
4404
- }
4405
- options.collection = collection;
4406
- queryCommand = buildMongoDBQueryCommand(options);
4407
- break;
4408
- default:
4409
- throw new Error(`Unsupported database type: ${type}`);
4429
+ case DB_TYPES.MYSQL:
4430
+ queryCommand = buildMySQLQueryCommand(options);
4431
+ break;
4432
+ case DB_TYPES.POSTGRESQL:
4433
+ queryCommand = buildPostgreSQLQueryCommand(options);
4434
+ break;
4435
+ case DB_TYPES.MONGODB:
4436
+ if (!collection) {
4437
+ throw new Error('collection parameter required for MongoDB queries');
4438
+ }
4439
+ options.collection = collection;
4440
+ queryCommand = buildMongoDBQueryCommand(options);
4441
+ break;
4442
+ default:
4443
+ throw new Error(`Unsupported database type: ${type}`);
4410
4444
  }
4411
4445
 
4412
4446
  // Execute query
@@ -4420,7 +4454,7 @@ server.registerTool(
4420
4454
  const output = result.stdout.trim();
4421
4455
  const lines = output.split('\n');
4422
4456
 
4423
- logger.info(`Query executed successfully`, {
4457
+ logger.info('Query executed successfully', {
4424
4458
  server: serverName,
4425
4459
  database,
4426
4460
  rows: lines.length