Doramagic Project Pack · Human Manual

mcp-grafana

Related topics: Installation, Authentication, Deployment Methods

Overview

Related topics: Installation, Authentication, Deployment Methods

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Component Overview

Continue reading this section for the full explanation and source context.

Section Query and Exploration Tools

Continue reading this section for the full explanation and source context.

Section Dashboard Management

Continue reading this section for the full explanation and source context.

Related topics: Installation, Authentication, Deployment Methods

Overview

Introduction

The Grafana MCP (Model Context Protocol) server is an open-source project that bridges Large Language Models (LLMs) with Grafana, enabling AI assistants to interact with Grafana resources through a standardized tool-based interface. This integration allows AI systems to query metrics, explore logs, manage dashboards, configure alerts, and perform administrative tasks within Grafana environments.

Source: README.md

Project Purpose and Scope

The mcp-grafana project serves as a dedicated MCP server implementation for Grafana, designed to:

  • Expose Grafana functionality as MCP tools that LLMs can discover and invoke
  • Support multi-organization scenarios through Grafana's organization model
  • Provide unified access across diverse datasources including Prometheus, Loki, InfluxDB, Graphite, and more
  • Enable interactive workflows where AI assistants can assist users in observability tasks

The server implements the MCP specification, accepting JSON-RPC requests and returning structured responses that LLMs can parse and act upon. It acts as a translation layer between natural language requests and Grafana's REST API.

Source: mcpgrafana.go

Architecture

The Grafana MCP server follows a layered architecture that separates concerns between protocol handling, business logic, and external communication.

graph TD
    subgraph "MCP Clients"
        A["Claude Desktop"]
        B["Claude Code"]
        C["Other MCP Clients"]
    end
    
    subgraph "Grafana MCP Server"
        D["MCP Protocol Handler"]
        E["Tool Registry"]
        F["Grafana API Client"]
    end
    
    subgraph "External Services"
        G["Grafana Instance"]
        H["Multiple Datasources"]
    end
    
    A --> D
    B --> D
    C --> D
    D --> E
    E --> F
    F --> G
    G --> H
    
    style D fill:#e1f5fe
    style E fill:#fff3e0
    style F fill:#e8f5e9

Component Overview

ComponentResponsibilityLocation
MCP Protocol HandlerProcess JSON-RPC requests, manage tool discoverymcpgrafana.go
Tool RegistryRegister and invoke MCP toolsmcpgrafana.go
Grafana API ClientCommunicate with Grafana REST APIInternal client packages
Configuration ManagerLoad and validate server configurationcmd/mcp-grafana/main.go

Source: cmd/mcp-grafana/main.go

Core Features

The Grafana MCP server provides a comprehensive set of tools organized into functional categories:

Query and Exploration Tools

  • Metrics queries against Prometheus, VictoriaMetrics, InfluxDB, and Graphite datasources
  • Log queries for Loki, OpenSearch, and InfluxDB
  • Trace exploration via Pyroscope profiling integration
  • Dashboard panel queries extraction and analysis

Dashboard Management

  • Retrieve and list dashboards by folder or UID
  • Create, update, and patch dashboard configurations
  • Generate deeplinks to specific dashboard panels
  • Export and import dashboard definitions

Alerting and Notifications

  • List and manage alerting rules across organizations
  • Configure notification policies and contact points
  • Set up time intervals for alert routing
  • Query alert state history and instances

Datasource Operations

  • List and manage Grafana datasources
  • Execute raw queries against configured datasources
  • Query datasource health and status

Administrative Functions

  • User and organization management
  • Plugin information retrieval
  • Generic API request tool for arbitrary HTTP requests to the Grafana API
  • Panel image rendering

Source: README.md

Supported Datasources

The server has native support for numerous Grafana datasources, each with specialized query capabilities:

DatasourceQuery LanguagesFeatures
PrometheusPromQLMetrics, series, label values
VictoriaMetricsPromQLMetrics with PromQL compatibility
LokiLogQLLog queries with filtering
InfluxDBFlux, InfluxQLTime-series metrics
GraphiteCarbonAPIMetrics with function discovery
OpenSearchLuceneLog and document queries
Google Cloud MonitoringMQLCloud metrics
PyroscopeProfilesSeries and profiling data

Source: v0.14.0 Release Notes

Authentication

The Grafana MCP server supports two primary authentication methods:

Service Account Tokens

The recommended approach for production deployments uses Grafana Service Accounts with API tokens:

mcp-grafana \
  --grafana-url=https://grafana.example.com \
  --grafana-token=<your-service-account-token>

Service accounts provide fine-grained permission control and avoid tying access to individual user accounts.

Basic Authentication

For development and testing environments, basic authentication is supported:

mcp-grafana \
  --grafana-url=https://grafana.example.com \
  --grafana-user=<username> \
  --grafana-password=<password>

Header Forwarding

In SSE and streamable-http transport modes, the server can forward selected request headers such as Cookie and Authorization. This enables SSO and ALB session cookie authentication for organizations that require delegated identity flows.

Source: v0.11.5 Release Notes

Transport Modes

The server supports multiple MCP transport protocols:

ModeDescriptionUse Case
stdioStandard input/output JSON-RPCDirect CLI integration, Claude Desktop
streamable-httpHTTP POST with streaming responsesWeb clients, scalable deployments
SSEServer-Sent Events for responsesWebhook integrations

Source: cmd/mcp-grafana/main.go

Configuration

Command-Line Flags

FlagDescriptionDefault
--grafana-urlGrafana instance URL (required)-
--grafana-tokenService account token-
--grafana-userUsername for basic auth-
--grafana-passwordPassword for basic auth-
--transportMCP transport modestdio
--session-idle-timeout-minutesIdle session timeout-
--log-levelLogging verbosityinfo

Environment Variables

Configuration can also be provided via environment variables using the GF_ prefix for Grafana-specific settings.

Source: cmd/mcp-grafana/main.go

Multi-Organization Support

Grafana MCP supports working with resources across multiple organizations. The server can be configured to target a specific organization, and supports per-request organization context through HTTP RoundTrippers. This enables scenarios where AI assistants need to query or manage resources in different organizational units.

Source: v0.12.1 Release Notes

Common Usage Patterns

Interactive Metric Exploration

graph LR
    A["User Query"] --> B["MCP Tool Call"]
    B --> C["Prometheus Query"]
    C --> D["Results"]
    D --> E["AI Analysis"]
    E --> F["Insight Summary"]
  1. User asks AI assistant to analyze system metrics
  2. AI invokes query_prometheus or datasource-specific query tool
  3. Server executes query against configured datasource
  4. Results are returned to AI for analysis
  5. AI provides insights and recommendations

Alerting Workflow

  1. AI retrieves existing alerting rules via alerting_list_rules
  2. User requests new alert configuration
  3. AI invokes alerting_manage_rules to create/update rules
  4. Server validates and creates rules in Grafana
  5. User receives confirmation and can monitor alert state

Source: v0.13.0 Release Notes

Known Limitations

Authentication

  • OAuth/SSO Support: Currently, the server does not natively support OAuth or SSO providers (Okta, Google, Azure AD). Organizations using SSO must use header forwarding in SSE mode or create service accounts. See Issue #284.

Query Results

  • Large Result Sets: Query tools may return large JSON responses that can exceed LLM output processing budgets. Pagination support varies by datasource. See Issue #761 for Loki-specific pagination requests.

Organization Context

  • Panel Images: The get_panel_image tool may not properly pass orgId in all scenarios, potentially causing panel rendering to fall back to the default organization. See Issue #883.

Development and Code Quality

The project maintains high code quality standards through automated linting:

JSONSchema Linter

Detects and prevents truncation issues with commas in jsonschema struct tags. Unescaped commas in description fields cause silent truncation.

# Run the linter
make lint-jsonschema

# Auto-fix issues
make lint-jsonschema-fix

Source: internal/linter/jsonschema/README.md

OpenAPI Linter

Ensures that OpenAPI client calls use context-aware *WithParams methods instead of convenience methods that may drop request context.

// Correct usage
client.GetDataSourcesWithParams(params)

// Avoid (may drop context)
client.GetDataSources()

Source: internal/linter/openapi/testdata/src/testpkg/usage.go

Version History Highlights

VersionKey Additions
v0.14.0Generic API request tool, OpenSearch support, plugin info tool
v0.13.1VictoriaMetrics PromQL support, recording rules visibility
v0.12.0InfluxDB (Flux/InfluxQL), Graphite support
v0.11.4Pyroscope profiling, Kubernetes-style API client
v0.11.3Panel filtering in queries, unified alert routing

Source: Release Notes

See Also

Source: https://github.com/grafana/mcp-grafana / Human Manual

Installation

Related topics: Overview, Deployment Methods, Authentication

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Authentication Requirements

Continue reading this section for the full explanation and source context.

Section Download Pre-built Binaries

Continue reading this section for the full explanation and source context.

Section Building from Source

Continue reading this section for the full explanation and source context.

Related topics: Overview, Deployment Methods, Authentication

Installation

This page covers all supported methods for installing and deploying the Grafana MCP server. The Grafana MCP server acts as a bridge between AI assistants (like Claude) and Grafana, enabling natural language interaction with Grafana resources including dashboards, datasources, and alerting systems.

Prerequisites

Before installing the Grafana MCP server, ensure you have:

RequirementDescription
Grafana InstanceA running Grafana instance (OSS, Cloud, or Enterprise)
Grafana API AccessA service account token or basic authentication credentials
Go (for source build)Go 1.21 or later (if building from source)
Docker (optional)Docker 20.10+ (if using containerized deployment)
uvx (optional)Python uv package runner (if using uvx installation)

Authentication Requirements

The Grafana MCP server currently supports two authentication methods:

  1. Service Account Tokens (recommended) - Create a service account in Grafana and generate an API token
  2. Basic Authentication - Username and password combination
Note: OAuth/SSO authentication (Okta, Google, Azure AD) is not currently supported. See Issue #284 for tracking.

Installation Methods Overview

graph TD
    A[Choose Installation Method] --> B[Binary]
    A --> C[Docker Container]
    A --> D[uvx Package Runner]
    A --> E[Helm Chart]
    
    B --> F[Configure Environment]
    C --> F
    D --> F
    E --> F
    
    F --> G[Start MCP Server]
    G --> H[Configure MCP Client]

Installing the Binary

Download and install the pre-built binary for your operating system.

Download Pre-built Binaries

Binaries are available on the GitHub Releases page. Download the archive for your platform:

# Linux (AMD64)
curl -L https://github.com/grafana/mcp-grafana/releases/latest/download/mcp-grafana-linux-amd64.tar.gz \
  | tar -xz

# Linux (ARM64)
curl -L https://github.com/grafana/mcp-grafana/releases/latest/download/mcp-grafana-linux-arm64.tar.gz \
  | tar -xz

# macOS (Intel)
curl -L https://github.com/grafana/mcp-grafana/releases/latest/download/mcp-grafana-darwin-amd64.tar.gz \
  | tar -xz

# macOS (Apple Silicon)
curl -L https://github.com/grafana/mcp-grafana/releases/latest/download/mcp-grafana-darwin-arm64.tar.gz \
  | tar -xz

Source: docs/sources/set-up/install-the-binary.md

Building from Source

If you have Go installed, you can build the binary from source:

# Clone the repository
git clone https://github.com/grafana/mcp-grafana.git
cd mcp-grafana

# Build the binary
make build

# The binary will be created at ./bin/mcp-grafana

The Makefile provides several build targets:

TargetDescription
make buildBuild the main server binary
make testRun unit tests
make lintRun linters
make lint-fixAuto-fix linting issues
make docker-buildBuild Docker image locally

