mcp-ssh-manager 3.0.0 → 3.1.2

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
@@ -7,6 +7,7 @@ import SSHManager from './ssh-manager.js';
7
7
  import * as dotenv from 'dotenv';
8
8
  import fs from 'fs';
9
9
  import path from 'path';
10
+ import os from 'os';
10
11
  import { fileURLToPath } from 'url';
11
12
  import { configLoader } from './config-loader.js';
12
13
  import {
@@ -27,6 +28,12 @@ import {
27
28
  listCommandAliases,
28
29
  suggestAliases
29
30
  } from './command-aliases.js';
31
+ import {
32
+ OUTPUT_LIMITS,
33
+ TIMEOUTS,
34
+ truncateOutput,
35
+ formatJSONResponse
36
+ } from './config.js';
30
37
  import {
31
38
  initializeHooks,
32
39
  executeHook,
@@ -76,7 +83,7 @@ import {
76
83
  hasHostKeyChanged,
77
84
  listKnownHosts,
78
85
  detectSSHKeyError,
79
- handleSSHKeyError
86
+ extractHostFromSSHError
80
87
  } from './ssh-key-manager.js';
81
88
  import {
82
89
  BACKUP_TYPES,
@@ -152,6 +159,7 @@ import {
152
159
  formatBytes,
153
160
  getConnectionInfo
154
161
  } from './database-manager.js';
162
+ import { loadToolConfig, isToolEnabled } from './tool-config-manager.js';
155
163
 
156
164
  const __filename = fileURLToPath(import.meta.url);
157
165
  const __dirname = path.dirname(__filename);
@@ -187,6 +195,20 @@ initializeHooks().catch(error => {
187
195
  logger.error('Failed to initialize hooks', { error: error.message });
188
196
  });
189
197
 
198
+ // Load tool configuration
199
+ let toolConfig = null;
200
+ loadToolConfig().then(config => {
201
+ toolConfig = config;
202
+ const summary = config.getSummary();
203
+ logger.info(`Tool configuration loaded: ${summary.mode} mode, ${summary.enabledCount}/${summary.totalTools} tools enabled`);
204
+ if (summary.mode === 'all') {
205
+ logger.info('💡 Tip: Run "ssh-manager tools configure" to reduce context usage in Claude Code');
206
+ }
207
+ }).catch(error => {
208
+ logger.error('Failed to load tool configuration', { error: error.message });
209
+ logger.info('Using default configuration (all tools enabled)');
210
+ });
211
+
190
212
  // Map to store active connections
191
213
  const connections = new Map();
192
214
 
@@ -213,23 +235,23 @@ function loadServerConfig() {
213
235
  async function execCommandWithTimeout(ssh, command, options = {}, timeoutMs = 30000) {
214
236
  // Pass through rawCommand if specified
215
237
  const { rawCommand, ...otherOptions } = options;
216
-
238
+
217
239
  // For commands that might hang, use the system's timeout command if available
218
240
  const useSystemTimeout = timeoutMs > 0 && timeoutMs < 300000 && !rawCommand; // Max 5 minutes, not for raw commands
219
-
241
+
220
242
  if (useSystemTimeout) {
221
243
  // Wrap command with timeout command (works on Linux/Mac)
222
244
  const timeoutSeconds = Math.ceil(timeoutMs / 1000);
223
- const wrappedCommand = `timeout ${timeoutSeconds} sh -c '${command.replace(/'/g, "'\\''")}'`;
224
-
245
+ const wrappedCommand = `timeout ${timeoutSeconds} sh -c '${command.replace(/'/g, '\'\\\'\'')}'`;
246
+
225
247
  try {
226
248
  const result = await ssh.execCommand(wrappedCommand, otherOptions);
227
-
249
+
228
250
  // Check if timeout occurred (exit code 124 on Linux, 124 or 143 on Mac)
229
251
  if (result.code === 124 || result.code === 143) {
230
252
  throw new Error(`Command timeout after ${timeoutMs}ms: ${command.substring(0, 100)}...`);
231
253
  }
232
-
254
+
233
255
  return result;
234
256
  } catch (error) {
235
257
  // If timeout occurred, remove connection from pool
@@ -406,8 +428,23 @@ const server = new McpServer({
406
428
 
407
429
  logger.info('MCP Server initialized', { version: '1.2.0' });
408
430
 
431
+ /**
432
+ * Helper function to conditionally register tools based on configuration
433
+ * @param {string} toolName - Name of the tool
434
+ * @param {Object} schema - Tool schema
435
+ * @param {Function} handler - Tool handler function
436
+ */
437
+ function registerToolConditional(toolName, schema, handler) {
438
+ if (isToolEnabled(toolName)) {
439
+ server.registerTool(toolName, schema, handler);
440
+ logger.debug(`Registered tool: ${toolName}`);
441
+ } else {
442
+ logger.debug(`Skipped disabled tool: ${toolName}`);
443
+ }
444
+ }
445
+
409
446
  // Register available tools
410
- server.registerTool(
447
+ registerToolConditional(
411
448
  'ssh_execute',
412
449
  {
413
450
  description: 'Execute command on remote SSH server',
@@ -415,10 +452,12 @@ server.registerTool(
415
452
  server: z.string().describe('Server name from configuration'),
416
453
  command: z.string().describe('Command to execute'),
417
454
  cwd: z.string().optional().describe('Working directory (optional, uses default if configured)'),
418
- timeout: z.number().optional().describe('Command timeout in milliseconds (default: 30000)')
455
+ timeout: z.number().optional().describe('Command timeout in milliseconds (default: 120000, max: 300000)')
419
456
  }
420
457
  },
421
- async ({ server: serverName, command, cwd, timeout = 30000 }) => {
458
+ async ({ server: serverName, command, cwd, timeout = TIMEOUTS.DEFAULT_COMMAND_TIMEOUT }) => {
459
+ // Cap timeout at maximum allowed
460
+ const cappedTimeout = Math.min(timeout, TIMEOUTS.MAX_COMMAND_TIMEOUT);
422
461
  try {
423
462
  const ssh = await getConnection(serverName);
424
463
 
@@ -443,8 +482,8 @@ server.registerTool(
443
482
  // Log command execution
444
483
  const startTime = logger.logCommand(serverName, fullCommand, workingDir);
445
484
 
446
- const result = await execCommandWithTimeout(ssh, fullCommand, {}, timeout);
447
-
485
+ const result = await execCommandWithTimeout(ssh, fullCommand, {}, cappedTimeout);
486
+
448
487
  // Log command result
449
488
  logger.logCommandResult(serverName, fullCommand, startTime, result);
450
489
 
@@ -457,35 +496,50 @@ server.registerTool(
457
496
  });
458
497
  }
459
498
 
499
+ // Truncate output if too large to prevent Claude Code crashes
500
+ const stdout = truncateOutput(result.stdout);
501
+ const stderr = truncateOutput(result.stderr);
502
+
460
503
  return {
461
504
  content: [
462
505
  {
463
506
  type: 'text',
464
- text: JSON.stringify({
507
+ text: formatJSONResponse({
465
508
  server: serverName,
466
509
  command: fullCommand,
467
- stdout: result.stdout,
468
- stderr: result.stderr,
510
+ stdout: stdout,
511
+ stderr: stderr,
469
512
  code: result.code,
470
513
  success: result.code === 0,
471
- }, null, 2),
514
+ }),
472
515
  },
473
516
  ],
474
517
  };
475
518
  } catch (error) {
519
+ logger.error('ssh_execute failed', {
520
+ server: serverName,
521
+ error: error.message
522
+ });
523
+
476
524
  return {
477
525
  content: [
478
526
  {
479
527
  type: 'text',
480
- text: `❌ Error: ${error.message}`,
528
+ text: formatJSONResponse({
529
+ server: serverName,
530
+ success: false,
531
+ error: truncateOutput(error.message, 1000),
532
+ code: -1
533
+ }),
481
534
  },
482
535
  ],
536
+ isError: true
483
537
  };
484
538
  }
485
539
  }
486
540
  );
487
541
 
488
- server.registerTool(
542
+ registerToolConditional(
489
543
  'ssh_upload',
490
544
  {
491
545
  description: 'Upload file to remote SSH server',
@@ -498,12 +552,12 @@ server.registerTool(
498
552
  async ({ server: serverName, localPath, remotePath }) => {
499
553
  try {
500
554
  const ssh = await getConnection(serverName);
501
-
555
+
502
556
  logger.logTransfer('upload', serverName, localPath, remotePath);
503
557
  const startTime = Date.now();
504
-
558
+
505
559
  await ssh.putFile(localPath, remotePath);
506
-
560
+
507
561
  const fileStats = fs.statSync(localPath);
508
562
  logger.logTransfer('upload', serverName, localPath, remotePath, {
509
563
  success: true,
@@ -536,7 +590,7 @@ server.registerTool(
536
590
  }
537
591
  );
538
592
 
539
- server.registerTool(
593
+ registerToolConditional(
540
594
  'ssh_download',
541
595
  {
542
596
  description: 'Download file from remote SSH server',
@@ -549,12 +603,12 @@ server.registerTool(
549
603
  async ({ server: serverName, remotePath, localPath }) => {
550
604
  try {
551
605
  const ssh = await getConnection(serverName);
552
-
606
+
553
607
  logger.logTransfer('download', serverName, remotePath, localPath);
554
608
  const startTime = Date.now();
555
-
609
+
556
610
  await ssh.getFile(localPath, remotePath);
557
-
611
+
558
612
  const fileStats = fs.statSync(localPath);
559
613
  logger.logTransfer('download', serverName, remotePath, localPath, {
560
614
  success: true,
@@ -587,7 +641,7 @@ server.registerTool(
587
641
  }
588
642
  );
589
643
 
590
- server.registerTool(
644
+ registerToolConditional(
591
645
  'ssh_sync',
592
646
  {
593
647
  description: 'Synchronize files/folders between local and remote via rsync',
@@ -609,7 +663,7 @@ server.registerTool(
609
663
  const ssh = await getConnection(serverName);
610
664
  const servers = loadServerConfig();
611
665
  const serverConfig = servers[serverName.toLowerCase()];
612
-
666
+
613
667
  // Check if sshpass is available for password authentication
614
668
  if (!serverConfig.keypath && serverConfig.password) {
615
669
  // Check if sshpass is installed
@@ -627,61 +681,61 @@ server.registerTool(
627
681
  };
628
682
  }
629
683
  }
630
-
684
+
631
685
  // Determine sync direction based on source/destination prefixes
632
686
  const isLocalSource = source.startsWith('local:');
633
687
  const isRemoteSource = source.startsWith('remote:');
634
688
  const isLocalDest = destination.startsWith('local:');
635
689
  const isRemoteDest = destination.startsWith('remote:');
636
-
690
+
637
691
  // Clean paths
638
692
  const cleanSource = source.replace(/^(local:|remote:)/, '');
639
693
  const cleanDest = destination.replace(/^(local:|remote:)/, '');
640
-
694
+
641
695
  // Validate direction
642
696
  if ((isLocalSource && isLocalDest) || (isRemoteSource && isRemoteDest)) {
643
697
  throw new Error('Source and destination must be different (one local, one remote). Use prefixes: local: or remote:');
644
698
  }
645
-
699
+
646
700
  // If no prefixes, assume old format (local source to remote dest)
647
701
  const direction = (isLocalSource || (!isLocalSource && !isRemoteSource)) ? 'push' : 'pull';
648
-
702
+
649
703
  // Build rsync command
650
704
  let rsyncOptions = ['-avz'];
651
-
705
+
652
706
  if (!compress) {
653
707
  rsyncOptions = ['-av'];
654
708
  }
655
-
709
+
656
710
  if (checksum) {
657
711
  rsyncOptions.push('--checksum');
658
712
  }
659
-
713
+
660
714
  if (deleteFiles) {
661
715
  rsyncOptions.push('--delete');
662
716
  }
663
-
717
+
664
718
  if (dryRun) {
665
719
  rsyncOptions.push('--dry-run');
666
720
  }
667
-
721
+
668
722
  if (verbose || logger.verbose) {
669
723
  // Only add stats, not progress to avoid blocking with too much output
670
724
  rsyncOptions.push('--stats');
671
725
  }
672
-
726
+
673
727
  // Add exclude patterns
674
728
  exclude.forEach(pattern => {
675
729
  rsyncOptions.push('--exclude', pattern);
676
730
  });
677
-
731
+
678
732
  let localPath;
679
733
  let remotePath;
680
-
734
+
681
735
  if (direction === 'push') {
682
736
  localPath = cleanSource;
683
737
  remotePath = cleanDest;
684
-
738
+
685
739
  // Check if local path exists
686
740
  if (!fs.existsSync(localPath)) {
687
741
  throw new Error(`Local path does not exist: ${localPath}`);
@@ -690,7 +744,7 @@ server.registerTool(
690
744
  localPath = cleanDest;
691
745
  remotePath = cleanSource;
692
746
  }
693
-
747
+
694
748
  // Add SSH options for non-interactive mode
695
749
  const sshOptions = [];
696
750
 
@@ -700,18 +754,18 @@ server.registerTool(
700
754
  sshOptions.push('-o StrictHostKeyChecking=accept-new'); // Accept new keys, reject changed ones
701
755
  sshOptions.push('-o ConnectTimeout=10'); // Connection timeout
702
756
 
703
- const keyPath = serverConfig.keypath.replace('~', process.env.HOME);
757
+ const keyPath = serverConfig.keypath.replace('~', os.homedir());
704
758
  sshOptions.push(`-i ${keyPath}`);
705
759
  } else {
706
760
  // With sshpass, we don't use BatchMode
707
761
  sshOptions.push('-o StrictHostKeyChecking=accept-new'); // Accept new keys, reject changed ones
708
762
  sshOptions.push('-o ConnectTimeout=10');
709
763
  }
710
-
764
+
711
765
  if (serverConfig.port && serverConfig.port !== '22') {
712
766
  sshOptions.push(`-p ${serverConfig.port}`);
713
767
  }
714
-
768
+
715
769
  logger.info(`Starting rsync ${direction}`, {
716
770
  server: serverName,
717
771
  source: direction === 'push' ? localPath : remotePath,
@@ -719,49 +773,49 @@ server.registerTool(
719
773
  dryRun,
720
774
  deleteFiles
721
775
  });
722
-
776
+
723
777
  const startTime = Date.now();
724
-
778
+
725
779
  // Execute rsync via spawn for non-blocking streaming
726
780
  const { spawn } = await import('child_process');
727
-
781
+
728
782
  return new Promise((resolve, reject) => {
729
783
  let output = '';
730
784
  let errorOutput = '';
731
785
  let killed = false;
732
-
786
+
733
787
  // Build command based on authentication method
734
788
  let rsyncCommand;
735
789
  let rsyncArgs = [];
736
790
  let processEnv = { ...process.env };
737
-
791
+
738
792
  if (serverConfig.password) {
739
793
  // Use sshpass for password authentication
740
794
  rsyncCommand = 'sshpass';
741
795
  rsyncArgs.push('-p', serverConfig.password);
742
796
  rsyncArgs.push('rsync');
743
-
797
+
744
798
  // Add rsync options
745
799
  rsyncOptions.forEach(opt => rsyncArgs.push(opt));
746
-
800
+
747
801
  // Add SSH command
748
802
  const sshCmd = `ssh ${sshOptions.join(' ')}`;
749
803
  rsyncArgs.push('-e', sshCmd);
750
804
  } else {
751
805
  // Direct rsync for key authentication
752
806
  rsyncCommand = 'rsync';
753
-
807
+
754
808
  // Add rsync options
755
809
  rsyncOptions.forEach(opt => rsyncArgs.push(opt));
756
-
810
+
757
811
  // Add SSH command with all options
758
812
  const sshCmd = `ssh ${sshOptions.join(' ')}`;
759
813
  rsyncArgs.push('-e', sshCmd);
760
-
814
+
761
815
  processEnv.SSH_ASKPASS = '/bin/false';
762
816
  processEnv.DISPLAY = '';
763
817
  }
764
-
818
+
765
819
  // Add source and destination
766
820
  if (direction === 'push') {
767
821
  rsyncArgs.push(localPath);
@@ -770,19 +824,19 @@ server.registerTool(
770
824
  rsyncArgs.push(`${serverConfig.user}@${serverConfig.host}:${remotePath}`);
771
825
  rsyncArgs.push(localPath);
772
826
  }
773
-
827
+
774
828
  const rsyncProcess = spawn(rsyncCommand, rsyncArgs, {
775
829
  stdio: ['ignore', 'pipe', 'pipe'],
776
830
  env: processEnv
777
831
  });
778
-
832
+
779
833
  // Set timeout
780
834
  const timer = setTimeout(() => {
781
835
  killed = true;
782
836
  rsyncProcess.kill('SIGTERM');
783
837
  reject(new Error(`Rsync timeout after ${timeout}ms`));
784
838
  }, timeout);
785
-
839
+
786
840
  // Collect output with size limit
787
841
  rsyncProcess.stdout.on('data', (data) => {
788
842
  const chunk = data.toString();
@@ -792,7 +846,7 @@ server.registerTool(
792
846
  output = output.slice(-50000);
793
847
  }
794
848
  });
795
-
849
+
796
850
  rsyncProcess.stderr.on('data', (data) => {
797
851
  const chunk = data.toString();
798
852
  errorOutput += chunk;
@@ -800,21 +854,21 @@ server.registerTool(
800
854
  errorOutput = errorOutput.slice(-25000);
801
855
  }
802
856
  });
803
-
857
+
804
858
  rsyncProcess.on('error', (err) => {
805
859
  clearTimeout(timer);
806
860
  reject(new Error(`Failed to start rsync: ${err.message}`));
807
861
  });
808
-
862
+
809
863
  rsyncProcess.on('close', (code) => {
810
864
  clearTimeout(timer);
811
-
865
+
812
866
  if (killed) {
813
867
  return; // Already rejected due to timeout
814
868
  }
815
-
869
+
816
870
  const duration = Date.now() - startTime;
817
-
871
+
818
872
  if (code !== 0) {
819
873
  logger.error(`Rsync ${direction} failed`, {
820
874
  server: serverName,
@@ -832,10 +886,10 @@ server.registerTool(
832
886
  errorMsg += `Host: ${hostInfo.host}:${hostInfo.port}\n`;
833
887
  }
834
888
 
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`;
889
+ errorMsg += '\n📍 To fix this issue:\n';
890
+ errorMsg += '1. Verify the server identity\n';
891
+ errorMsg += '2. Use \'ssh_key_manage\' tool with action \'verify\' to check the key\n';
892
+ errorMsg += '3. Use \'ssh_key_manage\' tool with action \'accept\' to update the key if you trust the server\n';
839
893
  errorMsg += `\nOriginal error:\n${errorOutput}`;
840
894
 
841
895
  reject(new Error(errorMsg));
@@ -844,23 +898,23 @@ server.registerTool(
844
898
  }
845
899
  return;
846
900
  }
847
-
901
+
848
902
  // Parse rsync output for statistics
849
903
  let stats = {
850
904
  filesTransferred: 0,
851
905
  totalSize: 0,
852
906
  totalTime: duration
853
907
  };
854
-
908
+
855
909
  // Extract statistics from rsync output
856
910
  const filesMatch = output.match(/Number of files transferred: (\d+)/);
857
911
  const sizeMatch = output.match(/Total transferred file size: ([\d,]+) bytes/);
858
912
  const speedMatch = output.match(/([\d.]+) bytes\/sec/);
859
-
913
+
860
914
  if (filesMatch) stats.filesTransferred = parseInt(filesMatch[1]);
861
915
  if (sizeMatch) stats.totalSize = parseInt(sizeMatch[1].replace(/,/g, ''));
862
916
  if (speedMatch) stats.speed = parseFloat(speedMatch[1]);
863
-
917
+
864
918
  logger.info(`Rsync ${direction} completed`, {
865
919
  server: serverName,
866
920
  direction,
@@ -869,14 +923,14 @@ server.registerTool(
869
923
  totalSize: stats.totalSize,
870
924
  dryRun
871
925
  });
872
-
926
+
873
927
  // Format output
874
928
  let resultText = dryRun ? '🔍 Dry run completed\n' : '✅ Sync completed successfully\n';
875
929
  resultText += `Direction: ${direction === 'push' ? 'Local → Remote' : 'Remote → Local'}\n`;
876
930
  resultText += `Server: ${serverName}\n`;
877
931
  resultText += `Source: ${direction === 'push' ? localPath : remotePath}\n`;
878
932
  resultText += `Destination: ${direction === 'push' ? remotePath : localPath}\n`;
879
-
933
+
880
934
  if (stats.filesTransferred > 0) {
881
935
  resultText += `Files transferred: ${stats.filesTransferred}\n`;
882
936
  if (stats.totalSize > 0) {
@@ -890,23 +944,23 @@ server.registerTool(
890
944
  } else {
891
945
  resultText += 'No files needed to be transferred\n';
892
946
  }
893
-
947
+
894
948
  resultText += `Time: ${(duration / 1000).toFixed(2)} seconds\n`;
895
-
949
+
896
950
  if (verbose && output.length < 5000) {
897
951
  resultText += '\n📋 Sync statistics:\n';
898
952
  // 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') ||
953
+ const statsLines = output.split('\n').filter(line =>
954
+ line.includes('Number of') ||
955
+ line.includes('Total') ||
956
+ line.includes('sent') ||
903
957
  line.includes('received')
904
958
  );
905
959
  if (statsLines.length > 0) {
906
960
  resultText += statsLines.join('\n');
907
961
  }
908
962
  }
909
-
963
+
910
964
  resolve({
911
965
  content: [
912
966
  {
@@ -930,7 +984,7 @@ server.registerTool(
930
984
  }
931
985
  );
932
986
 
933
- server.registerTool(
987
+ registerToolConditional(
934
988
  'ssh_tail',
935
989
  {
936
990
  description: 'Tail remote log files in real-time',
@@ -945,31 +999,31 @@ server.registerTool(
945
999
  async ({ server: serverName, file, lines = 10, follow = true, grep }) => {
946
1000
  try {
947
1001
  const ssh = await getConnection(serverName);
948
-
1002
+
949
1003
  // Build tail command
950
1004
  let command = `tail -n ${lines}`;
951
1005
  if (follow) {
952
1006
  command += ' -f';
953
1007
  }
954
1008
  command += ` "${file}"`;
955
-
1009
+
956
1010
  // Add grep filter if specified
957
1011
  if (grep) {
958
1012
  command += ` | grep "${grep}"`;
959
1013
  }
960
-
1014
+
961
1015
  logger.info(`Starting tail on ${serverName}`, {
962
1016
  file,
963
1017
  lines,
964
1018
  follow,
965
1019
  grep
966
1020
  });
967
-
1021
+
968
1022
  // For follow mode, we need to handle streaming
969
1023
  if (follow) {
970
1024
  // Create a unique session ID for this tail
971
1025
  const sessionId = `tail_${Date.now()}`;
972
-
1026
+
973
1027
  // Store the SSH stream for later cleanup
974
1028
  const stream = await ssh.execCommandStream(command, {
975
1029
  onStdout: (chunk) => {
@@ -980,7 +1034,7 @@ server.registerTool(
980
1034
  console.error(`[ERROR] ${chunk}`);
981
1035
  }
982
1036
  });
983
-
1037
+
984
1038
  return {
985
1039
  content: [
986
1040
  {
@@ -992,16 +1046,16 @@ server.registerTool(
992
1046
  } else {
993
1047
  // Non-follow mode - just get the output
994
1048
  const result = await execCommandWithTimeout(ssh, command, {}, 15000);
995
-
1049
+
996
1050
  if (result.code !== 0) {
997
1051
  throw new Error(result.stderr || 'Failed to tail file');
998
1052
  }
999
-
1053
+
1000
1054
  logger.info(`Tail completed on ${serverName}`, {
1001
1055
  file,
1002
1056
  lines: result.stdout.split('\n').length
1003
1057
  });
1004
-
1058
+
1005
1059
  return {
1006
1060
  content: [
1007
1061
  {
@@ -1016,7 +1070,7 @@ server.registerTool(
1016
1070
  file,
1017
1071
  error: error.message
1018
1072
  });
1019
-
1073
+
1020
1074
  return {
1021
1075
  content: [
1022
1076
  {
@@ -1029,7 +1083,7 @@ server.registerTool(
1029
1083
  }
1030
1084
  );
1031
1085
 
1032
- server.registerTool(
1086
+ registerToolConditional(
1033
1087
  'ssh_monitor',
1034
1088
  {
1035
1089
  description: 'Monitor system resources (CPU, RAM, disk) on remote server',
@@ -1043,62 +1097,62 @@ server.registerTool(
1043
1097
  async ({ server: serverName, type = 'overview', interval, duration }) => {
1044
1098
  try {
1045
1099
  const ssh = await getConnection(serverName);
1046
-
1100
+
1047
1101
  logger.info(`Starting system monitoring on ${serverName}`, {
1048
1102
  type,
1049
1103
  interval,
1050
1104
  duration
1051
1105
  });
1052
-
1106
+
1053
1107
  let commands = {};
1054
1108
  let output = {};
1055
-
1109
+
1056
1110
  // Define monitoring commands based on type
1057
1111
  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;
1112
+ case 'cpu':
1113
+ commands.cpu = 'top -bn1 | head -20';
1114
+ commands.load = 'uptime';
1115
+ commands.cores = 'nproc';
1116
+ break;
1117
+
1118
+ case 'memory':
1119
+ commands.memory = 'free -h';
1120
+ commands.swap = 'swapon --show';
1121
+ commands.top_mem = 'ps aux --sort=-%mem | head -10';
1122
+ break;
1123
+
1124
+ case 'disk':
1125
+ commands.disk = 'df -h';
1126
+ commands.inodes = 'df -i';
1127
+ commands.io = 'iostat -x 1 2 | tail -n +4';
1128
+ break;
1129
+
1130
+ case 'network':
1131
+ commands.interfaces = 'ip -s link show';
1132
+ commands.connections = 'ss -tunap | head -20';
1133
+ commands.netstat = 'netstat -i';
1134
+ break;
1135
+
1136
+ case 'process':
1137
+ commands.process = 'ps aux --sort=-%cpu | head -20';
1138
+ commands.count = 'ps aux | wc -l';
1139
+ commands.zombies = 'ps aux | grep -c defunct || echo 0';
1140
+ break;
1141
+
1142
+ case 'overview':
1143
+ default:
1144
+ commands.uptime = 'uptime';
1145
+ commands.cpu = 'mpstat 1 1 2>/dev/null || top -bn1 | grep \'Cpu\'';
1146
+ commands.memory = 'free -h';
1147
+ commands.disk = 'df -h | grep -E \'^/dev/\' | head -5';
1148
+ commands.load = 'cat /proc/loadavg';
1149
+ commands.processes = 'ps aux | wc -l';
1150
+ break;
1097
1151
  }
1098
-
1152
+
1099
1153
  // Execute all monitoring commands
1100
1154
  const startTime = Date.now();
1101
-
1155
+
1102
1156
  for (const [key, cmd] of Object.entries(commands)) {
1103
1157
  try {
1104
1158
  const result = await execCommandWithTimeout(ssh, cmd, {}, 10000);
@@ -1111,69 +1165,69 @@ server.registerTool(
1111
1165
  output[key] = `Error: ${err.message}`;
1112
1166
  }
1113
1167
  }
1114
-
1168
+
1115
1169
  const monitoringDuration = Date.now() - startTime;
1116
-
1170
+
1117
1171
  // Format the output based on type
1118
1172
  let formattedOutput = `📊 System Monitor - ${serverName}\n`;
1119
1173
  formattedOutput += `Type: ${type} | Time: ${new Date().toISOString()}\n`;
1120
1174
  formattedOutput += `Collection time: ${monitoringDuration}ms\n`;
1121
1175
  formattedOutput += '━'.repeat(50) + '\n\n';
1122
-
1176
+
1123
1177
  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;
1178
+ case 'overview':
1179
+ formattedOutput += `⏱️ UPTIME\n${output.uptime || 'N/A'}\n\n`;
1180
+ formattedOutput += `💻 CPU\n${output.cpu || 'N/A'}\n\n`;
1181
+ formattedOutput += `📈 LOAD AVERAGE\n${output.load || 'N/A'}\n\n`;
1182
+ formattedOutput += `💾 MEMORY\n${output.memory || 'N/A'}\n\n`;
1183
+ formattedOutput += `💿 DISK USAGE\n${output.disk || 'N/A'}\n\n`;
1184
+ formattedOutput += `📝 PROCESSES: ${output.processes || 'N/A'}\n`;
1185
+ break;
1186
+
1187
+ case 'cpu':
1188
+ formattedOutput += `🖥️ CPU CORES: ${output.cores || 'N/A'}\n\n`;
1189
+ formattedOutput += `📊 LOAD\n${output.load || 'N/A'}\n\n`;
1190
+ formattedOutput += `📈 TOP PROCESSES\n${output.cpu || 'N/A'}\n`;
1191
+ break;
1192
+
1193
+ case 'memory':
1194
+ formattedOutput += `💾 MEMORY USAGE\n${output.memory || 'N/A'}\n\n`;
1195
+ formattedOutput += `🔄 SWAP\n${output.swap || 'No swap configured'}\n\n`;
1196
+ formattedOutput += `📊 TOP MEMORY CONSUMERS\n${output.top_mem || 'N/A'}\n`;
1197
+ break;
1198
+
1199
+ case 'disk':
1200
+ formattedOutput += `💿 DISK SPACE\n${output.disk || 'N/A'}\n\n`;
1201
+ formattedOutput += `📁 INODE USAGE\n${output.inodes || 'N/A'}\n\n`;
1202
+ formattedOutput += `⚡ I/O STATS\n${output.io || 'N/A'}\n`;
1203
+ break;
1204
+
1205
+ case 'network':
1206
+ formattedOutput += `🌐 NETWORK INTERFACES\n${output.interfaces || 'N/A'}\n\n`;
1207
+ formattedOutput += `🔌 CONNECTIONS\n${output.connections || 'N/A'}\n\n`;
1208
+ formattedOutput += `📊 INTERFACE STATS\n${output.netstat || 'N/A'}\n`;
1209
+ break;
1210
+
1211
+ case 'process':
1212
+ formattedOutput += `📝 PROCESS COUNT: ${output.count || 'N/A'}\n`;
1213
+ formattedOutput += `⚠️ ZOMBIE PROCESSES: ${output.zombies || '0'}\n\n`;
1214
+ formattedOutput += `📊 TOP PROCESSES BY CPU\n${output.process || 'N/A'}\n`;
1215
+ break;
1162
1216
  }
1163
-
1217
+
1164
1218
  // Log monitoring results
1165
1219
  logger.info(`System monitoring completed on ${serverName}`, {
1166
1220
  type,
1167
1221
  duration: `${monitoringDuration}ms`,
1168
1222
  metrics: Object.keys(output).length
1169
1223
  });
1170
-
1224
+
1171
1225
  // If continuous monitoring requested
1172
1226
  if (interval && duration) {
1173
1227
  formattedOutput += `\n\n⏰ Continuous monitoring: Every ${interval}s for ${duration}s\n`;
1174
- formattedOutput += `(Not implemented in this version - would require streaming support)`;
1228
+ formattedOutput += '(Not implemented in this version - would require streaming support)';
1175
1229
  }
1176
-
1230
+
1177
1231
  return {
1178
1232
  content: [
1179
1233
  {
@@ -1187,7 +1241,7 @@ server.registerTool(
1187
1241
  type,
1188
1242
  error: error.message
1189
1243
  });
1190
-
1244
+
1191
1245
  return {
1192
1246
  content: [
1193
1247
  {
@@ -1200,7 +1254,7 @@ server.registerTool(
1200
1254
  }
1201
1255
  );
1202
1256
 
1203
- server.registerTool(
1257
+ registerToolConditional(
1204
1258
  'ssh_history',
1205
1259
  {
1206
1260
  description: 'View SSH command history',
@@ -1215,38 +1269,38 @@ server.registerTool(
1215
1269
  try {
1216
1270
  // Get history from logger
1217
1271
  let history = logger.getHistory(limit * 2); // Get more to account for filtering
1218
-
1272
+
1219
1273
  // Apply filters
1220
1274
  if (server) {
1221
1275
  history = history.filter(h => h.server?.toLowerCase().includes(server.toLowerCase()));
1222
1276
  }
1223
-
1277
+
1224
1278
  if (success !== undefined) {
1225
1279
  history = history.filter(h => h.success === success);
1226
1280
  }
1227
-
1281
+
1228
1282
  if (search) {
1229
1283
  history = history.filter(h => h.command?.toLowerCase().includes(search.toLowerCase()));
1230
1284
  }
1231
-
1285
+
1232
1286
  // Limit results
1233
1287
  history = history.slice(-limit);
1234
-
1288
+
1235
1289
  // Format output
1236
- let output = `📜 SSH Command History\n`;
1290
+ let output = '📜 SSH Command History\n';
1237
1291
  output += `Showing last ${history.length} commands`;
1238
-
1292
+
1239
1293
  const filters = [];
1240
1294
  if (server) filters.push(`server: ${server}`);
1241
1295
  if (success !== undefined) filters.push(success ? 'successful only' : 'failed only');
1242
1296
  if (search) filters.push(`search: ${search}`);
1243
-
1297
+
1244
1298
  if (filters.length > 0) {
1245
1299
  output += ` (filtered: ${filters.join(', ')})`;
1246
1300
  }
1247
-
1301
+
1248
1302
  output += '\n' + '━'.repeat(60) + '\n\n';
1249
-
1303
+
1250
1304
  if (history.length === 0) {
1251
1305
  output += 'No commands found matching the criteria.\n';
1252
1306
  } else {
@@ -1254,7 +1308,7 @@ server.registerTool(
1254
1308
  const time = new Date(entry.timestamp).toLocaleString();
1255
1309
  const status = entry.success ? '✅' : '❌';
1256
1310
  const duration = entry.duration || 'N/A';
1257
-
1311
+
1258
1312
  output += `${history.length - index}. ${status} [${time}]\n`;
1259
1313
  output += ` Server: ${entry.server || 'unknown'}\n`;
1260
1314
  output += ` Command: ${entry.command?.substring(0, 100) || 'N/A'}`;
@@ -1263,24 +1317,24 @@ server.registerTool(
1263
1317
  }
1264
1318
  output += '\n';
1265
1319
  output += ` Duration: ${duration}`;
1266
-
1320
+
1267
1321
  if (!entry.success && entry.error) {
1268
1322
  output += `\n Error: ${entry.error}`;
1269
1323
  }
1270
-
1324
+
1271
1325
  output += '\n\n';
1272
1326
  });
1273
1327
  }
1274
-
1328
+
1275
1329
  output += '━'.repeat(60) + '\n';
1276
1330
  output += `Total commands in history: ${logger.getHistory(1000).length}\n`;
1277
-
1331
+
1278
1332
  logger.info('Command history retrieved', {
1279
1333
  limit,
1280
1334
  filters: filters.length,
1281
1335
  results: history.length
1282
1336
  });
1283
-
1337
+
1284
1338
  return {
1285
1339
  content: [
1286
1340
  {
@@ -1304,7 +1358,7 @@ server.registerTool(
1304
1358
 
1305
1359
  // SSH Session Management Tools
1306
1360
 
1307
- server.registerTool(
1361
+ registerToolConditional(
1308
1362
  'ssh_session_start',
1309
1363
  {
1310
1364
  description: 'Start a persistent SSH session that maintains state and context',
@@ -1317,15 +1371,15 @@ server.registerTool(
1317
1371
  try {
1318
1372
  const ssh = await getConnection(serverName);
1319
1373
  const session = await createSession(serverName, ssh);
1320
-
1374
+
1321
1375
  const sessionName = name || `Session on ${serverName}`;
1322
-
1376
+
1323
1377
  logger.info('SSH session started', {
1324
1378
  id: session.id,
1325
1379
  server: serverName,
1326
1380
  name: sessionName
1327
1381
  });
1328
-
1382
+
1329
1383
  return {
1330
1384
  content: [
1331
1385
  {
@@ -1339,7 +1393,7 @@ server.registerTool(
1339
1393
  server: serverName,
1340
1394
  error: error.message
1341
1395
  });
1342
-
1396
+
1343
1397
  return {
1344
1398
  content: [
1345
1399
  {
@@ -1352,7 +1406,7 @@ server.registerTool(
1352
1406
  }
1353
1407
  );
1354
1408
 
1355
- server.registerTool(
1409
+ registerToolConditional(
1356
1410
  'ssh_session_send',
1357
1411
  {
1358
1412
  description: 'Send a command to an existing SSH session',
@@ -1365,36 +1419,36 @@ server.registerTool(
1365
1419
  async ({ session: sessionId, command, timeout = 30000 }) => {
1366
1420
  try {
1367
1421
  const session = getSession(sessionId);
1368
-
1422
+
1369
1423
  const startTime = Date.now();
1370
1424
  const result = await session.execute(command, { timeout });
1371
1425
  const duration = Date.now() - startTime;
1372
-
1426
+
1373
1427
  logger.info('Session command executed', {
1374
1428
  session: sessionId,
1375
1429
  command: command.substring(0, 50),
1376
1430
  success: result.success,
1377
1431
  duration: `${duration}ms`
1378
1432
  });
1379
-
1433
+
1380
1434
  let output = `📟 Session: ${sessionId}\n`;
1381
1435
  output += `Server: ${session.serverName}\n`;
1382
1436
  output += `Working Directory: ${session.context.cwd}\n`;
1383
1437
  output += `Command: ${command}\n`;
1384
1438
  output += `Duration: ${duration}ms\n`;
1385
1439
  output += '━'.repeat(60) + '\n\n';
1386
-
1440
+
1387
1441
  if (result.success) {
1388
1442
  output += '✅ Output:\n' + result.output;
1389
1443
  } else {
1390
1444
  output += '❌ Error:\n' + (result.error || result.output);
1391
1445
  }
1392
-
1446
+
1393
1447
  // Add session state info
1394
1448
  output += '\n\n' + '━'.repeat(60) + '\n';
1395
1449
  output += `Session State: ${session.state}\n`;
1396
1450
  output += `Commands Executed: ${session.context.history.length}\n`;
1397
-
1451
+
1398
1452
  return {
1399
1453
  content: [
1400
1454
  {
@@ -1409,7 +1463,7 @@ server.registerTool(
1409
1463
  command,
1410
1464
  error: error.message
1411
1465
  });
1412
-
1466
+
1413
1467
  return {
1414
1468
  content: [
1415
1469
  {
@@ -1422,7 +1476,7 @@ server.registerTool(
1422
1476
  }
1423
1477
  );
1424
1478
 
1425
- server.registerTool(
1479
+ registerToolConditional(
1426
1480
  'ssh_session_list',
1427
1481
  {
1428
1482
  description: 'List all active SSH sessions',
@@ -1433,17 +1487,17 @@ server.registerTool(
1433
1487
  async ({ server }) => {
1434
1488
  try {
1435
1489
  let sessions = listSessions();
1436
-
1490
+
1437
1491
  // Filter by server if specified
1438
1492
  if (server) {
1439
- sessions = sessions.filter(s =>
1493
+ sessions = sessions.filter(s =>
1440
1494
  s.server.toLowerCase().includes(server.toLowerCase())
1441
1495
  );
1442
1496
  }
1443
-
1444
- let output = `📋 Active SSH Sessions\n`;
1497
+
1498
+ let output = '📋 Active SSH Sessions\n';
1445
1499
  output += '━'.repeat(60) + '\n\n';
1446
-
1500
+
1447
1501
  if (sessions.length === 0) {
1448
1502
  output += 'No active sessions';
1449
1503
  if (server) {
@@ -1454,7 +1508,7 @@ server.registerTool(
1454
1508
  sessions.forEach((session, index) => {
1455
1509
  const age = Math.floor((Date.now() - new Date(session.created).getTime()) / 1000);
1456
1510
  const idle = Math.floor((Date.now() - new Date(session.lastActivity).getTime()) / 1000);
1457
-
1511
+
1458
1512
  output += `${index + 1}. Session: ${session.id}\n`;
1459
1513
  output += ` Server: ${session.server}\n`;
1460
1514
  output += ` State: ${session.state}\n`;
@@ -1462,23 +1516,23 @@ server.registerTool(
1462
1516
  output += ` Commands Run: ${session.historyCount}\n`;
1463
1517
  output += ` Age: ${formatDuration(age)}\n`;
1464
1518
  output += ` Idle: ${formatDuration(idle)}\n`;
1465
-
1519
+
1466
1520
  if (session.variables.length > 0) {
1467
1521
  output += ` Variables: ${session.variables.join(', ')}\n`;
1468
1522
  }
1469
-
1523
+
1470
1524
  output += '\n';
1471
1525
  });
1472
1526
  }
1473
-
1527
+
1474
1528
  output += '━'.repeat(60) + '\n';
1475
1529
  output += `Total Active Sessions: ${sessions.length}\n`;
1476
-
1530
+
1477
1531
  logger.info('Listed SSH sessions', {
1478
1532
  total: sessions.length,
1479
1533
  filter: server
1480
1534
  });
1481
-
1535
+
1482
1536
  return {
1483
1537
  content: [
1484
1538
  {
@@ -1500,7 +1554,7 @@ server.registerTool(
1500
1554
  }
1501
1555
  );
1502
1556
 
1503
- server.registerTool(
1557
+ registerToolConditional(
1504
1558
  'ssh_session_close',
1505
1559
  {
1506
1560
  description: 'Close an SSH session',
@@ -1513,7 +1567,7 @@ server.registerTool(
1513
1567
  if (sessionId === 'all') {
1514
1568
  const sessions = listSessions();
1515
1569
  const count = sessions.length;
1516
-
1570
+
1517
1571
  sessions.forEach(s => {
1518
1572
  try {
1519
1573
  closeSession(s.id);
@@ -1521,9 +1575,9 @@ server.registerTool(
1521
1575
  // Ignore individual close errors
1522
1576
  }
1523
1577
  });
1524
-
1578
+
1525
1579
  logger.info('Closed all SSH sessions', { count });
1526
-
1580
+
1527
1581
  return {
1528
1582
  content: [
1529
1583
  {
@@ -1534,9 +1588,9 @@ server.registerTool(
1534
1588
  };
1535
1589
  } else {
1536
1590
  closeSession(sessionId);
1537
-
1591
+
1538
1592
  logger.info('SSH session closed', { session: sessionId });
1539
-
1593
+
1540
1594
  return {
1541
1595
  content: [
1542
1596
  {
@@ -1551,7 +1605,7 @@ server.registerTool(
1551
1605
  session: sessionId,
1552
1606
  error: error.message
1553
1607
  });
1554
-
1608
+
1555
1609
  return {
1556
1610
  content: [
1557
1611
  {
@@ -1577,7 +1631,7 @@ function formatDuration(seconds) {
1577
1631
 
1578
1632
  // Server Group Management Tools
1579
1633
 
1580
- server.registerTool(
1634
+ registerToolConditional(
1581
1635
  'ssh_execute_group',
1582
1636
  {
1583
1637
  description: 'Execute command on a group of servers',
@@ -1597,15 +1651,15 @@ server.registerTool(
1597
1651
  groupName,
1598
1652
  async (serverName) => {
1599
1653
  const ssh = await getConnection(serverName);
1600
-
1654
+
1601
1655
  // Build full command with cwd if provided
1602
1656
  const servers = loadServerConfig();
1603
1657
  const serverConfig = servers[serverName.toLowerCase()];
1604
1658
  const workingDir = cwd || serverConfig?.default_dir;
1605
1659
  const fullCommand = workingDir ? `cd ${workingDir} && ${command}` : command;
1606
-
1660
+
1607
1661
  const execResult = await execCommandWithTimeout(ssh, fullCommand, {}, 30000);
1608
-
1662
+
1609
1663
  return {
1610
1664
  stdout: execResult.stdout,
1611
1665
  stderr: execResult.stderr,
@@ -1615,17 +1669,17 @@ server.registerTool(
1615
1669
  },
1616
1670
  { strategy, delay, stopOnError }
1617
1671
  );
1618
-
1672
+
1619
1673
  // Format output
1620
1674
  let output = `🚀 Group Execution: ${groupName}\n`;
1621
1675
  output += `Command: ${command}\n`;
1622
1676
  output += `Strategy: ${result.strategy}\n`;
1623
1677
  output += '━'.repeat(60) + '\n\n';
1624
-
1678
+
1625
1679
  // Show results for each server
1626
1680
  result.results.forEach(({ server, success, result: execResult, error }) => {
1627
1681
  output += `📍 ${server}: ${success ? '✅ SUCCESS' : '❌ FAILED'}\n`;
1628
-
1682
+
1629
1683
  if (success && execResult) {
1630
1684
  if (execResult.stdout) {
1631
1685
  output += ` Output: ${execResult.stdout.substring(0, 200)}`;
@@ -1640,7 +1694,7 @@ server.registerTool(
1640
1694
  }
1641
1695
  output += '\n';
1642
1696
  });
1643
-
1697
+
1644
1698
  // Summary
1645
1699
  output += '━'.repeat(60) + '\n';
1646
1700
  output += `Summary: ${result.summary.successful}/${result.summary.total} successful`;
@@ -1648,13 +1702,13 @@ server.registerTool(
1648
1702
  output += ` (${result.summary.failed} failed)`;
1649
1703
  }
1650
1704
  output += '\n';
1651
-
1705
+
1652
1706
  logger.info('Group command executed', {
1653
1707
  group: groupName,
1654
1708
  command: command.substring(0, 50),
1655
1709
  ...result.summary
1656
1710
  });
1657
-
1711
+
1658
1712
  return {
1659
1713
  content: [
1660
1714
  {
@@ -1668,7 +1722,7 @@ server.registerTool(
1668
1722
  group: groupName,
1669
1723
  error: error.message
1670
1724
  });
1671
-
1725
+
1672
1726
  return {
1673
1727
  content: [
1674
1728
  {
@@ -1681,7 +1735,7 @@ server.registerTool(
1681
1735
  }
1682
1736
  );
1683
1737
 
1684
- server.registerTool(
1738
+ registerToolConditional(
1685
1739
  'ssh_group_manage',
1686
1740
  {
1687
1741
  description: 'Manage server groups (create, update, delete, list)',
@@ -1699,94 +1753,95 @@ server.registerTool(
1699
1753
  try {
1700
1754
  let result;
1701
1755
  let output = '';
1702
-
1756
+
1703
1757
  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`;
1758
+ case 'create':
1759
+ if (!name) throw new Error('Group name required for create');
1760
+ result = createGroup(name, servers || [], {
1761
+ description,
1762
+ strategy,
1763
+ delay,
1764
+ stopOnError
1765
+ });
1766
+ output = `✅ Group '${name}' created\n`;
1767
+ output += `Servers: ${result.servers.join(', ') || 'none'}\n`;
1768
+ output += `Strategy: ${result.strategy}\n`;
1769
+ break;
1770
+
1771
+ case 'update':
1772
+ if (!name) throw new Error('Group name required for update');
1773
+ result = updateGroup(name, {
1774
+ servers,
1775
+ description,
1776
+ strategy,
1777
+ delay,
1778
+ stopOnError
1779
+ });
1780
+ output = `✅ Group '${name}' updated\n`;
1781
+ output += `Servers: ${result.servers.join(', ')}\n`;
1782
+ break;
1783
+
1784
+ case 'delete':
1785
+ if (!name) throw new Error('Group name required for delete');
1786
+ deleteGroup(name);
1787
+ output = `✅ Group '${name}' deleted`;
1788
+ break;
1789
+
1790
+ case 'add-servers':
1791
+ if (!name) throw new Error('Group name required');
1792
+ if (!servers || servers.length === 0) throw new Error('Servers required');
1793
+ result = addServersToGroup(name, servers);
1794
+ output = `✅ Added ${servers.length} servers to '${name}'\n`;
1795
+ output += `Total servers: ${result.servers.length}\n`;
1796
+ output += `Members: ${result.servers.join(', ')}`;
1797
+ break;
1798
+
1799
+ case 'remove-servers':
1800
+ if (!name) throw new Error('Group name required');
1801
+ if (!servers || servers.length === 0) throw new Error('Servers required');
1802
+ result = removeServersFromGroup(name, servers);
1803
+ output = `✅ Removed ${servers.length} servers from '${name}'\n`;
1804
+ output += `Remaining: ${result.servers.length}\n`;
1805
+ output += `Members: ${result.servers.join(', ') || 'none'}`;
1806
+ break;
1807
+
1808
+ case 'list': {
1809
+ const groups = listGroups();
1810
+ output = '📋 Server Groups\n';
1811
+ output += '━'.repeat(60) + '\n\n';
1812
+
1813
+ groups.forEach(group => {
1814
+ output += `📁 ${group.name}`;
1815
+ if (group.dynamic) output += ' (dynamic)';
1816
+ output += '\n';
1817
+ output += ` Description: ${group.description}\n`;
1818
+ output += ` Servers: ${group.serverCount} servers\n`;
1819
+ if (group.servers.length > 0) {
1820
+ output += ` Members: ${group.servers.slice(0, 5).join(', ')}`;
1821
+ if (group.servers.length > 5) output += ` ... +${group.servers.length - 5} more`;
1773
1822
  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}`);
1823
+ }
1824
+ output += ` Strategy: ${group.strategy || 'parallel'}\n`;
1825
+ if (group.delay) output += ` Delay: ${group.delay}ms\n`;
1826
+ if (group.stopOnError) output += ' Stop on error: yes\n';
1827
+ output += '\n';
1828
+ });
1829
+
1830
+ output += '━'.repeat(60) + '\n';
1831
+ output += `Total groups: ${groups.length}`;
1832
+ break;
1782
1833
  }
1783
-
1834
+
1835
+ default:
1836
+ throw new Error(`Unknown action: ${action}`);
1837
+ }
1838
+
1784
1839
  logger.info('Group management action completed', {
1785
1840
  action,
1786
1841
  name,
1787
1842
  servers: servers?.length
1788
1843
  });
1789
-
1844
+
1790
1845
  return {
1791
1846
  content: [
1792
1847
  {
@@ -1801,7 +1856,7 @@ server.registerTool(
1801
1856
  name,
1802
1857
  error: error.message
1803
1858
  });
1804
-
1859
+
1805
1860
  return {
1806
1861
  content: [
1807
1862
  {
@@ -1814,7 +1869,7 @@ server.registerTool(
1814
1869
  }
1815
1870
  );
1816
1871
 
1817
- server.registerTool(
1872
+ registerToolConditional(
1818
1873
  'ssh_list_servers',
1819
1874
  {
1820
1875
  description: 'List all configured SSH servers',
@@ -1844,7 +1899,7 @@ server.registerTool(
1844
1899
  );
1845
1900
 
1846
1901
  // New deploy tool for automated deployment
1847
- server.registerTool(
1902
+ registerToolConditional(
1848
1903
  'ssh_deploy',
1849
1904
  {
1850
1905
  description: 'Deploy files to remote server with automatic permission handling',
@@ -1945,7 +2000,7 @@ server.registerTool(
1945
2000
  );
1946
2001
 
1947
2002
  // Execute command with sudo support
1948
- server.registerTool(
2003
+ registerToolConditional(
1949
2004
  'ssh_execute_sudo',
1950
2005
  {
1951
2006
  description: 'Execute command with sudo on remote server',
@@ -2014,7 +2069,7 @@ server.registerTool(
2014
2069
  );
2015
2070
 
2016
2071
  // Manage command aliases
2017
- server.registerTool(
2072
+ registerToolConditional(
2018
2073
  'ssh_command_alias',
2019
2074
  {
2020
2075
  description: 'Manage command aliases for frequently used commands',
@@ -2115,7 +2170,7 @@ server.registerTool(
2115
2170
  );
2116
2171
 
2117
2172
  // Manage hooks
2118
- server.registerTool(
2173
+ registerToolConditional(
2119
2174
  'ssh_hooks',
2120
2175
  {
2121
2176
  description: 'Manage automation hooks for SSH operations',
@@ -2207,7 +2262,7 @@ server.registerTool(
2207
2262
  );
2208
2263
 
2209
2264
  // Manage profiles
2210
- server.registerTool(
2265
+ registerToolConditional(
2211
2266
  'ssh_profile',
2212
2267
  {
2213
2268
  description: 'Manage SSH Manager profiles for different project types',
@@ -2287,7 +2342,7 @@ server.registerTool(
2287
2342
  );
2288
2343
 
2289
2344
  // Connection management tool
2290
- server.registerTool(
2345
+ registerToolConditional(
2291
2346
  'ssh_connection_status',
2292
2347
  {
2293
2348
  description: 'Check status of SSH connections and manage connection pool',
@@ -2404,7 +2459,7 @@ server.registerTool(
2404
2459
  );
2405
2460
 
2406
2461
  // SSH Tunnel Management - Create tunnel
2407
- server.registerTool(
2462
+ registerToolConditional(
2408
2463
  'ssh_tunnel_create',
2409
2464
  {
2410
2465
  description: 'Create SSH tunnel (port forwarding or SOCKS proxy)',
@@ -2421,13 +2476,15 @@ server.registerTool(
2421
2476
  try {
2422
2477
  const servers = loadServerConfig();
2423
2478
  const resolvedName = resolveServerName(server, servers);
2424
-
2479
+
2425
2480
  if (!resolvedName) {
2426
2481
  throw new Error(`Server "${server}" not found`);
2427
2482
  }
2428
-
2429
- const ssh = await getSSHConnection(resolvedName);
2430
-
2483
+
2484
+ const serverConfig = servers[resolvedName];
2485
+ const ssh = new SSHManager(serverConfig);
2486
+ await ssh.connect();
2487
+
2431
2488
  const config = {
2432
2489
  type,
2433
2490
  localHost: localHost || '127.0.0.1',
@@ -2435,14 +2492,14 @@ server.registerTool(
2435
2492
  remoteHost,
2436
2493
  remotePort
2437
2494
  };
2438
-
2495
+
2439
2496
  const tunnel = await createTunnel(resolvedName, ssh, config);
2440
-
2441
- let output = `✅ SSH tunnel created\n`;
2497
+
2498
+ let output = '✅ SSH tunnel created\n';
2442
2499
  output += `ID: ${tunnel.id}\n`;
2443
2500
  output += `Type: ${type}\n`;
2444
2501
  output += `Local: ${config.localHost}:${localPort}\n`;
2445
-
2502
+
2446
2503
  if (type === 'local') {
2447
2504
  output += `Remote: ${remoteHost}:${remotePort}\n`;
2448
2505
  output += `\n📌 Access remote ${remoteHost}:${remotePort} via local ${config.localHost}:${localPort}`;
@@ -2454,14 +2511,14 @@ server.registerTool(
2454
2511
  output += `\n📌 SOCKS5 proxy available at ${config.localHost}:${localPort}`;
2455
2512
  output += `\n💡 Configure browser/app: SOCKS5 proxy ${config.localHost}:${localPort}`;
2456
2513
  }
2457
-
2514
+
2458
2515
  logger.info('SSH tunnel created', {
2459
2516
  id: tunnel.id,
2460
2517
  server: resolvedName,
2461
2518
  type,
2462
2519
  local: `${config.localHost}:${localPort}`
2463
2520
  });
2464
-
2521
+
2465
2522
  return {
2466
2523
  content: [
2467
2524
  {
@@ -2485,7 +2542,7 @@ server.registerTool(
2485
2542
  );
2486
2543
 
2487
2544
  // List active tunnels
2488
- server.registerTool(
2545
+ registerToolConditional(
2489
2546
  'ssh_tunnel_list',
2490
2547
  {
2491
2548
  description: 'List active SSH tunnels',
@@ -2497,16 +2554,16 @@ server.registerTool(
2497
2554
  try {
2498
2555
  const servers = loadServerConfig();
2499
2556
  let resolvedName = null;
2500
-
2557
+
2501
2558
  if (server) {
2502
2559
  resolvedName = resolveServerName(server, servers);
2503
2560
  if (!resolvedName) {
2504
2561
  throw new Error(`Server "${server}" not found`);
2505
2562
  }
2506
2563
  }
2507
-
2564
+
2508
2565
  const tunnels = listTunnels(resolvedName);
2509
-
2566
+
2510
2567
  if (tunnels.length === 0) {
2511
2568
  return {
2512
2569
  content: [
@@ -2517,21 +2574,21 @@ server.registerTool(
2517
2574
  ]
2518
2575
  };
2519
2576
  }
2520
-
2521
- let output = `📋 Active SSH Tunnels\n`;
2577
+
2578
+ let output = '📋 Active SSH Tunnels\n';
2522
2579
  output += '━'.repeat(60) + '\n\n';
2523
-
2580
+
2524
2581
  tunnels.forEach(tunnel => {
2525
2582
  output += `🔧 ${tunnel.id}\n`;
2526
2583
  output += ` Server: ${tunnel.server}\n`;
2527
2584
  output += ` Type: ${tunnel.type}\n`;
2528
2585
  output += ` State: ${tunnel.state}\n`;
2529
2586
  output += ` Local: ${tunnel.config.localHost}:${tunnel.config.localPort}\n`;
2530
-
2587
+
2531
2588
  if (tunnel.type !== 'dynamic') {
2532
2589
  output += ` Remote: ${tunnel.config.remoteHost}:${tunnel.config.remotePort}\n`;
2533
2590
  }
2534
-
2591
+
2535
2592
  output += ` Active connections: ${tunnel.activeConnections}\n`;
2536
2593
  output += ` Total connections: ${tunnel.stats.connectionsTotal}\n`;
2537
2594
  output += ` Bytes transferred: ${(tunnel.stats.bytesTransferred / 1024).toFixed(2)} KB\n`;
@@ -2540,10 +2597,10 @@ server.registerTool(
2540
2597
  output += ` Last activity: ${new Date(tunnel.lastActivity).toLocaleString()}\n`;
2541
2598
  output += '\n';
2542
2599
  });
2543
-
2600
+
2544
2601
  output += '━'.repeat(60) + '\n';
2545
2602
  output += `Total tunnels: ${tunnels.length}`;
2546
-
2603
+
2547
2604
  return {
2548
2605
  content: [
2549
2606
  {
@@ -2567,7 +2624,7 @@ server.registerTool(
2567
2624
  );
2568
2625
 
2569
2626
  // Close a tunnel
2570
- server.registerTool(
2627
+ registerToolConditional(
2571
2628
  'ssh_tunnel_close',
2572
2629
  {
2573
2630
  description: 'Close an SSH tunnel',
@@ -2581,33 +2638,33 @@ server.registerTool(
2581
2638
  if (!tunnelId && !server) {
2582
2639
  throw new Error('Either tunnelId or server must be specified');
2583
2640
  }
2584
-
2641
+
2585
2642
  let output = '';
2586
-
2643
+
2587
2644
  if (tunnelId) {
2588
2645
  // Close specific tunnel
2589
2646
  closeTunnel(tunnelId);
2590
2647
  output = `✅ Tunnel ${tunnelId} closed`;
2591
-
2648
+
2592
2649
  logger.info('SSH tunnel closed', { id: tunnelId });
2593
2650
  } else if (server) {
2594
2651
  // Close all tunnels for server
2595
2652
  const servers = loadServerConfig();
2596
2653
  const resolvedName = resolveServerName(server, servers);
2597
-
2654
+
2598
2655
  if (!resolvedName) {
2599
2656
  throw new Error(`Server "${server}" not found`);
2600
2657
  }
2601
-
2658
+
2602
2659
  const count = closeServerTunnels(resolvedName);
2603
2660
  output = `✅ Closed ${count} tunnel(s) for server ${resolvedName}`;
2604
-
2661
+
2605
2662
  logger.info('Server tunnels closed', {
2606
2663
  server: resolvedName,
2607
2664
  count
2608
2665
  });
2609
2666
  }
2610
-
2667
+
2611
2668
  return {
2612
2669
  content: [
2613
2670
  {
@@ -2631,7 +2688,7 @@ server.registerTool(
2631
2688
  );
2632
2689
 
2633
2690
  // Manage SSH host keys
2634
- server.registerTool(
2691
+ registerToolConditional(
2635
2692
  'ssh_key_manage',
2636
2693
  {
2637
2694
  description: 'Manage SSH host keys for security verification',
@@ -2658,207 +2715,207 @@ server.registerTool(
2658
2715
  }
2659
2716
 
2660
2717
  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
- });
2718
+ case 'verify': {
2719
+ // Check if host key has changed
2720
+ const verification = await hasHostKeyChanged(host, port);
2721
+
2722
+ if (verification.changed) {
2723
+ // Execute pre-connect-key-change hook
2724
+ await executeHook('pre-connect-key-change', {
2725
+ server: resolvedName,
2726
+ host,
2727
+ port,
2728
+ currentFingerprints: verification.currentFingerprints,
2729
+ newFingerprints: verification.newFingerprints
2730
+ });
2674
2731
 
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`;
2732
+ let output = `⚠️ SSH host key has changed for ${server} (${host}:${port})\n\n`;
2733
+ output += 'Current fingerprints:\n';
2734
+ verification.currentFingerprints.forEach(fp => {
2735
+ output += ` ${fp}\n`;
2736
+ });
2737
+ output += '\nNew fingerprints:\n';
2738
+ verification.newFingerprints.forEach(fp => {
2739
+ output += ` ${fp}\n`;
2740
+ });
2741
+ output += '\n⚠️ This could indicate a security issue or server reinstallation.\n';
2742
+ output += 'Use \'ssh_key_manage\' with action \'accept\' to update the key if you trust this change.';
2698
2743
 
2699
- if (verification.reason === 'not_in_known_hosts') {
2700
- output += `\nℹ️ Host not in known_hosts. Use 'accept' action to add it.`;
2701
- }
2744
+ return {
2745
+ content: [
2746
+ {
2747
+ type: 'text',
2748
+ text: output
2749
+ }
2750
+ ]
2751
+ };
2752
+ } else {
2753
+ let output = `✅ SSH host key verified for ${server} (${host}:${port})\n`;
2754
+ output += `Reason: ${verification.reason}\n`;
2702
2755
 
2703
- return {
2704
- content: [
2705
- {
2706
- type: 'text',
2707
- text: output
2708
- }
2709
- ]
2710
- };
2756
+ if (verification.reason === 'not_in_known_hosts') {
2757
+ output += '\nℹ️ Host not in known_hosts. Use \'accept\' action to add it.';
2711
2758
  }
2712
- }
2713
-
2714
- case 'accept': {
2715
- // Check if key exists
2716
- const isKnown = isHostKnown(host, port);
2717
2759
 
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
- });
2760
+ return {
2761
+ content: [
2762
+ {
2763
+ type: 'text',
2764
+ text: output
2765
+ }
2766
+ ]
2767
+ };
2768
+ }
2769
+ }
2751
2770
 
2752
- logger.info('SSH host key added', { server: resolvedName, host, port });
2771
+ case 'accept': {
2772
+ // Check if key exists
2773
+ const isKnown = isHostKnown(host, port);
2753
2774
 
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
- }
2775
+ if (isKnown) {
2776
+ // Update existing key
2777
+ await updateHostKey(host, port);
2764
2778
 
2765
- case 'remove': {
2766
- removeHostKey(host, port);
2779
+ // Execute post-key-update hook
2780
+ await executeHook('post-key-update', {
2781
+ server: resolvedName,
2782
+ host,
2783
+ port,
2784
+ action: 'updated'
2785
+ });
2767
2786
 
2768
- logger.info('SSH host key removed', { server: resolvedName, host, port });
2787
+ logger.info('SSH host key updated', { server: resolvedName, host, port });
2769
2788
 
2770
2789
  return {
2771
2790
  content: [
2772
2791
  {
2773
2792
  type: 'text',
2774
- text: `✅ SSH host key removed for ${server} (${host}:${port})`
2793
+ text: `✅ SSH host key updated for ${server} (${host}:${port})\nThe new key has been accepted and saved.`
2775
2794
  }
2776
2795
  ]
2777
2796
  };
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';
2797
+ } else {
2798
+ // Add new key
2799
+ await addHostKey(host, port);
2800
+
2801
+ // Execute post-key-update hook
2802
+ await executeHook('post-key-update', {
2803
+ server: resolvedName,
2804
+ host,
2805
+ port,
2806
+ action: 'added'
2807
+ });
2787
2808
 
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
- }
2796
-
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
- }
2809
+ logger.info('SSH host key added', { server: resolvedName, host, port });
2805
2810
 
2806
2811
  return {
2807
2812
  content: [
2808
2813
  {
2809
2814
  type: 'text',
2810
- text: output
2815
+ text: `✅ SSH host key added for ${server} (${host}:${port})\nThe key has been saved to known_hosts.`
2811
2816
  }
2812
2817
  ]
2813
2818
  };
2814
2819
  }
2820
+ }
2815
2821
 
2816
- case 'list': {
2817
- const knownHosts = listKnownHosts();
2822
+ case 'remove': {
2823
+ removeHostKey(host, port);
2818
2824
 
2819
- let output = `🔑 Known SSH Hosts\n`;
2820
- output += '━'.repeat(60) + '\n\n';
2825
+ logger.info('SSH host key removed', { server: resolvedName, host, port });
2821
2826
 
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);
2827
+ return {
2828
+ content: [
2829
+ {
2830
+ type: 'text',
2831
+ text: `✅ SSH host key removed for ${server} (${host}:${port})`
2830
2832
  }
2833
+ ]
2834
+ };
2835
+ }
2831
2836
 
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';
2837
+ case 'check': {
2838
+ // Get current fingerprints
2839
+ const currentKeys = getCurrentHostKey(host, port);
2840
+ const newKeys = await getHostKeyFingerprint(host, port);
2839
2841
 
2840
- entry.keys.forEach(key => {
2841
- output += ` ${key.type}: ${key.fingerprint}\n`;
2842
- });
2843
- output += '\n';
2844
- });
2842
+ let output = `🔑 SSH Host Keys for ${server} (${host}:${port})\n`;
2843
+ output += '━'.repeat(60) + '\n\n';
2844
+
2845
+ if (currentKeys && currentKeys.length > 0) {
2846
+ output += '📋 Keys in known_hosts:\n';
2847
+ currentKeys.forEach(key => {
2848
+ output += ` ${key.type}: ${key.fingerprint}\n`;
2849
+ });
2850
+ } else {
2851
+ output += '⚠️ No keys found in known_hosts\n';
2852
+ }
2853
+
2854
+ output += '\n🌐 Keys from server:\n';
2855
+ if (newKeys && newKeys.length > 0) {
2856
+ newKeys.forEach(key => {
2857
+ output += ` ${key.type}: ${key.fingerprint}\n`;
2858
+ });
2859
+ } else {
2860
+ output += ' ❌ Could not fetch keys from server\n';
2861
+ }
2862
+
2863
+ return {
2864
+ content: [
2865
+ {
2866
+ type: 'text',
2867
+ text: output
2868
+ }
2869
+ ]
2870
+ };
2871
+ }
2872
+
2873
+ case 'list': {
2874
+ const knownHosts = listKnownHosts();
2875
+
2876
+ let output = '🔑 Known SSH Hosts\n';
2877
+ output += '━'.repeat(60) + '\n\n';
2878
+
2879
+ if (knownHosts.length === 0) {
2880
+ output += 'No hosts in known_hosts file\n';
2881
+ } else {
2882
+ // Map server names to known hosts
2883
+ const serverMap = new Map();
2884
+ for (const [name, config] of Object.entries(servers)) {
2885
+ const key = `${config.host}:${config.port || 22}`;
2886
+ serverMap.set(key, name);
2845
2887
  }
2846
2888
 
2847
- output += '━'.repeat(60) + '\n';
2848
- output += `Total: ${knownHosts.length} hosts`;
2889
+ knownHosts.forEach(entry => {
2890
+ const serverName = serverMap.get(`${entry.host}:${entry.port}`);
2891
+ output += `📍 ${entry.host}:${entry.port}`;
2892
+ if (serverName) {
2893
+ output += ` (${serverName})`;
2894
+ }
2895
+ output += '\n';
2849
2896
 
2850
- return {
2851
- content: [
2852
- {
2853
- type: 'text',
2854
- text: output
2855
- }
2856
- ]
2857
- };
2897
+ entry.keys.forEach(key => {
2898
+ output += ` ${key.type}: ${key.fingerprint}\n`;
2899
+ });
2900
+ output += '\n';
2901
+ });
2858
2902
  }
2859
2903
 
2860
- default:
2861
- throw new Error(`Unknown action: ${action}`);
2904
+ output += '━'.repeat(60) + '\n';
2905
+ output += `Total: ${knownHosts.length} hosts`;
2906
+
2907
+ return {
2908
+ content: [
2909
+ {
2910
+ type: 'text',
2911
+ text: output
2912
+ }
2913
+ ]
2914
+ };
2915
+ }
2916
+
2917
+ default:
2918
+ throw new Error(`Unknown action: ${action}`);
2862
2919
  }
2863
2920
  } catch (error) {
2864
2921
  logger.error('SSH key management failed', { action, server, error: error.message });
@@ -2876,7 +2933,7 @@ server.registerTool(
2876
2933
  );
2877
2934
 
2878
2935
  // Manage server aliases
2879
- server.registerTool(
2936
+ registerToolConditional(
2880
2937
  'ssh_alias',
2881
2938
  {
2882
2939
  description: 'Manage server aliases for easier access',
@@ -2966,7 +3023,7 @@ server.registerTool(
2966
3023
  // BACKUP & RESTORE TOOLS
2967
3024
  // ============================================================================
2968
3025
 
2969
- server.registerTool(
3026
+ registerToolConditional(
2970
3027
  'ssh_backup_create',
2971
3028
  {
2972
3029
  description: 'Create backup of database or files on remote server',
@@ -3031,70 +3088,71 @@ server.registerTool(
3031
3088
  let backupCommand;
3032
3089
 
3033
3090
  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;
3091
+ case BACKUP_TYPES.MYSQL:
3092
+ if (!database) {
3093
+ throw new Error('database parameter required for MySQL backup');
3094
+ }
3095
+ backupCommand = buildMySQLDumpCommand({
3096
+ database,
3097
+ user: dbUser,
3098
+ password: dbPassword,
3099
+ host: dbHost,
3100
+ port: dbPort,
3101
+ outputFile: backupFile,
3102
+ compress
3103
+ });
3104
+ break;
3048
3105
 
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;
3106
+ case BACKUP_TYPES.POSTGRESQL:
3107
+ if (!database) {
3108
+ throw new Error('database parameter required for PostgreSQL backup');
3109
+ }
3110
+ backupCommand = buildPostgreSQLDumpCommand({
3111
+ database,
3112
+ user: dbUser,
3113
+ password: dbPassword,
3114
+ host: dbHost,
3115
+ port: dbPort,
3116
+ outputFile: backupFile,
3117
+ compress
3118
+ });
3119
+ break;
3063
3120
 
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;
3121
+ case BACKUP_TYPES.MONGODB: {
3122
+ if (!database) {
3123
+ throw new Error('database parameter required for MongoDB backup');
3124
+ }
3125
+ const mongoOutputDir = backupFile.replace('.gz', '');
3126
+ backupCommand = buildMongoDBDumpCommand({
3127
+ database,
3128
+ user: dbUser,
3129
+ password: dbPassword,
3130
+ host: dbHost,
3131
+ port: dbPort,
3132
+ outputDir: mongoOutputDir,
3133
+ compress
3134
+ });
3135
+ break;
3136
+ }
3079
3137
 
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;
3138
+ case BACKUP_TYPES.FILES:
3139
+ if (!paths || paths.length === 0) {
3140
+ throw new Error('paths parameter required for files backup');
3141
+ }
3142
+ backupCommand = buildFilesBackupCommand({
3143
+ paths,
3144
+ outputFile: backupFile,
3145
+ exclude: exclude || [],
3146
+ compress
3147
+ });
3148
+ break;
3091
3149
 
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.');
3150
+ case BACKUP_TYPES.FULL:
3151
+ // Full backup combines database and files
3152
+ throw new Error('Full backup not yet implemented. Use separate mysql/postgresql/files backups.');
3095
3153
 
3096
- default:
3097
- throw new Error(`Unknown backup type: ${type}`);
3154
+ default:
3155
+ throw new Error(`Unknown backup type: ${type}`);
3098
3156
  }
3099
3157
 
3100
3158
  // Execute backup command
@@ -3185,7 +3243,7 @@ server.registerTool(
3185
3243
  }
3186
3244
  );
3187
3245
 
3188
- server.registerTool(
3246
+ registerToolConditional(
3189
3247
  'ssh_backup_list',
3190
3248
  {
3191
3249
  description: 'List available backups on remote server',
@@ -3257,7 +3315,7 @@ server.registerTool(
3257
3315
  }
3258
3316
  );
3259
3317
 
3260
- server.registerTool(
3318
+ registerToolConditional(
3261
3319
  'ssh_backup_restore',
3262
3320
  {
3263
3321
  description: 'Restore from a backup on remote server',
@@ -3378,7 +3436,7 @@ server.registerTool(
3378
3436
  }
3379
3437
  );
3380
3438
 
3381
- server.registerTool(
3439
+ registerToolConditional(
3382
3440
  'ssh_backup_schedule',
3383
3441
  {
3384
3442
  description: 'Schedule automatic backups using cron',
@@ -3417,30 +3475,30 @@ server.registerTool(
3417
3475
  scriptContent += `BACKUP_TYPE="${type}"\n`;
3418
3476
  scriptContent += `BACKUP_ID="${backupId}"\n`;
3419
3477
  scriptContent += `BACKUP_FILE="${backupFile}"\n\n`;
3420
- scriptContent += `mkdir -p "$BACKUP_DIR"\n\n`;
3478
+ scriptContent += 'mkdir -p "$BACKUP_DIR"\n\n';
3421
3479
 
3422
3480
  // Add backup command based on type
3423
3481
  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;
3482
+ case BACKUP_TYPES.MYSQL:
3483
+ scriptContent += `mysqldump --single-transaction --routines --triggers ${database} | gzip > "$BACKUP_FILE"\n`;
3484
+ break;
3485
+ case BACKUP_TYPES.POSTGRESQL:
3486
+ scriptContent += `pg_dump --format=custom --clean --if-exists ${database} | gzip > "$BACKUP_FILE"\n`;
3487
+ break;
3488
+ case BACKUP_TYPES.MONGODB:
3489
+ scriptContent += `mongodump --db ${database} --out /tmp/mongo_\${RANDOM} && tar -czf "$BACKUP_FILE" -C /tmp mongo_*\n`;
3490
+ break;
3491
+ case BACKUP_TYPES.FILES:
3492
+ scriptContent += `tar -czf "$BACKUP_FILE" ${paths.join(' ')}\n`;
3493
+ break;
3436
3494
  }
3437
3495
 
3438
3496
  // Add cleanup command
3439
- scriptContent += `\n# Cleanup old backups\n`;
3497
+ scriptContent += '\n# Cleanup old backups\n';
3440
3498
  scriptContent += `find "$BACKUP_DIR" -name "*_${name}_*" -type f -mtime +${retention} -delete\n`;
3441
3499
 
3442
3500
  // Save script to remote server
3443
- const escapedScript = scriptContent.replace(/'/g, "'\\''");
3501
+ const escapedScript = scriptContent.replace(/'/g, '\'\\\'\'');
3444
3502
  await ssh.execCommand(`echo '${escapedScript}' > "${scriptPath}" && chmod +x "${scriptPath}"`);
3445
3503
 
3446
3504
  // Add to crontab
@@ -3501,7 +3559,7 @@ server.registerTool(
3501
3559
  // HEALTH CHECKS & MONITORING TOOLS
3502
3560
  // ============================================================================
3503
3561
 
3504
- server.registerTool(
3562
+ registerToolConditional(
3505
3563
  'ssh_health_check',
3506
3564
  {
3507
3565
  description: 'Perform comprehensive health check on remote server',
@@ -3596,7 +3654,7 @@ server.registerTool(
3596
3654
  }
3597
3655
  );
3598
3656
 
3599
- server.registerTool(
3657
+ registerToolConditional(
3600
3658
  'ssh_service_status',
3601
3659
  {
3602
3660
  description: 'Check status of services on remote server',
@@ -3638,11 +3696,11 @@ server.registerTool(
3638
3696
  stopped,
3639
3697
  services: serviceStatuses,
3640
3698
  overall_health: stopped === 0 ? HEALTH_STATUS.HEALTHY :
3641
- running > stopped ? HEALTH_STATUS.WARNING :
3642
- HEALTH_STATUS.CRITICAL
3699
+ running > stopped ? HEALTH_STATUS.WARNING :
3700
+ HEALTH_STATUS.CRITICAL
3643
3701
  };
3644
3702
 
3645
- logger.info(`Service check completed`, {
3703
+ logger.info('Service check completed', {
3646
3704
  server: serverName,
3647
3705
  running,
3648
3706
  stopped
@@ -3675,7 +3733,7 @@ server.registerTool(
3675
3733
  }
3676
3734
  );
3677
3735
 
3678
- server.registerTool(
3736
+ registerToolConditional(
3679
3737
  'ssh_process_manager',
3680
3738
  {
3681
3739
  description: 'List, monitor, or kill processes on remote server',
@@ -3708,92 +3766,92 @@ server.registerTool(
3708
3766
  let response;
3709
3767
 
3710
3768
  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);
3769
+ case 'list': {
3770
+ const listCommand = buildProcessListCommand({ sortBy, limit, filter });
3771
+ const result = await ssh.execCommand(listCommand);
3720
3772
 
3721
- response = {
3722
- server: serverName,
3723
- action: 'list',
3724
- count: processes.length,
3725
- sorted_by: sortBy,
3726
- processes
3727
- };
3728
- break;
3773
+ if (result.code !== 0) {
3774
+ throw new Error(`Failed to list processes: ${result.stderr}`);
3729
3775
  }
3730
3776
 
3731
- case 'kill': {
3732
- if (!pid) {
3733
- throw new Error('pid parameter required for kill action');
3734
- }
3777
+ const processes = parseProcessList(result.stdout);
3735
3778
 
3736
- // Get process info first
3737
- const infoCommand = buildProcessInfoCommand(pid);
3738
- const infoResult = await ssh.execCommand(infoCommand);
3779
+ response = {
3780
+ server: serverName,
3781
+ action: 'list',
3782
+ count: processes.length,
3783
+ sorted_by: sortBy,
3784
+ processes
3785
+ };
3786
+ break;
3787
+ }
3739
3788
 
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
- }
3789
+ case 'kill': {
3790
+ if (!pid) {
3791
+ throw new Error('pid parameter required for kill action');
3792
+ }
3748
3793
 
3749
- // Kill the process
3750
- const killCommand = buildKillProcessCommand(pid, signal);
3751
- const killResult = await ssh.execCommand(killCommand);
3794
+ // Get process info first
3795
+ const infoCommand = buildProcessInfoCommand(pid);
3796
+ const infoResult = await ssh.execCommand(infoCommand);
3752
3797
 
3753
- if (killResult.code !== 0) {
3754
- throw new Error(`Failed to kill process ${pid}: ${killResult.stderr}`);
3798
+ let processInfo = {};
3799
+ if (infoResult.code === 0 && infoResult.stdout) {
3800
+ try {
3801
+ processInfo = JSON.parse(infoResult.stdout);
3802
+ } catch (e) {
3803
+ // Process might not exist
3755
3804
  }
3805
+ }
3756
3806
 
3757
- response = {
3758
- server: serverName,
3759
- action: 'kill',
3760
- pid,
3761
- signal,
3762
- process: processInfo,
3763
- success: true
3764
- };
3807
+ // Kill the process
3808
+ const killCommand = buildKillProcessCommand(pid, signal);
3809
+ const killResult = await ssh.execCommand(killCommand);
3765
3810
 
3766
- logger.info(`Process killed: ${pid}`, {
3767
- server: serverName,
3768
- signal
3769
- });
3770
- break;
3811
+ if (killResult.code !== 0) {
3812
+ throw new Error(`Failed to kill process ${pid}: ${killResult.stderr}`);
3771
3813
  }
3772
3814
 
3773
- case 'info': {
3774
- if (!pid) {
3775
- throw new Error('pid parameter required for info action');
3776
- }
3815
+ response = {
3816
+ server: serverName,
3817
+ action: 'kill',
3818
+ pid,
3819
+ signal,
3820
+ process: processInfo,
3821
+ success: true
3822
+ };
3777
3823
 
3778
- const infoCommand = buildProcessInfoCommand(pid);
3779
- const result = await ssh.execCommand(infoCommand);
3824
+ logger.info(`Process killed: ${pid}`, {
3825
+ server: serverName,
3826
+ signal
3827
+ });
3828
+ break;
3829
+ }
3780
3830
 
3781
- if (result.code !== 0 || !result.stdout) {
3782
- throw new Error(`Process ${pid} not found`);
3783
- }
3831
+ case 'info': {
3832
+ if (!pid) {
3833
+ throw new Error('pid parameter required for info action');
3834
+ }
3784
3835
 
3785
- const processInfo = JSON.parse(result.stdout);
3836
+ const infoCommand = buildProcessInfoCommand(pid);
3837
+ const result = await ssh.execCommand(infoCommand);
3786
3838
 
3787
- response = {
3788
- server: serverName,
3789
- action: 'info',
3790
- process: processInfo
3791
- };
3792
- break;
3839
+ if (result.code !== 0 || !result.stdout) {
3840
+ throw new Error(`Process ${pid} not found`);
3793
3841
  }
3794
3842
 
3795
- default:
3796
- throw new Error(`Unknown action: ${action}`);
3843
+ const processInfo = JSON.parse(result.stdout);
3844
+
3845
+ response = {
3846
+ server: serverName,
3847
+ action: 'info',
3848
+ process: processInfo
3849
+ };
3850
+ break;
3851
+ }
3852
+
3853
+ default:
3854
+ throw new Error(`Unknown action: ${action}`);
3797
3855
  }
3798
3856
 
3799
3857
  return {
@@ -3824,7 +3882,7 @@ server.registerTool(
3824
3882
  }
3825
3883
  );
3826
3884
 
3827
- server.registerTool(
3885
+ registerToolConditional(
3828
3886
  'ssh_alert_setup',
3829
3887
  {
3830
3888
  description: 'Configure health monitoring alerts and thresholds',
@@ -3854,126 +3912,126 @@ server.registerTool(
3854
3912
  let response;
3855
3913
 
3856
3914
  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
- });
3915
+ case 'set': {
3916
+ // Create alert configuration
3917
+ const config = createAlertConfig({
3918
+ cpu: cpuThreshold,
3919
+ memory: memoryThreshold,
3920
+ disk: diskThreshold,
3921
+ enabled
3922
+ });
3865
3923
 
3866
- // Save to server
3867
- const saveCommand = buildSaveAlertConfigCommand(config, configPath);
3868
- const saveResult = await ssh.execCommand(saveCommand);
3924
+ // Save to server
3925
+ const saveCommand = buildSaveAlertConfigCommand(config, configPath);
3926
+ const saveResult = await ssh.execCommand(saveCommand);
3869
3927
 
3870
- if (saveResult.code !== 0) {
3871
- throw new Error(`Failed to save alert config: ${saveResult.stderr}`);
3872
- }
3928
+ if (saveResult.code !== 0) {
3929
+ throw new Error(`Failed to save alert config: ${saveResult.stderr}`);
3930
+ }
3873
3931
 
3874
- response = {
3875
- server: serverName,
3876
- action: 'set',
3877
- config,
3878
- config_path: configPath,
3879
- success: true
3880
- };
3932
+ response = {
3933
+ server: serverName,
3934
+ action: 'set',
3935
+ config,
3936
+ config_path: configPath,
3937
+ success: true
3938
+ };
3881
3939
 
3882
- logger.info('Alert thresholds configured', {
3883
- server: serverName,
3884
- thresholds: config
3885
- });
3886
- break;
3940
+ logger.info('Alert thresholds configured', {
3941
+ server: serverName,
3942
+ thresholds: config
3943
+ });
3944
+ break;
3945
+ }
3946
+
3947
+ case 'get': {
3948
+ // Load configuration
3949
+ const loadCommand = buildLoadAlertConfigCommand(configPath);
3950
+ const result = await ssh.execCommand(loadCommand);
3951
+
3952
+ let config = {};
3953
+ if (result.stdout && result.stdout.trim()) {
3954
+ try {
3955
+ config = JSON.parse(result.stdout);
3956
+ } catch (e) {
3957
+ config = { error: 'Failed to parse config' };
3958
+ }
3887
3959
  }
3888
3960
 
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
- }
3961
+ response = {
3962
+ server: serverName,
3963
+ action: 'get',
3964
+ config,
3965
+ config_path: configPath
3966
+ };
3967
+ break;
3968
+ }
3969
+
3970
+ case 'check': {
3971
+ // Load thresholds
3972
+ const loadCommand = buildLoadAlertConfigCommand(configPath);
3973
+ const loadResult = await ssh.execCommand(loadCommand);
3974
+
3975
+ let thresholds = {};
3976
+ if (loadResult.stdout && loadResult.stdout.trim()) {
3977
+ try {
3978
+ thresholds = JSON.parse(loadResult.stdout);
3979
+ } catch (e) {
3980
+ throw new Error('No alert configuration found. Use action=set to configure.');
3901
3981
  }
3982
+ } else {
3983
+ throw new Error('No alert configuration found. Use action=set to configure.');
3984
+ }
3902
3985
 
3986
+ if (!thresholds.enabled) {
3903
3987
  response = {
3904
3988
  server: serverName,
3905
- action: 'get',
3906
- config,
3907
- config_path: configPath
3989
+ action: 'check',
3990
+ message: 'Alerts are disabled',
3991
+ thresholds
3908
3992
  };
3909
3993
  break;
3910
3994
  }
3911
3995
 
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
- }
3927
-
3928
- if (!thresholds.enabled) {
3929
- response = {
3930
- server: serverName,
3931
- action: 'check',
3932
- message: 'Alerts are disabled',
3933
- thresholds
3934
- };
3935
- break;
3936
- }
3996
+ // Get current metrics
3997
+ const healthCommand = buildComprehensiveHealthCheckCommand();
3998
+ const healthResult = await ssh.execCommand(healthCommand);
3937
3999
 
3938
- // Get current metrics
3939
- const healthCommand = buildComprehensiveHealthCheckCommand();
3940
- const healthResult = await ssh.execCommand(healthCommand);
4000
+ if (healthResult.code !== 0) {
4001
+ throw new Error('Failed to get current metrics');
4002
+ }
3941
4003
 
3942
- if (healthResult.code !== 0) {
3943
- throw new Error('Failed to get current metrics');
3944
- }
4004
+ const metrics = parseComprehensiveHealthCheck(healthResult.stdout);
3945
4005
 
3946
- const metrics = parseComprehensiveHealthCheck(healthResult.stdout);
4006
+ // Check thresholds
4007
+ const alerts = checkAlertThresholds(metrics, thresholds);
3947
4008
 
3948
- // Check thresholds
3949
- const alerts = checkAlertThresholds(metrics, thresholds);
4009
+ response = {
4010
+ server: serverName,
4011
+ action: 'check',
4012
+ thresholds,
4013
+ current_metrics: {
4014
+ cpu: metrics.cpu,
4015
+ memory: metrics.memory,
4016
+ disks: metrics.disks
4017
+ },
4018
+ alerts,
4019
+ alert_count: alerts.length,
4020
+ status: alerts.length === 0 ? 'ok' : 'alerts_triggered'
4021
+ };
3950
4022
 
3951
- response = {
4023
+ if (alerts.length > 0) {
4024
+ logger.warn('Health alerts triggered', {
3952
4025
  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
4026
  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;
4027
+ alerts
4028
+ });
3973
4029
  }
4030
+ break;
4031
+ }
3974
4032
 
3975
- default:
3976
- throw new Error(`Unknown action: ${action}`);
4033
+ default:
4034
+ throw new Error(`Unknown action: ${action}`);
3977
4035
  }
3978
4036
 
3979
4037
  return {
@@ -4008,7 +4066,7 @@ server.registerTool(
4008
4066
  // DATABASE MANAGEMENT TOOLS
4009
4067
  // ============================================================================
4010
4068
 
4011
- server.registerTool(
4069
+ registerToolConditional(
4012
4070
  'ssh_db_dump',
4013
4071
  {
4014
4072
  description: 'Dump database to file (MySQL, PostgreSQL, MongoDB)',
@@ -4049,18 +4107,18 @@ server.registerTool(
4049
4107
  };
4050
4108
 
4051
4109
  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}`);
4110
+ case DB_TYPES.MYSQL:
4111
+ dumpCommand = buildDBMySQLDumpCommand(options);
4112
+ break;
4113
+ case DB_TYPES.POSTGRESQL:
4114
+ dumpCommand = buildDBPostgreSQLDumpCommand(options);
4115
+ break;
4116
+ case DB_TYPES.MONGODB:
4117
+ options.outputDir = outputFile.replace(/\.(tar\.gz|gz)$/, '');
4118
+ dumpCommand = buildDBMongoDBDumpCommand(options);
4119
+ break;
4120
+ default:
4121
+ throw new Error(`Unsupported database type: ${type}`);
4064
4122
  }
4065
4123
 
4066
4124
  // Execute dump
@@ -4120,7 +4178,7 @@ server.registerTool(
4120
4178
  }
4121
4179
  );
4122
4180
 
4123
- server.registerTool(
4181
+ registerToolConditional(
4124
4182
  'ssh_db_import',
4125
4183
  {
4126
4184
  description: 'Import database from SQL file (MySQL, PostgreSQL, MongoDB)',
@@ -4159,18 +4217,18 @@ server.registerTool(
4159
4217
  };
4160
4218
 
4161
4219
  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}`);
4220
+ case DB_TYPES.MYSQL:
4221
+ importCommand = buildMySQLImportCommand(options);
4222
+ break;
4223
+ case DB_TYPES.POSTGRESQL:
4224
+ importCommand = buildPostgreSQLImportCommand(options);
4225
+ break;
4226
+ case DB_TYPES.MONGODB:
4227
+ options.inputPath = inputFile;
4228
+ importCommand = buildMongoDBRestoreCommand(options);
4229
+ break;
4230
+ default:
4231
+ throw new Error(`Unsupported database type: ${type}`);
4174
4232
  }
4175
4233
 
4176
4234
  // Execute import
@@ -4180,7 +4238,7 @@ server.registerTool(
4180
4238
  throw new Error(`Import failed: ${result.stderr || result.stdout}`);
4181
4239
  }
4182
4240
 
4183
- logger.info(`Database import completed`, {
4241
+ logger.info('Database import completed', {
4184
4242
  server: serverName,
4185
4243
  database
4186
4244
  });
@@ -4222,7 +4280,7 @@ server.registerTool(
4222
4280
  }
4223
4281
  );
4224
4282
 
4225
- server.registerTool(
4283
+ registerToolConditional(
4226
4284
  'ssh_db_list',
4227
4285
  {
4228
4286
  description: 'List databases or tables/collections',
@@ -4261,28 +4319,28 @@ server.registerTool(
4261
4319
  if (database) {
4262
4320
  // List tables/collections
4263
4321
  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;
4322
+ case DB_TYPES.MYSQL:
4323
+ listCommand = buildMySQLListTablesCommand(options);
4324
+ break;
4325
+ case DB_TYPES.POSTGRESQL:
4326
+ listCommand = buildPostgreSQLListTablesCommand(options);
4327
+ break;
4328
+ case DB_TYPES.MONGODB:
4329
+ listCommand = buildMongoDBListCollectionsCommand(options);
4330
+ break;
4273
4331
  }
4274
4332
  } else {
4275
4333
  // List databases
4276
4334
  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;
4335
+ case DB_TYPES.MYSQL:
4336
+ listCommand = buildMySQLListDatabasesCommand(options);
4337
+ break;
4338
+ case DB_TYPES.POSTGRESQL:
4339
+ listCommand = buildPostgreSQLListDatabasesCommand(options);
4340
+ break;
4341
+ case DB_TYPES.MONGODB:
4342
+ listCommand = buildMongoDBListDatabasesCommand(options);
4343
+ break;
4286
4344
  }
4287
4345
  }
4288
4346
 
@@ -4347,7 +4405,7 @@ server.registerTool(
4347
4405
  }
4348
4406
  );
4349
4407
 
4350
- server.registerTool(
4408
+ registerToolConditional(
4351
4409
  'ssh_db_query',
4352
4410
  {
4353
4411
  description: 'Execute SELECT query on database (read-only, SELECT queries only)',
@@ -4392,21 +4450,21 @@ server.registerTool(
4392
4450
 
4393
4451
  // Build query command based on type
4394
4452
  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}`);
4453
+ case DB_TYPES.MYSQL:
4454
+ queryCommand = buildMySQLQueryCommand(options);
4455
+ break;
4456
+ case DB_TYPES.POSTGRESQL:
4457
+ queryCommand = buildPostgreSQLQueryCommand(options);
4458
+ break;
4459
+ case DB_TYPES.MONGODB:
4460
+ if (!collection) {
4461
+ throw new Error('collection parameter required for MongoDB queries');
4462
+ }
4463
+ options.collection = collection;
4464
+ queryCommand = buildMongoDBQueryCommand(options);
4465
+ break;
4466
+ default:
4467
+ throw new Error(`Unsupported database type: ${type}`);
4410
4468
  }
4411
4469
 
4412
4470
  // Execute query
@@ -4420,7 +4478,7 @@ server.registerTool(
4420
4478
  const output = result.stdout.trim();
4421
4479
  const lines = output.split('\n');
4422
4480
 
4423
- logger.info(`Query executed successfully`, {
4481
+ logger.info('Query executed successfully', {
4424
4482
  server: serverName,
4425
4483
  database,
4426
4484
  rows: lines.length