Linux版MCP系统监控服务器
一种模型上下文协议(MCP)服务器实现,专为AI代理监控Linux服务器(Ubuntu、CentOS、RedHat等)并与之交互而设计。该服务器通过MCP协议和HTTP REST API提供全面的系统信息,包括CPU、内存、磁盘、网络和过程数据,使AI代理能够执行远程系统监控和管理任务。
开发平台
该项目是使用 克劳德代码Max,一个先进的人工智能驱动的开发平台。整个代码库、架构设计、测试和文档都是在Claude Code Max的协助下创建的,使其成为一个全面的人工智能辅助开发项目。
作者
姓名: Thinh Nguyen\ 角色: 企业IT\ 电子邮件: hello@boringlab.info
仓库
官方GitHub:
目录
特性
- 人工智能辅助开发:完全采用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代理通信的标准模型上下文协议
建筑
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ HTTP Client │ │ MCP Client │ │ Other Tools │
└─────────┬───────┘ └─────────┬───────┘ └─────────┬───────┘
│ │ │
└──────────────────────┼──────────────────────┘
│
┌─────────────▼─────────────┐
│ HTTP Server │
│ (Port 8080) │
│ (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访问
构建并运行
- 克隆存储库:
git clone https://github.com/hungtrungthinh/mcp-system-monitor.git
cd mcp-system-monitor- 构建项目:
# Development build
cargo build
# Production build
cargo build --release- 运行服务器:
# Development mode
cargo run
# Production mode
cargo run --release默认情况下,服务器将在端口8080上启动。
快速开始
1.启动服务器
# Clone and build
git clone https://github.com/hungtrungthinh/mcp-system-monitor.git
cd mcp-system-monitor
cargo build --release
# Run the server
cargo run --release2.测试API
# Health check
curl http://localhost:8080/health
# Get system information
curl http://localhost:8080/api/system/info
# Get CPU information
curl http://localhost:8080/api/system/cpu3.运行示例客户端
# In another terminal
cargo run --example clientAPI文档
基础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实现了用于系统监控的模型上下文协议。
可用方法
getSystemInfo-获取系统信息getCPUInfo-获取CPU信息getMemoryInfo-获取内存信息getDiskInfo-获取磁盘信息getNetworkInfo-获取网络信息getProcesses-获取所有进程getProcessByPID-通过PID获取具体流程getSystemMetrics-获取完整的系统指标startMonitoring-开始监控stopMonitoring-停止监控
MCP请求示例
{
"jsonrpc": "2.0",
"id": "123",
"method": "getSystemInfo",
"params": {}
}MCP响应示例
{
"jsonrpc": "2.0",
"id": "123",
"result": {
"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"
},
"error": null
}错误响应
{
"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开发环境
- 安装Rust:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source ~/.cargo/env- 克隆和设置:
git clone https://github.com/hungtrungthinh/mcp-system-monitor.git
cd mcp-system-monitor- 安装开发依赖项:
# Install cargo-watch for development
cargo install cargo-watch
# Install cargo-audit for security
cargo install cargo-audit- 开发工作流程:
# 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 {
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-monitorDocker部署
构建Docker镜像
# Build the image
docker build -t mcp-system-monitor .
# Run the container
docker run -d -p 8080:8080 --name mcp-monitor mcp-system-monitorDocker 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框架
- 追踪:结构化日志记录和诊断
- 计时:支持时区的日期和时间处理
- 通用唯一标识符:唯一标识符生成
发展依赖性
- 东京试验:异步测试实用程序
- 请求:HTTP客户端示例(可选)
系统依赖
- Linux命令:ps、df、ip、cat、主机名、uname
- procfs:/proc文件系统访问
- 系统文件系统:/sys文件系统访问
性能考量
优化功能
- 异步/等待:非阻塞操作可实现更好的并发性
- 缓存:系统信息会根据需要进行缓存和刷新
- 高效的数据结构:通过适当的数据类型优化内存使用
- 流程排序:进程列表按CPU使用率排序,以获得更好的性能
- 懒加载:仅在请求时收集数据
性能基准
- 响应时间:对于大多数API调用,\ 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' }; } }
## 路线图
**注:** 项目路线图目前尚未公开。如有需要,请联系作者以获取更多信息。
______________________________________________________________________