Skip to main content
Glama

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 build

Configuration

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:

  1. Service Account Tokens (Recommended)

    GRAFANA_TOKEN=glsa_xxxxxxxxxxxxxxxxxxxx
  2. API Keys (Legacy)

    GRAFANA_TOKEN=eyJrIjoi...
  3. 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 format

Production

# Build and start production server
npm run build
npm start

MCP 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 metadata

  • get_dashboard_by_uid - Retrieve complete dashboard details

  • get_dashboard_panel_queries - Extract queries from all panels

  • update_dashboard - Create or update dashboards

  • get_dashboard_versions - View dashboard version history

  • restore_dashboard_version - Restore to a specific version

  • delete_dashboard - Remove dashboards

Datasource Tools (7 tools)

  • list_datasources - List all configured datasources

  • get_datasource_by_uid - Get datasource details by UID

  • get_datasource_by_name - Get datasource details by name

  • test_datasource_connection - Test datasource connectivity

  • get_datasources_by_type - Filter datasources by type

  • get_default_datasource - Get the default datasource

  • check_datasource_exists - Check if a datasource exists

Prometheus Tools (6 tools)

  • query_prometheus - Execute PromQL queries

  • get_prometheus_metadata - List available metrics

  • get_prometheus_labels - Get label names

  • get_prometheus_label_values - Get values for specific labels

  • get_prometheus_series - Find time series

  • build_prometheus_query - Interactive query builder

Loki Tools (6 tools)

  • query_loki - Execute LogQL queries

  • get_loki_labels - Get log stream labels

  • get_loki_label_values - Get label values

  • get_loki_series - Find log series

  • build_logql_query - LogQL query builder

  • get_loki_stats - Ingestion statistics

Alerting Tools (9 tools)

  • list_alert_rules - List all alert rules

  • get_alert_rule - Get specific alert rule details

  • create_alert_rule - Create new alert rules

  • update_alert_rule - Update existing rules

  • delete_alert_rule - Delete alert rules

  • list_contact_points - List notification contact points

  • get_contact_point - Get contact point details

  • test_contact_point - Test notification delivery

  • list_alert_rule_groups - List alert rule groups

Admin Tools (9 tools)

  • list_teams - List teams

  • get_team_by_uid - Get team details

  • list_users - List organization users

  • get_current_user - Get current user info

  • list_folders - List dashboard folders

  • get_folder_by_uid - Get folder details

  • list_api_keys - List API keys

  • list_service_accounts - List service accounts

  • get_current_organization - Get current organization info

Navigation Tools (8 tools)

  • generate_deeplink - Generate deeplink URLs for dashboards, panels, or Explore

  • generate_dashboard_url - Generate dashboard URLs with time range and variables

  • generate_panel_url - Generate panel-specific URLs

  • generate_explore_url - Generate Explore view URLs

  • generate_prometheus_explore_url - Generate Prometheus Explore URLs

  • generate_loki_explore_url - Generate Loki Explore URLs

  • get_time_range_presets - Get common time range presets

  • validate_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 sensor

  • query_sensor_metric - Query Prometheus metrics from a sensor's Grafana

  • deploy_ramp_dashboard - Deploy a standard RAMP dashboard to a sensor

  • list_baselines - List available performance baselines for comparison

  • sensor_performance_verdict - Compare current metrics against baselines (pass/marginal/fail)

  • annotate_test - Create Grafana annotations to mark test events

Examples

// 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"
  }
}
// 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 registry

  • HTTP Client (src/http-client.ts) - Grafana API communication

  • Services (src/services/) - Business logic for each Grafana area

  • Tools (src/tools/) - MCP tool definitions and handlers

  • Security (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/logs

Development

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.md

NPM 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.ts

Monitoring

Debug Mode

Enable comprehensive logging for troubleshooting:

GRAFANA_DEBUG=true npm start

Debug 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:

  1. Fork and Clone - Create your feature branch

  2. Code Standards - Follow TypeScript strict mode and ESLint rules

  3. Testing - Add tests for new functionality

  4. Security - Include security impact assessment

  5. 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 Grafana
  • Verify GRAFANA_URL is correct and accessible

  • Check network connectivity and firewall rules

Authentication Failures

HTTP 401: Authentication failed
  • Verify GRAFANA_TOKEN is valid and has required permissions

  • Check 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


Built with TypeScript, Zod, and the Model Context Protocol

-
security - not tested
F
license - not found
-
quality - not tested

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/quanticsoul4772/grafana-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server