SSH MCP Server

SSH MCP Server

Enables remote server administration via SSH, supporting command execution, SFTP file transfers, and multi-profile management. It features security safeguards like destructive command detection and audit logging to ensure safe interaction with remote Linux/Unix environments.

Category
访问服务器

README

SSH MCP Server

Node.js TypeScript MCP SDK SSH2 License npm Version

Leer en Espa\u00f1ol

MCP (Model Context Protocol) server for remote server administration via SSH. Supports multiple profiles, remote command execution, interactive commands (PTY), persistent shell sessions, file transfer (SFTP), destructive command detection with audit logging, and operation history with undo capabilities.


Architecture

General Overview

graph TB
    Client["Claude Desktop<br/>(or any MCP client)"]
    Server["SSH MCP Server"]
    MCP["MCP SDK<br/>(stdio)"]
    Router["Tool Router<br/>(index.ts)"]
    Security["Security Module<br/>- Dangerous cmd detection<br/>- Audit logging"]
    SSH["SSH Client (ssh2)"]
    Exec["exec()<br/>- Commands<br/>- cat (read)"]
    Interactive["exec() + PTY<br/>- Interactive commands<br/>- Auto prompt response"]
    Shell["shell() + PTY<br/>- Persistent sessions<br/>- REPLs / multi-step"]
    SFTP["SFTP (lazy init)<br/>- upload / download<br/>- ls / write / readdir"]
    Remote["Remote Server<br/>(Linux/Unix)"]

    Client -->|"stdio (JSON-RPC)"| Server
    Server --- MCP
    MCP --> Router
    Router --> Security
    Router --> SSH
    SSH --- Exec
    SSH --- Interactive
    SSH --- Shell
    SSH --- SFTP
    SSH -->|"SSH (TCP :22)"| Remote

Connection and Execution Flow

flowchart TD
    Start([Start]) --> ListProfiles["ssh_list_profiles<br/>View available profiles"]
    ListProfiles --> Connect["ssh_connect<br/>(profile name)"]
    Connect -->|Password not found| Error["Error: env var<br/>SSH_PASSWORD_NAME missing"]
    Connect -->|OK| Active["Active Connection<br/>(1 profile at a time)"]

    Active --> ExecBranch["ssh_exec<br/>(command)"]
    Active --> InteractiveBranch["ssh_exec_interactive<br/>(command + auto-responses)"]
    Active --> ShellBranch["Shell Sessions<br/>start / send / read / close"]
    Active --> SFTPBranch["SFTP operations<br/>upload / download<br/>ls / read / write"]
    Active --> StatusBranch["ssh_status<br/>ssh_disconnect"]

    ExecBranch --> DangerCheck{"Dangerous<br/>command?<br/>(regex)"}
    InteractiveBranch --> DangerCheck
    DangerCheck -->|No| Execute["Execute command"]
    DangerCheck -->|Yes| ConfirmCheck{"confirm:<br/>true?"}
    ConfirmCheck -->|Yes| Execute
    ConfirmCheck -->|No| Warning["WARNING<br/>(not executed)"]

    ShellBranch -->|"send (raw:false)"| DangerCheck
    ShellBranch -->|"send (raw:true)"| Execute

    Execute --> Audit["audit.log"]
    SFTPBranch --> Audit
    Warning --> Audit

Security Flow (Dangerous Commands)

flowchart LR
    Input["Command received"] --> Check["isDangerousCommand()<br/>(16 regex patterns)"]
    Check -->|Safe| Exec["Execute command"]
    Check -->|Dangerous| Confirm{"confirm: true?"}
    Confirm -->|Yes| Exec
    Confirm -->|No| Warn["WARNING returned<br/>(command NOT executed)"]
    Exec --> Log["audit.log"]
    Warn --> Log

    subgraph Detected Patterns
        P1["rm -rf /"]
        P2["mkfs.*"]
        P3["dd if="]
        P4["reboot / shutdown / halt"]
        P5["chmod 777 / chown -R"]
        P6["fork bomb"]
        P7["systemctl stop/disable"]
        P8["killall / iptables -F"]
    end

