mcp-ssh

mcp-ssh

Enables AI agents to establish and manage persistent SSH sessions, supporting smart command execution, async tasks, multi-host, sudo, and file operations through SFTP.

Category
Visit Server

README

MCP SSH Session

[!IMPORTANT] Alternative version: mcp-ssh-tmux. Uses tmux for improved persistence, observability, and a superior "LLM-as-Observer" approach.

An MCP (Model Context Protocol) server that enables AI agents to establish and manage persistent SSH sessions.

<a href="https://glama.ai/mcp/servers/@devnullvoid/mcp-ssh-session"> <img width="380" height="200" src="https://glama.ai/mcp/servers/@devnullvoid/mcp-ssh-session/badge" alt="SSH Session MCP server" /> </a>

Features

  • Smart Command Execution: Never hangs the server - automatically transitions to async mode if timeout is reached
  • Persistent Sessions: SSH connections are reused across multiple command executions
  • Async Command Execution: Non-blocking execution for long-running commands
  • SSH Config Support: Automatically reads and uses settings from ~/.ssh/config
  • Multi-host Support: Manage connections to multiple hosts simultaneously
  • Automatic Reconnection: Dead connections are detected and automatically re-established
  • Thread-safe: Safe for concurrent operations
  • Network Device Support: Automatic enable mode handling for routers and switches
  • Sudo Support: Automatic password handling for sudo commands on Unix/Linux hosts
  • File Operations: Safe helpers to read and write remote files over SFTP
  • Command Interruption: Send Ctrl+C to interrupt running commands

Installation

The package is published on PyPI as mcp-ssh.

Using uvx

uvx mcp-ssh

For a persistent local installation:

uv tool install mcp-ssh

This installs both mcp-ssh and the backward-compatible mcp-ssh-session command.

Using Claude Code

Add to your ~/.claude.json:

{
  "mcpServers": {
    "ssh-session": {
      "type": "stdio",
      "command": "uvx",
      "args": ["mcp-ssh"],
      "env": {}
    }
  }
}

Using MCP Inspector

npx @modelcontextprotocol/inspector uvx mcp-ssh

Development Installation

uv venv
source .venv/bin/activate
uv pip install -e .

Usage

Available Tools

execute_command

Execute a command on an SSH host using a persistent session.

Smart Execution: Starts synchronously and waits for completion. If timeout is reached, automatically transitions to async mode and returns a command ID. Server never hangs!

Advanced Features:

  • Automatic timeout handling with async transition
  • Interactive command support (use send_input for prompts)
  • Command interruption capability (interrupt_command_by_id)
  • Session persistence across multiple commands

Using SSH config alias:

{
  "host": "myserver",
  "command": "uptime"
}

Using explicit parameters:

{
  "host": "example.com",
  "username": "user",
  "command": "ls -la",
  "key_filename": "~/.ssh/id_rsa",
  "port": 22
}

Network device with enable mode:

{
  "host": "router.example.com",
  "username": "admin",
  "password": "ssh_password",
  "enable_password": "enable_password",
  "command": "show running-config"
}

Unix/Linux with sudo:

{
  "host": "server.example.com",
  "username": "user",
  "sudo_password": "user_password",
  "command": "systemctl restart nginx"
}

list_sessions

List all active SSH sessions.

close_session

Close a specific SSH session.

{
  "host": "myserver"
}

close_all_sessions

Close all active SSH sessions.

execute_command_async

Execute a command asynchronously without blocking the server. Returns a command ID for tracking.

Use with companion tools:

  • get_command_status(command_id) - Check progress and retrieve output
  • interrupt_command_by_id(command_id) - Send Ctrl+C to stop execution
  • send_input(command_id, text) - Provide input to interactive commands
{
  "host": "myserver",
  "command": "sleep 60 && echo 'Done'",
  "timeout": 300
}

get_command_status

Get the status and output of an async command.

