mcp-remote-shell
v1.0.1
Published
MCP server: safe remote shell + log cleanup + docker prune/logs cleanup with HTTP streaming and SDK
Downloads
12
Maintainers
Readme
MCP Safe Remote Shell với Official SDK
MCP server hoàn chỉnh sử dụng @modelcontextprotocol/sdk chính thức với nhiều transport options.
🚀 Tính năng chính
MCP Server với Official SDK (mcp-server.js)
- Stdio Transport: Dành cho Claude Desktop integration
- MCP Protocol 2024-11-05 compliant
- Tools: remote_shell, cleanup_logs, docker_cleanup, remove_log_files, journal_vacuum, docker_logs_cleanup
MCP Stream Server với SSE (mcp-stream-server.js)
- SSE Transport: Server-Sent Events cho web clients
- HTTP endpoints cho backward compatibility
- Real-time streaming support
- CORS enabled cho web applications
Legacy HTTP Server (server.js)
- REST API endpoints cho backward compatibility
- Direct HTTP access không qua MCP protocol
- Suitable cho simple HTTP clients
Custom SDK (mcp-sdk.js)
MCPClient: Client với retry logic và event handlingMCPBatchClient: Batch operations với rate limitingMCPConfig: Configuration helpers- Streaming support và ClaudeDesktop integration
Lưu ý quyền Docker: User chạy server cần thuộc group
dockerđể gọidockerCLI mà không cần root.
🛠️ Cài đặt
sudo apt update && sudo apt install -y nodejs npm
git clone <repo-or-copy> mcp-safe-remote-shell-docker
cd mcp-safe-remote-shell-docker
npm installChạy các services
# Legacy HTTP server (port 3000)
npm start
# MCP Server với stdio transport (cho Claude Desktop)
npm run start:mcp
# MCP Stream Server với SSE transport (port 3001)
npm run start:stream
# Chạy tất cả services
npm run start:all
# Development mode với auto-reload
npm run devTest nhanh
# Test legacy HTTP server
curl -s http://localhost:3000/mcp/limits | jq
# Test MCP capabilities
curl -s http://localhost:3000/mcp/capabilities | jq
# Test MCP stream server
curl -s http://localhost:3001/health | jq
# Test MCP protocol via SSE (JSON-RPC)
curl -s -X POST http://localhost:3001/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | jq
# Test legacy HTTP API (backward compatibility)
curl -s -X POST http://localhost:3001/mcp/tools/list \
-H "Content-Type: application/json" \
-d '{}' | jq
# Run integration tests
npm run test:integration
# Test với custom SDK
npm test🤖 Tích hợp với ClaudeDesktop
Bước 1: Copy config
cp src/examples/claude-desktop-config.json ~/.config/claude-desktop/claude_desktop_config.jsonConfig file bao gồm 2 server options:
remote-shell-stdio: MCP server với stdio transport (khuyến nghị)remote-shell-stream: MCP server với SSE transport
Bước 2: Khởi động MCP server
# Cho stdio transport (khuyến nghị)
npm run start:mcp
# Hoặc cho SSE transport
npm run start:streamBước 3: Restart ClaudeDesktop
ClaudeDesktop sẽ tự động kết nối với MCP server qua stdio transport và bạn có thể sử dụng các tools:
remote_shell: Thực thi lệnh shell an toàncleanup_logs: Dọn dẹp log filesdocker_cleanup: Dọn dẹp Docker resourcesremove_log_files: Xóa file log cụ thểjournal_vacuum: Thu gọn systemd journaldocker_logs_cleanup: Dọn dẹp Docker container logs
📚 Sử dụng Official MCP SDK
Tạo MCP Client (Node.js)
const { Client } = require('@modelcontextprotocol/sdk/client/index.js');
const { StdioClientTransport } = require('@modelcontextprotocol/sdk/client/stdio.js');
// Kết nối với MCP server qua stdio
const transport = new StdioClientTransport({
command: 'node',
args: ['mcp-server.js']
});
const client = new Client({
name: "my-client",
version: "1.0.0"
}, {
capabilities: {}
});
await client.connect(transport);
// List tools
const tools = await client.request({
method: "tools/list"
});
// Call tool
const result = await client.request({
method: "tools/call",
params: {
name: "remote_shell",
arguments: { cmd: "df" }
}
});Sử dụng http stream (HTTP/SSE)
import { MCPClient } from './src/mcp-sdk.js';
const client = new MCPClient({
serverUrl: 'http://localhost:3001'
});
await client.initialize();
const result = await client.executeShellCommand('df', ['-h']);
console.log(result.content[0].text);Batch Operations với Custom SDK
import { MCPBatchClient } from './src/mcp-sdk.js';
const batchClient = new MCPBatchClient({
serverUrl: 'http://localhost:3001',
batchSize: 3
});
const operations = [
{ tool: 'remote_shell', args: { cmd: 'whoami' } },
{ tool: 'cleanup_logs', args: { dryRun: true } }
];
const results = await batchClient.executeBatch(operations);Xem thêm examples trong thư mục src/examples/.
Chạy bằng systemd (khuyến nghị)
Tạo user không phải root (ví dụ mcpuser) và thêm vào group docker nếu cần dọn Docker:
sudo useradd -r -s /usr/sbin/nologin mcpuser || true
sudo usermod -aG docker mcpuserFile service /etc/systemd/system/mcp-remote-shell.service:
[Unit]
Description=MCP Remote Shell (safe)
After=network.target
[Service]
User=mcpuser
Group=mcpuser
WorkingDirectory=/opt/mcp
ExecStart=/usr/bin/node /opt/mcp/server.js
Environment=PORT=3000
Restart=always
RestartSec=2
# Hardening
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
ProtectHome=true
ReadWritePaths=/var/log /tmp /opt/app/logs /var/lib/docker/containers
CapabilityBoundingSet=
AmbientCapabilities=
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
LockPersonality=true
MemoryDenyWriteExecute=true
[Install]
WantedBy=multi-user.targetTriển khai:
sudo mkdir -p /opt/mcp
sudo cp -r ./* /opt/mcp/
sudo chown -R mcpuser:mcpuser /opt/mcp
# Copy systemd service file
sudo cp src/mcp-remote-shell.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable mcp-remote-shell
sudo systemctl start mcp-remote-shell
sudo systemctl status mcp-remote-shell📖 API Documentation
Official MCP Protocol
MCP Server (stdio transport)
- Sử dụng
@modelcontextprotocol/sdkchính thức - JSON-RPC 2.0 over stdio
- Dành cho Claude Desktop và MCP clients
MCP Stream Server (SSE transport)
- Sử dụng
@modelcontextprotocol/sdkvới SSE - HTTP endpoint:
POST /mcp(JSON-RPC) - Server-Sent Events cho streaming
- Port 3001
Legacy HTTP APIs (Port 3000)
1) /mcp/shell (POST)
{ "cmd": "df", "args": [] }cmdphải thuộc whitelist:ls, cat, tail, head, du, df, uptime, whoami, hostname, ps, journalctl.- Giới hạn dòng (
tail/head -n 200), giới hạn column trongps.
2) /mcp/rm-logs (POST)
{ "files": ["/var/log/nginx/access.log.1", "/opt/app/logs/app.log.2023-12-01.gz"] }- Chỉ xóa file trong
ALLOWED_LOG_ROOTS:/var/log,/tmp,/opt/app/logs. - Chỉ file với đuôi:
.log,.log.N,.log.*,.gz,.old. - Từ chối symlink và thư mục.
3) /mcp/cleanup-logs (POST)
{ "roots": ["/var/log", "/opt/app/logs"], "olderThanDays": 14, "dryRun": true }dryRun=trueđể xem trước danh sách.- Set
dryRun=falseđể thực thi xóa.
4) /mcp/journal-vacuum (POST)
{ "vacuum": "time", "value": "7d" } // hoặc { "vacuum": "size", "value": "500M" }5) /mcp/docker-cleanup (POST)
{ "target": "all", "force": true } // "containers" | "images" | "volumes" | "networks"6) /mcp/docker-logs-cleanup (POST)
{ "mode": "truncate", "maxSizeMB": 100 } // hoặc mode "delete"- Quét
/var/lib/docker/containers/<id>/<id>-json.logvà truncate/delete nếu vượt ngưỡng.
MCP Stream Server APIs (Port 3001)
Official MCP Protocol (JSON-RPC)
POST /mcp: Main MCP endpoint{ "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {} }
Legacy HTTP Endpoints (Backward Compatibility)
POST /mcp/tools/list: List available toolsPOST /mcp/tools/call: Execute toolGET /health: Health check
Available MCP Tools
- remote_shell: Execute safe shell commands
- cleanup_logs: Clean up old log files
- docker_cleanup: Clean Docker resources
- remove_log_files: Remove specific log files
- journal_vacuum: Vacuum systemd journal
- docker_logs_cleanup: Clean Docker container logs
SDK Methods
MCPClient
// Connection
await client.initialize()
await client.listTools()
await client.callTool(name, args)
await client.callToolWithStream(name, args)
// Convenience methods
await client.executeShellCommand(cmd, args)
await client.cleanupLogs(options)
await client.dockerCleanup(target, force)
await client.removeLogFiles(files)
await client.vacuumJournal(vacuum, value)
await client.cleanupDockerLogs(mode, maxSizeMB)
// Utility
await client.checkHealth()
await client.proxyCall(endpoint, method, body)
client.disconnect()MCPBatchClient
const operations = [
{ tool: 'remote_shell', args: { cmd: 'df' } },
{ tool: 'cleanup_logs', args: { dryRun: true } }
];
const results = await batchClient.executeBatch(operations);🏗️ Architecture
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Claude │ │ MCP Client │ │ Web Client │
│ Desktop │ │ (Node.js) │ │ (Browser) │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
│ stdio │ HTTP │ HTTP/SSE
▼ ▼ ▼
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ mcp-sdk.js │ │ server.js │ │ mcp-http- │
│ (stdio) │ │ (Rest API) │ | stream.js (SSE) │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
└───────────────────────┼───────────────────────┘
│
▼
┌──────────────────┐
│ System Tools │
│ (shell, docker, │
│ logs, etc.) │
└──────────────────┘Cấu hình tuỳ biến
- Sửa
ALLOWED_LOG_ROOTStrong các server files để khớp cây thư mục thực tế - Có thể thêm auth (API key) và audit log trước khi vào production
- Có thể thêm rate limit cho HTTP endpoints
- Cấu hình environment variables cho ports và paths
Bảo mật
- Chỉ whitelist lệnh quan sát; không có shell (không
sh -c) - Dùng
execFilevà validate args - Không xóa thư mục, không theo symlink
- Hardening bằng systemd và user không phải root
- MCP protocol với proper error handling
