Linux系统监控服务器

一个用于AI代理远程监控和管理Linux服务器(Ubuntu、CentOS、RedHat等)的系统监控服务器,提供CPU、内存、磁盘、网络和进程等全面的系统信息,并通过MCP协议和HTTP REST API进行交互。

  • by DarkPhilosophy
  • Rust
  • 本地部署
  • 4 星标
  • 更新于
在 GitHub 查看 DarkPhilosophy/mcp-system-monitor

使用说明

Linux版MCP系统监控服务器

一种模型上下文协议(MCP)服务器实现,专为AI代理监控Linux服务器(Ubuntu、CentOS、RedHat等)并与之交互而设计。该服务器通过MCP协议和HTTP REST API提供全面的系统信息,包括CPU、内存、磁盘、网络和过程数据,使AI代理能够执行远程系统监控和管理任务。

开发平台

该项目是使用 克劳德代码Max,一个先进的人工智能驱动的开发平台。整个代码库、架构设计、测试和文档都是在Claude Code Max的协助下创建的,使其成为一个全面的人工智能辅助开发项目。

作者和存储库

维护人员: 黑暗哲学 @黑暗哲学
存储库: https://github.com/DarkPhilosophy/mcp-system-monitor

原始项目由: Thinh Nguyen
原始存储库: https://github.com/hungtrungthinh/mcp-system-monitor

目录

特性

  • 人工智能辅助开发:完全采用Claude Code Max构建,展示了先进的人工智能软件开发能力
  • Linux服务器支持:针对Ubuntu、CentOS、RedHat和其他Linux发行版进行了优化
  • AI代理集成:专为AI代理执行远程系统监控和管理而设计
  • 真实系统数据:从Linux procfs和系统命令中收集实际系统信息
  • 系统信息:主机名、操作系统详细信息、内核版本、正常运行时间
  • CPU监控:使用百分比、频率、核心数量、品牌信息、温度
  • 内存监控:RAM和交换使用情况,来自/proc/menifo的可用内存
  • 磁盘监控:存储使用情况、文件系统信息、df命令的装载点
  • 网络监控:来自/proc/net/dev的接口统计信息、流量数据、错误计数
  • 进程管理:ps命令中的进程列表、单个进程详细信息、资源使用情况
  • 实时度量:全面的系统指标收集
  • HTTP REST API:易于集成AI代理和web应用程序
  • MCP协议:支持AI代理通信的标准模型上下文协议

最近更新(2025)

MCP协议修复

  • 流式HTTP传输合规性:修复了POST请求返回JSON响应而不是SSE的问题
  • 通知支持:实施了对MCP通知的适当处理(请求没有 id 现场)
  • 可选ID处理:使请求/响应ID可选,以符合JSON-RPC 2.0规范
  • 工具响应包装:已修复 tools/call 以适当的MCP内容格式包装结果的响应 { content: [{ type: "text", text: "..." }] }

数据解析增强功能

  • 区域感知大小解析:修复了使用特定于区域设置的格式解析磁盘大小的问题(例如,使用逗号分隔符的“4,6G”)
  • 灵活的时间解析:增强了运行时间解析,以处理“MM:SS”和“HH:MM:SS”或“D-HH:MM:SS”格式
  • 稳健的错误处理:改进了错误消息和解析验证

集成测试

  • OpenCode兼容性:已成功使用OpenCode MCP客户端进行测试
  • 协议验证:验证是否符合流式HTTP MCP规范

建筑

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   HTTP Client   │    │   MCP Client    │    │   Other Tools   │
└─────────┬───────┘    └─────────┬───────┘    └─────────┬───────┘
          │                      │                      │
          └──────────────────────┼──────────────────────┘
                                 │
                    ┌─────────────▼─────────────┐
                    │     HTTP Server           │
                    │   (Port 57996)            │
                    │   (Axum Framework)        │
                    └─────────────┬─────────────┘
                                  │
                    ┌─────────────▼─────────────┐
                    │     MCP Server            │
                    │  (JSON-RPC Handler)       │
                    │  (Protocol Implementation)│
                    └─────────────┬─────────────┘
                                  │
                    ┌─────────────▼─────────────┐
                    │   System Monitor          │
                    │  (Core Monitoring Logic)  │
                    │  (sysinfo integration)    │
                    └─────────────┬─────────────┘
                                  │
                    ┌─────────────▼─────────────┐
                    │   Linux System Layer      │
                    │  (procfs, sysfs, commands)│
                    │  (CPU, Memory, Disk, etc.)│
                    └───────────────────────────┘