{
  "command_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}

interrupt_command_by_id

Interrupt a running async command by sending Ctrl+C.

{
  "command_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}

list_running_commands

List all currently running async commands.

list_command_history

List recent command history (completed, failed, interrupted commands).

{
  "limit": 50
}

read_file

Read the contents of a remote file via SFTP, with optional sudo support.

Basic usage:

{
  "host": "myserver",
  "remote_path": "/etc/nginx/nginx.conf",
  "max_bytes": 131072
}

With passwordless sudo (NOPASSWD in sudoers):

{
  "host": "myserver",
  "remote_path": "/etc/shadow",
  "use_sudo": true
}

With sudo password:

{
  "host": "myserver",
  "remote_path": "/etc/shadow",
  "sudo_password": "user_password"
}
  • Attempts SFTP first for best performance
  • Falls back to sudo cat via shell if permission denied and use_sudo=true or sudo_password provided
  • Supports both passwordless sudo (NOPASSWD) and password-based sudo
  • Enforces a 2 MB maximum per request (configurable per call up to that limit)
  • Returns truncated notice when the content size exceeds the requested limit

write_file

Write text content to a remote file via SFTP, with optional sudo support.

Basic usage:

{
  "host": "myserver",
  "remote_path": "/tmp/app.env",
  "content": "DEBUG=true\n",
  "append": true,
  "make_dirs": true
}

With passwordless sudo (NOPASSWD in sudoers):

{
  "host": "myserver",
  "remote_path": "/etc/nginx/nginx.conf",
  "content": "server { ... }",
  "use_sudo": true,
  "permissions": 420
}

With sudo password:

{
  "host": "myserver",
  "remote_path": "/etc/nginx/nginx.conf",
  "content": "server { ... }",
  "sudo_password": "user_password",
  "permissions": 420
}
  • Uses SFTP when use_sudo=false and no sudo_password provided
  • Uses sudo tee via shell when use_sudo=true or sudo_password is provided
  • Supports both passwordless sudo (NOPASSWD) and password-based sudo
  • Content larger than 2 MB is rejected for safety
  • Optional append mode to add to existing files
  • Optional make_dirs flag will create missing parent directories
  • Supports permissions to set octal file modes after write (e.g., 420 for 0644)
  • Note: Shell fallback is slower than SFTP but enables writing to protected files

SSH Config Support

The server automatically reads ~/.ssh/config and supports:

  • Host aliases
  • Hostname mappings
  • Port configurations
  • User specifications
  • IdentityFile settings

Example ~/.ssh/config:

Host myserver
    HostName example.com
    User myuser
    Port 2222
    IdentityFile ~/.ssh/id_rsa

Then simply use:

{
  "host": "myserver",
  "command": "uptime"
}

Environment Variable Override System (Credential Hiding)

For production environments where AI agents should not have access to real credentials, you can use environment variables to override connection parameters. This allows agents to use simple aliases while real credentials are stored securely in the MCP server configuration.

Use case: Hide real hostnames, IPs, usernames, and passwords from AI agents while still allowing them to manage production servers.

Supported Environment Variables

Variable Description
OVRD_{alias}_HOST Real hostname or IP address
OVRD_{alias}_PORT SSH port (default: 22)
OVRD_{alias}_USER SSH username
OVRD_{alias}_PASS SSH password
OVRD_{alias}_KEY Path to SSH private key file
OVRD_{alias}_SUDO_PASS Sudo password
OVRD_{alias}_ENABLE_PASS Enable password for network devices (routers/switches)

Example Configuration

Claude Desktop config (~/.claude.json):

{
  "mcpServers": {
    "ssh-session": {
      "type": "stdio",
      "command": "uvx",
      "args": ["mcp-ssh"],
      "env": {
        "OVRD_prod_db_HOST": "192.168.1.100",
        "OVRD_prod_db_USER": "admin",
        "OVRD_prod_db_PASS": "secret_password",
        "OVRD_prod_db_SUDO_PASS": "sudo_password"
      }
    }
  }
}

Agent uses the alias (knows nothing about real credentials):

{
  "host": "prod_db",
  "command": "systemctl status postgresql"
}

System resolves to real credentials:

  • Host: prod_db192.168.1.100
  • User: (from env) → admin
  • Password: (from env) → secret_password

Notes

  • Fully backward compatible - works without environment variables
  • The agent sees only the alias (prod_db), not the real IP
  • Credentials never appear in the AI context
  • Works with all tools: execute_command, read_file, write_file, etc.

How It Works

Persistent Shell Sessions

Commands execute in persistent interactive shells that maintain state:

  • Current directory persists across commands (cd /tmp stays in /tmp)
  • Environment variables remain set
  • Shell history is maintained

Smart Command Completion Detection

On Unix-like shells, including BusyBox ash and OpenWrt, each command is followed by a unique sentinel that includes its exit status. This avoids guessing completion from prompts such as root@OpenWrt:/#.

Prompt detection remains available for network devices and interactive states that cannot use a POSIX shell sentinel. Idle detection is used only as a fallback while waiting for prompt or interactive-state changes.

Completion signals include:

  1. Sentinel detected: Reliable completion and exit status for Unix, BusyBox, and OpenWrt shells
  2. Prompt detected: Completion for routers, switches, and other non-POSIX targets
  3. Interactive state detected: Password, confirmation, editor, or pager handling

Idle handling: After two seconds without output, the server checks the sentinel, prompt, and interactive state again. Silence alone does not complete a sentinel-enabled command.

Long-running commands: The idle timer resets every time new output arrives, so builds or scripts that output sporadically continue running until naturally complete or the overall timeout is reached.

Documentation

License

Distributed under the MIT License. See LICENSE for details.

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured
E2B

E2B

Using MCP to run code via e2b.

Official
Featured