Skip to main content

Grafana MCP Server

Create a powerful Model Context Protocol (MCP) server for Grafana in minutes with our AI Gateway. This guide walks you through setting up seamless monitoring and visualization integration with enterprise-grade dashboards and instant API authentication.

About Grafana API

Grafana is the open-source analytics and interactive visualization platform that connects with every database. The API enables programmatic management of dashboards, data sources, alerts, and organizations, allowing for powerful automation and integration capabilities.

Key Capabilities

  • Dashboard Management: Create, update, and share dashboards
  • Data Source Integration: Connect to 100+ data sources
  • Alerting System: Define and manage alert rules
  • User Management: Control access and permissions
  • Annotations: Add events and markers to graphs
  • Playlists: Rotate dashboard displays
  • Snapshots: Share dashboard snapshots
  • Folders: Organize dashboards hierarchically

API Features

  • RESTful API: Standard HTTP methods
  • API Keys: Secure authentication
  • Service Accounts: Machine-to-machine auth
  • RBAC: Role-based access control
  • Provisioning: Configuration as code
  • Webhooks: Event notifications
  • Query API: Direct data queries
  • Admin API: Instance management

What You Can Do with Grafana MCP Server

The MCP server transforms Grafana API into a natural language interface, enabling AI agents to:

Dashboard Operations

  • Dashboard Management

    • "Create new performance dashboard"
    • "Update sales dashboard layout"
    • "Clone existing dashboard"
    • "Delete unused dashboards"
  • Panel Configuration

    • "Add time series panel"
    • "Configure gauge visualization"
    • "Set up stat panels"
    • "Create table views"
  • Dashboard Sharing

    • "Share dashboard with team"
    • "Create public dashboard"
    • "Generate snapshot link"
    • "Export dashboard JSON"

Data Source Management

  • Connection Setup

    • "Add Prometheus data source"
    • "Configure PostgreSQL connection"
    • "Set up CloudWatch integration"
    • "Test data source connectivity"
  • Query Configuration

    • "Create metric queries"
    • "Set up variables"
    • "Configure refresh intervals"
    • "Build complex queries"

Alert Management

  • Alert Rules

    • "Create CPU usage alert"
    • "Set up error rate monitoring"
    • "Configure threshold alerts"
    • "Define multi-condition alerts"
  • Notification Channels

    • "Add Slack notification"
    • "Configure email alerts"
    • "Set up PagerDuty integration"
    • "Create webhook notifications"
  • Alert Policies

    • "Set quiet hours"
    • "Configure escalation"
    • "Group related alerts"
    • "Manage alert states"

Organization Management

  • Folder Structure

    • "Create department folders"
    • "Organize by environment"
    • "Set folder permissions"
    • "Move dashboards between folders"
  • Team Management

    • "Create ops team"
    • "Assign dashboard permissions"
    • "Set team preferences"
    • "Manage team members"

User & Access Control

  • User Management

    • "Create new user"
    • "Assign roles"
    • "Reset passwords"
    • "Manage API keys"
  • Permission Control

    • "Grant dashboard access"
    • "Set folder permissions"
    • "Configure data source access"
    • "Define organization roles"

Annotations & Events

  • Event Tracking

    • "Add deployment marker"
    • "Mark incident timeline"
    • "Create maintenance window"
    • "Log configuration changes"
  • Annotation Queries

    • "Show deploy events"
    • "Filter by tags"
    • "Query time ranges"
    • "Correlate with metrics"

Automation Features

  • Provisioning

    • "Deploy dashboards via code"
    • "Configure data sources"
    • "Set up alert rules"
    • "Manage plugins"
  • Backup & Restore

    • "Export all dashboards"
    • "Backup configurations"
    • "Restore from JSON"
    • "Version control integration"

Prerequisites

  • Access to Cequence AI Gateway
  • Grafana instance (v8.0+)
  • Admin or Editor permissions
  • API key or service account token

Step 1: Configure Grafana API Access

1.1 Create API Key

  1. Log in to your Grafana instance
  2. Navigate to Configuration API Keys
  3. Click Add API Key
  4. Configure:
    • Key name: "AI Gateway Integration"
    • Role: Admin or Editor
    • Time to live: Set appropriate expiration
  1. Go to Administration Service accounts
  2. Click Add service account
  3. Configure:
    • Display name: "AI Gateway Service"
    • Role: Editor or Admin
  4. Create service account token

1.3 Permissions Setup

Ensure the API key/service account has permissions for:

  • Dashboard creation and modification
  • Data source management
  • Alert rule configuration
  • Folder management
  • Annotation creation

Step 2-4: Standard Setup