安装

先决条件

  • Linux服务器:Ubuntu 18.04+、CentOS 7+、RedHat 7+或兼容发行版
  • 系统工具:标准Linux命令(ps、df、ip、cat、hostname、uname)
  • 锈:1.70或更高
  • 货物:包管理器
  • 快速开始

系统要求

  • 最小:512MB RAM,1个CPU内核
  • 推荐:1GB RAM,2个CPU内核
  • 存储:100MB用于应用程序+日志
  • 网络:端口8080上的HTTP/HTTPS访问

构建并运行

  1. 克隆存储库:
git clone https://github.com/hungtrungthinh/mcp-system-monitor.git
cd mcp-system-monitor
  1. 构建项目:
# Development build
cargo build

# Production build
cargo build --release
  1. 运行服务器:
# Development mode
cargo run

# Production mode
cargo run --release

默认情况下,服务器将在端口8080上启动。

快速开始

自动安装(推荐)

# Clone repository and run install script
git clone https://github.com/DarkPhilosophy/mcp-system-monitor.git
cd mcp-system-monitor
chmod +x install.sh
sudo ./install.sh    # Linux
# or
./install.sh         # macOS

脚本将:

  • 通过自制程序或rustup安装Rust(如果需要)
  • 构建项目
  • 设置systemd(Linux)或launchd(macOS)服务
  • 自动启动服务
  • 测试API运行状况

手动安装

1.启动服务器

# Clone and build
git clone https://github.com/DarkPhilosophy/mcp-system-monitor.git
cd mcp-system-monitor
cargo build --release

# Run the server
cargo run --release

2.测试API

# Health check
curl http://localhost:57996/health

# Get system information
curl http://localhost:57996/api/system/info

# Get CPU information
curl http://localhost:57996/api/system/cpu

3.运行示例客户端

# In another terminal
cargo run --example client

OpenCode集成

OpenCode的安装

  1. 安装MCP系统监视器 (如果尚未安装):
sudo ./install.sh    # Automated installation
  1. 编辑OpenCode配置:

编辑 ~/.config/opencode/opencode.json 并添加到 mcp 章节:

{
  "mcp": {
    "mcp-system-monitor": {
      "type": "remote",
      "url": "http://localhost:57996/",
      "enabled": true
    }
  }
}

完整示例 ~/.config/opencode/opencode.json:

{
  "$schema": "https://opencode.ai/config.json",
  "model": "mistral/devstral-medium-latest",
  "mcp": {
    "mcp-system-monitor": {
      "type": "remote",
      "url": "http://localhost:57996/",
      "enabled": true
    }
  }
}

替代方案:使用stdio传输

如果您更喜欢stdio传输而不是HTTP:

{
  "mcp": {
    "mcp-system-monitor": {
      "type": "local",
      "command": [
        "/opt/mcp-system-monitor/target/release/mcp-system-monitor",
        "--stdio"
      ],
      "enabled": true
    }
  }
}

在MCP系统监视器中使用OpenCode

配置后,您可以直接从OpenCode查询系统信息:

User: What's my current CPU usage?
OpenCode will call: tools/call with method "get_cpu_info"
Response: CPU usage percentage and details

OpenCode中的可用工具

所有MCP方法都可以作为工具使用:

  • initialize -初始化MCP会话
  • tools/list -列出可用的监控工具
  • tools/call -调用具有参数的特定监控工具:
    • get_system_info -获取系统信息
    • get_cpu_info -获取CPU信息
    • get_memory_info -获取内存信息
    • get_disk_info -获取磁盘信息
    • get_network_info -获取网络信息
    • get_processes -获取所有进程
    • get_process_by_pid -获取具体流程
    • get_system_metrics -获取完整的系统指标

OpenCode查询示例

OpenCode: "Show me the top CPU consuming processes"
→ Calls: tools/call with "get_processes"
→ Returns: Process list sorted by CPU usage
→ OpenCode analyzes and presents results

OpenCode集成故障排除

