Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

**`reuse_connection` per-server option (default `true`).** Setting `reuse_connection = false` on a `[servers.*]` block makes every `execute`, `execute_on_group`, `upload_file` and `download_file` operation on that server open a brand-new SSH connection and close it, waiting for the close, right after the operation — on success or error — without ever storing it in the connection pool. It governs only operations run on that host itself: a jump host used as a tunnel is still reached through the shared pool and stays cached (tunnels use direct-tcpip channels, not exec channels). This is needed for Windows OpenSSH hosts that run a `ForceCommand` wrapper: Windows OpenSSH hands every exec channel after the first on one connection the first channel's `SSH_ORIGINAL_COMMAND`, so with a cached connection every command after the first returned the first command's output. The key must be a TOML boolean; a non-boolean value is rejected at load. With the default `true`, behaviour is unchanged.

## [0.9.3] - 2026-12-01

> **Why 0.9.3 and not 0.10.0:** nothing here makes a configuration that started on 0.9.2 refuse to start. The runtime dependency changes are lockfile-only patches (`opentelemetry-api`, `pydantic`); the only new declared floor is a uv constraint, and the container image's interpreter move adds no configuration surface.
Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,15 @@ Note two things about the timeouts, because the names invite confusion:

Per-server overrides (`hostname`, `port`, `user`, `identity_file`, `jump_host`, `default_dir`, `timeout`) take precedence over `~/.ssh/config`. See [config/servers.example.toml](https://github.com/blackaxgit/ssh-mcp/blob/main/config/servers.example.toml) for the annotated reference.

`reuse_connection` (boolean, default `true`) controls connection caching for one server. With `reuse_connection = false`, every `execute`, `execute_on_group`, `upload_file` and `download_file` operation on that server opens a brand-new SSH connection and closes it as soon as the operation finishes (success or error); nothing is cached, so each call pays a full connect and handshake. The setting governs only operations run on that host itself: a jump host used as a tunnel is always reached through the shared connection pool and stays cached whatever its own `reuse_connection` says (tunnels use direct-tcpip channels, not exec channels, so the Windows issue below does not apply to them). Set it to `false` on **Windows hosts whose `sshd` uses a `ForceCommand` wrapper**: Windows OpenSSH gives every exec channel after the first on one SSH connection the *first* channel's `SSH_ORIGINAL_COMMAND`, so over a cached connection every command after the first would silently return the first command's output. Linux and MikroTik hosts are unaffected and should keep the default.

```toml
[servers.win-app-01]
description = "Windows app server behind a ForceCommand wrapper"
groups = ["windows"]
reuse_connection = false
```

Restrict config file permissions to your user:

```bash
Expand Down
10 changes: 10 additions & 0 deletions config/servers.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,16 @@ jump_host = "bastion"
default_dir = "/srv/app"
timeout = 120

# Server whose sshd forces a wrapper command (e.g. Windows OpenSSH with a
# ForceCommand script). Windows OpenSSH gives every exec channel after the
# first on one connection the FIRST channel's SSH_ORIGINAL_COMMAND, so the
# cached connection must not be reused: reuse_connection = false opens a new
# connection per execute/upload/download and closes it afterwards (default true).
[servers.win-app-01]
description = "Windows app server behind a ForceCommand wrapper"
groups = ["staging"]
reuse_connection = false

# Server with multiple groups and custom user
[servers.monitor-01]
description = "Monitoring: Prometheus, Grafana, Alertmanager (Ubuntu 22.04)"
Expand Down
8 changes: 8 additions & 0 deletions src/ssh_mcp/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,13 @@ class ServerConfig:
default_dir: Default working directory for commands
timeout: Override command timeout for this server, in seconds
(1..3600)
reuse_connection: Keep one cached SSH connection for this server and
reuse it across operations (default True). False opens a
brand-new connection for every execute / group execute /
upload / download and closes it right after, never caching it.
Needed for Windows OpenSSH forced-command wrappers, which hand
every exec channel after the first on one connection the FIRST
channel's ``SSH_ORIGINAL_COMMAND``.
"""

name: str
Expand All @@ -181,6 +188,7 @@ class ServerConfig:
jump_host: str | None = None
default_dir: str | None = None
timeout: int | None = Field(default=None, ge=1, le=3600)
reuse_connection: bool = Field(default=True, strict=True)

@field_validator("groups", mode="before")
@classmethod
Expand Down
84 changes: 79 additions & 5 deletions src/ssh_mcp/ssh.py
Original file line number Diff line number Diff line change
Expand Up @@ -1554,6 +1554,7 @@ async def _execute_impl(
stays thin and the complex exit-path logic below does not need
per-branch tracing glue.
"""
fresh_conn: asyncssh.SSHClientConnection | None = None
try:
server = self.registry.get_server(server_name)

Expand Down Expand Up @@ -1619,7 +1620,7 @@ async def _execute_impl(
effective_command = f"cd {shlex.quote(cd_dir)} && {command}"

# Get or create connection
conn = await self._get_connection(server_name)
conn, _, fresh_conn = await self._open_connection(server_name)

# S10: conn.run() buffers the ENTIRE remote output before
# max_output_bytes truncates it — the setting bounded the
Expand Down Expand Up @@ -1875,6 +1876,10 @@ async def _execute_impl(
error=f"Unexpected error: {redacted}",
)

finally:
if fresh_conn is not None:
await self._close_fresh_connection(server_name, fresh_conn)

async def execute_on_group(
self,
group_name: str,
Expand Down Expand Up @@ -2169,9 +2174,12 @@ async def _upload_impl(
)
)
local_fd: int | None = None
fresh_conn: asyncssh.SSHClientConnection | None = None
try:
try:
conn = await self._get_connection(server_name)
conn, connection_id, fresh_conn = await self._open_connection(
server_name
)
except KeyError as e:
# N1: get_server() raises a raw KeyError for an unknown
# server name, outside the documented ValueError/RuntimeError
Expand All @@ -2183,7 +2191,7 @@ async def _upload_impl(
# start/complete/failed lines all share the connection_id.
ctx_tokens.update(
structlog.contextvars.bind_contextvars(
connection_id=self._connection_ids.get(server_name, "unknown"),
connection_id=connection_id,
)
)
self._audit.info("sftp.upload.start")
Expand Down Expand Up @@ -2329,6 +2337,8 @@ async def _upload_impl(
finally:
if local_fd is not None:
os.close(local_fd)
if fresh_conn is not None:
await self._close_fresh_connection(server_name, fresh_conn)
structlog.contextvars.reset_contextvars(**ctx_tokens)

async def download(
Expand Down Expand Up @@ -2409,16 +2419,19 @@ async def _download_impl(
# is created (below) so the cleanup unlink can prove IDENTITY, not
# just path confinement — see _unlink_beneath's docstring.
created_ino: tuple[int, int] | None = None
fresh_conn: asyncssh.SSHClientConnection | None = None
try:
try:
conn = await self._get_connection(server_name)
conn, connection_id, fresh_conn = await self._open_connection(
server_name
)
except KeyError as e:
# N1: see _upload_impl — convert to the documented contract.
raise ValueError(f"Server not found: {e}") from e

ctx_tokens.update(
structlog.contextvars.bind_contextvars(
connection_id=self._connection_ids.get(server_name, "unknown"),
connection_id=connection_id,
)
)
self._audit.info("sftp.download.start")
Expand Down Expand Up @@ -2593,6 +2606,8 @@ async def _download_impl(
finally:
if local_fd is not None:
os.close(local_fd)
if fresh_conn is not None:
await self._close_fresh_connection(server_name, fresh_conn)
structlog.contextvars.reset_contextvars(**ctx_tokens)

async def close_all(self) -> None:
Expand Down Expand Up @@ -2663,6 +2678,65 @@ async def close_all(self) -> None:
os.close(self._transfer_root_fd)
self._transfer_root_fd = None

async def _open_connection(
self, server_name: str
) -> tuple[asyncssh.SSHClientConnection, str, asyncssh.SSHClientConnection | None]:
"""Return a connection for one operation, honouring ``reuse_connection``.

With ``reuse_connection=True`` (the default) this is exactly
``_get_connection``: the cached connection is returned and the third
tuple element is ``None``. With ``reuse_connection=False`` a brand-new
connection is built via ``_create_connection``, is never stored in
``_connections``, and is returned as the third element so the caller
can hand it to
``_close_fresh_connection`` once the operation ends. No server lock
is held while the operation runs, same as the cached path.

A jump host, if any, is still reached through ``_get_connection``
(see ``_create_connection``), so its tunnel connection stays pooled
whatever its own ``reuse_connection`` says: tunnels use direct-tcpip
channels, not exec channels, so the forced-command problem does not
apply to them.

Why: Windows OpenSSH hands every exec channel after the first on one
connection the FIRST channel's ``SSH_ORIGINAL_COMMAND``, so a
forced-command wrapper there must see one connection per command.

Returns:
``(connection, connection_id, fresh_connection_or_None)``

Raises:
KeyError: If server not found in registry
Various SSH exceptions on connection failure
"""
server = self.registry.get_server(server_name)
if server.reuse_connection:
conn = await self._get_connection(server_name)
return conn, self._connection_ids.get(server_name, "unknown"), None

conn = await self._create_connection(server)
connection_id = _make_connection_id(server_name)
logger.info(
"Created one-shot connection to %s (id=%s)",
_safe_log_value(server_name),
connection_id,
)
return conn, connection_id, conn

async def _close_fresh_connection(
self, server_name: str, conn: asyncssh.SSHClientConnection
) -> None:
"""Close a one-shot connection and wait for the close to finish."""
try:
conn.close()
await conn.wait_closed()
except Exception as e: # noqa: BLE001 - cleanup of a one-shot connection must never mask the operation's own result or error
logger.warning(
"Error closing one-shot connection to %s: %s",
_safe_log_value(server_name),
_safe_exc(e),
)

async def _get_connection(
self, server_name: str, _depth: int = 0
) -> asyncssh.SSHClientConnection:
Expand Down
45 changes: 45 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,3 +434,48 @@ def test_non_list_groups_rejected_not_coerced(
def test_config_error_is_valueerror_subclass(self) -> None:
"""ConfigError must remain a ValueError subclass for backward compat."""
assert issubclass(ConfigError, ValueError)


class TestReuseConnectionKey:
"""TOML parsing of the per-server ``reuse_connection`` key."""

_TEMPLATE = """
[groups]
win = {{ description = "Windows" }}

[servers.win1]
description = "Windows host"
groups = ["win"]
{extra}

[servers.lin1]
description = "Linux host"
groups = ["win"]
"""

def _load(self, tmp_path: Path, extra: str) -> ServerRegistry:
f = tmp_path / "reuse.toml"
f.write_text(self._TEMPLATE.format(extra=extra))
return ServerRegistry(str(f))

def test_false_is_parsed_and_default_stays_true(self, tmp_path: Path) -> None:
registry = self._load(tmp_path, "reuse_connection = false")

assert registry.get_server("win1").reuse_connection is False
assert registry.get_server("lin1").reuse_connection is True

def test_omitted_defaults_to_true(self, tmp_path: Path) -> None:
registry = self._load(tmp_path, "")

assert registry.get_server("win1").reuse_connection is True

@pytest.mark.parametrize("raw", ['"false"', "0", "1", '"yes"'])
def test_non_bool_rejected_naming_key_and_server(
self, tmp_path: Path, raw: str
) -> None:
with pytest.raises(ConfigError) as exc_info:
self._load(tmp_path, f"reuse_connection = {raw}")

msg = str(exc_info.value)
assert "reuse_connection" in msg
assert "win1" in msg
25 changes: 25 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,3 +297,28 @@ def test_exec_result_with_stderr(self) -> None:

assert result.stderr == "cat: missing.txt: No such file or directory"
assert result.exit_code == 1


class TestServerConfigReuseConnection:
"""``reuse_connection`` toggles one-shot connections per operation."""

def test_defaults_to_true(self) -> None:
server = ServerConfig(name="web1", description="Web server 1")

assert server.reuse_connection is True

def test_accepts_false(self) -> None:
server = ServerConfig(
name="win1", description="Windows", reuse_connection=False
)

assert server.reuse_connection is False

@pytest.mark.parametrize("bad_value", ["false", "yes", 0, 1, None])
def test_rejects_non_bool(self, bad_value: object) -> None:
with pytest.raises(ValueError, match="reuse_connection"):
ServerConfig(
name="win1",
description="Windows",
reuse_connection=bad_value, # type: ignore[arg-type]
)
Loading