Source: Makefile

Installing with Docker

Docker provides a containerized deployment option that packages all dependencies.

Using the Official Image

The official Docker image is published to Docker Hub:

docker pull mcp/grafana:latest

Source: docs/sources/set-up/install-with-docker.md

Running the Container

Basic container execution:

docker run -d \
  --name mcp-grafana \
  -p 8765:8765 \
  -e GRAFANA_URL=http://grafana:3000 \
  -e GRAFANA_TOKEN=your-service-account-token \
  mcp/grafana:latest

Container Images

Two Dockerfiles are provided:

DockerfileBase ImageUse Case
DockerfileUbuntu-basedFull featured, larger image
Dockerfile.alpineAlpine LinuxMinimal footprint, smaller image

Source: Dockerfile, Dockerfile.alpine

Environment Variables for Docker

VariableRequiredDescriptionDefault
GRAFANA_URLYesBase URL of your Grafana instance-
GRAFANA_TOKENYes*Service account API token-
GRAFANA_AUTHYes*Basic auth (user:password)-
PORTNoHTTP server port8765
LOG_LEVELNoLogging level (debug, info, warn, error)info

*Either GRAFANA_TOKEN or GRAFANA_AUTH is required.

Source: internal/config/config.go

Installing with uvx

The uvx tool (from the uv Python package manager) can run the MCP server directly without manual installation.

Prerequisites

# Install uv if not already installed
curl -LsSf https://astral.sh/uv/install.sh | sh

# Or via pip
pip install uv

Running with uvx

uvx mcp-grafana \
  --grafana-url=http://localhost:3000 \
  --grafana-token=your-service-account-token

Source: docs/sources/set-up/install-with-uvx.md

Configuration File

For complex configurations, use a TOML configuration file:

uvx mcp-grafana --config /path/to/config.toml

Deploying with Helm

For Kubernetes deployments, a Helm chart is available for production-grade installations.

Adding the Helm Repository

helm repo add grafana https://grafana.github.io/helm-charts
helm repo update

Installing the Chart

helm install mcp-grafana grafana/mcp-grafana \
  --set grafana.url=https://grafana.example.com \
  --set grafana.token=your-service-account-token

Customizing Values

Create a values.yaml file for custom configuration:

grafana:
  url: https://grafana.example.com
  token: your-service-account-token

replicaCount: 2

resources:
  limits:
    cpu: 500m
    memory: 512Mi
  requests:
    cpu: 100m
    memory: 128Mi

service:
  type: ClusterIP
  port: 8765

Source: docs/sources/set-up/deploy-with-helm.md

Configuration Options

Command-Line Flags

FlagDescriptionDefault
--grafana-urlGrafana instance URL-
--grafana-tokenService account API token-
--grafana-authBasic auth (user:password)-
--portHTTP server port8765
--log-levelLogging levelinfo
--transportMCP transport (stdio, sse, streamable-http)stdio
--configPath to TOML configuration file-

Source: cmd/server/main.go

Configuration File Format

The server supports TOML configuration files:

[grafana]
url = "http://localhost:3000"
token = "your-service-account-token"

[server]
port = 8765
transport = "stdio"
log_level = "info"

[mcp]
enabled = true

Environment Variables

All configuration can be set via environment variables using the GRAFANA_ prefix:

Environment VariableConfig Field
GRAFANA_URLgrafana.url
GRAFANA_TOKENgrafana.token
GRAFANA_AUTHgrafana.auth
PORTserver.port
LOG_LEVELserver.log_level

Source: internal/config/config.go

Verifying Installation

Health Check

Once the server is running, verify it works by checking the health endpoint:

curl http://localhost:8765/health

Expected response:

{"status": "ok"}

Testing with an MCP Client

For Claude Desktop integration, add to your configuration:

{
  "mcpServers": {
    "grafana": {
      "command": "mcp-grafana",
      "args": [
        "--grafana-url", "http://localhost:3000",
        "--grafana-token", "your-token-here"
      ]
    }
  }
}

Or using Docker:

{
  "mcpServers": {
    "grafana": {
      "command": "docker",
      "args": [
        "run", "--rm", "-i",
        "-e", "GRAFANA_URL=http://host.docker.internal:3000",
        "-e", "GRAFANA_TOKEN=your-token-here",
        "mcp/grafana:latest"
      ]
    }
  }
}

Deployment Modes

The MCP server supports multiple transport modes:

ModeProtocolUse Case
stdioStandard I/OLocal CLI integration, Claude Desktop
sseServer-Sent EventsWeb-based clients
streamable-httpHTTP StreamingProduction HTTP clients

Source: cmd/server/main.go

Selecting Transport Mode

# stdio mode (default for MCP clients)
mcp-grafana --transport stdio

# SSE mode
mcp-grafana --transport sse --port 8765

# HTTP streaming mode
mcp-grafana --transport streamable-http --port 8765

Common Installation Issues

Docker Image Version Tags

Community Issue: Docker images currently only have the latest tag. Version-specific tags are requested in Issue #180.

If you need a specific version, you can reference the commit SHA:

docker pull mcp/grafana@sha256:<commit-sha>

Authentication Failures

If you receive authentication errors:

  1. Verify the service account token is valid and not expired
  2. Ensure the service account has the necessary permissions
  3. Check that the Grafana URL is accessible from your deployment

Port Conflicts

If port 8765 is already in use, specify an alternative:

mcp-grafana --port 8766

Next Steps

After installation, configure the MCP client to connect to your Grafana instance and start exploring dashboards, querying datasources, and managing alerts.

See Also

Source: https://github.com/grafana/mcp-grafana / Human Manual

Authentication

Related topics: Overview, Installation, Configuration Reference

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Service Account Token Authentication

Continue reading this section for the full explanation and source context.

Section Basic Authentication

Continue reading this section for the full explanation and source context.

Section Transport Layers

Continue reading this section for the full explanation and source context.

Related topics: Overview, Installation, Configuration Reference

Authentication

The Grafana MCP server supports multiple authentication mechanisms for connecting to Grafana instances. This document describes the authentication architecture, supported methods, configuration options, and best practices for securing MCP server deployments.

Overview

The mcp-grafana server authenticates with Grafana using service account tokens or basic authentication credentials. The authentication layer is designed to support both direct API access and delegated authentication scenarios where the MCP server operates behind proxies or load balancers that handle identity propagation.

Authentication configuration is centralized in the GrafanaConfig structure defined in internal/config/config.go. The configuration supports specifying a URL, authentication token or credentials, and optional headers for delegated authentication scenarios.

graph TD
    A[MCP Client] -->|Request| B[Grafana MCP Server]
    B -->|Authentication| C{GrafanaConfig}
    C -->|Bearer Token| D[Grafana API]
    C -->|Basic Auth| D
    C -->|Forwarded Headers| E[SSO/Proxy]
    E -->|X-Auth-Request| D
    B -->|Session Context| F[Per-Request Config]
    F -->|Override Headers| C

Supported Authentication Methods

The server supports the following authentication methods:

MethodConfiguration FieldDescription
Service Account TokenAuthTokenBearer token from Grafana service accounts
Basic AuthenticationBasicAuthUser / BasicAuthPasswordUsername/password credentials
AnonymousNoneNo authentication (limited access)

Source: internal/config/auth.go

Service Account Token Authentication

Service accounts are the recommended authentication method for MCP server deployments. To create a service account:

  1. Navigate to Configuration → Service Accounts in Grafana
  2. Click Add service account
  3. Assign appropriate roles (Viewer, Editor, or Admin depending on required permissions)
  4. Generate a token and store it securely

Configure the token in the MCP server:

export GRAFANA_AUTH_TOKEN="glsa_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

Basic Authentication

Basic authentication is supported for development and testing scenarios:

export GRAFANA_AUTH_BASIC_USER="admin"
export GRAFANA_AUTH_BASIC_PASSWORD="your-password"

Note: Basic authentication may be disabled in Grafana instances with strict security policies. Many organizations using SSO (Okta, Google OAuth, Azure AD) have disabled basic authentication entirely.

Transport Chain Architecture

The authentication system uses a Go HTTP transport chain that allows stacking multiple authentication and header-manipulation layers. This architecture enables scenarios like on-behalf-of authentication and header forwarding through proxies.

graph LR
    subgraph "Transport Chain"
        A[Request] --> B[Headers Transport]
        B --> C[OnBehalfOf Transport]
        C --> D[Auth Transport]
        D --> E[Grafana API]
    end

Transport Layers

The transport chain is implemented in internal/transport/transport.go and consists of the following layers:

LayerPurposeSource
HeadersTransportForward selected headers from MCP request contextinternal/transport/transport.go:1-50
OnBehalfOfTransportApply on-behalf-of authentication headersinternal/transport/transport.go:50-100
AuthTransportApply base authentication (token/basic)internal/transport/transport.go:100-150

Header Forwarding

As of v0.11.5, the MCP server can forward selected request headers (such as Cookie and Authorization) to Grafana when operating in SSE and streamable-http modes. This enables SSO and ALB session cookie authentication scenarios.

Source: v0.11.5 Release Notes

Headers are forwarded based on the headers configuration option in the server configuration:

{
  "mcpServers": {
    "grafana": {
      "command": "mcp-grafana",
      "args": ["--headers", "Cookie,Authorization"],
      "env": {
        "GRAFANA_URL": "https://grafana.example.com",
        "GRAFANA_AUTH_TOKEN": "glsa_..."
      }
    }
  }
}

On-Behalf-Of Authentication

The on-behalf-of authentication feature (introduced in v0.11.6) enables delegated identity for API requests. When enabled, the MCP server can use the identity of the requesting user rather than a fixed service account identity.

Source: v0.11.6 Release Notes

This feature is particularly useful when:

  • The MCP server is deployed behind an authenticating proxy
  • User-specific permissions should be enforced
  • Audit logs should reflect the actual user actions
sequenceDiagram
    participant User
    participant Proxy as Auth Proxy
    participant MCP as MCP Server
    participant Grafana
    
    User->>Proxy: Authenticated Request
    Proxy->>MCP: Forward Request + User Identity Headers
    MCP->>Grafana: API Request with Delegated Identity
    Grafana->>Grafana: Enforce User Permissions
    Grafana-->>MCP: Response
    MCP-->>Proxy: Response
    Proxy-->>User: Response

Multi-Organization Support

The authentication system supports Grafana's multi-organization architecture through the OrgID configuration option. This allows the MCP server to authenticate and operate within a specific organization context.

Source: docs/sources/configure/multi-organization-and-headers.md

ConfigurationEnvironment VariableDescription
OrgIDGRAFANA_ORG_IDTarget organization ID for API requests

Per-Request Configuration

As of v0.12.1, the MCP server supports per-request Grafana configuration via request context. This allows HTTP RoundTrippers to modify authentication or other settings on a per-request basis.

Source: v0.12.1 Release Notes

This feature is implemented through the perRequestConfigFunc callback in the transport configuration, enabling dynamic authentication overrides without creating separate client instances.

Client Caching and Session Management

The MCP server uses a client cache to manage Grafana API clients efficiently. Each cached client maintains its own authentication configuration.

Source: client_cache.go

graph TD
    A[Request with Config] --> B{Hash Exists?}
    B -->|Yes| C[Return Cached Client]
    B -->|No| D[Create New Client]
    D --> E[Configure Auth Transport]
    E --> F[Cache Client]
    F --> C

The client cache key is computed from the complete Grafana configuration, including authentication settings. This ensures that different authentication contexts receive appropriately configured clients.

Configuration Reference

Environment Variables