Follow standard steps to access AI Gateway, find Grafana API, and create MCP server.

Step 5: Configure API Endpoints

  1. Base URL: https://your-grafana-instance.com/api
  2. API Version: Latest stable
  3. Organization ID: Default or specific org
  4. Click Next

Step 6: MCP Server Configuration

  1. Name: "Grafana Monitoring"
  2. Description: "Visualization and monitoring platform"
  3. Request Timeout: 30 seconds
  4. Click Next

Step 7: Configure Authentication

  1. Authentication Type: Bearer Token
  2. Token Format: API Key or Service Account Token
  3. Header: Authorization: Bearer YOUR_TOKEN
  4. Test connection with health check

Available Grafana API Operations

Dashboard APIs

  • Dashboard Management

    • Create/Update dashboard
    • Get dashboard by UID
    • Delete dashboard
    • Search dashboards
  • Dashboard Versions

    • Get version history
    • Compare versions
    • Restore version
    • Get diff
  • Dashboard Permissions

    • Get permissions
    • Update permissions
    • Add team/user access
    • Remove access

Data Source APIs

  • Data Source Operations

    • List data sources
    • Create data source
    • Update configuration
    • Delete data source
  • Proxy Calls

    • Query through proxy
    • Test data source
    • Get metrics
    • Run queries

Alert APIs

  • Alert Rules

    • List alert rules
    • Create/Update rules
    • Delete rules
    • Test rules
  • Alert Notifications

    • List channels
    • Create channel
    • Test notification
    • Update settings

Organization APIs

  • Org Management
    • Switch organization
    • Update preferences
    • Manage users
    • Configure settings

Admin APIs

  • User Administration
    • Create users
    • Update permissions
    • Manage teams
    • Global settings

Step 8-10: Complete Setup

Configure security settings, choose deployment options, and deploy your server.

Using Your Grafana MCP Server

With Claude Desktop

{
"servers": {
"grafana": {
"url": "your-mcp-server-url",
"auth": {
"type": "bearer",
"token": "your-api-key"
},
"config": {
"grafana_url": "https://your-grafana.com",
"org_id": 1
}
}
}
}

Natural Language Commands

  • "Create a dashboard for application performance"
  • "Add Prometheus as a data source"
  • "Set up alert when CPU exceeds 80%"
  • "Share the infrastructure dashboard with the ops team"
  • "Show me all dashboards tagged with 'production'"

API Integration Example

// Initialize MCP client
const mcpClient = new MCPClient({
serverUrl: 'your-mcp-server-url',
auth: {
type: 'bearer',
token: 'your-api-key'
}
});

// Create a new dashboard
const dashboard = await mcpClient.grafana.createDashboard({
dashboard: {
title: 'Application Performance',
tags: ['production', 'performance'],
timezone: 'browser',
panels: [
{
id: 1,
gridPos: { h: 8, w: 12, x: 0, y: 0 },
type: 'graph',
title: 'CPU Usage',
datasource: 'Prometheus',
targets: [
{
expr: 'rate(cpu_usage_seconds_total[5m])',
refId: 'A'
}
]
},
{
id: 2,
gridPos: { h: 8, w: 12, x: 12, y: 0 },
type: 'graph',
title: 'Memory Usage',
datasource: 'Prometheus',
targets: [
{
expr: 'memory_usage_bytes',
refId: 'A'
}
]
}
]
},
folderId: 0,
overwrite: false
});

console.log(`Created dashboard: ${dashboard.url}`);

// Add a data source
const dataSource = await mcpClient.grafana.createDataSource({
name: 'Production Metrics',
type: 'prometheus',
url: 'http://prometheus:9090',
access: 'proxy',
basicAuth: false,
isDefault: true,
jsonData: {
httpMethod: 'POST',
keepCookies: []
}
});

// Create an alert rule
const alertRule = await mcpClient.grafana.createAlertRule({
uid: 'cpu-high-alert',
title: 'High CPU Usage Alert',
condition: 'A',
data: [
{
refId: 'A',
queryType: '',
model: {
expr: 'avg(rate(cpu_usage_seconds_total[5m])) > 0.8',
refId: 'A'
},
datasourceUid: dataSource.uid,
conditions: [
{
evaluator: {
params: [0.8],
type: 'gt'
},
operator: {
type: 'and'
},
query: {
params: ['A']
},
reducer: {
params: [],
type: 'avg'
},
type: 'query'
}
]
}
],
noDataState: 'NoData',
execErrState: 'Alerting',
for: '5m',
annotations: {
description: 'CPU usage has exceeded 80% for 5 minutes',
runbook_url: 'https://wiki.company.com/runbooks/high-cpu'
},
labels: {
severity: 'warning',
team: 'platform'
}
});

