ssh-connector-mcp 0.1.0__py3-none-any.whl
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.
- ssh_connector_mcp/__init__.py +3 -0
- ssh_connector_mcp/__main__.py +4 -0
- ssh_connector_mcp/server.py +149 -0
- ssh_connector_mcp/session.py +399 -0
- ssh_connector_mcp-0.1.0.dist-info/METADATA +226 -0
- ssh_connector_mcp-0.1.0.dist-info/RECORD +8 -0
- ssh_connector_mcp-0.1.0.dist-info/WHEEL +4 -0
- ssh_connector_mcp-0.1.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""MCP server exposing basic SSH operations over stdio."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import atexit
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from mcp.server.fastmcp import FastMCP
|
|
9
|
+
|
|
10
|
+
from . import session as ssh
|
|
11
|
+
|
|
12
|
+
mcp = FastMCP(
|
|
13
|
+
"ssh-connector",
|
|
14
|
+
instructions=(
|
|
15
|
+
"Minimal SSH connector. Open a session with ssh_connect, reuse its session_id for "
|
|
16
|
+
"ssh_execute, ssh_upload_file, ssh_download_file and ssh_list_directory, then call "
|
|
17
|
+
"ssh_disconnect. Host keys are always verified against known_hosts."
|
|
18
|
+
),
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
_manager = ssh.SessionManager()
|
|
22
|
+
atexit.register(_manager.close_all)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@mcp.tool()
|
|
26
|
+
def ssh_connect(
|
|
27
|
+
host: str,
|
|
28
|
+
username: str,
|
|
29
|
+
password: str | None = None,
|
|
30
|
+
private_key_path: str | None = None,
|
|
31
|
+
private_key_passphrase: str | None = None,
|
|
32
|
+
known_hosts_path: str | None = None,
|
|
33
|
+
port: int = ssh.DEFAULT_PORT,
|
|
34
|
+
session_id: str = ssh.DEFAULT_SESSION_ID,
|
|
35
|
+
connect_timeout: float = 15,
|
|
36
|
+
) -> dict[str, Any]:
|
|
37
|
+
"""Open an SSH session and keep it open for later tool calls.
|
|
38
|
+
|
|
39
|
+
Authenticate with either a password or a private key file. The server host key must
|
|
40
|
+
already be trusted in ~/.ssh/known_hosts (or the file given via known_hosts_path);
|
|
41
|
+
unknown keys are rejected and their SHA256 fingerprint is reported in the error.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
host: Remote hostname or IP address.
|
|
45
|
+
username: SSH login name.
|
|
46
|
+
password: Password for password authentication.
|
|
47
|
+
private_key_path: Path to a private key file (RSA/ECDSA/Ed25519).
|
|
48
|
+
private_key_passphrase: Passphrase that protects the private key, if any.
|
|
49
|
+
known_hosts_path: Extra known_hosts file to trust in addition to ~/.ssh/known_hosts.
|
|
50
|
+
port: SSH port.
|
|
51
|
+
session_id: Name used to address this session in later tool calls.
|
|
52
|
+
connect_timeout: TCP/banner/auth timeout in seconds.
|
|
53
|
+
"""
|
|
54
|
+
_, info = ssh.connect(
|
|
55
|
+
_manager,
|
|
56
|
+
session_id=session_id,
|
|
57
|
+
host=host,
|
|
58
|
+
username=username,
|
|
59
|
+
password=password,
|
|
60
|
+
private_key_path=private_key_path,
|
|
61
|
+
private_key_passphrase=private_key_passphrase,
|
|
62
|
+
known_hosts_path=known_hosts_path,
|
|
63
|
+
port=port,
|
|
64
|
+
connect_timeout=connect_timeout,
|
|
65
|
+
)
|
|
66
|
+
return info
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@mcp.tool()
|
|
70
|
+
def ssh_disconnect(session_id: str = ssh.DEFAULT_SESSION_ID) -> dict[str, Any]:
|
|
71
|
+
"""Close an SSH session and forget it.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
session_id: Session to close. Closing an unknown session is reported, not an error.
|
|
75
|
+
"""
|
|
76
|
+
return ssh.disconnect(_manager, session_id)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@mcp.tool()
|
|
80
|
+
def ssh_execute(
|
|
81
|
+
command: str,
|
|
82
|
+
session_id: str = ssh.DEFAULT_SESSION_ID,
|
|
83
|
+
timeout: float = ssh.DEFAULT_COMMAND_TIMEOUT,
|
|
84
|
+
) -> dict[str, Any]:
|
|
85
|
+
"""Run one non-interactive command and return its stdout, stderr and exit status.
|
|
86
|
+
|
|
87
|
+
Each stdout/stderr stream is capped at 1 MiB; when output is cut, `truncated` is true.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
command: Shell command to run on the remote host.
|
|
91
|
+
session_id: Session opened by ssh_connect.
|
|
92
|
+
timeout: Maximum seconds to wait for the command to finish.
|
|
93
|
+
"""
|
|
94
|
+
return ssh.execute_command(_manager.get(session_id), command, timeout)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@mcp.tool()
|
|
98
|
+
def ssh_upload_file(
|
|
99
|
+
local_path: str,
|
|
100
|
+
remote_path: str,
|
|
101
|
+
session_id: str = ssh.DEFAULT_SESSION_ID,
|
|
102
|
+
) -> dict[str, Any]:
|
|
103
|
+
"""Upload a local file to the remote host over SFTP, overwriting it if present.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
local_path: Path to the file on the machine running this MCP server.
|
|
107
|
+
remote_path: Destination path on the remote host.
|
|
108
|
+
session_id: Session opened by ssh_connect.
|
|
109
|
+
"""
|
|
110
|
+
return ssh.upload_file(_manager.get(session_id), local_path, remote_path)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@mcp.tool()
|
|
114
|
+
def ssh_download_file(
|
|
115
|
+
remote_path: str,
|
|
116
|
+
local_path: str,
|
|
117
|
+
session_id: str = ssh.DEFAULT_SESSION_ID,
|
|
118
|
+
) -> dict[str, Any]:
|
|
119
|
+
"""Download a remote file over SFTP, creating local parent directories as needed.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
remote_path: Source file path on the remote host.
|
|
123
|
+
local_path: Destination path on the machine running this MCP server.
|
|
124
|
+
session_id: Session opened by ssh_connect.
|
|
125
|
+
"""
|
|
126
|
+
return ssh.download_file(_manager.get(session_id), remote_path, local_path)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@mcp.tool()
|
|
130
|
+
def ssh_list_directory(
|
|
131
|
+
remote_path: str = ".",
|
|
132
|
+
session_id: str = ssh.DEFAULT_SESSION_ID,
|
|
133
|
+
) -> dict[str, Any]:
|
|
134
|
+
"""List a remote directory with name, type, size, mode and modification time.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
remote_path: Directory to list on the remote host.
|
|
138
|
+
session_id: Session opened by ssh_connect.
|
|
139
|
+
"""
|
|
140
|
+
return ssh.list_directory(_manager.get(session_id), remote_path)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def main() -> None:
|
|
144
|
+
"""Run the MCP server on stdio."""
|
|
145
|
+
mcp.run(transport="stdio")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
if __name__ == "__main__":
|
|
149
|
+
main()
|
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
"""SSH session management and operations backed by paramiko."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
import os
|
|
8
|
+
import posixpath
|
|
9
|
+
import stat
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from datetime import datetime, timezone
|
|
14
|
+
|
|
15
|
+
import paramiko
|
|
16
|
+
|
|
17
|
+
DEFAULT_PORT = 22
|
|
18
|
+
DEFAULT_SESSION_ID = "default"
|
|
19
|
+
DEFAULT_COMMAND_TIMEOUT = 60
|
|
20
|
+
KEEPALIVE_SECONDS = 30
|
|
21
|
+
MAX_CAPTURE_BYTES = 1024 * 1024
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class SSHConnectorError(RuntimeError):
|
|
25
|
+
"""Error whose message is meant to be shown to the MCP client."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class UnknownHostKeyError(SSHConnectorError):
|
|
29
|
+
"""Raised when the remote host key is missing from or differs from known_hosts."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def host_key_fingerprint(key: paramiko.PKey) -> str:
|
|
33
|
+
"""Return the OpenSSH-style SHA256 fingerprint of a host key."""
|
|
34
|
+
digest = hashlib.sha256(key.asbytes()).digest()
|
|
35
|
+
return "SHA256:" + base64.b64encode(digest).decode("ascii").rstrip("=")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _StrictHostKeyPolicy(paramiko.MissingHostKeyPolicy):
|
|
39
|
+
"""Reject unknown host keys, but report the fingerprint so it can be verified."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, port: int) -> None:
|
|
42
|
+
self._port = port
|
|
43
|
+
|
|
44
|
+
def missing_host_key(self, client: paramiko.SSHClient, hostname: str, key: paramiko.PKey) -> None:
|
|
45
|
+
if hostname.startswith("[") and "]:" in hostname:
|
|
46
|
+
host, _, port_text = hostname[1:].partition("]:")
|
|
47
|
+
port = int(port_text)
|
|
48
|
+
else:
|
|
49
|
+
host, port = hostname, self._port
|
|
50
|
+
entry = host if port == DEFAULT_PORT else f"[{host}]:{port}"
|
|
51
|
+
raise UnknownHostKeyError(
|
|
52
|
+
f"Host key verification failed for {host}:{port}. The server presented "
|
|
53
|
+
f"{key.get_name()} {host_key_fingerprint(key)}, which does not match any trusted key "
|
|
54
|
+
f"in known_hosts. Verify this fingerprint out of band, then add it with "
|
|
55
|
+
f"`ssh-keyscan -p {port} {host} >> ~/.ssh/known_hosts` "
|
|
56
|
+
f"(the known_hosts entry will be {entry})."
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class SSHSession:
|
|
62
|
+
session_id: str
|
|
63
|
+
host: str
|
|
64
|
+
port: int
|
|
65
|
+
username: str
|
|
66
|
+
client: paramiko.SSHClient
|
|
67
|
+
lock: threading.RLock = field(default_factory=threading.RLock)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class SessionManager:
|
|
71
|
+
"""Tracks live SSH sessions by id."""
|
|
72
|
+
|
|
73
|
+
def __init__(self) -> None:
|
|
74
|
+
self._sessions: dict[str, SSHSession] = {}
|
|
75
|
+
self._lock = threading.Lock()
|
|
76
|
+
|
|
77
|
+
def add(self, session: SSHSession) -> None:
|
|
78
|
+
with self._lock:
|
|
79
|
+
if session.session_id in self._sessions:
|
|
80
|
+
raise SSHConnectorError(
|
|
81
|
+
f"An SSH session named '{session.session_id}' already exists. "
|
|
82
|
+
"Disconnect it first or use a different session_id."
|
|
83
|
+
)
|
|
84
|
+
self._sessions[session.session_id] = session
|
|
85
|
+
|
|
86
|
+
def get(self, session_id: str) -> SSHSession:
|
|
87
|
+
with self._lock:
|
|
88
|
+
session = self._sessions.get(session_id)
|
|
89
|
+
if session is None:
|
|
90
|
+
known = ", ".join(sorted(self._sessions)) or "none"
|
|
91
|
+
raise SSHConnectorError(
|
|
92
|
+
f"No open SSH session named '{session_id}' (open sessions: {known}). "
|
|
93
|
+
"Call ssh_connect first."
|
|
94
|
+
)
|
|
95
|
+
return session
|
|
96
|
+
|
|
97
|
+
def remove(self, session_id: str) -> SSHSession | None:
|
|
98
|
+
with self._lock:
|
|
99
|
+
return self._sessions.pop(session_id, None)
|
|
100
|
+
|
|
101
|
+
def close_all(self) -> None:
|
|
102
|
+
with self._lock:
|
|
103
|
+
sessions = list(self._sessions.values())
|
|
104
|
+
self._sessions.clear()
|
|
105
|
+
for session in sessions:
|
|
106
|
+
session.client.close()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _known_hosts_files(extra: str | None) -> list[str]:
|
|
110
|
+
files: list[str] = []
|
|
111
|
+
default = os.path.join(os.path.expanduser("~"), ".ssh", "known_hosts")
|
|
112
|
+
if os.path.isfile(default):
|
|
113
|
+
files.append(default)
|
|
114
|
+
if extra:
|
|
115
|
+
path = os.path.abspath(os.path.expanduser(extra))
|
|
116
|
+
if not os.path.isfile(path):
|
|
117
|
+
raise SSHConnectorError(f"known_hosts file not found: {path}")
|
|
118
|
+
if path not in files:
|
|
119
|
+
files.append(path)
|
|
120
|
+
return files
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _ensure_active(session: SSHSession) -> None:
|
|
124
|
+
transport = session.client.get_transport()
|
|
125
|
+
if transport is None or not transport.is_active():
|
|
126
|
+
raise SSHConnectorError(
|
|
127
|
+
f"Session '{session.session_id}' is no longer connected. Call ssh_connect again."
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def connect(
|
|
132
|
+
manager: SessionManager,
|
|
133
|
+
*,
|
|
134
|
+
session_id: str,
|
|
135
|
+
host: str,
|
|
136
|
+
username: str,
|
|
137
|
+
password: str | None,
|
|
138
|
+
private_key_path: str | None,
|
|
139
|
+
private_key_passphrase: str | None,
|
|
140
|
+
known_hosts_path: str | None,
|
|
141
|
+
port: int,
|
|
142
|
+
connect_timeout: float,
|
|
143
|
+
) -> tuple[SSHSession, dict]:
|
|
144
|
+
"""Open a session, leaving it registered in ``manager``."""
|
|
145
|
+
if not host.strip():
|
|
146
|
+
raise SSHConnectorError("`host` must not be empty.")
|
|
147
|
+
if not username.strip():
|
|
148
|
+
raise SSHConnectorError("`username` must not be empty.")
|
|
149
|
+
if not 1 <= port <= 65535:
|
|
150
|
+
raise SSHConnectorError("`port` must be between 1 and 65535.")
|
|
151
|
+
if connect_timeout <= 0:
|
|
152
|
+
raise SSHConnectorError("`connect_timeout` must be greater than 0.")
|
|
153
|
+
if not password and not private_key_path:
|
|
154
|
+
raise SSHConnectorError("Provide authentication via `password` or `private_key_path`.")
|
|
155
|
+
|
|
156
|
+
key_path: str | None = None
|
|
157
|
+
if private_key_path:
|
|
158
|
+
key_path = os.path.abspath(os.path.expanduser(private_key_path))
|
|
159
|
+
if not os.path.isfile(key_path):
|
|
160
|
+
raise SSHConnectorError(f"Private key file not found: {key_path}")
|
|
161
|
+
|
|
162
|
+
known_hosts = _known_hosts_files(known_hosts_path)
|
|
163
|
+
|
|
164
|
+
client = paramiko.SSHClient()
|
|
165
|
+
client.set_missing_host_key_policy(_StrictHostKeyPolicy(port))
|
|
166
|
+
try:
|
|
167
|
+
for path in known_hosts:
|
|
168
|
+
client.load_host_keys(path)
|
|
169
|
+
client.connect(
|
|
170
|
+
hostname=host,
|
|
171
|
+
port=port,
|
|
172
|
+
username=username,
|
|
173
|
+
password=password or None,
|
|
174
|
+
key_filename=key_path,
|
|
175
|
+
passphrase=private_key_passphrase or None,
|
|
176
|
+
timeout=connect_timeout,
|
|
177
|
+
banner_timeout=connect_timeout,
|
|
178
|
+
auth_timeout=connect_timeout,
|
|
179
|
+
allow_agent=False,
|
|
180
|
+
look_for_keys=False,
|
|
181
|
+
)
|
|
182
|
+
except SSHConnectorError:
|
|
183
|
+
client.close()
|
|
184
|
+
raise
|
|
185
|
+
except (paramiko.SSHException, OSError, EOFError) as exc:
|
|
186
|
+
client.close()
|
|
187
|
+
raise SSHConnectorError(
|
|
188
|
+
f"Could not connect to {host}:{port} as {username}: {exc}"
|
|
189
|
+
) from exc
|
|
190
|
+
|
|
191
|
+
transport = client.get_transport()
|
|
192
|
+
if transport is None or not transport.is_active():
|
|
193
|
+
client.close()
|
|
194
|
+
raise SSHConnectorError(f"SSH transport to {host}:{port} closed immediately after connect.")
|
|
195
|
+
transport.set_keepalive(KEEPALIVE_SECONDS)
|
|
196
|
+
server_key = transport.get_remote_server_key()
|
|
197
|
+
|
|
198
|
+
session = SSHSession(
|
|
199
|
+
session_id=session_id,
|
|
200
|
+
host=host,
|
|
201
|
+
port=port,
|
|
202
|
+
username=username,
|
|
203
|
+
client=client,
|
|
204
|
+
)
|
|
205
|
+
try:
|
|
206
|
+
manager.add(session)
|
|
207
|
+
except SSHConnectorError:
|
|
208
|
+
client.close()
|
|
209
|
+
raise
|
|
210
|
+
|
|
211
|
+
return session, {
|
|
212
|
+
"session_id": session_id,
|
|
213
|
+
"host": host,
|
|
214
|
+
"port": port,
|
|
215
|
+
"username": username,
|
|
216
|
+
"server_banner": transport.remote_version,
|
|
217
|
+
"host_key_type": server_key.get_name(),
|
|
218
|
+
"host_key_fingerprint": host_key_fingerprint(server_key),
|
|
219
|
+
"known_hosts_files": known_hosts,
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def disconnect(manager: SessionManager, session_id: str) -> dict:
|
|
224
|
+
session = manager.remove(session_id)
|
|
225
|
+
if session is None:
|
|
226
|
+
return {
|
|
227
|
+
"session_id": session_id,
|
|
228
|
+
"disconnected": False,
|
|
229
|
+
"message": "No open session with that id.",
|
|
230
|
+
}
|
|
231
|
+
with session.lock:
|
|
232
|
+
session.client.close()
|
|
233
|
+
return {"session_id": session_id, "disconnected": True}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def execute_command(session: SSHSession, command: str, timeout: float) -> dict:
|
|
237
|
+
if not command.strip():
|
|
238
|
+
raise SSHConnectorError("`command` must not be empty.")
|
|
239
|
+
if timeout <= 0:
|
|
240
|
+
raise SSHConnectorError("`timeout` must be greater than 0.")
|
|
241
|
+
_ensure_active(session)
|
|
242
|
+
|
|
243
|
+
stdout = bytearray()
|
|
244
|
+
stderr = bytearray()
|
|
245
|
+
truncated = False
|
|
246
|
+
exit_status: int | None = None
|
|
247
|
+
|
|
248
|
+
with session.lock:
|
|
249
|
+
_ensure_active(session)
|
|
250
|
+
transport = session.client.get_transport()
|
|
251
|
+
channel = transport.open_session(timeout=timeout)
|
|
252
|
+
channel.settimeout(timeout)
|
|
253
|
+
try:
|
|
254
|
+
channel.exec_command(command)
|
|
255
|
+
deadline = time.monotonic() + timeout
|
|
256
|
+
while True:
|
|
257
|
+
if time.monotonic() >= deadline:
|
|
258
|
+
raise SSHConnectorError(
|
|
259
|
+
f"Command did not finish within {timeout}s and its channel was closed: {command!r}"
|
|
260
|
+
)
|
|
261
|
+
if channel.recv_ready():
|
|
262
|
+
chunk = channel.recv(32768)
|
|
263
|
+
room = MAX_CAPTURE_BYTES - len(stdout)
|
|
264
|
+
if len(chunk) > room:
|
|
265
|
+
truncated = True
|
|
266
|
+
stdout.extend(chunk[:room])
|
|
267
|
+
elif channel.recv_stderr_ready():
|
|
268
|
+
chunk = channel.recv_stderr(32768)
|
|
269
|
+
room = MAX_CAPTURE_BYTES - len(stderr)
|
|
270
|
+
if len(chunk) > room:
|
|
271
|
+
truncated = True
|
|
272
|
+
stderr.extend(chunk[:room])
|
|
273
|
+
elif channel.exit_status_ready() and channel.eof_received:
|
|
274
|
+
break
|
|
275
|
+
else:
|
|
276
|
+
time.sleep(0.02)
|
|
277
|
+
exit_status = channel.recv_exit_status()
|
|
278
|
+
except SSHConnectorError:
|
|
279
|
+
raise
|
|
280
|
+
except (paramiko.SSHException, OSError, EOFError) as exc:
|
|
281
|
+
raise SSHConnectorError(f"Failed to execute command {command!r}: {exc}") from exc
|
|
282
|
+
finally:
|
|
283
|
+
channel.close()
|
|
284
|
+
|
|
285
|
+
return {
|
|
286
|
+
"session_id": session.session_id,
|
|
287
|
+
"command": command,
|
|
288
|
+
"exit_status": exit_status,
|
|
289
|
+
"stdout": stdout.decode("utf-8", errors="replace"),
|
|
290
|
+
"stderr": stderr.decode("utf-8", errors="replace"),
|
|
291
|
+
"truncated": truncated,
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def upload_file(session: SSHSession, local_path: str, remote_path: str) -> dict:
|
|
296
|
+
local = os.path.abspath(os.path.expanduser(local_path))
|
|
297
|
+
if not os.path.isfile(local):
|
|
298
|
+
raise SSHConnectorError(f"Local file not found: {local}")
|
|
299
|
+
if not remote_path:
|
|
300
|
+
raise SSHConnectorError("`remote_path` must not be empty.")
|
|
301
|
+
_ensure_active(session)
|
|
302
|
+
|
|
303
|
+
with session.lock:
|
|
304
|
+
try:
|
|
305
|
+
sftp = session.client.open_sftp()
|
|
306
|
+
try:
|
|
307
|
+
attrs = sftp.put(local, remote_path, confirm=True)
|
|
308
|
+
finally:
|
|
309
|
+
sftp.close()
|
|
310
|
+
except (paramiko.SSHException, OSError, EOFError) as exc:
|
|
311
|
+
raise SSHConnectorError(f"Upload of {local} to {remote_path} failed: {exc}") from exc
|
|
312
|
+
|
|
313
|
+
return {
|
|
314
|
+
"session_id": session.session_id,
|
|
315
|
+
"local_path": local,
|
|
316
|
+
"remote_path": remote_path,
|
|
317
|
+
"size": attrs.st_size,
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def download_file(session: SSHSession, remote_path: str, local_path: str) -> dict:
|
|
322
|
+
if not remote_path:
|
|
323
|
+
raise SSHConnectorError("`remote_path` must not be empty.")
|
|
324
|
+
local = os.path.abspath(os.path.expanduser(local_path))
|
|
325
|
+
_ensure_active(session)
|
|
326
|
+
|
|
327
|
+
with session.lock:
|
|
328
|
+
try:
|
|
329
|
+
sftp = session.client.open_sftp()
|
|
330
|
+
try:
|
|
331
|
+
attrs = sftp.stat(remote_path)
|
|
332
|
+
parent = os.path.dirname(local)
|
|
333
|
+
if parent:
|
|
334
|
+
os.makedirs(parent, exist_ok=True)
|
|
335
|
+
sftp.get(remote_path, local)
|
|
336
|
+
finally:
|
|
337
|
+
sftp.close()
|
|
338
|
+
except (paramiko.SSHException, OSError, EOFError) as exc:
|
|
339
|
+
raise SSHConnectorError(f"Download of {remote_path} to {local} failed: {exc}") from exc
|
|
340
|
+
|
|
341
|
+
return {
|
|
342
|
+
"session_id": session.session_id,
|
|
343
|
+
"remote_path": remote_path,
|
|
344
|
+
"local_path": local,
|
|
345
|
+
"size": attrs.st_size,
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def list_directory(session: SSHSession, remote_path: str) -> dict:
|
|
350
|
+
if not remote_path:
|
|
351
|
+
raise SSHConnectorError("`remote_path` must not be empty.")
|
|
352
|
+
_ensure_active(session)
|
|
353
|
+
|
|
354
|
+
with session.lock:
|
|
355
|
+
try:
|
|
356
|
+
sftp = session.client.open_sftp()
|
|
357
|
+
try:
|
|
358
|
+
attrs = sftp.listdir_attr(remote_path)
|
|
359
|
+
finally:
|
|
360
|
+
sftp.close()
|
|
361
|
+
except (paramiko.SSHException, OSError, EOFError) as exc:
|
|
362
|
+
raise SSHConnectorError(f"Could not list {remote_path}: {exc}") from exc
|
|
363
|
+
|
|
364
|
+
entries = []
|
|
365
|
+
for attr in sorted(attrs, key=lambda item: item.filename.lower()):
|
|
366
|
+
mode = attr.st_mode
|
|
367
|
+
if mode is None:
|
|
368
|
+
kind = "unknown"
|
|
369
|
+
mode_text = None
|
|
370
|
+
elif stat.S_ISDIR(mode):
|
|
371
|
+
kind = "dir"
|
|
372
|
+
mode_text = stat.filemode(mode)
|
|
373
|
+
elif stat.S_ISLNK(mode):
|
|
374
|
+
kind = "symlink"
|
|
375
|
+
mode_text = stat.filemode(mode)
|
|
376
|
+
else:
|
|
377
|
+
kind = "file"
|
|
378
|
+
mode_text = stat.filemode(mode)
|
|
379
|
+
entries.append(
|
|
380
|
+
{
|
|
381
|
+
"name": attr.filename,
|
|
382
|
+
"path": posixpath.join(remote_path, attr.filename),
|
|
383
|
+
"type": kind,
|
|
384
|
+
"size": attr.st_size or 0,
|
|
385
|
+
"mode": mode_text,
|
|
386
|
+
"modified": (
|
|
387
|
+
datetime.fromtimestamp(attr.st_mtime, tz=timezone.utc).isoformat()
|
|
388
|
+
if attr.st_mtime
|
|
389
|
+
else None
|
|
390
|
+
),
|
|
391
|
+
}
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
return {
|
|
395
|
+
"session_id": session.session_id,
|
|
396
|
+
"path": remote_path,
|
|
397
|
+
"count": len(entries),
|
|
398
|
+
"entries": entries,
|
|
399
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ssh-connector-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Minimal SSH connector exposed as an MCP server over stdio, built on paramiko.
|
|
5
|
+
Author: newtouch
|
|
6
|
+
Keywords: mcp,paramiko,remote,sftp,ssh
|
|
7
|
+
Classifier: Development Status :: 4 - Beta
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Topic :: System :: Systems Administration
|
|
13
|
+
Classifier: Topic :: Terminals
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Requires-Dist: mcp<2.0.0,>=1.10.0
|
|
16
|
+
Requires-Dist: paramiko<5.0.0,>=3.4.0
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# SSH Connector MCP
|
|
20
|
+
|
|
21
|
+
一个最小化的 SSH 连接器,以 MCP(Model Context Protocol)server 的形式提供,使用 **stdio** 传输,可被任意 MCP 客户端(Trae、Claude Desktop、Cursor 等)直接配置加载。底层基于 Python + [paramiko](https://www.paramiko.org/)。
|
|
22
|
+
|
|
23
|
+
只提供常规 SSH 基础操作:连接/断开、远程执行命令、上传文件、下载文件、列出远程目录。支持密码与私钥两种认证方式,**主机指纹始终校验,不提供跳过开关**。
|
|
24
|
+
|
|
25
|
+
## 目录结构
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
ssh-connector-mcp/
|
|
29
|
+
├── pyproject.toml # 项目与依赖声明、MCP 入口
|
|
30
|
+
├── requirements.txt # 依赖列表(pip install -r 用)
|
|
31
|
+
├── README.md
|
|
32
|
+
└── src/
|
|
33
|
+
└── ssh_connector_mcp/
|
|
34
|
+
├── __init__.py
|
|
35
|
+
├── __main__.py # python -m ssh_connector_mcp
|
|
36
|
+
├── server.py # MCP 工具定义 + stdio 启动
|
|
37
|
+
└── session.py # 会话管理、SSH/SFTP 操作、主机指纹校验
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## 安装
|
|
41
|
+
|
|
42
|
+
要求 Python 3.10+。
|
|
43
|
+
|
|
44
|
+
```powershell
|
|
45
|
+
cd ssh-connector-mcp
|
|
46
|
+
python -m venv .venv
|
|
47
|
+
.\.venv\Scripts\python.exe -m pip install -e .
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
(Linux/macOS 下使用 `.venv/bin/python -m pip install -e .`。)
|
|
51
|
+
|
|
52
|
+
安装后会生成 `ssh-connector-mcp` 命令(位于虚拟环境的 `Scripts/` 或 `bin/` 下),等价于 `python -m ssh_connector_mcp`。
|
|
53
|
+
|
|
54
|
+
## MCP 客户端配置示例
|
|
55
|
+
|
|
56
|
+
把项目虚拟环境中的 Python 绝对路径填入 `command`(Windows 路径中的反斜杠需要写成 `\\`):
|
|
57
|
+
|
|
58
|
+
```json
|
|
59
|
+
{
|
|
60
|
+
"mcpServers": {
|
|
61
|
+
"ssh-connector": {
|
|
62
|
+
"command": "C:\\path\\to\\ssh-connector-mcp\\.venv\\Scripts\\python.exe",
|
|
63
|
+
"args": ["-m", "ssh_connector_mcp"]
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
如果虚拟环境的 `Scripts`/`bin` 已在 `PATH` 中,也可以直接使用安装好的入口:
|
|
70
|
+
|
|
71
|
+
```json
|
|
72
|
+
{
|
|
73
|
+
"mcpServers": {
|
|
74
|
+
"ssh-connector": {
|
|
75
|
+
"command": "ssh-connector-mcp"
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
两种方式都是 stdio 传输,无需额外参数或环境变量。
|
|
82
|
+
|
|
83
|
+
## 作为 Trae 插件使用(PyPI + uvx)
|
|
84
|
+
|
|
85
|
+
`plugin/` 目录是按 Trae 插件结构组织的跨平台插件包,运行时由 `uvx` 从 PyPI 拉取,不包含任何平台相关的二进制:
|
|
86
|
+
|
|
87
|
+
```
|
|
88
|
+
plugin/
|
|
89
|
+
├── .trae-plugin/plugin.json # 插件清单(名称、版本、图标、i18n 描述)
|
|
90
|
+
├── .mcp.json # MCP 启动声明:uvx --from ssh-connector-mcp==0.1.0 ssh-connector-mcp
|
|
91
|
+
└── assets/icon.svg
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
前置条件:安装 [uv](https://docs.astral.sh/uv/)(`pip install uv` 或官方安装脚本),并确保 `uvx` 在 `PATH` 中。
|
|
95
|
+
|
|
96
|
+
发布到 PyPI:
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
cd ssh-connector-mcp
|
|
100
|
+
uv build # 生成 dist/*.whl 和 dist/*.tar.gz
|
|
101
|
+
uv publish # 需要 PyPI API token(UV_PUBLISH_TOKEN 或交互输入)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
发布后验证一次:
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
uvx --from ssh-connector-mcp==0.1.0 ssh-connector-mcp
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
本地加载插件:把 `plugin/` 整体放到插件目录(如 `%USERPROFILE%\.trae-cn\plugins\local\ssh-connector\0.1.0\`)后重启客户端;具体的本地加载入口以当前客户端版本为准。提交市场时,该目录内容即为插件包。
|
|
111
|
+
|
|
112
|
+
版本升级时需同步修改三处:`pyproject.toml` 的 `version`、`plugin/.trae-plugin/plugin.json` 的 `version`、`plugin/.mcp.json` 中固定的 `ssh-connector-mcp==x.y.z`。
|
|
113
|
+
|
|
114
|
+
## 主机指纹校验
|
|
115
|
+
|
|
116
|
+
服务端**不会**自动信任未知主机,也不提供 `AutoAddPolicy` 之类的跳过选项:
|
|
117
|
+
|
|
118
|
+
- 连接时加载 `~/.ssh/known_hosts`;如果传入了 `known_hosts_path`,额外加载该文件。
|
|
119
|
+
- 若主机密钥不存在于 known_hosts,或与已记录密钥不一致,连接会被拒绝,错误信息中会给出服务器实际出示的密钥类型与 `SHA256:...` 指纹,以及添加方法,例如:
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
# 先在可信渠道核对该指纹,再执行(非默认端口请带 -p)
|
|
123
|
+
ssh-keyscan -p 22 192.168.1.10 >> ~/.ssh/known_hosts
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
非 22 端口的 known_hosts 条目形式为 `[host]:port`,`ssh-keyscan -p` 会自动按此格式写入。
|
|
127
|
+
|
|
128
|
+
## 工具说明
|
|
129
|
+
|
|
130
|
+
所有工具共用 `session_id` 来定位连接,默认值均为 `"default"`。同一时间可用不同 `session_id` 维持多个连接。
|
|
131
|
+
|
|
132
|
+
### `ssh_connect`
|
|
133
|
+
|
|
134
|
+
建立并保留一个 SSH 会话。
|
|
135
|
+
|
|
136
|
+
| 参数 | 类型 | 默认值 | 说明 |
|
|
137
|
+
| --- | --- | --- | --- |
|
|
138
|
+
| `host` | string | 必填 | 远程主机名或 IP |
|
|
139
|
+
| `username` | string | 必填 | 登录用户名 |
|
|
140
|
+
| `password` | string | `null` | 密码认证;与 `private_key_path` 至少提供一个 |
|
|
141
|
+
| `private_key_path` | string | `null` | 私钥文件路径(RSA/ECDSA/Ed25519),支持 `~` |
|
|
142
|
+
| `private_key_passphrase` | string | `null` | 私钥口令(如私钥有加密) |
|
|
143
|
+
| `known_hosts_path` | string | `null` | 额外信任的 known_hosts 文件;不存在会报错 |
|
|
144
|
+
| `port` | integer | `22` | SSH 端口 |
|
|
145
|
+
| `session_id` | string | `"default"` | 会话名,供后续工具使用;重名会报错 |
|
|
146
|
+
| `connect_timeout` | number | `15` | TCP/握手/认证超时(秒) |
|
|
147
|
+
|
|
148
|
+
返回:`session_id`、`host`、`port`、`username`、`server_banner`、`host_key_type`、`host_key_fingerprint`、`known_hosts_files`。
|
|
149
|
+
|
|
150
|
+
不会使用 ssh-agent,也不会自动搜索 `~/.ssh/id_*`,认证方式完全由参数决定。
|
|
151
|
+
|
|
152
|
+
### `ssh_disconnect`
|
|
153
|
+
|
|
154
|
+
| 参数 | 类型 | 默认值 | 说明 |
|
|
155
|
+
| --- | --- | --- | --- |
|
|
156
|
+
| `session_id` | string | `"default"` | 要关闭的会话 |
|
|
157
|
+
|
|
158
|
+
返回 `disconnected: true`;若会话不存在则返回 `disconnected: false`,不视为错误。
|
|
159
|
+
|
|
160
|
+
### `ssh_execute`
|
|
161
|
+
|
|
162
|
+
执行单条非交互命令,返回输出与退出码。
|
|
163
|
+
|
|
164
|
+
| 参数 | 类型 | 默认值 | 说明 |
|
|
165
|
+
| --- | --- | --- | --- |
|
|
166
|
+
| `command` | string | 必填 | 远程 shell 命令 |
|
|
167
|
+
| `session_id` | string | `"default"` | 已连接的会话 |
|
|
168
|
+
| `timeout` | number | `60` | 命令最长等待秒数;超时会关闭该 channel |
|
|
169
|
+
|
|
170
|
+
返回:`exit_status`、`stdout`、`stderr`、`truncated`(stdout/stderr 各自最多保留 1 MiB,被截断时为 `true`)。命令以 UTF-8 解码,非法字节替换为 `�`。
|
|
171
|
+
|
|
172
|
+
### `ssh_upload_file`
|
|
173
|
+
|
|
174
|
+
通过 SFTP 上传本地文件,远端同名文件会被覆盖。
|
|
175
|
+
|
|
176
|
+
| 参数 | 类型 | 默认值 | 说明 |
|
|
177
|
+
| --- | --- | --- | --- |
|
|
178
|
+
| `local_path` | string | 必填 | 运行本 MCP server 的机器上的文件路径 |
|
|
179
|
+
| `remote_path` | string | 必填 | 远端目标路径(目录需已存在) |
|
|
180
|
+
| `session_id` | string | `"default"` | 已连接的会话 |
|
|
181
|
+
|
|
182
|
+
返回:`local_path`、`remote_path`、`size`。
|
|
183
|
+
|
|
184
|
+
### `ssh_download_file`
|
|
185
|
+
|
|
186
|
+
通过 SFTP 下载远端文件,本地父目录会自动创建。
|
|
187
|
+
|
|
188
|
+
| 参数 | 类型 | 默认值 | 说明 |
|
|
189
|
+
| --- | --- | --- | --- |
|
|
190
|
+
| `remote_path` | string | 必填 | 远端源文件路径 |
|
|
191
|
+
| `local_path` | string | 必填 | 本地目标路径 |
|
|
192
|
+
| `session_id` | string | `"default"` | 已连接的会话 |
|
|
193
|
+
|
|
194
|
+
返回:`remote_path`、`local_path`、`size`。
|
|
195
|
+
|
|
196
|
+
### `ssh_list_directory`
|
|
197
|
+
|
|
198
|
+
列出远端目录内容。
|
|
199
|
+
|
|
200
|
+
| 参数 | 类型 | 默认值 | 说明 |
|
|
201
|
+
| --- | --- | --- | --- |
|
|
202
|
+
| `remote_path` | string | `"."` | 远端目录路径 |
|
|
203
|
+
| `session_id` | string | `"default"` | 已连接的会话 |
|
|
204
|
+
|
|
205
|
+
返回 `path`、`count` 与 `entries`,每个条目包含 `name`、`path`、`type`(`file` / `dir` / `symlink`)、`size`、`mode`(如 `-rw-r--r--`)、`modified`(UTC ISO 8601)。
|
|
206
|
+
|
|
207
|
+
## 典型调用顺序
|
|
208
|
+
|
|
209
|
+
1. `ssh_connect` → 得到一个 `session_id`
|
|
210
|
+
2. `ssh_execute` 执行 `uname -a`、部署命令等
|
|
211
|
+
3. `ssh_list_directory` / `ssh_upload_file` / `ssh_download_file` 处理文件
|
|
212
|
+
4. `ssh_disconnect` 释放连接(不调用也会在进程退出时自动关闭)
|
|
213
|
+
|
|
214
|
+
## 安全说明
|
|
215
|
+
|
|
216
|
+
- 主机密钥严格校验;未知或变更的密钥直接导致连接失败,并返回 SHA256 指纹便于人工核对。
|
|
217
|
+
- 密码、私钥口令只用于当次认证,不会被记录、回显或写入磁盘。
|
|
218
|
+
- 连接禁用 ssh-agent 与默认私钥自动搜索,避免隐式使用预期外的凭据。
|
|
219
|
+
- 每个会话内的操作串行执行(会话级锁),输出总量有上限,命令有超时。
|
|
220
|
+
- 会话仅保存在进程内存中,MCP server 重启后需重新连接。
|
|
221
|
+
|
|
222
|
+
## 已知限制
|
|
223
|
+
|
|
224
|
+
- 只执行单条非交互命令,不提供交互式 shell、PTY 或 `sudo` 密码自动输入。
|
|
225
|
+
- 不提供端口转发、跳板机、密钥生成、递归目录传输等扩展能力。
|
|
226
|
+
- 所有路径均为运行 MCP server 的本地机器视角;文件内容不经过 MCP 消息传递。
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
ssh_connector_mcp/__init__.py,sha256=v4HeywTS7qdI-54zL4fqHai3ycjunvEF0CW5OaYb5Qs,63
|
|
2
|
+
ssh_connector_mcp/__main__.py,sha256=NyuGdzKsVDkoEqOoDosVP1h6qAvgPe6lbqRyA-rO_QA,81
|
|
3
|
+
ssh_connector_mcp/server.py,sha256=aorpoljN-u8TgSJMLbSKXb36b9F-Olj99HkORmz9S5o,4708
|
|
4
|
+
ssh_connector_mcp/session.py,sha256=POqaTaFAoemqJJp7E-d1gN2vjm0qPH1zACy9JOAy2pA,13568
|
|
5
|
+
ssh_connector_mcp-0.1.0.dist-info/METADATA,sha256=Nd-pYKS0VFMQgstmvs1kRnSG20-SQgzCAtzQjMjTK5k,9063
|
|
6
|
+
ssh_connector_mcp-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
ssh_connector_mcp-0.1.0.dist-info/entry_points.txt,sha256=Cv9jPvCrl70yhb80RCVkMDgh5a8wEoBTpbcvryWQJlY,68
|
|
8
|
+
ssh_connector_mcp-0.1.0.dist-info/RECORD,,
|