npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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

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 handling
  • MCPBatchClient: Batch operations với rate limiting
  • MCPConfig: Configuration helpers
  • Streaming support và ClaudeDesktop integration

Lưu ý quyền Docker: User chạy server cần thuộc group docker để gọi docker CLI 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 install

Chạ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 dev

Test 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.json

Config 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:stream

Bướ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àn
  • cleanup_logs: Dọn dẹp log files
  • docker_cleanup: Dọn dẹp Docker resources
  • remove_log_files: Xóa file log cụ thể
  • journal_vacuum: Thu gọn systemd journal
  • docker_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 mcpuser

File 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.target

Triể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/sdk chí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/sdk vớ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": [] }
  • cmd phả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 trong ps.

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.log và 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 tools
  • POST /mcp/tools/call: Execute tool
  • GET /health: Health check

Available MCP Tools

  1. remote_shell: Execute safe shell commands
  2. cleanup_logs: Clean up old log files
  3. docker_cleanup: Clean Docker resources
  4. remove_log_files: Remove specific log files
  5. journal_vacuum: Vacuum systemd journal
  6. 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_ROOTS trong 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 execFile và 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