Provides comprehensive integration with Grafana instances through 52 MCP tools across 8 categories, enabling programmatic interaction with dashboards, data sources, metrics, logs, alerting, and administrative functions including dashboard management, user/team administration, and incident response.
Enables execution of PromQL queries, exploration of metrics metadata, retrieval of labels and label values, time series discovery, and interactive query building for Prometheus data sources within Grafana.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Grafana MCP Servershow me the top 5 CPU usage metrics from the last hour"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Grafana MCP Server
A Model Context Protocol (MCP) server that provides AI-powered integration with Grafana instances. This server exposes Grafana's comprehensive functionality through standardized MCP tools, enabling programmatic interaction with dashboards, data sources, metrics, logs, alerting, and administrative functions.
Features
59 MCP Tools across 9 categories for complete Grafana integration
Dashboard Management - Search, create, update, and analyze dashboards
Prometheus Integration - Execute PromQL queries and explore metrics
Loki Integration - Search logs with LogQL and manage log streams
Alerting & Incident Response - Manage alert rules and notifications
RAMP Integration - Auto-discover sensors via SSH tunnels, query metrics, compare baselines, render performance verdicts
Administrative Tools - User, team, and organization management
Navigation & Deep Links - Generate URLs for dashboards, panels, and Explore views
Security-First Design - Automatic credential sanitization and error categorization
TypeScript Excellence - Full type safety with strict mode enabled
Installation
Prerequisites
Node.js 18+ with ES modules support
TypeScript 4.9+
Access to a Grafana instance (v8.0+)
Setup
# Clone the repository
git clone https://github.com/your-org/grafana-mcp
cd grafana-mcp
# Install dependencies
npm install
# Build the project
npm run buildConfiguration
Environment Variables
Create a .env file or set these environment variables:
# Required Configuration
GRAFANA_URL=https://your-grafana-instance.com
GRAFANA_TOKEN=your-service-account-token-or-api-key
# Optional Configuration
GRAFANA_DEBUG=false # Enable debug logging
GRAFANA_TIMEOUT=30000 # HTTP timeout in milliseconds
GRAFANA_DISABLE_TOOLS=admin,alerting # Disable specific tool categories
# TLS Configuration (Optional)
GRAFANA_TLS_CERT_FILE=/path/to/client.crt
GRAFANA_TLS_KEY_FILE=/path/to/client.key
GRAFANA_TLS_CA_FILE=/path/to/ca.crt
GRAFANA_TLS_SKIP_VERIFY=false # Skip certificate verification (insecure)Authentication
The server supports multiple authentication methods:
Service Account Tokens (Recommended)
GRAFANA_TOKEN=glsa_xxxxxxxxxxxxxxxxxxxxAPI Keys (Legacy)
GRAFANA_TOKEN=eyJrIjoi...Basic Authentication
GRAFANA_TOKEN=admin:password
Usage
Development
# Start development server with hot reload
npm run dev
# Run tests
npm test
# Lint and format code
npm run lint
npm run formatProduction
# Build and start production server
npm run build
npm startMCP Client Integration
Configure your MCP client (e.g., Claude Desktop) to use this server:
{
"mcpServers": {
"grafana": {
"command": "node",
"args": ["/path/to/grafana-mcp/build/main.js"],
"env": {
"GRAFANA_URL": "https://your-grafana.com",
"GRAFANA_TOKEN": "your-service-account-token"
}
}
}
}Available Tools
Dashboard Tools (7 tools)
search_dashboards- Find dashboards by title, tags, or metadataget_dashboard_by_uid- Retrieve complete dashboard detailsget_dashboard_panel_queries- Extract queries from all panelsupdate_dashboard- Create or update dashboardsget_dashboard_versions- View dashboard version historyrestore_dashboard_version- Restore to a specific versiondelete_dashboard- Remove dashboards
Datasource Tools (7 tools)
list_datasources- List all configured datasourcesget_datasource_by_uid- Get datasource details by UIDget_datasource_by_name- Get datasource details by nametest_datasource_connection- Test datasource connectivityget_datasources_by_type- Filter datasources by typeget_default_datasource- Get the default datasourcecheck_datasource_exists- Check if a datasource exists
Prometheus Tools (6 tools)
query_prometheus- Execute PromQL queriesget_prometheus_metadata- List available metricsget_prometheus_labels- Get label namesget_prometheus_label_values- Get values for specific labelsget_prometheus_series- Find time seriesbuild_prometheus_query- Interactive query builder
Loki Tools (6 tools)
query_loki- Execute LogQL queriesget_loki_labels- Get log stream labelsget_loki_label_values- Get label valuesget_loki_series- Find log seriesbuild_logql_query- LogQL query builderget_loki_stats- Ingestion statistics
Alerting Tools (9 tools)
list_alert_rules- List all alert rulesget_alert_rule- Get specific alert rule detailscreate_alert_rule- Create new alert rulesupdate_alert_rule- Update existing rulesdelete_alert_rule- Delete alert ruleslist_contact_points- List notification contact pointsget_contact_point- Get contact point detailstest_contact_point- Test notification deliverylist_alert_rule_groups- List alert rule groups
Admin Tools (9 tools)
list_teams- List teamsget_team_by_uid- Get team detailslist_users- List organization usersget_current_user- Get current user infolist_folders- List dashboard foldersget_folder_by_uid- Get folder detailslist_api_keys- List API keyslist_service_accounts- List service accountsget_current_organization- Get current organization info
Navigation Tools (8 tools)
generate_deeplink- Generate deeplink URLs for dashboards, panels, or Exploregenerate_dashboard_url- Generate dashboard URLs with time range and variablesgenerate_panel_url- Generate panel-specific URLsgenerate_explore_url- Generate Explore view URLsgenerate_prometheus_explore_url- Generate Prometheus Explore URLsgenerate_loki_explore_url- Generate Loki Explore URLsget_time_range_presets- Get common time range presetsvalidate_time_range- Validate time range parameters
RAMP Tools (7 tools)
discover_sensors- Auto-discover Corelight sensors via SSH tunnels (ports 8080-8099)sensor_status- Get health and version info for a sensorquery_sensor_metric- Query Prometheus metrics from a sensor's Grafanadeploy_ramp_dashboard- Deploy a standard RAMP dashboard to a sensorlist_baselines- List available performance baselines for comparisonsensor_performance_verdict- Compare current metrics against baselines (pass/marginal/fail)annotate_test- Create Grafana annotations to mark test events
Examples
Dashboard Search
// Find all dashboards tagged "monitoring" in the "Production" folder
{
"tool": "search_dashboards",
"arguments": {
"query": "error",
"tags": ["monitoring"],
"folder": "Production",
"limit": 10
}
}Prometheus Query
// Query HTTP request rate over last 5 minutes
{
"tool": "query_prometheus",
"arguments": {
"query": "rate(http_requests_total[5m])",
"datasourceUid": "prometheus-uid",
"start": "2024-01-01T00:00:00Z",
"end": "2024-01-01T01:00:00Z"
}
}Loki Log Search
// Search for error logs in nginx service
{
"tool": "query_loki",
"arguments": {
"query": "{job=\"nginx\"} |= \"error\" | rate([5m])",
"datasourceUid": "loki-uid",
"limit": 100,
"direction": "backward"
}
}Architecture
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ MCP Client │ │ MCP Protocol │ │ Grafana Instance│
│ (Claude AI) │◄──►│ Server │◄──►│ (REST API) │
└─────────────────┘ └─────────────────┘ └─────────────────┘Core Components
MCP Server (
src/main.ts) - Protocol handler and tool registryHTTP Client (
src/http-client.ts) - Grafana API communicationServices (
src/services/) - Business logic for each Grafana areaTools (
src/tools/) - MCP tool definitions and handlersSecurity (
src/security-utils.ts) - Credential sanitization and error handling
Security Features
Automatic Data Sanitization - All logs and errors sanitize sensitive data
Error Categorization - User-safe vs internal error messaging
TLS Support - Full certificate validation and client certificates
Minimal Privilege - Tools operate with least required permissions
Deployment
Docker
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY build/ ./build/
EXPOSE 3000
CMD ["node", "build/main.js"]Docker Compose
version: '3.8'
services:
grafana-mcp:
build: .
environment:
- GRAFANA_URL=https://your-grafana.com
- GRAFANA_TOKEN=${GRAFANA_TOKEN}
- GRAFANA_DEBUG=false
volumes:
- ./logs:/app/logsDevelopment
Project Structure
grafana-mcp/
├── src/
│ ├── main.ts # Entry point and MCP server setup
│ ├── config.ts # Configuration management
│ ├── http-client.ts # Grafana API client
│ ├── security-utils.ts # Security and sanitization
│ ├── error-handler.ts # Centralized error handling
│ ├── tool-registry.ts # MCP tool registration
│ ├── types.ts # TypeScript definitions
│ ├── core/ # Base classes and interfaces
│ │ ├── base-service.ts # Base service with execute/health patterns
│ │ └── interfaces.ts # Service and HTTP interfaces
│ ├── services/ # Business logic services
│ │ ├── dashboard.ts # Dashboard operations
│ │ ├── datasource.ts # Datasource management
│ │ ├── prometheus.ts # Prometheus queries
│ │ ├── loki.ts # Loki log queries
│ │ ├── alerting.ts # Alert management
│ │ ├── admin.ts # Administrative functions
│ │ ├── navigation.ts # URL and deeplink generation
│ │ └── ramp.ts # RAMP sensor discovery and metrics
│ └── tools/ # MCP tool definitions
│ ├── dashboard.ts # Dashboard tools
│ ├── datasource.ts # Datasource tools
│ ├── prometheus.ts # Prometheus tools
│ ├── loki.ts # Loki tools
│ ├── alerting.ts # Alerting tools
│ ├── admin.ts # Admin tools
│ ├── navigation.ts # Navigation tools
│ └── ramp.ts # RAMP tools
├── build/ # Compiled JavaScript output
├── package.json
├── tsconfig.json
├── eslint.config.ts
└── README.mdNPM Scripts
{
"scripts": {
"build": "tsc", // Compile TypeScript
"dev": "tsx src/main.ts", // Development server
"start": "node build/main.js", // Production server
"test": "vitest", // Run tests
"test:coverage": "vitest --coverage", // Coverage report
"lint": "eslint src/", // ESLint checking
"lint:fix": "eslint src/ --fix", // Auto-fix issues
"format": "prettier --write src/", // Format code
"type-check": "tsc --noEmit" // Type checking only
}
}Code Standards
TypeScript Strict Mode - Full type safety enforcement
ESLint Rules - Zero-error policy with comprehensive rules
Prettier Formatting - Consistent code style
Zod Validation - Runtime type checking for all inputs
Security First - Automatic credential sanitization in all outputs
Testing
# Run all tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watch
# Run specific test file
npm test -- dashboard.test.tsMonitoring
Debug Mode
Enable comprehensive logging for troubleshooting:
GRAFANA_DEBUG=true npm startDebug output includes:
HTTP request/response details (sanitized)
Tool execution traces
Error categorization details
Performance metrics
Health Checks
The server provides health information through:
Process exit codes
Error logs with categorization
Connection status monitoring
Contributing
We welcome contributions! Please see our contributing guidelines:
Fork and Clone - Create your feature branch
Code Standards - Follow TypeScript strict mode and ESLint rules
Testing - Add tests for new functionality
Security - Include security impact assessment
Documentation - Update docs for new features
Pull Request Checklist
All tests pass (
npm test)No ESLint errors (
npm run lint)Code formatted (
npm run format)TypeScript compiles (
npm run type-check)Documentation updated
Security considerations addressed
License
[License information to be added]
Support
Common Issues
Connection Errors
Error: ECONNREFUSED - Unable to connect to GrafanaVerify
GRAFANA_URLis correct and accessibleCheck network connectivity and firewall rules
Authentication Failures
HTTP 401: Authentication failedVerify
GRAFANA_TOKENis valid and has required permissionsCheck token expiration and regenerate if needed
Tool Registration Errors
Schema validation failed Ensure all custom tools use proper Zod schema validation
Check that
zodToJsonSchema()wrapper is used correctly
Getting Help
Check the troubleshooting guide
Review API documentation
Open an issue for bugs or feature requests
Built with TypeScript, Zod, and the Model Context Protocol