连接被拒绝错误:

# Ensure service is running
sudo systemctl status mcp-system-monitor  # Linux
# or
launchctl list | grep mcp-system-monitor  # macOS

# Check if service is listening on port 57996
curl http://localhost:57996/health

--stdio模式的权限被拒绝:

# Ensure binary has correct permissions
chmod +x /opt/mcp-system-monitor/target/release/mcp-system-monitor

OpenCode找不到MCP服务器:

# Verify opencode.json syntax
cat ~/.config/opencode/opencode.json | python3 -m json.tool

# Test MCP connection manually
curl -X POST http://localhost:57996 \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":"1","method":"tools/list","params":{}}'

API文档

基本URL

http://localhost:8080

认证

目前,不需要身份验证。对于生产使用,实施适当的身份验证机制。

响应格式

所有API响应均为JSON格式,结构如下:

{
  "jsonrpc": "2.0",
  "id": "request-id",
  "result": { ... },
  "error": null
}

HTTP REST API端点

系统信息

GET /health

健康检查端点。

答复:

{
  "status": "healthy",
  "service": "MCP System Monitor",
  "timestamp": "2024-01-01T00:00:00Z"
}
GET /api/system/info

获取全面的系统信息。

答复:

{
  "hostname": "server.example.com",
  "os_name": "Ubuntu",
  "os_version": "20.04.3 LTS",
  "kernel_version": "5.4.0-74-generic",
  "uptime": 86400,
  "boot_time": "2024-01-01T00:00:00Z"
}
GET /api/system/cpu

获取CPU信息和使用统计数据。

答复:

{
  "name": "Intel(R) Core(TM) i7-8700K",
  "brand": "GenuineIntel",
  "frequency": 3600,
  "cores": 6,
  "usage_percent": 45.2,
  "temperature": 65.5
}
GET /api/system/memory

获取内存信息,包括RAM和交换使用情况。

答复:

{
  "total": 16777216000,
  "used": 8388608000,
  "free": 8388608000,
  "available": 12582912000,
  "swap_total": 2147483648,
  "swap_used": 0,
  "swap_free": 2147483648,
  "usage_percent": 50.0,
  "swap_usage_percent": 0.0
}
GET /api/system/disks

获取所有已装载文件系统的磁盘信息。

答复:

[
  {
    "name": "/dev/sda1",
    "mount_point": "/",
    "file_system": "ext4",
    "total_space": 107374182400,
    "used_space": 53687091200,
    "free_space": 53687091200,
    "usage_percent": 50.0
  }
]
GET /api/system/networks

获取网络接口信息和统计数据。

答复:

[
  {
    "interface": "eth0",
    "ip_address": "192.168.1.100",
    "mac_address": "00:11:22:33:44:55",
    "bytes_received": 1073741824,
    "bytes_transmitted": 536870912,
    "packets_received": 1000000,
    "packets_transmitted": 500000,
    "errors_received": 0,
    "errors_transmitted": 0
  }
]
GET /api/system/processes

获取有关所有正在运行的进程的信息。

答复:

[
  {
    "pid": 1,
    "name": "systemd",
    "command": "/sbin/init",
    "cpu_usage": 0.1,
    "memory_usage": 1048576,
    "memory_usage_percent": 0.01,
    "status": "S",
    "start_time": "2024-01-01T00:00:00Z",
    "user": "root",
    "priority": 0
  }
]
GET /api/system/processes/{pid}

通过PID获取特定进程的信息。

参数:

  • pid (路径):进程ID

答复:

{
  "pid": 1234,
  "name": "nginx",
  "command": "nginx: master process",
  "cpu_usage": 0.5,
  "memory_usage": 2097152,
  "memory_usage_percent": 0.02,
  "status": "S",
  "start_time": "2024-01-01T00:00:00Z",
  "user": "www-data",
  "priority": 0
}
GET /api/system/metrics

获取完整的系统指标快照。

答复:

{
  "timestamp": "2024-01-01T00:00:00Z",
  "system_info": { ... },
  "cpu_info": { ... },
  "memory_info": { ... },
  "disks": [ ... ],
  "networks": [ ... ],
  "processes": [ ... ]
}

监控

POST /api/monitoring/start

开始持续监测。

答复:

