@jiwonchang/mcp-ssh 0.0.0-stage → 0.1.0-dev.1
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/LICENSE +21 -0
- package/README.md +235 -2
- package/dist/config.js +77 -0
- package/dist/config.js.map +1 -0
- package/dist/index.js +37 -0
- package/dist/index.js.map +1 -0
- package/dist/jobs/engine.js +604 -0
- package/dist/jobs/engine.js.map +1 -0
- package/dist/jobs/store.js +78 -0
- package/dist/jobs/store.js.map +1 -0
- package/dist/output.js +57 -0
- package/dist/output.js.map +1 -0
- package/dist/server.js +350 -0
- package/dist/server.js.map +1 -0
- package/dist/ssh/exec.js +78 -0
- package/dist/ssh/exec.js.map +1 -0
- package/dist/ssh/hostkey.js +57 -0
- package/dist/ssh/hostkey.js.map +1 -0
- package/dist/ssh/pool.js +218 -0
- package/dist/ssh/pool.js.map +1 -0
- package/dist/ssh/sftp.js +133 -0
- package/dist/ssh/sftp.js.map +1 -0
- package/dist/ssh/transfer.js +312 -0
- package/dist/ssh/transfer.js.map +1 -0
- package/dist/worker.js +66 -0
- package/dist/worker.js.map +1 -0
- package/package.json +51 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 jiwonchang
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,236 @@
|
|
|
1
|
-
#
|
|
1
|
+
# mcp-ssh
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/jiwonchang/mcp-ssh/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
An [MCP](https://modelcontextprotocol.io) server that gives AI agents SSH access to remote hosts.
|
|
6
|
+
|
|
7
|
+
An agent with a shell can already run `ssh host "command"`. This server adds what that lacks:
|
|
8
|
+
|
|
9
|
+
- **Pooled connections.** One connection per host stays open between tool calls, so a call costs milliseconds instead of a new handshake. Dropped connections re-open on the next call.
|
|
10
|
+
- **Bounded output.** Command output is capped, keeping the start and end and dropping the middle, so a large log cannot flood the model's context.
|
|
11
|
+
- **Credential isolation.** The model refers to hosts by name. Keys, passwords and passphrases never appear in tool input or output, and cannot be placed in the config file.
|
|
12
|
+
- **Strict host key checking.** A host must match a pinned fingerprint or your `known_hosts`. The model has no way to accept a new key.
|
|
13
|
+
- **File operations over SFTP.** Reading and writing files does not depend on shell quoting, and writes are atomic. Whole directory trees and binary files transfer directly, without passing through the model. Files are copied in parallel, and each one is size-checked before it replaces anything.
|
|
14
|
+
- **No call hangs forever.** Commands have a timeout that covers the whole call, and a file operation the host stops answering is abandoned, the connection dropped, and the next call reconnects.
|
|
15
|
+
|
|
16
|
+
> **Status: early development (`0.1.0-dev`).** The tools below work and are tested. See [Roadmap](#roadmap) for what is not built yet.
|
|
17
|
+
|
|
18
|
+
## Tools
|
|
19
|
+
|
|
20
|
+
| Tool | What it does |
|
|
21
|
+
|---|---|
|
|
22
|
+
| `ssh_list_hosts` | Lists configured hosts and whether each is connected. |
|
|
23
|
+
| `ssh_exec` | Runs a non-interactive command. Returns exit code, stdout and stderr. Takes `cwd`, `timeoutSec` and `maxOutputBytes`. |
|
|
24
|
+
| `ssh_reconnect` | Closes the connection to a host and opens a new one, to pick up a change in the host's environment. |
|
|
25
|
+
| `ssh_read_file` | Reads a file, or a byte range of one. |
|
|
26
|
+
| `ssh_write_file` | Creates or replaces a file atomically, keeping an existing file's permissions. |
|
|
27
|
+
| `ssh_list_dir` | Lists a directory with type, size and modification time. |
|
|
28
|
+
| `ssh_upload` | Copies a local file or directory tree to a host. Existing files are skipped unless `overwrite` is set. |
|
|
29
|
+
| `ssh_download` | Copies a file or directory tree from a host to the local machine, with the same `overwrite` rule. |
|
|
30
|
+
| `ssh_transfer_start` | Starts a large or long copy in the background and returns a transfer id. See [Background transfers](#background-transfers). |
|
|
31
|
+
| `ssh_transfer_status` | Reports progress or the final result of a background transfer, or lists recent ones. |
|
|
32
|
+
| `ssh_transfer_cancel` | Stops a background transfer. |
|
|
33
|
+
|
|
34
|
+
## Setup
|
|
35
|
+
|
|
36
|
+
Requires Node.js 22 or later, on Linux, macOS or Windows.
|
|
37
|
+
|
|
38
|
+
There are two ways to get the server. Both end with a command your MCP client runs (step 3).
|
|
39
|
+
|
|
40
|
+
**Run it from GitHub, without a checkout.** Needs Git. npm downloads and builds the server the first time, which takes a minute, and reuses that copy afterwards:
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
npx -y github:jiwonchang/mcp-ssh
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
**Or build it from source**, which is also the way to work on it. A downloaded ZIP of the repository works the same as a clone:
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
git clone https://github.com/jiwonchang/mcp-ssh.git
|
|
50
|
+
cd mcp-ssh
|
|
51
|
+
npm install
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`npm install` compiles the server to `dist/`. Run `npm run build` after changing the source.
|
|
55
|
+
|
|
56
|
+
The package is not on the npm registry yet. The name `mcp-ssh` there belongs to an unrelated project, so do not run `npx mcp-ssh`.
|
|
57
|
+
|
|
58
|
+
### 1. Describe your hosts
|
|
59
|
+
|
|
60
|
+
Create `~/.mcp-ssh/hosts.json` (or point the `MCP_SSH_CONFIG` environment variable at another path). See [examples/hosts.example.json](examples/hosts.example.json).
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{
|
|
64
|
+
"hosts": {
|
|
65
|
+
"web1": {
|
|
66
|
+
"host": "192.0.2.10",
|
|
67
|
+
"username": "deploy",
|
|
68
|
+
"description": "Production web server"
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
| Field | Default | Meaning |
|
|
75
|
+
|---|---|---|
|
|
76
|
+
| `host` | required | Hostname or IP address, or a list of them for one machine (below). |
|
|
77
|
+
| `username` | required | Login user. |
|
|
78
|
+
| `port` | `22` | SSH port. |
|
|
79
|
+
| `auth` | `{ "type": "agent" }` | How to authenticate (below). |
|
|
80
|
+
| `hostKeyFingerprint` | none | Pins the host key, e.g. `SHA256:...` as printed by `ssh-keygen -lf`. |
|
|
81
|
+
| `shell` | `posix` | The shell the host runs commands in: `posix`, or `cmd` for Windows. |
|
|
82
|
+
| `description` | none | Shown to the model by `ssh_list_hosts`. |
|
|
83
|
+
|
|
84
|
+
Authentication methods:
|
|
85
|
+
|
|
86
|
+
- `{ "type": "agent" }` uses your SSH agent (`SSH_AUTH_SOCK`, or the OpenSSH agent service on Windows).
|
|
87
|
+
- `{ "type": "key", "path": "~/.ssh/id_ed25519", "passphraseEnv": "VAR" }` reads a private key file. `passphraseEnv` is optional and names an environment variable.
|
|
88
|
+
- `{ "type": "password", "env": "VAR" }` reads the password from an environment variable.
|
|
89
|
+
|
|
90
|
+
#### Several addresses for one host
|
|
91
|
+
|
|
92
|
+
`host` can be a list of up to 8 addresses for the same machine, tried in order:
|
|
93
|
+
|
|
94
|
+
```json
|
|
95
|
+
"host": ["laptop.local", "192.0.2.20"]
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
This suits a machine whose address can change, or one reached by a different address from another network. Put the address that follows the machine first (usually its name) and a fixed address after it.
|
|
99
|
+
|
|
100
|
+
- The next address is tried only when no SSH server answers at the current one: the name does not resolve, the connection is refused, or it times out. Each address can take up to 20 seconds to give up.
|
|
101
|
+
- Once a server answers, that address is final. If its host key is not trusted or it refuses the login, the connection fails and the remaining addresses are not tried.
|
|
102
|
+
- Every address is held to the same host key check. Without `hostKeyFingerprint`, each address needs its own entry in `known_hosts`, so pinning the fingerprint is the simpler choice here.
|
|
103
|
+
- `ssh_list_hosts` shows which address an open connection is using.
|
|
104
|
+
|
|
105
|
+
#### Windows hosts
|
|
106
|
+
|
|
107
|
+
Windows hosts running the built-in OpenSSH server work with `"shell": "cmd"`, which is that server's default shell. Commands are then written for `cmd.exe`. File tools take paths in SFTP form, either relative to the user's home directory or absolute like `/C:/Users/name/file.txt`. A host whose default SSH shell was changed to PowerShell is not supported by the `cwd` option.
|
|
108
|
+
|
|
109
|
+
Things to know when installing software on a Windows host over SSH:
|
|
110
|
+
|
|
111
|
+
- **A new `PATH` is not seen straight away.** An installer that changes the system `PATH` does not change it for SSH sessions. Two things hold the old value, and both need refreshing:
|
|
112
|
+
1. The `sshd` service keeps the environment it started with and hands it to every new connection. Restart the service, or reboot the host.
|
|
113
|
+
2. The pooled connection keeps the environment it was opened with, even after the service restarts. Call `ssh_reconnect` afterwards.
|
|
114
|
+
|
|
115
|
+
Until then, run the new program by its full path.
|
|
116
|
+
- **Restart `sshd` from a scheduled task, not from the session.** A restart run inside an SSH session can be cut off after the stop and before the start, which leaves the host unreachable. A one-off task run by the system account finishes regardless of the session. This needs an administrator account:
|
|
117
|
+
|
|
118
|
+
```bat
|
|
119
|
+
schtasks /create /tn RestartSshdOnce /tr "cmd /c net stop sshd & net start sshd" /sc once /st 23:59 /ru SYSTEM /f
|
|
120
|
+
schtasks /run /tn RestartSshdOnce
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Then check that `sc query sshd` reports `RUNNING`, delete the task with `schtasks /delete /tn RestartSshdOnce /f`, and call `ssh_reconnect`. If the service does not come back, someone has to start it at the machine, so get the owner's agreement first.
|
|
124
|
+
- **Programs installed from the Microsoft Store may not run.** Their commands are app execution aliases under `AppData\Local\Microsoft\WindowsApps`, and starting one over SSH can fail with `Access is denied` (seen with the Store version of PowerShell 7). Install the regular installer version, which puts a real executable under `Program Files`.
|
|
125
|
+
|
|
126
|
+
### 2. Trust each host key
|
|
127
|
+
|
|
128
|
+
The server connects only when the host key is trusted. Either:
|
|
129
|
+
|
|
130
|
+
- connect once yourself with `ssh user@host` so the key is recorded in `~/.ssh/known_hosts`, or
|
|
131
|
+
- set `hostKeyFingerprint` for the host.
|
|
132
|
+
|
|
133
|
+
Plain and hashed `known_hosts` entries are supported. Wildcard patterns and `@cert-authority` lines are not.
|
|
134
|
+
|
|
135
|
+
### 3. Register the server with your MCP client
|
|
136
|
+
|
|
137
|
+
The server speaks MCP over stdio: the client starts it on demand, so there is nothing to host or keep running.
|
|
138
|
+
|
|
139
|
+
Claude Code:
|
|
140
|
+
|
|
141
|
+
```sh
|
|
142
|
+
claude mcp add ssh -- npx -y github:jiwonchang/mcp-ssh
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
or, for a build from source:
|
|
146
|
+
|
|
147
|
+
```sh
|
|
148
|
+
claude mcp add ssh -- node /absolute/path/to/mcp-ssh/dist/index.js
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Other clients (Claude Desktop and similar) take an entry like this in their MCP configuration:
|
|
152
|
+
|
|
153
|
+
```json
|
|
154
|
+
{
|
|
155
|
+
"mcpServers": {
|
|
156
|
+
"ssh": {
|
|
157
|
+
"command": "node",
|
|
158
|
+
"args": ["/absolute/path/to/mcp-ssh/dist/index.js"],
|
|
159
|
+
"env": { "LAB_PASSWORD": "..." }
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
## Background transfers
|
|
166
|
+
|
|
167
|
+
`ssh_upload` and `ssh_download` run inside one tool call and stop at the first failure, which suits small copies. For a copy that takes a long time or must finish unattended, `ssh_transfer_start` runs it in a separate process and returns at once.
|
|
168
|
+
|
|
169
|
+
A background transfer:
|
|
170
|
+
|
|
171
|
+
- **Outlives the tool call and the server.** The copy runs in its own process, so it carries on if the MCP client or this server exits.
|
|
172
|
+
- **Reconnects.** When the connection drops it waits (5 seconds, doubling up to 2 minutes) and tries again. It gives up only when nothing has been copied for `maxIdleHours` (default 12).
|
|
173
|
+
- **Continues large files.** A file that was partly sent when the connection dropped is continued from the last acknowledged byte, not restarted.
|
|
174
|
+
- **Does not let one file stop the rest.** A file that fails on a working connection is tried 3 times, then recorded, and everything else is still copied.
|
|
175
|
+
- **Never leaves a partial file under a real name.** Each file is written as `<name>.mcp-ssh-part`, size-checked, and then moved into place.
|
|
176
|
+
- **Is not stopped for being slow.** The `maxIdleHours` limit restarts with every piece of data copied, so a copy that is still making progress runs for as long as it needs. To cap the total running time as well, set `maxHours`; it is off by default, and when set it stops the transfer even in the middle of a file.
|
|
177
|
+
- **Can verify contents.** With `verify`, every copied file is read back and its SHA-256 checksum compared with the source before it is kept.
|
|
178
|
+
- **Reports.** `ssh_transfer_status` shows progress and lists every file that could not be copied, with the reason. The same report is kept as JSON in `~/.mcp-ssh/jobs/` (or `MCP_SSH_STATE_DIR`).
|
|
179
|
+
|
|
180
|
+
Without `overwrite`, a destination file of the same size as its source is skipped, and one of a different size is reported and left alone. Starting the same transfer again therefore copies only what is missing.
|
|
181
|
+
|
|
182
|
+
Limits to know about:
|
|
183
|
+
|
|
184
|
+
- A partly copied file is continued only within one transfer. If the worker process itself dies (for example the machine restarts), start the transfer again: finished files are skipped, and the files that were in progress are sent again from the beginning.
|
|
185
|
+
- Neither machine is kept awake. A machine that goes to sleep pauses the transfer until it wakes; a host that stays asleep past `maxIdleHours` ends it.
|
|
186
|
+
- The worker is started detached, but a client that kills its whole process tree on exit could still stop it.
|
|
187
|
+
|
|
188
|
+
## Security model
|
|
189
|
+
|
|
190
|
+
This server lets a model run commands on your machines. Treat it accordingly.
|
|
191
|
+
|
|
192
|
+
- The model can run **any command the configured user can run**. There is no command filtering yet. Use a least-privilege account on each host.
|
|
193
|
+
- Only hosts in the config file are reachable. The model cannot supply an address, user or credential.
|
|
194
|
+
- `ssh_upload`, `ssh_download` and `ssh_transfer_start` read and write files on the machine running this server, with the permissions of the user running it. The model chooses the local path.
|
|
195
|
+
- Secrets are read from the SSH agent, key files or environment variables. The config schema rejects unknown fields, so a password cannot be stored in it by mistake.
|
|
196
|
+
- Host keys are always verified. An unknown or changed key refuses the connection and tells the model to ask you.
|
|
197
|
+
- Keep your MCP client's per-call approval on for `ssh_exec`, `ssh_write_file`, `ssh_upload`, `ssh_download` and `ssh_transfer_start` unless you fully trust the task.
|
|
198
|
+
|
|
199
|
+
## Roadmap
|
|
200
|
+
|
|
201
|
+
- Background commands: start, poll, tail and stop long-running commands that survive a disconnect. (Background file transfers exist.)
|
|
202
|
+
- Interactive sessions (PTY) for prompts and REPLs.
|
|
203
|
+
- Per-host policy: read-only mode, command allow and deny lists.
|
|
204
|
+
- Audit log of every command and file change.
|
|
205
|
+
- Jump hosts and port forwarding.
|
|
206
|
+
- Line-based file reads and in-place string edits.
|
|
207
|
+
- Reading hosts from `~/.ssh/config`.
|
|
208
|
+
- Streamable HTTP transport for remote clients.
|
|
209
|
+
|
|
210
|
+
### To revisit
|
|
211
|
+
|
|
212
|
+
Open questions about background transfers, recorded so they are not lost:
|
|
213
|
+
|
|
214
|
+
- **Resolving a failed file instead of only reporting it.** Today a file that fails 3 times is recorded and skipped. Work out what could be tried first, and who tries it. Candidates for the server: wait longer for a locked file, retry under the Windows long-path form, fall back to a single-stream copy. Candidates for the agent: read the failure from `ssh_transfer_status`, fix the cause on the host with `ssh_exec` (close the program holding the file, fix permissions, free disk space), then start the transfer again. A failure should be left in the report only when every applicable remedy has been tried.
|
|
215
|
+
- **Keeping both machines awake for the length of a transfer.** The host should not need its power settings changed beforehand. Options to evaluate: hold a wake request on the host for as long as the transfer runs (`powercfg /requestsoverride` or a process calling `SetThreadExecutionState` on Windows, `systemd-inhibit` on Linux, `caffeinate` on macOS), released when the transfer ends or its connection is gone; and the same on the machine running the worker. Needs care that a crashed transfer cannot leave a machine awake for good.
|
|
216
|
+
- **Whether a transfer should outlive the MCP client, and how to guarantee it.** Recommendation: yes. A copy meant to run unattended should not depend on a client window staying open. That is acceptable only within these bounds, which should all hold: the worker exits by itself when the copy ends; it ends when it has made no progress for `maxIdleHours`, and at `maxHours` when that is set; it touches nothing but the source and destination it was given; and any session can see it with `ssh_transfer_status` and stop it with `ssh_transfer_cancel`. Still to do: confirm whether the worker survives a client that kills its whole process tree on exit (it survives the server exiting), and if it does not, start it through the operating system's scheduler (Task Scheduler, `systemd-run`, `launchd`) so it is fully independent.
|
|
217
|
+
- **Resuming automatically after the machine restarts.** Today a transfer whose worker died (shutdown, crash) stays stopped until someone starts it again. Evaluate an option set per transfer, off by default, that restarts it at sign-in. Bounds to keep: only transfers that asked for it; never one that was cancelled or that ended in failure; still subject to the transfer's time limit, counted from the original start; and it must cope with credentials that are not available at sign-in (an SSH agent that is not running yet, a password in an environment variable). Needs something registered with the operating system to run at sign-in, which must be removed when the transfer ends and documented as part of uninstalling. Related: continuing a partly copied file across worker runs, which today works only within one run.
|
|
218
|
+
- **Helping a new session find a transfer that is already running or was interrupted.** A session that did not start a transfer has to connect "my copy from last night" with `ssh_transfer_status`. Options, cheapest first: say so in that tool's description (no extra context, but clients that load tool descriptions on demand may show only the name); MCP server instructions (shown in every session that has the server connected, so they cost a little context even when the server is not used); a client skill shipped in this repository with install and uninstall steps (the most room for a procedure, such as asking which transfer is meant, but specific to one client and one more thing to remove). Start with the tool description and move up only if a session fails to find a transfer.
|
|
219
|
+
- **Testing reconnection against a real host.** Reconnecting and continuing a partly copied file are covered by automated tests against the in-process server only. A live test means cutting the connection mid-transfer on a real machine (stopping its SSH service briefly, or pulling the network), which needs the owner's agreement because a service that does not come back has to be started at the machine.
|
|
220
|
+
- **Cleaning up old transfer records.** The state files in `~/.mcp-ssh/jobs/` are never removed. Decide on a rule (by age, by count, or a tool to clear finished ones), and make sure it never removes the record of a transfer that is still running.
|
|
221
|
+
- **Listing more than the 20 most recent transfers.** `ssh_transfer_status` without an id shows only the newest 20. Consider a filter (running only, by host) or paging.
|
|
222
|
+
|
|
223
|
+
## Development
|
|
224
|
+
|
|
225
|
+
```sh
|
|
226
|
+
npm run typecheck # type-check src and test
|
|
227
|
+
npm test # build, then run all tests
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
Tests start a real SSH server in-process (using `ssh2`), with an SFTP subsystem served from a temporary directory, and drive the built MCP server over stdio with the official MCP client. No external host is needed.
|
|
231
|
+
|
|
232
|
+
See [CLAUDE.md](CLAUDE.md) for the code layout, [Docs/Changelog.md](Docs/Changelog.md) for changes, and [Docs/Conventions](Docs/Conventions) for versioning and workflow.
|
|
233
|
+
|
|
234
|
+
## License
|
|
235
|
+
|
|
236
|
+
[MIT](LICENSE)
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import * as z from 'zod';
|
|
5
|
+
const authSchema = z.discriminatedUnion('type', [
|
|
6
|
+
z.strictObject({ type: z.literal('agent') }),
|
|
7
|
+
z.strictObject({
|
|
8
|
+
type: z.literal('key'),
|
|
9
|
+
path: z.string().min(1),
|
|
10
|
+
/** Name of the environment variable holding the key's passphrase. */
|
|
11
|
+
passphraseEnv: z.string().min(1).optional(),
|
|
12
|
+
}),
|
|
13
|
+
z.strictObject({
|
|
14
|
+
type: z.literal('password'),
|
|
15
|
+
/** Name of the environment variable holding the password. */
|
|
16
|
+
env: z.string().min(1),
|
|
17
|
+
}),
|
|
18
|
+
]);
|
|
19
|
+
const hostSchema = z.strictObject({
|
|
20
|
+
/** One address, or several for the same machine, tried in order until one is reachable. */
|
|
21
|
+
host: z.union([z.string().min(1), z.array(z.string().min(1)).min(1).max(8)]),
|
|
22
|
+
port: z.number().int().min(1).max(65535).default(22),
|
|
23
|
+
username: z.string().min(1),
|
|
24
|
+
auth: authSchema.default({ type: 'agent' }),
|
|
25
|
+
/** Pins the server's host key, in the `SHA256:...` form `ssh-keygen -lf` prints. */
|
|
26
|
+
hostKeyFingerprint: z
|
|
27
|
+
.string()
|
|
28
|
+
.regex(/^SHA256:[A-Za-z0-9+/]{43}=?$/, 'expected a SHA256:<base64> fingerprint')
|
|
29
|
+
.optional(),
|
|
30
|
+
/** The shell the host runs commands in: `posix` (sh, bash, zsh) or `cmd` (Windows OpenSSH default). */
|
|
31
|
+
shell: z.enum(['posix', 'cmd']).default('posix'),
|
|
32
|
+
description: z.string().optional(),
|
|
33
|
+
});
|
|
34
|
+
const configSchema = z.strictObject({
|
|
35
|
+
hosts: z.record(z.string().regex(/^[A-Za-z0-9._-]+$/, 'host names may use letters, digits, ".", "_" and "-"'), hostSchema),
|
|
36
|
+
});
|
|
37
|
+
/** The addresses to try for a host, in order. */
|
|
38
|
+
export function hostAddresses(host) {
|
|
39
|
+
return typeof host.host === 'string' ? [host.host] : host.host;
|
|
40
|
+
}
|
|
41
|
+
export function defaultConfigPath(env = process.env) {
|
|
42
|
+
return env.MCP_SSH_CONFIG ?? join(homedir(), '.mcp-ssh', 'hosts.json');
|
|
43
|
+
}
|
|
44
|
+
export function expandHome(path) {
|
|
45
|
+
if (path === '~')
|
|
46
|
+
return homedir();
|
|
47
|
+
if (path.startsWith('~/') || path.startsWith('~\\'))
|
|
48
|
+
return join(homedir(), path.slice(2));
|
|
49
|
+
return path;
|
|
50
|
+
}
|
|
51
|
+
export function parseConfig(json) {
|
|
52
|
+
let raw;
|
|
53
|
+
try {
|
|
54
|
+
raw = JSON.parse(json);
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
throw new Error(`config is not valid JSON: ${error.message}`);
|
|
58
|
+
}
|
|
59
|
+
const result = configSchema.safeParse(raw);
|
|
60
|
+
if (!result.success)
|
|
61
|
+
throw new Error(`invalid config:\n${z.prettifyError(result.error)}`);
|
|
62
|
+
return result.data;
|
|
63
|
+
}
|
|
64
|
+
/** Loads the host registry. A missing file yields an empty registry so the server can still start. */
|
|
65
|
+
export function loadConfig(path) {
|
|
66
|
+
let json;
|
|
67
|
+
try {
|
|
68
|
+
json = readFileSync(path, 'utf8');
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
if (error.code === 'ENOENT')
|
|
72
|
+
return { hosts: {} };
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
return parseConfig(json);
|
|
76
|
+
}
|
|
77
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AAEzB,MAAM,UAAU,GAAG,CAAC,CAAC,kBAAkB,CAAC,MAAM,EAAE;IAC9C,CAAC,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;IAC5C,CAAC,CAAC,YAAY,CAAC;QACb,IAAI,EAAE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,KAAK,CAAC,6BAA8B,KAAe,CAAC,OAAO,EAAE,CAAC,CAAC;IAC3E,CAAC;IACD,MAAM,MAAM,GAAG,YAAY,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IAC3C,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC1F,OAAO,MAAM,CAAC,IAAI,CAAC;AACrB,CAAC;AAED,sGAAsG;AACtG,MAAM,UAAU,UAAU,CAAC,IAAY;IACrC,IAAI,IAAY,CAAC;IACjB,IAAI,CAAC;QACH,IAAI,GAAG,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACpC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAK,KAA+B,CAAC,IAAI,KAAK,QAAQ;YAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;QAC7E,MAAM,KAAK,CAAC;IACd,CAAC;IACD,OAAO,WAAW,CAAC,IAAI,CAAC,CAAC;AAC3B,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
|
|
4
|
+
import { defaultConfigPath, loadConfig } from './config.js';
|
|
5
|
+
import { createServer } from './server.js';
|
|
6
|
+
import { ConnectionPool } from './ssh/pool.js';
|
|
7
|
+
// stdout carries the MCP protocol, so all diagnostics go to stderr.
|
|
8
|
+
const log = (message) => process.stderr.write(`mcp-ssh: ${message}\n`);
|
|
9
|
+
const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
10
|
+
const configPath = defaultConfigPath();
|
|
11
|
+
let config;
|
|
12
|
+
try {
|
|
13
|
+
config = loadConfig(configPath);
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
log(`cannot load ${configPath}: ${error.message}`);
|
|
17
|
+
process.exit(1);
|
|
18
|
+
}
|
|
19
|
+
const pool = new ConnectionPool(config);
|
|
20
|
+
const server = createServer(config, pool, { version, configPath });
|
|
21
|
+
let closing = false;
|
|
22
|
+
const shutdown = async () => {
|
|
23
|
+
if (closing)
|
|
24
|
+
return;
|
|
25
|
+
closing = true;
|
|
26
|
+
await pool.closeAll();
|
|
27
|
+
await server.close().catch(() => { });
|
|
28
|
+
process.exit(0);
|
|
29
|
+
};
|
|
30
|
+
process.on('SIGINT', shutdown);
|
|
31
|
+
process.on('SIGTERM', shutdown);
|
|
32
|
+
// Open SSH connections keep the process alive, so exit explicitly when the client goes away.
|
|
33
|
+
process.stdin.on('end', shutdown);
|
|
34
|
+
process.stdin.on('close', shutdown);
|
|
35
|
+
await server.connect(new StdioServerTransport());
|
|
36
|
+
log(`v${version} ready, ${Object.keys(config.hosts).length} host(s) from ${configPath}`);
|
|
37
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAE/C,oEAAoE;AACpE,MAAM,GAAG,GAAG,CAAC,OAAe,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,YAAY,OAAO,IAAI,CAAC,CAAC;AAE/E,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,KAAK,CAC5B,YAAY,CAAC,IAAI,GAAG,CAAC,iB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