mcp-ssh-manager 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/.claude/settings.local.json +87 -0
  2. package/.flake8 +15 -0
  3. package/.hooks-config.json +131 -0
  4. package/.pre-commit-config.yaml +105 -0
  5. package/CHANGELOG.md +137 -0
  6. package/CLAUDE.md +190 -0
  7. package/CONTRIBUTING.md +114 -0
  8. package/DESCRIPTION +1 -0
  9. package/INSTALLATION.md +180 -0
  10. package/LICENSE +21 -0
  11. package/QUICKSTART.md +77 -0
  12. package/README.md +718 -0
  13. package/cli/README.md +286 -0
  14. package/cli/build.sh +199 -0
  15. package/cli/commands/server.sh +284 -0
  16. package/cli/demo.sh +107 -0
  17. package/cli/install.sh +164 -0
  18. package/cli/lib/colors.sh +174 -0
  19. package/cli/lib/config.sh +284 -0
  20. package/cli/lib/menu.sh +430 -0
  21. package/cli/migrate.sh +168 -0
  22. package/cli/ssh-manager +525 -0
  23. package/docs/ALIASES_AND_HOOKS.md +285 -0
  24. package/docs/BACKUP_GUIDE.md +500 -0
  25. package/docs/DEPLOYMENT_GUIDE.md +241 -0
  26. package/docs/SEO.md +257 -0
  27. package/examples/backup-workflow.js +481 -0
  28. package/examples/claude-code-config.example.json +40 -0
  29. package/examples/codex-ssh-config.example.toml +71 -0
  30. package/examples/deploy-workflow.py +183 -0
  31. package/glama.json +6 -0
  32. package/package.json +85 -0
  33. package/profiles/README.md +40 -0
  34. package/profiles/default.json +52 -0
  35. package/profiles/docker.json +62 -0
  36. package/profiles/frappe.json +107 -0
  37. package/profiles/nodejs.json +63 -0
  38. package/pyproject.toml +17 -0
  39. package/scripts/setup-hooks.sh +60 -0
  40. package/scripts/validate.sh +76 -0
  41. package/src/backup-manager.js +469 -0
  42. package/src/command-aliases.js +151 -0
  43. package/src/config-loader.js +281 -0
  44. package/src/database-manager.js +555 -0
  45. package/src/deploy-helper.js +176 -0
  46. package/src/health-monitor.js +428 -0
  47. package/src/hooks-system.js +327 -0
  48. package/src/index.js +4499 -0
  49. package/src/logger.js +276 -0
  50. package/src/profile-loader.js +187 -0
  51. package/src/server-aliases.js +150 -0
  52. package/src/server-groups.js +409 -0
  53. package/src/session-manager.js +410 -0
  54. package/src/ssh-key-manager.js +378 -0
  55. package/src/ssh-manager.js +435 -0
  56. package/src/tunnel-manager.js +576 -0
