mcp-ssh-manager 3.2.1 → 3.3.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/CHANGELOG.md CHANGED
@@ -5,6 +5,34 @@ All notable changes to MCP SSH Manager will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [3.3.0] - 2026-05-02
9
+
10
+ ### Added
11
+
12
+ - **ProxyCommand support** for SOCKS5 and custom proxy connections ([#24](https://github.com/bvisible/mcp-ssh-manager/pull/24))
13
+ - New `SSH_SERVER_<NAME>_PROXYCOMMAND` env var (and `proxy_command` in TOML) to specify a custom command (e.g. `ncat --proxy 127.0.0.1:1080 --proxy-type socks5 %h %p`, `ssh -W %h:%p bastion`).
14
+ - Useful for reaching servers behind SOCKS5 proxies, custom jump hosts, or any scenario the existing `ProxyJump` doesn't cover.
15
+
16
+ ### Fixed
17
+
18
+ - **`ssh_execute` timeout silently capped at 30 s** when the requested timeout was below 300 000 ms ([#28](https://github.com/bvisible/mcp-ssh-manager/issues/28), [#29](https://github.com/bvisible/mcp-ssh-manager/pull/29) — thanks @LukasOrcik for the precise root-cause analysis and @MakksSh for the patch)
19
+ - In `execCommandWithTimeout`, the wrapped `timeout NNN sh -c …` path forwarded `otherOptions` to `ssh.execCommand` without a `timeout` key, so the underlying `SSHManager.execCommand` fell back to its hardcoded 30 000 ms default. The local stream was aborted at 30 s while the remote `timeout` wrapper was still running.
20
+ - Now passes `timeout: timeoutMs + 5000` so the inner timer always exceeds the requested timeout. The +5000 grace lets the remote `timeout` binary return exit code 124/143 first, surfacing the nicer `Command timeout after Nms` message instead of a stream abort.
21
+
22
+ - **Windows global install fails with `/bin/bash` shim error** ([#22](https://github.com/bvisible/mcp-ssh-manager/issues/22), [#23](https://github.com/bvisible/mcp-ssh-manager/pull/23) — confirmed by @Eleef on Win11 / PS7)
23
+ - npm's PowerShell shim refused to launch the legacy bash entry point because Windows has no `/bin/bash.exe`.
24
+ - New cross-platform `cli/ssh-manager.js` Node wrapper is now the `bin.ssh-manager` entry point. On Windows it probes Git Bash → WSL → `bash` on PATH (with proper `C:\…` → `/c/…` and `/mnt/c/…` path conversion); on Unix it just `spawnSync`s `bash`.
25
+
26
+ - **`server add` blocked at startup by missing `rsync`** ([#22](https://github.com/bvisible/mcp-ssh-manager/issues/22) follow-up, [#26](https://github.com/bvisible/mcp-ssh-manager/pull/26))
27
+ - `rsync` was in the **required** dependency list, but it's only used by `ssh-manager sync`. Git for Windows doesn't ship `rsync`, so the CLI was unusable on a stock Windows install for users who never call `sync`.
28
+ - `rsync` is now optional. `cmd_sync` checks lazily and emits an actionable error with install hints for macOS / Debian / Windows (MSYS2 + WSL).
29
+
30
+ - **`server add` accepted hyphens in server names, producing entries invisible to MCP clients** ([#25](https://github.com/bvisible/mcp-ssh-manager/issues/25), [#27](https://github.com/bvisible/mcp-ssh-manager/pull/27) — thanks @alexeibugrov)
31
+ - The Bash CLI used a loose regex when reading `.env` and accepted `web-server`, but POSIX env-var names disallow hyphens. The MCP Node loader uses a strict `/^SSH_SERVER_([A-Z0-9_]+)_HOST$/` and silently dropped the entry, so Claude Code reported zero servers while the CLI listed them.
32
+ - `validate_server_name` now rejects `-` (and any other non-`[A-Za-z0-9_]`) at the prompt, with a copy-paste suggestion (`web-server` → `Try 'web_server' instead`).
33
+ - `server list` detects pre-existing invalid entries, marks each affected row with `⚠ invalid`, and prints a warning block telling the user how to migrate.
34
+ - Prompt examples updated from `web-server` to `web_server` in both `server add` and the interactive wizard.
35
+
8
36
  ## [3.1.2] - 2026-02-09
9
37
 
10
38
  ### Fixed
package/CLAUDE.md CHANGED
@@ -156,6 +156,7 @@ SSH_SERVER_[NAME]_DEFAULT_DIR=/path # Optional default working directory
156
156
  SSH_SERVER_[NAME]_SUDO_PASSWORD=pass # Optional for automated sudo
157
157
  SSH_SERVER_[NAME]_PLATFORM=windows # Optional: "linux" (default) or "windows"
158
158
  SSH_SERVER_[NAME]_PROXYJUMP=bastion # Optional: name of another server to use as jump host
159
+ SSH_SERVER_[NAME]_PROXYCOMMAND=command # Optional: custom proxy command (ncat, ssh -W, etc.)
159
160
  ```
160
161
 
161
162
  ### TOML Format
@@ -171,6 +172,7 @@ default_dir = "/path" # Optional default working directory
171
172
  sudo_password = "pass" # Optional for automated sudo
172
173
  platform = "windows" # Optional: "linux" (default) or "windows"
173
174
  proxy_jump = "bastion" # Optional: name of another server to use as jump host
175
+ proxy_command = "command" # Optional: custom proxy command (ncat, ssh -W, etc.)
174
176
  ```
175
177
 
176
178
  ## Key Implementation Details
@@ -185,6 +187,8 @@ proxy_jump = "bastion" # Optional: name of another server to
185
187
 
186
188
  5. **Environment Loading**: Uses dotenv to load configuration from `.env` file in project root
187
189
 
190
+ 6. **Proxy Command Support**: Custom proxy commands (SOCKS5, ssh -W, etc.) are executed locally to establish connections, with proper error handling and timeout management (src/index.js:389-432)
191
+
188
192
  ## Security Considerations
189
193
 
190
194
  - Never commit `.env` files (included in .gitignore)
package/README.md CHANGED
@@ -1,51 +1,42 @@
1
1
  # MCP SSH Manager - SSH Remote Server Management via Model Context Protocol 🚀
2
2
 
3
- > **Looking for MCP SSH tools?** This is the **MCP SSH Manager** - a complete Model Context Protocol (MCP) server for SSH remote server management compatible with Claude Code and OpenAI Codex.
4
-
5
- A powerful Model Context Protocol (MCP) server that enables **Claude Code** and **OpenAI Codex** to manage multiple SSH connections seamlessly. Control remote servers, execute commands, transfer files, manage databases, and automate DevOps tasks directly from your AI assistant.
6
-
7
- **Keywords:** MCP SSH, MCP SSH Manager, SSH MCP, Model Context Protocol SSH, Claude Code SSH, SSH MCP Server, Remote SSH Management, MCP Server SSH
3
+ A Model Context Protocol (MCP) server that enables **Claude Code** and **OpenAI Codex** to manage multiple SSH connections. Execute commands, transfer files, manage databases, create backups, monitor health, and automate DevOps tasks across your servers — directly from your AI assistant.
8
4
 
9
5
  <div align="center">
10
6
 
11
7
  [![npm version](https://img.shields.io/npm/v/mcp-ssh-manager.svg?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/mcp-ssh-manager)
12
8
  [![npm downloads](https://img.shields.io/npm/dt/mcp-ssh-manager.svg?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/mcp-ssh-manager)
13
- [![MCP SSH Server](https://img.shields.io/badge/MCP_SSH-Server-orange?style=for-the-badge)](https://github.com/bvisible/mcp-ssh-manager)
14
- [![SSH MCP](https://img.shields.io/badge/SSH_MCP-Compatible-blue?style=for-the-badge)](https://modelcontextprotocol.io)
15
- [![Version](https://img.shields.io/badge/Version-3.2.0-brightgreen?style=for-the-badge)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.2.0)
9
+ [![Version](https://img.shields.io/badge/Version-3.2.2-brightgreen?style=for-the-badge)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.2.2)
16
10
  [![Claude Code](https://img.shields.io/badge/Claude_Code-Compatible-5A67D8?style=for-the-badge&logo=anthropic)](https://claude.ai/code)
17
11
  [![OpenAI Codex](https://img.shields.io/badge/OpenAI_Codex-Compatible-00A67E?style=for-the-badge&logo=openai)](https://openai.com/codex)
18
12
  [![MCP](https://img.shields.io/badge/MCP-Server-orange?style=for-the-badge)](https://modelcontextprotocol.io)
19
13
  [![License](https://img.shields.io/badge/License-MIT-blue?style=for-the-badge)](LICENSE)
20
14
 
21
- <a href="https://glama.ai/mcp/servers/@bvisible/mcp-ssh-manager">
22
- <img width="380" height="200" src="https://glama.ai/mcp/servers/@bvisible/mcp-ssh-manager/badge" alt="SSH Manager MCP server" />
23
- </a>
15
+ </div>
24
16
 
25
- <br/>
17
+ ---
26
18
 
27
- <a href="https://mseep.ai/app/bvisible-mcp-ssh-manager">
28
- <img src="https://mseep.net/pr/bvisible-mcp-ssh-manager-badge.png" alt="MseeP.ai Security Assessment Badge" />
29
- </a>
19
+ ## 🎉 What's New in v3.2.2
30
20
 
31
- </div>
21
+ **Global Install Fix & CLI Binary** (Released: April 7, 2026)
22
+
23
+ - **🔧 Global install fixed**: `.env` path resolution now uses a fallback chain instead of hardcoded `__dirname` — works correctly with `npm install -g` ([#16](https://github.com/bvisible/mcp-ssh-manager/issues/16), [#19](https://github.com/bvisible/mcp-ssh-manager/issues/19))
24
+ - Fallback chain: `~/.ssh-manager/.env` → `cwd/.env` → `~/.env` → project `.env`
25
+ - Auto-creates `~/.ssh-manager/.env` on first `ssh-manager server add`
26
+ - **📦 `ssh-manager` CLI registered as binary**: `npm install -g` now creates both `mcp-ssh-manager` and `ssh-manager` commands ([#18](https://github.com/bvisible/mcp-ssh-manager/issues/18))
27
+ - **⚡ Race condition fix**: Server config is now fully loaded before the MCP server accepts requests
32
28
 
33
29
  ---
34
30
 
35
- ## 🎉 What's New in v3.2.0
31
+ ## Previous Releases
36
32
 
37
- **SSH ProxyJump / Bastion Host Support & npx Fix** (Released: March 18, 2026)
33
+ ### v3.2.0 - ProxyJump / Bastion Host Support (March 18, 2026)
38
34
 
39
35
  - **🔀 ProxyJump support**: Connect to servers behind bastion/jump hosts with a simple `PROXYJUMP` config field ([#15](https://github.com/bvisible/mcp-ssh-manager/issues/15))
40
36
  - Chain multiple jumps (A → B → C) via recursive connections
41
37
  - Circular dependency detection prevents infinite loops
42
- - All tools work transparently through jump hosts (execute, upload, download, sync...)
43
- - Jump connections are pooled and reused like direct connections
44
- - **📦 npx support fixed**: Added `bin` field to `package.json` — `npx mcp-ssh-manager` now works correctly ([#14](https://github.com/bvisible/mcp-ssh-manager/issues/14))
45
-
46
- ---
47
-
48
- ## Previous Releases
38
+ - All tools work transparently through jump hosts
39
+ - **📦 npx support fixed**: `npx mcp-ssh-manager` now works correctly ([#14](https://github.com/bvisible/mcp-ssh-manager/issues/14))
49
40
 
50
41
  ### v3.1.5 - SSH Agent & Passphrase Support (March 5, 2026)
51
42
 
@@ -105,13 +96,16 @@ This release adds **12 new MCP tools** transforming SSH Manager into a comprehen
105
96
  ## 📑 Table of Contents
106
97
 
107
98
  - [Features](#-features)
99
+ - [Tool Management](#-tool-management--context-optimization)
100
+ - [Prerequisites](#-prerequisites)
108
101
  - [Quick Start - Claude Code](#-quick-start---claude-code)
109
102
  - [Quick Start - OpenAI Codex](#-quick-start---openai-codex)
110
- - [Prerequisites](#-prerequisites)
111
103
  - [Available MCP Tools](#-available-mcp-tools)
112
104
  - [Configuration](#-configuration)
113
105
  - [Usage Examples](#-usage-examples)
106
+ - [Security](#-security-best-practices)
114
107
  - [Troubleshooting](#-troubleshooting)
108
+ - [Known Limitations](#known-limitations)
115
109
  - [Contributing](#-contributing)
116
110
  - [License](#-license)
117
111
 
@@ -123,6 +117,7 @@ This release adds **12 new MCP tools** transforming SSH Manager into a comprehen
123
117
  - **🔗 Multiple SSH Connections** - Manage unlimited SSH servers from a single interface
124
118
  - **🔐 Secure Authentication** - Support for password, SSH key, and ssh-agent authentication (including passphrase-protected keys)
125
119
  - **🔀 ProxyJump / Bastion Host** - Connect to servers behind jump hosts with chained multi-hop support
120
+ - **🔌 ProxyCommand / Custom Proxy** - Connect through SOCKS5 proxies or custom proxy commands (ncat, ssh -W, etc.)
126
121
  - **📁 File Operations** - Upload and download files between local and remote systems
127
122
  - **⚡ Command Execution** - Run commands on remote servers with working directory support
128
123
  - **📂 Default Directories** - Set default working directories per server for convenience
@@ -198,22 +193,6 @@ ssh-manager tools disable backup
198
193
 
199
194
  ---
200
195
 
201
- ## 🔍 Alternative Search Terms
202
-
203
- Looking for:
204
- - **MCP SSH** server? ✅ You're in the right place
205
- - **SSH MCP** integration? ✅ This is it
206
- - **Claude Code SSH** tools? ✅ Fully compatible
207
- - **Model Context Protocol SSH** manager? ✅ Complete solution
208
- - **OpenAI Codex SSH** server? ✅ Full support
209
- - **Remote SSH MCP** server? ✅ Works seamlessly
210
- - **MCP Server for SSH**? ✅ Production ready
211
- - **SSH automation with AI**? ✅ Perfect tool
212
-
213
- This is **the** MCP SSH Manager you've been searching for! 🎯
214
-
215
- ---
216
-
217
196
  ## 📋 Prerequisites
218
197
 
219
198
  - Node.js (v18 or higher)
@@ -590,6 +569,7 @@ SSH_SERVER_[NAME]_DEFAULT_DIR=/path/to/dir # Optional, default working director
590
569
  SSH_SERVER_[NAME]_DESCRIPTION=Description # Optional
591
570
  SSH_SERVER_[NAME]_PLATFORM=windows # Optional: "linux" (default) or "windows"
592
571
  SSH_SERVER_[NAME]_PROXYJUMP=bastion # Optional: name of another server to use as jump host
572
+ SSH_SERVER_[NAME]_PROXYCOMMAND=command # Optional: custom proxy command (ncat, ssh -W, etc.)
593
573
 
594
574
  # Example: Linux server
595
575
  SSH_SERVER_PRODUCTION_HOST=prod.example.com
@@ -636,19 +616,24 @@ The Python management tool (`tools/server_manager.py`) provides:
636
616
  ```
637
617
  mcp-ssh-manager/
638
618
  ├── src/
639
- │ └── index.js # Main MCP server implementation
640
- ├── tools/
641
- │ ├── server_manager.py # Interactive server management
642
- │ ├── test-connection.py # Connection testing utility
643
- │ └── requirements.txt # Python dependencies
644
- ├── examples/
645
- │ ├── .env.example # Example configuration
646
- │ ├── claude-code-config.example.json
647
- │ ├── backup-workflow.js # Backup and restore examples
648
- │ └── codex-ssh-config.example.toml
649
- ├── package.json # Node.js dependencies
650
- ├── .env # Your server configurations (create from .env.example)
651
- └── README.md # This file
619
+ │ ├── index.js # Main MCP server (37 tools)
620
+ │ ├── ssh-manager.js # SSH connection handling
621
+ │ ├── config-loader.js # .env & TOML config loading
622
+ │ ├── session-manager.js # Persistent SSH sessions
623
+ │ ├── backup-manager.js # Backup & restore
624
+ │ ├── health-monitor.js # Health checks & alerts
625
+ │ ├── database-manager.js # Database operations
626
+ │ ├── tunnel-manager.js # SSH tunnel management
627
+ │ ├── server-groups.js # Group operations
628
+ │ └── ...
629
+ ├── cli/
630
+ │ ├── ssh-manager # Bash CLI entrypoint
631
+ │ ├── commands/ # CLI command modules
632
+ │ └── lib/ # CLI libraries
633
+ ├── profiles/ # Configuration profiles (frappe, docker, nodejs...)
634
+ ├── examples/ # Example configs
635
+ ├── docs/ # Documentation
636
+ └── package.json
652
637
  ```
653
638
 
654
639
  ## 🧪 Testing
@@ -748,6 +733,37 @@ proxy_jump = "bastion"
748
733
 
749
734
  **Chained jumps** are supported: if `bastion` itself has a `proxy_jump`, the chain is followed recursively. Circular references are detected and rejected.
750
735
 
736
+ ### ProxyCommand / Custom Proxy
737
+
738
+ Connect through SOCKS5 proxies or custom proxy commands. The proxy command executes locally and forwards traffic to the remote host.
739
+
740
+ ```env
741
+ # SOCKS5 proxy via ncat
742
+ SSH_SERVER_SOCKS_HOST=target.example.com
743
+ SSH_SERVER_SOCKS_USER=admin
744
+ SSH_SERVER_SOCKS_PROXYCOMMAND="ncat --proxy 127.0.0.1:1080 --proxy-type socks5 %h %p"
745
+
746
+ # Windows SSH proxy command
747
+ SSH_SERVER_WINPROXY_HOST=internal.example.com
748
+ SSH_SERVER_WINPROXY_USER=admin
749
+ SSH_SERVER_WINPROXY_PROXYCOMMAND="C:\Windows\System32\OpenSSH\ssh.exe -W %h:%p user@jump-host"
750
+ ```
751
+
752
+ Or in TOML:
753
+ ```toml
754
+ [ssh_servers.socks]
755
+ host = "target.example.com"
756
+ user = "admin"
757
+ proxy_command = "ncat --proxy 127.0.0.1:1080 --proxy-type socks5 %h %p"
758
+
759
+ [ssh_servers.winproxy]
760
+ host = "internal.example.com"
761
+ user = "admin"
762
+ proxy_command = "C:\\Windows\\System32\\OpenSSH\\ssh.exe -W %h:%p user@jump-host"
763
+ ```
764
+
765
+ The proxy command must be a valid command that reads from stdin and writes to stdout, accepting `%h` and `%p` placeholders for host and port.
766
+
751
767
  ### Documentation
752
768
  - [DEPLOYMENT_GUIDE.md](docs/DEPLOYMENT_GUIDE.md) - Deployment strategies and permission handling
753
769
  - [ALIASES_AND_HOOKS.md](docs/ALIASES_AND_HOOKS.md) - Command aliases and automation hooks
@@ -807,42 +823,6 @@ See [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) for complete guide.
807
823
  2. Check SSH key permissions: `chmod 600 ~/.ssh/your_key`
808
824
  3. Ensure user has necessary permissions on remote server
809
825
 
810
- ## 🛠️ Available MCP Tools
811
-
812
- Once installed in Claude Code, you'll have access to these powerful tools:
813
-
814
- ### Core Tools
815
- - `ssh_execute` - Execute commands on remote servers
816
- - `ssh_upload` - Upload files to remote servers
817
- - `ssh_download` - Download files from remote servers
818
- - `ssh_list_servers` - List all configured SSH servers
819
-
820
- ### Advanced Tools (v2.0)
821
- - `ssh_sync` - Bidirectional file synchronization with rsync
822
- - `ssh_tail` - Real-time log monitoring with follow mode
823
- - `ssh_monitor` - System metrics monitoring (CPU, RAM, disk, network)
824
- - `ssh_history` - View command execution history
825
-
826
- ### Session Management
827
- - `ssh_session_start` - Start persistent SSH session
828
- - `ssh_session_send` - Send commands to active session
829
- - `ssh_session_list` - List active sessions
830
- - `ssh_session_close` - Close specific session
831
-
832
- ### Server Groups
833
- - `ssh_execute_group` - Execute commands on server groups
834
- - `ssh_group_manage` - Manage server groups (create, update, delete)
835
-
836
- ### SSH Tunnels
837
- - `ssh_tunnel_create` - Create SSH tunnels (local, remote, SOCKS)
838
- - `ssh_tunnel_list` - List active tunnels with statistics
839
- - `ssh_tunnel_close` - Close specific or all tunnels
840
-
841
- ### Deployment & Security
842
- - `ssh_deploy` - Smart deployment with permission handling
843
- - `ssh_execute_sudo` - Execute commands with sudo privileges
844
- - `ssh_alias` - Manage server aliases
845
-
846
826
  ## 📚 Usage Examples
847
827
 
848
828
  ### Backup & Restore
@@ -939,16 +919,8 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
939
919
  - SSH handling via [node-ssh](https://www.npmjs.com/package/node-ssh)
940
920
  - Server management with [Paramiko](https://www.paramiko.org)
941
921
 
942
- ## 📧 Support
943
-
944
- For issues, questions, or suggestions:
945
- - Open an issue on [GitHub Issues](https://github.com/yourusername/mcp-ssh-manager/issues)
946
- - Check existing issues before creating new ones
947
-
948
922
  ---
949
923
 
950
- Made with ❤️ for the Claude Code community
951
-
952
924
  ## Known Limitations
953
925
 
954
926
  ### Command Timeout
@@ -967,7 +939,28 @@ Made with ❤️ for the Claude Code community
967
939
  - If a connection becomes stale, it will be automatically reconnected on next use
968
940
  - Force reconnection by using the `ssh_connection_status` tool with `reconnect` action
969
941
 
970
- ## Support
942
+ ## 📧 Support
943
+
944
+ For issues, questions, or suggestions:
945
+ - Open an issue on [GitHub Issues](https://github.com/bvisible/mcp-ssh-manager/issues)
946
+ - Check existing issues before creating new ones
947
+
948
+ ---
949
+
950
+ <div align="center">
951
+
952
+ Made with ❤️ for the Claude Code community
953
+
954
+ <br/><br/>
955
+
956
+ <a href="https://glama.ai/mcp/servers/@bvisible/mcp-ssh-manager">
957
+ <img width="380" height="200" src="https://glama.ai/mcp/servers/@bvisible/mcp-ssh-manager/badge" alt="SSH Manager MCP server" />
958
+ </a>
959
+
960
+ <br/>
971
961
 
972
- For issues, feature requests, or contributions, please visit:
973
- https://github.com/bvisible/mcp-ssh-manager
962
+ <a href="https://mseep.ai/app/bvisible-mcp-ssh-manager">
963
+ <img src="https://mseep.net/pr/bvisible-mcp-ssh-manager-badge.png" alt="MseeP.ai Security Assessment Badge" />
964
+ </a>
965
+
966
+ </div>
@@ -8,7 +8,7 @@ cmd_server_add() {
8
8
  # Get server name
9
9
  local server_name
10
10
  while true; do
11
- prompt_input "Server name (e.g., prod1, web-server)" "" "server_name"
11
+ prompt_input "Server name (e.g., prod1, web_server) — letters, digits, underscore only" "" "server_name"
12
12
  if validate_server_name "$server_name"; then
13
13
  break
14
14
  fi
@@ -81,35 +81,62 @@ cmd_server_add() {
81
81
  # List all servers
82
82
  cmd_server_list() {
83
83
  print_header "SSH Servers"
84
-
84
+
85
85
  local servers=($(load_servers))
86
-
86
+
87
87
  if [ ${#servers[@]} -eq 0 ]; then
88
88
  print_warning "No servers configured"
89
89
  print_info "Use 'ssh-manager server add' to add a server"
90
90
  return 0
91
91
  fi
92
-
92
+
93
+ # Collect names invisible to the MCP loader (#25) so we can mark them.
94
+ local invalid_names=()
95
+ while IFS= read -r n; do
96
+ [ -n "$n" ] && invalid_names+=("$n")
97
+ done < <(list_invalid_server_names)
98
+
93
99
  print_table_header "NAME" "HOST" "USER"
94
-
100
+
95
101
  for server in "${servers[@]}"; do
96
102
  local host=$(get_server_config "$server" "HOST")
97
103
  local user=$(get_server_config "$server" "USER")
98
104
  local port=$(get_server_config "$server" "PORT")
99
105
  local description=$(get_server_config "$server" "DESCRIPTION")
100
-
106
+
101
107
  port=${port:-22}
102
-
108
+
103
109
  local host_info="$host:$port"
104
110
  if [ -n "$description" ]; then
105
111
  host_info="$host_info ($description)"
106
112
  fi
107
-
108
- print_table_row "$server" "$host_info" "$user"
113
+
114
+ # Mark entries invisible to the MCP loader.
115
+ local display_name="$server"
116
+ local is_invalid=0
117
+ for inv in "${invalid_names[@]}"; do
118
+ if [ "$inv" = "$server" ]; then
119
+ is_invalid=1
120
+ break
121
+ fi
122
+ done
123
+ if [ "$is_invalid" = "1" ]; then
124
+ display_name="$server ⚠ invalid"
125
+ fi
126
+
127
+ print_table_row "$display_name" "$host_info" "$user"
109
128
  done
110
-
129
+
111
130
  echo
112
131
  print_info "Total servers: ${#servers[@]}"
132
+
133
+ if [ ${#invalid_names[@]} -gt 0 ]; then
134
+ echo
135
+ print_warning "${#invalid_names[@]} server(s) have names that are invisible to MCP clients (Claude Code, etc.)"
136
+ print_info "Names with characters other than letters/digits/underscore produce invalid env vars"
137
+ print_info "Affected: ${invalid_names[*]}"
138
+ print_info "Fix: 'ssh-manager server remove <name>' then re-add with a valid name (e.g. replace '-' with '_')"
139
+ fi
113
140
  }
114
141
 
115
142
  # Test server connection
package/cli/install.sh CHANGED
@@ -22,7 +22,7 @@ echo
22
22
  echo -e "${YELLOW}Checking dependencies...${NC}"
23
23
  missing=()
24
24
 
25
- for cmd in ssh rsync; do
25
+ for cmd in ssh; do
26
26
  if command -v "$cmd" >/dev/null 2>&1; then
27
27
  echo -e " ${GREEN}✓${NC} $cmd"
28
28
  else
@@ -31,7 +31,9 @@ for cmd in ssh rsync; do
31
31
  fi
32
32
  done
33
33
 
34
- for cmd in jq sshpass; do
34
+ # rsync is only used by `ssh-manager sync`; not bundled with Git Bash on Windows.
35
+ # Treat as optional so the CLI is usable without it.
36
+ for cmd in rsync jq sshpass; do
35
37
  if command -v "$cmd" >/dev/null 2>&1; then
36
38
  echo -e " ${GREEN}✓${NC} $cmd"
37
39
  else
package/cli/lib/config.sh CHANGED
@@ -5,20 +5,39 @@
5
5
  export SSH_MANAGER_HOME="${SSH_MANAGER_HOME:-$HOME/.ssh-manager}"
6
6
  export SSH_MANAGER_CONFIG="$SSH_MANAGER_HOME/config.json"
7
7
 
8
- # Resolve .env path - handle both direct and symlinked execution
8
+ # Resolve .env path with fallback chain (consistent with src/index.js):
9
+ # 1. SSH_MANAGER_ENV env var (explicit override)
10
+ # 2. ~/.ssh-manager/.env (user config directory — preferred for global installs)
11
+ # 3. $PWD/.env (current working directory)
12
+ # 4. ~/.env (home directory)
13
+ # 5. <project-root>/.env (backward compat for local/dev installs)
9
14
  if [ -z "$SSH_MANAGER_ENV" ]; then
10
- if [ -n "$SCRIPT_DIR" ]; then
11
- # Called from main ssh-manager script
12
- SSH_MANAGER_ENV="$(dirname "$SCRIPT_DIR")/.env"
15
+ if [ -f "$SSH_MANAGER_HOME/.env" ]; then
16
+ SSH_MANAGER_ENV="$SSH_MANAGER_HOME/.env"
17
+ elif [ -f "$PWD/.env" ]; then
18
+ SSH_MANAGER_ENV="$PWD/.env"
19
+ elif [ -f "$HOME/.env" ]; then
20
+ SSH_MANAGER_ENV="$HOME/.env"
13
21
  else
14
- # Called directly - need to resolve path ourselves
15
- if [ -L "$0" ]; then
16
- REAL_PATH="$(readlink -f "$0" 2>/dev/null || readlink "$0")"
22
+ # Resolve project root from script location (works for local installs)
23
+ if [ -n "$SCRIPT_DIR" ]; then
24
+ _PROJECT_ENV="$(dirname "$SCRIPT_DIR")/.env"
17
25
  else
18
- REAL_PATH="$0"
26
+ if [ -L "$0" ]; then
27
+ _REAL_PATH="$(readlink -f "$0" 2>/dev/null || readlink "$0")"
28
+ else
29
+ _REAL_PATH="$0"
30
+ fi
31
+ _REAL_DIR="$(cd "$(dirname "$_REAL_PATH")" && pwd)"
32
+ _PROJECT_ENV="$(dirname "$(dirname "$_REAL_DIR")")/.env"
19
33
  fi
20
- REAL_DIR="$(cd "$(dirname "$REAL_PATH")" && pwd)"
21
- SSH_MANAGER_ENV="$(dirname "$(dirname "$REAL_DIR")")/.env"
34
+ if [ -f "$_PROJECT_ENV" ]; then
35
+ SSH_MANAGER_ENV="$_PROJECT_ENV"
36
+ else
37
+ # Default to user config directory (will be created on first server add)
38
+ SSH_MANAGER_ENV="$SSH_MANAGER_HOME/.env"
39
+ fi
40
+ unset _PROJECT_ENV _REAL_PATH _REAL_DIR
22
41
  fi
23
42
  export SSH_MANAGER_ENV
24
43
  fi
@@ -154,9 +173,13 @@ add_server_to_env() {
154
173
  return 1
155
174
  fi
156
175
 
176
+ # Ensure parent directory and .env file exist
177
+ mkdir -p "$(dirname "$SSH_MANAGER_ENV")"
178
+ touch "$SSH_MANAGER_ENV"
179
+
157
180
  # Backup .env file
158
181
  cp "$SSH_MANAGER_ENV" "$SSH_MANAGER_ENV.bak"
159
-
182
+
160
183
  # Add server configuration
161
184
  {
162
185
  echo ""
@@ -316,59 +339,123 @@ test_ssh_connection() {
316
339
  }
317
340
 
318
341
  # Validate server name
342
+ #
343
+ # Server names are baked into POSIX environment variable names of the form
344
+ # SSH_SERVER_<NAME>_HOST. POSIX env-var names are restricted to letters,
345
+ # digits and underscore — hyphens are NOT valid (issue #25). Allowing them
346
+ # silently produced keys like SSH_SERVER_WEB-SERVER_HOST that the Bash CLI
347
+ # happily wrote and re-read, but the MCP Node loader (which uses a strict
348
+ # /^SSH_SERVER_([A-Z0-9_]+)_HOST$/ regex) silently dropped — so the server
349
+ # appeared in `ssh-manager server list` but Claude Code saw zero servers.
350
+ #
351
+ # We now reject hyphens at the source. If a user pasted in a name with a
352
+ # hyphen, we suggest the underscore equivalent in the error message so the
353
+ # fix is one keystroke away.
319
354
  validate_server_name() {
320
355
  local name="$1"
321
-
356
+
322
357
  # Check if name is empty
323
358
  if [ -z "$name" ]; then
324
359
  print_error "Server name cannot be empty"
325
360
  return 1
326
361
  fi
327
-
328
- # Check for invalid characters
329
- if ! [[ "$name" =~ ^[a-zA-Z0-9_-]+$ ]]; then
330
- print_error "Server name can only contain letters, numbers, underscore and hyphen"
362
+
363
+ # Reject hyphens with a targeted message and a copy-paste suggestion.
364
+ if [[ "$name" == *-* ]]; then
365
+ local suggested="${name//-/_}"
366
+ print_error "Server name cannot contain '-' (POSIX env var names allow only letters, digits, underscore)"
367
+ print_info "Try '$suggested' instead"
331
368
  return 1
332
369
  fi
333
-
370
+
371
+ # Catch any other invalid characters
372
+ if ! [[ "$name" =~ ^[a-zA-Z0-9_]+$ ]]; then
373
+ print_error "Server name can only contain letters, digits and underscore"
374
+ return 1
375
+ fi
376
+
334
377
  # Check if name starts with a letter
335
378
  if ! [[ "$name" =~ ^[a-zA-Z] ]]; then
336
379
  print_error "Server name must start with a letter"
337
380
  return 1
338
381
  fi
339
-
382
+
340
383
  return 0
341
384
  }
342
385
 
386
+ # Detect server entries in .env whose names contain characters that are
387
+ # silently dropped by the MCP Node loader. Used by `server list` to flag
388
+ # legacy entries created before the validation fix in #25.
389
+ # Echoes one invalid name per line.
390
+ list_invalid_server_names() {
391
+ if [ ! -f "$SSH_MANAGER_ENV" ]; then
392
+ return 0
393
+ fi
394
+ while IFS= read -r line; do
395
+ if [[ "$line" =~ ^SSH_SERVER_(.+)_HOST= ]]; then
396
+ local raw="${BASH_REMATCH[1]}"
397
+ if ! [[ "$raw" =~ ^[A-Za-z0-9_]+$ ]]; then
398
+ # Lowercase, matching load_servers' output convention
399
+ printf '%s\n' "$(echo "$raw" | tr '[:upper:]' '[:lower:]')"
400
+ fi
401
+ fi
402
+ done < "$SSH_MANAGER_ENV" | sort -u
403
+ }
404
+
343
405
  # Check dependencies
406
+ # Only `ssh` is strictly required for the CLI to start.
407
+ # rsync is only needed by `ssh-manager sync`; on Windows + Git Bash it is not
408
+ # bundled by default, so requiring it here would block every other command
409
+ # (server add/list/test, exec, ssh, tunnel...). It is checked lazily by
410
+ # `cmd_sync` instead.
344
411
  check_dependencies() {
345
412
  local missing=()
346
-
413
+
347
414
  # Check for required commands
348
- for cmd in ssh rsync; do
415
+ for cmd in ssh; do
349
416
  if ! command -v "$cmd" >/dev/null 2>&1; then
350
417
  missing+=("$cmd")
351
418
  fi
352
419
  done
353
-
420
+
354
421
  # Check for optional but recommended commands
355
422
  local optional=()
356
- for cmd in jq sshpass; do
423
+ for cmd in rsync jq sshpass; do
357
424
  if ! command -v "$cmd" >/dev/null 2>&1; then
358
425
  optional+=("$cmd")
359
426
  fi
360
427
  done
361
-
428
+
362
429
  if [ ${#missing[@]} -gt 0 ]; then
363
430
  print_error "Missing required dependencies: ${missing[*]}"
364
431
  print_info "Please install them and try again"
365
432
  return 1
366
433
  fi
367
-
434
+
368
435
  if [ ${#optional[@]} -gt 0 ]; then
369
436
  print_warning "Missing optional dependencies: ${optional[*]}"
370
- print_info "Some features may not work without them"
437
+ print_info "Some features may not work without them (rsync is needed for 'ssh-manager sync')"
438
+ fi
439
+
440
+ return 0
441
+ }
442
+
443
+ # Ensure a specific command is available; print an actionable error if not.
444
+ # Used by commands with feature-specific dependencies (e.g. cmd_sync needs rsync).
445
+ require_command() {
446
+ local cmd="$1"
447
+ local feature="${2:-this command}"
448
+ if ! command -v "$cmd" >/dev/null 2>&1; then
449
+ print_error "'$cmd' is required for $feature but was not found on PATH"
450
+ case "$cmd" in
451
+ rsync)
452
+ print_info "Install rsync:"
453
+ print_info " • macOS: brew install rsync"
454
+ print_info " • Debian: sudo apt-get install rsync"
455
+ print_info " • Windows: install via MSYS2/Cygwin, or use WSL"
456
+ ;;
457
+ esac
458
+ return 1
371
459
  fi
372
-
373
460
  return 0
374
461
  }
package/cli/lib/menu.sh CHANGED
@@ -80,7 +80,8 @@ wizard_add_server() {
80
80
  # Step 1: Server name
81
81
  print_subheader "Step 1: Server Identification"
82
82
  echo "Choose a short, memorable name for this server."
83
- echo "Examples: prod1, web-server, database, staging"
83
+ echo "Letters, digits and underscore only — no hyphens (POSIX env var rule)."
84
+ echo "Examples: prod1, web_server, database, staging"
84
85
  echo
85
86
 
86
87
  local server_name
package/cli/ssh-manager CHANGED
@@ -159,11 +159,15 @@ cmd_sync() {
159
159
  local server="$2"
160
160
  local source="$3"
161
161
  local dest="$4"
162
-
162
+
163
163
  if [ -z "$direction" ] || [ -z "$server" ] || [ -z "$source" ] || [ -z "$dest" ]; then
164
164
  print_error "Usage: ssh-manager sync <push|pull> <server> <source> <destination>"
165
165
  return 1
166
166
  fi
167
+
168
+ # rsync is only required at this point — fail with a clear message
169
+ # rather than blocking the whole CLI at startup.
170
+ require_command rsync "ssh-manager sync" || return 1
167
171
 
168
172
  local host=$(get_server_config "$server" "HOST")
169
173
  local user=$(get_server_config "$server" "USER")
@@ -0,0 +1,174 @@
1
+ #!/usr/bin/env node
2
+ // Cross-platform entry point for the `ssh-manager` CLI.
3
+ //
4
+ // The real CLI is implemented as a Bash script (cli/ssh-manager). On Unix-like
5
+ // systems we simply forward to it. On Windows, npm cannot create a usable shim
6
+ // for a Bash shebang, so this Node wrapper locates a usable Bash interpreter
7
+ // (Git Bash, WSL, or a bash on PATH) and invokes the script with the correct
8
+ // path conversion.
9
+ //
10
+ // See: https://github.com/bvisible/mcp-ssh-manager/issues/22
11
+
12
+ import { spawnSync } from 'node:child_process';
13
+ import { existsSync } from 'node:fs';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { dirname, join, resolve } from 'node:path';
16
+ import { platform } from 'node:os';
17
+
18
+ const __filename = fileURLToPath(import.meta.url);
19
+ const __dirname = dirname(__filename);
20
+ const bashScript = resolve(__dirname, 'ssh-manager');
21
+
22
+ if (!existsSync(bashScript)) {
23
+ console.error(`[ssh-manager] Unable to locate CLI script at: ${bashScript}`);
24
+ process.exit(1);
25
+ }
26
+
27
+ const isWindows = platform() === 'win32';
28
+ const args = process.argv.slice(2);
29
+
30
+ /**
31
+ * Convert a Windows-style path (C:\foo\bar) into a POSIX-style path
32
+ * understood by Git Bash / MSYS (/c/foo/bar). Leaves non-Windows paths alone.
33
+ */
34
+ function toPosixPath(winPath) {
35
+ const match = /^([A-Za-z]):[\\/](.*)$/.exec(winPath);
36
+ if (!match) return winPath.replace(/\\/g, '/');
37
+ const drive = match[1].toLowerCase();
38
+ const rest = match[2].replace(/\\/g, '/');
39
+ return `/${drive}/${rest}`;
40
+ }
41
+
42
+ /**
43
+ * Convert a Windows-style path into a WSL-style path (/mnt/c/foo/bar).
44
+ */
45
+ function toWslPath(winPath) {
46
+ const match = /^([A-Za-z]):[\\/](.*)$/.exec(winPath);
47
+ if (!match) return winPath.replace(/\\/g, '/');
48
+ const drive = match[1].toLowerCase();
49
+ const rest = match[2].replace(/\\/g, '/');
50
+ return `/mnt/${drive}/${rest}`;
51
+ }
52
+
53
+ /**
54
+ * Try to locate a Git Bash executable on Windows.
55
+ * Returns an absolute path or null if none is found.
56
+ */
57
+ function findGitBash() {
58
+ const candidates = [
59
+ process.env.ProgramFiles && join(process.env.ProgramFiles, 'Git', 'bin', 'bash.exe'),
60
+ process.env['ProgramFiles(x86)'] && join(process.env['ProgramFiles(x86)'], 'Git', 'bin', 'bash.exe'),
61
+ process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, 'Programs', 'Git', 'bin', 'bash.exe'),
62
+ 'C:\\Program Files\\Git\\bin\\bash.exe',
63
+ 'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
64
+ ].filter(Boolean);
65
+
66
+ for (const candidate of candidates) {
67
+ if (existsSync(candidate)) return candidate;
68
+ }
69
+ return null;
70
+ }
71
+
72
+ /**
73
+ * Check whether WSL is available by running `wsl.exe --status`.
74
+ */
75
+ function hasWsl() {
76
+ try {
77
+ const result = spawnSync('wsl.exe', ['--status'], { stdio: 'ignore' });
78
+ return result.status === 0;
79
+ } catch {
80
+ return false;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Check whether `bash` is on PATH (covers Unix and some Windows setups).
86
+ */
87
+ function hasBashOnPath() {
88
+ const probe = isWindows ? 'where' : 'which';
89
+ try {
90
+ const result = spawnSync(probe, ['bash'], { stdio: 'ignore' });
91
+ return result.status === 0;
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
96
+
97
+ function runUnix() {
98
+ const result = spawnSync('bash', [bashScript, ...args], {
99
+ stdio: 'inherit',
100
+ });
101
+ if (result.error) {
102
+ console.error(`[ssh-manager] Failed to execute bash: ${result.error.message}`);
103
+ process.exit(1);
104
+ }
105
+ process.exit(result.status ?? 0);
106
+ }
107
+
108
+ function runWindows() {
109
+ // 1. Prefer Git Bash — it understands MSYS-style paths natively.
110
+ const gitBash = findGitBash();
111
+ if (gitBash) {
112
+ const posixScript = toPosixPath(bashScript);
113
+ const result = spawnSync(gitBash, [posixScript, ...args], {
114
+ stdio: 'inherit',
115
+ });
116
+ if (result.error) {
117
+ console.error(`[ssh-manager] Failed to run Git Bash: ${result.error.message}`);
118
+ process.exit(1);
119
+ }
120
+ process.exit(result.status ?? 0);
121
+ }
122
+
123
+ // 2. Fall back to WSL — the script lives on the Windows filesystem, so we
124
+ // translate C:\... into /mnt/c/... before invoking it.
125
+ if (hasWsl()) {
126
+ const wslScript = toWslPath(bashScript);
127
+ const result = spawnSync('wsl.exe', ['bash', wslScript, ...args], {
128
+ stdio: 'inherit',
129
+ });
130
+ if (result.error) {
131
+ console.error(`[ssh-manager] Failed to run WSL bash: ${result.error.message}`);
132
+ process.exit(1);
133
+ }
134
+ process.exit(result.status ?? 0);
135
+ }
136
+
137
+ // 3. Last resort: a `bash` on PATH (e.g. custom MSYS2 install).
138
+ if (hasBashOnPath()) {
139
+ const result = spawnSync('bash', [bashScript, ...args], {
140
+ stdio: 'inherit',
141
+ });
142
+ if (result.error) {
143
+ console.error(`[ssh-manager] Failed to run bash: ${result.error.message}`);
144
+ process.exit(1);
145
+ }
146
+ process.exit(result.status ?? 0);
147
+ }
148
+
149
+ // Nothing worked — print an actionable message.
150
+ console.error(`
151
+ [ssh-manager] No compatible Bash interpreter was found on this Windows system.
152
+
153
+ The \`ssh-manager\` CLI is implemented as a Bash script and requires one of:
154
+
155
+ 1. Git for Windows (recommended)
156
+ Download: https://git-scm.com/download/win
157
+ This ships a Git Bash that \`ssh-manager\` can use transparently.
158
+
159
+ 2. Windows Subsystem for Linux (WSL)
160
+ Install with: wsl --install
161
+ Then re-run \`ssh-manager\`.
162
+
163
+ Note: the MCP server itself (\`mcp-ssh-manager\`) is pure Node.js and works on
164
+ Windows without any of the above. Only the interactive \`ssh-manager\` CLI
165
+ needs a Bash environment.
166
+ `);
167
+ process.exit(1);
168
+ }
169
+
170
+ if (isWindows) {
171
+ runWindows();
172
+ } else {
173
+ runUnix();
174
+ }
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "mcp-ssh-manager",
3
- "version": "3.2.1",
3
+ "version": "3.3.0",
4
4
  "description": "MCP SSH Manager: Model Context Protocol server for SSH remote server management. Control SSH connections from Claude Code and OpenAI Codex - execute commands, transfer files, database operations, backups, health monitoring, and DevOps automation. NEW: Tool activation system reduces context usage by 92%",
5
5
  "main": "src/index.js",
6
6
  "bin": {
7
- "mcp-ssh-manager": "src/index.js"
7
+ "mcp-ssh-manager": "src/index.js",
8
+ "ssh-manager": "cli/ssh-manager.js"
8
9
  },
9
10
  "type": "module",
10
11
  "scripts": {
@@ -94,6 +94,7 @@ export class ConfigLoader {
94
94
  description: serverConfig.description,
95
95
  platform: serverConfig.platform ? serverConfig.platform.toLowerCase() : undefined,
96
96
  proxyJump: serverConfig.proxy_jump,
97
+ proxyCommand: serverConfig.proxy_command || serverConfig.proxycommand,
97
98
  source: 'toml'
98
99
  });
99
100
  }
@@ -143,6 +144,7 @@ export class ConfigLoader {
143
144
  description: env[`SSH_SERVER_${match[1]}_DESCRIPTION`],
144
145
  platform: (env[`SSH_SERVER_${match[1]}_PLATFORM`] || '').toLowerCase() || undefined,
145
146
  proxyJump: env[`SSH_SERVER_${match[1]}_PROXYJUMP`],
147
+ proxyCommand: env[`SSH_SERVER_${match[1]}_PROXYCOMMAND`],
146
148
  source: 'env'
147
149
  };
148
150
 
@@ -196,6 +198,7 @@ export class ConfigLoader {
196
198
  if (server.description) serverConfig.description = server.description;
197
199
  if (server.platform) serverConfig.platform = server.platform;
198
200
  if (server.proxyJump) serverConfig.proxy_jump = server.proxyJump;
201
+ if (server.proxyCommand) serverConfig.proxy_command = server.proxyCommand;
199
202
 
200
203
  config.ssh_servers[name] = serverConfig;
201
204
  }
@@ -225,6 +228,7 @@ export class ConfigLoader {
225
228
  if (server.description) lines.push(`SSH_SERVER_${upperName}_DESCRIPTION="${server.description}"`);
226
229
  if (server.platform) lines.push(`SSH_SERVER_${upperName}_PLATFORM=${server.platform}`);
227
230
  if (server.proxyJump) lines.push(`SSH_SERVER_${upperName}_PROXYJUMP=${server.proxyJump}`);
231
+ if (server.proxyCommand) lines.push(`SSH_SERVER_${upperName}_PROXYCOMMAND=${server.proxyCommand}`);
228
232
  lines.push('');
229
233
  }
230
234
 
package/src/index.js CHANGED
@@ -166,14 +166,17 @@ const __dirname = path.dirname(__filename);
166
166
 
167
167
  // Resolve .env file path with fallback chain:
168
168
  // 1. SSH_ENV_PATH env var (explicit override)
169
- // 2. process.cwd()/.env (standard working directory)
170
- // 3. ~/.env (home directory, where ssh-manager server add writes)
171
- // 4. __dirname/../.env (backward compat for local installs)
169
+ // 2. ~/.ssh-manager/.env (user config dir — where ssh-manager CLI writes)
170
+ // 3. process.cwd()/.env (standard working directory)
171
+ // 4. ~/.env (home directory)
172
+ // 5. __dirname/../.env (backward compat for local installs)
172
173
  function resolveEnvFilePath() {
173
174
  if (process.env.SSH_ENV_PATH) {
174
175
  return process.env.SSH_ENV_PATH;
175
176
  }
177
+ const sshManagerHome = process.env.SSH_MANAGER_HOME || path.join(os.homedir(), '.ssh-manager');
176
178
  const candidates = [
179
+ path.join(sshManagerHome, '.env'),
177
180
  path.join(process.cwd(), '.env'),
178
181
  path.join(os.homedir(), '.env'),
179
182
  path.join(__dirname, '..', '.env'),
@@ -183,7 +186,6 @@ function resolveEnvFilePath() {
183
186
  return candidate;
184
187
  }
185
188
  }
186
- // Default to cwd (consistent with config-loader.js)
187
189
  return path.join(process.cwd(), '.env');
188
190
  }
189
191
 
@@ -249,6 +251,10 @@ const KEEPALIVE_INTERVAL = 5 * 60 * 1000;
249
251
  // Map to store keepalive intervals
250
252
  const keepaliveIntervals = new Map();
251
253
 
254
+ // Extra grace window so the remote `timeout` wrapper can exit cleanly
255
+ // and return its timeout exit code before the local SSH exec timeout fires.
256
+ const WRAPPED_COMMAND_TIMEOUT_GRACE_MS = 5000;
257
+
252
258
  // Map to track proxy jump dependencies (target -> jump server)
253
259
  const jumpDependencies = new Map();
254
260
 
@@ -275,7 +281,10 @@ async function execCommandWithTimeout(ssh, command, options = {}, timeoutMs = 30
275
281
  const wrappedCommand = `timeout ${timeoutSeconds} sh -c '${command.replace(/'/g, '\'\\\'\'')}'`;
276
282
 
277
283
  try {
278
- const result = await ssh.execCommand(wrappedCommand, otherOptions);
284
+ const result = await ssh.execCommand(wrappedCommand, {
285
+ ...otherOptions,
286
+ timeout: timeoutMs + WRAPPED_COMMAND_TIMEOUT_GRACE_MS
287
+ });
279
288
 
280
289
  // Check if timeout occurred (exit code 124 on Linux, 124 or 143 on Mac)
281
290
  if (result.code === 124 || result.code === 143) {
@@ -383,6 +392,56 @@ function cleanupOldConnections() {
383
392
  }
384
393
  }
385
394
 
395
+ // Create a socket from a proxy command (e.g., "ncat --proxy 127.0.0.1:1080 --proxy-type socks5 %h %p")
396
+ // The command is executed through the system shell, matching OpenSSH ProxyCommand semantics,
397
+ // so quoted arguments and shell metacharacters work as users expect.
398
+ async function createProxyCommandSocket(proxyCommand, host, port) {
399
+ const { spawn } = await import('child_process');
400
+ const { Duplex } = await import('stream');
401
+
402
+ const cmd = proxyCommand.replace(/%h/g, host).replace(/%p/g, port.toString());
403
+
404
+ return new Promise((resolve, reject) => {
405
+ const child = spawn(cmd, {
406
+ shell: true,
407
+ stdio: ['pipe', 'pipe', 'pipe']
408
+ });
409
+
410
+ const socket = Duplex.from({
411
+ readable: child.stdout,
412
+ writable: child.stdin,
413
+ allowHalfOpen: false
414
+ });
415
+
416
+ // Forward proxy stderr to the MCP server's stderr for debugging
417
+ child.stderr.on('data', (chunk) => {
418
+ process.stderr.write(`[proxy-command] ${chunk}`);
419
+ });
420
+
421
+ let settled = false;
422
+ const settle = (fn, arg) => {
423
+ if (settled) return;
424
+ settled = true;
425
+ fn(arg);
426
+ };
427
+
428
+ socket.on('close', () => {
429
+ if (!child.killed) child.kill();
430
+ });
431
+
432
+ child.on('error', (err) => settle(reject, err));
433
+ child.on('spawn', () => settle(resolve, socket));
434
+ child.on('exit', (code, signal) => {
435
+ // Only surface unexpected exits — a kill() after a successful connection is normal.
436
+ if (!settled && code !== 0) {
437
+ settle(reject, new Error(`Proxy command exited with code ${code}${signal ? ` (${signal})` : ''}`));
438
+ } else if (settled && code !== 0 && !signal && !socket.destroyed) {
439
+ socket.destroy(new Error(`Proxy command exited with code ${code}`));
440
+ }
441
+ });
442
+ });
443
+ }
444
+
386
445
  // Get or create SSH connection with reconnection support
387
446
  async function getConnection(serverName) {
388
447
  const servers = loadServerConfig();
@@ -463,6 +522,14 @@ async function getConnection(serverName) {
463
522
  await ssh.connect({ sock: stream });
464
523
  jumpDependencies.set(normalizedName, jumpServerName);
465
524
  ssh.jumpConnection = jumpSSH;
525
+ } else if (serverConfig.proxyCommand) {
526
+ // Create socket via proxy command (e.g., SOCKS5 proxy)
527
+ const socket = await createProxyCommandSocket(
528
+ serverConfig.proxyCommand,
529
+ serverConfig.host,
530
+ serverConfig.port || 22
531
+ );
532
+ await ssh.connect({ sock: socket });
466
533
  } else {
467
534
  await ssh.connect();
468
535
  }
@@ -477,7 +544,8 @@ async function getConnection(serverName) {
477
544
  host: serverConfig.host,
478
545
  port: serverConfig.port,
479
546
  method: serverConfig.password ? 'password' : 'key',
480
- proxyJump: serverConfig.proxyJump || null
547
+ proxyJump: serverConfig.proxyJump || null,
548
+ proxyCommand: serverConfig.proxyCommand ? '<set>' : null
481
549
  });
482
550
 
483
551
  // Execute post-connect hook