monitoring-mcp
sandraschi/monitoring-mcp
A comprehensive FastMCP 2.14.3-powered monitoring server providing intelligent operations across Grafana, Prometheus, and Loki ecosystems with conversational AI assistance for DevOps workflows.
Instalação
npx convez-ai sandraschi/monitoring-mcp1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
README
A tradução para o português deste README ainda está na fila.
Monitoring MCP Server
📖 Installation Guide — quick start, manual setup, and troubleshooting
A comprehensive FastMCP 3.1.0-powered monitoring server providing intelligent operations across Grafana, Prometheus, and Loki ecosystems with conversational AI assistance for DevOps workflows.
Quick Start
git clone https://github.com/sandraschi/monitoring-mcp
cd monitoring-mcp
just
This opens an interactive dashboard showing all available commands. Run just bootstrap to install dependencies, then just serve or just dev to start.
Manual Setup
If you don't have just installed:
Features
FastMCP 3.1.0 Integration
- Conversational Tool Returns - AI-friendly responses with actionable insights
- Sampling Capabilities - Intelligent data sampling for large result sets
- Persistent Storage - DiskStore backend for configuration and state
- Production-Ready - Built for high-performance monitoring operations
Comprehensive Monitoring Tools
Grafana Management (grafana_management)
- Dashboard Operations: List, create, update, delete, and analyze dashboards
- Data Source Queries: Execute queries against configured data sources
- Panel Management: Add and modify dashboard panels
- Alert Configuration: Set up alerting rules for dashboard metrics
- AI-Powered Analysis: Intelligent dashboard optimization suggestions
Prometheus Monitoring (prometheus_monitoring)
- Metric Queries: Execute PromQL queries with intelligent sampling
- Range Queries: Time-series analysis with automatic optimization
- Target Health: Monitor scrape target status and connectivity
- Alert Management: List active alerts and manage alert rules
- Performance Analysis: Query optimization and bottleneck detection
Loki Logging (loki_logging)
- Log Queries: Execute LogQL queries with pattern recognition
- Real-time Tailing: Stream live logs with configurable limits
- Anomaly Detection: AI-powered log pattern analysis
- Error Correlation: Link error logs with system events
- Request Tracing: Follow request flows through log streams
Cross-System Correlation (cross_system_correlation)
- Incident Analysis: Correlate metrics, logs, and traces for root cause analysis
- Performance Correlation: Link performance metrics with system events
- Error Correlation: Connect error patterns across systems
- Health Assessment: Comprehensive system health scoring
- Predictive Insights: AI-powered trend analysis and recommendations
Status & Health Monitoring (monitoring_status)
- System Health Checks: Comprehensive health assessment across all systems
- Connectivity Testing: Verify connections to all monitoring components
- Configuration Validation: Validate system configurations and settings
- Data Flow Monitoring: Check data flow between monitoring systems
- Alert Status: Monitor alerting system health and active alerts
AI-Powered Intelligence
- Conversational Responses: Natural language summaries and actionable insights
- Intelligent Sampling: Automatic data reduction for large datasets
- Root Cause Analysis: AI-assisted incident investigation
- Optimization Recommendations: Performance and configuration suggestions
- Pattern Recognition: Automated anomaly detection and trend analysis
Enterprise Features
- Persistent Configuration: Encrypted storage with platform-aware paths
- Rate Limiting: Intelligent request throttling and error handling
- Structured Logging: JSON-formatted logs with rich context
- Error Recovery: Graceful degradation and automatic retry logic
- Security: Authentication support with API key management
Conversational Usage Examples
These examples show how users interact with the Monitoring MCP server through natural language conversations, as you would in Claude Desktop or other MCP-enabled applications.
System Health Check Conversation
User: "Check the overall health of my monitoring system"
Monitoring MCP Response:
"I found your monitoring system is mostly healthy!
System Status: Degraded (3 out of 4 components healthy)
Grafana: Healthy (12 dashboards, 3 data sources configured) Prometheus: Healthy (247 targets, 98% up) Loki: Unhealthy (Connection timeout - check if Loki service is running) Overall: 1 issue needs attention
Recommendation: Start the Loki service and run connectivity tests to verify the fix."
Incident Investigation Conversation
User: "Our API response times spiked at 3:15 PM today. Can you help me investigate what happened?"
Monitoring MCP Response:
"I'll investigate the API response time spike at 3:15 PM. Let me correlate metrics, logs, and system events.
Timeline Analysis:
- 3:15 PM: API latency jumped from 45ms to 890ms
- Metrics: Memory usage spiked to 92% on web-01 server
- Logs: Multiple "GC overhead limit exceeded" errors in web-api service
Root Cause Identified: Memory pressure triggered garbage collection storms, causing response delays.
Evidence:
- Memory usage: 92% (threshold: 80%)
- GC pause time: 450ms (normal: <50ms)
- Error logs: 47 "GC overhead" exceptions in 5-minute window
Recommendations:
- Scale up web-01 instance (currently t3.medium)
- Tune JVM GC settings (-XX:+UseG1GC -XX:MaxGCPauseMillis=100)
- Add memory monitoring alerts at 75% threshold"
Performance Analysis Conversation
User: "Why is our database query performance degraded this week?"
Monitoring MCP Response:
"I've analyzed your database performance over the past week. Here's what I found:
Performance Trend: 23% degradation in query response times
Key Metrics:
- Average query time: 450ms (up from 320ms)
- Slow queries (>1s): 15% of total (up from 8%)
- Connection pool utilization: 89% (up from 72%)
Correlated Events:
- Tuesday 2:30 PM: Database restart (maintenance window)
- Wednesday: Index rebuild completed (expected performance dip)
- Friday: Connection pool exhausted multiple times
Performance Insights:
- Connection Pool Contention: 89% utilization suggests pool size needs increasing
- Index Fragmentation: Recent rebuild shows 40% improvement potential
- Memory Pressure: Buffer cache hit ratio dropped to 87%
Action Items:
- Increase connection pool size by 25%
- Schedule regular index maintenance
- Add monitoring for connection pool utilization >80%"
Log Analysis Conversation
User: "I'm seeing authentication failures in my logs. Can you analyze the patterns?"
Monitoring MCP Response:
"I've analyzed your authentication failure patterns across the last 24 hours:
Summary: 1,247 failed login attempts detected
Top Failure Reasons:
- Invalid Credentials: 68% (851 attempts) - normal user errors
- Account Locked: 22% (275 attempts) - brute force protection
- Expired Tokens: 8% (100 attempts) - session timeouts
- IP Blocked: 2% (21 attempts) - security measures
Suspicious Patterns Detected:
- IP 192.168.1.100: 45 consecutive failures in 10 minutes
- User 'admin': Targeted by 89 different IPs
- Time Pattern: Peak failures between 2-4 AM UTC
Security Recommendations:
- Block IP 192.168.1.100 temporarily (brute force attempt)
- Implement progressive delays on failed logins
- Add geo-blocking for suspicious regions
- Enable MFA for admin accounts"
Dashboard Creation Conversation
User: "Create a dashboard showing our service health overview"
Monitoring MCP Response:
"I'll create a comprehensive service health dashboard for you!
Dashboard Created: 'Service Health Overview' UID: svc-health-2024
Panels Included:
- Service Status Grid - Real-time health of all services
- Error Rate Trends - 1h, 24h, 7d error rate graphs
- Response Time Distribution - P50, P95, P99 latency metrics
- Resource Utilization - CPU, Memory, Disk, Network usage
- Alert Summary - Active alerts by severity
- Top Error Sources - Services generating most errors
Data Sources Connected:
- Prometheus (metrics)
- Loki (logs)
- Grafana (visualization)
Auto-Refresh: 30 seconds Time Range: Last 1 hour
Access: Available at
/d/svc-health-2024/service-health-overviewThe dashboard is now live and will help you monitor service health at a glance!"
Configuration Validation Conversation
User: "Validate that my monitoring configuration is correct"
Monitoring MCP Response:
"Let me check your monitoring system configuration across all components:
Configuration Validation Results: All Valid
Grafana (http://grafana:3000):
- API connectivity confirmed
- 3 data sources configured (Prometheus, Loki, TestData)
- 12 dashboards available
- Admin permissions verified
Prometheus (http://prometheus:9090):
- Query API responding
- 247 scrape targets configured
- 98% target health (243/247 up)
- 45 alerting rules active
Loki (http://loki:3100):
- LogQL API functional
- 8 distinct log streams
- 2.3GB logs ingested (last 24h)
- Retention policy: 30 days
Cross-System Integration:
- Grafana can query Prometheus data
- Grafana can query Loki logs
- Alert routing configured
- Dashboard links functional
Recommendations:
- 4 unhealthy targets in Prometheus need investigation
- Consider increasing retention if you need longer log history
- Add more alerting rules for critical services
Your monitoring stack is properly configured and operational! "
API Usage Examples
For developers integrating directly with the MCP tools:
Grafana Dashboard Management
# List all dashboards
await grafana_management(operation="list_dashboards")
# Create a new dashboard
await grafana_management(
operation="create_dashboard",
dashboard_data={
"title": "System Overview",
"tags": ["system", "overview"],
"panels": [...]
}
)
Prometheus Metrics Analysis
# Query system CPU usage
await prometheus_monitoring(
operation="query_metrics",
query="100 - (avg by(instance) (irate(node_cpu_seconds_total{mode='idle'}[5m])) * 100)"
)
Loki Log Analysis
# Search for error patterns
await loki_logging(
operation="search_errors",
query='{job="web-api"} |= "ERROR" or "Exception"'
)
Cross-System Incident Analysis
# Correlate incident data
await cross_system_correlation(
operation="correlate_incident",
incident_description="API response times spiked"
)
Health Monitoring
# Check overall system health
await monitoring_status(operation="system_health")
Installation
Prerequisites
- uv installed (RECOMMENDED)
- Python 3.12+
Quick Start
Run immediately via uvx:
uvx monitoring-mcp
Claude Desktop Integration
Add to your claude_desktop_config.json:
"mcpServers": {
"monitoring-mcp": {
"command": "uv",
"args": ["--directory", "D:/Dev/repos/monitoring-mcp", "run", "monitoring-mcp"]
}
}
Prerequisites
- Python 3.10+
- Access to Grafana, Prometheus, and Loki instances
- FastMCP 3.1.0+ (installed automatically)
From PyPI (Recommended)
pip install monitoring-mcp
From Source
git clone https://github.com/sandraschi/monitoring-mcp.git
cd monitoring-mcp
uv pip install -e .[dev]
Configuration
Create a .env file or set environment variables:
# Monitoring endpoints
MONITORING_MCP_GRAFANA_URL=http://localhost:3000
MONITORING_MCP_PROMETHEUS_URL=http://localhost:9090
MONITORING_MCP_LOKI_URL=http://localhost:3100
# Authentication (optional)
MONITORING_MCP_GRAFANA_API_KEY=your_grafana_api_key
MONITORING_MCP_GRAFANA_USERNAME=your_username
MONITORING_MCP_GRAFANA_PASSWORD=your_password
# Performance settings
MONITORING_MCP_REQUEST_TIMEOUT=30
MONITORING_MCP_MAX_CONCURRENT_REQUESTS=10
MONITORING_MCP_MAX_RESULTS_LIMIT=1000
# Sampling configuration
MONITORING_MCP_ENABLE_SAMPLING=true
MONITORING_MCP_SAMPLING_THRESHOLD=10000
MONITORING_MCP_SAMPLING_RATE=0.1
Configuration
Environment Variables
| Variable | Description | Default |
|---|---|---|
MONITORING_MCP_GRAFANA_URL | Grafana server URL | http://localhost:3000 |
MONITORING_MCP_PROMETHEUS_URL | Prometheus server URL | http://localhost:9090 |
MONITORING_MCP_LOKI_URL | Loki server URL | http://localhost:3100 |
MONITORING_MCP_REQUEST_TIMEOUT | Request timeout (seconds) | 30 |
MONITORING_MCP_MAX_RESULTS_LIMIT | Maximum results per query | 1000 |
MONITORING_MCP_ENABLE_SAMPLING | Enable intelligent sampling | true |
Authentication
Grafana Authentication
- API Key (recommended): Set
MONITORING_MCP_GRAFANA_API_KEY - Username/Password: Set both
MONITORING_MCP_GRAFANA_USERNAMEandMONITORING_MCP_GRAFANA_PASSWORD
Prometheus & Loki
- Currently use direct HTTP access (no authentication required for local setups)
- For production deployments, configure reverse proxies with authentication
Quick Start
1. Start the Server
# Using the installed package
monitoring-mcp
# Or directly with Python
python -m monitoring_mcp
2. Configure Claude Desktop
Add to your claude_desktop_config.json:
{
"mcpServers": {
"monitoring": {
"command": "python",
"args": ["-m", "monitoring_mcp"],
"env": {
"MONITORING_MCP_GRAFANA_URL": "http://your-grafana:3000",
"MONITORING_MCP_PROMETHEUS_URL": "http://your-prometheus:9090",
"MONITORING_MCP_LOKI_URL": "http://your-loki:3100"
}
}
}
}
3. Test Connection
# Check system health
result = await monitoring_status(operation="system_health")
print(f"System status: {result['health_status']['overall_status']}")
# Query a simple metric
result = await prometheus_monitoring(
operation="query_metrics",
query="up"
)
print(f"Found {result['result_count']} metric series")
Monitoring Architecture
Monitoring MCP Server
Portmanteau Tools
Grafana Prometheus Loki
Management Monitoring Logging
Grafana Promethe Loki
Dashboards us Met- Logs
& Panels rics & Analysis
Alerts
Cross-System
Correlation Engine
Incident Analysis
Root Cause Detection
Performance Insights
Health Assessment
Tool Reference
Grafana Management (grafana_management)
| Operation | Description |
|---|---|
list_dashboards | List all dashboards with metadata |
get_dashboard | Retrieve specific dashboard |
create_dashboard | Create new dashboard |
update_dashboard | Modify existing dashboard |
delete_dashboard | Remove dashboard |
search_dashboards | Search dashboards by criteria |
list_datasources | List configured data sources |
query_datasource | Execute queries against data sources |
analyze_dashboard | AI-powered dashboard analysis |
Prometheus Monitoring (prometheus_monitoring)
| Operation | Description |
|---|---|
query_metrics | Execute instant PromQL queries |
query_range | Execute range PromQL queries |
list_targets | List scrape targets and status |
get_target_health | Check specific target health |
list_rules | List alerting and recording rules |
list_alerts | List active alerts |
analyze_metrics | AI-powered metrics analysis |
optimize_queries | Query optimization suggestions |
Loki Logging (loki_logging)
| Operation | Description |
|---|---|
query_logs | Execute instant LogQL queries |
query_range | Execute range LogQL queries |
tail_logs | Stream live logs |
analyze_logs | AI-powered log pattern analysis |
detect_anomalies | Identify unusual log patterns |
search_errors | Find error messages and exceptions |
trace_requests | Follow request traces |
get_labels | List available log labels |
Cross-System Correlation (cross_system_correlation)
| Operation | Description |
|---|---|
correlate_incident | Analyze incident across systems |
find_root_cause | AI-powered root cause analysis |
performance_correlation | Link performance with events |
error_correlation | Connect error patterns |
health_assessment | Comprehensive system health |
service_dependency_map | Map service relationships |
Status Monitoring (monitoring_status)
| Operation | Description |
|---|---|
system_health | Overall system health check |
connectivity_test | Test system connectivity |
configuration_validation | Validate configurations |
performance_metrics | Monitor system performance |
data_flow_status | Check data flow health |
alert_status | Monitor alerting systems |
Development
Setup Development Environment
# Install development dependencies
uv pip install -e .[dev]
# Run tests
pytest
# Run linting
ruff check .
# Format code
ruff format .
# Type checking
mypy src/
Testing
# Run all tests
pytest
# Run with coverage
pytest --cov=monitoring_mcp --cov-report=html
# Run specific test category
pytest tests/unit/ -v
pytest tests/integration/ -v
Docker Development
# Build development image
docker build -t monitoring-mcp:dev -f Dockerfile.dev .
# Run with hot reload
docker run -p 8000:8000 -v $(pwd):/app monitoring-mcp:dev
Documentation
Guides and Documentation
- API Reference - Complete API documentation
- Grafana Integration - Grafana-specific guides
- Prometheus Queries - PromQL practices
- Loki Queries - LogQL patterns and examples
- Correlation Analysis - Cross-system analysis techniques
- Troubleshooting - Common issues and solutions
Architecture Documentation
- System Architecture - System design and components
- Performance Guide - Optimization and scaling
- Security - Security considerations and practices
- Deployment - Production deployment guides
Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Workflow
- Fork the repository
- Create a feature branch (
git checkout -b feature/-feature) - Make your changes with comprehensive tests
- Run the full test suite:
make test-all - Update documentation as needed
- Submit a pull request
Code Standards
- FastMCP 3.1.0+: Use latest features and patterns
- Type Hints: Full type coverage required
- Async First: All operations should be async where appropriate
- Conversational: Tool responses should be AI-friendly
- Documentation: Comprehensive docstrings and examples
🛡️ Industrial Quality Stack
This project adheres to SOTA 14.1 industrial standards for high-fidelity agentic orchestration:
- Python (Core): Ruff for linting and formatting. Zero-tolerance for
printstatements in core handlers (T201). - Webapp (UI): Biome for sub-millisecond linting. Strict
noConsoleLogenforcement. - Protocol Compliance: Hardened
stdout/stderrisolation to ensure crash-resistant JSON-RPC communication. - Automation: Justfile recipes for all fleet operations (
just lint,just fix,just dev). - Security: Automated audits via
banditandsafety.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- FastMCP Team - For the excellent MCP framework
- Grafana Labs - For Grafana, Prometheus, and Loki
- OpenTelemetry Community - For observability standards
- Pydantic Team - For powerful data validation
Built with using FastMCP 3.1.0 for intelligent monitoring operations