{
  "started": true,
  "message": "Monitoring started successfully"
}
POST /api/monitoring/stop

停止连续监测。

答复:

{
  "stopped": true,
  "message": "Monitoring stopped successfully"
}
GET /api/monitoring/status

获取监控状态。

答复:

{
  "monitoring_active": true,
  "last_update": "2024-01-01T00:00:00Z",
  "service_status": "running"
}

API使用示例

使用curl

# Get system information
curl http://localhost:8080/api/system/info

# Get CPU usage and temperature
curl http://localhost:8080/api/system/cpu

# Get memory information
curl http://localhost:8080/api/system/memory

# Get disk usage
curl http://localhost:8080/api/system/disks

# Get network interfaces
curl http://localhost:8080/api/system/networks

# Get top processes by CPU usage
curl http://localhost:8080/api/system/processes

# Get specific process details
curl http://localhost:8080/api/system/processes/1234

# Get complete system metrics
curl http://localhost:8080/api/system/metrics

# Start continuous monitoring
curl -X POST http://localhost:8080/api/monitoring/start

# Stop monitoring
curl -X POST http://localhost:8080/api/monitoring/stop

使用Python

import requests

base_url = "http://localhost:8080"

# Get system info
response = requests.get(f"{base_url}/api/system/info")
system_info = response.json()

# Get CPU info
response = requests.get(f"{base_url}/api/system/cpu")
cpu_info = response.json()

# Get processes
response = requests.get(f"{base_url}/api/system/processes")
processes = response.json()

使用JavaScript/Node.js

const axios = require('axios');

const baseUrl = 'http://localhost:8080';

// Get system info
const systemInfo = await axios.get(`${baseUrl}/api/system/info`);

// Get CPU info
const cpuInfo = await axios.get(`${baseUrl}/api/system/cpu`);

// Get processes
const processes = await axios.get(`${baseUrl}/api/system/processes`);

MCP协议

服务器使用JSON-RPC 2.0和Streamable HTTP传输实现了用于系统监控的模型上下文协议。

MCP方法

请求方法(需要响应)

  • initialize -通过协议版本协商初始化MCP会话
  • tools/list -列出所有可用的监控工具
  • tools/call -调用特定的监控工具

通知方式(预期无响应)

  • initialized -信号初始化完成

可用工具

通话时 tools/call,使用这些工具名称:

  • get_system_info -获取系统信息
  • get_cpu_info -获取CPU信息
  • get_memory_info -获取内存信息
  • get_disk_info -获取磁盘信息
  • get_network_info -获取网络信息
  • get_processes -获取所有进程
  • get_system_metrics -获取完整的系统指标

MCP请求示例

初始化请求(POST/)

{
  "jsonrpc": "2.0",
  "id": 0,
  "method": "initialize",
  "params": {
    "protocolVersion": "2025-06-18",
    "clientInfo": {
      "name": "opencode",
      "version": "1.0"
    },
    "capabilities": {}
  }
}

初始化响应

{
  "jsonrpc": "2.0",
  "id": 0,
  "result": {
    "protocolVersion": "2025-06-18",
    "capabilities": {
      "tools": {}
    },
    "serverInfo": {
      "name": "mcp-system-monitor",
      "version": "0.1.0"
    }
  }
}

工具列表请求(POST/)

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list",
  "params": null
}

工具调用请求(POST/)

{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "get_system_info",
    "arguments": {}
  }
}

工具调用响应

{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\n  \"hostname\": \"hp\",\n  \"os_name\": \"Bazzite\",\n  \"os_version\": \"43.20251222.0 (Silverblue)\",\n  \"kernel_version\": \"6.17.7-ba22.fc43.x86_64\",\n  \"uptime\": 172051,\n  \"boot_time\": \"2025-12-23T11:29:47Z\"\n}"
      }
    ]
  }
}

初始化通知(POST/)

{
  "jsonrpc": "2.0",
  "method": "initialized",
  "params": {}
}

错误响应

{
  "jsonrpc": "2.0",
  "id": "123",
  "result": null,
  "error": {
    "code": -32601,
    "message": "Method not found",
    "data": null
  }
}

数据结构

系统信息

