diff --git a/mcp/README.md b/mcp/README.md index 5b9256e8..23eee1c0 100644 --- a/mcp/README.md +++ b/mcp/README.md @@ -1,994 +1,325 @@ -# Practical Usage Examples - Glances MCP +# Glances MCP Server -This guide presents concrete examples of using the Glances MCP server with Claude. +A Model Context Protocol (MCP) server that provides system monitoring capabilities through integration with [Glances](https://github.com/nicolargo/glances), a cross-platform system monitoring tool. -## ๐ฏ Scenario 1: Daily Monitoring +## Overview -### Example 1.1: Morning Check-up +The Glances MCP Server exposes Glances monitoring data through the MCP protocol, allowing AI assistants and other MCP clients to query system statistics, monitor processes, check resource usage, and analyze system performance. -**You**: -``` -Good morning Claude! Can you give me a status report on my server this morning? -``` +## Features -**Claude**: -``` -Good morning! Here's your server status this morning: +- **Real-time System Monitoring**: Access CPU, memory, disk, network, and process information +- **Multiple Transport Options**: Supports both stdio (standard) and HTTP transports +- **15+ Tools**: Comprehensive set of tools for system monitoring +- **Resource Summaries**: Formatted system statistics summaries +- **Performance Analysis**: Built-in prompts for system performance analysis -โ OVERALL STATUS: Healthy +## Prerequisites -๐ KEY METRICS: -โข CPU: 12% usage (4 cores) - - User: 8%, System: 3%, Idle: 89% - - Load average: 0.45, 0.52, 0.48 (1/5/15 min) +- Python 3.10 or higher +- [Glances](https://github.com/nicolargo/glances) installed and running +- pip or uv package manager -โข MEMORY: 8.2 GB / 16 GB (51%) - - Available: 7.8 GB - - Swap: 512 MB / 4 GB (12%) +## Installation -โข DISKS: - - / (sda1): 285 GB / 500 GB (57%) โ - - /home (sda2): 156 GB / 200 GB (78%) โ ๏ธ - - /var (sda3): 42 GB / 50 GB (84%) โ ๏ธ +### 1. Install Glances -โข NETWORK (eth0): - - Received: 2.5 Mbps - - Sent: 0.8 Mbps - -โข TEMPERATURE: 48ยฐC (normal) - -โ ๏ธ ATTENTION POINTS: -1. /home approaching 80% - consider cleanup -2. /var at 84% - check logs - -Need to analyze anything in particular? -``` - -*MCP tools used: `check_glances_status()`, `get_cpu_usage()`, `get_memory_usage()`, `get_disk_usage()`, `get_network_stats()`, `get_system_sensors()`* - ---- - -### Example 1.2: Simplified Monitoring - -**You**: -``` -Just CPU and RAM please -``` - -**Claude**: -``` -๐ Quick Stats: - -CPU: 15% (Load: 0.6) -RAM: 51% (8.2/16 GB) - -All good! ๐ -``` - -*MCP tools used: `get_cpu_usage()`, `get_memory_usage()`* - ---- - -## ๐ Scenario 2: Problem Diagnosis - -### Example 2.1: Slow Computer - -**You**: -``` -My computer has been sluggish for 10 minutes, what's happening? -``` - -**Claude**: -``` -Let me analyze what's slowing down your system... - -๐ด PROBLEM IDENTIFIED! - -CPU is at 94% usage - here are the culprits: - -TOP 5 RESOURCE-INTENSIVE PROCESSES: -1. โ node (PID 3421) - 45% CPU, 2.8 GB RAM - โโ Command: node --max-old-space-size=4096 build.js - โโ Started: 12 min ago - -2. โ chrome (PID 2156) - 28% CPU, 3.2 GB RAM - โโ 47 tabs open - -3. โ ๏ธ docker (PID 1234) - 12% CPU, 1.5 GB RAM - โโ Container: mysql_prod - -4. โ code (PID 4567) - 5% CPU, 800 MB RAM -5. โ spotify (PID 5678) - 4% CPU, 450 MB RAM - -๐ฏ ANALYSIS: -The Node.js process is performing a build consuming 45% CPU. -Chrome with 47 tabs is making the situation worse. - -๐ก RECOMMENDATIONS: -1. Urgent: Close some Chrome tabs (will save ~15% CPU) -2. Wait for Node.js build to finish (2-3 min estimated) -3. Optional: Restart MySQL container if slowness persists - -Would you like me to monitor progress every 30 seconds? -``` - -*MCP tools used: `get_cpu_usage()`, `get_top_processes(10)`, `get_process_info(3421)`, `get_process_info(2156)`* - ---- - -### Example 2.2: Memory Saturation - -**You**: -``` -I'm getting "Out of memory" messages, help me! -``` - -**Claude**: -``` -๐จ CRITICAL MEMORY ALERT! - -CURRENT STATE: -โข RAM: 15.4 GB / 16 GB (96%) โ -โข Swap: 3.8 GB / 4 GB (95%) โ -โข Available: Only 640 MB - -๐ด PROCESSES CONSUMING MOST RAM: - -1. docker (PID 1234) - 4.2 GB - โโ Container postgres_db - โโ SUGGESTION: Limit Docker RAM - -2. chrome (PID 2345) - 3.8 GB - โโ 63 tabs open - โโ ACTION: Close immediately! - -3. intellij-idea (PID 5678) - 2.9 GB - โโ Heap size: 2048m - โโ SUGGESTION: Reduce -Xmx - -4. node (PID 8901) - 2.1 GB - โโ Multiple active processes - -5. firefox (PID 3456) - 1.4 GB - -โก IMMEDIATE ACTIONS: -1. โ Close Chrome NOW (will free ~4 GB) -2. โ ๏ธ Restart IntelliJ with -Xmx1024m -3. ๐ Restart Postgres container with RAM limit -4. ๐งน Kill unused Node processes - -๐ง SUGGESTED COMMANDS: ```bash -# Kill Chrome cleanly -killall chrome +# Using pip +pip install glances -# Limit Docker Postgres -docker update --memory=2g postgres_db +# Using system package manager (Ubuntu/Debian) +sudo apt install glances -# View Node processes -ps aux | grep node +# Using Homebrew (macOS) +brew install glances ``` -Long-term configuration recommended: upgrade to 32 GB RAM -``` +### 2. Install MCP Server Dependencies -*MCP tools used: `get_memory_usage()`, `get_top_processes(15)`, RAM analysis* - ---- - -## ๐ Scenario 3: Temporal Analysis - -### Example 3.1: Performance Evolution - -**You**: -``` -Show me CPU evolution over the last 2 hours -``` - -**Claude**: -``` -๐ CPU EVOLUTION - LAST 2 HOURS (120 measurements) - -ASCII Chart: -100%| โโ | - 90%| โโโโ | - 80%| โโโโโโ | - 70%| โโโโโโโโ | - 60%| โโโโโโโโโโ | - 50%| โโ โโโโโโโโโโโโ | - 40%| โโโโ โโโโโโโโโโโโโโ โโ | - 30%| โโโโโโ โโโโโโโโโโโโโโโโ โโโโ | - 20%| โโโโโโโโ โโโโโโโโโโโโโโโโโโ โโโโโโ | - 10%|โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ| - 0%|__________________________________________________| - 12:00 13:00 14:00 (now) - -๐ STATISTICS: -โข Average: 28% -โข Minimum: 8% (at 12:15) -โข Maximum: 94% (at 13:23) -โข Current: 15% - -๐ NOTABLE EVENTS: - -1. โ ๏ธ PEAK at 13:23 (94%) - Duration: 8 minutes - Probable cause: Build or compilation - -2. ๐ Stable usage 12:00-12:45 (~12%) - Low activity period - -3. ๐ Progressive increase 12:45-13:15 - Normal ramp-up - -4. โ Back to normal since 13:30 - System stabilized - -๐ก ANALYSIS: -Normal behavior with an isolated peak probably caused by -a batch task. No performance issues detected. - -Want to see details of the 13:23 peak? -``` - -*MCP tools used: `get_plugin_history("cpu", 120)`* - ---- - -### Example 3.2: Disk Trend - -**You**: -``` -My disk is filling up quickly, how long until it's full? -``` - -**Claude**: -``` -๐ PREDICTIVE ANALYSIS - DISK SPACE - -CURRENT STATE (/): -โข Used: 285 GB / 500 GB (57%) -โข Available: 215 GB -โข Inodes: 12% used - -๐ HISTORICAL ANALYSIS (last 30 days): -``` -Day 1: โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 42% -Day 5: โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 44% -Day 10: โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 46% -Day 15: โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 49% -Day 20: โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 52% -Day 25: โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 55% -Day 30: โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 57% โ Today -``` - -๐ฎ PREDICTIONS: - -Average growth: +500 MB/day (~0.1%/day) - -โข 70% (350 GB): In ~130 days (April 21, 2026) -โข 80% (400 GB): In ~230 days (July 30, 2026) -โข 90% (450 GB): In ~330 days (November 7, 2026) -โข 95% (475 GB): In ~380 days (December 27, 2026) - -๐ MAIN CONSUMERS: -1. /var/log: 45 GB (application logs) -2. /home/user/Downloads: 38 GB -3. Docker images: 32 GB -4. /tmp: 12 GB - -๐ก RECOMMENDATIONS: - -โจ QUICK ACTIONS (gain: ~80 GB): ```bash -# Clean old logs -sudo journalctl --vacuum-time=7d - -# Empty downloads -rm -rf ~/Downloads/old/* - -# Remove unused Docker images -docker system prune -a +# Install required packages +pip install requests mcp uvicorn fastapi ``` -๐ PLANNING: -โข Short term (OK): Nothing urgent -โข Medium term: Implement automatic log rotation -โข Long term: Disk extension or NAS +Or create a `requirements.txt`: -You're safe for at least 6 months! ๐ +```txt +requests>=2.31.0 +mcp>=1.0.0 +uvicorn>=0.27.0 +fastapi>=0.104.0 ``` -*MCP tools used: `get_plugin_history("fs", 30)`, `get_disk_usage()`* +Then install: ---- - -## ๐ง Scenario 4: Advanced Operations - -### Example 4.1: Monitoring a Critical Process - -**You**: -``` -I just launched an important Python script (PID 9876). -Monitor it and let me know if there's a problem. -``` - -**Claude**: -``` -โ Monitoring activated for process 9876 - -๐ INITIAL INFORMATION: -โข Name: python3 -โข Command: python3 data_processing.py --batch-size=1000 -โข State: Running -โข Started: 2 seconds ago -โข CPU: 85% (normal for data processing) -โข RAM: 1.2 GB / 16 GB -โข Disk I/O: 45 MB/s read, 12 MB/s write -โข Threads: 4 - -๐ SYSTEM RESOURCES: -โข Global CPU: 89% (your script + others) -โข Available RAM: 14.2 GB (plenty available) -โข Temperature: 62ยฐC (normal increase) - -โ EVERYTHING IS NORMAL - -I will monitor: -1. CPU usage (alert if > 98% for 5 min) -2. RAM usage (alert if > 8 GB) -3. Process state (alert if crash) -4. Excessive I/O (alert if > 200 MB/s for 10 min) - -[โฑ๏ธ I'll keep you informed every 5 minutes or in case of anomaly] - -๐ก TIP: Type "status 9876" for instant update -``` - -*MCP tools used: `get_process_info(9876)`, `get_cpu_usage()`, `get_memory_usage()`* - ---- - -**5 minutes later...** - -**Claude** (automatic update): -``` -๐ UPDATE - Process 9876 - -Elapsed time: 5 min 23 sec - -State: โ Running (all good) -โข CPU: 78% (stable) -โข RAM: 2.1 GB (+900 MB - normal growth) -โข I/O: 38 MB/s (decreasing, end of reading?) -โข Estimated progress: ~25% (based on I/O patterns) - -No anomalies detected. Next update in 5 min. -``` - ---- - -### Example 4.2: Before/After Comparison - -**You**: -``` -I'm going to optimize my MySQL config. Note the current state, -I'll tell you when to compare. -``` - -**Claude**: -``` -๐ธ SNAPSHOT SAVED - MySQL Performance - -TIMESTAMP: 2025-12-11 14:23:45 - -๐ MYSQL STATE (PID 1234): -โข CPU: 23% -โข RAM: 2.8 GB -โข Threads: 156 -โข Connections: 48 active - -๐ SYSTEM METRICS: -โข Global CPU: 45% -โข Total RAM: 12.1 GB / 16 GB (75%) -โข Load average: 1.8, 2.1, 1.9 -โข Disk I/O: 85 MB/s - -๐ QUERIES (via process analysis): -โข Queries/sec: ~450 (estimated via CPU patterns) -โข I/O operations: High - -โ Baseline saved! -Type "compare mysql" when you're done with the optimization. -``` - ---- - -**After optimization...** - -**You**: -``` -compare mysql -``` - -**Claude**: -``` -๐ BEFORE/AFTER COMPARISON - MySQL Optimization - -โโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโ -โ Metric โ Before โ After โ ฮ โ -โโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโค -โ CPU Usage โ 23% โ 14% โ -39% โ โ -โ RAM Usage โ 2.8 GB โ 2.1 GB โ -25% โ โ -โ Threads โ 156 โ 98 โ -37% โ โ -โ Connections โ 48 โ 45 โ -6% โ โ -โ Load Avg (1m) โ 1.8 โ 1.2 โ -33% โ โ -โ Disk I/O โ 85 MB/s โ 62 MB/s โ -27% โ โ -โโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโ - -๐ EXCELLENT RESULTS! - -๐ก GAINS ACHIEVED: -โข CPU saved: 9 percentage points -โข RAM freed: 700 MB -โข System load reduced by 33% -โข I/O lightened by 23 MB/s - -๐ PERFORMANCE: -The optimization is very effective! The system breathes better -and should handle more load. - -โ RECOMMENDATION: -Keep this configuration. Monitor for 24h to -confirm stability. - -Would you like me to generate a complete report? -``` - -*MCP tools used: `get_process_info()`, temporal snapshots, comparisons* - ---- - -## ๐ณ Scenario 5: Docker and Containers - -### Example 5.1: Docker Overview - -**You**: -``` -Give me a status of my Docker containers -``` - -**Claude**: -``` -๐ณ DOCKER CONTAINERS - OVERVIEW - -๐ SUMMARY: -โข Total containers: 5 -โข Running: 4 โ -โข Stopped: 1 โ ๏ธ - -โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ - -1. โ webapp_prod (nginx:alpine) - โโ Status: Running (uptime: 12d 5h) - โโ CPU: 2% (very low) - โโ RAM: 125 MB / 512 MB limit (24%) - โโ Network: โ 5.2 Mbps โ 1.8 Mbps - โโ Health: Healthy - -2. โ postgres_db (postgres:14) - โโ Status: Running (uptime: 12d 5h) - โโ CPU: 15% (active) - โโ RAM: 1.8 GB / 4 GB limit (45%) - โโ Network: โ 2.1 Mbps โ 3.4 Mbps - โโ I/O: 85 MB/s read, 42 MB/s write - โโ Health: Healthy - -3. โ redis_cache (redis:7-alpine) - โโ Status: Running (uptime: 12d 5h) - โโ CPU: 1% - โโ RAM: 89 MB / 256 MB limit (35%) - โโ Network: โ 0.8 Mbps โ 0.3 Mbps - โโ Health: Healthy - -4. โ worker_queue (python:3.11-slim) - โโ Status: Running (uptime: 3h 22m) - โโ CPU: 8% - โโ RAM: 340 MB / 1 GB limit (34%) - โโ Network: โ 0.2 Mbps โ 0.1 Mbps - โโ Health: Healthy - -5. โ ๏ธ backup_service (custom/backup:latest) - โโ Status: Exited (code 0) - 2h ago - โโ Last seen: OK (normal, scheduled task) - โโ Note: Launches automatically - -โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ - -๐ TOTAL DOCKER USAGE: -โข CPU: 26% (all containers) -โข RAM: 2.36 GB / 5.77 GB allocated (41%) -โข Network: โ 8.3 Mbps โ 5.6 Mbps - -๐พ IMAGES: -โข Total size: 4.2 GB -โข Unused images: 1.8 GB (cleanable) - -โ OVERALL HEALTH: Excellent -All critical services are operational. - -๐ก SUGGESTION: ```bash -# Clean unused images -docker image prune -a -# Estimated gain: ~1.8 GB -``` +pip install -r requirements.txt ``` -*MCP tools used: `get_plugin_data("docker")`, Docker process analysis* +### 3. Download the MCP Server ---- +Save the `glances_mcp.py` file to your desired location. -## ๐ Scenario 6: Reports and Exports +## Usage -### Example 6.1: Weekly Report +### Starting Glances -**You**: -``` -Generate a system health report for my DevOps team +First, start Glances in web server mode: + +```bash +glances -w ``` -**Claude**: -```markdown -# ๐ System Health Report -**Period**: Week of December 4-11, 2025 -**Server**: prod-server-01 -**Generated on**: December 11, 2025 at 2:30 PM +By default, Glances runs on `http://localhost:61208` ---- +### Running the MCP Server -## ๐ฏ Executive Summary +#### Option 1: Stdio Transport (Default - for Claude Desktop) -โ **Overall Status**: HEALTHY -โ ๏ธ **Attention Points**: 2 -โ **Critical Issues**: 0 +```bash +python glances_mcp.py +``` ---- +This mode is used for direct integration with Claude Desktop and other MCP clients that communicate via stdio. -## ๐ Key Metrics +#### Option 2: HTTP Transport (for testing and remote access) -### CPU -- **Average usage**: 28% -- **Maximum peak**: 94% (Dec 8 at 3:23 PM) -- **Load average**: 1.2 / 1.5 / 1.4 -- **Trend**: โ๏ธ +5% vs previous week +```bash +# Using uvicorn +uvicorn glances_mcp:app --host 0.0.0.0 --port 8000 -### Memory -- **Average usage**: 12.2 GB / 16 GB (76%) -- **Maximum peak**: 15.1 GB (94%) on Dec 9 -- **Swap used**: Minimal (< 500 MB) -- **Trend**: โ Stable +# Or with auto-reload for development +uvicorn glances_mcp:app --host 0.0.0.0 --port 8000 --reload -### Disks -| Partition | Used | Capacity | Evolution | -|-----------|------|----------|-----------| -| / | 285 GB | 500 GB (57%) | +2 GB/week | -| /home | 156 GB | 200 GB (78%) | +5 GB/week โ ๏ธ | -| /var | 42 GB | 50 GB (84%) | +1 GB/week โ ๏ธ | +# Or using the built-in flag +python glances_mcp.py --http +``` + +The MCP endpoint will be available at: `http://localhost:8000/mcp` + +## Configuration + +### Glances URL + +By default, the server connects to Glances at `http://localhost:61208`. To change this, edit the `GLANCES_URL` variable in `glances_mcp.py`: + +```python +GLANCES_URL = "http://your-glances-server:61208" +``` + +### Claude Desktop Integration + +Add the following to your Claude Desktop configuration file: + +**macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` +**Windows**: `%APPDATA%\Claude\claude_desktop_config.json` +**Linux**: `~/.config/Claude/claude_desktop_config.json` + +#### For Stdio Transport: + +```json +{ + "mcpServers": { + "glances": { + "command": "python", + "args": ["/full/path/to/glances_mcp.py"] + } + } +} +``` + +#### For HTTP Transport: + +```json +{ + "mcpServers": { + "glances": { + "url": "http://localhost:8000/mcp" + } + } +} +``` + +## Available Tools + +The MCP server provides the following tools: + +### System Status +- **get_status**: Check Glances API health status +- **get_all_stats**: Get all system statistics from all plugins +- **get_plugins_list**: Get list of available Glances plugins + +### CPU & Memory +- **get_cpu_stats**: Get CPU usage statistics +- **get_memory_stats**: Get memory usage statistics + +### Storage & I/O +- **get_disk_stats**: Get disk I/O statistics +- **get_sensors**: Get sensor readings (temperature, fans) ### Network -- **Average traffic**: โ 25 Mbps / โ 12 Mbps -- **Inbound peak**: 180 Mbps (backup on Dec 10) -- **Packet loss**: 0% -- **Average latency**: < 1ms +- **get_network_stats**: Get network interface statistics ---- +### Processes +- **get_processes**: Get process list (optionally limit to top N processes) +- **get_process_by_pid**: Get detailed information for a specific process -## โ ๏ธ Attention Points +### System Information +- **get_system_info**: Get system information (OS, hostname, platform) +- **get_config**: Get Glances configuration -### 1. Disk space /home (78%) -- **Priority**: Medium -- **Action**: Cleanup recommended within 30 days -- **Estimate**: Saturation in ~4 months at current rate +### Docker +- **get_docker_stats**: Get Docker container statistics (if Docker is available) -### 2. Disk space /var (84%) -- **Priority**: Medium -- **Action**: Implement log rotation -- **Detail**: 28 GB of logs in /var/log +### Advanced +- **get_plugin_data**: Get data from any specific Glances plugin by name +- **get_plugin_history**: Get historical data for a plugin +- **get_plugin_limits**: Get configured limits for a plugin ---- +## Resources -## ๐ฏ Service Performance +- **glances://stats**: A formatted summary of system statistics including CPU, memory, and load averages -### Docker Applications -| Service | Uptime | Avg CPU | Avg RAM | Status | -|---------|--------|---------|---------|--------| -| webapp_prod | 99.9% | 2% | 125 MB | โ | -| postgres_db | 100% | 12% | 1.8 GB | โ | -| redis_cache | 100% | 1% | 89 MB | โ | -| worker_queue | 98.2% | 8% | 340 MB | โ | +## Prompts -**Note**: worker_queue restarted 1x (planned maintenance) +- **analyze_system_performance**: A template prompt for comprehensive system performance analysis ---- +## Testing -## ๐ Incidents & Events +### Using MCP Inspector -### Notable events -1. **Dec 8, 3:23 PM** - CPU peak 94% (duration: 8 min) - - Cause: Scheduled application build - - Impact: None +The MCP Inspector is a great tool for testing your MCP server: -2. **Dec 9, 3:15 AM** - RAM usage 94% - - Cause: Database backup - - Impact: None, resolved automatically +```bash +# For HTTP transport +npx @modelcontextprotocol/inspector http://localhost:8000/mcp -3. **Dec 10, 2:00 AM** - Network peak 180 Mbps - - Cause: Offsite backup - - Impact: None - -**Total alerts**: 3 (all resolved) - ---- - -## ๐ก Recommendations - -### Short term (this week) -1. โ Implement automatic log rotation - ```bash - sudo logrotate -f /etc/logrotate.conf - ``` - -2. โ Clean /home/user/Downloads (estimated gain: 35 GB) - -### Medium term (this month) -1. ๐ Plan thorough /home cleanup -2. ๐ Evaluate RAM upgrade need (frequently approaches 90%) - -### Long term (Q1 2026) -1. ๐พ Extend disk capacity or implement NAS -2. ๐ Migrate to server with 32 GB RAM - ---- - -## ๐ Contacts & Support -**Team**: DevOps -**Contact**: devops@company.com -**Documentation**: wiki.company.com/infra - ---- - -*Report generated automatically via Glances MCP* +# For stdio transport +npx @modelcontextprotocol/inspector python glances_mcp.py ``` -Would you like this report in PDF or sent via email? +### Using curl (HTTP transport only) + +```bash +# Test if Glances is responding +curl http://localhost:61208/api/4/status + +# Test if MCP server is running +curl http://localhost:8000/mcp ``` -*MCP tools used: `get_all_system_stats()`, 7-day historical analysis, aggregation* +## Example Usage with Claude ---- +Once configured, you can ask Claude questions like: -## ๐ฎ Scenario 7: Conversational Interactions +- "What's my current CPU usage?" +- "Show me the top 10 processes by memory usage" +- "What's the system load average?" +- "Check if my disk I/O is high" +- "Monitor network traffic" +- "Analyze my system performance and suggest optimizations" -### Example 7.1: Natural Dialogue +## Troubleshooting -**You**: -``` -My computer is heating up a lot, is that normal? -``` +### Connection Issues -**Claude**: -``` -Let me check the temperature sensors... +**Problem**: MCP server can't connect to Glances -๐ก๏ธ CURRENT TEMPERATURE: 78ยฐC +**Solution**: +1. Verify Glances is running: `curl http://localhost:61208/api/4/status` +2. Check the `GLANCES_URL` in `glances_mcp.py` +3. Ensure no firewall is blocking port 61208 -โ ๏ธ That's indeed elevated! Normal temperature is -between 40-60ยฐC at idle, and up to 70ยฐC under load. +### Empty Responses -Let's see what's causing this heat... +**Problem**: Tools return empty or error responses -๐ฅ ANALYSIS: -โข CPU: 89% usage โ Main heat source -โข Fans: 2800 RPM (85% of max speed) -โข Resource-intensive processes detected: - 1. blender (3D rendering) - 52% CPU - 2. chrome (23 tabs) - 25% CPU - 3. docker - 12% CPU +**Solution**: +1. Check Glances logs for errors +2. Verify the plugin exists: `curl http://localhost:61208/api/4/pluginslist` +3. Try accessing the specific endpoint directly via curl -๐ก EXPLANATION: -Blender is doing a 3D render, heating is normal! -The fans are spinning fast to compensate. +### HTTP Transport 404 Errors -POSSIBLE ACTIONS: -1. โ Let the render finish (fans are doing their job) -2. ๐จ Make sure vents aren't blocked -3. ๐งน Clean fans if you haven't done so recently -4. โ Avoid using Chrome in parallel (closing = -10ยฐC) +**Problem**: Getting 404 when connecting to MCP server via HTTP -Want me to monitor the temperature and alert you if it -exceeds 85ยฐC? -``` +**Solution**: +1. Make sure to connect to `/mcp` endpoint: `http://localhost:8000/mcp` +2. Verify the server is running with `ps aux | grep glances_mcp` +3. Check server logs for startup errors ---- +### Claude Desktop Not Detecting Server -**You**: -``` -Yes please monitor it -``` +**Problem**: Server doesn't appear in Claude Desktop -**Claude**: -``` -โ Temperature monitoring activated! +**Solution**: +1. Check the configuration file syntax (must be valid JSON) +2. Use full absolute paths in the configuration +3. Restart Claude Desktop after configuration changes +4. Check Claude Desktop logs for errors -Alert threshold: 85ยฐC -Current temperature: 78ยฐC +## Development -I'll notify you if: -- Temperature > 85ยฐC (critical) -- Temperature > 80ยฐC for > 10 min (attention) -- Fans reach 100% (saturation) +### Adding New Tools -๐ง Meanwhile, everything is under control. -The fans are managing heat dissipation well. -``` +To add a new tool, follow this pattern: ---- - -## ๐ค Scenario 8: Automation and Scripts - -### Example 8.1: Monitoring Script - -**You**: -``` -Create a script that checks every hour if -my disks exceed 85% and sends me an email if so -``` - -**Claude**: ```python -#!/usr/bin/env python3 -""" -Disk monitoring script with email alerts -Checks disk space every hour via Glances API -""" +@mcp.tool() +def your_new_tool(param: str) -> dict[str, Any]: + """ + Description of what your tool does -import requests -import smtplib -from email.mime.text import MIMEText -from email.mime.multipart import MIMEMultipart -import time -from datetime import datetime - -# Configuration -GLANCES_URL = "http://localhost:61208" -THRESHOLD = 85 # Threshold in % -EMAIL_FROM = "monitoring@your-server.com" -EMAIL_TO = "you@example.com" -SMTP_SERVER = "smtp.gmail.com" -SMTP_PORT = 587 -CHECK_INTERVAL = 3600 # 1 hour in seconds - -def check_disk_usage(): - """Check disk usage via Glances API""" - try: - response = requests.get(f"{GLANCES_URL}/api/4/fs") - response.raise_for_status() - disks = response.json() - - alerts = [] - for disk in disks: - usage_percent = disk.get('percent', 0) - mount_point = disk.get('mnt_point', 'Unknown') - - if usage_percent >= THRESHOLD: - alerts.append({ - 'mount_point': mount_point, - 'percent': usage_percent, - 'size': disk.get('size', 0) / (1024**3), # GB - 'used': disk.get('used', 0) / (1024**3), # GB - 'free': disk.get('free', 0) / (1024**3), # GB - }) - - return alerts - except Exception as e: - print(f"Error during check: {e}") - return None - -def send_email_alert(alerts): - """Send email alert""" - try: - msg = MIMEMultipart() - msg['From'] = EMAIL_FROM - msg['To'] = EMAIL_TO - msg['Subject'] = f"โ ๏ธ Disk Space Alert - {len(alerts)} saturated partition(s)" - - # Email body - body = f""" - -
-Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
-Threshold: {THRESHOLD}%
- -| Mount point | -Usage | -Used | -Free | -Total | -
|---|---|---|---|---|
| {alert['mount_point']} | -{alert['percent']:.1f}% | -{alert['used']:.1f} GB | -{alert['free']:.1f} GB | -{alert['size']:.1f} GB | -
This message was automatically generated by the monitoring script.
- - - """ - - msg.attach(MIMEText(body, 'html')) - - # Send email - with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server: - server.starttls() - server.login(EMAIL_FROM, "your_password") # To configure - server.send_message(msg) - - print(f"โ Alert email sent for {len(alerts)} partition(s)") - return True - except Exception as e: - print(f"โ Error sending email: {e}") - return False - -def main(): - """Main monitoring loop""" - print("๐ Starting disk monitoring...") - print(f" Threshold: {THRESHOLD}%") - print(f" Interval: {CHECK_INTERVAL}s ({CHECK_INTERVAL/3600}h)") - print(f" Email: {EMAIL_TO}") - print() - - while True: - print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Checking...") - - alerts = check_disk_usage() - - if alerts is None: - print(" โ ๏ธ Glances connection error") - elif len(alerts) > 0: - print(f" ๐จ {len(alerts)} partition(s) above threshold!") - for alert in alerts: - print(f" - {alert['mount_point']}: {alert['percent']:.1f}%") - send_email_alert(alerts) - else: - print(" โ All disks OK") - - print(f" ๐ค Next check in {CHECK_INTERVAL/3600}h...\n") - time.sleep(CHECK_INTERVAL) - -if __name__ == "__main__": - try: - main() - except KeyboardInterrupt: - print("\n\n๐ Stopping monitoring") + Args: + param: Description of the parameter + """ + return make_request(f"/api/4/{param}") ``` -๐ **INSTALLATION INSTRUCTIONS:** +### Custom Glances Plugins -1. Install dependencies: -```bash -pip install requests -``` +If you've added custom plugins to Glances, you can access them using: -2. Configure the script: ```python -EMAIL_FROM = "your-email@example.com" -EMAIL_TO = "recipient@example.com" -# Also configure SMTP credentials +get_plugin_data("your_plugin_name") ``` -3. Run the script: -```bash -# Foreground (test) -python3 disk_monitor.py +## API Reference -# Background -nohup python3 disk_monitor.py > monitor.log 2>&1 & +For detailed information about the Glances API endpoints, see the [Glances RESTful API documentation](https://github.com/nicolargo/glances/wiki/The-Glances-RESTFULL-JSON-API). -# Or with systemd (production) -sudo systemctl start disk-monitor -``` +## License -4. Systemd configuration (optional): -```bash -# Create /etc/systemd/system/disk-monitor.service -sudo nano /etc/systemd/system/disk-monitor.service -``` +This MCP server follows the same license as Glances (LGPL-3.0). -Would you also like the complete systemd configuration? -``` +## Contributing -*Conceptual MCP tools: API integration demonstration* +Contributions are welcome! Please: ---- +1. Fork the repository +2. Create a feature branch +3. Make your changes +4. Add tests if applicable +5. Submit a pull request -## ๐ Scenario 9: Learning and Explanations +## Support -### Example 9.1: Understanding Metrics +- **Glances Issues**: [Glances GitHub Issues](https://github.com/nicolargo/glances/issues) +- **MCP Protocol**: [Model Context Protocol Documentation](https://modelcontextprotocol.io/) +- **General Questions**: Open an issue in this repository -**You**: -``` -What is Load Average and why is mine at 2.5? -``` +## Changelog -**Claude**: -``` -๐ EXPLANATION - Load Average +### Latest Version +- โ Converted from httpx to requests library +- โ Added HTTP transport support via uvicorn +- โ Improved error handling for empty responses +- โ Added comprehensive documentation +- โ Fixed MCP endpoint configuration -Load Average represents the average system load over 3 periods: -โข 1 minute -โข 5 minutes -โข 15 minutes +## Acknowledgments -๐ YOUR SYSTEM CURRENTLY: -Load Average: 2.5, 2.3, 1.8 -Number of CPUs: 4 cores - -๐ก HOW TO INTERPRET IT: - -Load Average indicates the average number of processes waiting -for execution. For a 4-core system: - -โข 0.0 - 1.0 โ Underutilized system โ -โข 1.0 - 4.0 โ Normal usage โ -โข 4.0 - 8.0 โ Loaded system โ ๏ธ -โข > 8.0 โ Overloaded system โ - -๐ฏ YOUR CASE (2.5): -Load: 2.5 / CPUs: 4 = 62.5% load - -This is PERFECTLY NORMAL! Your system is using ~63% of its -capacity, with 37% margin remaining. - -๐ DETAIL: -โข Load 1m: 2.5 (current load) -โข Load 5m: 2.3 (slight increase) -โข Load 15m: 1.8 (upward trend over 15min) - -๐ TREND: -Load is gradually increasing. Currently active processes: -1. python (build) - 45% CPU -2. chrome - 28% CPU -3. docker - 12% CPU - -๐ GOLDEN RULE: -Load Average < Number of CPUs = All good! - -In your case: 2.5 < 4 โ - -Questions about other metrics? -``` - ---- +- [Glances](https://github.com/nicolargo/glances) by Nicolas Hennion +- [Model Context Protocol](https://modelcontextprotocol.io/) by Anthropic +- [FastMCP](https://github.com/jlowin/fastmcp) by Jeff Lowin \ No newline at end of file