Doramagic Project Pack · Human Manual
mcp-grafana
Related topics: Installation, Authentication, Deployment Methods
Overview
Related topics: Installation, Authentication, Deployment Methods
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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:#e8f5e9Component Overview
| Component | Responsibility | Location |
|---|---|---|
| MCP Protocol Handler | Process JSON-RPC requests, manage tool discovery | mcpgrafana.go |
| Tool Registry | Register and invoke MCP tools | mcpgrafana.go |
| Grafana API Client | Communicate with Grafana REST API | Internal client packages |
| Configuration Manager | Load and validate server configuration | cmd/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:
| Datasource | Query Languages | Features |
|---|---|---|
| Prometheus | PromQL | Metrics, series, label values |
| VictoriaMetrics | PromQL | Metrics with PromQL compatibility |
| Loki | LogQL | Log queries with filtering |
| InfluxDB | Flux, InfluxQL | Time-series metrics |
| Graphite | CarbonAPI | Metrics with function discovery |
| OpenSearch | Lucene | Log and document queries |
| Google Cloud Monitoring | MQL | Cloud metrics |
| Pyroscope | Profiles | Series 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:
| Mode | Description | Use Case |
|---|---|---|
stdio | Standard input/output JSON-RPC | Direct CLI integration, Claude Desktop |
streamable-http | HTTP POST with streaming responses | Web clients, scalable deployments |
SSE | Server-Sent Events for responses | Webhook integrations |
Source: cmd/mcp-grafana/main.go
Configuration
Command-Line Flags
| Flag | Description | Default |
|---|---|---|
--grafana-url | Grafana instance URL (required) | - |
--grafana-token | Service account token | - |
--grafana-user | Username for basic auth | - |
--grafana-password | Password for basic auth | - |
--transport | MCP transport mode | stdio |
--session-idle-timeout-minutes | Idle session timeout | - |
--log-level | Logging verbosity | info |
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"]- User asks AI assistant to analyze system metrics
- AI invokes
query_prometheusor datasource-specific query tool - Server executes query against configured datasource
- Results are returned to AI for analysis
- AI provides insights and recommendations
Alerting Workflow
- AI retrieves existing alerting rules via
alerting_list_rules - User requests new alert configuration
- AI invokes
alerting_manage_rulesto create/update rules - Server validates and creates rules in Grafana
- 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_imagetool may not properly passorgIdin 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
| Version | Key Additions |
|---|---|
| v0.14.0 | Generic API request tool, OpenSearch support, plugin info tool |
| v0.13.1 | VictoriaMetrics PromQL support, recording rules visibility |
| v0.12.0 | InfluxDB (Flux/InfluxQL), Graphite support |
| v0.11.4 | Pyroscope profiling, Kubernetes-style API client |
| v0.11.3 | Panel filtering in queries, unified alert routing |
Source: Release Notes
See Also
- Installation Guide - Setting up the Grafana MCP server
- Configuration Reference - Detailed configuration options
- Tool Reference - Complete list of MCP tools
- Datasource Integration - Working with different datasources
- Contributing Guide - How to contribute to the project
Source: https://github.com/grafana/mcp-grafana / Human Manual
Installation
Related topics: Overview, Deployment Methods, Authentication
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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:
| Requirement | Description |
|---|---|
| Grafana Instance | A running Grafana instance (OSS, Cloud, or Enterprise) |
| Grafana API Access | A 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:
- Service Account Tokens (recommended) - Create a service account in Grafana and generate an API token
- 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:
| Target | Description |
|---|---|
make build | Build the main server binary |
make test | Run unit tests |
make lint | Run linters |
make lint-fix | Auto-fix linting issues |
make docker-build | Build 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:
| Dockerfile | Base Image | Use Case |
|---|---|---|
Dockerfile | Ubuntu-based | Full featured, larger image |
Dockerfile.alpine | Alpine Linux | Minimal footprint, smaller image |
Source: Dockerfile, Dockerfile.alpine
Environment Variables for Docker
| Variable | Required | Description | Default |
|---|---|---|---|
GRAFANA_URL | Yes | Base URL of your Grafana instance | - |
GRAFANA_TOKEN | Yes* | Service account API token | - |
GRAFANA_AUTH | Yes* | Basic auth (user:password) | - |
PORT | No | HTTP server port | 8765 |
LOG_LEVEL | No | Logging 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
| Flag | Description | Default |
|---|---|---|
--grafana-url | Grafana instance URL | - |
--grafana-token | Service account API token | - |
--grafana-auth | Basic auth (user:password) | - |
--port | HTTP server port | 8765 |
--log-level | Logging level | info |
--transport | MCP transport (stdio, sse, streamable-http) | stdio |
--config | Path 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 Variable | Config Field |
|---|---|
GRAFANA_URL | grafana.url |
GRAFANA_TOKEN | grafana.token |
GRAFANA_AUTH | grafana.auth |
PORT | server.port |
LOG_LEVEL | server.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:
| Mode | Protocol | Use Case |
|---|---|---|
stdio | Standard I/O | Local CLI integration, Claude Desktop |
sse | Server-Sent Events | Web-based clients |
streamable-http | HTTP Streaming | Production 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:
- Verify the service account token is valid and not expired
- Ensure the service account has the necessary permissions
- 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
- Configuration Reference - Detailed configuration options
- Authentication Guide - Setting up Grafana service accounts
- Deployment - Production deployment strategies
- Troubleshooting - Common issues and solutions
Source: https://github.com/grafana/mcp-grafana / Human Manual
Authentication
Related topics: Overview, Installation, Configuration Reference
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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| CSupported Authentication Methods
The server supports the following authentication methods:
| Method | Configuration Field | Description |
|---|---|---|
| Service Account Token | AuthToken | Bearer token from Grafana service accounts |
| Basic Authentication | BasicAuthUser / BasicAuthPassword | Username/password credentials |
| Anonymous | None | No 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:
- Navigate to Configuration → Service Accounts in Grafana
- Click Add service account
- Assign appropriate roles (Viewer, Editor, or Admin depending on required permissions)
- 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]
endTransport Layers
The transport chain is implemented in internal/transport/transport.go and consists of the following layers:
| Layer | Purpose | Source |
|---|---|---|
HeadersTransport | Forward selected headers from MCP request context | internal/transport/transport.go:1-50 |
OnBehalfOfTransport | Apply on-behalf-of authentication headers | internal/transport/transport.go:50-100 |
AuthTransport | Apply 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: ResponseMulti-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
| Configuration | Environment Variable | Description |
|---|---|---|
OrgID | GRAFANA_ORG_ID | Target 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 --> CThe 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
| Variable | Required | Description |
|---|---|---|
GRAFANA_URL | Yes | Base URL of the Grafana instance |
GRAFANA_AUTH_TOKEN | No* | Service account bearer token |
GRAFANA_AUTH_BASIC_USER | No* | Basic auth username |
GRAFANA_AUTH_BASIC_PASSWORD | No* | Basic auth password |
GRAFANA_ORG_ID | No | Target organization ID |
GRAFANA_HEADERS | No | Comma-separated list of headers to forward |
*At least one authentication method is required.
Command-Line Flags
| Flag | Type | Default | Description |
|---|---|---|---|
--grafana-url | string | - | Grafana server URL |
--grafana-token | string | - | Service account token |
--grafana-headers | string | - | Headers to forward from requests |
--session-idle-timeout-minutes | int | 30 | Session idle timeout |
Common Issues and Troubleshooting
Authentication Failures
Symptom: 401 Unauthorized or 403 Forbidden errors when making API calls.
Solutions:
- Verify the service account token is valid and not expired
- Check that the service account has appropriate roles for the operations being attempted
- Ensure the Grafana URL is correct and reachable
SSO Authentication Not Working
Symptom: SSO-authenticated sessions fail to authenticate with Grafana.
Solutions:
- Confirm the
headersconfiguration includes necessary headers (Cookie,Authorization) - Verify the authenticating proxy is forwarding headers correctly
- 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:
- Verify
GRAFANA_ORG_IDis set correctly for the target organization - Ensure the service account has permissions within the target organization
- 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
- Configuration Guide - General configuration options
- Multi-Organization and Headers - Advanced organization and header configuration
- Transport Architecture - Detailed transport chain documentation
- Troubleshooting Guide - Common issues and solutions
Source: https://github.com/grafana/mcp-grafana / Human Manual
Dashboard Tools
Related topics: Datasource Tools, Utility Tools
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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
| Capability | Description | Primary Source |
|---|---|---|
| Dashboard CRUD | Create, read, update, delete dashboards | tools/dashboard.go |
| Panel Rendering | Generate PNG images of dashboard panels | tools/rendering.go |
| Resource Search | Search dashboards, folders, panels, and datasources | tools/search.go |
| Folder Management | Create and manage dashboard folders | tools/folder.go |
| Navigation Links | Generate short URLs and deeplinks | tools/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
| Tool | Purpose | Source |
|---|---|---|
get_dashboard | Retrieve a dashboard by its UID | tools/dashboard.go:1 |
get_dashboard_by_slug | Retrieve a dashboard by its URL slug | tools/dashboard.go:1 |
save_dashboard | Create or update a dashboard | tools/dashboard.go:1 |
delete_dashboard | Delete a dashboard by UID | tools/dashboard.go:1 |
get_dashboard_panel_queries | Extract queries from dashboard panels | tools/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
| Parameter | Type | Description | Required |
|---|---|---|---|
uid | string | Unique identifier for the dashboard | For get/update/delete |
dashboard | object | Dashboard JSON model | For create/update |
folderUid | string | UID of the parent folder | For create |
message | string | Commit message for dashboard changes | Optional |
overwrite | boolean | Overwrite existing dashboard | Optional |
Search Operations
The search functionality provides unified search across Grafana resources including dashboards, folders, panels, and datasources.
Search Tool
| Tool | Purpose | Source |
|---|---|---|
search | Search for dashboards, folders, and panels | tools/search.go:1 |
Search Parameters
| Parameter | Type | Description | Default |
|---|---|---|---|
query | string | Search query string | - |
type | string | Resource type filter (dash-folder, dash-db, panel) | all |
folderUid | string | Limit search to specific folder | root |
limit | integer | Maximum results to return | 50 |
page | integer | Page number for pagination | 1 |
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
| Tool | Purpose | Source |
|---|---|---|
get_panel_image | Render a dashboard panel to PNG | tools/rendering.go:1 |
Rendering Parameters
| Parameter | Type | Description | Required |
|---|---|---|---|
dashboardUid | string | UID of the dashboard containing the panel | Yes |
panelId | integer | ID of the panel to render | Yes |
width | integer | Output image width in pixels | Optional |
height | integer | Output image height in pixels | Optional |
timeout | integer | Render timeout in seconds | Optional |
theme | string | Theme 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
| Tool | Purpose | Source |
|---|---|---|
create_folder | Create a new folder | tools/folder.go:1 |
get_folder | Retrieve folder by UID | tools/folder.go:1 |
list_folders | List all accessible folders | tools/folder.go:1 |
update_folder | Update folder properties | tools/folder.go:1 |
delete_folder | Delete a folder | tools/folder.go:1 |
Folder Parameters
| Parameter | Type | Description | Required |
|---|---|---|---|
uid | string | Unique identifier for the folder | For get/update/delete |
title | string | Display title for the folder | Yes |
parentUid | string | UID of parent folder for nested organization | Optional |
Navigation Operations
Navigation tools enable the generation of URLs and deeplinks for navigating to Grafana resources.
Navigation Tools
| Tool | Purpose | Source |
|---|---|---|
generate_deeplink | Generate Explore and dashboard deeplinks | tools/navigation.go:1 |
create_short_url | Create a short URL via /api/short-urls | tools/shorturls.go:1 |
Deeplink Generation
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
Deeplink Parameters
| Parameter | Type | Description | Required |
|---|---|---|---|
datasourceUid | string | UID of the datasource for Explore links | Conditional |
query | object | Query configuration including expr, queryType | Conditional |
dashboardUid | string | UID of dashboard for direct links | Conditional |
panelId | integer | Panel ID for direct panel links | Optional |
timeRange | object | Time range specification | Optional |
Short URL Parameters
| Parameter | Type | Description | Required |
|---|---|---|---|
path | string | The path portion of the URL to shorten | Yes |
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 Scenario | Cause | Resolution |
|---|---|---|
| Dashboard not found | Invalid UID or insufficient permissions | Verify UID and check org access |
| Folder not empty | Cannot delete folder with contents | Move or delete contents first |
| Render timeout | Panel query takes too long | Increase timeout parameter |
| Write conflict | Dashboard modified since retrieval | Re-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
- Data Source Tools - Querying Prometheus, Loki, InfluxDB, and other datasources
- Alerting Tools - Managing alerts and notification policies
- Configuration Guide - Setting up authentication and connection parameters
- Usage Examples - Common workflow examples
Source: https://github.com/grafana/mcp-grafana / Human Manual
Datasource Tools
Related topics: Dashboard Tools, Alerting Tools
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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]
endTool 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:
| Datasource | Query Language | Tools Available | Since Version |
|---|---|---|---|
| Prometheus | PromQL | Metric discovery, query execution, function list | Initial release |
| InfluxDB | Flux / InfluxQL | Query execution, bucket discovery | v0.12.0 |
| Graphite | graphite-api | Metric finding, query execution, function discovery | v0.12.0 |
| VictoriaMetrics | PromQL | PromQL queries against VM datasources | v0.13.1 |
| CloudWatch | CloudWatch Metrics | Query metrics, list namespaces | v0.9.0+ |
| OpenSearch | PPL | Query execution | v0.14.0 |
Log Datasources
| Datasource | Query Language | Tools Available | Since Version |
|---|---|---|---|
| Loki | LogQL | Log queries, label discovery, sample queries | Initial release |
| Elasticsearch | ES DSL | Log queries, index discovery | v0.9.0+ |
| OpenSearch | PPL | Log queries | v0.14.0 |
Profiling Datasources
| Datasource | Tools Available | Since Version |
|---|---|---|
| Pyroscope | Series query, unified profiling queries | v0.11.4 |
SQL and Analytics Datasources
| Datasource | Tools Available | Since Version |
|---|---|---|
| Snowflake | Query execution | v0.9.0+ |
| Athena | Query execution, table listing | v0.9.0+ |
| ClickHouse | Query execution | v0.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:
| Parameter | Type | Required | Description |
|---|---|---|---|
datasourceUid | string | Yes | The UID of the Prometheus datasource |
matchers | string[] | Yes | Label 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
datasourceUid | string | Yes | The UID of the Prometheus datasource |
matchers | string[] | Yes | Label matchers to filter series |
start | number | No | Start time (epoch seconds) |
end | number | No | End time (epoch seconds) |
#### query_prometheus_query
Executes a PromQL instant query.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
datasourceUid | string | Yes | The UID of the Prometheus datasource |
expr | string | Yes | PromQL expression |
time | number | No | Evaluation time (epoch seconds) |
#### query_prometheus_range
Executes a PromQL range query.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
datasourceUid | string | Yes | The UID of the Prometheus datasource |
expr | string | Yes | PromQL expression |
start | number | Yes | Start time (epoch seconds) |
end | number | Yes | End time (epoch seconds) |
step | string | Yes | Query 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
datasourceUid | string | Yes | The UID of the Loki datasource |
query | string | Yes | LogQL query expression |
limit | number | No | Maximum number of log lines to return (default: 100) |
start | number | No | Start time (epoch nanoseconds) |
end | number | No | End time (epoch nanoseconds) |
direction | string | No | Query 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
datasourceUid | string | Yes | The UID of the InfluxDB datasource |
query | string | Yes | InfluxQL query |
database | string | No | Target database |
retentionPolicy | string | No | Retention policy |
Source: tools/influxdb.go
#### query_flux
Executes a Flux query against an InfluxDB datasource.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
datasourceUid | string | Yes | The UID of the InfluxDB datasource |
query | string | Yes | Flux 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
datasourceUid | string | Yes | The UID of the Graphite datasource |
query | string | Yes | Graphite query expression |
target | string | No | Target 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
datasourceUid | string | Yes | The UID of the Elasticsearch datasource |
query | string | Yes | Elasticsearch JSON query |
index | string | No | Target index pattern |
timeField | string | No | Field 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
datasourceUid | string | Yes | The UID of the Snowflake datasource |
query | string | Yes | SQL query |
database | string | No | Target database |
schema | string | No | Target 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
datasourceUid | string | Yes | The UID of the ClickHouse datasource |
query | string | Yes | SQL query |
database | string | No | Target 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:
| Parameter | Type | Description |
|---|---|---|
datasourceUid | string | Unique identifier of the target datasource in Grafana |
orgId | number | Target 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 resultsExample: 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]
endKnown 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
- Authentication Overview - Service account tokens and authentication methods
- Tool Reference - Complete list of all MCP tools
- Configuration Guide - Configuring datasource connections
- Troubleshooting - Common issues with datasource queries
Source: https://github.com/grafana/mcp-grafana / Human Manual
Alerting Tools
Related topics: Datasource Tools, Incident and OnCall Tools
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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:
- Alerting Rules - Create, read, update, and delete alerting rules
- Notification Routing - Manage notification policies and routing trees
- 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
| Component | File | Responsibility |
|---|---|---|
| MCP Tools | alerting.go | Defines MCP tool schemas and entry points |
| Client | alerting_client.go | HTTP client for Grafana Alerting API |
| Rule Handlers | alerting_manage_rules_handlers.go | Business logic for rule CRUD operations |
| Rule Types | alerting_manage_rules_types.go | Type definitions and transformations |
| Rule Datasource | alerting_manage_rules_datasource.go | Data access for alerting rules |
| Routing | alerting_routing.go | Notification policy management |
| Contact Points | alerting_contact_points.go | Contact 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
| Operation | Description |
|---|---|
| List Rules | Retrieve alerting rules with filtering by folder, datasource, group |
| Create Rule | Create new alerting or recording rules |
| Update Rule | Modify existing alerting rules |
| Delete Rule | Remove alerting rules |
| Group Operations | Manage 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
| Component | Purpose |
|---|---|
| Notification Policies | Define routing trees and matching conditions |
| Contact Points | Configure notification endpoints (email, Slack, PagerDuty, etc.) |
| Time Intervals | Define 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 --> IContact 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
| Type | Description |
|---|---|
| Send email notifications | |
| Slack | Slack webhook integration |
| PagerDuty | PagerDuty incident creation |
| Webhook | Generic HTTP webhook calls |
| OpsGenie | OpsGenie alert integration |
| Telegram | Telegram bot notifications |
| Discord | Discord webhook notifications |
| Custom | Plugin-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:
- Identifying the target folder and rule group
- Defining the query or condition
- Setting evaluation intervals and no-data/firing states
- Configuring labels and annotations
- 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
| Issue | Cause | Resolution |
|---|---|---|
| Type Mismatches | LLM passing string vs number | Use v0.13.0+ which includes automatic type conversion |
| Missing Recording Rules | Incomplete ruler listings | v0.13.1 includes recording rules in datasource listings |
| Context Loss | Missing request context propagation | Ensure using WithParams variants of API calls |
Debugging Tips
- Verify API Permissions: Ensure the service account has appropriate alerting permissions
- Check Datasource Availability: Confirm datasources referenced in rules are accessible
- Validate Routing Configuration: Test notification routing with dry-run or test endpoints
- Review Label Matching: Ensure alert labels match expected routing conditions
Version History
| Version | Changes |
|---|---|
| v0.13.1 | Include recording rules in datasource ruler listings |
| v0.13.0 | Fixed type mismatch handling (string vs number) in alerting_manage_rules |
| v0.11.3 | Added alerting_manage_routing for unified notification policy management |
See Also
- Getting Started Guide - Initial setup and configuration
- Datasource Tools - Query execution and datasource management
- Dashboard Tools - Dashboard and panel operations
- Configuration Reference - Full configuration options including authentication
Source: https://github.com/grafana/mcp-grafana / Human Manual
Incident and OnCall Tools
Related topics: Alerting Tools, Utility Tools
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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_APIThe 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 Name | Purpose |
|---|---|
create_incident | Create a new Grafana incident with title, description, and severity |
get_incident | Retrieve details of a specific incident by ID |
list_incidents | List incidents with optional filtering by status, severity, or time range |
update_incident | Modify incident properties such as status, severity, or assignment |
add_incident_comment | Add comments or notes to an existing incident |
get_incident_timeline | Retrieve the chronological timeline of an incident |
Incident Data Model
Source: tools/incident.go:50-150
The incident data model includes the following core fields:
| Field | Type | Description |
|---|---|---|
id | string | Unique identifier for the incident |
title | string | Brief title describing the incident |
description | string | Detailed description of the incident |
status | string | Current status (active, resolved, acknowledged) |
severity | string | Impact level (critical, high, medium, low) |
created_at | timestamp | When the incident was created |
updated_at | timestamp | Last modification time |
created_by | string | User who created the incident |
assignee | string | User or team assigned to the incident |
labels | array | Optional 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| EOnCall 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 Name | Purpose |
|---|---|
oncall_list_schedules | List all on-call schedules |
oncall_get_schedule | Get details of a specific schedule |
oncall_create_schedule | Create a new on-call schedule |
oncall_update_schedule | Modify an existing schedule |
oncall_delete_schedule | Remove a schedule |
oncall_get_current_oncall | Get the current on-call user for a schedule |
oncall_get_schedule_shifts | Retrieve shifts for a schedule |
Escalation Policy Management
| Tool Name | Purpose |
|---|---|
oncall_list_escalation_policies | List all escalation policies |
oncall_get_escalation_policy | Get a specific escalation policy |
oncall_create_escalation_policy | Create a new escalation policy |
oncall_update_escalation_policy | Modify an escalation policy |
oncall_delete_escalation_policy | Remove an escalation policy |
User and Team Management
| Tool Name | Purpose |
|---|---|
oncall_list_users | List all users in OnCall |
oncall_get_user | Get details of a specific user |
oncall_list_teams | List all teams |
oncall_get_team | Get a specific team |
oncall_get_user_oncall_status | Check if a user is currently on-call |
Integration Management
| Tool Name | Purpose |
|---|---|
oncall_list_integrations | List all OnCall integrations |
oncall_get_integration | Get details of an integration |
oncall_create_integration | Create a new integration |
oncall_update_integration | Modify an integration |
oncall_delete_integration | Remove 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:
| Type | Fields | Description |
|---|---|---|
ScheduleType | id, name, type, team_id, timezone | Defines an on-call schedule |
ShiftType | id, schedule_id, user_id, start, end, type | A time block when a user is on-call |
EscalationPolicyType | id, name, team_id, steps | Defines escalation rules |
UserType | id, email, username, role, is_verified | OnCall 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 ResultProxy 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
| Feature | Description |
|---|---|
| Cross-resource search | Search across incidents, alerts, dashboards, and other resources |
| Fuzzy matching | Find resources using approximate string matching |
| Filter by type | Narrow results to specific resource types |
| Pagination | Handle large result sets efficiently |
Configuration
Required Permissions
The MCP server requires the following Grafana permissions for Incident and OnCall tools:
| Permission | Required For |
|---|---|
apikeys:read | API key authentication |
plugins:manage | Plugin management |
datasources:read | Reading datasource configurations |
datasources:write | Modifying datasource configurations |
organizations:read | Multi-org support |
teams:read | Team listing |
teams:write | Team management |
users:read | User listing |
Environment Variables
| Variable | Description | Default |
|---|---|---|
GRAFANA_URL | Grafana instance URL | Required |
GRAFANA_TOKEN | Service account token or API key | Required |
GRAFANA_ORG_ID | Target organization ID | 1 |
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
| Error | Cause | Resolution |
|---|---|---|
401 Unauthorized | Invalid or expired token | Regenerate service account token |
403 Forbidden | Insufficient permissions | Verify required permissions are granted |
Missing Authorization header | Token not configured | Set GRAFANA_TOKEN environment variable |
API Connectivity Issues
| Error | Cause | Resolution |
|---|---|---|
connection refused | Grafana not reachable | Verify Grafana URL and network connectivity |
timeout | Slow API response | Increase timeout settings or check Grafana health |
404 Not Found | Resource doesn't exist | Verify resource ID and organization context |
Data Consistency Issues
| Issue | Description | Mitigation |
|---|---|---|
| Stale on-call data | Schedule changes may take time to propagate | Use refresh=true parameter when querying current on-call |
| Missing incident fields | Some fields require specific Grafana plugins | Verify Grafana Incident plugin is installed and configured |
Known Limitations
Based on community feedback and issue tracking:
- Panel Image and Organization Context: The
get_panel_imagetool does not currently supportorgIdfor rendering panels across organizations. See Issue #883.
- Short URLs: The
generate_deeplinktool 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.
- 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
- Create incidents with complete information: Include severity, affected systems, and initial assessment in the incident description
- Use consistent labeling: Apply standard labels for easier filtering and post-mortem analysis
- Document timeline: Add comments at key decision points during incident response
- Resolve systematically: Follow your organization's incident resolution checklist
On-Call Best Practices
- Schedule rotation: Configure regular rotation periods to distribute on-call load
- Escalation paths: Define clear escalation steps with appropriate timeouts
- Integration validation: Test integrations regularly to ensure alert routing works correctly
- Override management: Use schedule overrides sparingly and communicate them clearly
See Also
- Getting Started Guide - Setup and authentication configuration
- Alerting Tools - Grafana alerting system integration
- Data Source Tools - Querying Prometheus, Loki, InfluxDB, and other datasources
- Dashboard Management - Dashboard creation and modification
- Configuration Reference - Complete configuration options
Source: https://github.com/grafana/mcp-grafana / Human Manual
Utility Tools
Related topics: Dashboard Tools, Incident and OnCall Tools
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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
| Operation | Description |
|---|---|
annotations_create | Create a new annotation in Grafana |
annotations_list | List annotations with optional filtering |
annotations_delete | Delete annotations by ID |
annotations_update | Update 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 listCommon Parameters
| Parameter | Type | Description |
|---|---|---|
text | string | The annotation text content |
time | int64 | Start time in epoch milliseconds |
timeEnd | int64 | End time (for range annotations) |
tags | string[] | Tags for categorization and filtering |
dashboardUid | string | Associated dashboard UID |
panelId | int64 | Associated 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
| Operation | Description |
|---|---|
admin_get_settings | Retrieve Grafana server settings |
admin_get_stats | Get server statistics |
admin_manage_users | User management operations |
admin_manage_orgs | Organization 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
| Operation | Description |
|---|---|
plugins_list | List all installed plugins |
plugins_get | Get 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
| Operation | Description |
|---|---|
api_request | Make arbitrary HTTP requests to Grafana API |
Source: tools/api.go
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
method | string | Yes | HTTP method (GET, POST, PUT, PATCH, DELETE) |
path | string | Yes | API endpoint path (e.g., /api/dashboards/uid/foo) |
body | object | No | Request body for POST/PUT/PATCH |
headers | object | No | Additional 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
| Operation | Description |
|---|---|
hints_get | Retrieve 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
| Operation | Description |
|---|---|
k8s_list | List resources of a given type |
k8s_get | Get a specific resource |
k8s_create | Create a new resource |
k8s_update | Update an existing resource |
k8s_delete | Delete 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| CSource: 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 --> ESource: tools/annotations.go, tools/admin.go
Error Handling
Utility tools follow consistent error handling patterns:
| Error Type | Description | Resolution |
|---|---|---|
NotFoundError | Resource does not exist | Verify resource ID/UID |
PermissionError | Insufficient permissions | Check service account roles |
ValidationError | Invalid parameters | Review parameter formats |
APIError | Grafana API error | Check 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
- Getting Started - Setting up authentication for utility tools
- Data Sources - Query-specific datasource tools
- Alerting - Alert management tools
- Dashboard Management - Dashboard CRUD operations
- Authentication - Service account configuration
- Configuration - Tool configuration options
Source: https://github.com/grafana/mcp-grafana / Human Manual
Deployment Methods
Related topics: Installation, Configuration Reference
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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:
| Image | Base | Size | Use Case |
|---|---|---|---|
mcp/grafana | Ubuntu-based | Larger | General purpose, full compatibility |
mcp/grafana:alpine | Alpine Linux | Smaller | Memory-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
| Transport | Protocol | Use Case | Stateful |
|---|---|---|---|
stdio | Standard I/O | Local tools, CLI integration | No |
sse | Server-Sent Events | Web-based MCP clients | Yes |
streamable-http | HTTP/1.1 Streaming | Scalable deployments, load balancers | Configurable |
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:
| Flag | Environment Variable | Default | Description |
|---|---|---|---|
--address | MCP_ADDRESS | :8080 | Bind address for network transports |
--stdio-address | MCP_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
| Option | Flag | Description |
|---|---|---|
| Server Certificate | --tls-cert-file | Path to PEM-encoded TLS certificate |
| Private Key | --tls-key-file | Path 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| HSource: session.go
Session Configuration
| Parameter | Flag | Environment Variable | Default | Description |
|---|---|---|---|---|
| Session Timeout | --session-idle-timeout-minutes | MCP_SESSION_IDLE_TIMEOUT_MINUTES | 5 | Minutes 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 --> DBWhen 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.
Service Account Token (Recommended)
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
SSO and Session Cookie Authentication
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:
| Method | Priority | Example |
|---|---|---|
| CLI flags | Highest | --grafana-url https://... |
| Environment variables | Medium | GRAFANA_URL=https://... |
| Config file | Lowest | grafana.url: https://... |
Common Environment Variables
| Variable | Description | Example |
|---|---|---|
GRAFANA_URL | Grafana instance URL | https://grafana.example.com:3000 |
GRAFANA_TOKEN | Service account token | glsa_xxxxx |
GRAFANA_USER | Basic auth username | admin |
GRAFANA_PASSWORD | Basic auth password | secret |
MCP_TRANSPORT | Transport mode | streamable-http |
MCP_ADDRESS | Server 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
- Use Service Account Tokens: Avoid basic authentication in production; create dedicated service accounts with minimal required permissions.
- Enable TLS: Always use TLS encryption for HTTP-based transports to protect credentials in transit.
- Configure Session Timeouts: Set appropriate session idle timeouts based on your use case to manage resource usage.
- Use Load Balancers: For horizontal scaling, configure health checks and sticky sessions at the load balancer level.
- 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
- Configuration Reference - Detailed transport and address configuration
- TLS Configuration - Server TLS setup for streamable HTTP
- Authentication Overview - Authentication methods and best practices
Source: https://github.com/grafana/mcp-grafana / Human Manual
Configuration Reference
Related topics: Authentication, Deployment Methods
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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
| Method | Description | Configuration Key |
|---|---|---|
| Service Account Token | Recommended for production use | GRAFANA_TOKEN or --grafana-token |
| Basic Auth | Username/password combination | GRAFANA_USER / GRAFANA_PASSWORD |
| SSO Headers | Cookie/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:
| Mode | Description | Use Case |
|---|---|---|
stdio | Standard input/output (default) | Local MCP clients |
sse | Server-Sent Events | Web-based clients |
streamable-http | Streaming HTTP | Production 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
| Category | Description | Example Tools |
|---|---|---|
| Dashboard | Dashboard CRUD operations | get_dashboard, update_dashboard |
| Alerting | Alert rule management | alerting_list_rules, alerting_manage_rules |
| Datasources | Query execution | query_prometheus, query_loki_logs, query_influx |
| Explore | Log and trace exploration | query_loki_logs, query_traces |
| Rendering | Panel image capture | get_panel_image |
| Admin | Server administration | admin_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:
| Endpoint | Description |
|---|---|
/health | Returns 200 if server is running |
/ready | Returns 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 Variable | CLI Flag Equivalent | Description |
|---|---|---|
MCP_GRAFANA_URL | --grafana-url | Grafana instance URL |
MCP_GRAFANA_TOKEN | --grafana-token | Service account token |
MCP_GRAFANA_USER | --grafana-user | Basic auth username |
MCP_GRAFANA_PASSWORD | --grafana-password | Basic auth password |
MCP_TRANSPORT | --transport | Transport mode |
MCP_PORT | --port | Server port |
MCP_LOG_LEVEL | --log-level | Logging level |
MCP_LOG_FORMAT | --log-format | Log output format |
MCP_TOOLS_CONFIG | --tools-config | Path to tools YAML |
MCP_HEALTH_PORT | --health-port | Health 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):
- Default values (hardcoded)
- Configuration file (
--configflag) - Environment variables
- 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
| Issue | Cause | Solution |
|---|---|---|
| Authentication failures | Invalid or expired token | Verify token in Grafana settings |
| Connection refused | Wrong port or URL | Check --grafana-url and firewall rules |
| Tools not appearing | Disabled in tools config | Verify YAML file and --tools-config path |
| SSO not working | Headers not forwarded | Ensure --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
- Command Line Reference - Detailed CLI flag documentation
- Tool Reference - Available MCP tools
- Authentication Guide - Setting up authentication
- Docker Deployment - Containerized deployment
- Contributing Guide - Development setup
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.
May increase setup, validation, or first-run risk for the user.
May increase setup, validation, or first-run risk for the user.
May increase setup, validation, or first-run risk for the user.
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.
Count of project-level external discussion links exposed on this manual page.
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.
- Insturctions - github / github_issue
- Security consideration: Prompt injection via dashboard data in MCP conte - github / github_issue
- [[Feature]: Add tools for Pyroscope](https://github.com/grafana/mcp-grafana/issues/158) - github / github_issue
- Add tool to create Grafana short URLs (/goto/<uid>) via /api/short-urls - github / github_issue
get_panel_imageshould supportorgIdwhen rendering panels - github / github_issue- Feature Request: OAuth/SSO Authentication Support (Okta, Google, etc.) - github / github_issue
- Feature request: pagination / chunking for query_loki_logs results - github / github_issue
- v0.14.0 - github / github_release
- v0.13.1 - github / github_release
- v0.13.0 - github / github_release
- v0.12.1 - github / github_release
- v0.12.0 - github / github_release
Source: Project Pack community evidence and pitfall evidence