VariableRequiredDescription
GRAFANA_URLYesBase URL of the Grafana instance
GRAFANA_AUTH_TOKENNo*Service account bearer token
GRAFANA_AUTH_BASIC_USERNo*Basic auth username
GRAFANA_AUTH_BASIC_PASSWORDNo*Basic auth password
GRAFANA_ORG_IDNoTarget organization ID
GRAFANA_HEADERSNoComma-separated list of headers to forward

*At least one authentication method is required.

Command-Line Flags

FlagTypeDefaultDescription
--grafana-urlstring-Grafana server URL
--grafana-tokenstring-Service account token
--grafana-headersstring-Headers to forward from requests
--session-idle-timeout-minutesint30Session idle timeout

Common Issues and Troubleshooting

Authentication Failures

Symptom: 401 Unauthorized or 403 Forbidden errors when making API calls.

Solutions:

  1. Verify the service account token is valid and not expired
  2. Check that the service account has appropriate roles for the operations being attempted
  3. Ensure the Grafana URL is correct and reachable

SSO Authentication Not Working

Symptom: SSO-authenticated sessions fail to authenticate with Grafana.

Solutions:

  1. Confirm the headers configuration includes necessary headers (Cookie, Authorization)
  2. Verify the authenticating proxy is forwarding headers correctly
  3. Check that the Grafana instance allows the forwarded authentication method

Organization Context Issues

Symptom: Accessing resources in the wrong organization or permission denied errors.

Solutions:

  1. Verify GRAFANA_ORG_ID is set correctly for the target organization
  2. Ensure the service account has permissions within the target organization
  3. Note that some operations require organization-level admin privileges

Community Considerations

OAuth/SSO Feature Request

Issue #284 tracks a community request for native OAuth/SSO authentication support. Currently, the MCP server supports SSO only through header forwarding when deployed behind an authenticating proxy. Organizations using Okta, Google OAuth, or Azure AD should ensure their deployment architecture supports this indirect authentication method.

Regular User Workflow

Issue #151 discusses the intended workflow for regular users. The current architecture requires service account tokens, which typically requires elevated privileges to create. This can be impractical for interactive use cases where individual users want to use their own Grafana credentials.

See Also

Source: https://github.com/grafana/mcp-grafana / Human Manual

Dashboard Tools

Related topics: Datasource Tools, Utility Tools

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Capabilities

Continue reading this section for the full explanation and source context.

Section Tool Descriptions

Continue reading this section for the full explanation and source context.

Section Dashboard Models

Continue reading this section for the full explanation and source context.

Related topics: Datasource Tools, Utility Tools

Dashboard Tools

The Dashboard Tools module provides a comprehensive set of MCP (Model Context Protocol) tools for interacting with Grafana dashboards, folders, navigation, and rendering capabilities. This module enables AI assistants and automated workflows to perform dashboard lifecycle operations, search for resources, navigate Grafana's information architecture, and capture panel visualizations as images.

Overview

The Dashboard Tools module is one of the core components of the mcp-grafana project, providing programmatic access to Grafana dashboard operations that would otherwise require manual interaction through the Grafana web UI. These tools allow LLM-powered agents to integrate Grafana dashboard management into AI-driven workflows for incident response, monitoring, and operational automation.

Core Capabilities

CapabilityDescriptionPrimary Source
Dashboard CRUDCreate, read, update, delete dashboardstools/dashboard.go
Panel RenderingGenerate PNG images of dashboard panelstools/rendering.go
Resource SearchSearch dashboards, folders, panels, and datasourcestools/search.go
Folder ManagementCreate and manage dashboard folderstools/folder.go
Navigation LinksGenerate short URLs and deeplinkstools/navigation.go, tools/shorturls.go

Architecture

graph TD
    A[MCP Client / LLM Agent] --> B[Dashboard Tools Module]
    B --> C[Dashboard Operations]
    B --> D[Search Operations]
    B --> E[Rendering Operations]
    B --> F[Folder Operations]
    B --> G[Navigation Operations]
    
    C --> H[Grafana REST API]
    D --> H
    E --> H
    F --> H
    G --> H
    
    H --> I[Dashboard JSON Models]
    H --> J[Folder Models]
    H --> K[Panel Models]

The Dashboard Tools module follows a layered architecture where each tool category is implemented as a separate Go file with corresponding helper modules. The tools communicate with Grafana through the official Grafana API client library, ensuring compatibility with Grafana's data models and authentication mechanisms.

Dashboard Operations

The dashboard operations provide complete lifecycle management for Grafana dashboards, including creation, retrieval, updates, patches, and deletion.

Tool Descriptions

ToolPurposeSource
get_dashboardRetrieve a dashboard by its UIDtools/dashboard.go:1
get_dashboard_by_slugRetrieve a dashboard by its URL slugtools/dashboard.go:1
save_dashboardCreate or update a dashboardtools/dashboard.go:1
delete_dashboardDelete a dashboard by UIDtools/dashboard.go:1
get_dashboard_panel_queriesExtract queries from dashboard panelstools/dashboard_helpers.go:1

Dashboard Models

The dashboard operations rely on the Grafana API client models which represent dashboards with their metadata, settings, and panel configurations. The get_dashboard_panel_queries tool specifically extracts and analyzes the query configurations from dashboard panels, supporting panel filtering and template variable substitution for more targeted query extraction (introduced in v0.11.3).

graph LR
    A[Dashboard UID/URL] --> B[get_dashboard]
    B --> C[Dashboard Response]
    C --> D[Panels Array]
    D --> E[Panel Queries]
    E --> F[Data Source IDs]

Patch Mode Behavior

When updating dashboards, the save_dashboard tool supports patch mode operations. A critical fix in v0.11.6 ensures that dashboard identity fields (id, uid, version) are preserved during patch operations to prevent accidental dashboard duplication. Source: Release v0.11.6

Common Parameters

ParameterTypeDescriptionRequired
uidstringUnique identifier for the dashboardFor get/update/delete
dashboardobjectDashboard JSON modelFor create/update
folderUidstringUID of the parent folderFor create
messagestringCommit message for dashboard changesOptional
overwritebooleanOverwrite existing dashboardOptional

Search Operations

The search functionality provides unified search across Grafana resources including dashboards, folders, panels, and datasources.

Search Tool

ToolPurposeSource
searchSearch for dashboards, folders, and panelstools/search.go:1

Search Parameters

ParameterTypeDescriptionDefault
querystringSearch query string-
typestringResource type filter (dash-folder, dash-db, panel)all
folderUidstringLimit search to specific folderroot
limitintegerMaximum results to return50
pageintegerPage number for pagination1

Search Response Structure

The search tool returns an array of search results with metadata including the resource type, title, UID, and folder information. This enables AI agents to locate specific resources and navigate to them programmatically.

Rendering Operations

The rendering tools enable programmatic capture of dashboard panels and dashboards as PNG images.

Rendering Tool

ToolPurposeSource
get_panel_imageRender a dashboard panel to PNGtools/rendering.go:1

Rendering Parameters

ParameterTypeDescriptionRequired
dashboardUidstringUID of the dashboard containing the panelYes
panelIdintegerID of the panel to renderYes
widthintegerOutput image width in pixelsOptional
heightintegerOutput image height in pixelsOptional
timeoutintegerRender timeout in secondsOptional
themestringTheme to use (dark, light, current)current

Legacy Render Mode

Version v0.12.0 introduced support for the legacy d-solo render mode for panel image rendering, ensuring backward compatibility with older Grafana installations. Source: Release v0.12.0

Known Limitations

The get_panel_image tool does not currently expose or pass an orgId parameter when rendering a panel image. This limitation affects users working with Grafana resources across multiple organizations, as panel rendering falls back to the default Grafana organization. This issue is tracked at GitHub Issue #883.

Folder Operations

Folder tools provide management capabilities for the folder-based organization system in Grafana.

Folder Tools

ToolPurposeSource
create_folderCreate a new foldertools/folder.go:1
get_folderRetrieve folder by UIDtools/folder.go:1
list_foldersList all accessible folderstools/folder.go:1
update_folderUpdate folder propertiestools/folder.go:1
delete_folderDelete a foldertools/folder.go:1

Folder Parameters

ParameterTypeDescriptionRequired
uidstringUnique identifier for the folderFor get/update/delete
titlestringDisplay title for the folderYes
parentUidstringUID of parent folder for nested organizationOptional

Navigation Operations

Navigation tools enable the generation of URLs and deeplinks for navigating to Grafana resources.

Navigation Tools

ToolPurposeSource
generate_deeplinkGenerate Explore and dashboard deeplinkstools/navigation.go:1
create_short_urlCreate a short URL via /api/short-urlstools/shorturls.go:1

The generate_deeplink tool produces URLs that navigate directly to specific Grafana resources, including Explore views with pre-populated queries. This is particularly useful for AI agents to share links to specific analysis contexts.

graph TD
    A[Query Data] --> B[generate_deeplink Tool]
    B --> C{Link Type}
    C -->|Explore| D[Explore URL]
    C -->|Dashboard| E[Dashboard URL]
    D --> F[panes/queries JSON in left= param]
    E --> G[Dashboard with time range]

Short URL Feature

The create_short_url tool provides a way to generate Grafana short URLs (/goto/<uid>) through the Grafana /api/short-urls API endpoint. This addresses the issue where generate_deeplink produces fully-qualified Explore URLs that embed the entire panes/queries JSON in the left= query parameter, which for non-trivial LogQL/PromQL queries can grow to several hundred characters of URL-encoded JSON. Short URLs provide a more compact way to share links. Source: GitHub Issue #820

ParameterTypeDescriptionRequired
datasourceUidstringUID of the datasource for Explore linksConditional
queryobjectQuery configuration including expr, queryTypeConditional
dashboardUidstringUID of dashboard for direct linksConditional
panelIdintegerPanel ID for direct panel linksOptional
timeRangeobjectTime range specificationOptional

Short URL Parameters

ParameterTypeDescriptionRequired
pathstringThe path portion of the URL to shortenYes

Common Usage Patterns

Pattern 1: Dashboard Lifecycle Workflow

graph TD
    A[Create Folder] --> B[Create Dashboard in Folder]
    B --> C[Add Panels with Queries]
    C --> D[Render Panel Image]
    D --> E[Generate Shareable Link]
    E --> F[Share with Stakeholders]

Pattern 2: Panel Investigation Workflow

graph TD
    A[Search for Dashboard] --> B[Retrieve Dashboard]
    B --> C[Extract Panel Queries]
    C --> D[Analyze Query Structure]
    D --> E[Generate Explore Deeplink]
    E --> F[Open in Explore for Analysis]

Pattern 3: Automated Reporting

graph TD
    A[Identify Target Dashboard] --> B[Retrieve Dashboard Config]
    B --> C[Iterate Through Panels]
    C --> D[Render Each Panel]
    D --> E[Compile into Report]

Error Handling

Dashboard tools return structured error responses that include error codes and messages from the Grafana API. Common error scenarios include:

Error ScenarioCauseResolution
Dashboard not foundInvalid UID or insufficient permissionsVerify UID and check org access
Folder not emptyCannot delete folder with contentsMove or delete contents first
Render timeoutPanel query takes too longIncrease timeout parameter
Write conflictDashboard modified since retrievalRe-fetch and retry update

Authentication Considerations

The Dashboard Tools module operates within the authentication context established when the MCP server is configured. All operations respect the permissions associated with the configured credentials:

  • Service Account Tokens: Primary authentication method
  • Basic Authentication: Username/password (may be disabled in some Grafana configurations)