{
  "hostname": "string",           // System hostname
  "os_name": "string",           // Operating system name
  "os_version": "string",        // Operating system version
  "kernel_version": "string",    // Kernel version
  "uptime": "number",            // System uptime in seconds
  "boot_time": "datetime"        // System boot time (ISO 8601)
}

CPUInfo

{
  "name": "string",              // CPU model name
  "brand": "string",             // CPU brand information
  "frequency": "number",         // CPU frequency in MHz
  "cores": "number",             // Number of CPU cores
  "usage_percent": "number",     // CPU usage percentage (0.0-100.0)
  "temperature": "number|null"   // CPU temperature in Celsius
}

内存信息

{
  "total": "number",             // Total physical memory in bytes
  "used": "number",              // Used physical memory in bytes
  "free": "number",              // Free physical memory in bytes
  "available": "number",         // Available physical memory in bytes
  "swap_total": "number",        // Total swap space in bytes
  "swap_used": "number",         // Used swap space in bytes
  "swap_free": "number",         // Free swap space in bytes
  "usage_percent": "number",     // Memory usage percentage (0.0-100.0)
  "swap_usage_percent": "number" // Swap usage percentage (0.0-100.0)
}

磁盘信息

{
  "name": "string",              // Device name
  "mount_point": "string",       // Mount point
  "file_system": "string",       // File system type
  "total_space": "number",       // Total disk space in bytes
  "used_space": "number",        // Used disk space in bytes
  "free_space": "number",        // Free disk space in bytes
  "usage_percent": "number"      // Disk usage percentage (0.0-100.0)
}

网络信息

{
  "interface": "string",         // Network interface name
  "ip_address": "string",        // IP address
  "mac_address": "string",       // MAC address
  "bytes_received": "number",    // Total bytes received
  "bytes_transmitted": "number", // Total bytes transmitted
  "packets_received": "number",  // Total packets received
  "packets_transmitted": "number", // Total packets transmitted
  "errors_received": "number",   // Total receive errors
  "errors_transmitted": "number" // Total transmit errors
}

进程信息

{
  "pid": "number",               // Process ID
  "name": "string",              // Process name
  "command": "string",           // Full command line
  "cpu_usage": "number",         // CPU usage percentage
  "memory_usage": "number",      // Memory usage in bytes
  "memory_usage_percent": "number", // Memory usage percentage
  "status": "string",            // Process status
  "start_time": "datetime",      // Process start time (ISO 8601)
  "user": "string",              // Process owner
  "priority": "number"           // Process priority
}

发展

使用Claude Code Max进行人工智能辅助开发

该项目完全是使用 克劳德代码Max,一个先进的人工智能驱动的开发平台。开发过程包括:

  • 架构设计:完整的系统架构和组件设计
  • 代码生成:使用Rust最佳实践实现完整的代码库
  • 测试策略:全面的测试套件和集成测试
  • 文档:完整的API文档和用户指南
  • 部署:Docker容器化和部署脚本
  • 质量保证:代码审查、linting和安全审计

与Claude Code Max的集成展示了人工智能辅助开发在创建生产就绪的企业级软件解决方案方面的能力。

项目结构

mcp-system-monitor/
├── src/
│   ├── main.rs                 # Application entry point
│   ├── lib.rs                  # Library exports and documentation
│   ├── server.rs               # MCP protocol handler
│   ├── http_server.rs          # HTTP REST API server
│   ├── types/                  # Data structures and constants
│   │   ├── mod.rs              # Module exports
│   │   ├── protocol.rs         # MCP protocol types
│   │   ├── system.rs           # System data structures
│   │   └── constants.rs        # Protocol constants
│   └── system_monitor/         # System monitoring logic
│       ├── mod.rs              # Module exports
│       ├── core.rs             # Core monitoring functionality
│       ├── helpers.rs          # Utility functions
│       └── linux.rs            # Linux-specific implementations
├── examples/
│   └── client.rs               # Example HTTP client
├── tests/
│   └── integration_test.rs     # Integration tests
├── .vscode/                    # VS Code configuration
├── Cargo.toml                  # Dependencies and build configuration
├── Cargo.lock                  # Dependency lock file
├── README.md                   # This file
├── LICENSE                     # MIT License
├── Dockerfile                  # Docker containerization
├── docker-compose.yml          # Docker Compose configuration
├── deploy.sh                   # Deployment script
└── test_server.sh              # Server testing script

