mcp-ssh-manager 3.7.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js CHANGED
@@ -47,6 +47,7 @@ import {
47
47
  } from './profile-loader.js';
48
48
  import { logger } from './logger.js';
49
49
  import { parseRsyncStats } from './rsync-stats.js';
50
+ import { toRsyncLocalPath } from './rsync-path.js';
50
51
  import {
51
52
  createSession,
52
53
  getSession,
@@ -54,6 +55,8 @@ import {
54
55
  closeSession
55
56
  } from './session-manager.js';
56
57
  import {
58
+ setServerConfigProvider,
59
+ getGroup,
57
60
  createGroup,
58
61
  updateGroup,
59
62
  deleteGroup,
@@ -192,6 +195,10 @@ const serverConfigManager = new ServerConfigManager({
192
195
  preferToml: getRuntimeEnv('PREFER_TOML_CONFIG') === 'true'
193
196
  });
194
197
 
198
+ // Let the group layer read the loaded servers, so groups can be derived from
199
+ // each server's `group` field (and so the 'all' group also sees TOML servers).
200
+ setServerConfigProvider(() => serverConfigManager.servers);
201
+
195
202
  try {
196
203
  const loadedServers = await serverConfigManager.loadInitial();
197
204
  logger.info(`Loaded ${Object.keys(loadedServers).length} SSH server configurations`);
@@ -296,6 +303,13 @@ async function auditOk(serverName, toolName, args, executionResult) {
296
303
  }
297
304
 
298
305
  // Execute command with timeout - using child_process timeout for real kill
306
+ /**
307
+ * @param {any} ssh
308
+ * @param {string} command
309
+ * @param {{rawCommand?: boolean, platform?: string, execOptions?: Record<string, any>,
310
+ * [key: string]: any}} [options]
311
+ * @param {number} [timeoutMs]
312
+ */
299
313
  async function execCommandWithTimeout(ssh, command, options = {}, timeoutMs = 30000) {
300
314
  // Pass through rawCommand and platform if specified
301
315
  const { rawCommand, platform = 'linux', ...otherOptions } = options;
@@ -461,11 +475,13 @@ async function createProxyCommandSocket(proxyCommand, host, port) {
461
475
  stdio: ['pipe', 'pipe', 'pipe']
462
476
  });
463
477
 
464
- const socket = Duplex.from({
478
+ // Cast: Node accepts a {readable, writable} pair here, but the bundled
479
+ // types only model the stream/iterable overloads.
480
+ const socket = Duplex.from(/** @type {any} */ ({
465
481
  readable: child.stdout,
466
482
  writable: child.stdin,
467
483
  allowHalfOpen: false
468
- });
484
+ }));
469
485
 
470
486
  // Forward proxy stderr to the MCP server's stderr for debugging
471
487
  child.stderr.on('data', (chunk) => {
@@ -614,23 +630,42 @@ async function getConnection(serverName) {
614
630
  return connections.get(normalizedName);
615
631
  }
616
632
 
633
+ // Server version reported to MCP clients — derived from package.json so it
634
+ // always reflects the real build instead of a literal that drifts across
635
+ // releases. Resolves both in-repo (src/../package.json) and installed, since
636
+ // package.json always sits at the package root.
637
+ function getServerVersion() {
638
+ try {
639
+ const pkgPath = path.join(__dirname, '..', 'package.json');
640
+ const version = JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version;
641
+ if (version) return version;
642
+ } catch (error) {
643
+ logger.warn('Could not read version from package.json', { error: error.message });
644
+ }
645
+
646
+ return '0.0.0-unknown';
647
+ }
648
+
617
649
  // Create MCP server
650
+ const serverVersion = getServerVersion();
618
651
  const server = new McpServer({
619
652
  name: 'mcp-ssh-manager',
620
- version: '1.2.0',
653
+ version: serverVersion,
621
654
  });
622
655
 
623
- logger.info('MCP Server initialized', { version: '1.2.0' });
656
+ logger.info('MCP Server initialized', { version: serverVersion });
624
657
 
625
658
  /**
626
659
  * Helper function to conditionally register tools based on configuration
627
660
  * @param {string} toolName - Name of the tool
628
- * @param {Object} schema - Tool schema
629
- * @param {Function} handler - Tool handler function
661
+ * @param {any} schema - Tool schema (description + zod inputSchema)
662
+ * @param {(args: any, extra?: any) => any} handler - Tool handler function
630
663
  */
631
664
  function registerToolConditional(toolName, schema, handler) {
632
665
  if (isToolEnabled(toolName)) {
633
- server.registerTool(toolName, schema, handler);
666
+ // Cast: registerTool infers its handler signature from the zod schema, which
667
+ // this generic wrapper cannot express while staying one helper for 37 tools.
668
+ server.registerTool(toolName, schema, /** @type {any} */ (handler));
634
669
  logger.debug(`Registered tool: ${toolName}`);
635
670
  } else {
636
671
  logger.debug(`Skipped disabled tool: ${toolName}`);
@@ -874,11 +909,11 @@ registerToolConditional(
874
909
  registerToolConditional(
875
910
  'ssh_sync',
876
911
  {
877
- description: 'Synchronizes files or directories between local and remote using rsync over SSH on the named server. Each of source and destination must carry a local: or remote: prefix and one side must be local and the other remote; with no prefix it assumes a push from local to remote. Mutates the destination. Setting delete true removes destination files absent from source, which is destructive; dryRun true previews without changing anything. Compression is on by default. Password authentication requires sshpass installed locally. Blocked on readonly or restricted servers. Timeout defaults to 30000 ms.',
912
+ description: 'Synchronizes files or directories between local and remote using rsync over SSH on the named server. Each of source and destination must carry a local: or remote: prefix and one side must be local and the other remote; with no prefix it assumes a push from local to remote. On Windows MCP hosts, provide native Windows local paths such as C:\\project or .\\project; the tool converts drive-letter and UNC paths to MSYS2 format before spawning rsync. Do not pre-convert a local path to /c/project because Node performs local filesystem checks using Windows path semantics. Mutates the destination. Setting delete true removes destination files absent from source, which is destructive; dryRun true previews without changing anything. Compression is on by default. Password authentication requires sshpass installed locally. Blocked on readonly or restricted servers. Timeout defaults to 30000 ms.',
878
913
  inputSchema: {
879
914
  server: z.string().describe('Server name from configuration'),
880
- source: z.string().describe('Source path (use "local:" or "remote:" prefix)'),
881
- destination: z.string().describe('Destination path (use "local:" or "remote:" prefix)'),
915
+ source: z.string().describe('Source path with a "local:" or "remote:" prefix. On Windows, use a native local path such as "local:C:\\project" or "local:.\\project"; do not pre-convert it to MSYS2 /c/... syntax.'),
916
+ destination: z.string().describe('Destination path with a "local:" or "remote:" prefix. On Windows, use a native local path such as "local:C:\\output" or "local:.\\output"; do not pre-convert it to MSYS2 /c/... syntax.'),
882
917
  exclude: z.array(z.string()).optional().describe('Patterns to exclude from sync'),
883
918
  dryRun: z.boolean().optional().describe('Perform dry run without actual changes'),
884
919
  delete: z.boolean().optional().describe('Delete files in destination not in source'),
@@ -976,6 +1011,10 @@ registerToolConditional(
976
1011
  remotePath = cleanSource;
977
1012
  }
978
1013
 
1014
+ // Native Windows paths must remain unchanged for fs.existsSync() and
1015
+ // logging, but MSYS2 rsync expects drive paths such as /c/project/file.
1016
+ const rsyncLocalPath = toRsyncLocalPath(localPath);
1017
+
979
1018
  // Add SSH options for non-interactive mode
980
1019
  const sshOptions = [];
981
1020
 
@@ -993,7 +1032,9 @@ registerToolConditional(
993
1032
  sshOptions.push('-o ConnectTimeout=10');
994
1033
  }
995
1034
 
996
- if (serverConfig.port && serverConfig.port !== '22') {
1035
+ // port is a number (ConfigLoader parseInt's it), so comparing against the
1036
+ // string '22' never matched and every server got an explicit -p 22.
1037
+ if (serverConfig.port && serverConfig.port !== 22) {
997
1038
  sshOptions.push(`-p ${serverConfig.port}`);
998
1039
  }
999
1040
 
@@ -1049,11 +1090,11 @@ registerToolConditional(
1049
1090
 
1050
1091
  // Add source and destination
1051
1092
  if (direction === 'push') {
1052
- rsyncArgs.push(localPath);
1093
+ rsyncArgs.push(rsyncLocalPath);
1053
1094
  rsyncArgs.push(`${serverConfig.user}@${serverConfig.host}:${remotePath}`);
1054
1095
  } else {
1055
1096
  rsyncArgs.push(`${serverConfig.user}@${serverConfig.host}:${remotePath}`);
1056
- rsyncArgs.push(localPath);
1097
+ rsyncArgs.push(rsyncLocalPath);
1057
1098
  }
1058
1099
 
1059
1100
  const rsyncProcess = spawn(rsyncCommand, rsyncArgs, {
@@ -1861,7 +1902,7 @@ function formatDuration(seconds) {
1861
1902
  registerToolConditional(
1862
1903
  'ssh_execute_group',
1863
1904
  {
1864
- description: 'Runs one command on every server belonging to the named group and returns a per-server success or failure report. Mutates remote state on each member and is not idempotent. Best-effort: the security policy of each server is evaluated independently, so readonly or restricted members are reported as failed without aborting the rest unless stopOnError is set. Strategy may be parallel, sequential, or rolling (delay applies between servers). Per-server timeout is 30000 ms; cwd defaults to the default_dir of each server.',
1905
+ description: 'Runs one command on every server belonging to the named group and returns a per-server success or failure report. Members come from the groups defined with ssh_group_manage plus every server whose configuration carries a matching group field, so a group can exist through the config alone. Mutates remote state on each member and is not idempotent. Best-effort: the security policy of each server is evaluated independently, so readonly or restricted members are reported as failed without aborting the rest unless stopOnError is set. Strategy may be parallel, sequential, or rolling (delay applies between servers). Per-server timeout is 30000 ms; cwd defaults to the default_dir of each server.',
1865
1906
  inputSchema: {
1866
1907
  group: z.string().describe('Group name (e.g., "production", "staging", "all")'),
1867
1908
  command: z.string().describe('Command to execute'),
@@ -1873,6 +1914,11 @@ registerToolConditional(
1873
1914
  },
1874
1915
  async ({ group: groupName, command, strategy, delay, stopOnError, cwd }) => {
1875
1916
  try {
1917
+ // Refresh the server config before resolving the group: membership can
1918
+ // come from the per-server `group` field, so an edited config must be
1919
+ // visible here, not only inside the per-server executor below.
1920
+ await loadServerConfig();
1921
+
1876
1922
  // Execute command on each server in the group
1877
1923
  const result = await executeOnGroup(
1878
1924
  groupName,
@@ -1985,10 +2031,29 @@ registerToolConditional(
1985
2031
  }
1986
2032
  );
1987
2033
 
2034
+ // The stored member list is only half the story: servers tagged with this group
2035
+ // in their SSH config belong to it too. Spell that out after an edit, so the
2036
+ // counts above are not read as the full set of targets.
2037
+ function formatConfigMembers(groupName, storedServers) {
2038
+ try {
2039
+ const resolved = getGroup(groupName);
2040
+ if (!resolved.fromConfig) return '';
2041
+
2042
+ const stored = new Set(storedServers.map(server => server.toLowerCase()));
2043
+ const fromConfig = resolved.servers.filter(server => !stored.has(server));
2044
+ if (fromConfig.length === 0) return '';
2045
+
2046
+ return `\n\nAlso in this group via the server config (group = "${groupName}"): ${fromConfig.join(', ')}` +
2047
+ `\nEffective target: ${resolved.servers.length} servers`;
2048
+ } catch {
2049
+ return '';
2050
+ }
2051
+ }
2052
+
1988
2053
  registerToolConditional(
1989
2054
  'ssh_group_manage',
1990
2055
  {
1991
- description: 'Creates, updates, deletes, and inspects named server groups used by ssh_execute_group, persisting changes to local configuration only with no remote side effects. The action selects the operation: create, update, delete, add-servers, remove-servers, or list. Every action except list requires name; add-servers and remove-servers also require a non-empty servers array. list is read-only. Optional strategy, delay, and stopOnError set default group execution behavior.',
2056
+ description: 'Creates, updates, deletes, and inspects named server groups used by ssh_execute_group, persisting changes to local configuration only with no remote side effects. The action selects the operation: create, update, delete, add-servers, remove-servers, or list. Every action except list requires name; add-servers and remove-servers also require a non-empty servers array. list is read-only and also reports the groups derived from the per-server group field of the SSH configuration, which are read-only here and change only by editing that configuration. Optional strategy, delay, and stopOnError set default group execution behavior.',
1992
2057
  inputSchema: {
1993
2058
  action: z.enum(['create', 'update', 'delete', 'list', 'add-servers', 'remove-servers']).describe('Action to perform'),
1994
2059
  name: z.string().optional().describe('Group name'),
@@ -2001,6 +2066,10 @@ registerToolConditional(
2001
2066
  },
2002
2067
  async ({ action, name, servers, description, strategy, delay, stopOnError }) => {
2003
2068
  try {
2069
+ // Groups can be derived from the per-server `group` field, so make sure
2070
+ // the group layer sees the current configuration before answering.
2071
+ await loadServerConfig();
2072
+
2004
2073
  let result;
2005
2074
  let output = '';
2006
2075
 
@@ -2044,6 +2113,7 @@ registerToolConditional(
2044
2113
  output = `✅ Added ${servers.length} servers to '${name}'\n`;
2045
2114
  output += `Total servers: ${result.servers.length}\n`;
2046
2115
  output += `Members: ${result.servers.join(', ')}`;
2116
+ output += formatConfigMembers(name, result.servers);
2047
2117
  break;
2048
2118
 
2049
2119
  case 'remove-servers':
@@ -2053,6 +2123,7 @@ registerToolConditional(
2053
2123
  output = `✅ Removed ${servers.length} servers from '${name}'\n`;
2054
2124
  output += `Remaining: ${result.servers.length}\n`;
2055
2125
  output += `Members: ${result.servers.join(', ') || 'none'}`;
2126
+ output += formatConfigMembers(name, result.servers);
2056
2127
  break;
2057
2128
 
2058
2129
  case 'list': {
@@ -2063,6 +2134,7 @@ registerToolConditional(
2063
2134
  groups.forEach(group => {
2064
2135
  output += `📁 ${group.name}`;
2065
2136
  if (group.dynamic) output += ' (dynamic)';
2137
+ if (group.fromConfig) output += ' (from server config)';
2066
2138
  output += '\n';
2067
2139
  output += ` Description: ${group.description}\n`;
2068
2140
  output += ` Servers: ${group.serverCount} servers\n`;
@@ -2122,7 +2194,7 @@ registerToolConditional(
2122
2194
  registerToolConditional(
2123
2195
  'ssh_list_servers',
2124
2196
  {
2125
- description: 'Lists all SSH servers defined in the loaded configuration, returning for each the name, host, user, port, authentication type (password or key), default directory, and description. Read-only and local: it reads configuration only and opens no SSH connections. Deliberately omits secrets, so no passwords, key paths, passphrases, or sudo passwords are returned. Takes no parameters. Useful as a first call to discover which server names other tools accept.',
2197
+ description: 'Lists all SSH servers defined in the loaded configuration, returning for each the name, host, user, port, authentication type (password or key), default directory, group, and description. Read-only and local: it reads configuration only and opens no SSH connections. Deliberately omits secrets, so no passwords, key paths, passphrases, or sudo passwords are returned. Takes no parameters. Useful as a first call to discover which server names other tools accept.',
2126
2198
  inputSchema: {}
2127
2199
  },
2128
2200
  async () => {
@@ -2134,6 +2206,7 @@ registerToolConditional(
2134
2206
  port: config.port || '22',
2135
2207
  auth: config.password ? 'password' : 'key',
2136
2208
  defaultDir: config.defaultDir || '',
2209
+ group: config.group || '',
2137
2210
  description: config.description || ''
2138
2211
  }));
2139
2212
 
@@ -2993,7 +3066,9 @@ registerToolConditional(
2993
3066
  }
2994
3067
  serverConfig = servers[resolvedName];
2995
3068
  host = serverConfig.host;
2996
- port = parseInt(serverConfig.port || '22');
3069
+ // port is already a number from ConfigLoader; parseInt() on it only
3070
+ // worked because JS stringifies the argument first.
3071
+ port = serverConfig.port || 22;
2997
3072
  }
2998
3073
 
2999
3074
  switch (action) {
@@ -0,0 +1,73 @@
1
+ import path from 'path';
2
+
3
+ /**
4
+ * Convert a local path into the POSIX-style path expected by an MSYS2 rsync.
5
+ *
6
+ * Node must keep using the native Windows path for filesystem checks. Only the
7
+ * argument handed to rsync is converted, otherwise a drive prefix such as
8
+ * `C:` is parsed by rsync as a remote host name.
9
+ *
10
+ * @param {string} localPath
11
+ * @param {{ platform?: NodeJS.Platform, cwd?: string }} [options]
12
+ * @returns {string}
13
+ */
14
+ export function toRsyncLocalPath(localPath, options = {}) {
15
+ const platform = options.platform ?? process.platform;
16
+ if (platform !== 'win32') return localPath;
17
+ if (localPath.length === 0) {
18
+ throw new Error('Local rsync path cannot be empty');
19
+ }
20
+
21
+ const cwd = options.cwd ?? process.cwd();
22
+
23
+ // Already in MSYS2 form — a drive mount (/c/project) or a UNC share
24
+ // (//server/share). Pass it through untouched instead of resolving it against
25
+ // the current drive, which would produce /c/c/project. Windows users hit this
26
+ // bug before it was fixed and worked around it by pre-converting their paths;
27
+ // silently double-mounting those would trade one broken path for another.
28
+ // The test is deliberately narrow: only a single-letter first segment is a
29
+ // drive mount, so a genuine rooted path such as /Users/me still converts.
30
+ if (/^\/[A-Za-z](\/|$)/.test(localPath) || localPath.startsWith('//')) {
31
+ return localPath;
32
+ }
33
+
34
+ const preserveTrailingSeparator = /[\\/]$/.test(localPath);
35
+ let nativePath = localPath;
36
+
37
+ // Normalize Windows extended-length paths before resolving them. MSYS2
38
+ // understands drive mounts and UNC paths, but not the \\?\ device prefix.
39
+ if (/^\\\\\?\\UNC\\/i.test(nativePath)) {
40
+ nativePath = `\\\\${nativePath.slice(8)}`;
41
+ } else if (/^\\\\\?\\[A-Za-z]:[\\/]/.test(nativePath)) {
42
+ nativePath = nativePath.slice(4);
43
+ } else if (/^\\\\\?\\/.test(nativePath)) {
44
+ throw new Error(`Unsupported Windows device path for rsync: ${localPath}`);
45
+ }
46
+
47
+ // Relative paths already work in MSYS2/Cygwin and must remain relative to
48
+ // the MCP process working directory. Only normalize their separators.
49
+ // Drive-relative paths (C:folder) still contain rsync's remote separator, so
50
+ // resolve those before conversion as well.
51
+ if (!path.win32.isAbsolute(nativePath) && !/^[A-Za-z]:/.test(nativePath)) {
52
+ return nativePath.replaceAll('\\', '/');
53
+ }
54
+
55
+ const absolutePath = path.win32.resolve(cwd, nativePath);
56
+ const driveMatch = /^([A-Za-z]):[\\/](.*)$/.exec(absolutePath);
57
+ let rsyncPath;
58
+
59
+ if (driveMatch) {
60
+ const [, drive, rest] = driveMatch;
61
+ rsyncPath = `/${drive.toLowerCase()}/${rest.replaceAll('\\', '/')}`;
62
+ } else if (absolutePath.startsWith('\\\\')) {
63
+ rsyncPath = `//${absolutePath.slice(2).replaceAll('\\', '/')}`;
64
+ } else {
65
+ throw new Error(`Unable to convert Windows path for rsync: ${localPath}`);
66
+ }
67
+
68
+ if (preserveTrailingSeparator && !rsyncPath.endsWith('/')) {
69
+ rsyncPath += '/';
70
+ }
71
+
72
+ return rsyncPath;
73
+ }
@@ -2,21 +2,31 @@ import fs from 'fs';
2
2
  import { ConfigLoader } from './config-loader.js';
3
3
  import { logger } from './logger.js';
4
4
 
5
+ /** @typedef {import('./config-loader.js').ServerConfig} ServerConfig */
6
+
5
7
  export class ServerConfigManager {
6
8
  constructor({ envPath, tomlPath, preferToml = false, configLoader = new ConfigLoader() }) {
7
9
  this.envPath = envPath;
8
10
  this.tomlPath = tomlPath;
9
11
  this.preferToml = preferToml;
10
12
  this.configLoader = configLoader;
13
+ /**
14
+ * Loaded servers keyed by normalized name. camelCase fields only — see the
15
+ * ServerConfig typedef in config-loader.js.
16
+ * @type {Record<string, ServerConfig>}
17
+ */
11
18
  this.servers = {};
19
+ /** @type {string|null} */
12
20
  this.fileSignature = null;
13
21
  }
14
22
 
23
+ /** @returns {Promise<Record<string, ServerConfig>>} */
15
24
  async loadInitial() {
16
25
  await this.reload();
17
26
  return this.servers;
18
27
  }
19
28
 
29
+ /** @returns {Promise<Record<string, ServerConfig>>} */
20
30
  async getServers() {
21
31
  if (this.hasFileBackedConfigChanged()) {
22
32
  await this.reload();
@@ -41,6 +51,7 @@ export class ServerConfigManager {
41
51
  preferToml: this.preferToml
42
52
  });
43
53
 
54
+ /** @type {Record<string, ServerConfig>} */
44
55
  const nextServers = {};
45
56
  for (const [name, config] of loadedServers) {
46
57
  nextServers[name] = config;