Project Structure

s01_ssh_mcp/
├── src/
│   ├── index.ts       # SSHMCPServer class — tool router, SSH logic, interactive/shell handlers
│   ├── tools.ts       # MCP tool definitions (17 tools, JSON schemas)
│   ├── profiles.ts    # Profile loading + password injection from env
│   ├── security.ts    # Dangerous command detection + AuditLogger
│   └── types.ts       # Interfaces: SSHProfile, AuditEntry, PromptResponse, ShellSession, CommandRecord, ReverseInfo
├── dist/              # Compiled output (generated by tsc)
├── profiles.json      # SSH server configuration
├── .env               # Passwords (not versioned)
├── audit.log          # Audit log (generated at runtime)
├── package.json
└── tsconfig.json

Setup

1. Server Profiles

Edit profiles.json:

{
  "production": {
    "host": "192.168.1.100",
    "port": 22,
    "username": "deploy"
  },
  "staging": {
    "host": "192.168.1.101",
    "port": 22,
    "username": "deploy"
  }
}

2. Passwords

Create .env (copy from .env.example):

SSH_PASSWORD_PRODUCTION=your_password
SSH_PASSWORD_STAGING=your_password

Format: SSH_PASSWORD_<PROFILE_NAME_UPPERCASE>.

3. Build and Run

npm install
npm run build
npm start

4. MCP Configuration (Claude Desktop)

Option A: Using npx (recommended)

No local installation required — just add to your Claude Desktop config (claude_desktop_config.json):

{
  "mcpServers": {
    "ssh": {
      "command": "npx",
      "args": ["-y", "s01-ssh-mcp"],
      "env": {
        "SSH_PASSWORD_PRODUCTION": "your_password",
        "SSH_PASSWORD_STAGING": "your_password"
      }
    }
  }
}

Option B: Local installation

{
  "mcpServers": {
    "ssh": {
      "command": "node",
      "args": ["/path/to/s01_ssh_mcp/dist/index.js"],
      "env": {
        "SSH_PASSWORD_PRODUCTION": "your_password",
        "SSH_PASSWORD_STAGING": "your_password"
      }
    }
  }
}

Note: You can optionally set SSH_PROFILES_PATH in env to point to a profiles.json in a different location.


Available Tools

Tool Description Requires Connection
ssh_list_profiles List configured profiles (without passwords) No
ssh_connect Connect to an SSH profile No
ssh_disconnect Close the active SSH connection (closes all shell sessions) Yes
ssh_status Connection status (profile, host, uptime) Yes
ssh_exec Execute a remote command Yes
ssh_exec_interactive Execute interactive command with PTY and auto-response to prompts Yes
ssh_shell_start Start a persistent interactive shell session with PTY Yes
ssh_shell_send Send input to an active shell session Yes
ssh_shell_read Read accumulated output from a shell session buffer Yes
ssh_shell_close Close a shell session and release resources Yes
ssh_upload Upload a local file to the server (SFTP) Yes
ssh_download Download a file from the server (SFTP) Yes
ssh_ls List a remote directory (SFTP) Yes
ssh_read_file Read remote file contents Yes
ssh_write_file Write content to a remote file (SFTP) Yes
ssh_history View operation history for the active connection Yes
ssh_undo Revert a specific operation by record ID Yes

Tool Parameters