开发设置

  1. 安装Rust:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source ~/.cargo/env
  1. 克隆和设置:
git clone https://github.com/hungtrungthinh/mcp-system-monitor.git
cd mcp-system-monitor
  1. 安装开发依赖项:
# Install cargo-watch for development
cargo install cargo-watch

# Install cargo-audit for security
cargo install cargo-audit
  1. 开发工作流程:
# Run in development mode with auto-reload
cargo watch -x run

# Run tests
cargo test

# Run tests with output
cargo test -- --nocapture

# Check code quality
cargo clippy

# Check for security vulnerabilities
cargo audit

添加新功能

1.新系统指标

添加方法 src/system_monitor/core.rs:

impl SystemMonitor {
    pub fn get_new_metric(&mut self) -> Result<NewMetricInfo> {
        self.refresh();
        self.linux_info.get_new_metric()
    }
}

2.API新端点

将路线添加到 src/http_server.rs:

.route("/api/system/new-metric", get(Self::get_new_metric))

3.新的MCP方法

将处理程序添加到 src/server.rs:

METHOD_GET_NEW_METRIC => self.handle_get_new_metric(id).await,

4.更新常量

将方法常量添加到 src/types/constants.rs:

pub const METHOD_GET_NEW_METRIC: &str = "getNewMetric";

测试

单元测试

# Run all tests
cargo test

# Run specific test
cargo test test_name

# Run tests with output
cargo test -- --nocapture

集成测试

# Run integration tests
cargo test --test integration_test

# Run with verbose output
cargo test --test integration_test -- --nocapture

客户端示例

# Run the example client
cargo run --example client

代码质量

代码检查

# Run clippy for code quality
cargo clippy

# Run clippy with all warnings
cargo clippy -- -W clippy::all

格式化

# Format code
cargo fmt

# Check formatting
cargo fmt -- --check

安全

# Check for security vulnerabilities
cargo audit

# Update dependencies
cargo update

部署

生产建设

# Build for production
cargo build --release

# The binary will be in target/release/mcp-system-monitor

系统化服务

创建 /etc/systemd/system/mcp-system-monitor.service:

[Unit]
Description=MCP System Monitor Server
After=network.target

[Service]
Type=simple
User=mcp-monitor
Group=mcp-monitor
WorkingDirectory=/opt/mcp-system-monitor
ExecStart=/opt/mcp-system-monitor/mcp-system-monitor
Restart=always
RestartSec=5
Environment=RUST_LOG=info

[Install]
WantedBy=multi-user.target

启用并启动服务:

sudo systemctl daemon-reload
sudo systemctl enable mcp-system-monitor
sudo systemctl start mcp-system-monitor
sudo systemctl status mcp-system-monitor

Docker部署

构建Docker镜像

# Build the image
docker build -t mcp-system-monitor .

# Run the container
docker run -d -p 8080:8080 --name mcp-monitor mcp-system-monitor

Docker Compose

# Start with docker-compose
docker-compose up -d

# View logs
docker-compose logs -f

# Stop services
docker-compose down

反向代理(Nginx)

创建 /etc/nginx/sites-available/mcp-system-monitor:

server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

启用站点:

sudo ln -s /etc/nginx/sites-available/mcp-system-monitor /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

带有Let’s Encrypt的SSL/TLS

# Install certbot
sudo apt install certbot python3-certbot-nginx

# Get SSL certificate
sudo certbot --nginx -d your-domain.com

# Auto-renewal
sudo crontab -e
# Add: 0 12 * * * /usr/bin/certbot renew --quiet

监控和日志记录

日志配置

设置环境变量:

export RUST_LOG=info
export RUST_BACKTRACE=1

日志轮转

创建 /etc/logrotate.d/mcp-system-monitor:

/var/log/mcp-system-monitor.log {
    daily
    missingok
    rotate 52
    compress
    delaycompress
    notifempty
    create 644 mcp-monitor mcp-monitor
    postrotate
        systemctl reload mcp-system-monitor
    endscript
}

安全考虑

防火墙配置

# Allow only specific IPs
sudo ufw allow from 192.168.1.0/24 to any port 8080

# Or use specific IPs
sudo ufw allow from 10.0.0.5 to any port 8080

身份验证(未来增强)

