mcp-ssh-manager 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,434 @@
1
+ /**
2
+ * Tool Configuration Manager
3
+ *
4
+ * Manages tool enablement configuration stored in JSON format.
5
+ * Handles loading, saving, and querying tool configuration.
6
+ */
7
+
8
+ import fs from 'fs';
9
+ import path from 'path';
10
+ import os from 'os';
11
+ import { logger } from './logger.js';
12
+ import { TOOL_GROUPS, findToolGroup, getAllTools } from './tool-registry.js';
13
+
14
+ /**
15
+ * Configuration file location
16
+ * User-global only: ~/.ssh-manager/tools-config.json
17
+ */
18
+ const CONFIG_DIR = path.join(os.homedir(), '.ssh-manager');
19
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'tools-config.json');
20
+
21
+ /**
22
+ * Tool Configuration Manager Class
23
+ */
24
+ export class ToolConfigManager {
25
+ constructor() {
26
+ this.config = null;
27
+ this.configPath = CONFIG_FILE;
28
+ }
29
+
30
+ /**
31
+ * Load tool configuration from file
32
+ * @returns {Promise<Object>} Configuration object
33
+ */
34
+ async load() {
35
+ try {
36
+ if (fs.existsSync(this.configPath)) {
37
+ const content = fs.readFileSync(this.configPath, 'utf8');
38
+ this.config = JSON.parse(content);
39
+
40
+ // Validate config structure
41
+ if (!this.validateConfig(this.config)) {
42
+ logger.warn('Invalid tool configuration, using defaults');
43
+ this.config = this.getDefaultConfig();
44
+ } else {
45
+ logger.info(`Tool configuration loaded from ${this.configPath}`);
46
+ logger.info(`Mode: ${this.config.mode}, Enabled tools: ${this.getEnabledTools().length}/37`);
47
+ }
48
+ } else {
49
+ // No config file - default to all tools enabled
50
+ logger.info('No tool configuration found, enabling all tools (default)');
51
+ logger.info('Run "ssh-manager tools configure" to optimize and reduce context usage');
52
+ this.config = this.getDefaultConfig();
53
+ }
54
+ } catch (error) {
55
+ logger.error(`Failed to load tool configuration: ${error.message}`);
56
+ logger.info('Using default configuration (all tools enabled)');
57
+ this.config = this.getDefaultConfig();
58
+ }
59
+
60
+ return this.config;
61
+ }
62
+
63
+ /**
64
+ * Get default configuration (all tools enabled)
65
+ * @returns {Object} Default configuration
66
+ */
67
+ getDefaultConfig() {
68
+ return {
69
+ version: '1.0',
70
+ mode: 'all',
71
+ groups: {
72
+ core: { enabled: true },
73
+ sessions: { enabled: true },
74
+ monitoring: { enabled: true },
75
+ backup: { enabled: true },
76
+ database: { enabled: true },
77
+ advanced: { enabled: true }
78
+ },
79
+ tools: {},
80
+ _comment: 'Tool configuration for MCP SSH Manager. Run "ssh-manager tools configure" to customize.'
81
+ };
82
+ }
83
+
84
+ /**
85
+ * Validate configuration structure
86
+ * @param {Object} config - Configuration to validate
87
+ * @returns {boolean} True if valid
88
+ */
89
+ validateConfig(config) {
90
+ if (!config || typeof config !== 'object') {
91
+ return false;
92
+ }
93
+
94
+ // Check required fields
95
+ if (!config.version || !config.mode) {
96
+ return false;
97
+ }
98
+
99
+ // Validate mode
100
+ if (!['all', 'minimal', 'custom'].includes(config.mode)) {
101
+ return false;
102
+ }
103
+
104
+ // Check groups structure
105
+ if (config.mode === 'custom' && !config.groups) {
106
+ return false;
107
+ }
108
+
109
+ return true;
110
+ }
111
+
112
+ /**
113
+ * Check if a specific tool is enabled
114
+ * @param {string} toolName - Name of the tool
115
+ * @returns {boolean} True if enabled
116
+ */
117
+ isToolEnabled(toolName) {
118
+ if (!this.config) {
119
+ return true; // Default to enabled if no config loaded
120
+ }
121
+
122
+ // Mode: all - everything enabled
123
+ if (this.config.mode === 'all') {
124
+ return true;
125
+ }
126
+
127
+ // Check individual tool override first
128
+ if (this.config.tools && toolName in this.config.tools) {
129
+ return this.config.tools[toolName];
130
+ }
131
+
132
+ // Mode: minimal - only core tools
133
+ if (this.config.mode === 'minimal') {
134
+ const group = findToolGroup(toolName);
135
+ return group === 'core';
136
+ }
137
+
138
+ // Mode: custom - check group setting
139
+ if (this.config.mode === 'custom') {
140
+ const group = findToolGroup(toolName);
141
+ if (group && this.config.groups && group in this.config.groups) {
142
+ return this.config.groups[group].enabled;
143
+ }
144
+ }
145
+
146
+ // Default to enabled if group not found (for new tools in updates)
147
+ return true;
148
+ }
149
+
150
+ /**
151
+ * Get array of all enabled tool names
152
+ * @returns {string[]} Array of enabled tool names
153
+ */
154
+ getEnabledTools() {
155
+ const allTools = getAllTools();
156
+ return allTools.filter(tool => this.isToolEnabled(tool));
157
+ }
158
+
159
+ /**
160
+ * Get array of all disabled tool names
161
+ * @returns {string[]} Array of disabled tool names
162
+ */
163
+ getDisabledTools() {
164
+ const allTools = getAllTools();
165
+ return allTools.filter(tool => !this.isToolEnabled(tool));
166
+ }
167
+
168
+ /**
169
+ * Check if a group is enabled
170
+ * @param {string} groupName - Name of the group
171
+ * @returns {boolean} True if enabled
172
+ */
173
+ isGroupEnabled(groupName) {
174
+ if (!this.config) {
175
+ return true;
176
+ }
177
+
178
+ if (this.config.mode === 'all') {
179
+ return true;
180
+ }
181
+
182
+ if (this.config.mode === 'minimal') {
183
+ return groupName === 'core';
184
+ }
185
+
186
+ if (this.config.mode === 'custom' && this.config.groups) {
187
+ return this.config.groups[groupName]?.enabled ?? true;
188
+ }
189
+
190
+ return true;
191
+ }
192
+
193
+ /**
194
+ * Save configuration to file
195
+ * @returns {Promise<boolean>} True if saved successfully
196
+ */
197
+ async save() {
198
+ try {
199
+ // Ensure config directory exists
200
+ if (!fs.existsSync(CONFIG_DIR)) {
201
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
202
+ }
203
+
204
+ // Write config file
205
+ const content = JSON.stringify(this.config, null, 2);
206
+ fs.writeFileSync(this.configPath, content, 'utf8');
207
+
208
+ logger.info(`Tool configuration saved to ${this.configPath}`);
209
+ return true;
210
+ } catch (error) {
211
+ logger.error(`Failed to save tool configuration: ${error.message}`);
212
+ return false;
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Enable a tool group
218
+ * @param {string} groupName - Name of the group to enable
219
+ * @returns {Promise<boolean>} True if successful
220
+ */
221
+ async enableGroup(groupName) {
222
+ if (!TOOL_GROUPS[groupName]) {
223
+ logger.error(`Unknown tool group: ${groupName}`);
224
+ return false;
225
+ }
226
+
227
+ // Ensure we're in custom mode
228
+ if (this.config.mode !== 'custom') {
229
+ this.config.mode = 'custom';
230
+ }
231
+
232
+ // Initialize groups if needed
233
+ if (!this.config.groups) {
234
+ this.config.groups = {};
235
+ }
236
+
237
+ // Enable the group
238
+ this.config.groups[groupName] = { enabled: true };
239
+
240
+ logger.info(`Enabled tool group: ${groupName}`);
241
+ return await this.save();
242
+ }
243
+
244
+ /**
245
+ * Disable a tool group
246
+ * @param {string} groupName - Name of the group to disable
247
+ * @returns {Promise<boolean>} True if successful
248
+ */
249
+ async disableGroup(groupName) {
250
+ if (!TOOL_GROUPS[groupName]) {
251
+ logger.error(`Unknown tool group: ${groupName}`);
252
+ return false;
253
+ }
254
+
255
+ if (groupName === 'core') {
256
+ logger.error('Cannot disable core group (required for basic functionality)');
257
+ return false;
258
+ }
259
+
260
+ // Ensure we're in custom mode
261
+ if (this.config.mode !== 'custom') {
262
+ this.config.mode = 'custom';
263
+ }
264
+
265
+ // Initialize groups if needed
266
+ if (!this.config.groups) {
267
+ this.config.groups = {};
268
+ }
269
+
270
+ // Disable the group
271
+ this.config.groups[groupName] = { enabled: false };
272
+
273
+ logger.info(`Disabled tool group: ${groupName}`);
274
+ return await this.save();
275
+ }
276
+
277
+ /**
278
+ * Enable a specific tool (individual override)
279
+ * @param {string} toolName - Name of the tool to enable
280
+ * @returns {Promise<boolean>} True if successful
281
+ */
282
+ async enableTool(toolName) {
283
+ const allTools = getAllTools();
284
+ if (!allTools.includes(toolName)) {
285
+ logger.error(`Unknown tool: ${toolName}`);
286
+ return false;
287
+ }
288
+
289
+ // Initialize tools object if needed
290
+ if (!this.config.tools) {
291
+ this.config.tools = {};
292
+ }
293
+
294
+ // Enable the tool
295
+ this.config.tools[toolName] = true;
296
+
297
+ logger.info(`Enabled tool: ${toolName}`);
298
+ return await this.save();
299
+ }
300
+
301
+ /**
302
+ * Disable a specific tool (individual override)
303
+ * @param {string} toolName - Name of the tool to disable
304
+ * @returns {Promise<boolean>} True if successful
305
+ */
306
+ async disableTool(toolName) {
307
+ const allTools = getAllTools();
308
+ if (!allTools.includes(toolName)) {
309
+ logger.error(`Unknown tool: ${toolName}`);
310
+ return false;
311
+ }
312
+
313
+ // Check if it's a core tool
314
+ if (TOOL_GROUPS.core.includes(toolName)) {
315
+ logger.warn(`Disabling core tool: ${toolName} (may limit functionality)`);
316
+ }
317
+
318
+ // Initialize tools object if needed
319
+ if (!this.config.tools) {
320
+ this.config.tools = {};
321
+ }
322
+
323
+ // Disable the tool
324
+ this.config.tools[toolName] = false;
325
+
326
+ logger.info(`Disabled tool: ${toolName}`);
327
+ return await this.save();
328
+ }
329
+
330
+ /**
331
+ * Set configuration mode
332
+ * @param {string} mode - Mode to set ('all', 'minimal', 'custom')
333
+ * @returns {Promise<boolean>} True if successful
334
+ */
335
+ async setMode(mode) {
336
+ if (!['all', 'minimal', 'custom'].includes(mode)) {
337
+ logger.error(`Invalid mode: ${mode}`);
338
+ return false;
339
+ }
340
+
341
+ this.config.mode = mode;
342
+ logger.info(`Set tool configuration mode to: ${mode}`);
343
+ return await this.save();
344
+ }
345
+
346
+ /**
347
+ * Reset configuration to defaults
348
+ * @returns {Promise<boolean>} True if successful
349
+ */
350
+ async reset() {
351
+ this.config = this.getDefaultConfig();
352
+ logger.info('Reset tool configuration to defaults (all tools enabled)');
353
+ return await this.save();
354
+ }
355
+
356
+ /**
357
+ * Get configuration summary
358
+ * @returns {Object} Summary object
359
+ */
360
+ getSummary() {
361
+ const enabledTools = this.getEnabledTools();
362
+ const disabledTools = this.getDisabledTools();
363
+
364
+ return {
365
+ mode: this.config.mode,
366
+ configPath: this.configPath,
367
+ totalTools: 37,
368
+ enabledCount: enabledTools.length,
369
+ disabledCount: disabledTools.length,
370
+ groups: Object.keys(TOOL_GROUPS).map(groupName => ({
371
+ name: groupName,
372
+ enabled: this.isGroupEnabled(groupName),
373
+ toolCount: TOOL_GROUPS[groupName].length
374
+ }))
375
+ };
376
+ }
377
+
378
+ /**
379
+ * Export Claude Code auto-approval configuration
380
+ * @returns {Object} Auto-approval config snippet
381
+ */
382
+ exportClaudeCodeConfig() {
383
+ const enabledTools = this.getEnabledTools();
384
+
385
+ const autoApprovalPatterns = enabledTools.map(tool => `mcp__ssh-manager__${tool}`);
386
+
387
+ return {
388
+ comment: 'Add these patterns to autoApprove.tools in claude_code_config.json',
389
+ patterns: autoApprovalPatterns,
390
+ exampleConfig: {
391
+ autoApprove: {
392
+ tools: autoApprovalPatterns
393
+ }
394
+ }
395
+ };
396
+ }
397
+ }
398
+
399
+ /**
400
+ * Singleton instance
401
+ */
402
+ let toolConfigInstance = null;
403
+
404
+ /**
405
+ * Load tool configuration (singleton)
406
+ * @returns {Promise<ToolConfigManager>} Configuration manager instance
407
+ */
408
+ export async function loadToolConfig() {
409
+ if (!toolConfigInstance) {
410
+ toolConfigInstance = new ToolConfigManager();
411
+ await toolConfigInstance.load();
412
+ }
413
+ return toolConfigInstance;
414
+ }
415
+
416
+ /**
417
+ * Check if a tool is enabled (convenience function)
418
+ * @param {string} toolName - Name of the tool
419
+ * @returns {boolean} True if enabled
420
+ */
421
+ export function isToolEnabled(toolName) {
422
+ if (!toolConfigInstance) {
423
+ return true; // Default to enabled before config is loaded
424
+ }
425
+ return toolConfigInstance.isToolEnabled(toolName);
426
+ }
427
+
428
+ /**
429
+ * Get the tool configuration manager instance
430
+ * @returns {ToolConfigManager|null} Configuration manager or null if not loaded
431
+ */
432
+ export function getToolConfigManager() {
433
+ return toolConfigInstance;
434
+ }
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Tool Registry
3
+ *
4
+ * Centralized registry of all MCP tools organized into functional groups.
5
+ * Used for conditional tool registration based on user configuration.
6
+ */
7
+
8
+ /**
9
+ * Tool groups with their associated tools
10
+ * Total: 37 tools across 6 groups
11
+ */
12
+ export const TOOL_GROUPS = {
13
+ // Core group (5 tools) - Essential SSH operations
14
+ core: [
15
+ 'ssh_list_servers',
16
+ 'ssh_execute',
17
+ 'ssh_upload',
18
+ 'ssh_download',
19
+ 'ssh_sync'
20
+ ],
21
+
22
+ // Sessions group (4 tools) - Persistent SSH session management
23
+ sessions: [
24
+ 'ssh_session_start',
25
+ 'ssh_session_send',
26
+ 'ssh_session_list',
27
+ 'ssh_session_close'
28
+ ],
29
+
30
+ // Monitoring group (6 tools) - System health and monitoring
31
+ monitoring: [
32
+ 'ssh_health_check',
33
+ 'ssh_service_status',
34
+ 'ssh_process_manager',
35
+ 'ssh_monitor',
36
+ 'ssh_tail',
37
+ 'ssh_alert_setup'
38
+ ],
39
+
40
+ // Backup group (4 tools) - Backup and restore operations
41
+ backup: [
42
+ 'ssh_backup_create',
43
+ 'ssh_backup_list',
44
+ 'ssh_backup_restore',
45
+ 'ssh_backup_schedule'
46
+ ],
47
+
48
+ // Database group (4 tools) - Database operations
49
+ database: [
50
+ 'ssh_db_dump',
51
+ 'ssh_db_import',
52
+ 'ssh_db_list',
53
+ 'ssh_db_query'
54
+ ],
55
+
56
+ // Advanced group (14 tools) - Advanced features
57
+ advanced: [
58
+ 'ssh_deploy',
59
+ 'ssh_execute_sudo',
60
+ 'ssh_alias',
61
+ 'ssh_command_alias',
62
+ 'ssh_hooks',
63
+ 'ssh_profile',
64
+ 'ssh_connection_status',
65
+ 'ssh_tunnel_create',
66
+ 'ssh_tunnel_list',
67
+ 'ssh_tunnel_close',
68
+ 'ssh_key_manage',
69
+ 'ssh_execute_group',
70
+ 'ssh_group_manage',
71
+ 'ssh_history'
72
+ ]
73
+ };
74
+
75
+ /**
76
+ * Human-readable descriptions for each tool group
77
+ */
78
+ export const TOOL_GROUP_DESCRIPTIONS = {
79
+ core: 'Essential SSH operations (list servers, execute commands, upload/download files, sync)',
80
+ sessions: 'Persistent SSH sessions with state management',
81
+ monitoring: 'System health checks, service monitoring, process management, and alerts',
82
+ backup: 'Automated backup and restore for databases and files',
83
+ database: 'Database operations (MySQL, PostgreSQL, MongoDB)',
84
+ advanced: 'Advanced features (deployment, sudo, tunnels, groups, aliases, hooks, profiles)'
85
+ };
86
+
87
+ /**
88
+ * Tool count per group
89
+ */
90
+ export const TOOL_GROUP_COUNTS = {
91
+ core: 5,
92
+ sessions: 4,
93
+ monitoring: 6,
94
+ backup: 4,
95
+ database: 4,
96
+ advanced: 14
97
+ };
98
+
99
+ /**
100
+ * Get all tool names across all groups
101
+ * @returns {string[]} Array of all 37 tool names
102
+ */
103
+ export function getAllTools() {
104
+ return Object.values(TOOL_GROUPS).flat();
105
+ }
106
+
107
+ /**
108
+ * Find which group a tool belongs to
109
+ * @param {string} toolName - Name of the tool
110
+ * @returns {string|null} Group name or null if not found
111
+ */
112
+ export function findToolGroup(toolName) {
113
+ for (const [groupName, tools] of Object.entries(TOOL_GROUPS)) {
114
+ if (tools.includes(toolName)) {
115
+ return groupName;
116
+ }
117
+ }
118
+ return null;
119
+ }
120
+
121
+ /**
122
+ * Get all tools in a specific group
123
+ * @param {string} groupName - Name of the group
124
+ * @returns {string[]} Array of tool names in the group
125
+ */
126
+ export function getGroupTools(groupName) {
127
+ return TOOL_GROUPS[groupName] || [];
128
+ }
129
+
130
+ /**
131
+ * Validate that all expected tools are registered
132
+ * @param {string[]} registeredTools - Array of registered tool names
133
+ * @returns {Object} Validation result with missing and unexpected tools
134
+ */
135
+ export function validateToolRegistry(registeredTools) {
136
+ const allExpectedTools = getAllTools();
137
+ const registeredSet = new Set(registeredTools);
138
+ const expectedSet = new Set(allExpectedTools);
139
+
140
+ const missing = allExpectedTools.filter(tool => !registeredSet.has(tool));
141
+ const unexpected = registeredTools.filter(tool => !expectedSet.has(tool));
142
+
143
+ return {
144
+ valid: missing.length === 0 && unexpected.length === 0,
145
+ total: allExpectedTools.length,
146
+ registered: registeredTools.length,
147
+ missing,
148
+ unexpected
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Get statistics about tool groups
154
+ * @returns {Object} Statistics object
155
+ */
156
+ export function getToolStats() {
157
+ const groups = Object.keys(TOOL_GROUPS);
158
+ const totalTools = getAllTools().length;
159
+
160
+ return {
161
+ totalGroups: groups.length,
162
+ totalTools,
163
+ groups: groups.map(groupName => ({
164
+ name: groupName,
165
+ count: TOOL_GROUP_COUNTS[groupName],
166
+ description: TOOL_GROUP_DESCRIPTIONS[groupName],
167
+ tools: TOOL_GROUPS[groupName]
168
+ }))
169
+ };
170
+ }
171
+
172
+ /**
173
+ * Verify tool registry integrity (no duplicates, all accounted for)
174
+ * @returns {Object} Integrity check result
175
+ */
176
+ export function verifyIntegrity() {
177
+ const allTools = getAllTools();
178
+ const uniqueTools = new Set(allTools);
179
+
180
+ const duplicates = allTools.filter((tool, index) =>
181
+ allTools.indexOf(tool) !== index
182
+ );
183
+
184
+ const expectedTotal = Object.values(TOOL_GROUP_COUNTS).reduce((a, b) => a + b, 0);
185
+
186
+ return {
187
+ valid: duplicates.length === 0 && allTools.length === expectedTotal,
188
+ totalTools: allTools.length,
189
+ uniqueTools: uniqueTools.size,
190
+ expectedTotal,
191
+ duplicates,
192
+ issues: []
193
+ .concat(duplicates.length > 0 ? [`Found ${duplicates.length} duplicate tools`] : [])
194
+ .concat(allTools.length !== expectedTotal ? [`Expected ${expectedTotal} tools but found ${allTools.length}`] : [])
195
+ };
196
+ }