Tool Parameters Required
ssh_connect profile (string) Yes
ssh_exec command (string), confirm (boolean) command
ssh_exec_interactive command (string), responses[] ({prompt, answer, sensitive}), timeout (number), confirm (boolean) command
ssh_shell_start cols (number, default: 80), rows (number, default: 24) No
ssh_shell_send sessionId (string), input (string), raw (boolean), timeout (number), confirm (boolean) sessionId, input
ssh_shell_read sessionId (string), timeout (number) sessionId
ssh_shell_close sessionId (string) sessionId
ssh_upload localPath (string), remotePath (string) Both
ssh_download remotePath (string), localPath (string) Both
ssh_ls path (string, default: home) No
ssh_read_file path (string) Yes
ssh_write_file path (string), content (string) Both
ssh_history filter ("all" | "reversible" | "reversed"), limit (number) No
ssh_undo recordId (number), confirm (boolean) recordId

Operation History & Undo

Every operation executed during an active connection is recorded in memory. This allows reviewing what was done and reverting specific operations.

Reversibility by Operation

Operation Reversible Undo Strategy
ssh_write_file Yes Restores previous content. If file didn't exist, deletes it
ssh_upload Yes Restores previous remote content. If file didn't exist, deletes it
ssh_download Yes Deletes the downloaded local file
ssh_exec No Recorded but not auto-reversible
ssh_exec_interactive No Recorded but not auto-reversible
ssh_read_file N/A Read-only, nothing to revert
ssh_ls N/A Read-only, nothing to revert
ssh_shell_send N/A Cannot revert input sent to an interactive shell

The history is cleared on ssh_connect and ssh_disconnect.


Security

Destructive Command Detection

The following patterns are intercepted and require confirm: true to execute. This applies to ssh_exec, ssh_exec_interactive, and ssh_shell_send (when raw: false):

Pattern Reason
rm -rf / Recursive rm on system root
rm -r, rm -rf Mass file deletion
mkfs.* Filesystem formatting
dd if= Direct disk write
reboot, shutdown, halt, poweroff Server state control
init 0, init 6 Runlevel change
chmod 777 / Insecure permissions on root
chown -R Mass ownership change
> /dev/* Direct device write
:(){ :|:& };: Fork bomb
systemctl stop|disable|mask System service shutdown
killall Mass process termination
iptables -F Firewall rules flush

Audit Log

All operations are logged to audit.log with the format:

[timestamp] [profile] [tool] [parameters] [RESULT: ok|error]

Example:

[2026-03-04T10:30:00.000Z] [production] [ssh_exec] [ls -la /var/log] [RESULT: ok]
[2026-03-04T10:31:00.000Z] [production] [ssh_upload] [./app.tar.gz -> /tmp/app.tar.gz] [RESULT: ok]

Technical Details

  • MCP Transport: stdio (JSON-RPC over stdin/stdout)
  • SSH Connection: One active connection at a time. Attempting to connect to another profile without disconnecting raises an error.
  • SFTP: Lazy initialization — created on first file operation use and reused thereafter.
  • Interactive Exec: Uses exec() with pty: true for commands requiring interactive input. Supports auto-response to prompts via regex matching. Settle timeout (2s) detects command completion; global timeout (default 30s) prevents hangs.
  • Shell Sessions: Uses shell() with PTY for persistent interactive terminals. Up to 5 concurrent sessions stored in a Map<string, ShellSession>. Auto-close after 5 minutes of inactivity. Buffer capped at 1MB. All sessions are closed on ssh_disconnect. ANSI escape codes are stripped from output.
  • File Reading: Uses ssh exec cat (not SFTP) for text files.
  • File Writing: Uses SFTP createWriteStream for large file support.
  • Argument Escaping: Shell escaping with single quotes to prevent command injection.
  • Audit Logging: Non-blocking — log write failures are silently ignored to avoid disrupting operations. Responses marked sensitive: true are logged as [REDACTED].
  • Profile Cache: profiles.json is read once and cached in memory.
  • Operation History: All operations are recorded in memory during the active connection. File operations (ssh_write_file, ssh_upload) capture previous content before modifying, enabling undo. History is cleared on connect/disconnect.

License

This project is licensed under the MIT License.

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选