Organizations using SSO providers like Okta, Google OAuth, or Azure AD should be aware that these authentication methods are not directly supported by the MCP server, which may require service account token generation with appropriate permissions. Source: GitHub Issue #284

See Also

Source: https://github.com/grafana/mcp-grafana / Human Manual

Datasource Tools

Related topics: Dashboard Tools, Alerting Tools

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Tool Organization

Continue reading this section for the full explanation and source context.

Section Tool Registration

Continue reading this section for the full explanation and source context.

Section Time Series Databases

Continue reading this section for the full explanation and source context.

Related topics: Dashboard Tools, Alerting Tools

Datasource Tools

Overview

The Datasource Tools are a collection of MCP (Model Context Protocol) tools that enable querying and interacting with various data sources configured in Grafana. These tools provide a standardized interface for executing queries, discovering metrics, and retrieving data across multiple time-series and log databases through the Grafana API.

Datasource Tools serve as the primary mechanism for LLM-powered applications to query observability data. They bridge the gap between natural language queries and the underlying datasource query languages (PromQL, LogQL, Flux, InfluxQL, etc.) by exposing tool definitions that MCP clients can invoke. Source: tools/prometheus.go, tools/loki.go

Architecture

Tool Organization

Datasource tools are organized by their target datasource type, with each file implementing tools specific to that datasource. The tools communicate with Grafana through the Grafana API, which proxies requests to the appropriate datasource backend.

graph TD
    subgraph "MCP Client"
        A[LLM / Claude] --> B[MCP Request]
    end
    
    subgraph "mcp-grafana Server"
        B --> C[Tool Router]
        C --> D[Prometheus Tools]
        C --> E[Loki Tools]
        C --> F[InfluxDB Tools]
        C --> G[Elasticsearch Tools]
        C --> H[CloudWatch Tools]
        C --> I[Graphite Tools]
        C --> J[Pyroscope Tools]
        C --> K[Other Datasources]
    end
    
    subgraph "Grafana API"
        L[Proxy Layer]
    end
    
    D --> L
    E --> L
    F --> L
    G --> L
    H --> L
    I --> L
    J --> L
    K --> L
    
    subgraph "Datasources"
        L --> M[Prometheus]
        L --> N[Loki]
        L --> O[InfluxDB]
        L --> P[Elasticsearch]
        L --> Q[CloudWatch]
        L --> R[Graphite]
        L --> S[Pyroscope]
        L --> T[OpenSearch]
        L --> U[Snowflake]
        L --> V[Athena]
        L --> W[ClickHouse]
    end

Tool Registration

Tools are registered with the MCP server during initialization. Each datasource module exports a createTools() function that returns a slice of mcp.Tool definitions. Source: tools/datasources.go

Supported Datasources

Time Series Databases

The following table summarizes supported time-series datasources and their associated tools:

DatasourceQuery LanguageTools AvailableSince Version
PrometheusPromQLMetric discovery, query execution, function listInitial release
InfluxDBFlux / InfluxQLQuery execution, bucket discoveryv0.12.0
Graphitegraphite-apiMetric finding, query execution, function discoveryv0.12.0
VictoriaMetricsPromQLPromQL queries against VM datasourcesv0.13.1
CloudWatchCloudWatch MetricsQuery metrics, list namespacesv0.9.0+
OpenSearchPPLQuery executionv0.14.0

Log Datasources

DatasourceQuery LanguageTools AvailableSince Version
LokiLogQLLog queries, label discovery, sample queriesInitial release
ElasticsearchES DSLLog queries, index discoveryv0.9.0+
OpenSearchPPLLog queriesv0.14.0

Profiling Datasources

DatasourceTools AvailableSince Version
PyroscopeSeries query, unified profiling queriesv0.11.4

SQL and Analytics Datasources

DatasourceTools AvailableSince Version
SnowflakeQuery executionv0.9.0+
AthenaQuery execution, table listingv0.9.0+
ClickHouseQuery executionv0.9.0+

Source: tools/influxdb.go, tools/graphite.go, tools/pyroscope.go

Prometheus Tools

The Prometheus tools provide comprehensive access to Prometheus-compatible datasources, including Prometheus itself and VictoriaMetrics.

Available Tools

#### query_prometheus_metrics

Retrieves a list of metric names matching a specified label matcher.

Parameters:

ParameterTypeRequiredDescription
datasourceUidstringYesThe UID of the Prometheus datasource
matchersstring[]YesLabel matchers to filter metrics

Example:

{
  "datasourceUid": "prometheus-1",
  "matchers": ["{job=\"prometheus\"}"]
}

Source: tools/prometheus.go

#### query_prometheus_series

Queries for series matching a label selector.

Parameters:

ParameterTypeRequiredDescription
datasourceUidstringYesThe UID of the Prometheus datasource
matchersstring[]YesLabel matchers to filter series
startnumberNoStart time (epoch seconds)
endnumberNoEnd time (epoch seconds)

#### query_prometheus_query

Executes a PromQL instant query.

Parameters:

ParameterTypeRequiredDescription
datasourceUidstringYesThe UID of the Prometheus datasource
exprstringYesPromQL expression
timenumberNoEvaluation time (epoch seconds)

#### query_prometheus_range

Executes a PromQL range query.

Parameters:

ParameterTypeRequiredDescription
datasourceUidstringYesThe UID of the Prometheus datasource
exprstringYesPromQL expression
startnumberYesStart time (epoch seconds)
endnumberYesEnd time (epoch seconds)
stepstringYesQuery resolution step (e.g., "15s", "1m")

#### get_prometheus_function_names

Returns a list of available PromQL functions.

Source: tools/prometheus.go

Loki Tools

The Loki tools provide access to log data stored in Grafana Loki or compatible backends.

Available Tools

#### query_loki_logs

Executes a LogQL query to retrieve log entries.

Parameters:

ParameterTypeRequiredDescription
datasourceUidstringYesThe UID of the Loki datasource
querystringYesLogQL query expression
limitnumberNoMaximum number of log lines to return (default: 100)
startnumberNoStart time (epoch nanoseconds)
endnumberNoEnd time (epoch nanoseconds)
directionstringNoQuery direction: "forward" or "backward"