// Configure notification channel
const slackChannel = await mcpClient.grafana.createNotificationChannel({
name: 'Slack Alerts',
type: 'slack',
settings: {
url: 'https://hooks.slack.com/services/YOUR/WEBHOOK/URL',
channel: '#alerts',
username: 'Grafana'
},
isDefault: true,
sendReminder: true,
frequency: '10m'
});

// Search dashboards
const dashboards = await mcpClient.grafana.searchDashboards({
query: 'performance',
tag: ['production'],
type: 'dash-db',
limit: 20
});

console.log(`Found ${dashboards.length} performance dashboards`);

// Add annotation
const annotation = await mcpClient.grafana.createAnnotation({
dashboardUID: dashboard.uid,
time: Date.now(),
timeEnd: Date.now() + 3600000,
tags: ['deployment', 'v2.1.0'],
text: 'Deployed version 2.1.0 to production'
});

// Create folder structure
const folder = await mcpClient.grafana.createFolder({
title: 'Production Dashboards',
uid: 'prod-dashboards'
});

// Move dashboard to folder
await mcpClient.grafana.moveDashboard({
uid: dashboard.uid,
folderId: folder.id
});

// Set folder permissions
await mcpClient.grafana.updateFolderPermissions({
uid: folder.uid,
items: [
{
role: 'Viewer',
permission: 1
},
{
teamId: 2,
permission: 2 // Edit
},
{
userId: 10,
permission: 4 // Admin
}
]
});

// Create dashboard snapshot
const snapshot = await mcpClient.grafana.createSnapshot({
dashboard: dashboard,
name: 'Performance Snapshot',
expires: 3600, // 1 hour
external: true,
key: 'unique-snapshot-key'
});

console.log(`Snapshot URL: ${snapshot.url}`);

// Query data directly
const queryResult = await mcpClient.grafana.queryDataSource({
datasourceId: dataSource.id,
queries: [
{
refId: 'A',
expr: 'up',
range: true,
interval: '30s'
}
],
from: 'now-1h',
to: 'now'
});

// Provision dashboard from code
const provisionedDashboard = await mcpClient.grafana.provisionDashboard({
folderUID: 'prod-dashboards',
dashboard: {
uid: 'app-overview',
title: 'Application Overview',
refresh: '30s',
schemaVersion: 30,
templating: {
list: [
{
name: 'environment',
type: 'query',
query: 'label_values(environment)',
current: {
value: 'production',
text: 'production'
}
}
]
},
panels: [
// Panel definitions...
]
}
});

// Create playlist
const playlist = await mcpClient.grafana.createPlaylist({
name: 'Operations Overview',
interval: '1m',
items: [
{ type: 'dashboard_by_uid', value: 'app-overview' },
{ type: 'dashboard_by_uid', value: 'infrastructure' },
{ type: 'dashboard_by_tag', value: 'critical' }
]
});

// Export all dashboards for backup
const allDashboards = await mcpClient.grafana.searchDashboards({});
const backups = [];

for (const dash of allDashboards) {
const fullDashboard = await mcpClient.grafana.getDashboard({
uid: dash.uid
});
backups.push(fullDashboard);
}

// Save backups to file or version control
console.log(`Backed up ${backups.length} dashboards`);

Common Use Cases

Infrastructure Monitoring

  • Server metrics visualization
  • Network performance tracking
  • Resource utilization dashboards
  • Capacity planning

Application Performance

  • Response time monitoring
  • Error rate tracking
  • User experience metrics
  • Service dependencies

Business Metrics

  • KPI dashboards
  • Sales analytics
  • Customer metrics
  • Revenue tracking

DevOps Automation

  • CI/CD pipeline metrics
  • Deployment tracking
  • Incident management
  • SLO monitoring

Best Practices

  1. Dashboard Design:

    • Use consistent layouts
    • Group related metrics
    • Add helpful descriptions
    • Use appropriate visualizations
  2. Alert Configuration:

    • Set meaningful thresholds
    • Avoid alert fatigue
    • Use proper escalation
    • Document runbooks
  3. Performance Optimization:

    • Limit query time ranges
    • Use recording rules
    • Cache when possible
    • Optimize refresh rates

Troubleshooting

Common Issues

  1. Authentication Errors

    • Verify API key validity
    • Check permissions
    • Ensure correct org context
    • Validate token format
  2. Dashboard Issues

    • Check UID conflicts
    • Verify data source exists
    • Validate JSON schema
    • Review panel queries
  3. Alert Problems

    • Test notification channels
    • Verify query syntax
    • Check evaluation intervals
    • Review alert states

Getting Help