package/src/index.js ADDED
@@ -0,0 +1,4499 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
+ import { z } from 'zod';
6
+ import SSHManager from './ssh-manager.js';
7
+ import * as dotenv from 'dotenv';
8
+ import fs from 'fs';
9
+ import path from 'path';
10
+ import { fileURLToPath } from 'url';
11
+ import { configLoader } from './config-loader.js';
12
+ import {
13
+ getTempFilename,
14
+ buildDeploymentStrategy,
15
+ detectDeploymentNeeds
16
+ } from './deploy-helper.js';
17
+ import {
18
+ resolveServerName,
19
+ addAlias,
20
+ removeAlias,
21
+ listAliases
22
+ } from './server-aliases.js';
23
+ import {
24
+ expandCommandAlias,
25
+ addCommandAlias,
26
+ removeCommandAlias,
27
+ listCommandAliases,
28
+ suggestAliases
29
+ } from './command-aliases.js';
30
+ import {
31
+ initializeHooks,
32
+ executeHook,
33
+ toggleHook,
34
+ listHooks
35
+ } from './hooks-system.js';
36
+ import {
37
+ loadProfile,
38
+ listProfiles,
39
+ setActiveProfile,
40
+ getActiveProfileName
41
+ } from './profile-loader.js';
42
+ import { logger } from './logger.js';
43
+ import {
44
+ createSession,
45
+ getSession,
46
+ listSessions,
47
+ closeSession,
48
+ SESSION_STATES
49
+ } from './session-manager.js';
50
+ import {
51
+ getGroup,
52
+ createGroup,
53
+ updateGroup,
54
+ deleteGroup,
55
+ addServersToGroup,
56
+ removeServersFromGroup,
57
+ listGroups,
58
+ executeOnGroup,
59
+ EXECUTION_STRATEGIES
60
+ } from './server-groups.js';
61
+ import {
62
+ createTunnel,
63
+ getTunnel,
64
+ listTunnels,
65
+ closeTunnel,
66
+ closeServerTunnels,
67
+ TUNNEL_TYPES
68
+ } from './tunnel-manager.js';
69
+ import {
70
+ getHostKeyFingerprint,
71
+ isHostKnown,
72
+ getCurrentHostKey,
73
+ removeHostKey,
74
+ addHostKey,
75
+ updateHostKey,
76
+ hasHostKeyChanged,
77
+ listKnownHosts,
78
+ detectSSHKeyError,
79
+ handleSSHKeyError
80
+ } from './ssh-key-manager.js';
81
+ import {
82
+ BACKUP_TYPES,
83
+ DEFAULT_BACKUP_DIR,
84
+ generateBackupId,
85
+ getBackupMetadataPath,
86
+ getBackupFilePath,
87
+ buildMySQLDumpCommand,
88
+ buildPostgreSQLDumpCommand,
89
+ buildMongoDBDumpCommand,
90
+ buildFilesBackupCommand,
91
+ buildRestoreCommand,
92
+ createBackupMetadata,
93
+ buildSaveMetadataCommand,
94
+ buildListBackupsCommand,
95
+ parseBackupsList,
96
+ buildCleanupCommand,
97
+ buildCronScheduleCommand,
98
+ parseCronJobs
99
+ } from './backup-manager.js';
100
+ import {
101
+ HEALTH_STATUS,
102
+ COMMON_SERVICES,
103
+ buildCPUCheckCommand,
104
+ buildMemoryCheckCommand,
105
+ buildDiskCheckCommand,
106
+ buildNetworkCheckCommand,
107
+ buildLoadAverageCommand,
108
+ buildUptimeCommand,
109
+ parseCPUUsage,
110
+ parseMemoryUsage,
111
+ parseDiskUsage,
112
+ parseNetworkStats,
113
+ determineOverallHealth,
114
+ buildServiceStatusCommand,
115
+ parseServiceStatus,
116
+ buildProcessListCommand,
117
+ parseProcessList,
118
+ buildKillProcessCommand,
119
+ buildProcessInfoCommand,
120
+ createAlertConfig,
121
+ buildSaveAlertConfigCommand,
122
+ buildLoadAlertConfigCommand,
123
+ checkAlertThresholds,
124
+ buildComprehensiveHealthCheckCommand,
125
+ parseComprehensiveHealthCheck,
126
+ getCommonServices,
127
+ resolveServiceName
128
+ } from './health-monitor.js';
129
+ import {
130
+ DB_TYPES,
131
+ DB_PORTS,
132
+ buildMySQLDumpCommand as buildDBMySQLDumpCommand,
133
+ buildPostgreSQLDumpCommand as buildDBPostgreSQLDumpCommand,
134
+ buildMongoDBDumpCommand as buildDBMongoDBDumpCommand,
135
+ buildMySQLImportCommand,
136
+ buildPostgreSQLImportCommand,
137
+ buildMongoDBRestoreCommand,
138
+ buildMySQLListDatabasesCommand,
139
+ buildMySQLListTablesCommand,
140
+ buildPostgreSQLListDatabasesCommand,
141
+ buildPostgreSQLListTablesCommand,
142
+ buildMongoDBListDatabasesCommand,
143
+ buildMongoDBListCollectionsCommand,
144
+ buildMySQLQueryCommand,
145
+ buildPostgreSQLQueryCommand,
146
+ buildMongoDBQueryCommand,
147
+ isSafeQuery,
148
+ parseDatabaseList,
149
+ parseTableList,
150
+ buildEstimateSizeCommand,
151
+ parseSize,
152
+ formatBytes,
153
+ getConnectionInfo
154
+ } from './database-manager.js';
155
+
156
+ const __filename = fileURLToPath(import.meta.url);
157
+ const __dirname = path.dirname(__filename);
158
+
159
+ // Load environment variables (for backward compatibility)
160
+ dotenv.config({ path: path.join(__dirname, '..', '.env') });
161
+
162
+ // Initialize logger
163
+ logger.info('MCP SSH Manager starting', {
164
+ logLevel: process.env.SSH_LOG_LEVEL || 'INFO',
165
+ verbose: process.env.SSH_VERBOSE === 'true'
166
+ });
167
+
168
+ // Load SSH server configuration
169
+ let servers = {};
170
+ configLoader.load({
171
+ envPath: path.join(__dirname, '..', '.env'),
172
+ tomlPath: process.env.SSH_CONFIG_PATH,
173
+ preferToml: process.env.PREFER_TOML_CONFIG === 'true'
174
+ }).then(loadedServers => {
175
+ // Convert Map to object for backward compatibility
176
+ servers = {};
177
+ for (const [name, config] of loadedServers) {
178
+ servers[name] = config;
179
+ }
180
+ logger.info(`Loaded ${loadedServers.size} SSH server configurations from ${configLoader.configSource}`);
181
+ }).catch(error => {
182
+ logger.error('Failed to load server configuration', { error: error.message });
183
+ });
184
+
185
+ // Initialize hooks system
186
+ initializeHooks().catch(error => {
187
+ logger.error('Failed to initialize hooks', { error: error.message });
188
+ });
189
+
190
+ // Map to store active connections
191
+ const connections = new Map();
192
+
193
+ // Map to store connection timestamps for timeout management
194
+ const connectionTimestamps = new Map();
195
+
196
+ // Connection timeout in milliseconds (30 minutes)
197
+ const CONNECTION_TIMEOUT = 30 * 60 * 1000;
198
+
199
+ // Keepalive interval in milliseconds (5 minutes)
200
+ const KEEPALIVE_INTERVAL = 5 * 60 * 1000;
201
+
202
+ // Map to store keepalive intervals
203
+ const keepaliveIntervals = new Map();
204
+
205
+ // Load server configuration (backward compatibility wrapper)
206
+ function loadServerConfig() {
207
+ // This function is kept for backward compatibility
208
+ // The actual loading is done by configLoader during initialization
209
+ return servers;
210
+ }
211
+
212
+ // Execute command with timeout - using child_process timeout for real kill
213
+ async function execCommandWithTimeout(ssh, command, options = {}, timeoutMs = 30000) {
214
+ // Pass through rawCommand if specified
215
+ const { rawCommand, ...otherOptions } = options;
216
+
217
+ // For commands that might hang, use the system's timeout command if available
218
+ const useSystemTimeout = timeoutMs > 0 && timeoutMs < 300000 && !rawCommand; // Max 5 minutes, not for raw commands
219
+
220
+ if (useSystemTimeout) {
221
+ // Wrap command with timeout command (works on Linux/Mac)
222
+ const timeoutSeconds = Math.ceil(timeoutMs / 1000);
223
+ const wrappedCommand = `timeout ${timeoutSeconds} sh -c '${command.replace(/'/g, "'\\''")}'`;
224
+
225
+ try {
226
+ const result = await ssh.execCommand(wrappedCommand, otherOptions);
227
+
228
+ // Check if timeout occurred (exit code 124 on Linux, 124 or 143 on Mac)
229
+ if (result.code === 124 || result.code === 143) {
230
+ throw new Error(`Command timeout after ${timeoutMs}ms: ${command.substring(0, 100)}...`);
231
+ }
232
+
233
+ return result;
234
+ } catch (error) {
235
+ // If timeout occurred, remove connection from pool
236
+ if (error.message.includes('timeout')) {
237
+ for (const [name, conn] of connections.entries()) {
238
+ if (conn === ssh) {
239
+ logger.warn(`Removing timed-out connection for ${name}`);
240
+ connections.delete(name);
241
+ connectionTimestamps.delete(name);
242
+ if (keepaliveIntervals.has(name)) {
243
+ clearInterval(keepaliveIntervals.get(name));
244
+ keepaliveIntervals.delete(name);
245
+ }
246
+ // Force close the connection
247
+ ssh.dispose();
248
+ break;
249
+ }
250
+ }
251
+ }
252
+ throw error;
253
+ }
254
+ } else {
255
+ // No timeout or very long timeout, execute normally
256
+ return ssh.execCommand(command, { ...options, timeout: timeoutMs });
257
+ }
258
+ }
259
+
260
+ // Check if a connection is still valid
261
+ async function isConnectionValid(ssh) {
262
+ try {
263
+ return await ssh.ping();
264
+ } catch (error) {
265
+ logger.debug('Connection validation failed', { error: error.message });
266
+ return false;
267
+ }
268
+ }
269
+
270
+ // Setup keepalive for a connection
271
+ function setupKeepalive(serverName, ssh) {
272
+ // Clear existing keepalive if any
273
+ if (keepaliveIntervals.has(serverName)) {
274
+ clearInterval(keepaliveIntervals.get(serverName));
275
+ }
276
+
277
+ // Set up new keepalive interval
278
+ const interval = setInterval(async () => {
279
+ try {
280
+ const isValid = await isConnectionValid(ssh);
281
+ if (!isValid) {
282
+ logger.warn(`Connection to ${serverName} lost, will reconnect on next use`);
283
+ closeConnection(serverName);
284
+ } else {
285
+ // Update timestamp on successful keepalive
286
+ connectionTimestamps.set(serverName, Date.now());
287
+ logger.debug('Keepalive successful', { server: serverName });
288
+ }
289
+ } catch (error) {
290
+ logger.error(`Keepalive failed for ${serverName}`, { error: error.message });
291
+ }
292
+ }, KEEPALIVE_INTERVAL);
293
+
294
+ keepaliveIntervals.set(serverName, interval);
295
+ }
296
+
297
+ // Close a connection and clean up
298
+ function closeConnection(serverName) {
299
+ const normalizedName = serverName.toLowerCase();
300
+
301
+ // Clear keepalive interval
302
+ if (keepaliveIntervals.has(normalizedName)) {
303
+ clearInterval(keepaliveIntervals.get(normalizedName));
304
+ keepaliveIntervals.delete(normalizedName);
305
+ }
306
+
307
+ // Close SSH connection
308
+ const ssh = connections.get(normalizedName);
309
+ if (ssh) {
310
+ ssh.dispose();
311
+ connections.delete(normalizedName);
312
+ }
313
+
314
+ // Remove timestamp
315
+ connectionTimestamps.delete(normalizedName);
316
+
317
+ logger.logConnection(serverName, 'closed');
318
+ }
319
+
320
+ // Clean up old connections
321
+ function cleanupOldConnections() {
322
+ const now = Date.now();
323
+ for (const [serverName, timestamp] of connectionTimestamps.entries()) {
324
+ if (now - timestamp > CONNECTION_TIMEOUT) {
325
+ logger.info(`Connection to ${serverName} timed out, closing`, { timeout: CONNECTION_TIMEOUT });
326
+ closeConnection(serverName);
327
+ }
328
+ }
329
+ }
330
+
331
+ // Get or create SSH connection with reconnection support
332
+ async function getConnection(serverName) {
333
+ const servers = loadServerConfig();
334
+
335
+ // Execute pre-connect hook
336
+ await executeHook('pre-connect', { server: serverName });
337
+
338
+ // Try to resolve through aliases first
339
+ const resolvedName = resolveServerName(serverName, servers);
340
+
341
+ if (!resolvedName) {
342
+ const availableServers = Object.keys(servers);
343
+ const aliases = listAliases();
344
+ const aliasInfo = aliases.length > 0 ?
345
+ ` Aliases: ${aliases.map(a => `${a.alias}->${a.target}`).join(', ')}` : '';
346
+ throw new Error(
347
+ `Server "${serverName}" not found. Available servers: ${availableServers.join(', ') || 'none'}.${aliasInfo}`
348
+ );
349
+ }
350
+
351
+ const normalizedName = resolvedName;
352
+
353
+ // Check if we have an existing connection
354
+ if (connections.has(normalizedName)) {
355
+ const existingSSH = connections.get(normalizedName);
356
+
357
+ // Verify the connection is still valid
358
+ const isValid = await isConnectionValid(existingSSH);
359
+
360
+ if (isValid) {
361
+ // Update timestamp and return existing connection
362
+ connectionTimestamps.set(normalizedName, Date.now());
363
+ return existingSSH;
364
+ } else {
365
+ // Connection is dead, remove it
366
+ logger.info(`Connection to ${serverName} lost, reconnecting`);
367
+ closeConnection(normalizedName);
368
+ }
369
+ }
370
+
371
+ // Create new connection
372
+ const serverConfig = servers[normalizedName];
373
+ const ssh = new SSHManager(serverConfig);
374
+
375
+ try {
376
+ await ssh.connect();
377
+ connections.set(normalizedName, ssh);
378
+ connectionTimestamps.set(normalizedName, Date.now());
379
+
380
+ // Setup keepalive
381
+ setupKeepalive(normalizedName, ssh);
382
+
383
+ logger.logConnection(serverName, 'established', {
384
+ host: serverConfig.host,
385
+ port: serverConfig.port,
386
+ method: serverConfig.password ? 'password' : 'key'
387
+ });
388
+
389
+ // Execute post-connect hook
390
+ await executeHook('post-connect', { server: serverName });
391
+ } catch (error) {
392
+ logger.logConnection(serverName, 'failed', { error: error.message });
393
+ // Execute error hook
394
+ await executeHook('on-error', { server: serverName, error: error.message });
395
+ throw new Error(`Failed to connect to ${serverName}: ${error.message}`);
396
+ }
397
+
398
+ return connections.get(normalizedName);
399
+ }
400
+
401
+ // Create MCP server
402
+ const server = new McpServer({
403
+ name: 'mcp-ssh-manager',
404
+ version: '1.2.0',
405
+ });
406
+
407
+ logger.info('MCP Server initialized', { version: '1.2.0' });
408
+
409
+ // Register available tools
410
+ server.registerTool(
411
+ 'ssh_execute',
412
+ {
413
+ description: 'Execute command on remote SSH server',
414
+ inputSchema: {
415
+ server: z.string().describe('Server name from configuration'),
416
+ command: z.string().describe('Command to execute'),
417
+ cwd: z.string().optional().describe('Working directory (optional, uses default if configured)'),
418
+ timeout: z.number().optional().describe('Command timeout in milliseconds (default: 30000)')
419
+ }
420
+ },
421
+ async ({ server: serverName, command, cwd, timeout = 30000 }) => {
422
+ try {
423
+ const ssh = await getConnection(serverName);
424
+
425
+ // Expand command aliases
426
+ const expandedCommand = expandCommandAlias(command);
427
+
428
+ // Execute hooks for bench commands
429
+ if (expandedCommand.includes('bench update')) {
430
+ await executeHook('pre-bench-update', {
431
+ server: serverName,
432
+ sshConnection: ssh,
433
+ defaultDir: cwd
434
+ });
435
+ }
436
+
437
+ // Use provided cwd, or default_dir from config, or no cwd
438
+ const servers = loadServerConfig();
439
+ const serverConfig = servers[serverName.toLowerCase()];
440
+ const workingDir = cwd || serverConfig?.default_dir;
441
+ const fullCommand = workingDir ? `cd ${workingDir} && ${expandedCommand}` : expandedCommand;
442
+
443
+ // Log command execution
444
+ const startTime = logger.logCommand(serverName, fullCommand, workingDir);
445
+
446
+ const result = await execCommandWithTimeout(ssh, fullCommand, {}, timeout);
447
+
448
+ // Log command result
449
+ logger.logCommandResult(serverName, fullCommand, startTime, result);
450
+
451
+ // Execute post-hooks for bench commands
452
+ if (expandedCommand.includes('bench update') && result.code === 0) {
453
+ await executeHook('post-bench-update', {
454
+ server: serverName,
455
+ sshConnection: ssh,
456
+ defaultDir: cwd
457
+ });
458
+ }
459
+
460
+ return {
461
+ content: [
462
+ {
463
+ type: 'text',
464
+ text: JSON.stringify({
465
+ server: serverName,
466
+ command: fullCommand,
467
+ stdout: result.stdout,
468
+ stderr: result.stderr,
469
+ code: result.code,
470
+ success: result.code === 0,
471
+ }, null, 2),
472
+ },
473
+ ],
474
+ };
475
+ } catch (error) {
476
+ return {
477
+ content: [
478
+ {
479
+ type: 'text',
480
+ text: `āŒ Error: ${error.message}`,
481
+ },
482
+ ],
483
+ };
484
+ }
485
+ }
486
+ );
487
+
488
+ server.registerTool(
489
+ 'ssh_upload',
490
+ {
491
+ description: 'Upload file to remote SSH server',
492
+ inputSchema: {
493
+ server: z.string().describe('Server name'),
494
+ localPath: z.string().describe('Local file path'),
495
+ remotePath: z.string().describe('Remote destination path')
496
+ }
497
+ },
498
+ async ({ server: serverName, localPath, remotePath }) => {
499
+ try {
500
+ const ssh = await getConnection(serverName);
501
+
502
+ logger.logTransfer('upload', serverName, localPath, remotePath);
503
+ const startTime = Date.now();
504
+
505
+ await ssh.putFile(localPath, remotePath);
506
+
507
+ const fileStats = fs.statSync(localPath);
508
+ logger.logTransfer('upload', serverName, localPath, remotePath, {
509
+ success: true,
510
+ size: fileStats.size,
511
+ duration: `${Date.now() - startTime}ms`
512
+ });
513
+
514
+ return {
515
+ content: [
516
+ {
517
+ type: 'text',
518
+ text: `āœ… File uploaded successfully\nServer: ${serverName}\nLocal: ${localPath}\nRemote: ${remotePath}`,
519
+ },
520
+ ],
521
+ };
522
+ } catch (error) {
523
+ logger.logTransfer('upload', serverName, localPath, remotePath, {
524
+ success: false,
525
+ error: error.message
526
+ });
527
+ return {
528
+ content: [
529
+ {
530
+ type: 'text',
531
+ text: `āŒ Upload error: ${error.message}`,
532
+ },
533
+ ],
534
+ };
535
+ }
536
+ }
537
+ );
538
+
539
+ server.registerTool(
540
+ 'ssh_download',
541
+ {
542
+ description: 'Download file from remote SSH server',
543
+ inputSchema: {
544
+ server: z.string().describe('Server name'),
545
+ remotePath: z.string().describe('Remote file path'),
546
+ localPath: z.string().describe('Local destination path')
547
+ }
548
+ },
549
+ async ({ server: serverName, remotePath, localPath }) => {
550
+ try {
551
+ const ssh = await getConnection(serverName);
552
+
553
+ logger.logTransfer('download', serverName, remotePath, localPath);
554
+ const startTime = Date.now();
555
+
556
+ await ssh.getFile(localPath, remotePath);
557
+
558
+ const fileStats = fs.statSync(localPath);
559
+ logger.logTransfer('download', serverName, remotePath, localPath, {
560
+ success: true,
561
+ size: fileStats.size,
562
+ duration: `${Date.now() - startTime}ms`
563
+ });
564
+
565
+ return {
566
+ content: [
567
+ {
568
+ type: 'text',
569
+ text: `āœ… File downloaded successfully\nServer: ${serverName}\nRemote: ${remotePath}\nLocal: ${localPath}`,
570
+ },
571
+ ],
572
+ };
573
+ } catch (error) {
574
+ logger.logTransfer('download', serverName, remotePath, localPath, {
575
+ success: false,
576
+ error: error.message
577
+ });
578
+ return {
579
+ content: [
580
+ {
581
+ type: 'text',
582
+ text: `āŒ Download error: ${error.message}`,
583
+ },
584
+ ],
585
+ };
586
+ }
587
+ }
588
+ );
589
+
590
+ server.registerTool(
591
+ 'ssh_sync',
592
+ {
593
+ description: 'Synchronize files/folders between local and remote via rsync',
594
+ inputSchema: {
595
+ server: z.string().describe('Server name from configuration'),
596
+ source: z.string().describe('Source path (use "local:" or "remote:" prefix)'),
597
+ destination: z.string().describe('Destination path (use "local:" or "remote:" prefix)'),
598
+ exclude: z.array(z.string()).optional().describe('Patterns to exclude from sync'),
599
+ dryRun: z.boolean().optional().describe('Perform dry run without actual changes'),
600
+ delete: z.boolean().optional().describe('Delete files in destination not in source'),
601
+ compress: z.boolean().optional().describe('Compress during transfer'),
602
+ verbose: z.boolean().optional().describe('Show detailed progress'),
603
+ checksum: z.boolean().optional().describe('Use checksum instead of timestamp for comparison'),
604
+ timeout: z.number().optional().describe('Timeout in milliseconds (default: 30000)')
605
+ }
606
+ },
607
+ async ({ server: serverName, source, destination, exclude = [], dryRun = false, delete: deleteFiles = false, compress = true, verbose = false, checksum = false, timeout = 30000 }) => {
608
+ try {
609
+ const ssh = await getConnection(serverName);
610
+ const servers = loadServerConfig();
611
+ const serverConfig = servers[serverName.toLowerCase()];
612
+
613
+ // Check if sshpass is available for password authentication
614
+ if (!serverConfig.keypath && serverConfig.password) {
615
+ // Check if sshpass is installed
616
+ try {
617
+ const { execSync } = await import('child_process');
618
+ execSync('which sshpass', { stdio: 'ignore' });
619
+ } catch (error) {
620
+ return {
621
+ content: [
622
+ {
623
+ type: 'text',
624
+ text: `āŒ Error: ssh_sync with password authentication requires sshpass.\n\nThe server '${serverName}' uses password authentication.\nPlease install sshpass: brew install hudochenkov/sshpass/sshpass (macOS) or apt-get install sshpass (Linux)\n\nAlternatively, use ssh_upload or ssh_download for single file transfers.`
625
+ }
626
+ ]
627
+ };
628
+ }
629
+ }
630
+
631
+ // Determine sync direction based on source/destination prefixes
632
+ const isLocalSource = source.startsWith('local:');
633
+ const isRemoteSource = source.startsWith('remote:');
634
+ const isLocalDest = destination.startsWith('local:');
635
+ const isRemoteDest = destination.startsWith('remote:');
636
+
637
+ // Clean paths
638
+ const cleanSource = source.replace(/^(local:|remote:)/, '');
639
+ const cleanDest = destination.replace(/^(local:|remote:)/, '');
640
+
641
+ // Validate direction
642
+ if ((isLocalSource && isLocalDest) || (isRemoteSource && isRemoteDest)) {
643
+ throw new Error('Source and destination must be different (one local, one remote). Use prefixes: local: or remote:');
644
+ }
645
+
646
+ // If no prefixes, assume old format (local source to remote dest)
647
+ const direction = (isLocalSource || (!isLocalSource && !isRemoteSource)) ? 'push' : 'pull';
648
+
649
+ // Build rsync command
650
+ let rsyncOptions = ['-avz'];
651
+
652
+ if (!compress) {
653
+ rsyncOptions = ['-av'];
654
+ }
655
+
656
+ if (checksum) {
657
+ rsyncOptions.push('--checksum');
658
+ }
659
+
660
+ if (deleteFiles) {
661
+ rsyncOptions.push('--delete');
662
+ }
663
+
664
+ if (dryRun) {
665
+ rsyncOptions.push('--dry-run');
666
+ }
667
+
668
+ if (verbose || logger.verbose) {
669
+ // Only add stats, not progress to avoid blocking with too much output
670
+ rsyncOptions.push('--stats');
671
+ }
672
+
673
+ // Add exclude patterns
674
+ exclude.forEach(pattern => {
675
+ rsyncOptions.push('--exclude', pattern);
676
+ });
677
+
678
+ let localPath;
679
+ let remotePath;
680
+
681
+ if (direction === 'push') {
682
+ localPath = cleanSource;
683
+ remotePath = cleanDest;
684
+
685
+ // Check if local path exists
686
+ if (!fs.existsSync(localPath)) {
687
+ throw new Error(`Local path does not exist: ${localPath}`);
688
+ }
689
+ } else {
690
+ localPath = cleanDest;
691
+ remotePath = cleanSource;
692
+ }
693
+
694
+ // Add SSH options for non-interactive mode
695
+ const sshOptions = [];
696
+
697
+ // Different options based on authentication method
698
+ if (serverConfig.keypath) {
699
+ sshOptions.push('-o BatchMode=yes'); // No password prompts
700
+ sshOptions.push('-o StrictHostKeyChecking=accept-new'); // Accept new keys, reject changed ones
701
+ sshOptions.push('-o ConnectTimeout=10'); // Connection timeout
702
+
703
+ const keyPath = serverConfig.keypath.replace('~', process.env.HOME);
704
+ sshOptions.push(`-i ${keyPath}`);
705
+ } else {
706
+ // With sshpass, we don't use BatchMode
707
+ sshOptions.push('-o StrictHostKeyChecking=accept-new'); // Accept new keys, reject changed ones
708
+ sshOptions.push('-o ConnectTimeout=10');
709
+ }
710
+
711
+ if (serverConfig.port && serverConfig.port !== '22') {
712
+ sshOptions.push(`-p ${serverConfig.port}`);
713
+ }
714
+
715
+ logger.info(`Starting rsync ${direction}`, {
716
+ server: serverName,
717
+ source: direction === 'push' ? localPath : remotePath,
718
+ destination: direction === 'push' ? remotePath : localPath,
719
+ dryRun,
720
+ deleteFiles
721
+ });
722
+
723
+ const startTime = Date.now();
724
+
725
+ // Execute rsync via spawn for non-blocking streaming
726
+ const { spawn } = await import('child_process');
727
+
728
+ return new Promise((resolve, reject) => {
729
+ let output = '';
730
+ let errorOutput = '';
731
+ let killed = false;
732
+
733
+ // Build command based on authentication method
734
+ let rsyncCommand;
735
+ let rsyncArgs = [];
736
+ let processEnv = { ...process.env };
737
+
738
+ if (serverConfig.password) {
739
+ // Use sshpass for password authentication
740
+ rsyncCommand = 'sshpass';
741
+ rsyncArgs.push('-p', serverConfig.password);
742
+ rsyncArgs.push('rsync');
743
+
744
+ // Add rsync options
745
+ rsyncOptions.forEach(opt => rsyncArgs.push(opt));
746
+
747
+ // Add SSH command
748
+ const sshCmd = `ssh ${sshOptions.join(' ')}`;
749
+ rsyncArgs.push('-e', sshCmd);
750
+ } else {
751
+ // Direct rsync for key authentication
752
+ rsyncCommand = 'rsync';
753
+
754
+ // Add rsync options
755
+ rsyncOptions.forEach(opt => rsyncArgs.push(opt));
756
+
757
+ // Add SSH command with all options
758
+ const sshCmd = `ssh ${sshOptions.join(' ')}`;
759
+ rsyncArgs.push('-e', sshCmd);
760
+
761
+ processEnv.SSH_ASKPASS = '/bin/false';
762
+ processEnv.DISPLAY = '';
763
+ }
764
+
765
+ // Add source and destination
766
+ if (direction === 'push') {
767
+ rsyncArgs.push(localPath);
768
+ rsyncArgs.push(`${serverConfig.user}@${serverConfig.host}:${remotePath}`);
769
+ } else {
770
+ rsyncArgs.push(`${serverConfig.user}@${serverConfig.host}:${remotePath}`);
771
+ rsyncArgs.push(localPath);
772
+ }
773
+
774
+ const rsyncProcess = spawn(rsyncCommand, rsyncArgs, {
775
+ stdio: ['ignore', 'pipe', 'pipe'],
776
+ env: processEnv
777
+ });
778
+
779
+ // Set timeout
780
+ const timer = setTimeout(() => {
781
+ killed = true;
782
+ rsyncProcess.kill('SIGTERM');
783
+ reject(new Error(`Rsync timeout after ${timeout}ms`));
784
+ }, timeout);
785
+
786
+ // Collect output with size limit
787
+ rsyncProcess.stdout.on('data', (data) => {
788
+ const chunk = data.toString();
789
+ output += chunk;
790
+ // Limit output size to prevent memory issues
791
+ if (output.length > 100000) {
792
+ output = output.slice(-50000);
793
+ }
794
+ });
795
+
796
+ rsyncProcess.stderr.on('data', (data) => {
797
+ const chunk = data.toString();
798
+ errorOutput += chunk;
799
+ if (errorOutput.length > 50000) {
800
+ errorOutput = errorOutput.slice(-25000);
801
+ }
802
+ });
803
+
804
+ rsyncProcess.on('error', (err) => {
805
+ clearTimeout(timer);
806
+ reject(new Error(`Failed to start rsync: ${err.message}`));
807
+ });
808
+
809
+ rsyncProcess.on('close', (code) => {
810
+ clearTimeout(timer);
811
+
812
+ if (killed) {
813
+ return; // Already rejected due to timeout
814
+ }
815
+
816
+ const duration = Date.now() - startTime;
817
+
818
+ if (code !== 0) {
819
+ logger.error(`Rsync ${direction} failed`, {
820
+ server: serverName,
821
+ exitCode: code,
822
+ error: errorOutput,
823
+ duration: `${duration}ms`
824
+ });
825
+
826
+ // Check if it's an SSH key error
827
+ if (detectSSHKeyError(errorOutput)) {
828
+ const hostInfo = extractHostFromSSHError(errorOutput);
829
+ let errorMsg = `SSH host key verification failed for ${serverName}.\n`;
830
+
831
+ if (hostInfo) {
832
+ errorMsg += `Host: ${hostInfo.host}:${hostInfo.port}\n`;
833
+ }
834
+
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`;
839
+ errorMsg += `\nOriginal error:\n${errorOutput}`;
840
+
841
+ reject(new Error(errorMsg));
842
+ } else {
843
+ reject(new Error(`Rsync failed with exit code ${code}: ${errorOutput || 'Unknown error'}`));
844
+ }
845
+ return;
846
+ }
847
+
848
+ // Parse rsync output for statistics
849
+ let stats = {
850
+ filesTransferred: 0,
851
+ totalSize: 0,
852
+ totalTime: duration
853
+ };
854
+
855
+ // Extract statistics from rsync output
856
+ const filesMatch = output.match(/Number of files transferred: (\d+)/);
857
+ const sizeMatch = output.match(/Total transferred file size: ([\d,]+) bytes/);
858
+ const speedMatch = output.match(/([\d.]+) bytes\/sec/);
859
+
860
+ if (filesMatch) stats.filesTransferred = parseInt(filesMatch[1]);
861
+ if (sizeMatch) stats.totalSize = parseInt(sizeMatch[1].replace(/,/g, ''));
862
+ if (speedMatch) stats.speed = parseFloat(speedMatch[1]);
863
+
864
+ logger.info(`Rsync ${direction} completed`, {
865
+ server: serverName,
866
+ direction,
867
+ duration: `${duration}ms`,
868
+ filesTransferred: stats.filesTransferred,
869
+ totalSize: stats.totalSize,
870
+ dryRun
871
+ });
872
+
873
+ // Format output
874
+ let resultText = dryRun ? 'šŸ” Dry run completed\n' : 'āœ… Sync completed successfully\n';
875
+ resultText += `Direction: ${direction === 'push' ? 'Local → Remote' : 'Remote → Local'}\n`;
876
+ resultText += `Server: ${serverName}\n`;
877
+ resultText += `Source: ${direction === 'push' ? localPath : remotePath}\n`;
878
+ resultText += `Destination: ${direction === 'push' ? remotePath : localPath}\n`;
879
+
880
+ if (stats.filesTransferred > 0) {
881
+ resultText += `Files transferred: ${stats.filesTransferred}\n`;
882
+ if (stats.totalSize > 0) {
883
+ const sizeKB = (stats.totalSize / 1024).toFixed(2);
884
+ resultText += `Total size: ${sizeKB} KB\n`;
885
+ }
886
+ if (stats.speed) {
887
+ const speedKB = (stats.speed / 1024).toFixed(2);
888
+ resultText += `Average speed: ${speedKB} KB/s\n`;
889
+ }
890
+ } else {
891
+ resultText += 'No files needed to be transferred\n';
892
+ }
893
+
894
+ resultText += `Time: ${(duration / 1000).toFixed(2)} seconds\n`;
895
+
896
+ if (verbose && output.length < 5000) {
897
+ resultText += '\nšŸ“‹ Sync statistics:\n';
898
+ // 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') ||
903
+ line.includes('received')
904
+ );
905
+ if (statsLines.length > 0) {
906
+ resultText += statsLines.join('\n');
907
+ }
908
+ }
909
+
910
+ resolve({
911
+ content: [
912
+ {
913
+ type: 'text',
914
+ text: resultText
915
+ }
916
+ ]
917
+ });
918
+ });
919
+ });
920
+ } catch (error) {
921
+ return {
922
+ content: [
923
+ {
924
+ type: 'text',
925
+ text: `āŒ Sync error: ${error.message}`
926
+ }
927
+ ]
928
+ };
929
+ }
930
+ }
931
+ );
932
+
933
+ server.registerTool(
934
+ 'ssh_tail',
935
+ {
936
+ description: 'Tail remote log files in real-time',
937
+ inputSchema: {
938
+ server: z.string().describe('Server name from configuration'),
939
+ file: z.string().describe('Path to the log file to tail'),
940
+ lines: z.number().optional().describe('Number of lines to show initially (default: 10)'),
941
+ follow: z.boolean().optional().describe('Follow file for new content (default: true)'),
942
+ grep: z.string().optional().describe('Filter lines with grep pattern')
943
+ }
944
+ },
945
+ async ({ server: serverName, file, lines = 10, follow = true, grep }) => {
946
+ try {
947
+ const ssh = await getConnection(serverName);
948
+
949
+ // Build tail command
950
+ let command = `tail -n ${lines}`;
951
+ if (follow) {
952
+ command += ' -f';
953
+ }
954
+ command += ` "${file}"`;
955
+
956
+ // Add grep filter if specified
957
+ if (grep) {
958
+ command += ` | grep "${grep}"`;
959
+ }
960
+
961
+ logger.info(`Starting tail on ${serverName}`, {
962
+ file,
963
+ lines,
964
+ follow,
965
+ grep
966
+ });
967
+
968
+ // For follow mode, we need to handle streaming
969
+ if (follow) {
970
+ // Create a unique session ID for this tail
971
+ const sessionId = `tail_${Date.now()}`;
972
+
973
+ // Store the SSH stream for later cleanup
974
+ const stream = await ssh.execCommandStream(command, {
975
+ onStdout: (chunk) => {
976
+ // In a real implementation, this would stream to the client
977
+ console.error(`[${serverName}:${file}] ${chunk}`);
978
+ },
979
+ onStderr: (chunk) => {
980
+ console.error(`[ERROR] ${chunk}`);
981
+ }
982
+ });
983
+
984
+ return {
985
+ content: [
986
+ {
987
+ type: 'text',
988
+ text: `šŸ“œ Tailing ${file} on ${serverName}\nSession ID: ${sessionId}\nShowing last ${lines} lines${grep ? ` (filtered: ${grep})` : ''}\n\nāš ļø Note: In follow mode, output is streamed to stderr.\nTo stop tailing, you'll need to kill the session.`
989
+ }
990
+ ]
991
+ };
992
+ } else {
993
+ // Non-follow mode - just get the output
994
+ const result = await execCommandWithTimeout(ssh, command, {}, 15000);
995
+
996
+ if (result.code !== 0) {
997
+ throw new Error(result.stderr || 'Failed to tail file');
998
+ }
999
+
1000
+ logger.info(`Tail completed on ${serverName}`, {
1001
+ file,
1002
+ lines: result.stdout.split('\n').length
1003
+ });
1004
+
1005
+ return {
1006
+ content: [
1007
+ {
1008
+ type: 'text',
1009
+ text: `šŸ“œ Last ${lines} lines of ${file} on ${serverName}${grep ? ` (filtered: ${grep})` : ''}:\n\n${result.stdout}`
1010
+ }
1011
+ ]
1012
+ };
1013
+ }
1014
+ } catch (error) {
1015
+ logger.error(`Tail failed on ${serverName}`, {
1016
+ file,
1017
+ error: error.message
1018
+ });
1019
+
1020
+ return {
1021
+ content: [
1022
+ {
1023
+ type: 'text',
1024
+ text: `āŒ Tail error: ${error.message}`
1025
+ }
1026
+ ]
1027
+ };
1028
+ }
1029
+ }
1030
+ );
1031
+
1032
+ server.registerTool(
1033
+ 'ssh_monitor',
1034
+ {
1035
+ description: 'Monitor system resources (CPU, RAM, disk) on remote server',
1036
+ inputSchema: {
1037
+ server: z.string().describe('Server name from configuration'),
1038
+ type: z.enum(['overview', 'cpu', 'memory', 'disk', 'network', 'process']).optional().describe('Type of monitoring (default: overview)'),
1039
+ interval: z.number().optional().describe('Update interval in seconds for continuous monitoring'),
1040
+ duration: z.number().optional().describe('Duration in seconds for continuous monitoring')
1041
+ }
1042
+ },
1043
+ async ({ server: serverName, type = 'overview', interval, duration }) => {
1044
+ try {
1045
+ const ssh = await getConnection(serverName);
1046
+
1047
+ logger.info(`Starting system monitoring on ${serverName}`, {
1048
+ type,
1049
+ interval,
1050
+ duration
1051
+ });
1052
+
1053
+ let commands = {};
1054
+ let output = {};
1055
+
1056
+ // Define monitoring commands based on type
1057
+ 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;
1097
+ }
1098
+
1099
+ // Execute all monitoring commands
1100
+ const startTime = Date.now();
1101
+
1102
+ for (const [key, cmd] of Object.entries(commands)) {
1103
+ try {
1104
+ const result = await execCommandWithTimeout(ssh, cmd, {}, 10000);
1105
+ if (result.code === 0) {
1106
+ output[key] = result.stdout.trim();
1107
+ } else {
1108
+ output[key] = `Error: ${result.stderr || 'Command failed'}`;
1109
+ }
1110
+ } catch (err) {
1111
+ output[key] = `Error: ${err.message}`;
1112
+ }
1113
+ }
1114
+
1115
+ const monitoringDuration = Date.now() - startTime;
1116
+
1117
+ // Format the output based on type
1118
+ let formattedOutput = `šŸ“Š System Monitor - ${serverName}\n`;
1119
+ formattedOutput += `Type: ${type} | Time: ${new Date().toISOString()}\n`;
1120
+ formattedOutput += `Collection time: ${monitoringDuration}ms\n`;
1121
+ formattedOutput += '━'.repeat(50) + '\n\n';
1122
+
1123
+ 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;
1162
+ }
1163
+
1164
+ // Log monitoring results
1165
+ logger.info(`System monitoring completed on ${serverName}`, {
1166
+ type,
1167
+ duration: `${monitoringDuration}ms`,
1168
+ metrics: Object.keys(output).length
1169
+ });
1170
+
1171
+ // If continuous monitoring requested
1172
+ if (interval && duration) {
1173
+ formattedOutput += `\n\nā° Continuous monitoring: Every ${interval}s for ${duration}s\n`;
1174
+ formattedOutput += `(Not implemented in this version - would require streaming support)`;
1175
+ }
1176
+
1177
+ return {
1178
+ content: [
1179
+ {
1180
+ type: 'text',
1181
+ text: formattedOutput
1182
+ }
1183
+ ]
1184
+ };
1185
+ } catch (error) {
1186
+ logger.error(`Monitoring failed on ${serverName}`, {
1187
+ type,
1188
+ error: error.message
1189
+ });
1190
+
1191
+ return {
1192
+ content: [
1193
+ {
1194
+ type: 'text',
1195
+ text: `āŒ Monitor error: ${error.message}`
1196
+ }
1197
+ ]
1198
+ };
1199
+ }
1200
+ }
1201
+ );
1202
+
1203
+ server.registerTool(
1204
+ 'ssh_history',
1205
+ {
1206
+ description: 'View SSH command history',
1207
+ inputSchema: {
1208
+ limit: z.number().optional().describe('Number of commands to show (default: 20)'),
1209
+ server: z.string().optional().describe('Filter by server name'),
1210
+ success: z.boolean().optional().describe('Filter by success/failure'),
1211
+ search: z.string().optional().describe('Search in commands')
1212
+ }
1213
+ },
1214
+ async ({ limit = 20, server, success, search }) => {
1215
+ try {
1216
+ // Get history from logger
1217
+ let history = logger.getHistory(limit * 2); // Get more to account for filtering
1218
+
1219
+ // Apply filters
1220
+ if (server) {
1221
+ history = history.filter(h => h.server?.toLowerCase().includes(server.toLowerCase()));
1222
+ }
1223
+
1224
+ if (success !== undefined) {
1225
+ history = history.filter(h => h.success === success);
1226
+ }
1227
+
1228
+ if (search) {
1229
+ history = history.filter(h => h.command?.toLowerCase().includes(search.toLowerCase()));
1230
+ }
1231
+
1232
+ // Limit results
1233
+ history = history.slice(-limit);
1234
+
1235
+ // Format output
1236
+ let output = `šŸ“œ SSH Command History\n`;
1237
+ output += `Showing last ${history.length} commands`;
1238
+
1239
+ const filters = [];
1240
+ if (server) filters.push(`server: ${server}`);
1241
+ if (success !== undefined) filters.push(success ? 'successful only' : 'failed only');
1242
+ if (search) filters.push(`search: ${search}`);
1243
+
1244
+ if (filters.length > 0) {
1245
+ output += ` (filtered: ${filters.join(', ')})`;
1246
+ }
1247
+
1248
+ output += '\n' + '━'.repeat(60) + '\n\n';
1249
+
1250
+ if (history.length === 0) {
1251
+ output += 'No commands found matching the criteria.\n';
1252
+ } else {
1253
+ history.forEach((entry, index) => {
1254
+ const time = new Date(entry.timestamp).toLocaleString();
1255
+ const status = entry.success ? 'āœ…' : 'āŒ';
1256
+ const duration = entry.duration || 'N/A';
1257
+
1258
+ output += `${history.length - index}. ${status} [${time}]\n`;
1259
+ output += ` Server: ${entry.server || 'unknown'}\n`;
1260
+ output += ` Command: ${entry.command?.substring(0, 100) || 'N/A'}`;
1261
+ if (entry.command && entry.command.length > 100) {
1262
+ output += '...';
1263
+ }
1264
+ output += '\n';
1265
+ output += ` Duration: ${duration}`;
1266
+
1267
+ if (!entry.success && entry.error) {
1268
+ output += `\n Error: ${entry.error}`;
1269
+ }
1270
+
1271
+ output += '\n\n';
1272
+ });
1273
+ }
1274
+
1275
+ output += '━'.repeat(60) + '\n';
1276
+ output += `Total commands in history: ${logger.getHistory(1000).length}\n`;
1277
+
1278
+ logger.info('Command history retrieved', {
1279
+ limit,
1280
+ filters: filters.length,
1281
+ results: history.length
1282
+ });
1283
+
1284
+ return {
1285
+ content: [
1286
+ {
1287
+ type: 'text',
1288
+ text: output
1289
+ }
1290
+ ]
1291
+ };
1292
+ } catch (error) {
1293
+ return {
1294
+ content: [
1295
+ {
1296
+ type: 'text',
1297
+ text: `āŒ Error retrieving history: ${error.message}`
1298
+ }
1299
+ ]
1300
+ };
1301
+ }
1302
+ }
1303
+ );
1304
+
1305
+ // SSH Session Management Tools
1306
+
1307
+ server.registerTool(
1308
+ 'ssh_session_start',
1309
+ {
1310
+ description: 'Start a persistent SSH session that maintains state and context',
1311
+ inputSchema: {
1312
+ server: z.string().describe('Server name from configuration'),
1313
+ name: z.string().optional().describe('Optional session name for identification')
1314
+ }
1315
+ },
1316
+ async ({ server: serverName, name }) => {
1317
+ try {
1318
+ const ssh = await getConnection(serverName);
1319
+ const session = await createSession(serverName, ssh);
1320
+
1321
+ const sessionName = name || `Session on ${serverName}`;
1322
+
1323
+ logger.info('SSH session started', {
1324
+ id: session.id,
1325
+ server: serverName,
1326
+ name: sessionName
1327
+ });
1328
+
1329
+ return {
1330
+ content: [
1331
+ {
1332
+ type: 'text',
1333
+ text: `šŸš€ SSH Session Started\n\nSession ID: ${session.id}\nServer: ${serverName}\nName: ${sessionName}\nState: ${session.state}\nWorking Directory: ${session.context.cwd}\n\nUse ssh_session_send to execute commands in this session.\nUse ssh_session_close to terminate the session.`
1334
+ }
1335
+ ]
1336
+ };
1337
+ } catch (error) {
1338
+ logger.error('Failed to start SSH session', {
1339
+ server: serverName,
1340
+ error: error.message
1341
+ });
1342
+
1343
+ return {
1344
+ content: [
1345
+ {
1346
+ type: 'text',
1347
+ text: `āŒ Failed to start session: ${error.message}`
1348
+ }
1349
+ ]
1350
+ };
1351
+ }
1352
+ }
1353
+ );
1354
+
1355
+ server.registerTool(
1356
+ 'ssh_session_send',
1357
+ {
1358
+ description: 'Send a command to an existing SSH session',
1359
+ inputSchema: {
1360
+ session: z.string().describe('Session ID from ssh_session_start'),
1361
+ command: z.string().describe('Command to execute in the session'),
1362
+ timeout: z.number().optional().describe('Command timeout in milliseconds (default: 30000)')
1363
+ }
1364
+ },
1365
+ async ({ session: sessionId, command, timeout = 30000 }) => {
1366
+ try {
1367
+ const session = getSession(sessionId);
1368
+
1369
+ const startTime = Date.now();
1370
+ const result = await session.execute(command, { timeout });
1371
+ const duration = Date.now() - startTime;
1372
+
1373
+ logger.info('Session command executed', {
1374
+ session: sessionId,
1375
+ command: command.substring(0, 50),
1376
+ success: result.success,
1377
+ duration: `${duration}ms`
1378
+ });
1379
+
1380
+ let output = `šŸ“Ÿ Session: ${sessionId}\n`;
1381
+ output += `Server: ${session.serverName}\n`;
1382
+ output += `Working Directory: ${session.context.cwd}\n`;
1383
+ output += `Command: ${command}\n`;
1384
+ output += `Duration: ${duration}ms\n`;
1385
+ output += '━'.repeat(60) + '\n\n';
1386
+
1387
+ if (result.success) {
1388
+ output += 'āœ… Output:\n' + result.output;
1389
+ } else {
1390
+ output += 'āŒ Error:\n' + (result.error || result.output);
1391
+ }
1392
+
1393
+ // Add session state info
1394
+ output += '\n\n' + '━'.repeat(60) + '\n';
1395
+ output += `Session State: ${session.state}\n`;
1396
+ output += `Commands Executed: ${session.context.history.length}\n`;
1397
+
1398
+ return {
1399
+ content: [
1400
+ {
1401
+ type: 'text',
1402
+ text: output
1403
+ }
1404
+ ]
1405
+ };
1406
+ } catch (error) {
1407
+ logger.error('Failed to send command to session', {
1408
+ session: sessionId,
1409
+ command,
1410
+ error: error.message
1411
+ });
1412
+
1413
+ return {
1414
+ content: [
1415
+ {
1416
+ type: 'text',
1417
+ text: `āŒ Session error: ${error.message}`
1418
+ }
1419
+ ]
1420
+ };
1421
+ }
1422
+ }
1423
+ );
1424
+
1425
+ server.registerTool(
1426
+ 'ssh_session_list',
1427
+ {
1428
+ description: 'List all active SSH sessions',
1429
+ inputSchema: {
1430
+ server: z.string().optional().describe('Filter by server name')
1431
+ }
1432
+ },
1433
+ async ({ server }) => {
1434
+ try {
1435
+ let sessions = listSessions();
1436
+
1437
+ // Filter by server if specified
1438
+ if (server) {
1439
+ sessions = sessions.filter(s =>
1440
+ s.server.toLowerCase().includes(server.toLowerCase())
1441
+ );
1442
+ }
1443
+
1444
+ let output = `šŸ“‹ Active SSH Sessions\n`;
1445
+ output += '━'.repeat(60) + '\n\n';
1446
+
1447
+ if (sessions.length === 0) {
1448
+ output += 'No active sessions';
1449
+ if (server) {
1450
+ output += ` for server "${server}"`;
1451
+ }
1452
+ output += '.\n';
1453
+ } else {
1454
+ sessions.forEach((session, index) => {
1455
+ const age = Math.floor((Date.now() - new Date(session.created).getTime()) / 1000);
1456
+ const idle = Math.floor((Date.now() - new Date(session.lastActivity).getTime()) / 1000);
1457
+
1458
+ output += `${index + 1}. Session: ${session.id}\n`;
1459
+ output += ` Server: ${session.server}\n`;
1460
+ output += ` State: ${session.state}\n`;
1461
+ output += ` Working Dir: ${session.cwd || 'unknown'}\n`;
1462
+ output += ` Commands Run: ${session.historyCount}\n`;
1463
+ output += ` Age: ${formatDuration(age)}\n`;
1464
+ output += ` Idle: ${formatDuration(idle)}\n`;
1465
+
1466
+ if (session.variables.length > 0) {
1467
+ output += ` Variables: ${session.variables.join(', ')}\n`;
1468
+ }
1469
+
1470
+ output += '\n';
1471
+ });
1472
+ }
1473
+
1474
+ output += '━'.repeat(60) + '\n';
1475
+ output += `Total Active Sessions: ${sessions.length}\n`;
1476
+
1477
+ logger.info('Listed SSH sessions', {
1478
+ total: sessions.length,
1479
+ filter: server
1480
+ });
1481
+
1482
+ return {
1483
+ content: [
1484
+ {
1485
+ type: 'text',
1486
+ text: output
1487
+ }
1488
+ ]
1489
+ };
1490
+ } catch (error) {
1491
+ return {
1492
+ content: [
1493
+ {
1494
+ type: 'text',
1495
+ text: `āŒ Error listing sessions: ${error.message}`
1496
+ }
1497
+ ]
1498
+ };
1499
+ }
1500
+ }
1501
+ );
1502
+
1503
+ server.registerTool(
1504
+ 'ssh_session_close',
1505
+ {
1506
+ description: 'Close an SSH session',
1507
+ inputSchema: {
1508
+ session: z.string().describe('Session ID to close (or "all" to close all sessions)')
1509
+ }
1510
+ },
1511
+ async ({ session: sessionId }) => {
1512
+ try {
1513
+ if (sessionId === 'all') {
1514
+ const sessions = listSessions();
1515
+ const count = sessions.length;
1516
+
1517
+ sessions.forEach(s => {
1518
+ try {
1519
+ closeSession(s.id);
1520
+ } catch (err) {
1521
+ // Ignore individual close errors
1522
+ }
1523
+ });
1524
+
1525
+ logger.info('Closed all SSH sessions', { count });
1526
+
1527
+ return {
1528
+ content: [
1529
+ {
1530
+ type: 'text',
1531
+ text: `šŸ”š Closed ${count} SSH sessions`
1532
+ }
1533
+ ]
1534
+ };
1535
+ } else {
1536
+ closeSession(sessionId);
1537
+
1538
+ logger.info('SSH session closed', { session: sessionId });
1539
+
1540
+ return {
1541
+ content: [
1542
+ {
1543
+ type: 'text',
1544
+ text: `šŸ”š Session closed: ${sessionId}`
1545
+ }
1546
+ ]
1547
+ };
1548
+ }
1549
+ } catch (error) {
1550
+ logger.error('Failed to close session', {
1551
+ session: sessionId,
1552
+ error: error.message
1553
+ });
1554
+
1555
+ return {
1556
+ content: [
1557
+ {
1558
+ type: 'text',
1559
+ text: `āŒ Failed to close session: ${error.message}`
1560
+ }
1561
+ ]
1562
+ };
1563
+ }
1564
+ }
1565
+ );
1566
+
1567
+ // Helper function to format duration
1568
+ function formatDuration(seconds) {
1569
+ if (seconds < 60) {
1570
+ return `${seconds}s`;
1571
+ } else if (seconds < 3600) {
1572
+ return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
1573
+ } else {
1574
+ return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
1575
+ }
1576
+ }
1577
+
1578
+ // Server Group Management Tools
1579
+
1580
+ server.registerTool(
1581
+ 'ssh_execute_group',
1582
+ {
1583
+ description: 'Execute command on a group of servers',
1584
+ inputSchema: {
1585
+ group: z.string().describe('Group name (e.g., "production", "staging", "all")'),
1586
+ command: z.string().describe('Command to execute'),
1587
+ strategy: z.enum(['parallel', 'sequential', 'rolling']).optional().describe('Execution strategy'),
1588
+ delay: z.number().optional().describe('Delay between servers in ms (for rolling)'),
1589
+ stopOnError: z.boolean().optional().describe('Stop execution on first error'),
1590
+ cwd: z.string().optional().describe('Working directory')
1591
+ }
1592
+ },
1593
+ async ({ group: groupName, command, strategy, delay, stopOnError, cwd }) => {
1594
+ try {
1595
+ // Execute command on each server in the group
1596
+ const result = await executeOnGroup(
1597
+ groupName,
1598
+ async (serverName) => {
1599
+ const ssh = await getConnection(serverName);
1600
+
1601
+ // Build full command with cwd if provided
1602
+ const servers = loadServerConfig();
1603
+ const serverConfig = servers[serverName.toLowerCase()];
1604
+ const workingDir = cwd || serverConfig?.default_dir;
1605
+ const fullCommand = workingDir ? `cd ${workingDir} && ${command}` : command;
1606
+
1607
+ const execResult = await execCommandWithTimeout(ssh, fullCommand, {}, 30000);
1608
+
1609
+ return {
1610
+ stdout: execResult.stdout,
1611
+ stderr: execResult.stderr,
1612
+ code: execResult.code,
1613
+ success: execResult.code === 0
1614
+ };
1615
+ },
1616
+ { strategy, delay, stopOnError }
1617
+ );
1618
+
1619
+ // Format output
1620
+ let output = `šŸš€ Group Execution: ${groupName}\n`;
1621
+ output += `Command: ${command}\n`;
1622
+ output += `Strategy: ${result.strategy}\n`;
1623
+ output += '━'.repeat(60) + '\n\n';
1624
+
1625
+ // Show results for each server
1626
+ result.results.forEach(({ server, success, result: execResult, error }) => {
1627
+ output += `šŸ“ ${server}: ${success ? 'āœ… SUCCESS' : 'āŒ FAILED'}\n`;
1628
+
1629
+ if (success && execResult) {
1630
+ if (execResult.stdout) {
1631
+ output += ` Output: ${execResult.stdout.substring(0, 200)}`;
1632
+ if (execResult.stdout.length > 200) output += '...';
1633
+ output += '\n';
1634
+ }
1635
+ if (execResult.stderr) {
1636
+ output += ` Stderr: ${execResult.stderr.substring(0, 100)}\n`;
1637
+ }
1638
+ } else if (error) {
1639
+ output += ` Error: ${error}\n`;
1640
+ }
1641
+ output += '\n';
1642
+ });
1643
+
1644
+ // Summary
1645
+ output += '━'.repeat(60) + '\n';
1646
+ output += `Summary: ${result.summary.successful}/${result.summary.total} successful`;
1647
+ if (result.summary.failed > 0) {
1648
+ output += ` (${result.summary.failed} failed)`;
1649
+ }
1650
+ output += '\n';
1651
+
1652
+ logger.info('Group command executed', {
1653
+ group: groupName,
1654
+ command: command.substring(0, 50),
1655
+ ...result.summary
1656
+ });
1657
+
1658
+ return {
1659
+ content: [
1660
+ {
1661
+ type: 'text',
1662
+ text: output
1663
+ }
1664
+ ]
1665
+ };
1666
+ } catch (error) {
1667
+ logger.error('Group execution failed', {
1668
+ group: groupName,
1669
+ error: error.message
1670
+ });
1671
+
1672
+ return {
1673
+ content: [
1674
+ {
1675
+ type: 'text',
1676
+ text: `āŒ Group execution error: ${error.message}`
1677
+ }
1678
+ ]
1679
+ };
1680
+ }
1681
+ }
1682
+ );
1683
+
1684
+ server.registerTool(
1685
+ 'ssh_group_manage',
1686
+ {
1687
+ description: 'Manage server groups (create, update, delete, list)',
1688
+ inputSchema: {
1689
+ action: z.enum(['create', 'update', 'delete', 'list', 'add-servers', 'remove-servers']).describe('Action to perform'),
1690
+ name: z.string().optional().describe('Group name'),
1691
+ servers: z.array(z.string()).optional().describe('Server names'),
1692
+ description: z.string().optional().describe('Group description'),
1693
+ strategy: z.enum(['parallel', 'sequential', 'rolling']).optional().describe('Execution strategy'),
1694
+ delay: z.number().optional().describe('Delay between servers in ms'),
1695
+ stopOnError: z.boolean().optional().describe('Stop on error flag')
1696
+ }
1697
+ },
1698
+ async ({ action, name, servers, description, strategy, delay, stopOnError }) => {
1699
+ try {
1700
+ let result;
1701
+ let output = '';
1702
+
1703
+ 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`;
1773
+ 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}`);
1782
+ }
1783
+
1784
+ logger.info('Group management action completed', {
1785
+ action,
1786
+ name,
1787
+ servers: servers?.length
1788
+ });
1789
+
1790
+ return {
1791
+ content: [
1792
+ {
1793
+ type: 'text',
1794
+ text: output
1795
+ }
1796
+ ]
1797
+ };
1798
+ } catch (error) {
1799
+ logger.error('Group management failed', {
1800
+ action,
1801
+ name,
1802
+ error: error.message
1803
+ });
1804
+
1805
+ return {
1806
+ content: [
1807
+ {
1808
+ type: 'text',
1809
+ text: `āŒ Group management error: ${error.message}`
1810
+ }
1811
+ ]
1812
+ };
1813
+ }
1814
+ }
1815
+ );
1816
+
1817
+ server.registerTool(
1818
+ 'ssh_list_servers',
1819
+ {
1820
+ description: 'List all configured SSH servers',
1821
+ inputSchema: {}
1822
+ },
1823
+ async () => {
1824
+ const servers = loadServerConfig();
1825
+ const serverInfo = Object.entries(servers).map(([name, config]) => ({
1826
+ name,
1827
+ host: config.host,
1828
+ user: config.user,
1829
+ port: config.port || '22',
1830
+ auth: config.password ? 'password' : 'key',
1831
+ defaultDir: config.default_dir || '',
1832
+ description: config.description || ''
1833
+ }));
1834
+
1835
+ return {
1836
+ content: [
1837
+ {
1838
+ type: 'text',
1839
+ text: JSON.stringify(serverInfo, null, 2),
1840
+ },
1841
+ ],
1842
+ };
1843
+ }
1844
+ );
1845
+
1846
+ // New deploy tool for automated deployment
1847
+ server.registerTool(
1848
+ 'ssh_deploy',
1849
+ {
1850
+ description: 'Deploy files to remote server with automatic permission handling',
1851
+ inputSchema: {
1852
+ server: z.string().describe('Server name or alias'),
1853
+ files: z.array(z.object({
1854
+ local: z.string().describe('Local file path'),
1855
+ remote: z.string().describe('Remote file path')
1856
+ })).describe('Array of files to deploy'),
1857
+ options: z.object({
1858
+ owner: z.string().optional().describe('Set file owner (e.g., "user:group")'),
1859
+ permissions: z.string().optional().describe('Set file permissions (e.g., "644")'),
1860
+ backup: z.boolean().optional().default(true).describe('Backup existing files'),
1861
+ restart: z.string().optional().describe('Service to restart after deployment'),
1862
+ sudoPassword: z.string().optional().describe('Sudo password if needed (use with caution)')
1863
+ }).optional().describe('Deployment options')
1864
+ }
1865
+ },
1866
+ async ({ server, files, options = {} }) => {
1867
+ try {
1868
+ const ssh = await getConnection(server);
1869
+
1870
+ // Execute pre-deploy hook
1871
+ await executeHook('pre-deploy', {
1872
+ server: server,
1873
+ files: files.map(f => f.local).join(', ')
1874
+ });
1875
+
1876
+ const deployments = [];
1877
+ const results = [];
1878
+
1879
+ // Prepare deployment for each file
1880
+ for (const file of files) {
1881
+ const tempFile = getTempFilename(path.basename(file.local));
1882
+ const needs = detectDeploymentNeeds(file.remote);
1883
+
1884
+ // Merge detected needs with user options
1885
+ const deployOptions = {
1886
+ ...options,
1887
+ owner: options.owner || needs.suggestedOwner,
1888
+ permissions: options.permissions || needs.suggestedPerms
1889
+ };
1890
+
1891
+ const strategy = buildDeploymentStrategy(file.remote, deployOptions);
1892
+
1893
+ // Upload file to temp location first
1894
+ await ssh.putFile(file.local, tempFile);
1895
+ results.push(`āœ… Uploaded ${path.basename(file.local)} to temp location`);
1896
+
1897
+ // Execute deployment strategy
1898
+ for (const step of strategy.steps) {
1899
+ const command = step.command.replace('{{tempFile}}', tempFile);
1900
+
1901
+ const result = await execCommandWithTimeout(ssh, command, {}, 15000);
1902
+
1903
+ if (result.code !== 0 && step.type !== 'backup') {
1904
+ throw new Error(`${step.type} failed: ${result.stderr}`);
1905
+ }
1906
+
1907
+ if (step.type !== 'cleanup') {
1908
+ results.push(`āœ… ${step.type}: ${file.remote}`);
1909
+ }
1910
+ }
1911
+
1912
+ deployments.push({
1913
+ local: file.local,
1914
+ remote: file.remote,
1915
+ tempFile,
1916
+ strategy
1917
+ });
1918
+ }
1919
+
1920
+ // Execute post-deploy hook
1921
+ await executeHook('post-deploy', {
1922
+ server: server,
1923
+ files: files.map(f => f.remote).join(', ')
1924
+ });
1925
+
1926
+ return {
1927
+ content: [
1928
+ {
1929
+ type: 'text',
1930
+ text: `šŸš€ Deployment successful!\n\n${results.join('\n')}`,
1931
+ },
1932
+ ],
1933
+ };
1934
+ } catch (error) {
1935
+ return {
1936
+ content: [
1937
+ {
1938
+ type: 'text',
1939
+ text: `āŒ Deployment failed: ${error.message}`,
1940
+ },
1941
+ ],
1942
+ };
1943
+ }
1944
+ }
1945
+ );
1946
+
1947
+ // Execute command with sudo support
1948
+ server.registerTool(
1949
+ 'ssh_execute_sudo',
1950
+ {
1951
+ description: 'Execute command with sudo on remote server',
1952
+ inputSchema: {
1953
+ server: z.string().describe('Server name or alias'),
1954
+ command: z.string().describe('Command to execute with sudo'),
1955
+ password: z.string().optional().describe('Sudo password (will be masked in output)'),
1956
+ cwd: z.string().optional().describe('Working directory'),
1957
+ timeout: z.number().optional().describe('Command timeout in milliseconds (default: 30000)')
1958
+ }
1959
+ },
1960
+ async ({ server, command, password, cwd, timeout = 30000 }) => {
1961
+ try {
1962
+ const ssh = await getConnection(server);
1963
+ const servers = loadServerConfig();
1964
+ const resolvedName = resolveServerName(server, servers);
1965
+ const serverConfig = servers[resolvedName];
1966
+
1967
+ // Build the full command
1968
+ let fullCommand = command;
1969
+
1970
+ // Add sudo if not already present
1971
+ if (!fullCommand.startsWith('sudo ')) {
1972
+ fullCommand = `sudo ${fullCommand}`;
1973
+ }
1974
+
1975
+ // Add password if provided
1976
+ if (password) {
1977
+ fullCommand = `echo "${password}" | sudo -S ${command.replace(/^sudo /, '')}`;
1978
+ } else if (serverConfig?.sudo_password) {
1979
+ // Use configured sudo password if available
1980
+ fullCommand = `echo "${serverConfig.sudo_password}" | sudo -S ${command.replace(/^sudo /, '')}`;
1981
+ }
1982
+
1983
+ // Add working directory if specified
1984
+ if (cwd) {
1985
+ fullCommand = `cd ${cwd} && ${fullCommand}`;
1986
+ } else if (serverConfig?.default_dir) {
1987
+ fullCommand = `cd ${serverConfig.default_dir} && ${fullCommand}`;
1988
+ }
1989
+
1990
+ const result = await execCommandWithTimeout(ssh, fullCommand, {}, timeout);
1991
+
1992
+ // Mask password in output for security
1993
+ const maskedCommand = fullCommand.replace(/echo "[^"]+" \| sudo -S/, 'sudo');
1994
+
1995
+ return {
1996
+ content: [
1997
+ {
1998
+ type: 'text',
1999
+ text: `šŸ” Sudo command executed\nServer: ${server}\nCommand: ${maskedCommand}\nExit code: ${result.code}\n\nOutput:\n${result.stdout || result.stderr}`,
2000
+ },
2001
+ ],
2002
+ };
2003
+ } catch (error) {
2004
+ return {
2005
+ content: [
2006
+ {
2007
+ type: 'text',
2008
+ text: `āŒ Sudo execution failed: ${error.message}`,
2009
+ },
2010
+ ],
2011
+ };
2012
+ }
2013
+ }
2014
+ );
2015
+
2016
+ // Manage command aliases
2017
+ server.registerTool(
2018
+ 'ssh_command_alias',
2019
+ {
2020
+ description: 'Manage command aliases for frequently used commands',
2021
+ inputSchema: {
2022
+ action: z.enum(['add', 'remove', 'list', 'suggest']).describe('Action to perform'),
2023
+ alias: z.string().optional().describe('Alias name (for add/remove)'),
2024
+ command: z.string().optional().describe('Command to alias (for add) or search term (for suggest)')
2025
+ }
2026
+ },
2027
+ async ({ action, alias, command }) => {
2028
+ try {
2029
+ switch (action) {
2030
+ case 'add': {
2031
+ if (!alias || !command) {
2032
+ throw new Error('Both alias and command are required for add action');
2033
+ }
2034
+
2035
+ addCommandAlias(alias, command);
2036
+ return {
2037
+ content: [
2038
+ {
2039
+ type: 'text',
2040
+ text: `āœ… Command alias created: ${alias} -> ${command}`,
2041
+ },
2042
+ ],
2043
+ };
2044
+ }
2045
+
2046
+ case 'remove': {
2047
+ if (!alias) {
2048
+ throw new Error('Alias is required for remove action');
2049
+ }
2050
+
2051
+ removeCommandAlias(alias);
2052
+ return {
2053
+ content: [
2054
+ {
2055
+ type: 'text',
2056
+ text: `āœ… Command alias removed: ${alias}`,
2057
+ },
2058
+ ],
2059
+ };
2060
+ }
2061
+
2062
+ case 'list': {
2063
+ const aliases = listCommandAliases();
2064
+
2065
+ const aliasInfo = aliases.map(({ alias, command, isFromProfile, isCustom }) =>
2066
+ ` ${alias} -> ${command}${isFromProfile ? ' (profile)' : ''}${isCustom ? ' (custom)' : ''}`
2067
+ ).join('\n');
2068
+
2069
+ return {
2070
+ content: [
2071
+ {
2072
+ type: 'text',
2073
+ text: aliases.length > 0 ?
2074
+ `šŸ“ Command aliases:\n${aliasInfo}` :
2075
+ 'šŸ“ No command aliases configured',
2076
+ },
2077
+ ],
2078
+ };
2079
+ }
2080
+
2081
+ case 'suggest': {
2082
+ if (!command) {
2083
+ throw new Error('Command search term is required for suggest action');
2084
+ }
2085
+
2086
+ const suggestions = suggestAliases(command);
2087
+
2088
+ const suggestionInfo = suggestions.map(({ alias, command }) =>
2089
+ ` ${alias} -> ${command}`
2090
+ ).join('\n');
2091
+
2092
+ return {
2093
+ content: [
2094
+ {
2095
+ type: 'text',
2096
+ text: suggestions.length > 0 ?
2097
+ `šŸ’” Suggested aliases for "${command}":\n${suggestionInfo}` :
2098
+ `šŸ’” No aliases found matching "${command}"`,
2099
+ },
2100
+ ],
2101
+ };
2102
+ }
2103
+ }
2104
+ } catch (error) {
2105
+ return {
2106
+ content: [
2107
+ {
2108
+ type: 'text',
2109
+ text: `āŒ Command alias operation failed: ${error.message}`,
2110
+ },
2111
+ ],
2112
+ };
2113
+ }
2114
+ }
2115
+ );
2116
+
2117
+ // Manage hooks
2118
+ server.registerTool(
2119
+ 'ssh_hooks',
2120
+ {
2121
+ description: 'Manage automation hooks for SSH operations',
2122
+ inputSchema: {
2123
+ action: z.enum(['list', 'enable', 'disable', 'status']).describe('Action to perform'),
2124
+ hook: z.string().optional().describe('Hook name (for enable/disable)')
2125
+ }
2126
+ },
2127
+ async ({ action, hook }) => {
2128
+ try {
2129
+ switch (action) {
2130
+ case 'list': {
2131
+ const hooks = listHooks();
2132
+
2133
+ const hooksInfo = hooks.map(({ name, enabled, description, actionCount }) =>
2134
+ ` ${enabled ? 'āœ…' : 'ā­•'} ${name}: ${description} (${actionCount} actions)`
2135
+ ).join('\n');
2136
+
2137
+ return {
2138
+ content: [
2139
+ {
2140
+ type: 'text',
2141
+ text: hooks.length > 0 ?
2142
+ `šŸŽ£ Available hooks:\n${hooksInfo}` :
2143
+ 'šŸŽ£ No hooks configured',
2144
+ },
2145
+ ],
2146
+ };
2147
+ }
2148
+
2149
+ case 'enable': {
2150
+ if (!hook) {
2151
+ throw new Error('Hook name is required for enable action');
2152
+ }
2153
+
2154
+ toggleHook(hook, true);
2155
+ return {
2156
+ content: [
2157
+ {
2158
+ type: 'text',
2159
+ text: `āœ… Hook enabled: ${hook}`,
2160
+ },
2161
+ ],
2162
+ };
2163
+ }
2164
+
2165
+ case 'disable': {
2166
+ if (!hook) {
2167
+ throw new Error('Hook name is required for disable action');
2168
+ }
2169
+
2170
+ toggleHook(hook, false);
2171
+ return {
2172
+ content: [
2173
+ {
2174
+ type: 'text',
2175
+ text: `ā­• Hook disabled: ${hook}`,
2176
+ },
2177
+ ],
2178
+ };
2179
+ }
2180
+
2181
+ case 'status': {
2182
+ const hooks = listHooks();
2183
+ const enabledHooks = hooks.filter(h => h.enabled);
2184
+ const disabledHooks = hooks.filter(h => !h.enabled);
2185
+
2186
+ return {
2187
+ content: [
2188
+ {
2189
+ type: 'text',
2190
+ text: `šŸŽ£ Hook status:\n Enabled: ${enabledHooks.map(h => h.name).join(', ') || 'none'}\n Disabled: ${disabledHooks.map(h => h.name).join(', ') || 'none'}`,
2191
+ },
2192
+ ],
2193
+ };
2194
+ }
2195
+ }
2196
+ } catch (error) {
2197
+ return {
2198
+ content: [
2199
+ {
2200
+ type: 'text',
2201
+ text: `āŒ Hook operation failed: ${error.message}`,
2202
+ },
2203
+ ],
2204
+ };
2205
+ }
2206
+ }
2207
+ );
2208
+
2209
+ // Manage profiles
2210
+ server.registerTool(
2211
+ 'ssh_profile',
2212
+ {
2213
+ description: 'Manage SSH Manager profiles for different project types',
2214
+ inputSchema: {
2215
+ action: z.enum(['list', 'switch', 'current']).describe('Action to perform'),
2216
+ profile: z.string().optional().describe('Profile name (for switch)')
2217
+ }
2218
+ },
2219
+ async ({ action, profile }) => {
2220
+ try {
2221
+ switch (action) {
2222
+ case 'list': {
2223
+ const profiles = listProfiles();
2224
+
2225
+ const profileInfo = profiles.map(p =>
2226
+ ` ${p.name}: ${p.description} (${p.aliasCount} aliases, ${p.hookCount} hooks)`
2227
+ ).join('\n');
2228
+
2229
+ const current = getActiveProfileName();
2230
+
2231
+ return {
2232
+ content: [
2233
+ {
2234
+ type: 'text',
2235
+ text: profiles.length > 0 ?
2236
+ `šŸ“š Available profiles (current: ${current}):\n${profileInfo}` :
2237
+ 'šŸ“š No profiles found',
2238
+ },
2239
+ ],
2240
+ };
2241
+ }
2242
+
2243
+ case 'switch': {
2244
+ if (!profile) {
2245
+ throw new Error('Profile name is required for switch action');
2246
+ }
2247
+
2248
+ if (setActiveProfile(profile)) {
2249
+ return {
2250
+ content: [
2251
+ {
2252
+ type: 'text',
2253
+ text: `āœ… Switched to profile: ${profile}\nāš ļø Restart Claude Code to apply profile changes`,
2254
+ },
2255
+ ],
2256
+ };
2257
+ } else {
2258
+ throw new Error(`Failed to switch to profile: ${profile}`);
2259
+ }
2260
+ }
2261
+
2262
+ case 'current': {
2263
+ const current = getActiveProfileName();
2264
+ const profile = loadProfile();
2265
+
2266
+ return {
2267
+ content: [
2268
+ {
2269
+ type: 'text',
2270
+ text: `šŸ“¦ Current profile: ${current}\nšŸ“ Description: ${profile.description || 'No description'}\nšŸ”§ Aliases: ${Object.keys(profile.commandAliases || {}).length}\nšŸŽ£ Hooks: ${Object.keys(profile.hooks || {}).length}`,
2271
+ },
2272
+ ],
2273
+ };
2274
+ }
2275
+ }
2276
+ } catch (error) {
2277
+ return {
2278
+ content: [
2279
+ {
2280
+ type: 'text',
2281
+ text: `āŒ Profile operation failed: ${error.message}`,
2282
+ },
2283
+ ],
2284
+ };
2285
+ }
2286
+ }
2287
+ );
2288
+
2289
+ // Connection management tool
2290
+ server.registerTool(
2291
+ 'ssh_connection_status',
2292
+ {
2293
+ description: 'Check status of SSH connections and manage connection pool',
2294
+ inputSchema: {
2295
+ action: z.enum(['status', 'reconnect', 'disconnect', 'cleanup']).describe('Action to perform'),
2296
+ server: z.string().optional().describe('Server name (for reconnect/disconnect)')
2297
+ }
2298
+ },
2299
+ async ({ action, server }) => {
2300
+ try {
2301
+ switch (action) {
2302
+ case 'status': {
2303
+ const activeConnections = [];
2304
+ const now = Date.now();
2305
+
2306
+ for (const [serverName, ssh] of connections.entries()) {
2307
+ const timestamp = connectionTimestamps.get(serverName);
2308
+ const ageMinutes = Math.floor((now - timestamp) / 1000 / 60);
2309
+ const isValid = await isConnectionValid(ssh);
2310
+
2311
+ activeConnections.push({
2312
+ server: serverName,
2313
+ status: isValid ? 'āœ… Active' : 'āŒ Dead',
2314
+ age: `${ageMinutes} minutes`,
2315
+ keepalive: keepaliveIntervals.has(serverName) ? 'āœ…' : 'āŒ'
2316
+ });
2317
+ }
2318
+
2319
+ const statusInfo = activeConnections.length > 0 ?
2320
+ activeConnections.map(c => ` ${c.server}: ${c.status} (age: ${c.age}, keepalive: ${c.keepalive})`).join('\n') :
2321
+ ' No active connections';
2322
+
2323
+ return {
2324
+ content: [
2325
+ {
2326
+ type: 'text',
2327
+ text: `šŸ”Œ Connection Pool Status:\n${statusInfo}\n\nSettings:\n Timeout: ${CONNECTION_TIMEOUT / 1000 / 60} minutes\n Keepalive: Every ${KEEPALIVE_INTERVAL / 1000 / 60} minutes`,
2328
+ },
2329
+ ],
2330
+ };
2331
+ }
2332
+
2333
+ case 'reconnect': {
2334
+ if (!server) {
2335
+ throw new Error('Server name is required for reconnect action');
2336
+ }
2337
+
2338
+ const normalizedName = server.toLowerCase();
2339
+ if (connections.has(normalizedName)) {
2340
+ closeConnection(normalizedName);
2341
+ }
2342
+
2343
+ await getConnection(server);
2344
+ return {
2345
+ content: [
2346
+ {
2347
+ type: 'text',
2348
+ text: `ā™»ļø Reconnected to ${server}`,
2349
+ },
2350
+ ],
2351
+ };
2352
+ }
2353
+
2354
+ case 'disconnect': {
2355
+ if (!server) {
2356
+ throw new Error('Server name is required for disconnect action');
2357
+ }
2358
+
2359
+ closeConnection(server);
2360
+ return {
2361
+ content: [
2362
+ {
2363
+ type: 'text',
2364
+ text: `šŸ”Œ Disconnected from ${server}`,
2365
+ },
2366
+ ],
2367
+ };
2368
+ }
2369
+
2370
+ case 'cleanup': {
2371
+ const oldCount = connections.size;
2372
+ cleanupOldConnections();
2373
+
2374
+ // Also check and remove dead connections
2375
+ for (const [serverName, ssh] of connections.entries()) {
2376
+ const isValid = await isConnectionValid(ssh);
2377
+ if (!isValid) {
2378
+ closeConnection(serverName);
2379
+ }
2380
+ }
2381
+
2382
+ const cleaned = oldCount - connections.size;
2383
+ return {
2384
+ content: [
2385
+ {
2386
+ type: 'text',
2387
+ text: `🧹 Cleanup complete: ${cleaned} connections closed, ${connections.size} active`,
2388
+ },
2389
+ ],
2390
+ };
2391
+ }
2392
+ }
2393
+ } catch (error) {
2394
+ return {
2395
+ content: [
2396
+ {
2397
+ type: 'text',
2398
+ text: `āŒ Connection management failed: ${error.message}`,
2399
+ },
2400
+ ],
2401
+ };
2402
+ }
2403
+ }
2404
+ );
2405
+
2406
+ // SSH Tunnel Management - Create tunnel
2407
+ server.registerTool(
2408
+ 'ssh_tunnel_create',
2409
+ {
2410
+ description: 'Create SSH tunnel (port forwarding or SOCKS proxy)',
2411
+ inputSchema: {
2412
+ server: z.string().describe('Server name or alias'),
2413
+ type: z.enum(['local', 'remote', 'dynamic']).describe('Tunnel type'),
2414
+ localHost: z.string().optional().describe('Local host (default: 127.0.0.1)'),
2415
+ localPort: z.number().describe('Local port'),
2416
+ remoteHost: z.string().optional().describe('Remote host (not needed for dynamic)'),
2417
+ remotePort: z.number().optional().describe('Remote port (not needed for dynamic)')
2418
+ }
2419
+ },
2420
+ async ({ server, type, localHost, localPort, remoteHost, remotePort }) => {
2421
+ try {
2422
+ const servers = loadServerConfig();
2423
+ const resolvedName = resolveServerName(server, servers);
2424
+
2425
+ if (!resolvedName) {
2426
+ throw new Error(`Server "${server}" not found`);
2427
+ }
2428
+
2429
+ const ssh = await getSSHConnection(resolvedName);
2430
+
2431
+ const config = {
2432
+ type,
2433
+ localHost: localHost || '127.0.0.1',
2434
+ localPort,
2435
+ remoteHost,
2436
+ remotePort
2437
+ };
2438
+
2439
+ const tunnel = await createTunnel(resolvedName, ssh, config);
2440
+
2441
+ let output = `āœ… SSH tunnel created\n`;
2442
+ output += `ID: ${tunnel.id}\n`;
2443
+ output += `Type: ${type}\n`;
2444
+ output += `Local: ${config.localHost}:${localPort}\n`;
2445
+
2446
+ if (type === 'local') {
2447
+ output += `Remote: ${remoteHost}:${remotePort}\n`;
2448
+ output += `\nšŸ“Œ Access remote ${remoteHost}:${remotePort} via local ${config.localHost}:${localPort}`;
2449
+ } else if (type === 'remote') {
2450
+ output += `Remote: ${remoteHost}:${remotePort}\n`;
2451
+ output += `\nšŸ“Œ Remote ${remoteHost}:${remotePort} will forward to local ${config.localHost}:${localPort}`;
2452
+ } else if (type === 'dynamic') {
2453
+ output += `SOCKS proxy: ${config.localHost}:${localPort}\n`;
2454
+ output += `\nšŸ“Œ SOCKS5 proxy available at ${config.localHost}:${localPort}`;
2455
+ output += `\nšŸ’” Configure browser/app: SOCKS5 proxy ${config.localHost}:${localPort}`;
2456
+ }
2457
+
2458
+ logger.info('SSH tunnel created', {
2459
+ id: tunnel.id,
2460
+ server: resolvedName,
2461
+ type,
2462
+ local: `${config.localHost}:${localPort}`
2463
+ });
2464
+
2465
+ return {
2466
+ content: [
2467
+ {
2468
+ type: 'text',
2469
+ text: output
2470
+ }
2471
+ ]
2472
+ };
2473
+ } catch (error) {
2474
+ logger.error('Failed to create tunnel', { error: error.message });
2475
+ return {
2476
+ content: [
2477
+ {
2478
+ type: 'text',
2479
+ text: `āŒ Tunnel creation failed: ${error.message}`
2480
+ }
2481
+ ]
2482
+ };
2483
+ }
2484
+ }
2485
+ );
2486
+
2487
+ // List active tunnels
2488
+ server.registerTool(
2489
+ 'ssh_tunnel_list',
2490
+ {
2491
+ description: 'List active SSH tunnels',
2492
+ inputSchema: {
2493
+ server: z.string().optional().describe('Filter by server name')
2494
+ }
2495
+ },
2496
+ async ({ server }) => {
2497
+ try {
2498
+ const servers = loadServerConfig();
2499
+ let resolvedName = null;
2500
+
2501
+ if (server) {
2502
+ resolvedName = resolveServerName(server, servers);
2503
+ if (!resolvedName) {
2504
+ throw new Error(`Server "${server}" not found`);
2505
+ }
2506
+ }
2507
+
2508
+ const tunnels = listTunnels(resolvedName);
2509
+
2510
+ if (tunnels.length === 0) {
2511
+ return {
2512
+ content: [
2513
+ {
2514
+ type: 'text',
2515
+ text: 'šŸ“‹ No active tunnels'
2516
+ }
2517
+ ]
2518
+ };
2519
+ }
2520
+
2521
+ let output = `šŸ“‹ Active SSH Tunnels\n`;
2522
+ output += '━'.repeat(60) + '\n\n';
2523
+
2524
+ tunnels.forEach(tunnel => {
2525
+ output += `šŸ”§ ${tunnel.id}\n`;
2526
+ output += ` Server: ${tunnel.server}\n`;
2527
+ output += ` Type: ${tunnel.type}\n`;
2528
+ output += ` State: ${tunnel.state}\n`;
2529
+ output += ` Local: ${tunnel.config.localHost}:${tunnel.config.localPort}\n`;
2530
+
2531
+ if (tunnel.type !== 'dynamic') {
2532
+ output += ` Remote: ${tunnel.config.remoteHost}:${tunnel.config.remotePort}\n`;
2533
+ }
2534
+
2535
+ output += ` Active connections: ${tunnel.activeConnections}\n`;
2536
+ output += ` Total connections: ${tunnel.stats.connectionsTotal}\n`;
2537
+ output += ` Bytes transferred: ${(tunnel.stats.bytesTransferred / 1024).toFixed(2)} KB\n`;
2538
+ output += ` Errors: ${tunnel.stats.errors}\n`;
2539
+ output += ` Created: ${new Date(tunnel.created).toLocaleString()}\n`;
2540
+ output += ` Last activity: ${new Date(tunnel.lastActivity).toLocaleString()}\n`;
2541
+ output += '\n';
2542
+ });
2543
+
2544
+ output += '━'.repeat(60) + '\n';
2545
+ output += `Total tunnels: ${tunnels.length}`;
2546
+
2547
+ return {
2548
+ content: [
2549
+ {
2550
+ type: 'text',
2551
+ text: output
2552
+ }
2553
+ ]
2554
+ };
2555
+ } catch (error) {
2556
+ logger.error('Failed to list tunnels', { error: error.message });
2557
+ return {
2558
+ content: [
2559
+ {
2560
+ type: 'text',
2561
+ text: `āŒ Failed to list tunnels: ${error.message}`
2562
+ }
2563
+ ]
2564
+ };
2565
+ }
2566
+ }
2567
+ );
2568
+
2569
+ // Close a tunnel
2570
+ server.registerTool(
2571
+ 'ssh_tunnel_close',
2572
+ {
2573
+ description: 'Close an SSH tunnel',
2574
+ inputSchema: {
2575
+ tunnelId: z.string().optional().describe('Tunnel ID to close'),
2576
+ server: z.string().optional().describe('Close all tunnels for this server')
2577
+ }
2578
+ },
2579
+ async ({ tunnelId, server }) => {
2580
+ try {
2581
+ if (!tunnelId && !server) {
2582
+ throw new Error('Either tunnelId or server must be specified');
2583
+ }
2584
+
2585
+ let output = '';
2586
+
2587
+ if (tunnelId) {
2588
+ // Close specific tunnel
2589
+ closeTunnel(tunnelId);
2590
+ output = `āœ… Tunnel ${tunnelId} closed`;
2591
+
2592
+ logger.info('SSH tunnel closed', { id: tunnelId });
2593
+ } else if (server) {
2594
+ // Close all tunnels for server
2595
+ const servers = loadServerConfig();
2596
+ const resolvedName = resolveServerName(server, servers);
2597
+
2598
+ if (!resolvedName) {
2599
+ throw new Error(`Server "${server}" not found`);
2600
+ }
2601
+
2602
+ const count = closeServerTunnels(resolvedName);
2603
+ output = `āœ… Closed ${count} tunnel(s) for server ${resolvedName}`;
2604
+
2605
+ logger.info('Server tunnels closed', {
2606
+ server: resolvedName,
2607
+ count
2608
+ });
2609
+ }
2610
+
2611
+ return {
2612
+ content: [
2613
+ {
2614
+ type: 'text',
2615
+ text: output
2616
+ }
2617
+ ]
2618
+ };
2619
+ } catch (error) {
2620
+ logger.error('Failed to close tunnel', { error: error.message });
2621
+ return {
2622
+ content: [
2623
+ {
2624
+ type: 'text',
2625
+ text: `āŒ Failed to close tunnel: ${error.message}`
2626
+ }
2627
+ ]
2628
+ };
2629
+ }
2630
+ }
2631
+ );
2632
+
2633
+ // Manage SSH host keys
2634
+ server.registerTool(
2635
+ 'ssh_key_manage',
2636
+ {
2637
+ description: 'Manage SSH host keys for security verification',
2638
+ inputSchema: {
2639
+ action: z.enum(['verify', 'accept', 'remove', 'list', 'check']).describe('Action to perform'),
2640
+ server: z.string().optional().describe('Server name (required for most actions)'),
2641
+ autoAccept: z.boolean().optional().describe('Automatically accept new keys (use with caution)')
2642
+ }
2643
+ },
2644
+ async ({ action, server, autoAccept = false }) => {
2645
+ try {
2646
+ const servers = loadServerConfig();
2647
+ let resolvedName, serverConfig, host, port;
2648
+
2649
+ // Resolve server details for actions that need them
2650
+ if (server && action !== 'list') {
2651
+ resolvedName = resolveServerName(server, servers);
2652
+ if (!resolvedName) {
2653
+ throw new Error(`Server "${server}" not found`);
2654
+ }
2655
+ serverConfig = servers[resolvedName];
2656
+ host = serverConfig.host;
2657
+ port = parseInt(serverConfig.port || '22');
2658
+ }
2659
+
2660
+ 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
+ });
2674
+
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`;
2698
+
2699
+ if (verification.reason === 'not_in_known_hosts') {
2700
+ output += `\nā„¹ļø Host not in known_hosts. Use 'accept' action to add it.`;
2701
+ }
2702
+
2703
+ return {
2704
+ content: [
2705
+ {
2706
+ type: 'text',
2707
+ text: output
2708
+ }
2709
+ ]
2710
+ };
2711
+ }
2712
+ }
2713
+
2714
+ case 'accept': {
2715
+ // Check if key exists
2716
+ const isKnown = isHostKnown(host, port);
2717
+
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
+ });
2751
+
2752
+ logger.info('SSH host key added', { server: resolvedName, host, port });
2753
+
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
+ }
2764
+
2765
+ case 'remove': {
2766
+ removeHostKey(host, port);
2767
+
2768
+ logger.info('SSH host key removed', { server: resolvedName, host, port });
2769
+
2770
+ return {
2771
+ content: [
2772
+ {
2773
+ type: 'text',
2774
+ text: `āœ… SSH host key removed for ${server} (${host}:${port})`
2775
+ }
2776
+ ]
2777
+ };
2778
+ }
2779
+
2780
+ case 'check': {
2781
+ // Get current fingerprints
2782
+ const currentKeys = getCurrentHostKey(host, port);
2783
+ const newKeys = await getHostKeyFingerprint(host, port);
2784
+
2785
+ let output = `šŸ”‘ SSH Host Keys for ${server} (${host}:${port})\n`;
2786
+ output += '━'.repeat(60) + '\n\n';
2787
+
2788
+ if (currentKeys && currentKeys.length > 0) {
2789
+ output += `šŸ“‹ Keys in known_hosts:\n`;
2790
+ currentKeys.forEach(key => {
2791
+ output += ` ${key.type}: ${key.fingerprint}\n`;
2792
+ });
2793
+ } else {
2794
+ output += `āš ļø No keys found in known_hosts\n`;
2795
+ }
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
+ }
2805
+
2806
+ return {
2807
+ content: [
2808
+ {
2809
+ type: 'text',
2810
+ text: output
2811
+ }
2812
+ ]
2813
+ };
2814
+ }
2815
+
2816
+ case 'list': {
2817
+ const knownHosts = listKnownHosts();
2818
+
2819
+ let output = `šŸ”‘ Known SSH Hosts\n`;
2820
+ output += '━'.repeat(60) + '\n\n';
2821
+
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);
2830
+ }
2831
+
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';
2839
+
2840
+ entry.keys.forEach(key => {
2841
+ output += ` ${key.type}: ${key.fingerprint}\n`;
2842
+ });
2843
+ output += '\n';
2844
+ });
2845
+ }
2846
+
2847
+ output += '━'.repeat(60) + '\n';
2848
+ output += `Total: ${knownHosts.length} hosts`;
2849
+
2850
+ return {
2851
+ content: [
2852
+ {
2853
+ type: 'text',
2854
+ text: output
2855
+ }
2856
+ ]
2857
+ };
2858
+ }
2859
+
2860
+ default:
2861
+ throw new Error(`Unknown action: ${action}`);
2862
+ }
2863
+ } catch (error) {
2864
+ logger.error('SSH key management failed', { action, server, error: error.message });
2865
+
2866
+ return {
2867
+ content: [
2868
+ {
2869
+ type: 'text',
2870
+ text: `āŒ SSH key management error: ${error.message}`
2871
+ }
2872
+ ]
2873
+ };
2874
+ }
2875
+ }
2876
+ );
2877
+
2878
+ // Manage server aliases
2879
+ server.registerTool(
2880
+ 'ssh_alias',
2881
+ {
2882
+ description: 'Manage server aliases for easier access',
2883
+ inputSchema: {
2884
+ action: z.enum(['add', 'remove', 'list']).describe('Action to perform'),
2885
+ alias: z.string().optional().describe('Alias name (for add/remove)'),
2886
+ server: z.string().optional().describe('Server name (for add)')
2887
+ }
2888
+ },
2889
+ async ({ action, alias, server }) => {
2890
+ try {
2891
+ switch (action) {
2892
+ case 'add': {
2893
+ if (!alias || !server) {
2894
+ throw new Error('Both alias and server are required for add action');
2895
+ }
2896
+
2897
+ const servers = loadServerConfig();
2898
+ const resolvedName = resolveServerName(server, servers);
2899
+
2900
+ if (!resolvedName) {
2901
+ throw new Error(`Server "${server}" not found`);
2902
+ }
2903
+
2904
+ addAlias(alias, resolvedName);
2905
+ return {
2906
+ content: [
2907
+ {
2908
+ type: 'text',
2909
+ text: `āœ… Alias created: ${alias} -> ${resolvedName}`,
2910
+ },
2911
+ ],
2912
+ };
2913
+ }
2914
+
2915
+ case 'remove': {
2916
+ if (!alias) {
2917
+ throw new Error('Alias is required for remove action');
2918
+ }
2919
+
2920
+ removeAlias(alias);
2921
+ return {
2922
+ content: [
2923
+ {
2924
+ type: 'text',
2925
+ text: `āœ… Alias removed: ${alias}`,
2926
+ },
2927
+ ],
2928
+ };
2929
+ }
2930
+
2931
+ case 'list': {
2932
+ const aliases = listAliases();
2933
+ const servers = loadServerConfig();
2934
+
2935
+ const aliasInfo = aliases.map(({ alias, target }) => {
2936
+ const server = servers[target];
2937
+ return ` ${alias} -> ${target} (${server?.host || 'unknown'})`;
2938
+ }).join('\n');
2939
+
2940
+ return {
2941
+ content: [
2942
+ {
2943
+ type: 'text',
2944
+ text: aliases.length > 0 ?
2945
+ `šŸ“ Server aliases:\n${aliasInfo}` :
2946
+ 'šŸ“ No aliases configured',
2947
+ },
2948
+ ],
2949
+ };
2950
+ }
2951
+ }
2952
+ } catch (error) {
2953
+ return {
2954
+ content: [
2955
+ {
2956
+ type: 'text',
2957
+ text: `āŒ Alias operation failed: ${error.message}`,
2958
+ },
2959
+ ],
2960
+ };
2961
+ }
2962
+ }
2963
+ );
2964
+
2965
+ // ============================================================================
2966
+ // BACKUP & RESTORE TOOLS
2967
+ // ============================================================================
2968
+
2969
+ server.registerTool(
2970
+ 'ssh_backup_create',
2971
+ {
2972
+ description: 'Create backup of database or files on remote server',
2973
+ inputSchema: {
2974
+ server: z.string().describe('Server name'),
2975
+ type: z.enum(['mysql', 'postgresql', 'mongodb', 'files', 'full'])
2976
+ .describe('Backup type: mysql, postgresql, mongodb, files, or full'),
2977
+ name: z.string().describe('Backup name (e.g., production, app-data)'),
2978
+ database: z.string().optional()
2979
+ .describe('Database name (required for db types)'),
2980
+ dbUser: z.string().optional()
2981
+ .describe('Database user'),
2982
+ dbPassword: z.string().optional()
2983
+ .describe('Database password'),
2984
+ dbHost: z.string().optional()
2985
+ .describe('Database host (default: localhost)'),
2986
+ dbPort: z.number().optional()
2987
+ .describe('Database port'),
2988
+ paths: z.array(z.string()).optional()
2989
+ .describe('Paths to backup (for files type)'),
2990
+ exclude: z.array(z.string()).optional()
2991
+ .describe('Patterns to exclude from backup'),
2992
+ backupDir: z.string().optional()
2993
+ .describe(`Backup directory (default: ${DEFAULT_BACKUP_DIR})`),
2994
+ retention: z.number().optional()
2995
+ .describe('Retention period in days (default: 7)'),
2996
+ compress: z.boolean().optional()
2997
+ .describe('Compress backup (default: true)')
2998
+ }
2999
+ },
3000
+ async ({ server: serverName, type, name, database, dbUser, dbPassword, dbHost, dbPort, paths, exclude, backupDir, retention = 7, compress = true }) => {
3001
+ try {
3002
+ const ssh = await getConnection(serverName);
3003
+
3004
+ // Execute pre-backup hook
3005
+ await executeHook('pre-backup', {
3006
+ server: serverName,
3007
+ type,
3008
+ database,
3009
+ paths
3010
+ });
3011
+
3012
+ const backupDirectory = backupDir || DEFAULT_BACKUP_DIR;
3013
+ const backupId = generateBackupId(type, name);
3014
+ const backupFile = getBackupFilePath(backupId, backupDirectory);
3015
+ const metadataPath = getBackupMetadataPath(backupId, backupDirectory);
3016
+
3017
+ // Ensure backup directory exists with proper error handling
3018
+ const mkdirResult = await ssh.execCommand(`mkdir -p "${backupDirectory}"`);
3019
+ if (mkdirResult.code !== 0) {
3020
+ throw new Error(`Failed to create backup directory: ${mkdirResult.stderr || mkdirResult.stdout}`);
3021
+ }
3022
+
3023
+ logger.info(`Creating backup: ${backupId}`, {
3024
+ server: serverName,
3025
+ type,
3026
+ name,
3027
+ database
3028
+ });
3029
+
3030
+ // Build backup command based on type
3031
+ let backupCommand;
3032
+
3033
+ 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;
3048
+
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;
3063
+
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;
3079
+
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;
3091
+
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.');
3095
+
3096
+ default:
3097
+ throw new Error(`Unknown backup type: ${type}`);
3098
+ }
3099
+
3100
+ // Execute backup command
3101
+ const result = await ssh.execCommand(backupCommand);
3102
+
3103
+ if (result.code !== 0) {
3104
+ throw new Error(`Backup failed: ${result.stderr || result.stdout}`);
3105
+ }
3106
+
3107
+ // Get backup file size
3108
+ const sizeResult = await ssh.execCommand(`stat -f%z "${backupFile}" 2>/dev/null || stat -c%s "${backupFile}" 2>/dev/null`);
3109
+ const size = parseInt(sizeResult.stdout.trim()) || 0;
3110
+
3111
+ // Create and save metadata
3112
+ const metadata = createBackupMetadata(backupId, type, {
3113
+ server: serverName,
3114
+ database,
3115
+ paths,
3116
+ compress,
3117
+ retention
3118
+ });
3119
+ metadata.size = size;
3120
+ metadata.status = 'completed';
3121
+
3122
+ const saveMetadataCmd = buildSaveMetadataCommand(metadata, metadataPath);
3123
+ await ssh.execCommand(saveMetadataCmd);
3124
+
3125
+ // Cleanup old backups based on retention
3126
+ const cleanupCmd = buildCleanupCommand(backupDirectory, retention);
3127
+ await ssh.execCommand(cleanupCmd);
3128
+
3129
+ // Execute post-backup hook
3130
+ await executeHook('post-backup', {
3131
+ server: serverName,
3132
+ backupId,
3133
+ type,
3134
+ size,
3135
+ success: true
3136
+ });
3137
+
3138
+ logger.info(`Backup created successfully: ${backupId}`, {
3139
+ size,
3140
+ location: backupFile
3141
+ });
3142
+
3143
+ return {
3144
+ content: [
3145
+ {
3146
+ type: 'text',
3147
+ text: JSON.stringify({
3148
+ success: true,
3149
+ backup_id: backupId,
3150
+ type,
3151
+ size,
3152
+ size_human: `${(size / 1024 / 1024).toFixed(2)} MB`,
3153
+ location: backupFile,
3154
+ metadata_path: metadataPath,
3155
+ created_at: metadata.created_at,
3156
+ retention_days: retention
3157
+ }, null, 2)
3158
+ }
3159
+ ]
3160
+ };
3161
+
3162
+ } catch (error) {
3163
+ logger.error('Backup creation failed', {
3164
+ server: serverName,
3165
+ type,
3166
+ error: error.message
3167
+ });
3168
+
3169
+ await executeHook('post-backup', {
3170
+ server: serverName,
3171
+ type,
3172
+ success: false,
3173
+ error: error.message
3174
+ });
3175
+
3176
+ return {
3177
+ content: [
3178
+ {
3179
+ type: 'text',
3180
+ text: `āŒ Backup failed: ${error.message}`
3181
+ }
3182
+ ]
3183
+ };
3184
+ }
3185
+ }
3186
+ );
3187
+
3188
+ server.registerTool(
3189
+ 'ssh_backup_list',
3190
+ {
3191
+ description: 'List available backups on remote server',
3192
+ inputSchema: {
3193
+ server: z.string().describe('Server name'),
3194
+ type: z.enum(['mysql', 'postgresql', 'mongodb', 'files', 'full']).optional()
3195
+ .describe('Filter by backup type'),
3196
+ backupDir: z.string().optional()
3197
+ .describe(`Backup directory (default: ${DEFAULT_BACKUP_DIR})`)
3198
+ }
3199
+ },
3200
+ async ({ server: serverName, type, backupDir }) => {
3201
+ try {
3202
+ const ssh = await getConnection(serverName);
3203
+ const backupDirectory = backupDir || DEFAULT_BACKUP_DIR;
3204
+
3205
+ logger.info(`Listing backups on ${serverName}`, { type, backupDir: backupDirectory });
3206
+
3207
+ // Build and execute list command
3208
+ const listCommand = buildListBackupsCommand(backupDirectory, type);
3209
+ const result = await ssh.execCommand(listCommand);
3210
+
3211
+ if (result.code !== 0 && result.stderr) {
3212
+ throw new Error(`Failed to list backups: ${result.stderr}`);
3213
+ }
3214
+
3215
+ // Parse backups list
3216
+ const backups = parseBackupsList(result.stdout);
3217
+
3218
+ return {
3219
+ content: [
3220
+ {
3221
+ type: 'text',
3222
+ text: JSON.stringify({
3223
+ success: true,
3224
+ count: backups.length,
3225
+ backups: backups.map(b => ({
3226
+ id: b.id,
3227
+ type: b.type,
3228
+ created_at: b.created_at,
3229
+ database: b.database,
3230
+ paths: b.paths,
3231
+ size: b.size,
3232
+ size_human: b.size ? `${(b.size / 1024 / 1024).toFixed(2)} MB` : 'unknown',
3233
+ compressed: b.compressed,
3234
+ retention_days: b.retention,
3235
+ status: b.status
3236
+ }))
3237
+ }, null, 2)
3238
+ }
3239
+ ]
3240
+ };
3241
+
3242
+ } catch (error) {
3243
+ logger.error('Failed to list backups', {
3244
+ server: serverName,
3245
+ error: error.message
3246
+ });
3247
+
3248
+ return {
3249
+ content: [
3250
+ {
3251
+ type: 'text',
3252
+ text: `āŒ Failed to list backups: ${error.message}`
3253
+ }
3254
+ ]
3255
+ };
3256
+ }
3257
+ }
3258
+ );
3259
+
3260
+ server.registerTool(
3261
+ 'ssh_backup_restore',
3262
+ {
3263
+ description: 'Restore from a backup on remote server',
3264
+ inputSchema: {
3265
+ server: z.string().describe('Server name'),
3266
+ backupId: z.string().describe('Backup ID to restore'),
3267
+ database: z.string().optional()
3268
+ .describe('Target database name (for db restores)'),
3269
+ dbUser: z.string().optional()
3270
+ .describe('Database user'),
3271
+ dbPassword: z.string().optional()
3272
+ .describe('Database password'),
3273
+ dbHost: z.string().optional()
3274
+ .describe('Database host (default: localhost)'),
3275
+ dbPort: z.number().optional()
3276
+ .describe('Database port'),
3277
+ targetPath: z.string().optional()
3278
+ .describe('Target path for files restore (default: /)'),
3279
+ backupDir: z.string().optional()
3280
+ .describe(`Backup directory (default: ${DEFAULT_BACKUP_DIR})`)
3281
+ }
3282
+ },
3283
+ async ({ server: serverName, backupId, database, dbUser, dbPassword, dbHost, dbPort, targetPath, backupDir }) => {
3284
+ try {
3285
+ const ssh = await getConnection(serverName);
3286
+ const backupDirectory = backupDir || DEFAULT_BACKUP_DIR;
3287
+ const metadataPath = getBackupMetadataPath(backupId, backupDirectory);
3288
+
3289
+ // Read backup metadata
3290
+ const metadataResult = await ssh.execCommand(`cat "${metadataPath}"`);
3291
+ if (metadataResult.code !== 0) {
3292
+ throw new Error(`Backup not found: ${backupId}`);
3293
+ }
3294
+
3295
+ const metadata = JSON.parse(metadataResult.stdout);
3296
+ const backupFile = getBackupFilePath(backupId, backupDirectory);
3297
+
3298
+ // Execute pre-restore hook
3299
+ await executeHook('pre-restore', {
3300
+ server: serverName,
3301
+ backupId,
3302
+ type: metadata.type,
3303
+ database
3304
+ });
3305
+
3306
+ logger.info(`Restoring backup: ${backupId}`, {
3307
+ server: serverName,
3308
+ type: metadata.type
3309
+ });
3310
+
3311
+ // Build restore command
3312
+ const restoreCommand = buildRestoreCommand(metadata.type, backupFile, {
3313
+ database: database || metadata.database,
3314
+ user: dbUser,
3315
+ password: dbPassword,
3316
+ host: dbHost,
3317
+ port: dbPort,
3318
+ targetPath
3319
+ });
3320
+
3321
+ // Execute restore
3322
+ const result = await ssh.execCommand(restoreCommand);
3323
+
3324
+ if (result.code !== 0) {
3325
+ throw new Error(`Restore failed: ${result.stderr || result.stdout}`);
3326
+ }
3327
+
3328
+ // Execute post-restore hook
3329
+ await executeHook('post-restore', {
3330
+ server: serverName,
3331
+ backupId,
3332
+ type: metadata.type,
3333
+ success: true
3334
+ });
3335
+
3336
+ logger.info(`Backup restored successfully: ${backupId}`);
3337
+
3338
+ return {
3339
+ content: [
3340
+ {
3341
+ type: 'text',
3342
+ text: JSON.stringify({
3343
+ success: true,
3344
+ backup_id: backupId,
3345
+ type: metadata.type,
3346
+ restored_at: new Date().toISOString(),
3347
+ original_created: metadata.created_at,
3348
+ database: database || metadata.database,
3349
+ paths: metadata.paths
3350
+ }, null, 2)
3351
+ }
3352
+ ]
3353
+ };
3354
+
3355
+ } catch (error) {
3356
+ logger.error('Restore failed', {
3357
+ server: serverName,
3358
+ backupId,
3359
+ error: error.message
3360
+ });
3361
+
3362
+ await executeHook('post-restore', {
3363
+ server: serverName,
3364
+ backupId,
3365
+ success: false,
3366
+ error: error.message
3367
+ });
3368
+
3369
+ return {
3370
+ content: [
3371
+ {
3372
+ type: 'text',
3373
+ text: `āŒ Restore failed: ${error.message}`
3374
+ }
3375
+ ]
3376
+ };
3377
+ }
3378
+ }
3379
+ );
3380
+
3381
+ server.registerTool(
3382
+ 'ssh_backup_schedule',
3383
+ {
3384
+ description: 'Schedule automatic backups using cron',
3385
+ inputSchema: {
3386
+ server: z.string().describe('Server name'),
3387
+ schedule: z.string().describe('Cron schedule (e.g., "0 2 * * *" for daily at 2 AM)'),
3388
+ type: z.enum(['mysql', 'postgresql', 'mongodb', 'files'])
3389
+ .describe('Backup type'),
3390
+ name: z.string().describe('Backup name'),
3391
+ database: z.string().optional()
3392
+ .describe('Database name (for db types)'),
3393
+ paths: z.array(z.string()).optional()
3394
+ .describe('Paths to backup (for files type)'),
3395
+ retention: z.number().optional()
3396
+ .describe('Retention period in days (default: 7)')
3397
+ }
3398
+ },
3399
+ async ({ server: serverName, schedule, type, name, database, paths, retention = 7 }) => {
3400
+ try {
3401
+ const ssh = await getConnection(serverName);
3402
+
3403
+ // Build backup script path
3404
+ const scriptPath = `/usr/local/bin/ssh-manager-backup-${name}.sh`;
3405
+ const backupDirectory = DEFAULT_BACKUP_DIR;
3406
+
3407
+ // Create backup script
3408
+ let scriptContent = '#!/bin/bash\n\n';
3409
+ scriptContent += `# SSH Manager automated backup: ${name}\n`;
3410
+ scriptContent += `# Type: ${type}\n`;
3411
+ scriptContent += `# Created: ${new Date().toISOString()}\n\n`;
3412
+
3413
+ const backupId = `\${BACKUP_TYPE}_${name}_$(date +%Y%m%d_%H%M%S)_\${RANDOM}`;
3414
+ const backupFile = `${backupDirectory}/${backupId}.gz`;
3415
+
3416
+ scriptContent += `BACKUP_DIR="${backupDirectory}"\n`;
3417
+ scriptContent += `BACKUP_TYPE="${type}"\n`;
3418
+ scriptContent += `BACKUP_ID="${backupId}"\n`;
3419
+ scriptContent += `BACKUP_FILE="${backupFile}"\n\n`;
3420
+ scriptContent += `mkdir -p "$BACKUP_DIR"\n\n`;
3421
+
3422
+ // Add backup command based on type
3423
+ 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;
3436
+ }
3437
+
3438
+ // Add cleanup command
3439
+ scriptContent += `\n# Cleanup old backups\n`;
3440
+ scriptContent += `find "$BACKUP_DIR" -name "*_${name}_*" -type f -mtime +${retention} -delete\n`;
3441
+
3442
+ // Save script to remote server
3443
+ const escapedScript = scriptContent.replace(/'/g, "'\\''");
3444
+ await ssh.execCommand(`echo '${escapedScript}' > "${scriptPath}" && chmod +x "${scriptPath}"`);
3445
+
3446
+ // Add to crontab
3447
+ const cronComment = `ssh-manager-backup-${name}`;
3448
+ const cronCommand = buildCronScheduleCommand(schedule, scriptPath, cronComment);
3449
+ const cronResult = await ssh.execCommand(cronCommand);
3450
+
3451
+ if (cronResult.code !== 0) {
3452
+ throw new Error(`Failed to schedule backup: ${cronResult.stderr}`);
3453
+ }
3454
+
3455
+ logger.info(`Backup scheduled: ${name}`, {
3456
+ server: serverName,
3457
+ schedule,
3458
+ type,
3459
+ retention
3460
+ });
3461
+
3462
+ return {
3463
+ content: [
3464
+ {
3465
+ type: 'text',
3466
+ text: JSON.stringify({
3467
+ success: true,
3468
+ name,
3469
+ schedule,
3470
+ type,
3471
+ database,
3472
+ paths,
3473
+ retention_days: retention,
3474
+ script_path: scriptPath,
3475
+ next_run: 'Use crontab -l to see next run time'
3476
+ }, null, 2)
3477
+ }
3478
+ ]
3479
+ };
3480
+
3481
+ } catch (error) {
3482
+ logger.error('Failed to schedule backup', {
3483
+ server: serverName,
3484
+ name,
3485
+ error: error.message
3486
+ });
3487
+
3488
+ return {
3489
+ content: [
3490
+ {
3491
+ type: 'text',
3492
+ text: `āŒ Failed to schedule backup: ${error.message}`
3493
+ }
3494
+ ]
3495
+ };
3496
+ }
3497
+ }
3498
+ );
3499
+
3500
+ // ============================================================================
3501
+ // HEALTH CHECKS & MONITORING TOOLS
3502
+ // ============================================================================
3503
+
3504
+ server.registerTool(
3505
+ 'ssh_health_check',
3506
+ {
3507
+ description: 'Perform comprehensive health check on remote server',
3508
+ inputSchema: {
3509
+ server: z.string().describe('Server name'),
3510
+ detailed: z.boolean().optional()
3511
+ .describe('Include detailed metrics (network, load average)')
3512
+ }
3513
+ },
3514
+ async ({ server: serverName, detailed = false }) => {
3515
+ try {
3516
+ const ssh = await getConnection(serverName);
3517
+
3518
+ logger.info(`Running health check on ${serverName}`, { detailed });
3519
+
3520
+ // Build and execute comprehensive health check
3521
+ const healthCommand = buildComprehensiveHealthCheckCommand();
3522
+ const result = await ssh.execCommand(healthCommand);
3523
+
3524
+ if (result.code !== 0) {
3525
+ throw new Error(`Health check failed: ${result.stderr}`);
3526
+ }
3527
+
3528
+ // Parse results
3529
+ const health = parseComprehensiveHealthCheck(result.stdout);
3530
+
3531
+ // Build response
3532
+ const response = {
3533
+ server: serverName,
3534
+ timestamp: new Date().toISOString(),
3535
+ overall_status: health.overall_status || HEALTH_STATUS.UNKNOWN,
3536
+ cpu: health.cpu,
3537
+ memory: health.memory,
3538
+ disks: health.disks,
3539
+ uptime: health.uptime
3540
+ };
3541
+
3542
+ if (detailed) {
3543
+ response.load_average = health.load_average;
3544
+ response.network = health.network;
3545
+ }
3546
+
3547
+ // Check if there are any critical issues
3548
+ const criticalIssues = [];
3549
+ if (health.cpu && health.cpu.status === HEALTH_STATUS.CRITICAL) {
3550
+ criticalIssues.push(`CPU usage critical: ${health.cpu.percent}%`);
3551
+ }
3552
+ if (health.memory && health.memory.status === HEALTH_STATUS.CRITICAL) {
3553
+ criticalIssues.push(`Memory usage critical: ${health.memory.percent}%`);
3554
+ }
3555
+ if (health.disks) {
3556
+ for (const disk of health.disks) {
3557
+ if (disk.status === HEALTH_STATUS.CRITICAL) {
3558
+ criticalIssues.push(`Disk ${disk.mount} critical: ${disk.percent}%`);
3559
+ }
3560
+ }
3561
+ }
3562
+
3563
+ if (criticalIssues.length > 0) {
3564
+ response.critical_issues = criticalIssues;
3565
+ }
3566
+
3567
+ logger.info(`Health check completed: ${health.overall_status}`, {
3568
+ server: serverName,
3569
+ status: health.overall_status
3570
+ });
3571
+
3572
+ return {
3573
+ content: [
3574
+ {
3575
+ type: 'text',
3576
+ text: JSON.stringify(response, null, 2)
3577
+ }
3578
+ ]
3579
+ };
3580
+
3581
+ } catch (error) {
3582
+ logger.error('Health check failed', {
3583
+ server: serverName,
3584
+ error: error.message
3585
+ });
3586
+
3587
+ return {
3588
+ content: [
3589
+ {
3590
+ type: 'text',
3591
+ text: `āŒ Health check failed: ${error.message}`
3592
+ }
3593
+ ]
3594
+ };
3595
+ }
3596
+ }
3597
+ );
3598
+
3599
+ server.registerTool(
3600
+ 'ssh_service_status',
3601
+ {
3602
+ description: 'Check status of services on remote server',
3603
+ inputSchema: {
3604
+ server: z.string().describe('Server name'),
3605
+ services: z.array(z.string())
3606
+ .describe('Service names to check (e.g., nginx, mysql, docker)')
3607
+ }
3608
+ },
3609
+ async ({ server: serverName, services }) => {
3610
+ try {
3611
+ const ssh = await getConnection(serverName);
3612
+
3613
+ logger.info(`Checking service status on ${serverName}`, {
3614
+ services: services.join(', ')
3615
+ });
3616
+
3617
+ const serviceStatuses = [];
3618
+
3619
+ // Check each service
3620
+ for (const serviceName of services) {
3621
+ const resolvedName = resolveServiceName(serviceName);
3622
+ const statusCommand = buildServiceStatusCommand(resolvedName);
3623
+ const result = await ssh.execCommand(statusCommand);
3624
+
3625
+ const status = parseServiceStatus(result.stdout, serviceName);
3626
+ serviceStatuses.push(status);
3627
+ }
3628
+
3629
+ // Count running vs stopped
3630
+ const running = serviceStatuses.filter(s => s.status === 'running').length;
3631
+ const stopped = serviceStatuses.filter(s => s.status === 'stopped').length;
3632
+
3633
+ const response = {
3634
+ server: serverName,
3635
+ timestamp: new Date().toISOString(),
3636
+ total: serviceStatuses.length,
3637
+ running,
3638
+ stopped,
3639
+ services: serviceStatuses,
3640
+ overall_health: stopped === 0 ? HEALTH_STATUS.HEALTHY :
3641
+ running > stopped ? HEALTH_STATUS.WARNING :
3642
+ HEALTH_STATUS.CRITICAL
3643
+ };
3644
+
3645
+ logger.info(`Service check completed`, {
3646
+ server: serverName,
3647
+ running,
3648
+ stopped
3649
+ });
3650
+
3651
+ return {
3652
+ content: [
3653
+ {
3654
+ type: 'text',
3655
+ text: JSON.stringify(response, null, 2)
3656
+ }
3657
+ ]
3658
+ };
3659
+
3660
+ } catch (error) {
3661
+ logger.error('Service status check failed', {
3662
+ server: serverName,
3663
+ error: error.message
3664
+ });
3665
+
3666
+ return {
3667
+ content: [
3668
+ {
3669
+ type: 'text',
3670
+ text: `āŒ Service status check failed: ${error.message}`
3671
+ }
3672
+ ]
3673
+ };
3674
+ }
3675
+ }
3676
+ );
3677
+
3678
+ server.registerTool(
3679
+ 'ssh_process_manager',
3680
+ {
3681
+ description: 'List, monitor, or kill processes on remote server',
3682
+ inputSchema: {
3683
+ server: z.string().describe('Server name'),
3684
+ action: z.enum(['list', 'kill', 'info'])
3685
+ .describe('Action: list processes, kill process, or get process info'),
3686
+ pid: z.number().optional()
3687
+ .describe('Process ID (required for kill and info actions)'),
3688
+ signal: z.enum(['TERM', 'KILL', 'HUP', 'INT', 'QUIT']).optional()
3689
+ .describe('Signal to send when killing (default: TERM)'),
3690
+ sortBy: z.enum(['cpu', 'memory']).optional()
3691
+ .describe('Sort processes by CPU or memory (default: cpu)'),
3692
+ limit: z.number().optional()
3693
+ .describe('Number of processes to return (default: 20)'),
3694
+ filter: z.string().optional()
3695
+ .describe('Filter processes by name/command')
3696
+ }
3697
+ },
3698
+ async ({ server: serverName, action, pid, signal = 'TERM', sortBy = 'cpu', limit = 20, filter }) => {
3699
+ try {
3700
+ const ssh = await getConnection(serverName);
3701
+
3702
+ logger.info(`Process manager action: ${action}`, {
3703
+ server: serverName,
3704
+ pid,
3705
+ filter
3706
+ });
3707
+
3708
+ let response;
3709
+
3710
+ 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);
3720
+
3721
+ response = {
3722
+ server: serverName,
3723
+ action: 'list',
3724
+ count: processes.length,
3725
+ sorted_by: sortBy,
3726
+ processes
3727
+ };
3728
+ break;
3729
+ }
3730
+
3731
+ case 'kill': {
3732
+ if (!pid) {
3733
+ throw new Error('pid parameter required for kill action');
3734
+ }
3735
+
3736
+ // Get process info first
3737
+ const infoCommand = buildProcessInfoCommand(pid);
3738
+ const infoResult = await ssh.execCommand(infoCommand);
3739
+
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
+ }
3748
+
3749
+ // Kill the process
3750
+ const killCommand = buildKillProcessCommand(pid, signal);
3751
+ const killResult = await ssh.execCommand(killCommand);
3752
+
3753
+ if (killResult.code !== 0) {
3754
+ throw new Error(`Failed to kill process ${pid}: ${killResult.stderr}`);
3755
+ }
3756
+
3757
+ response = {
3758
+ server: serverName,
3759
+ action: 'kill',
3760
+ pid,
3761
+ signal,
3762
+ process: processInfo,
3763
+ success: true
3764
+ };
3765
+
3766
+ logger.info(`Process killed: ${pid}`, {
3767
+ server: serverName,
3768
+ signal
3769
+ });
3770
+ break;
3771
+ }
3772
+
3773
+ case 'info': {
3774
+ if (!pid) {
3775
+ throw new Error('pid parameter required for info action');
3776
+ }
3777
+
3778
+ const infoCommand = buildProcessInfoCommand(pid);
3779
+ const result = await ssh.execCommand(infoCommand);
3780
+
3781
+ if (result.code !== 0 || !result.stdout) {
3782
+ throw new Error(`Process ${pid} not found`);
3783
+ }
3784
+
3785
+ const processInfo = JSON.parse(result.stdout);
3786
+
3787
+ response = {
3788
+ server: serverName,
3789
+ action: 'info',
3790
+ process: processInfo
3791
+ };
3792
+ break;
3793
+ }
3794
+
3795
+ default:
3796
+ throw new Error(`Unknown action: ${action}`);
3797
+ }
3798
+
3799
+ return {
3800
+ content: [
3801
+ {
3802
+ type: 'text',
3803
+ text: JSON.stringify(response, null, 2)
3804
+ }
3805
+ ]
3806
+ };
3807
+
3808
+ } catch (error) {
3809
+ logger.error('Process manager failed', {
3810
+ server: serverName,
3811
+ action,
3812
+ error: error.message
3813
+ });
3814
+
3815
+ return {
3816
+ content: [
3817
+ {
3818
+ type: 'text',
3819
+ text: `āŒ Process manager failed: ${error.message}`
3820
+ }
3821
+ ]
3822
+ };
3823
+ }
3824
+ }
3825
+ );
3826
+
3827
+ server.registerTool(
3828
+ 'ssh_alert_setup',
3829
+ {
3830
+ description: 'Configure health monitoring alerts and thresholds',
3831
+ inputSchema: {
3832
+ server: z.string().describe('Server name'),
3833
+ action: z.enum(['set', 'get', 'check'])
3834
+ .describe('Action: set thresholds, get config, or check current metrics against thresholds'),
3835
+ cpuThreshold: z.number().optional()
3836
+ .describe('CPU usage threshold percentage (e.g., 80)'),
3837
+ memoryThreshold: z.number().optional()
3838
+ .describe('Memory usage threshold percentage (e.g., 90)'),
3839
+ diskThreshold: z.number().optional()
3840
+ .describe('Disk usage threshold percentage (e.g., 85)'),
3841
+ enabled: z.boolean().optional()
3842
+ .describe('Enable or disable alerts (default: true)')
3843
+ }
3844
+ },
3845
+ async ({ server: serverName, action, cpuThreshold, memoryThreshold, diskThreshold, enabled = true }) => {
3846
+ try {
3847
+ const ssh = await getConnection(serverName);
3848
+ const configPath = '/etc/ssh-manager-alerts.json';
3849
+
3850
+ logger.info(`Alert setup action: ${action}`, {
3851
+ server: serverName
3852
+ });
3853
+
3854
+ let response;
3855
+
3856
+ 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
+ });
3865
+
3866
+ // Save to server
3867
+ const saveCommand = buildSaveAlertConfigCommand(config, configPath);
3868
+ const saveResult = await ssh.execCommand(saveCommand);
3869
+
3870
+ if (saveResult.code !== 0) {
3871
+ throw new Error(`Failed to save alert config: ${saveResult.stderr}`);
3872
+ }
3873
+
3874
+ response = {
3875
+ server: serverName,
3876
+ action: 'set',
3877
+ config,
3878
+ config_path: configPath,
3879
+ success: true
3880
+ };
3881
+
3882
+ logger.info('Alert thresholds configured', {
3883
+ server: serverName,
3884
+ thresholds: config
3885
+ });
3886
+ break;
3887
+ }
3888
+
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
+ }
3901
+ }
3902
+
3903
+ response = {
3904
+ server: serverName,
3905
+ action: 'get',
3906
+ config,
3907
+ config_path: configPath
3908
+ };
3909
+ break;
3910
+ }
3911
+
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
+ }
3937
+
3938
+ // Get current metrics
3939
+ const healthCommand = buildComprehensiveHealthCheckCommand();
3940
+ const healthResult = await ssh.execCommand(healthCommand);
3941
+
3942
+ if (healthResult.code !== 0) {
3943
+ throw new Error('Failed to get current metrics');
3944
+ }
3945
+
3946
+ const metrics = parseComprehensiveHealthCheck(healthResult.stdout);
3947
+
3948
+ // Check thresholds
3949
+ const alerts = checkAlertThresholds(metrics, thresholds);
3950
+
3951
+ response = {
3952
+ 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
+ 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;
3973
+ }
3974
+
3975
+ default:
3976
+ throw new Error(`Unknown action: ${action}`);
3977
+ }
3978
+
3979
+ return {
3980
+ content: [
3981
+ {
3982
+ type: 'text',
3983
+ text: JSON.stringify(response, null, 2)
3984
+ }
3985
+ ]
3986
+ };
3987
+
3988
+ } catch (error) {
3989
+ logger.error('Alert setup failed', {
3990
+ server: serverName,
3991
+ action,
3992
+ error: error.message
3993
+ });
3994
+
3995
+ return {
3996
+ content: [
3997
+ {
3998
+ type: 'text',
3999
+ text: `āŒ Alert setup failed: ${error.message}`
4000
+ }
4001
+ ]
4002
+ };
4003
+ }
4004
+ }
4005
+ );
4006
+
4007
+ // ============================================================================
4008
+ // DATABASE MANAGEMENT TOOLS
4009
+ // ============================================================================
4010
+
4011
+ server.registerTool(
4012
+ 'ssh_db_dump',
4013
+ {
4014
+ description: 'Dump database to file (MySQL, PostgreSQL, MongoDB)',
4015
+ inputSchema: {
4016
+ server: z.string().describe('Server name'),
4017
+ type: z.enum(['mysql', 'postgresql', 'mongodb'])
4018
+ .describe('Database type'),
4019
+ database: z.string().describe('Database name'),
4020
+ outputFile: z.string().describe('Output file path (will be created on remote server)'),
4021
+ dbUser: z.string().optional().describe('Database user'),
4022
+ dbPassword: z.string().optional().describe('Database password'),
4023
+ dbHost: z.string().optional().describe('Database host (default: localhost)'),
4024
+ dbPort: z.number().optional().describe('Database port'),
4025
+ compress: z.boolean().optional().describe('Compress output with gzip (default: true)'),
4026
+ tables: z.array(z.string()).optional().describe('Specific tables to dump (MySQL/PostgreSQL only)')
4027
+ }
4028
+ },
4029
+ async ({ server: serverName, type, database, outputFile, dbUser, dbPassword, dbHost, dbPort, compress = true, tables }) => {
4030
+ try {
4031
+ const ssh = await getConnection(serverName);
4032
+
4033
+ logger.info(`Dumping ${type} database: ${database}`, {
4034
+ server: serverName,
4035
+ compress
4036
+ });
4037
+
4038
+ // Build dump command based on type
4039
+ let dumpCommand;
4040
+ const options = {
4041
+ database,
4042
+ user: dbUser,
4043
+ password: dbPassword,
4044
+ host: dbHost,
4045
+ port: dbPort,
4046
+ outputFile,
4047
+ compress,
4048
+ tables
4049
+ };
4050
+
4051
+ 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}`);
4064
+ }
4065
+
4066
+ // Execute dump
4067
+ const result = await ssh.execCommand(dumpCommand);
4068
+
4069
+ if (result.code !== 0) {
4070
+ throw new Error(`Dump failed: ${result.stderr || result.stdout}`);
4071
+ }
4072
+
4073
+ // Get file size
4074
+ const sizeCommand = `stat -f%z "${outputFile}" 2>/dev/null || stat -c%s "${outputFile}" 2>/dev/null`;
4075
+ const sizeResult = await ssh.execCommand(sizeCommand);
4076
+ const size = parseSize(sizeResult.stdout);
4077
+
4078
+ logger.info(`Database dump completed: ${formatBytes(size)}`, {
4079
+ server: serverName,
4080
+ database,
4081
+ size
4082
+ });
4083
+
4084
+ return {
4085
+ content: [
4086
+ {
4087
+ type: 'text',
4088
+ text: JSON.stringify({
4089
+ success: true,
4090
+ server: serverName,
4091
+ type,
4092
+ database,
4093
+ output_file: outputFile,
4094
+ size_bytes: size,
4095
+ size_human: formatBytes(size),
4096
+ compressed: compress,
4097
+ timestamp: new Date().toISOString()
4098
+ }, null, 2)
4099
+ }
4100
+ ]
4101
+ };
4102
+
4103
+ } catch (error) {
4104
+ logger.error('Database dump failed', {
4105
+ server: serverName,
4106
+ type,
4107
+ database,
4108
+ error: error.message
4109
+ });
4110
+
4111
+ return {
4112
+ content: [
4113
+ {
4114
+ type: 'text',
4115
+ text: `āŒ Database dump failed: ${error.message}`
4116
+ }
4117
+ ]
4118
+ };
4119
+ }
4120
+ }
4121
+ );
4122
+
4123
+ server.registerTool(
4124
+ 'ssh_db_import',
4125
+ {
4126
+ description: 'Import database from SQL file (MySQL, PostgreSQL, MongoDB)',
4127
+ inputSchema: {
4128
+ server: z.string().describe('Server name'),
4129
+ type: z.enum(['mysql', 'postgresql', 'mongodb'])
4130
+ .describe('Database type'),
4131
+ database: z.string().describe('Target database name'),
4132
+ inputFile: z.string().describe('Input file path (on remote server)'),
4133
+ dbUser: z.string().optional().describe('Database user'),
4134
+ dbPassword: z.string().optional().describe('Database password'),
4135
+ dbHost: z.string().optional().describe('Database host (default: localhost)'),
4136
+ dbPort: z.number().optional().describe('Database port'),
4137
+ drop: z.boolean().optional().describe('Drop existing collections/tables before import (MongoDB only, default: true)')
4138
+ }
4139
+ },
4140
+ async ({ server: serverName, type, database, inputFile, dbUser, dbPassword, dbHost, dbPort, drop = true }) => {
4141
+ try {
4142
+ const ssh = await getConnection(serverName);
4143
+
4144
+ logger.info(`Importing ${type} database: ${database}`, {
4145
+ server: serverName,
4146
+ inputFile
4147
+ });
4148
+
4149
+ // Build import command based on type
4150
+ let importCommand;
4151
+ const options = {
4152
+ database,
4153
+ user: dbUser,
4154
+ password: dbPassword,
4155
+ host: dbHost,
4156
+ port: dbPort,
4157
+ inputFile,
4158
+ drop
4159
+ };
4160
+
4161
+ 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}`);
4174
+ }
4175
+
4176
+ // Execute import
4177
+ const result = await ssh.execCommand(importCommand);
4178
+
4179
+ if (result.code !== 0) {
4180
+ throw new Error(`Import failed: ${result.stderr || result.stdout}`);
4181
+ }
4182
+
4183
+ logger.info(`Database import completed`, {
4184
+ server: serverName,
4185
+ database
4186
+ });
4187
+
4188
+ return {
4189
+ content: [
4190
+ {
4191
+ type: 'text',
4192
+ text: JSON.stringify({
4193
+ success: true,
4194
+ server: serverName,
4195
+ type,
4196
+ database,
4197
+ input_file: inputFile,
4198
+ timestamp: new Date().toISOString(),
4199
+ message: `Database ${database} imported successfully`
4200
+ }, null, 2)
4201
+ }
4202
+ ]
4203
+ };
4204
+
4205
+ } catch (error) {
4206
+ logger.error('Database import failed', {
4207
+ server: serverName,
4208
+ type,
4209
+ database,
4210
+ error: error.message
4211
+ });
4212
+
4213
+ return {
4214
+ content: [
4215
+ {
4216
+ type: 'text',
4217
+ text: `āŒ Database import failed: ${error.message}`
4218
+ }
4219
+ ]
4220
+ };
4221
+ }
4222
+ }
4223
+ );
4224
+
4225
+ server.registerTool(
4226
+ 'ssh_db_list',
4227
+ {
4228
+ description: 'List databases or tables/collections',
4229
+ inputSchema: {
4230
+ server: z.string().describe('Server name'),
4231
+ type: z.enum(['mysql', 'postgresql', 'mongodb'])
4232
+ .describe('Database type'),
4233
+ database: z.string().optional()
4234
+ .describe('Database name (if provided, lists tables/collections; if omitted, lists databases)'),
4235
+ dbUser: z.string().optional().describe('Database user'),
4236
+ dbPassword: z.string().optional().describe('Database password'),
4237
+ dbHost: z.string().optional().describe('Database host (default: localhost)'),
4238
+ dbPort: z.number().optional().describe('Database port')
4239
+ }
4240
+ },
4241
+ async ({ server: serverName, type, database, dbUser, dbPassword, dbHost, dbPort }) => {
4242
+ try {
4243
+ const ssh = await getConnection(serverName);
4244
+
4245
+ const listType = database ? 'tables/collections' : 'databases';
4246
+ logger.info(`Listing ${listType} for ${type}`, {
4247
+ server: serverName,
4248
+ database
4249
+ });
4250
+
4251
+ let listCommand;
4252
+ const options = {
4253
+ database,
4254
+ user: dbUser,
4255
+ password: dbPassword,
4256
+ host: dbHost,
4257
+ port: dbPort
4258
+ };
4259
+
4260
+ // Build command based on type and what to list
4261
+ if (database) {
4262
+ // List tables/collections
4263
+ 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;
4273
+ }
4274
+ } else {
4275
+ // List databases
4276
+ 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;
4286
+ }
4287
+ }
4288
+
4289
+ // Execute list command
4290
+ const result = await ssh.execCommand(listCommand);
4291
+
4292
+ if (result.code !== 0 && result.stderr) {
4293
+ throw new Error(`List failed: ${result.stderr}`);
4294
+ }
4295
+
4296
+ // Parse results
4297
+ const items = database
4298
+ ? parseTableList(result.stdout)
4299
+ : parseDatabaseList(result.stdout, type);
4300
+
4301
+ const response = {
4302
+ success: true,
4303
+ server: serverName,
4304
+ type,
4305
+ listing: database ? 'tables' : 'databases'
4306
+ };
4307
+
4308
+ if (database) {
4309
+ response.database = database;
4310
+ response.tables = items;
4311
+ response.count = items.length;
4312
+ } else {
4313
+ response.databases = items;
4314
+ response.count = items.length;
4315
+ }
4316
+
4317
+ logger.info(`Listed ${items.length} ${listType}`, {
4318
+ server: serverName,
4319
+ type
4320
+ });
4321
+
4322
+ return {
4323
+ content: [
4324
+ {
4325
+ type: 'text',
4326
+ text: JSON.stringify(response, null, 2)
4327
+ }
4328
+ ]
4329
+ };
4330
+
4331
+ } catch (error) {
4332
+ logger.error('Database list failed', {
4333
+ server: serverName,
4334
+ type,
4335
+ error: error.message
4336
+ });
4337
+
4338
+ return {
4339
+ content: [
4340
+ {
4341
+ type: 'text',
4342
+ text: `āŒ Database list failed: ${error.message}`
4343
+ }
4344
+ ]
4345
+ };
4346
+ }
4347
+ }
4348
+ );
4349
+
4350
+ server.registerTool(
4351
+ 'ssh_db_query',
4352
+ {
4353
+ description: 'Execute SELECT query on database (read-only, SELECT queries only)',
4354
+ inputSchema: {
4355
+ server: z.string().describe('Server name'),
4356
+ type: z.enum(['mysql', 'postgresql', 'mongodb'])
4357
+ .describe('Database type'),
4358
+ database: z.string().describe('Database name'),
4359
+ query: z.string().describe('SQL query (SELECT only) or MongoDB find query'),
4360
+ collection: z.string().optional()
4361
+ .describe('Collection name (MongoDB only)'),
4362
+ dbUser: z.string().optional().describe('Database user'),
4363
+ dbPassword: z.string().optional().describe('Database password'),
4364
+ dbHost: z.string().optional().describe('Database host (default: localhost)'),
4365
+ dbPort: z.number().optional().describe('Database port')
4366
+ }
4367
+ },
4368
+ async ({ server: serverName, type, database, query, collection, dbUser, dbPassword, dbHost, dbPort }) => {
4369
+ try {
4370
+ const ssh = await getConnection(serverName);
4371
+
4372
+ // Validate query safety for SQL databases
4373
+ if (type !== DB_TYPES.MONGODB && !isSafeQuery(query)) {
4374
+ throw new Error('Only SELECT queries are allowed for security reasons');
4375
+ }
4376
+
4377
+ logger.info(`Executing ${type} query`, {
4378
+ server: serverName,
4379
+ database,
4380
+ query: query.substring(0, 100)
4381
+ });
4382
+
4383
+ let queryCommand;
4384
+ const options = {
4385
+ database,
4386
+ query,
4387
+ user: dbUser,
4388
+ password: dbPassword,
4389
+ host: dbHost,
4390
+ port: dbPort
4391
+ };
4392
+
4393
+ // Build query command based on type
4394
+ 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}`);
4410
+ }
4411
+
4412
+ // Execute query
4413
+ const result = await ssh.execCommand(queryCommand);
4414
+
4415
+ if (result.code !== 0) {
4416
+ throw new Error(`Query failed: ${result.stderr || result.stdout}`);
4417
+ }
4418
+
4419
+ // Parse output (basic parsing, output depends on database type)
4420
+ const output = result.stdout.trim();
4421
+ const lines = output.split('\n');
4422
+
4423
+ logger.info(`Query executed successfully`, {
4424
+ server: serverName,
4425
+ database,
4426
+ rows: lines.length
4427
+ });
4428
+
4429
+ return {
4430
+ content: [
4431
+ {
4432
+ type: 'text',
4433
+ text: JSON.stringify({
4434
+ success: true,
4435
+ server: serverName,
4436
+ type,
4437
+ database,
4438
+ collection: collection || null,
4439
+ query,
4440
+ row_count: lines.length,
4441
+ output: output,
4442
+ timestamp: new Date().toISOString()
4443
+ }, null, 2)
4444
+ }
4445
+ ]
4446
+ };
4447
+
4448
+ } catch (error) {
4449
+ logger.error('Database query failed', {
4450
+ server: serverName,
4451
+ type,
4452
+ database,
4453
+ error: error.message
4454
+ });
4455
+
4456
+ return {
4457
+ content: [
4458
+ {
4459
+ type: 'text',
4460
+ text: `āŒ Database query failed: ${error.message}`
4461
+ }
4462
+ ]
4463
+ };
4464
+ }
4465
+ }
4466
+ );
4467
+
4468
+ // Clean up connections on shutdown
4469
+ process.on('SIGINT', async () => {
4470
+ console.error('\nšŸ”Œ Closing SSH connections...');
4471
+ for (const [name, ssh] of connections) {
4472
+ ssh.dispose();
4473
+ console.error(` Closed connection to ${name}`);
4474
+ }
4475
+ process.exit(0);
4476
+ });
4477
+
4478
+ // Start the server
4479
+ async function main() {
4480
+ const transport = new StdioServerTransport();
4481
+ await server.connect(transport);
4482
+
4483
+ const servers = loadServerConfig();
4484
+ const serverList = Object.keys(servers);
4485
+ const activeProfile = getActiveProfileName();
4486
+
4487
+ console.error('šŸš€ MCP SSH Manager Server started');
4488
+ console.error(`šŸ“¦ Profile: ${activeProfile}`);
4489
+ console.error(`šŸ–„ļø Available servers: ${serverList.length > 0 ? serverList.join(', ') : 'none configured'}`);
4490
+ console.error('šŸ’” Use server-manager.py to configure servers');
4491
+ console.error('šŸ”„ Connection management: Auto-reconnect enabled, 30min timeout');
4492
+
4493
+ // Set up periodic cleanup of old connections (every 10 minutes)
4494
+ setInterval(() => {
4495
+ cleanupOldConnections();
4496
+ }, 10 * 60 * 1000);
4497
+ }
4498
+
4499
+ main().catch(console.error);