Community Note: Large LogQL queries may return results exceeding LLM processing budgets. Pagination/chunking for query_loki_logs results is a requested feature (see Issue #761).

Source: tools/loki.go

#### query_loki_stats

Returns statistics about a LogQL query without returning actual log data.

#### get_loki_label_names

Retrieves all label names available for the specified time range.

#### get_loki_label_values

Retrieves values for a specific label.

#### query_loki_sample

Executes a LogQL sample query (for metric queries on logs).

InfluxDB Tools

InfluxDB support was added in v0.12.0 with both Flux and InfluxQL query language support.

Available Tools

#### query_influxql

Executes an InfluxQL query against an InfluxDB datasource.

Parameters:

ParameterTypeRequiredDescription
datasourceUidstringYesThe UID of the InfluxDB datasource
querystringYesInfluxQL query
databasestringNoTarget database
retentionPolicystringNoRetention policy

Source: tools/influxdb.go

#### query_flux

Executes a Flux query against an InfluxDB datasource.

Parameters:

ParameterTypeRequiredDescription
datasourceUidstringYesThe UID of the InfluxDB datasource
querystringYesFlux query

Community Note: Feature request for InfluxDB support was tracked in Issue #176 and was implemented in v0.12.0.

Graphite Tools

Graphite support was added in v0.12.0, providing metric finding, query execution, and function discovery.

Available Tools

#### get_graphite_metrics

Discovers available metrics in the Graphite datasource.

#### query_graphite_query

Executes a Graphite query.

Parameters:

ParameterTypeRequiredDescription
datasourceUidstringYesThe UID of the Graphite datasource
querystringYesGraphite query expression
targetstringNoTarget metric path

#### get_graphite_function_names

Returns available Graphite functions.

Source: tools/graphite.go

Elasticsearch Tools

The Elasticsearch tools provide access to Elasticsearch and OpenSearch datasources.

Available Tools

#### query_elasticsearch

Executes a query against Elasticsearch.

Parameters:

ParameterTypeRequiredDescription
datasourceUidstringYesThe UID of the Elasticsearch datasource
querystringYesElasticsearch JSON query
indexstringNoTarget index pattern
timeFieldstringNoField to use for time filtering

#### get_elasticsearch_indices

Lists available Elasticsearch indices.

Source: tools/elasticsearch.go

CloudWatch Tools

CloudWatch tools enable querying AWS CloudWatch metrics through Grafana.

Available Tools

#### query_cloudwatch_metrics

Executes a CloudWatch metrics query.

#### get_cloudwatch_namespaces

Lists available CloudWatch namespaces.

#### get_cloudwatch_dimension_keys

Retrieves dimension keys for a given namespace.

#### get_cloudwatch_metrics

Lists metrics in a namespace or filtered by dimension.

Community Note: The projectName parameter for Cloud Monitoring datasources to query specific GCP projects was added in v0.11.5 (PR #710).

Source: tools/cloudwatch.go

Pyroscope Tools

Pyroscope tools provide access to profiling data stored in Grafana Phlare/Pyroscope.

Available Tools

#### query_pyroscope_series

Queries series from the Pyroscope datasource.

#### query_pyroscope

Executes a unified profiling query.

Community Note: Pyroscope series query and unified query tool were added in v0.11.4 (PR #672).

Source: tools/pyroscope.go

SQL Datasource Tools

Snowflake

#### query_snowflake

Executes a SQL query against Snowflake.

Parameters:

ParameterTypeRequiredDescription
datasourceUidstringYesThe UID of the Snowflake datasource
querystringYesSQL query
databasestringNoTarget database
schemastringNoTarget schema

Source: tools/snowflake.go

Athena

#### query_athena

Executes a SQL query against Amazon Athena.

#### get_athena_tables

Lists available tables in the configured Athena workgroup.

Source: tools/athena.go

ClickHouse

#### query_clickhouse

Executes a SQL query against ClickHouse.

Parameters:

ParameterTypeRequiredDescription
datasourceUidstringYesThe UID of the ClickHouse datasource
querystringYesSQL query
databasestringNoTarget database

Source: tools/clickhouse.go

Datasource Discovery

`list_datasources`

Returns a list of all configured datasources in the Grafana instance.

Response:

{
  "datasources": [
    {
      "uid": "prometheus-1",
      "name": "Prometheus",
      "type": "prometheus",
      "url": "http://prometheus:9090"
    }
  ]
}

Source: tools/datasources.go

Common Parameters

Most datasource tools share common parameters for consistency:

ParameterTypeDescription
datasourceUidstringUnique identifier of the target datasource in Grafana
orgIdnumberTarget organization ID (for multi-org deployments)

Community Note: The get_panel_image tool does not currently expose orgId for panel rendering across organizations (see Issue #883).

Usage Patterns

Basic Query Workflow

sequenceDiagram
    participant LLM
    participant MCP as MCP Server
    participant Grafana as Grafana API
    
    LLM->>MCP: list_datasources
    MCP->>Grafana: GET /api/datasources
    Grafana-->>MCP: [datasources]
    MCP-->>LLM: [{uid, name, type}]
    
    LLM->>MCP: query_prometheus_query(datasourceUid="prom-1", expr="up")
    MCP->>Grafana: POST /api/ds/query with PromQL
    Grafana->>Prometheus: Query execution
    Prometheus-->>Grafana: Time series data
    Grafana-->>MCP: Query results
    MCP-->>LLM: Query results

Example: Prometheus Metric Discovery

{
  "tool": "query_prometheus_metrics",
  "parameters": {
    "datasourceUid": "prometheus-default",
    "matchers": ["{job=\"node\"}"]
  }
}

Example: Loki Log Query

{
  "tool": "query_loki_logs",
  "parameters": {
    "datasourceUid": "loki-logs",
    "query": "{namespace=\"production\"} |= \"error\"",
    "limit": 50
  }
}

Source: tools/examples.go

Multi-Org Support

Datasource tools support querying resources across multiple Grafana organizations. The orgId parameter can be specified to target a specific organization, or the tool will use the default organization associated with the configured API key.

Authentication Context

Per-request Grafana configuration is supported via context in HTTP RoundTrippers, enabling delegated identity for API requests. This was added in v0.12.1 (PR #805).

graph LR
    subgraph "Request Flow"
        A[Request with orgId] --> B[Transport Layer]
        B --> C[Auth Context]
        C --> D[Grafana API]
    end
    
    subgraph "Multi-Org"
        D --> E[Org 1 Datasources]
        D --> F[Org 2 Datasources]
        D --> G[Org N Datasources]
    end

Known Limitations

Result Size

Large queries, particularly LogQL queries in Loki, may return results that exceed LLM processing capabilities. This is especially relevant for broad queries that match many log lines.

Workaround: Use more specific query filters to reduce result set size.

See: Issue #761 - Feature request for pagination/chunking

SQL Datasources

SQL datasources (PostgreSQL, MySQL, MSSQL) are not currently exposed as dedicated tools. Support for SQL datasources using the Grafana sqlutil package was requested in Issue #146.

Multi-Org Panel Rendering

The get_panel_image tool does not support orgId parameter, which may cause panel rendering to fall back to the default organization.

See: Issue #883

See Also

Source: https://github.com/grafana/mcp-grafana / Human Manual

Alerting Tools

Related topics: Datasource Tools, Incident and OnCall Tools

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Component Responsibilities

Continue reading this section for the full explanation and source context.

Section Tool Capabilities

Continue reading this section for the full explanation and source context.

Section Type Handling

Continue reading this section for the full explanation and source context.

Related topics: Datasource Tools, Incident and OnCall Tools

Alerting Tools

The Alerting Tools module in mcp-grafana provides a comprehensive set of MCP (Model Context Protocol) tools for managing Grafana alerting resources programmatically. This module enables AI assistants and automated systems to interact with Grafana's alerting infrastructure, including alerting rules, notification routing, and contact points.

Overview

The alerting subsystem is architected around three primary concerns that map to the core resources in Grafana Alerting:

  1. Alerting Rules - Create, read, update, and delete alerting rules
  2. Notification Routing - Manage notification policies and routing trees
  3. Contact Points - Configure and maintain notification endpoints

These tools bridge the gap between Grafana's REST API and MCP-compatible AI assistants, allowing natural language interaction with alerting configurations. The module handles type conversions between LLM-friendly representations and Grafana's internal data structures, addressing common type mismatches such as string vs. number inconsistencies that could cause tool call failures.

Source: tools/alerting.go

Architecture

The alerting module follows a layered architecture with clear separation between MCP tool definitions, business logic handlers, data source adapters, and type definitions.

graph TD
    subgraph "MCP Layer"
        A[MCP Tools] --> B[Tool Handlers]
    end
    
    subgraph "Business Logic Layer"
        B --> C[alerting_manage_rules_handlers.go]
        B --> D[alerting_routing.go]
        B --> E[alerting_contact_points.go]
    end
    
    subgraph "Data Access Layer"
        C --> F[alerting_manage_rules_datasource.go]
        C --> G[alerting_client.go]
        D --> G
        E --> G
    end
    
    subgraph "Type Definitions"
        H[alerting_manage_rules_types.go]
    end
    
    G --> H
    F --> H
    
    G --> I[Grafana Alerting API]

Component Responsibilities

ComponentFileResponsibility
MCP Toolsalerting.goDefines MCP tool schemas and entry points
Clientalerting_client.goHTTP client for Grafana Alerting API
Rule Handlersalerting_manage_rules_handlers.goBusiness logic for rule CRUD operations
Rule Typesalerting_manage_rules_types.goType definitions and transformations
Rule Datasourcealerting_manage_rules_datasource.goData access for alerting rules
Routingalerting_routing.goNotification policy management
Contact Pointsalerting_contact_points.goContact point configuration

Source: tools/alerting_client.go

Alerting Rules Management

The alerting_manage_rules tool provides comprehensive alerting rule management capabilities. It supports both Grafana-managed and data source-native alerting rules, including recording rules.

Tool Capabilities

OperationDescription
List RulesRetrieve alerting rules with filtering by folder, datasource, group
Create RuleCreate new alerting or recording rules
Update RuleModify existing alerting rules
Delete RuleRemove alerting rules
Group OperationsManage rule groups within folders

Source: tools/alerting_manage_rules_handlers.go

Type Handling

The alerting module includes robust type handling to prevent common LLM-related failures. A key improvement in v0.13.0 addressed type mismatches where LLMs might pass string values where numeric values were expected:

graph LR
    A[LLM Input] --> B[Type Validation]
    B --> C{Valid Types?}
    C -->|Yes| D[Execute Operation]
    C -->|No| E[Type Conversion]
    E --> D
    D --> F[Grafana API]

The type definitions in alerting_manage_rules_types.go provide LLM-friendly structures that automatically handle conversion to Grafana's internal formats.

Datasource Integration

The alerting rules datasource component handles interaction with multiple data source backends. In v0.13.1, support for recording rules was enhanced to include datasource ruler listings for complete alerting rule visibility.

Source: tools/alerting_manage_rules_datasource.go

Notification Routing

The alerting_manage_routing tool (introduced in v0.11.3) provides unified management of notification policies, contact points, and time intervals in a single cohesive tool.

Routing Components

ComponentPurpose
Notification PoliciesDefine routing trees and matching conditions
Contact PointsConfigure notification endpoints (email, Slack, PagerDuty, etc.)
Time IntervalsDefine on-call schedules and notification blackout periods

Source: tools/alerting_routing.go

Routing Flow

graph TD
    A[Alert Fires] --> B[Evaluate Routes]
    B --> C{Match Group}
    C -->|Group A| D[Contact Point A]
    C -->|Group B| E[Check Time Interval]
    E --> F{Within Interval?}
    F -->|Yes| G[Contact Point B]
    F -->|No| H[No Notification]
    D --> I[Send Notification]
    G --> I

Contact Points

Contact points define where notifications are delivered when alerts fire. The contact points module supports various notification types through Grafana's plugin architecture.

Supported Contact Point Types

TypeDescription
EmailSend email notifications
SlackSlack webhook integration
PagerDutyPagerDuty incident creation
WebhookGeneric HTTP webhook calls
OpsGenieOpsGenie alert integration
TelegramTelegram bot notifications
DiscordDiscord webhook notifications
CustomPlugin-defined contact types

Source: tools/alerting_contact_points.go

Common Patterns and Usage

Creating an Alerting Rule

The typical workflow for creating an alerting rule involves:

  1. Identifying the target folder and rule group
  2. Defining the query or condition
  3. Setting evaluation intervals and no-data/firing states
  4. Configuring labels and annotations
  5. Optional: Setting up recording rule outputs

Managing Multi-Org Environments

When working with Grafana instances that have multiple organizations, the alerting tools respect the authentication context to route requests to the appropriate organization. This is particularly important for:

  • Querying rules across organizations
  • Managing contact points with org-specific configurations
  • Handling notification routing with org-scoped policies

Troubleshooting

Common Issues

IssueCauseResolution
Type MismatchesLLM passing string vs numberUse v0.13.0+ which includes automatic type conversion
Missing Recording RulesIncomplete ruler listingsv0.13.1 includes recording rules in datasource listings
Context LossMissing request context propagationEnsure using WithParams variants of API calls

Debugging Tips

  1. Verify API Permissions: Ensure the service account has appropriate alerting permissions
  2. Check Datasource Availability: Confirm datasources referenced in rules are accessible
  3. Validate Routing Configuration: Test notification routing with dry-run or test endpoints
  4. Review Label Matching: Ensure alert labels match expected routing conditions

Version History

VersionChanges
v0.13.1Include recording rules in datasource ruler listings
v0.13.0Fixed type mismatch handling (string vs number) in alerting_manage_rules
v0.11.3Added alerting_manage_routing for unified notification policy management

See Also

Source: https://github.com/grafana/mcp-grafana / Human Manual

Incident and OnCall Tools

Related topics: Alerting Tools, Utility Tools

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Available Tools

Continue reading this section for the full explanation and source context.

Section Incident Data Model

Continue reading this section for the full explanation and source context.

Section Common Usage Pattern

Continue reading this section for the full explanation and source context.

Related topics: Alerting Tools, Utility Tools

Incident and OnCall Tools

The Incident and OnCall Tools in mcp-grafana provide Model Context Protocol (MCP) tool interfaces for interacting with Grafana's incident management and on-call scheduling systems. These tools enable AI assistants and automated workflows to create, query, and manage incidents, on-call schedules, escalation policies, and team on-call status directly through the Grafana API.

Overview

The Incident and OnCall module consists of two primary components that work together to provide comprehensive incident lifecycle management:

  • Incident Tools: Handle creation, retrieval, and management of Grafana incidents
  • OnCall Tools: Manage on-call schedules, escalation policies, users, teams, and integrations

These tools are designed to integrate with Grafana OnCall (formerly Amixr), which provides robust alerting, on-call scheduling, and incident response capabilities.

Source: tools/incident.go:1-50 Source: tools/oncall.go:1-100

Architecture

graph TD
    subgraph "MCP Client Layer"
        LLM["AI Assistant / LLM"]
        MCP["MCP Protocol"]
    end
    
    subgraph "Tool Implementation Layer"
        INC["Incident Tools"]
        ONCALL["OnCall Tools"]
        SIFT["Sift Tool"]
    end
    
    subgraph "OnCall Proxy Layer"
        PROXY["oncall_proxy.go"]
        TRANSPORT["HTTP Transport"]
    end
    
    subgraph "Grafana API Layer"
        INC_API["Incident API"]
        ONCALL_API["OnCall API"]
    end
    
    LLM --> MCP
    MCP --> INC
    MCP --> ONCALL
    MCP --> SIFT
    
    ONCALL --> PROXY
    PROXY --> TRANSPORT
    TRANSPORT --> INC_API
    TRANSPORT --> ONCALL_API

The architecture follows a layered approach where the MCP protocol serves as the interface layer, tool implementations provide the business logic, and the OnCall proxy handles communication with the Grafana OnCall API.

Source: tools/oncall_proxy.go:1-80

Incident Tools

The Incident tools provide functionality for managing Grafana incidents throughout their lifecycle.

Available Tools

Tool NamePurpose
create_incidentCreate a new Grafana incident with title, description, and severity
get_incidentRetrieve details of a specific incident by ID
list_incidentsList incidents with optional filtering by status, severity, or time range
update_incidentModify incident properties such as status, severity, or assignment
add_incident_commentAdd comments or notes to an existing incident
get_incident_timelineRetrieve the chronological timeline of an incident

Incident Data Model

Source: tools/incident.go:50-150

The incident data model includes the following core fields:

FieldTypeDescription
idstringUnique identifier for the incident
titlestringBrief title describing the incident
descriptionstringDetailed description of the incident
statusstringCurrent status (active, resolved, acknowledged)
severitystringImpact level (critical, high, medium, low)
created_attimestampWhen the incident was created
updated_attimestampLast modification time
created_bystringUser who created the incident
assigneestringUser or team assigned to the incident
labelsarrayOptional labels for categorization

Common Usage Pattern

graph LR
    A[Alert Triggered] --> B[Create Incident]
    B --> C{Incident Active?}
    C -->|Yes| D[Add Comments]
    C -->|No| E[Resolve Incident]
    D --> F[Monitor Timeline]
    E --> G[Post-Mortem]
    F --> H[Update Status]
    H -->|Resolved| E

OnCall Tools

The OnCall tools provide comprehensive access to Grafana OnCall features including schedules, escalation policies, users, teams, and integrations.

Source: tools/oncall.go:100-300

Schedule Management

Tool NamePurpose
oncall_list_schedulesList all on-call schedules
oncall_get_scheduleGet details of a specific schedule
oncall_create_scheduleCreate a new on-call schedule
oncall_update_scheduleModify an existing schedule
oncall_delete_scheduleRemove a schedule
oncall_get_current_oncallGet the current on-call user for a schedule
oncall_get_schedule_shiftsRetrieve shifts for a schedule

Escalation Policy Management

Tool NamePurpose
oncall_list_escalation_policiesList all escalation policies
oncall_get_escalation_policyGet a specific escalation policy
oncall_create_escalation_policyCreate a new escalation policy
oncall_update_escalation_policyModify an escalation policy
oncall_delete_escalation_policyRemove an escalation policy

User and Team Management

Tool NamePurpose
oncall_list_usersList all users in OnCall
oncall_get_userGet details of a specific user
oncall_list_teamsList all teams
oncall_get_teamGet a specific team
oncall_get_user_oncall_statusCheck if a user is currently on-call

Integration Management

Tool NamePurpose
oncall_list_integrationsList all OnCall integrations
oncall_get_integrationGet details of an integration
oncall_create_integrationCreate a new integration
oncall_update_integrationModify an integration
oncall_delete_integrationRemove an integration

OnCall Type Definitions

Source: tools/oncall_types.go:1-100

The on-call system uses structured types for schedules, shifts, escalation policies, and users:

TypeFieldsDescription
ScheduleTypeid, name, type, team_id, timezoneDefines an on-call schedule
ShiftTypeid, schedule_id, user_id, start, end, typeA time block when a user is on-call
EscalationPolicyTypeid, name, team_id, stepsDefines escalation rules
UserTypeid, email, username, role, is_verifiedOnCall user account

OnCall Proxy Architecture

The OnCall proxy handles the HTTP communication between the MCP server and the Grafana OnCall API. It supports both direct API calls and streaming responses.

Source: tools/oncall_proxy.go:80-200

sequenceDiagram
    participant MCP as MCP Client
    participant Tool as OnCall Tool
    participant Proxy as OnCall Proxy
    participant API as Grafana OnCall API
    
    MCP->>Tool: Call oncall_* tool
    Tool->>Proxy: Execute API request
    Proxy->>API: HTTP Request
    API-->>Proxy: JSON Response
    Proxy-->>Tool: Parsed Response
    Tool-->>MCP: Tool Result

Proxy Configuration

The proxy supports per-request configuration through HTTP RoundTrippers, enabling context-aware request handling.

Source: tools/oncall_proxy.go:50-80

Sift Tool

The Sift tool provides advanced searching and filtering capabilities across Grafana resources, complementing the incident and on-call tools by enabling rapid resource discovery.

Source: tools/sift.go:1-100

Sift Capabilities

FeatureDescription
Cross-resource searchSearch across incidents, alerts, dashboards, and other resources
Fuzzy matchingFind resources using approximate string matching
Filter by typeNarrow results to specific resource types
PaginationHandle large result sets efficiently

Configuration

Required Permissions

The MCP server requires the following Grafana permissions for Incident and OnCall tools:

PermissionRequired For
apikeys:readAPI key authentication
plugins:managePlugin management
datasources:readReading datasource configurations
datasources:writeModifying datasource configurations
organizations:readMulti-org support
teams:readTeam listing
teams:writeTeam management
users:readUser listing

Environment Variables

VariableDescriptionDefault
GRAFANA_URLGrafana instance URLRequired
GRAFANA_TOKENService account token or API keyRequired
GRAFANA_ORG_IDTarget organization ID1

Multi-Organization Support

The OnCall tools support querying resources across multiple Grafana organizations. The orgId parameter can be passed with most tool calls to specify the target organization.

Common Failure Modes

Authentication Issues

ErrorCauseResolution
401 UnauthorizedInvalid or expired tokenRegenerate service account token
403 ForbiddenInsufficient permissionsVerify required permissions are granted
Missing Authorization headerToken not configuredSet GRAFANA_TOKEN environment variable

API Connectivity Issues

ErrorCauseResolution
connection refusedGrafana not reachableVerify Grafana URL and network connectivity
timeoutSlow API responseIncrease timeout settings or check Grafana health
404 Not FoundResource doesn't existVerify resource ID and organization context

Data Consistency Issues

IssueDescriptionMitigation
Stale on-call dataSchedule changes may take time to propagateUse refresh=true parameter when querying current on-call
Missing incident fieldsSome fields require specific Grafana pluginsVerify Grafana Incident plugin is installed and configured

Known Limitations

Based on community feedback and issue tracking:

  1. Panel Image and Organization Context: The get_panel_image tool does not currently support orgId for rendering panels across organizations. See Issue #883.
  1. Short URLs: The generate_deeplink tool produces fully-qualified Explore URLs with embedded JSON that can become lengthy. Consider using the Grafana short URL API (/api/short-urls) for more manageable links. See Issue #820.
  1. OAuth/SSO Authentication: Currently, the MCP server only supports Service Account Tokens and Basic authentication. OAuth/SSO support for Okta, Google, and Azure AD is not yet available. See Issue #284.

Best Practices

Incident Management Workflow

  1. Create incidents with complete information: Include severity, affected systems, and initial assessment in the incident description
  2. Use consistent labeling: Apply standard labels for easier filtering and post-mortem analysis
  3. Document timeline: Add comments at key decision points during incident response
  4. Resolve systematically: Follow your organization's incident resolution checklist

On-Call Best Practices

  1. Schedule rotation: Configure regular rotation periods to distribute on-call load
  2. Escalation paths: Define clear escalation steps with appropriate timeouts
  3. Integration validation: Test integrations regularly to ensure alert routing works correctly
  4. Override management: Use schedule overrides sparingly and communicate them clearly

See Also

Source: https://github.com/grafana/mcp-grafana / Human Manual

Utility Tools

Related topics: Dashboard Tools, Incident and OnCall Tools

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Purpose

Continue reading this section for the full explanation and source context.

Section Available Operations

Continue reading this section for the full explanation and source context.

Section Data Flow

Continue reading this section for the full explanation and source context.

Related topics: Dashboard Tools, Incident and OnCall Tools

Utility Tools

Utility Tools in mcp-grafana provide supplementary functionality that enhances the core datasource query and dashboard management capabilities. These tools handle cross-cutting concerns such as annotations management, administrative operations, plugin introspection, generic API access, contextual guidance, and Kubernetes resource integration.

Overview

The Utility Tools category encompasses non-datasource-specific operations that interact with various Grafana API endpoints. Unlike datasource tools that execute queries against specific data sources (Prometheus, Loki, InfluxDB, etc.), utility tools operate on Grafana's platform-level resources and APIs.

graph TD
    A[Utility Tools] --> B[Annotations Tools]
    A --> C[Admin Tools]
    A --> D[Plugin Tools]
    A --> E[Generic API Tool]
    A --> F[Hints Tool]
    A --> G[Kubernetes Resources]
    
    B --> H[Grafana Annotations API]
    C --> I[Grafana Admin API]
    D --> J[Grafana Plugins API]
    E --> K[Any Grafana API Endpoint]
    F --> L[Tool Usage Guidance]
    G --> M[Grafana App Platform API]

Source: tools/annotations.go, tools/admin.go, tools/plugins.go, tools/api.go, tools/hints.go, k8s_resource.go

Annotations Tools

Annotations tools enable interaction with Grafana's annotations system, which allows marking points on dashboards with contextual information derived from data queries or manual entry.

Purpose

Annotations are timestamped events that can be overlaid on Grafana dashboards. They are commonly used to mark deployments, incidents, or other significant events alongside metric data.

Source: tools/annotations.go

Available Operations

OperationDescription
annotations_createCreate a new annotation in Grafana
annotations_listList annotations with optional filtering
annotations_deleteDelete annotations by ID
annotations_updateUpdate existing annotations

Source: tools/annotations.go

Data Flow

sequenceDiagram
    participant MCP as MCP Client
    participant Grafana as Grafana API
    MCP->>Grafana: Create Annotation POST /api/annotations
    Note over MCP: Annotation with tags, text, time range
    Grafana-->>MCP: Annotation ID
    MCP->>Grafana: List Annotations GET /api/annotations
    Note over MCP: With from/to time range filters
    Grafana-->>MCP: Annotation list

Common Parameters

ParameterTypeDescription
textstringThe annotation text content
timeint64Start time in epoch milliseconds
timeEndint64End time (for range annotations)
tagsstring[]Tags for categorization and filtering
dashboardUidstringAssociated dashboard UID
panelIdint64Associated panel ID

Source: tools/annotations.go

Admin Tools

Admin tools provide access to Grafana administrative functions that are typically restricted to users with admin or editor roles.

Purpose

These tools enable operations that affect Grafana system configuration, user management, and global settings.

Source: tools/admin.go

Available Operations

OperationDescription
admin_get_settingsRetrieve Grafana server settings
admin_get_statsGet server statistics
admin_manage_usersUser management operations
admin_manage_orgsOrganization management

Source: tools/admin.go

Requirements

Admin tools require authentication with an account that has sufficient permissions. Service accounts with the Admin role or higher are typically required.

Source: tools/admin.go

Plugin Tools

Plugin tools provide introspection capabilities for Grafana plugins, enabling discovery of installed plugins and their capabilities.

Purpose

Introduced in v0.14.0, plugin tools allow MCP clients to discover what plugins are installed in Grafana and retrieve metadata about them. This is useful for determining available visualization options, data source capabilities, and app features.

Source: tools/plugins.go

Available Operations

OperationDescription
plugins_listList all installed plugins
plugins_getGet details for a specific plugin

Source: tools/plugins.go

Plugin Information Structure

graph LR
    A[Plugin Query] --> B[plugins_list]
    B --> C[Installed Plugins]
    C --> D[Core Plugins]
    C --> E[Community Plugins]
    
    F[Plugin Details] --> G[plugins_get]
    G --> H[Plugin ID]
    H --> I[Type: panel/datasource/app]
    H --> J[Info: name, version, description]
    H --> K[Dependencies]

Source: tools/plugins.go

Generic API Tool

The Generic API Tool provides flexible access to any Grafana API endpoint, enabling operations not covered by dedicated tools.

Purpose

Added in v0.14.0, this tool addresses the need for arbitrary HTTP requests to the Grafana API. Rather than requiring a new dedicated tool for every API endpoint, users can make generic API calls directly.

Source: tools/api.go

Available Operations

OperationDescription
api_requestMake arbitrary HTTP requests to Grafana API

Source: tools/api.go

Parameters

ParameterTypeRequiredDescription
methodstringYesHTTP method (GET, POST, PUT, PATCH, DELETE)
pathstringYesAPI endpoint path (e.g., /api/dashboards/uid/foo)
bodyobjectNoRequest body for POST/PUT/PATCH
headersobjectNoAdditional headers to include

Source: tools/api.go

Usage Example

{
  "method": "GET",
  "path": "/api/short-urls",
  "body": {
    "path": "/d/abc123/my-dashboard"
  }
}

Source: tools/api.go

Use Cases

The Generic API Tool enables operations such as:

  • Creating short URLs for dashboards (addressing issue #820)
  • Accessing undocumented or recently added API endpoints
  • Performing operations not yet supported by dedicated tools

Source: tools/api.go

Hints Tool

The Hints Tool provides contextual guidance about available MCP tools and their appropriate usage.

Purpose

This tool assists users in understanding what tools are available and how to use them effectively, particularly useful when integrating with LLM-powered workflows.

Source: tools/hints.go

Available Operations

OperationDescription
hints_getRetrieve usage hints for tools

Source: tools/hints.go

Kubernetes Resources

The Kubernetes-style API client enables interaction with Grafana app platform resources using Kubernetes-style semantics.

Purpose

Introduced in v0.11.4, this provides a generic Kubernetes-style API client for interacting with Grafana app platform resources. This allows MCP clients to work with custom Grafana applications using familiar Kubernetes resource patterns.

Source: k8s_resource.go

Resource Operations

OperationDescription
k8s_listList resources of a given type
k8s_getGet a specific resource
k8s_createCreate a new resource
k8s_updateUpdate an existing resource
k8s_deleteDelete a resource

Source: k8s_resource.go

Architecture

graph TD
    A[MCP Client] -->|k8s_resource calls| B[K8s Resource Handler]
    B --> C[App Platform API Client]
    C --> D[Grafana App Platform]
    
    E[Kubernetes-style Semantics] --> B
    E -->|List/Get/Create/Update/Delete| C

Source: k8s_resource.go

Tool Registration

Utility tools are registered with the MCP server through the tool registry system. Each tool defines its input schema, output schema, and handler function.

graph LR
    A[Tool Definition] --> B[Input Schema]
    A --> C[Output Schema]
    A --> D[Handler Function]
    
    B --> E[MCP Protocol]
    C --> E
    D --> E

Source: tools/annotations.go, tools/admin.go

Error Handling

Utility tools follow consistent error handling patterns:

Error TypeDescriptionResolution
NotFoundErrorResource does not existVerify resource ID/UID
PermissionErrorInsufficient permissionsCheck service account roles
ValidationErrorInvalid parametersReview parameter formats
APIErrorGrafana API errorCheck Grafana server status

Source: tools/annotations.go

Common Failure Modes

Permission Issues

Many utility tools require specific Grafana roles. Ensure your service account has the appropriate permissions:

  • Admin tools: Require Admin role
  • Annotation tools: Require Editor or Admin role
  • Plugin tools: Require Viewer role minimum

Source: tools/admin.go

Organization Context

When working across multiple organizations, some tools may not respect the orgId context. This is a known limitation tracked in issue #883.

Source: tools/plugins.go

URL Length Limitations

When using the generic API tool for operations like creating short URLs, be aware that Grafana has URL length limitations. For complex queries, consider:

  • Using short URLs instead of full Explore URLs (issue #820)
  • Breaking down large operations into smaller requests

Source: tools/api.go

See Also

Source: https://github.com/grafana/mcp-grafana / Human Manual

Deployment Methods

Related topics: Installation, Configuration Reference

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Base Images

Continue reading this section for the full explanation and source context.

Section Building the Container

Continue reading this section for the full explanation and source context.

Section Running the Container

Continue reading this section for the full explanation and source context.

Related topics: Installation, Configuration Reference

Deployment Methods

This page documents the various deployment methods available for the Grafana MCP server, covering containerized deployments, session management for horizontal scaling, transport configuration options, and TLS security settings.

Overview

The Grafana MCP server (mcp-grafana) can be deployed using multiple methods depending on your infrastructure requirements. The server supports several transport protocols and can run as a standalone binary, within Docker containers, or integrated into MCP-compatible AI tooling.

Source: docker-compose.yaml

Docker Container Deployment

Base Images

The project provides two official Docker images optimized for different use cases:

ImageBaseSizeUse Case
mcp/grafanaUbuntu-basedLargerGeneral purpose, full compatibility
mcp/grafana:alpineAlpine LinuxSmallerMemory-constrained environments

Source: Dockerfile, Dockerfile.alpine

Building the Container

To build the Docker image locally:

docker build -t mcp/grafana .

For Alpine-based image:

docker build -f Dockerfile.alpine -t mcp/grafana:alpine .

Running the Container

The container accepts configuration through environment variables. The following example demonstrates a basic run configuration:

docker run -p 8080:8080 \
  -e GRAFANA_URL=http://host.docker.internal:3000 \
  -e GRAFANA_TOKEN=your-service-account-token \
  mcp/grafana

Source: docker-compose.yaml

Transport Configuration

The MCP server supports multiple transport protocols, each suited for different deployment scenarios.

Available Transport Modes

TransportProtocolUse CaseStateful
stdioStandard I/OLocal tools, CLI integrationNo
sseServer-Sent EventsWeb-based MCP clientsYes
streamable-httpHTTP/1.1 StreamingScalable deployments, load balancersConfigurable

Source: docs/sources/configure/transports-and-addresses.md

Transport Selection

The transport mode is configured via the --transport flag or MCP_TRANSPORT environment variable:

# Standard I/O mode (default for local usage)
mcp-grafana --transport stdio

# Server-Sent Events mode
mcp-grafana --transport sse --address :8080

# Streamable HTTP mode with session support
mcp-grafana --transport streamable-http --address :8080

Address Binding

The server can bind to different addresses depending on the transport protocol:

FlagEnvironment VariableDefaultDescription
--addressMCP_ADDRESS:8080Bind address for network transports
--stdio-addressMCP_STDIO_ADDRESS(none)Path for stdio socket

Source: docs/sources/configure/transports-and-addresses.md

TLS Configuration

For production deployments using HTTP-based transports, TLS encryption is recommended.

Server TLS for Streamable HTTP

When using streamable-http transport, TLS can be enabled using PEM-encoded certificates:

mcp-grafana \
  --transport streamable-http \
  --address :8443 \
  --tls-cert-file /path/to/server.crt \
  --tls-key-file /path/to/server.key

Source: docs/sources/configure/server-tls-streamable-http.md, tls_test.go

TLS Configuration Options

OptionFlagDescription
Server Certificate--tls-cert-filePath to PEM-encoded TLS certificate
Private Key--tls-key-filePath to PEM-encoded private key
Minimum TLS Version(auto)TLS 1.2+ required

Source: docs/sources/configure/server-tls-streamable-http.md

Session Management

The MCP server includes session management capabilities essential for horizontal scaling in production environments.

Session Lifecycle

Sessions track client state across multiple requests, enabling stateful connections even in horizontally scaled deployments:

graph TD
    A[Client Connection] --> B{New Session?}
    B -->|Yes| C[Create Session]
    B -->|Existing| D[Resume Session]
    C --> E[Generate Session ID]
    D --> F[Load Session State]
    E --> G[Return Session Token]
    F --> G
    G --> H[Active Connection]
    H --> I[Session Idle Timeout]
    I -->|Expired| J[Cleanup Session]
    I -->|Active| H

Source: session.go

Session Configuration

ParameterFlagEnvironment VariableDefaultDescription
Session Timeout--session-idle-timeout-minutesMCP_SESSION_IDLE_TIMEOUT_MINUTES5Minutes before idle session cleanup

Source: session.go, docs/sources/configure/transports-and-addresses.md

Horizontal Scaling Architecture

For production deployments requiring high availability, multiple server instances can run behind a load balancer:

graph LR
    A[MCP Client] --> LB[Load Balancer]
    LB -->|Round Robin| S1[Server Instance 1]
    LB -->|Round Robin| S2[Server Instance 2]
    LB -->|Round Robin| SN[Server Instance N]
    S1 --> DB[(Shared Grafana<br/>Instance)]
    S2 --> DB
    SN --> DB

When sessions are enabled, each instance maintains session state that clients must reference on subsequent requests. This allows the load balancer to route requests from the same session to different instances while maintaining continuity.

Source: session_horizontal_scaling_test.go

Authentication Configuration

The Grafana MCP server supports multiple authentication mechanisms to connect to Grafana instances.

For production deployments, service account tokens provide secure, scoped access:

mcp-grafana \
  --grafana-url https://grafana.example.com \
  --grafana-token glsa_yourtoken_xxxxxxxxxxxxxxxxxx

Basic Authentication

For development or testing environments:

mcp-grafana \
  --grafana-url https://grafana.example.com \
  --grafana-user admin \
  --grafana-password yourpassword

Starting with v0.11.5, the server supports forwarding authentication headers in SSE and streamable-http modes. This enables:

  • SSO provider authentication (Okta, Google OAuth, Azure AD)
  • ALB session cookie authentication
  • Custom authentication proxies

Source: docs/sources/configure/transports-and-addresses.md

Per-Request Authentication

The server supports per-request Grafana configuration via request context, enabling delegated identity for API requests:

# Enable on-behalf-of authentication headers
mcp-grafana --transport streamable-http

Source: session.go

Configuration Methods

Configuration can be provided through multiple mechanisms, evaluated in priority order:

MethodPriorityExample
CLI flagsHighest--grafana-url https://...
Environment variablesMediumGRAFANA_URL=https://...
Config fileLowestgrafana.url: https://...

Common Environment Variables

VariableDescriptionExample
GRAFANA_URLGrafana instance URLhttps://grafana.example.com:3000
GRAFANA_TOKENService account tokenglsa_xxxxx
GRAFANA_USERBasic auth usernameadmin
GRAFANA_PASSWORDBasic auth passwordsecret
MCP_TRANSPORTTransport modestreamable-http
MCP_ADDRESSServer bind address:8080

Docker Compose Example

For local development and testing, a Docker Compose configuration is provided:

version: '3.8'
services:
  mcp-grafana:
    build: .
    ports:
      - "8080:8080"
    environment:
      GRAFANA_URL: http://host.docker.internal:3000
      GRAFANA_TOKEN: ${GRAFANA_TOKEN}
      MCP_TRANSPORT: streamable-http
      MCP_ADDRESS: :8080
    extra_hosts:
      - "host.docker.internal:host-gateway"

Source: docker-compose.yaml

Deployment Best Practices

Production Checklist

  1. Use Service Account Tokens: Avoid basic authentication in production; create dedicated service accounts with minimal required permissions.
  2. Enable TLS: Always use TLS encryption for HTTP-based transports to protect credentials in transit.
  3. Configure Session Timeouts: Set appropriate session idle timeouts based on your use case to manage resource usage.
  4. Use Load Balancers: For horizontal scaling, configure health checks and sticky sessions at the load balancer level.
  5. Monitor Resource Usage: Container memory limits should account for Grafana API query result sizes.

Security Considerations

  • Rotate service account tokens regularly
  • Use network segmentation to isolate the MCP server from untrusted networks
  • Configure firewall rules to restrict access to the server port
  • Consider enabling request header forwarding only when SSO integration is required

See Also

Source: https://github.com/grafana/mcp-grafana / Human Manual

Configuration Reference

Related topics: Authentication, Deployment Methods

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Supported Authentication Methods

Continue reading this section for the full explanation and source context.

Section Service Account Token

Continue reading this section for the full explanation and source context.

Section Basic Authentication

Continue reading this section for the full explanation and source context.

Related topics: Authentication, Deployment Methods

Configuration Reference

This page provides comprehensive documentation for configuring the Grafana MCP server. The server supports multiple configuration mechanisms including command-line flags, environment variables, configuration files, and runtime tool management.

Overview

The Grafana MCP server (mcp-grafana) acts as a bridge between AI assistants and Grafana's API, providing tools for querying datasources, managing dashboards, configuring alerts, and more. Configuration controls authentication, tool availability, logging, and server behavior.

graph TD
    A[Grafana MCP Server] --> B[Configuration Sources]
    B --> C[Command Line Flags]
    B --> D[Environment Variables]
    B --> E[Config File]
    A --> F[Tool Registry]
    A --> G[Grafana API Client]
    G --> H[Grafana Instance]

Source: cmd/mcp-grafana/main.go

Authentication Configuration

The MCP server supports multiple authentication methods to connect to Grafana instances.

Supported Authentication Methods

MethodDescriptionConfiguration Key
Service Account TokenRecommended for production useGRAFANA_TOKEN or --grafana-token
Basic AuthUsername/password combinationGRAFANA_USER / GRAFANA_PASSWORD
SSO HeadersCookie/Authorization forwarding--forward-headers flag

Source: cmd/mcp-grafana/main.go

Service Account Token

The recommended authentication method uses Grafana service accounts with API tokens:

mcp-grafana serve \
  --grafana-url=https://grafana.example.com \
  --grafana-token=glsa_xxxxxxxxxxxxxxxxxxxxxxx

Basic Authentication

For development or environments without service accounts:

mcp-grafana serve \
  --grafana-url=https://grafana.example.com \
  --grafana-user=admin \
  --grafana-password=yourpassword

SSO Header Forwarding

In SSE and streamable-http modes, the server can forward authentication headers from the client request to Grafana. This enables SSO and ALB session cookie authentication:

mcp-grafana serve \
  --transport=streamable-http \
  --forward-headers=Cookie,Authorization \
  --forward-headers=X-Custom-Auth

This feature was added in v0.11.5 to address community requests for SSO support (see Issue #284).

Source: docs/sources/configure/proxied-tools.md

Server Configuration

Transport Modes

The server supports multiple transport modes for MCP communication:

ModeDescriptionUse Case
stdioStandard input/output (default)Local MCP clients
sseServer-Sent EventsWeb-based clients
streamable-httpStreaming HTTPProduction deployments
mcp-grafana serve --transport=streamable-http --port=8080

Source: docs/sources/configure/command-line-flags.md

Session Management

# Set idle session timeout in minutes
mcp-grafana serve --session-idle-timeout-minutes=30

This configuration controls how long inactive sessions are maintained before cleanup. Added in v0.11.4.

Source: docs/sources/configure/command-line-flags.md

Tool Configuration

Enabling and Disabling Tools

Individual tools can be enabled or disabled using YAML configuration files or CLI flags. The tool registry maintains the complete list of available MCP tools.

# tools.yaml
tools:
  # Dashboard tools
  search_dashboards: true
  get_dashboard: true
  get_dashboard_panel_queries: true
  
  # Alerting tools
  alerting_list_rules: true
  alerting_manage_rules: true
  alerting_manage_routing: false
  
  # Datasource tools
  query_prometheus: true
  query_loki_logs: true
  query_influx: true

Apply tool configuration using the --tools-config flag:

mcp-grafana serve --tools-config=/path/to/tools.yaml

Source: tools/config.go

Tool Categories

CategoryDescriptionExample Tools
DashboardDashboard CRUD operationsget_dashboard, update_dashboard
AlertingAlert rule managementalerting_list_rules, alerting_manage_rules
DatasourcesQuery executionquery_prometheus, query_loki_logs, query_influx
ExploreLog and trace explorationquery_loki_logs, query_traces
RenderingPanel image captureget_panel_image
AdminServer administrationadmin_list_users, get_org

Source: tools/config.go

Proxied Tools

Some tools require direct API access through a proxy configuration. Proxied tools forward requests directly to Grafana APIs without MCP server processing.

# proxied-tools.yaml
proxied:
  enabled: true
  url: https://grafana.example.com
  headers:
    Authorization: Bearer ${GRAFANA_TOKEN}

Source: docs/sources/configure/proxied-tools.md

Observability Configuration

Logging

The MCP server supports structured logging with configurable output:

# Enable JSON formatted logs
mcp-grafana serve --log-format=json

# Set log level (debug, info, warn, error)
mcp-grafana serve --log-level=debug

For programmatic configuration, use the Logger field in GrafanaConfig:

import "github.com/grafana/mcp-grafana/observability"

cfg := &GrafanaConfig{
    Logger: observability.NewLogger(slog.Default()),
}

Added in v0.12.1 with optional structured logging support.

Source: observability/observability.go

Health Check Endpoint

The server exposes a health check endpoint for load balancer and orchestration integration:

# Configure health check port (default: 8081)
mcp-grafana serve --health-port=8081

Health check responses:

EndpointDescription
/healthReturns 200 if server is running
/readyReturns 200 if server is ready to serve requests

Source: docs/sources/configure/health-check-endpoint.md

Multi-Organization Support

The MCP server supports working with Grafana resources across multiple organizations through the orgId parameter in various tools. When querying panels or accessing resources in non-default organizations, specify the target organization:

mcp-grafana serve --default-org-id=1

Some tools like get_panel_image support per-request orgId specification. Note: There is an open enhancement request (Issue #883) to better support orgId in all panel-related operations.

Source: cmd/mcp-grafana/main.go

Environment Variables

All configuration options can be set via environment variables using the pattern MCP_ prefix and uppercase with underscores:

Environment VariableCLI Flag EquivalentDescription
MCP_GRAFANA_URL--grafana-urlGrafana instance URL
MCP_GRAFANA_TOKEN--grafana-tokenService account token
MCP_GRAFANA_USER--grafana-userBasic auth username
MCP_GRAFANA_PASSWORD--grafana-passwordBasic auth password
MCP_TRANSPORT--transportTransport mode
MCP_PORT--portServer port
MCP_LOG_LEVEL--log-levelLogging level
MCP_LOG_FORMAT--log-formatLog output format
MCP_TOOLS_CONFIG--tools-configPath to tools YAML
MCP_HEALTH_PORT--health-portHealth check port

Source: docs/sources/configure/command-line-flags.md

Configuration Precedence

Configuration values are applied in the following order (later sources override earlier ones):

  1. Default values (hardcoded)
  2. Configuration file (--config flag)
  3. Environment variables
  4. Command-line flags
graph LR
    A[Defaults] --> B[Config File]
    B --> C[Environment Vars]
    C --> D[CLI Flags]
    D --> E[Effective Config]

Source: cmd/mcp-grafana/main.go

Complete Configuration Example

A production-ready configuration might look like:

mcp-grafana serve \
  --grafana-url=https://grafana.example.com \
  --grafana-token=glsa_xxxxxxxxxxxxxxxxxxxxxxx \
  --transport=streamable-http \
  --port=8080 \
  --health-port=8081 \
  --session-idle-timeout-minutes=30 \
  --log-format=json \
  --log-level=info \
  --tools-config=/etc/mcp-grafana/tools.yaml \
  --forward-headers=Cookie,Authorization

With corresponding tools.yaml:

tools:
  # Enable core tools
  search_dashboards: true
  get_dashboard: true
  query_prometheus: true
  query_loki_logs: true
  alerting_list_rules: true
  get_panel_image: true
  
  # Disable tools not needed in production
  admin_list_users: false
  admin_create_user: false

Source: tools/config.go

Troubleshooting

Common Configuration Issues

IssueCauseSolution
Authentication failuresInvalid or expired tokenVerify token in Grafana settings
Connection refusedWrong port or URLCheck --grafana-url and firewall rules
Tools not appearingDisabled in tools configVerify YAML file and --tools-config path
SSO not workingHeaders not forwardedEnsure --forward-headers includes required headers

Debug Mode

Enable debug logging for troubleshooting:

mcp-grafana serve --log-level=debug --log-format=json

The JSON format makes it easier to parse and filter logs in production systems.

Source: observability/observability.go

See Also

Source: https://github.com/grafana/mcp-grafana / Human Manual

Doramagic Pitfall Log

Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.

high Security or permission risk requires verification

May increase setup, validation, or first-run risk for the user.

high Security or permission risk requires verification

May increase setup, validation, or first-run risk for the user.

high Security or permission risk requires verification

May increase setup, validation, or first-run risk for the user.

high Security or permission risk requires verification

May increase setup, validation, or first-run risk for the user.

Doramagic Pitfall Log

Found 11 structured pitfall item(s), including 5 high/blocking item(s). Top priority: Security or permission risk - Security or permission risk requires verification.

1. Security or permission risk: Security or permission risk requires verification

  • Severity: high
  • Finding: Project evidence flags a security or permission risk. Review the linked source before relying on this workflow.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: community_evidence:github | cevd_9cf63ed3a3854737bbca0bbe18c11907 | https://github.com/grafana/mcp-grafana/issues/820

2. Security or permission risk: Security or permission risk requires verification

  • Severity: high
  • Finding: Project evidence flags a security or permission risk. Review the linked source before relying on this workflow.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: community_evidence:github | cevd_ec3078db55a742068339d4ce3b6cc13f | https://github.com/grafana/mcp-grafana/issues/284

3. Security or permission risk: Security or permission risk requires verification

  • Severity: high
  • Finding: Project evidence flags a security or permission risk. Review the linked source before relying on this workflow.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: community_evidence:github | cevd_cb6f3653732644d387da810f289708c4 | https://github.com/grafana/mcp-grafana/issues/761

4. Security or permission risk: Security or permission risk requires verification

  • Severity: high
  • Finding: Project evidence flags a security or permission risk. Review the linked source before relying on this workflow.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: community_evidence:github | cevd_91b6f0b129764ca0b5d8cec3ee1497a7 | https://github.com/grafana/mcp-grafana/issues/680

5. Security or permission risk: Security or permission risk requires verification

  • Severity: high
  • Finding: Project evidence flags a security or permission risk. Review the linked source before relying on this workflow.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: community_evidence:github | cevd_a05127eb498a4339b382b65279eef3de | https://github.com/grafana/mcp-grafana/issues/883

6. Capability evidence risk: Capability evidence risk requires verification

  • Severity: medium
  • Finding: README/documentation is current enough for a first validation pass.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: capability.assumptions | github_repo:907869862 | https://github.com/grafana/mcp-grafana

7. Maintenance risk: Maintenance risk requires verification

  • Severity: medium
  • Finding: Project evidence flags a maintenance risk. Review the linked source before relying on this workflow.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: evidence.maintainer_signals | github_repo:907869862 | https://github.com/grafana/mcp-grafana

8. Security or permission risk: Security or permission risk requires verification

  • Severity: medium
  • Finding: no_demo
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: downstream_validation.risk_items | github_repo:907869862 | https://github.com/grafana/mcp-grafana

9. Security or permission risk: Security or permission risk requires verification

  • Severity: medium
  • Finding: no_demo
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: risks.scoring_risks | github_repo:907869862 | https://github.com/grafana/mcp-grafana

10. Maintenance risk: Maintenance risk requires verification

  • Severity: low
  • Finding: issue_or_pr_quality=unknown。
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: evidence.maintainer_signals | github_repo:907869862 | https://github.com/grafana/mcp-grafana

11. Maintenance risk: Maintenance risk requires verification

  • Severity: low
  • Finding: release_recency=unknown。
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: evidence.maintainer_signals | github_repo:907869862 | https://github.com/grafana/mcp-grafana

Source: Doramagic discovery, validation, and Project Pack records

Community Discussion Evidence

These external discussion links are review inputs, not standalone proof that the project is production-ready.

Sources 12

Count of project-level external discussion links exposed on this manual page.

Use Review before install

Open the linked issues or discussions before treating the pack as ready for your environment.

Community Discussion Evidence

Doramagic exposes project-level community discussion separately from official documentation. Review these links before using mcp-grafana with real data or production workflows.

Source: Project Pack community evidence and pitfall evidence