ls-ssh-mcp
An MCP server for SSH session management with browser-based terminal monitoring, supporting persistent connections, command execution, SFTP file operations, and multi-session management.
README
SSH MCP Server
A Model Context Protocol (MCP) server that provides SSH session management for Claude Code with browser-based terminal monitoring.
Features
Core Functionality
- Persistent SSH Sessions - Named SSH connections that maintain state across commands
- Interactive Terminal Interface - Full browser-based terminal with keyboard input and command execution
- Multi-Session Support - Manage multiple independent SSH sessions simultaneously
- Real-time Output Streaming - Live terminal output via WebSocket with single clean display
- Command History - Track executed commands with timestamps and exit codes
- Session Isolation - Each session maintains separate terminal history and state
Interactive Terminal Capabilities
- Direct Command Input - Type commands directly in the browser terminal interface
- Local Echo - Immediate character display with terminal cursor movement
- Command Line Editing - Full keyboard navigation (arrows, Home, End, backspace)
- Terminal State Management - Smart locking/unlocking based on command execution status
- Source Attribution - Commands from browser users vs Claude Code are properly tracked
- Concurrent Execution - User and Claude Code commands execute through shared SSH session with queuing
Advanced Features
- Multiple Authentication Methods - SSH keys (encrypted/unencrypted), username/password, direct key content
- Command Queuing - FIFO execution prevents output interleaving between user and Claude Code commands
- WebSocket Communication - Bidirectional messaging for command execution and output streaming
- Session State Synchronization - Multiple browser clients stay in sync with terminal state
- Clean Terminal Display - Single output with preserved ANSI colors and formatting
Installation & Setup
For complete platform-specific installation, upgrade, verification, and removal steps, see INSTALLATION.md.
Prerequisites
- Node.js 20+ and npm (Node.js 20 LTS recommended)
- Claude Code CLI installed and configured
- SSH server access (for remote connections)
- Bash,
netstatorss, andclaudeCLI forinstall-mcp.sh
1. Clone and Build
git clone <repository-url> ls-ssh-mcp
cd ls-ssh-mcp
npm install
npm run build
2. Register with Claude Code
# Use the installation script (recommended)
./install-mcp.sh
# Or manually register
claude mcp add ssh node /absolute/path/to/ls-ssh-mcp/dist/src/mcp-server.js
3. Verify Installation
# Check that the server was registered
claude mcp list
How it works:
- The
install-mcp.shscript registers the server with Claude Code with an auto-discovered port - Claude Code automatically starts the server when you use SSH tools
- No need to manually start/stop - the server runs on-demand
- Web monitoring interface is available at
http://localhost:{port}/session/{session-name}
The installation script handles port discovery, cleanup of existing configurations, and proper registration.
Usage
Basic Workflow
- Connect to SSH server: Use
ssh_connectwith your credentials - Execute commands: Use
ssh_execto run commands on the remote server - Monitor sessions: Use
ssh_get_monitoring_urlto get browser monitoring URL - Manage sessions: Use
ssh_list_sessionsandssh_disconnectas needed
Available MCP Tools
| Tool | Purpose | Required Parameters |
|---|---|---|
ssh_connect |
Establish SSH connection | name, host, username, auth method* |
ssh_exec |
Execute commands on remote server | sessionName, command |
ssh_list_sessions |
List all active SSH sessions | None |
ssh_get_monitoring_url |
Get browser monitoring URL | sessionName |
ssh_disconnect |
Disconnect an SSH session | sessionName |
ssh_cancel_command |
Cancel a running MCP command | sessionName, optional commandId |
ssh_poll_task |
Poll an async/background command | sessionName, taskId |
ssh_upload |
Upload one local file over SFTP | sessionName, localPath, remotePath |
ssh_download |
Download one remote file over SFTP | sessionName, remotePath, localPath |
ssh_fs |
Run remote SFTP filesystem operation | sessionName, op, path |
ssh_upload_dir |
Archive and recursively upload a directory | sessionName, localDir, remoteDir |
ssh_version |
Return version and build information | None |
* Authentication methods: Choose one:
password- SSH user account passwordprivateKey- Direct private key content (+ optionalpassphraseif key is encrypted)keyFilePath- Path to private key file (+ optionalpassphraseif key is encrypted)
Command cancellation and polling
Long-running commands can transition to background execution with asyncTimeout. Poll the returned task with ssh_poll_task, and cancel active work with ssh_cancel_command.
ssh_exec sessionName="myserver" command="long-running-command" asyncTimeout=5000
ssh_poll_task sessionName="myserver" taskId="<task-id>"
ssh_cancel_command sessionName="myserver" commandId="<command-id>"
SFTP file operations
Use ssh_upload and ssh_download for single files. Use ssh_fs with stat, ls, mkdir, or rm for remote filesystem operations. ssh_upload_dir recursively archives and transfers a local directory; it excludes node_modules, .git, .DS_Store, and __pycache__ by default, accepts additional exclude globs, and verifies the remote file count by default.
ssh_upload sessionName="myserver" localPath="./build/app.js" remotePath="/srv/app/app.js"
ssh_download sessionName="myserver" remotePath="/var/log/app.log" localPath="./tmp/app.log"
ssh_fs sessionName="myserver" op="ls" path="/srv/app"
ssh_upload_dir sessionName="myserver" localDir="./dist" remoteDir="/srv/app" exclude=["*.map"] verify=true
Example Usage
# 1. Connect to a server (multiple authentication methods)
# Option A: Username/password authentication
ssh_connect name="myserver" host="example.com" username="user" password="pass"
# Option B: SSH key file (recommended)
ssh_connect name="myserver" host="example.com" username="user" keyFilePath="~/.ssh/id_rsa"
# Option C: SSH key file with passphrase (encrypted key)
ssh_connect name="myserver" host="example.com" username="user" keyFilePath="~/.ssh/id_ed25519" passphrase="mypassphrase"
# Option D: Direct private key content (unencrypted)
ssh_connect name="myserver" host="example.com" username="user" privateKey="-----BEGIN OPENSSH PRIVATE KEY-----..."
# Option E: Direct private key content (encrypted with passphrase)
ssh_connect name="myserver" host="example.com" username="user" privateKey="-----BEGIN OPENSSH PRIVATE KEY-----..." passphrase="keypassword"
# 2. Execute commands
ssh_exec sessionName="myserver" command="ls -la"
ssh_exec sessionName="myserver" command="htop"
# 3. Get monitoring URL for real-time terminal
ssh_get_monitoring_url sessionName="myserver"
# Returns: http://localhost:8082/session/myserver
# 4. List all active sessions
ssh_list_sessions
# 5. Disconnect when done
ssh_disconnect sessionName="myserver"
Interactive Web Terminal
The browser interface provides a fully interactive terminal experience:
Terminal Input & Navigation
- Direct Command Input - Type commands directly in the terminal, just like a native SSH client
- Local Echo - Characters appear immediately as you type with cursor movement
- Command Line Editing - Use arrow keys, Home, End, and backspace for full editing
- Terminal Locking - Interface locks during command execution, unlocks when complete
Real-time Features
- Live Output Streaming - See command results in real-time via WebSocket
- Concurrent Commands - User-typed commands and Claude Code commands execute seamlessly
- Session Synchronization - Multiple browser windows stay synchronized
- Command History - Complete history with timestamps and exit codes
Advanced Capabilities
- Source Attribution - Terminal tracks whether commands came from user input or Claude Code
- Queue Management - Commands execute in order without output mixing
- State Persistence - Session state maintained across browser reconnects
- Clean Output Display - Single command output without duplication or formatting issues
Usage: Navigate to the monitoring URL and interact with the terminal exactly like a local SSH session. Type commands, press Enter, and see results instantly. Claude Code can also execute commands in the same session without interference.
SSH Authentication Methods
The server supports multiple SSH authentication methods with automatic fallback:
1. SSH Key Files (Recommended)
- Best for: Regular usage, automated deployments, security-conscious users
- Supports: RSA, ED25519, ECDSA key formats
- Encryption: Both encrypted (with passphrase) and unencrypted keys
- Path expansion: Supports tilde expansion (
~/.ssh/id_rsa)
# Unencrypted key
ssh_connect name="prod" host="server.com" username="deploy" keyFilePath="~/.ssh/id_ed25519"
# Encrypted key with passphrase
ssh_connect name="secure" host="server.com" username="admin" keyFilePath="~/.ssh/id_rsa" passphrase="mysecretpass"
2. Username/Password
- Best for: Quick testing, one-off connections, legacy systems
- Security note: Less secure than key-based authentication
ssh_connect name="test" host="server.com" username="user" password="password"
3. Direct Private Key Content (Legacy)
- Best for: Programmatic usage, CI/CD systems with key management
- Note: Requires pasting full private key content
ssh_connect name="ci" host="server.com" username="deploy" privateKey="-----BEGIN OPENSSH PRIVATE KEY-----..."
Authentication Priority
privateKey(if provided) - highest prioritykeyFilePath(if provided) - recommended methodpassword(if provided) - fallback method
Configuration
Environment Variables
SSH_TIMEOUT- SSH operation timeout in milliseconds (default: 30000)MAX_SESSIONS- Maximum concurrent SSH sessions (default: 10)LOG_LEVEL- Logging level: 'error', 'warn', 'info', 'debug' (default: 'info')
Web server port is automatically discovered and managed by the installation script.
Development
Setup Development Environment
# Install dependencies
npm install
# Run in development mode with auto-reload
npm run dev
# Run tests
npm test
# Run E2E tests (requires SSH server on localhost)
npm run test:e2e
# Build for production
npm run build
# Lint code
npm run lint
Testing Requirements
For running tests, you need:
- SSH server running on localhost
- Test user account:
test_userwith passwordpassword123 - Or configure your own test credentials in the test files
Project Structure
├── src/
│ ├── mcp-server.ts # Main server orchestrator
│ ├── mcp-ssh-server.ts # MCP protocol handler
│ ├── web-server-manager.ts # Web interface server + WebSocket handlers
│ ├── ssh-connection-manager.ts # SSH session management + command queuing
│ └── types.ts # TypeScript definitions + command source types
├── static/ # Interactive xterm.js terminal interface
│ ├── terminal-input-handler.js # Browser input handling and state management
│ └── [xterm.js assets] # Terminal rendering components
├── plans/
│ ├── interactive-terminal-epic.md # Complete implementation documentation
│ └── [other planning docs] # Additional project planning
├── tests/ # Comprehensive test suite
│ ├── story*.test.ts # User story validation tests
│ ├── e2e-*.test.ts # End-to-end functionality tests
│ └── manual-tests/ # Manual testing scripts and plans
├── install-mcp.sh # Installation script
└── dist/ # Compiled output
Security Considerations
- SSH sessions are kept in memory only
- Credentials are not persisted
- Web interface runs on localhost by default
- Use SSH key authentication when possible
Architecture
Overall Design
The SSH MCP Server implements a sophisticated architecture that seamlessly integrates Claude Code's MCP tools with interactive browser terminals:
┌─────────────────┐ stdio ┌─────────────────┐ WebSocket ┌─────────────────┐
│ Claude Code │◄──────────►│ MCP Server │◄──────────────►│ Browser Terminal│
└─────────────────┘ commands └─────────────────┘ bidirectional └─────────────────┘
│
▼
┌─────────────────┐
│ SSH Connection │
│ Manager │
│ (with Queue) │
└─────────────────┘
│
▼
┌─────────────────┐
│ Remote SSH │
│ Server │
└─────────────────┘
Core Components
- MCP Server: Handles Claude Code communication via stdio protocol (no network port)
- Web Server: Provides interactive terminal interface via HTTP and WebSocket
- SSH Connection Manager: Centralized session management with command queuing
- Interactive Terminal: Browser-based xterm.js interface with input handling
Key Architectural Features
1. Unified Command Execution
- Both Claude Code tools and browser user input execute through the same SSH sessions
- Commands are queued in FIFO order to prevent output interleaving
- Source attribution tracks whether commands came from "user" or "claude"
2. Real-time Communication
- MCP Protocol: stdio transport between Claude Code and server
- WebSocket: Bidirectional communication between browser and server
- SSH Connection: Persistent shell channels with streaming output
3. State Management
- Session Persistence: SSH sessions maintain state across all command sources
- Terminal Synchronization: Multiple browser clients stay synchronized
- Queue Management: Commands execute sequentially with proper cleanup
Port Management
- MCP Communication: Uses stdio transport only (stdin/stdout with Claude Code)
- Web Interface: Single auto-discovered port serves both HTTP routes and WebSocket connections
- Port Discovery: Installation script discovers available port and stores as
WEB_PORTenvironment variable - URL Generation: MCP tools return monitoring URLs pointing to the web interface
Interactive Terminal Architecture
Browser-Side Components
- xterm.js Terminal: Renders terminal interface with full VT100 compatibility
- Input Handler: Manages keyboard input, local echo, and command submission
- WebSocket Client: Handles bidirectional communication with server
- State Manager: Tracks terminal lock/unlock state and command execution
Server-Side Processing
- WebSocket Handler: Processes terminal input messages from browser
- Command Router: Routes commands to SSH connection manager with source attribution
- Output Broadcaster: Streams command results back to all connected clients
- Queue Coordinator: Ensures proper execution order for mixed command sources
Deployment Modes
- Production: Claude Code automatically starts server on-demand when SSH tools are used
- Development: Manual testing with independent port discovery
- Interactive Mode: Browser clients can connect and interact with existing SSH sessions
Data Flow
- Claude Code Command:
ssh_exec→ MCP Server → SSH Manager → Queue → SSH Session - Browser Command: Terminal Input → WebSocket → Web Server → SSH Manager → Queue → SSH Session
- Output Streaming: SSH Session → SSH Manager → WebSocket → Browser Terminal
- State Updates: Command completion → Terminal unlock (for user commands only)
Troubleshooting
Common Issues
Server not starting after registration:
# Check if Claude Code recognizes the server
claude mcp list
# Verify build exists
ls -la dist/src/mcp-server.js
# Test the server directly
node dist/src/mcp-server.js
Port conflicts:
# Re-run installation to discover new port
./install-mcp.sh
# Verify new configuration
claude mcp get ssh
SSH connection failures:
- Verify SSH server is running and accessible
- Check credentials (username/password or privateKey)
- Ensure SSH server allows password authentication if using passwords
Web interface not accessible:
- Use
ssh_get_monitoring_urlto get the correct URL with current port - Check that the server is running:
ps aux | grep mcp-server
Logs and Debugging
# Enable debug logging when using Claude Code
export LOG_LEVEL=debug
# Check MCP server configuration
claude mcp get ssh
# Test server manually with debug output
LOG_LEVEL=debug node dist/src/mcp-server.js
License
MIT License - see LICENSE file for details.
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。