mcp-ssh-manager 3.2.2 → 3.4.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 +46 -0
- package/CLAUDE.md +4 -0
- package/README.md +123 -102
- package/cli/commands/server.sh +37 -10
- package/cli/install.sh +4 -2
- package/cli/lib/config.sh +79 -15
- package/cli/lib/menu.sh +2 -1
- package/cli/ssh-manager +5 -1
- package/cli/ssh-manager.js +174 -0
- package/docs/images/ssh-manager-cli-menu.png +0 -0
- package/package.json +2 -2
- package/src/config-loader.js +4 -0
- package/src/index.js +138 -15
- package/src/session-manager.js +30 -29
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,52 @@ 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.4.0] - 2026-05-07
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **Full Windows OpenSSH command execution** ([#31](https://github.com/bvisible/mcp-ssh-manager/pull/31) — thanks @WenKingSu)
|
|
13
|
+
- When a server is configured with `platform = "windows"`, commands are now wrapped as `powershell -NoProfile -OutputFormat Text -EncodedCommand <utf16le-base64>`. This is the same approach used by Ansible, Chef, and Puppet for Windows remote execution. It sidesteps every `cmd.exe` quoting and OEM code page issue (CP950, CP932, CP1252…) that was causing mojibake on non-ASCII output.
|
|
14
|
+
- Prepends `$ProgressPreference='SilentlyContinue'` (suppresses CLIXML progress sentinels in stderr) and `[Console]::OutputEncoding=UTF8` (forces clean UTF-8 stdout).
|
|
15
|
+
- Working-directory prefix uses `Set-Location '${escapedDir}'; ${cmd}` (PowerShell-native, with `'` → `''` escaping) instead of `cd ${dir} && ${cmd}` which is invalid in `cmd.exe`. Applied consistently across `ssh_execute`, `ssh_execute_group`, and `ssh_execute_sudo`.
|
|
16
|
+
- Strictly gated behind `platform === 'windows'` — Linux/macOS targets are completely unaffected.
|
|
17
|
+
|
|
18
|
+
### Fixed
|
|
19
|
+
|
|
20
|
+
- **`ssh_session_start` timing out on real-world shells** ([#20](https://github.com/bvisible/mcp-ssh-manager/issues/20), [#30](https://github.com/bvisible/mcp-ssh-manager/pull/30) — thanks @MakksSh)
|
|
21
|
+
- The previous shell-prompt detection used a fragile regex (`/[$#>]\s*$/`) that broke on custom prompts, ANSI color codes, multiline prompts, slow shells, `.bashrc`/profile script noise, and any non-standard prompt symbol. Sessions would frequently fail to initialize with `Timeout waiting for shell prompt`.
|
|
22
|
+
- Replaced with a marker-based protocol: the PTY is requested with `ECHO: 0`, a unique UUID v4 readiness marker is sent on session start, and every executed command is wrapped with `set +e; <cmd>; __mcp_status=$?; printf '\n<marker>:%s\n' "$__mcp_status"`. The completion marker carries the **real exit code** captured from `$?` instead of the previous `!output.includes('command not found')` heuristic.
|
|
23
|
+
- A shell prompt is presentation, not a protocol boundary. Marker-based sync is shell-agnostic, deterministic, and requires zero per-server configuration.
|
|
24
|
+
- Bonus: sessions now report accurate `success`/`exitCode` for downstream consumers.
|
|
25
|
+
|
|
26
|
+
## [3.3.0] - 2026-05-02
|
|
27
|
+
|
|
28
|
+
### Added
|
|
29
|
+
|
|
30
|
+
- **ProxyCommand support** for SOCKS5 and custom proxy connections ([#24](https://github.com/bvisible/mcp-ssh-manager/pull/24))
|
|
31
|
+
- 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`).
|
|
32
|
+
- Useful for reaching servers behind SOCKS5 proxies, custom jump hosts, or any scenario the existing `ProxyJump` doesn't cover.
|
|
33
|
+
|
|
34
|
+
### Fixed
|
|
35
|
+
|
|
36
|
+
- **`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)
|
|
37
|
+
- 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.
|
|
38
|
+
- 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.
|
|
39
|
+
|
|
40
|
+
- **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)
|
|
41
|
+
- npm's PowerShell shim refused to launch the legacy bash entry point because Windows has no `/bin/bash.exe`.
|
|
42
|
+
- 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`.
|
|
43
|
+
|
|
44
|
+
- **`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))
|
|
45
|
+
- `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`.
|
|
46
|
+
- `rsync` is now optional. `cmd_sync` checks lazily and emits an actionable error with install hints for macOS / Debian / Windows (MSYS2 + WSL).
|
|
47
|
+
|
|
48
|
+
- **`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)
|
|
49
|
+
- 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.
|
|
50
|
+
- `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`).
|
|
51
|
+
- `server list` detects pre-existing invalid entries, marks each affected row with `⚠ invalid`, and prints a warning block telling the user how to migrate.
|
|
52
|
+
- Prompt examples updated from `web-server` to `web_server` in both `server add` and the interactive wizard.
|
|
53
|
+
|
|
8
54
|
## [3.1.2] - 2026-02-09
|
|
9
55
|
|
|
10
56
|
### 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,70 @@
|
|
|
1
1
|
# MCP SSH Manager - SSH Remote Server Management via Model Context Protocol 🚀
|
|
2
2
|
|
|
3
|
-
|
|
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
|
[](https://www.npmjs.com/package/mcp-ssh-manager)
|
|
12
8
|
[](https://www.npmjs.com/package/mcp-ssh-manager)
|
|
13
|
-
[](https://modelcontextprotocol.io)
|
|
15
|
-
[](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.2.0)
|
|
9
|
+
[](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.4.0)
|
|
16
10
|
[](https://claude.ai/code)
|
|
17
11
|
[](https://openai.com/codex)
|
|
18
12
|
[](https://modelcontextprotocol.io)
|
|
19
13
|
[](LICENSE)
|
|
20
14
|
|
|
21
|
-
|
|
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
|
-
<
|
|
17
|
+
<p align="center">
|
|
18
|
+
<img src="docs/images/ssh-manager-cli-menu.png" alt="ssh-manager interactive CLI menu" width="900">
|
|
19
|
+
</p>
|
|
26
20
|
|
|
27
|
-
|
|
28
|
-
<img src="https://mseep.net/pr/bvisible-mcp-ssh-manager-badge.png" alt="MseeP.ai Security Assessment Badge" />
|
|
29
|
-
</a>
|
|
21
|
+
---
|
|
30
22
|
|
|
31
|
-
|
|
23
|
+
## 🎉 What's New in v3.4.0
|
|
24
|
+
|
|
25
|
+
**Full Windows OpenSSH support + shell-agnostic session sync** (Released: May 7, 2026)
|
|
26
|
+
|
|
27
|
+
- **🪟 Windows OpenSSH targets — encoding & syntax fixes** ([#31](https://github.com/bvisible/mcp-ssh-manager/pull/31))
|
|
28
|
+
- **Mojibake fix** — Commands on Windows hosts no longer inherit the OEM code page (CP950, CP932, CP1252…). Payloads are now wrapped as `powershell -NoProfile -OutputFormat Text -EncodedCommand <utf16le-base64>` (the same approach used by Ansible / Chef / Puppet for Windows remote execution), sidestepping every `cmd.exe` quoting and code-page issue
|
|
29
|
+
- **`cd && ` syntax fix** — `cd ${workingDir} && ${cmd}` is invalid in `cmd.exe`; replaced with `Set-Location '${escapedDir}'; ${cmd}` (PowerShell-native, with `'` → `''` escaping) across `ssh_execute`, `ssh_execute_group`, and `ssh_execute_sudo`
|
|
30
|
+
- Strictly gated behind `platform = "windows"` — Linux/macOS targets take the exact same code path as before, zero risk of regression
|
|
31
|
+
- Thanks [@WenKingSu](https://github.com/WenKingSu) for the clean, well-documented patch
|
|
32
|
+
- **🎯 Marker-based SSH session sync — replaces fragile prompt detection** ([#30](https://github.com/bvisible/mcp-ssh-manager/pull/30))
|
|
33
|
+
- The previous `/[$#>]\s*$/` regex broke on custom prompts, ANSI color codes, multiline prompts, slow shells, `.bashrc` noise, AIX-style login flows — `ssh_session_start` would frequently fail with "Timeout waiting for shell prompt"
|
|
34
|
+
- Now uses **UUID v4 markers** as protocol boundaries: each command is wrapped with a unique end marker (`set +e; <cmd>; __mcp_status=$?; printf '\n<marker>:%s\n' "$__mcp_status"`), and the PTY is opened with `ECHO: 0` so the buffer contains only command output
|
|
35
|
+
- **Bonus**: sessions now report **real exit codes** captured from `$?` instead of the previous `!output.includes('command not found')` heuristic
|
|
36
|
+
- Resolves [#20](https://github.com/bvisible/mcp-ssh-manager/issues/20) and supersedes the proposed configurable `prompt_pattern` approach by making the problem disappear entirely — no per-server config required
|
|
37
|
+
- Thanks [@MakksSh](https://github.com/MakksSh) for the precise root-cause analysis and the clean refactor
|
|
38
|
+
|
|
39
|
+
[Read full changelog →](CHANGELOG.md#340---2026-05-07)
|
|
32
40
|
|
|
33
41
|
---
|
|
34
42
|
|
|
35
|
-
##
|
|
43
|
+
## Previous Releases
|
|
44
|
+
|
|
45
|
+
### v3.3.0 - ProxyCommand & Critical Fixes (May 2, 2026)
|
|
46
|
+
|
|
47
|
+
- **🔌 ProxyCommand support** for SOCKS5 / custom proxy commands ([#24](https://github.com/bvisible/mcp-ssh-manager/pull/24))
|
|
48
|
+
- **⏱️ `ssh_execute` timeout silently capped at 30 s** — fixed ([#28](https://github.com/bvisible/mcp-ssh-manager/issues/28), [#29](https://github.com/bvisible/mcp-ssh-manager/pull/29))
|
|
49
|
+
- **🪟 Windows global install `/bin/bash` shim error** — fixed ([#22](https://github.com/bvisible/mcp-ssh-manager/issues/22), [#23](https://github.com/bvisible/mcp-ssh-manager/pull/23))
|
|
50
|
+
- **🔧 `server add` blocked by missing `rsync`** — `rsync` now optional ([#26](https://github.com/bvisible/mcp-ssh-manager/pull/26))
|
|
51
|
+
- **🔡 Hyphenated server names silently dropped** — validation hardened ([#25](https://github.com/bvisible/mcp-ssh-manager/issues/25), [#27](https://github.com/bvisible/mcp-ssh-manager/pull/27))
|
|
52
|
+
|
|
53
|
+
### v3.2.2 - Global Install Fix & CLI Binary (April 7, 2026)
|
|
54
|
+
|
|
55
|
+
- **🔧 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))
|
|
56
|
+
- Fallback chain: `~/.ssh-manager/.env` → `cwd/.env` → `~/.env` → project `.env`
|
|
57
|
+
- Auto-creates `~/.ssh-manager/.env` on first `ssh-manager server add`
|
|
58
|
+
- **📦 `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))
|
|
59
|
+
- **⚡ Race condition fix**: Server config is now fully loaded before the MCP server accepts requests
|
|
36
60
|
|
|
37
|
-
|
|
61
|
+
### v3.2.0 - ProxyJump / Bastion Host Support (March 18, 2026)
|
|
38
62
|
|
|
39
63
|
- **🔀 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
64
|
- Chain multiple jumps (A → B → C) via recursive connections
|
|
41
65
|
- Circular dependency detection prevents infinite loops
|
|
42
|
-
- All tools work transparently through jump hosts
|
|
43
|
-
|
|
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
|
|
66
|
+
- All tools work transparently through jump hosts
|
|
67
|
+
- **📦 npx support fixed**: `npx mcp-ssh-manager` now works correctly ([#14](https://github.com/bvisible/mcp-ssh-manager/issues/14))
|
|
49
68
|
|
|
50
69
|
### v3.1.5 - SSH Agent & Passphrase Support (March 5, 2026)
|
|
51
70
|
|
|
@@ -105,13 +124,16 @@ This release adds **12 new MCP tools** transforming SSH Manager into a comprehen
|
|
|
105
124
|
## 📑 Table of Contents
|
|
106
125
|
|
|
107
126
|
- [Features](#-features)
|
|
127
|
+
- [Tool Management](#-tool-management--context-optimization)
|
|
128
|
+
- [Prerequisites](#-prerequisites)
|
|
108
129
|
- [Quick Start - Claude Code](#-quick-start---claude-code)
|
|
109
130
|
- [Quick Start - OpenAI Codex](#-quick-start---openai-codex)
|
|
110
|
-
- [Prerequisites](#-prerequisites)
|
|
111
131
|
- [Available MCP Tools](#-available-mcp-tools)
|
|
112
132
|
- [Configuration](#-configuration)
|
|
113
133
|
- [Usage Examples](#-usage-examples)
|
|
134
|
+
- [Security](#-security-best-practices)
|
|
114
135
|
- [Troubleshooting](#-troubleshooting)
|
|
136
|
+
- [Known Limitations](#known-limitations)
|
|
115
137
|
- [Contributing](#-contributing)
|
|
116
138
|
- [License](#-license)
|
|
117
139
|
|
|
@@ -123,6 +145,7 @@ This release adds **12 new MCP tools** transforming SSH Manager into a comprehen
|
|
|
123
145
|
- **🔗 Multiple SSH Connections** - Manage unlimited SSH servers from a single interface
|
|
124
146
|
- **🔐 Secure Authentication** - Support for password, SSH key, and ssh-agent authentication (including passphrase-protected keys)
|
|
125
147
|
- **🔀 ProxyJump / Bastion Host** - Connect to servers behind jump hosts with chained multi-hop support
|
|
148
|
+
- **🔌 ProxyCommand / Custom Proxy** - Connect through SOCKS5 proxies or custom proxy commands (ncat, ssh -W, etc.)
|
|
126
149
|
- **📁 File Operations** - Upload and download files between local and remote systems
|
|
127
150
|
- **⚡ Command Execution** - Run commands on remote servers with working directory support
|
|
128
151
|
- **📂 Default Directories** - Set default working directories per server for convenience
|
|
@@ -198,22 +221,6 @@ ssh-manager tools disable backup
|
|
|
198
221
|
|
|
199
222
|
---
|
|
200
223
|
|
|
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
224
|
## 📋 Prerequisites
|
|
218
225
|
|
|
219
226
|
- Node.js (v18 or higher)
|
|
@@ -590,6 +597,7 @@ SSH_SERVER_[NAME]_DEFAULT_DIR=/path/to/dir # Optional, default working director
|
|
|
590
597
|
SSH_SERVER_[NAME]_DESCRIPTION=Description # Optional
|
|
591
598
|
SSH_SERVER_[NAME]_PLATFORM=windows # Optional: "linux" (default) or "windows"
|
|
592
599
|
SSH_SERVER_[NAME]_PROXYJUMP=bastion # Optional: name of another server to use as jump host
|
|
600
|
+
SSH_SERVER_[NAME]_PROXYCOMMAND=command # Optional: custom proxy command (ncat, ssh -W, etc.)
|
|
593
601
|
|
|
594
602
|
# Example: Linux server
|
|
595
603
|
SSH_SERVER_PRODUCTION_HOST=prod.example.com
|
|
@@ -636,19 +644,24 @@ The Python management tool (`tools/server_manager.py`) provides:
|
|
|
636
644
|
```
|
|
637
645
|
mcp-ssh-manager/
|
|
638
646
|
├── src/
|
|
639
|
-
│
|
|
640
|
-
├──
|
|
641
|
-
│ ├──
|
|
642
|
-
│ ├──
|
|
643
|
-
│
|
|
644
|
-
├──
|
|
645
|
-
│ ├── .
|
|
646
|
-
│ ├──
|
|
647
|
-
│ ├──
|
|
648
|
-
│ └──
|
|
649
|
-
├──
|
|
650
|
-
├──
|
|
651
|
-
|
|
647
|
+
│ ├── index.js # Main MCP server (37 tools)
|
|
648
|
+
│ ├── ssh-manager.js # SSH connection handling
|
|
649
|
+
│ ├── config-loader.js # .env & TOML config loading
|
|
650
|
+
│ ├── session-manager.js # Persistent SSH sessions
|
|
651
|
+
│ ├── backup-manager.js # Backup & restore
|
|
652
|
+
│ ├── health-monitor.js # Health checks & alerts
|
|
653
|
+
│ ├── database-manager.js # Database operations
|
|
654
|
+
│ ├── tunnel-manager.js # SSH tunnel management
|
|
655
|
+
│ ├── server-groups.js # Group operations
|
|
656
|
+
│ └── ...
|
|
657
|
+
├── cli/
|
|
658
|
+
│ ├── ssh-manager # Bash CLI entrypoint
|
|
659
|
+
│ ├── commands/ # CLI command modules
|
|
660
|
+
│ └── lib/ # CLI libraries
|
|
661
|
+
├── profiles/ # Configuration profiles (frappe, docker, nodejs...)
|
|
662
|
+
├── examples/ # Example configs
|
|
663
|
+
├── docs/ # Documentation
|
|
664
|
+
└── package.json
|
|
652
665
|
```
|
|
653
666
|
|
|
654
667
|
## 🧪 Testing
|
|
@@ -748,6 +761,37 @@ proxy_jump = "bastion"
|
|
|
748
761
|
|
|
749
762
|
**Chained jumps** are supported: if `bastion` itself has a `proxy_jump`, the chain is followed recursively. Circular references are detected and rejected.
|
|
750
763
|
|
|
764
|
+
### ProxyCommand / Custom Proxy
|
|
765
|
+
|
|
766
|
+
Connect through SOCKS5 proxies or custom proxy commands. The proxy command executes locally and forwards traffic to the remote host.
|
|
767
|
+
|
|
768
|
+
```env
|
|
769
|
+
# SOCKS5 proxy via ncat
|
|
770
|
+
SSH_SERVER_SOCKS_HOST=target.example.com
|
|
771
|
+
SSH_SERVER_SOCKS_USER=admin
|
|
772
|
+
SSH_SERVER_SOCKS_PROXYCOMMAND="ncat --proxy 127.0.0.1:1080 --proxy-type socks5 %h %p"
|
|
773
|
+
|
|
774
|
+
# Windows SSH proxy command
|
|
775
|
+
SSH_SERVER_WINPROXY_HOST=internal.example.com
|
|
776
|
+
SSH_SERVER_WINPROXY_USER=admin
|
|
777
|
+
SSH_SERVER_WINPROXY_PROXYCOMMAND="C:\Windows\System32\OpenSSH\ssh.exe -W %h:%p user@jump-host"
|
|
778
|
+
```
|
|
779
|
+
|
|
780
|
+
Or in TOML:
|
|
781
|
+
```toml
|
|
782
|
+
[ssh_servers.socks]
|
|
783
|
+
host = "target.example.com"
|
|
784
|
+
user = "admin"
|
|
785
|
+
proxy_command = "ncat --proxy 127.0.0.1:1080 --proxy-type socks5 %h %p"
|
|
786
|
+
|
|
787
|
+
[ssh_servers.winproxy]
|
|
788
|
+
host = "internal.example.com"
|
|
789
|
+
user = "admin"
|
|
790
|
+
proxy_command = "C:\\Windows\\System32\\OpenSSH\\ssh.exe -W %h:%p user@jump-host"
|
|
791
|
+
```
|
|
792
|
+
|
|
793
|
+
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.
|
|
794
|
+
|
|
751
795
|
### Documentation
|
|
752
796
|
- [DEPLOYMENT_GUIDE.md](docs/DEPLOYMENT_GUIDE.md) - Deployment strategies and permission handling
|
|
753
797
|
- [ALIASES_AND_HOOKS.md](docs/ALIASES_AND_HOOKS.md) - Command aliases and automation hooks
|
|
@@ -807,42 +851,6 @@ See [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) for complete guide.
|
|
|
807
851
|
2. Check SSH key permissions: `chmod 600 ~/.ssh/your_key`
|
|
808
852
|
3. Ensure user has necessary permissions on remote server
|
|
809
853
|
|
|
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
854
|
## 📚 Usage Examples
|
|
847
855
|
|
|
848
856
|
### Backup & Restore
|
|
@@ -939,16 +947,8 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
|
|
|
939
947
|
- SSH handling via [node-ssh](https://www.npmjs.com/package/node-ssh)
|
|
940
948
|
- Server management with [Paramiko](https://www.paramiko.org)
|
|
941
949
|
|
|
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
950
|
---
|
|
949
951
|
|
|
950
|
-
Made with ❤️ for the Claude Code community
|
|
951
|
-
|
|
952
952
|
## Known Limitations
|
|
953
953
|
|
|
954
954
|
### Command Timeout
|
|
@@ -967,7 +967,28 @@ Made with ❤️ for the Claude Code community
|
|
|
967
967
|
- If a connection becomes stale, it will be automatically reconnected on next use
|
|
968
968
|
- Force reconnection by using the `ssh_connection_status` tool with `reconnect` action
|
|
969
969
|
|
|
970
|
-
## Support
|
|
970
|
+
## 📧 Support
|
|
971
971
|
|
|
972
|
-
For issues,
|
|
973
|
-
https://github.com/bvisible/mcp-ssh-manager
|
|
972
|
+
For issues, questions, or suggestions:
|
|
973
|
+
- Open an issue on [GitHub Issues](https://github.com/bvisible/mcp-ssh-manager/issues)
|
|
974
|
+
- Check existing issues before creating new ones
|
|
975
|
+
|
|
976
|
+
---
|
|
977
|
+
|
|
978
|
+
<div align="center">
|
|
979
|
+
|
|
980
|
+
Made with ❤️ for the Claude Code community
|
|
981
|
+
|
|
982
|
+
<br/><br/>
|
|
983
|
+
|
|
984
|
+
<a href="https://glama.ai/mcp/servers/@bvisible/mcp-ssh-manager">
|
|
985
|
+
<img width="380" height="200" src="https://glama.ai/mcp/servers/@bvisible/mcp-ssh-manager/badge" alt="SSH Manager MCP server" />
|
|
986
|
+
</a>
|
|
987
|
+
|
|
988
|
+
<br/>
|
|
989
|
+
|
|
990
|
+
<a href="https://mseep.ai/app/bvisible-mcp-ssh-manager">
|
|
991
|
+
<img src="https://mseep.net/pr/bvisible-mcp-ssh-manager-badge.png" alt="MseeP.ai Security Assessment Badge" />
|
|
992
|
+
</a>
|
|
993
|
+
|
|
994
|
+
</div>
|
package/cli/commands/server.sh
CHANGED
|
@@ -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,
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
@@ -339,59 +339,123 @@ test_ssh_connection() {
|
|
|
339
339
|
}
|
|
340
340
|
|
|
341
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.
|
|
342
354
|
validate_server_name() {
|
|
343
355
|
local name="$1"
|
|
344
|
-
|
|
356
|
+
|
|
345
357
|
# Check if name is empty
|
|
346
358
|
if [ -z "$name" ]; then
|
|
347
359
|
print_error "Server name cannot be empty"
|
|
348
360
|
return 1
|
|
349
361
|
fi
|
|
350
|
-
|
|
351
|
-
#
|
|
352
|
-
if
|
|
353
|
-
|
|
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"
|
|
354
368
|
return 1
|
|
355
369
|
fi
|
|
356
|
-
|
|
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
|
+
|
|
357
377
|
# Check if name starts with a letter
|
|
358
378
|
if ! [[ "$name" =~ ^[a-zA-Z] ]]; then
|
|
359
379
|
print_error "Server name must start with a letter"
|
|
360
380
|
return 1
|
|
361
381
|
fi
|
|
362
|
-
|
|
382
|
+
|
|
363
383
|
return 0
|
|
364
384
|
}
|
|
365
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
|
+
|
|
366
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.
|
|
367
411
|
check_dependencies() {
|
|
368
412
|
local missing=()
|
|
369
|
-
|
|
413
|
+
|
|
370
414
|
# Check for required commands
|
|
371
|
-
for cmd in ssh
|
|
415
|
+
for cmd in ssh; do
|
|
372
416
|
if ! command -v "$cmd" >/dev/null 2>&1; then
|
|
373
417
|
missing+=("$cmd")
|
|
374
418
|
fi
|
|
375
419
|
done
|
|
376
|
-
|
|
420
|
+
|
|
377
421
|
# Check for optional but recommended commands
|
|
378
422
|
local optional=()
|
|
379
|
-
for cmd in jq sshpass; do
|
|
423
|
+
for cmd in rsync jq sshpass; do
|
|
380
424
|
if ! command -v "$cmd" >/dev/null 2>&1; then
|
|
381
425
|
optional+=("$cmd")
|
|
382
426
|
fi
|
|
383
427
|
done
|
|
384
|
-
|
|
428
|
+
|
|
385
429
|
if [ ${#missing[@]} -gt 0 ]; then
|
|
386
430
|
print_error "Missing required dependencies: ${missing[*]}"
|
|
387
431
|
print_info "Please install them and try again"
|
|
388
432
|
return 1
|
|
389
433
|
fi
|
|
390
|
-
|
|
434
|
+
|
|
391
435
|
if [ ${#optional[@]} -gt 0 ]; then
|
|
392
436
|
print_warning "Missing optional dependencies: ${optional[*]}"
|
|
393
|
-
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
|
|
394
459
|
fi
|
|
395
|
-
|
|
396
460
|
return 0
|
|
397
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 "
|
|
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
|
+
}
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-ssh-manager",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.4.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
7
|
"mcp-ssh-manager": "src/index.js",
|
|
8
|
-
"ssh-manager": "cli/ssh-manager"
|
|
8
|
+
"ssh-manager": "cli/ssh-manager.js"
|
|
9
9
|
},
|
|
10
10
|
"type": "module",
|
|
11
11
|
"scripts": {
|
package/src/config-loader.js
CHANGED
|
@@ -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
|
@@ -251,6 +251,10 @@ const KEEPALIVE_INTERVAL = 5 * 60 * 1000;
|
|
|
251
251
|
// Map to store keepalive intervals
|
|
252
252
|
const keepaliveIntervals = new Map();
|
|
253
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
|
+
|
|
254
258
|
// Map to track proxy jump dependencies (target -> jump server)
|
|
255
259
|
const jumpDependencies = new Map();
|
|
256
260
|
|
|
@@ -264,12 +268,31 @@ function loadServerConfig() {
|
|
|
264
268
|
// Execute command with timeout - using child_process timeout for real kill
|
|
265
269
|
async function execCommandWithTimeout(ssh, command, options = {}, timeoutMs = 30000) {
|
|
266
270
|
// Pass through rawCommand and platform if specified
|
|
267
|
-
const { rawCommand, platform, ...otherOptions } = options;
|
|
268
|
-
|
|
271
|
+
const { rawCommand, platform = 'linux', ...otherOptions } = options;
|
|
272
|
+
|
|
273
|
+
// Windows targets: encode the command as PowerShell -EncodedCommand (UTF-16
|
|
274
|
+
// LE base64). This is the standard approach (used by Ansible / Chef / Puppet)
|
|
275
|
+
// because cmd.exe's quoting rules are inconsistent across versions and break
|
|
276
|
+
// commands containing $vars, $(...) subexpressions, double-quoted strings,
|
|
277
|
+
// pipes, etc. Base64 sidesteps all escape issues entirely.
|
|
278
|
+
if (platform === 'windows' && !rawCommand) {
|
|
279
|
+
// Suppress progress (avoids CLIXML sentinels in stderr) + force UTF-8 stdout
|
|
280
|
+
const prelude = `$ProgressPreference='SilentlyContinue'; [Console]::OutputEncoding=[System.Text.Encoding]::UTF8;`;
|
|
281
|
+
const fullPSCommand = `${prelude} ${command}`;
|
|
282
|
+
const utf16le = Buffer.from(fullPSCommand, 'utf16le');
|
|
283
|
+
const b64 = utf16le.toString('base64');
|
|
284
|
+
// -OutputFormat Text prevents stderr/info streams from being CLIXML-encoded
|
|
285
|
+
const wrappedCommand = `powershell -NoProfile -OutputFormat Text -EncodedCommand ${b64}`;
|
|
286
|
+
return ssh.execCommand(wrappedCommand, { ...otherOptions, execOptions: { ...(otherOptions.execOptions || {}) } });
|
|
287
|
+
}
|
|
269
288
|
|
|
270
|
-
// For commands that might hang, use the system's timeout command if available
|
|
271
|
-
//
|
|
272
|
-
|
|
289
|
+
// For commands that might hang, use the system's timeout command if available.
|
|
290
|
+
// Note: the `!isWindows` guard that existed here previously is intentionally
|
|
291
|
+
// removed. Windows targets return early above (the `if (platform === 'windows'
|
|
292
|
+
// && !rawCommand)` block), so by the time execution reaches this line it is
|
|
293
|
+
// guaranteed to be a Linux/macOS target. The behaviour is identical; the old
|
|
294
|
+
// guard was made redundant by the early-return path.
|
|
295
|
+
const useSystemTimeout = timeoutMs > 0 && timeoutMs < 300000 && !rawCommand; // Max 5 minutes, not for raw commands
|
|
273
296
|
|
|
274
297
|
if (useSystemTimeout) {
|
|
275
298
|
// Wrap command with timeout command (works on Linux/Mac)
|
|
@@ -277,7 +300,10 @@ async function execCommandWithTimeout(ssh, command, options = {}, timeoutMs = 30
|
|
|
277
300
|
const wrappedCommand = `timeout ${timeoutSeconds} sh -c '${command.replace(/'/g, '\'\\\'\'')}'`;
|
|
278
301
|
|
|
279
302
|
try {
|
|
280
|
-
const result = await ssh.execCommand(wrappedCommand,
|
|
303
|
+
const result = await ssh.execCommand(wrappedCommand, {
|
|
304
|
+
...otherOptions,
|
|
305
|
+
timeout: timeoutMs + WRAPPED_COMMAND_TIMEOUT_GRACE_MS
|
|
306
|
+
});
|
|
281
307
|
|
|
282
308
|
// Check if timeout occurred (exit code 124 on Linux, 124 or 143 on Mac)
|
|
283
309
|
if (result.code === 124 || result.code === 143) {
|
|
@@ -385,6 +411,56 @@ function cleanupOldConnections() {
|
|
|
385
411
|
}
|
|
386
412
|
}
|
|
387
413
|
|
|
414
|
+
// Create a socket from a proxy command (e.g., "ncat --proxy 127.0.0.1:1080 --proxy-type socks5 %h %p")
|
|
415
|
+
// The command is executed through the system shell, matching OpenSSH ProxyCommand semantics,
|
|
416
|
+
// so quoted arguments and shell metacharacters work as users expect.
|
|
417
|
+
async function createProxyCommandSocket(proxyCommand, host, port) {
|
|
418
|
+
const { spawn } = await import('child_process');
|
|
419
|
+
const { Duplex } = await import('stream');
|
|
420
|
+
|
|
421
|
+
const cmd = proxyCommand.replace(/%h/g, host).replace(/%p/g, port.toString());
|
|
422
|
+
|
|
423
|
+
return new Promise((resolve, reject) => {
|
|
424
|
+
const child = spawn(cmd, {
|
|
425
|
+
shell: true,
|
|
426
|
+
stdio: ['pipe', 'pipe', 'pipe']
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
const socket = Duplex.from({
|
|
430
|
+
readable: child.stdout,
|
|
431
|
+
writable: child.stdin,
|
|
432
|
+
allowHalfOpen: false
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
// Forward proxy stderr to the MCP server's stderr for debugging
|
|
436
|
+
child.stderr.on('data', (chunk) => {
|
|
437
|
+
process.stderr.write(`[proxy-command] ${chunk}`);
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
let settled = false;
|
|
441
|
+
const settle = (fn, arg) => {
|
|
442
|
+
if (settled) return;
|
|
443
|
+
settled = true;
|
|
444
|
+
fn(arg);
|
|
445
|
+
};
|
|
446
|
+
|
|
447
|
+
socket.on('close', () => {
|
|
448
|
+
if (!child.killed) child.kill();
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
child.on('error', (err) => settle(reject, err));
|
|
452
|
+
child.on('spawn', () => settle(resolve, socket));
|
|
453
|
+
child.on('exit', (code, signal) => {
|
|
454
|
+
// Only surface unexpected exits — a kill() after a successful connection is normal.
|
|
455
|
+
if (!settled && code !== 0) {
|
|
456
|
+
settle(reject, new Error(`Proxy command exited with code ${code}${signal ? ` (${signal})` : ''}`));
|
|
457
|
+
} else if (settled && code !== 0 && !signal && !socket.destroyed) {
|
|
458
|
+
socket.destroy(new Error(`Proxy command exited with code ${code}`));
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
|
|
388
464
|
// Get or create SSH connection with reconnection support
|
|
389
465
|
async function getConnection(serverName) {
|
|
390
466
|
const servers = loadServerConfig();
|
|
@@ -465,6 +541,14 @@ async function getConnection(serverName) {
|
|
|
465
541
|
await ssh.connect({ sock: stream });
|
|
466
542
|
jumpDependencies.set(normalizedName, jumpServerName);
|
|
467
543
|
ssh.jumpConnection = jumpSSH;
|
|
544
|
+
} else if (serverConfig.proxyCommand) {
|
|
545
|
+
// Create socket via proxy command (e.g., SOCKS5 proxy)
|
|
546
|
+
const socket = await createProxyCommandSocket(
|
|
547
|
+
serverConfig.proxyCommand,
|
|
548
|
+
serverConfig.host,
|
|
549
|
+
serverConfig.port || 22
|
|
550
|
+
);
|
|
551
|
+
await ssh.connect({ sock: socket });
|
|
468
552
|
} else {
|
|
469
553
|
await ssh.connect();
|
|
470
554
|
}
|
|
@@ -479,7 +563,8 @@ async function getConnection(serverName) {
|
|
|
479
563
|
host: serverConfig.host,
|
|
480
564
|
port: serverConfig.port,
|
|
481
565
|
method: serverConfig.password ? 'password' : 'key',
|
|
482
|
-
proxyJump: serverConfig.proxyJump || null
|
|
566
|
+
proxyJump: serverConfig.proxyJump || null,
|
|
567
|
+
proxyCommand: serverConfig.proxyCommand ? '<set>' : null
|
|
483
568
|
});
|
|
484
569
|
|
|
485
570
|
// Execute post-connect hook
|
|
@@ -551,12 +636,25 @@ registerToolConditional(
|
|
|
551
636
|
const servers = loadServerConfig();
|
|
552
637
|
const serverConfig = servers[serverName.toLowerCase()];
|
|
553
638
|
const workingDir = cwd || serverConfig?.default_dir;
|
|
554
|
-
const
|
|
639
|
+
const platform = serverConfig?.platform || 'linux';
|
|
640
|
+
|
|
641
|
+
// Build cwd-prefixed command using platform-appropriate syntax
|
|
642
|
+
let fullCommand;
|
|
643
|
+
if (workingDir) {
|
|
644
|
+
if (platform === 'windows') {
|
|
645
|
+
const escapedDir = workingDir.replace(/'/g, "''");
|
|
646
|
+
fullCommand = `Set-Location '${escapedDir}'; ${expandedCommand}`;
|
|
647
|
+
} else {
|
|
648
|
+
fullCommand = `cd ${workingDir} && ${expandedCommand}`;
|
|
649
|
+
}
|
|
650
|
+
} else {
|
|
651
|
+
fullCommand = expandedCommand;
|
|
652
|
+
}
|
|
555
653
|
|
|
556
654
|
// Log command execution
|
|
557
655
|
const startTime = logger.logCommand(serverName, fullCommand, workingDir);
|
|
558
656
|
|
|
559
|
-
const result = await execCommandWithTimeout(ssh, fullCommand, { platform
|
|
657
|
+
const result = await execCommandWithTimeout(ssh, fullCommand, { platform }, cappedTimeout);
|
|
560
658
|
|
|
561
659
|
// Log command result
|
|
562
660
|
logger.logCommandResult(serverName, fullCommand, startTime, result);
|
|
@@ -1730,13 +1828,27 @@ registerToolConditional(
|
|
|
1730
1828
|
async (serverName) => {
|
|
1731
1829
|
const ssh = await getConnection(serverName);
|
|
1732
1830
|
|
|
1733
|
-
// Build full command with cwd if provided
|
|
1831
|
+
// Build full command with cwd if provided.
|
|
1832
|
+
// Use platform-appropriate syntax: Set-Location for Windows (cmd.exe
|
|
1833
|
+
// does not support `cd && `) vs cd && for Linux/macOS.
|
|
1734
1834
|
const servers = loadServerConfig();
|
|
1735
1835
|
const serverConfig = servers[serverName.toLowerCase()];
|
|
1736
1836
|
const workingDir = cwd || serverConfig?.default_dir;
|
|
1737
|
-
const
|
|
1837
|
+
const platform = serverConfig?.platform || 'linux';
|
|
1838
|
+
let fullCommand;
|
|
1839
|
+
if (workingDir) {
|
|
1840
|
+
if (platform === 'windows') {
|
|
1841
|
+
// Single-quote escaping: replace ' with '' (PowerShell convention)
|
|
1842
|
+
const escapedDir = workingDir.replace(/'/g, "''");
|
|
1843
|
+
fullCommand = `Set-Location '${escapedDir}'; ${command}`;
|
|
1844
|
+
} else {
|
|
1845
|
+
fullCommand = `cd ${workingDir} && ${command}`;
|
|
1846
|
+
}
|
|
1847
|
+
} else {
|
|
1848
|
+
fullCommand = command;
|
|
1849
|
+
}
|
|
1738
1850
|
|
|
1739
|
-
const execResult = await execCommandWithTimeout(ssh, fullCommand, { platform
|
|
1851
|
+
const execResult = await execCommandWithTimeout(ssh, fullCommand, { platform }, 30000);
|
|
1740
1852
|
|
|
1741
1853
|
return {
|
|
1742
1854
|
stdout: execResult.stdout,
|
|
@@ -2116,13 +2228,24 @@ registerToolConditional(
|
|
|
2116
2228
|
}
|
|
2117
2229
|
|
|
2118
2230
|
// Add working directory if specified
|
|
2231
|
+
const platform = serverConfig?.platform || 'linux';
|
|
2119
2232
|
if (cwd) {
|
|
2120
|
-
|
|
2233
|
+
if (platform === 'windows') {
|
|
2234
|
+
const escapedDir = cwd.replace(/'/g, "''");
|
|
2235
|
+
fullCommand = `Set-Location '${escapedDir}'; ${fullCommand}`;
|
|
2236
|
+
} else {
|
|
2237
|
+
fullCommand = `cd ${cwd} && ${fullCommand}`;
|
|
2238
|
+
}
|
|
2121
2239
|
} else if (serverConfig?.default_dir) {
|
|
2122
|
-
|
|
2240
|
+
if (platform === 'windows') {
|
|
2241
|
+
const escapedDir = serverConfig.default_dir.replace(/'/g, "''");
|
|
2242
|
+
fullCommand = `Set-Location '${escapedDir}'; ${fullCommand}`;
|
|
2243
|
+
} else {
|
|
2244
|
+
fullCommand = `cd ${serverConfig.default_dir} && ${fullCommand}`;
|
|
2245
|
+
}
|
|
2123
2246
|
}
|
|
2124
2247
|
|
|
2125
|
-
const result = await execCommandWithTimeout(ssh, fullCommand, { platform
|
|
2248
|
+
const result = await execCommandWithTimeout(ssh, fullCommand, { platform }, timeout);
|
|
2126
2249
|
|
|
2127
2250
|
// Mask password in output for security
|
|
2128
2251
|
const maskedCommand = fullCommand.replace(/echo "[^"]+" \| sudo -S/, 'sudo');
|
package/src/session-manager.js
CHANGED
|
@@ -9,6 +9,10 @@ import { logger } from './logger.js';
|
|
|
9
9
|
// Map to store active sessions
|
|
10
10
|
const sessions = new Map();
|
|
11
11
|
|
|
12
|
+
function generateMarker(prefix) {
|
|
13
|
+
return `${prefix}_${uuidv4().replace(/-/g, '')}`;
|
|
14
|
+
}
|
|
15
|
+
|
|
12
16
|
// Session states
|
|
13
17
|
export const SESSION_STATES = {
|
|
14
18
|
INITIALIZING: 'initializing',
|
|
@@ -50,7 +54,10 @@ class SSHSession {
|
|
|
50
54
|
this.shell = await this.ssh.requestShell({
|
|
51
55
|
term: 'xterm-256color',
|
|
52
56
|
cols: 80,
|
|
53
|
-
rows: 24
|
|
57
|
+
rows: 24,
|
|
58
|
+
modes: {
|
|
59
|
+
ECHO: 0
|
|
60
|
+
}
|
|
54
61
|
});
|
|
55
62
|
|
|
56
63
|
// Setup event handlers
|
|
@@ -79,8 +86,11 @@ class SSHSession {
|
|
|
79
86
|
});
|
|
80
87
|
});
|
|
81
88
|
|
|
82
|
-
// Wait for shell prompt
|
|
83
|
-
|
|
89
|
+
// Wait for an explicit readiness marker instead of a shell prompt
|
|
90
|
+
const readyMarker = generateMarker('ready');
|
|
91
|
+
const readyCommand = `printf '\\n${readyMarker}\\n'`;
|
|
92
|
+
this.shell.write(`${readyCommand}\n`);
|
|
93
|
+
await this.waitForMarker(readyMarker);
|
|
84
94
|
|
|
85
95
|
// Allow context queries through standard execute flow
|
|
86
96
|
this.state = SESSION_STATES.READY;
|
|
@@ -103,14 +113,13 @@ class SSHSession {
|
|
|
103
113
|
}
|
|
104
114
|
|
|
105
115
|
/**
|
|
106
|
-
* Wait for shell
|
|
116
|
+
* Wait for a marker in shell output
|
|
107
117
|
*/
|
|
108
|
-
async
|
|
118
|
+
async waitForMarker(marker, timeout = 5000) {
|
|
109
119
|
const startTime = Date.now();
|
|
110
120
|
|
|
111
121
|
while (Date.now() - startTime < timeout) {
|
|
112
|
-
|
|
113
|
-
if (this.outputBuffer.match(/[$#>]\s*$/)) {
|
|
122
|
+
if (this.outputBuffer.includes(marker)) {
|
|
114
123
|
return true;
|
|
115
124
|
}
|
|
116
125
|
|
|
@@ -118,7 +127,7 @@ class SSHSession {
|
|
|
118
127
|
await new Promise(resolve => setTimeout(resolve, 100));
|
|
119
128
|
}
|
|
120
129
|
|
|
121
|
-
throw new Error(
|
|
130
|
+
throw new Error(`Timeout waiting for marker: ${marker}`);
|
|
122
131
|
}
|
|
123
132
|
|
|
124
133
|
/**
|
|
@@ -175,31 +184,23 @@ class SSHSession {
|
|
|
175
184
|
});
|
|
176
185
|
}
|
|
177
186
|
|
|
178
|
-
|
|
179
|
-
this.shell.write(command + '\n');
|
|
187
|
+
const endMarker = generateMarker('cmd');
|
|
180
188
|
|
|
181
|
-
//
|
|
182
|
-
|
|
189
|
+
// Send command wrapped in an explicit completion marker
|
|
190
|
+
this.shell.write(`set +e\n${command}\n__mcp_status=$?\nprintf '\\n${endMarker}:%s\\n' "$__mcp_status"\n`);
|
|
183
191
|
|
|
184
|
-
//
|
|
185
|
-
|
|
192
|
+
// Wait for command completion marker
|
|
193
|
+
await this.waitForMarker(endMarker, options.timeout || 30000);
|
|
186
194
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
lines.shift();
|
|
195
|
+
const markerIndex = this.outputBuffer.indexOf(endMarker);
|
|
196
|
+
if (markerIndex < 0) {
|
|
197
|
+
throw new Error(`Command marker not found: ${endMarker}`);
|
|
191
198
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
const
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
output = lines.join('\n').trim();
|
|
200
|
-
|
|
201
|
-
// Check for command success (basic heuristic)
|
|
202
|
-
const success = !this.errorBuffer && !output.includes('command not found');
|
|
199
|
+
const markerLine = this.outputBuffer.slice(markerIndex).split(/\r?\n/, 1)[0];
|
|
200
|
+
const statusMatch = markerLine.match(/:(\d+)$/);
|
|
201
|
+
const exitCode = statusMatch ? Number.parseInt(statusMatch[1], 10) : null;
|
|
202
|
+
const output = this.outputBuffer.slice(0, markerIndex).replace(/\r?\n+$/, '');
|
|
203
|
+
const success = exitCode === 0;
|
|
203
204
|
|
|
204
205
|
// Update context if command might have changed it
|
|
205
206
|
if (command.startsWith('cd ') || command.startsWith('export ')) {
|