对于生产使用,实施身份验证:

// Add to http_server.rs
use tower_http::auth::RequireAuthorizationLayer;

let auth_layer = RequireAuthorizationLayer::bearer("your-secret-token");

错误处理

服务器使用标准JSON-RPC错误代码:

标准JSON-RPC错误

  • -32600:无效请求-发送的JSON不是有效的Request对象
  • -32601:找不到方法-该方法不存在/不可用
  • -32602:参数无效-方法参数无效
  • -32603:内部错误-内部JSON-RPC错误
  • -32700:解析错误-服务器接收到无效的JSON

自定义错误代码

  • -32001:找不到进程-指定的进程PID不存在
  • -32002:监控已开始-持续监控已处于活动状态
  • -32003:监控未启动-连续监控未激活
  • -32004:系统命令失败-所需的系统命令无法执行
  • -32005:权限被拒绝-权限不足,无法访问系统信息

错误响应格式

{
  "jsonrpc": "2.0",
  "id": "request-id",
  "result": null,
  "error": {
    "code": -32001,
    "message": "Process with PID 9999 not found",
    "data": null
  }
}

依赖项

核心依赖

  • 东京:异步运行时用于高性能I/O
  • 塞尔德:JSON处理的序列化/反序列化
  • 系统信息:跨平台系统信息收集
  • 阿克苏姆:现代HTTP web框架
  • 追踪:结构化日志记录和诊断
  • 计时:支持时区的日期和时间处理
  • 通用唯一标识符:唯一标识符生成

发展依赖性

  • 东京试验:异步测试实用程序
  • reqwest:HTTP客户端示例(可选)

系统相关性

  • Linux命令:ps、df、ip、cat、主机名、uname
  • procfs:/proc文件系统访问
  • 系统文件系统:/sys文件系统访问

性能考量

优化功能

  • 异步/等待:非阻塞操作可实现更好的并发性
  • 缓存:系统信息会根据需要进行缓存和刷新
  • 高效的数据结构:通过适当的数据类型优化内存使用
  • 流程排序:进程列表按CPU使用率排序,以获得更好的性能
  • 延迟加载:仅在请求时收集数据

性能基准

  • 响应时间:对于大多数API调用,<100毫秒
  • 内存使用:典型使用约50MB
  • CPU 使用率:空闲时<1%
  • 并发连接:支持1000+并发请求

缩放注意事项

  • 水平缩放:在负载平衡器后面部署多个实例
  • 垂直缩放:增加服务器资源以实现更高的负载
  • 缓存层:为频繁访问的数据添加Redis
  • 数据库:将历史指标存储在PostgreSQL/InfluxDB中

安全

当前安全功能

  • 输入验证:所有参数在处理前都经过验证
  • 错误清理:错误消息不会暴露敏感的系统信息
  • 本地主机绑定:默认情况下,服务器在本地主机上运行
  • 资源限制:内置限制,防止资源枯竭

安全建议

  • 认证:实现API密钥或JWT身份验证
  • 超文本传输安全协议:对所有通信使用SSL/TLS加密
  • 防火墙:限制对特定IP地址的访问
  • 速率限制:实施请求速率限制
  • 审计日志:记录所有API访问以进行安全监控
  • 定期更新:保持安全补丁的依赖关系更新

安全检查列表

  • []实现身份验证机制
  • []启用HTTPS/TLS加密
  • []配置防火墙规则
  • []设置速率限制
  • []启用审核日志记录
  • []定期安全更新
  • []监控可疑活动
  • []备份配置和数据

贡献

开发工作流程

  1. 克隆该仓库
git clone https://github.com/your-username/mcp-system-monitor.git
cd mcp-system-monitor
  1. 创建要素分支
git checkout -b feature/your-feature-name
  1. 进行更改
# Make code changes
# Add tests
# Update documentation
  1. 运行测试和检查
cargo test
cargo clippy
cargo fmt -- --check
  1. 提交您的更改
git add .
git commit -m "feat: add new feature description"
  1. 推送并创建拉取请求
git push origin feature/your-feature-name
# Create PR on GitHub

代码风格指南

  • 遵循Rust编码规范
  • 使用有意义的变量和函数名
  • 添加全面的文档
  • 为新功能编写测试
  • 保持功能小而集中
  • 使用适当的错误处理

提交消息格式

使用常规提交格式:

type(scope): description

[optional body]

[optional footer]

类型:

  • feat:新功能
  • fix:Bug修复
  • docs:文件更改
  • style:代码样式更改
  • refactor:代码重构
  • test:测试更改
  • chore:维护任务

许可证

此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。

法律免责声明

本软件仅用于合法的系统监控和管理目的。严禁出于恶意目的未经授权使用、修改或利用本软件,包括但不限于未经授权的系统访问、数据盗窃或系统中断,这可能违反适用的法律法规。用户有责任确保遵守其管辖范围内的所有适用法律法规。作者对滥用本软件不承担任何责任。

支持

获取帮助

  1. 检查文档 -此README和代码注释
  2. 搜索现有问题 -在GitHub上查找类似问题
  3. 创建新问题 -提供有关问题的详细信息

问题报告

在报告问题时,请包括:

  • 环境:操作系统版本、Rust版本、系统详细信息
  • 重现步骤:重现问题的明确步骤
  • 预期行为你期望会发生什么
  • 实际行为实际发生了什么
  • 日志:相关错误消息和日志
  • 代码:最小代码示例(如适用)

社区

  • GitHub问题:用于错误报告和功能请求
  • GitHub 讨论区:供提问和一般性讨论
  • 电子邮件: hello@boringlab.info直接支持

AI代理用例

远程服务器管理

  • 多服务器监控:AI代理可以同时监视多个Linux服务器
  • 自动警报:根据系统指标设置智能警报
  • 预测性维护:分析趋势以预测潜在问题
  • 资源优化:人工智能驱动的资源分配建议

DevOps与运营

  • CI/CD集成:在部署期间监视系统运行状况
  • 性能测试:负载测试期间的轨道系统性能
  • 容量规划:资源使用模式的人工智能分析
  • 事件响应:事故期间快速系统评估

安全监控

  • 过程监控:检测异常过程活动
  • 资源使用分析:识别潜在的安全威胁
  • 网络流量监控:监视网络接口活动
  • 系统完整性:跟踪系统变化和异常

云和边缘计算

  • 云实例监控:监控云环境中的Linux实例
  • 边缘设备管理:监视基于Linux的边缘设备
  • 集装箱监控:监控容器化应用程序的系统资源
  • 微服务健康:跟踪微服务架构的系统健康状况

AI代理集成示例

Python AI代理

import requests
import json

class SystemMonitorAgent:
    def __init__(self, server_url):
        self.server_url = server_url
    
    def get_system_health(self):
        response = requests.get(f"{self.server_url}/api/system/metrics")
        metrics = response.json()
        
        # AI analysis of system health
        cpu_usage = metrics['cpu_info']['usage_percent']
        memory_usage = metrics['memory_info']['usage_percent']
        
        if cpu_usage > 80 or memory_usage > 90:
            return "CRITICAL"
        elif cpu_usage > 60 or memory_usage > 70:
            return "WARNING"
        else:
            return "HEALTHY"
    
    def recommend_actions(self, health_status):
        if health_status == "CRITICAL":
            return ["Restart high-CPU processes", "Increase memory", "Scale horizontally"]
        elif health_status == "WARNING":
            return ["Monitor closely", "Optimize resource usage"]
        else:
            return ["Continue monitoring"]

JavaScript人工智能代理

class SystemMonitorAgent {
    constructor(serverUrl) {
        this.serverUrl = serverUrl;
    }
    
    async analyzeSystemHealth() {
        const response = await fetch(`${this.serverUrl}/api/system/metrics`);
        const metrics = await response.json();
        
        const analysis = {
            cpuHealth: this.analyzeCPU(metrics.cpu_info),
            memoryHealth: this.analyzeMemory(metrics.memory_info),
            diskHealth: this.analyzeDisks(metrics.disks),
            recommendations: []
        };
        
        return analysis;
    }
    
    analyzeCPU(cpuInfo) {
        if (cpuInfo.usage_percent > 80) {
            return { status: 'CRITICAL', message: 'High CPU usage detected' };
        }
        return { status: 'HEALTHY', message: 'CPU usage normal' };
    }
}

路线图

注: 项目路线图目前尚未公开。如有需要,请联系作者以获取更多信息。