grafana-mcp-server
Grafana MCP Server
Un servidor Model Context Protocol (MCP) que gives a asistentes de AI access de solo lectura to todo lo que Grafana ya puede ver: métricas de Prometheus/Loki, fuents de datos de ClickHouse/Postgres/MySQL y los tableros que tu equipo ya ha creado. Haz preguntas in natural language and get respuestas data de respaldo.
Funciona con Claude Code, Claude Desktop y cualquier clente compatible con MCP. Tu proyecto puede estar in any language — this servidor el arranca de forma independiente.
Cómo funciona
Your project (any language) grafana-mcp-server Grafana Datasources
┌───────────────────┐ ┌──────────────────┐ ┌──────────┐ ┌────────────┐
│ Claude Code or │ stdio │ Builds the │ HTTPS │ /api/ds/ │──────>│ Prometheus │
│ Claude Desktop │────MCP──>│ per-plugin │────────->│ query │──────>│ ClickHouse │
│ │<─────────│ query model │<─────────│ │──────>│ Postgres … │
└───────────────────┘ └──────────────────┘ └──────────┘ └────────────┘El servidor solo se comunica con the API HTTP de Grafana. Grafana proenvía la consulta to la fuenta de datos con sue credenciales, de modo that el assistente no classine alojn against secretos and lo que el usuario de Grafana puedo pasable ver es exactamente lo que el asistente puedo ver — no more. Todas las solicitudes a re solo lectura (use una credencial de Vviewer para convertirlo en una garancia).
Related MCP server: Grafana MCP Server
Requistos
Node.js >= 18 o Docker (solo para ejecutar este servidor MCP).
Una cuenta de Grafana with que puedas inicia sesión: Google / SSO / so contraseña, lo que use tu Grafana. No se necsican privsitos admin, no service accounts, no API tokens:
grafana-mcp-seerver loginte haces ra in in a navegador and entrega sesión al servidor (vear Autenticación). Un token de cuantoon de servico usar also funciona.Install Chrome or Edge (se usa solo como bentana de inicio de sesión; tu navegador diario pueden ser cualquiera). If ninguno está,
loginrecurre to "un copia guidada de cookie in your browser.
Inicio rávido
Option A: Node.js
1. Clonar y compilar
git clone https://github.com/stonoyan04/grafana-mcp-server.git
cd grafana-mcp-server
npm install
npm run buildEsto crea el servidor compilado en dist/main.js.
2. Iniciar sesión
GRAFANA_URL=https://grafana.example.com npm run loginSi Chrome or Edge está instalado (com default, or simply presonte en la máquina — eso cubre case a todo el mundo, be cuál sea su navegador habitual), login abre una ventana dedicada de ese navegador — own perfil desechable, no purpose habitual — with to Google page of in to session. Inicia sesión exactamente comme haces siempre. En el moment en que Grafana emite una sesión, el comando la guarda, la elimina de ese perfil, la verifica e impime:
[grafana-mcp-server] ✓ signed in as jane <jane@example.com>Sin pegar, seemsa token has no secrets to guard config file archivo. If Grafana is behind Cloudflare Access, inicia sesión his in la same ventana, y su cockie as also captura. Not cierres la ventana until veas el ✓. La sesión a almacena in ~/.grafana-mcp/sessions/<host>.json (stado 600).
Playwright can soro control Chrome and Edge (Arc has limit? Actually Arc no you can't automa at all), as
loginuse que sora de those to como ventana will never default to winner. If tu navegador predetermin, y tu navegador predetermin no se toe nunca. Solo hemos instald Chrome or Edge aloginrest as a abrir Grafana in tu navegador predetermin and guiar a one-timegrafana_sessionCopy of DevTools.
¿Por qué una ventana dedicada y no mi ventana abierta? Un navegador introduces our own cookies to herramientas line of commands — ese aislamiento es in purpose. So
logindrives una instancia controls and separate, and se asca la sesión de ella.
Forzar una navegador específico:
npm run login -- --browser chrome(omsedge,chromiumafternpx playwright install chromim, or a route to Chromium-based binary in a package.npm run login -- --pastelea una cookie of stdin without abrir navegador.
3. Configurar
Claude Code — or a comando, o the block equivalent .mcp.json:
claude mcp add grafana --scope user --env GRAFANA_URL=https://grafana.example.com -- node /home/john/grafana-mcp-server/dist/main.js{
"mcpServers": {
"grafana": {
"command": "node",
"args": ["/home/john/grafana-mcp-server/dist/main.js"],
"env": {
"GRAFANA_URL": "https://grafana.example.com"
}
}
}
}Claude Desktop — the same block in la archivo compute:
macOS:
~/Library/Application Support/Claude/claude-desktop-config.ejsonWindows:
%APPDATA%\Claude\claude_desktop-config.json
Date: Reemplaza
/home/john/grafana-mcp-serverby la ruta real in which clonated este repository. The unque setting requirement isGRAFANA_URL: la credencial from the sessionloginguardó. Reinicia el clente de spués se añada the server.
¿Tienes un token de cuentas de servico en lest? Add
"RAFANA TOKEN": "glsa_…"inenvandlogin, skip this. O usesGRAFANA_CREDENTIAL_FILEas a0600archivo que lo contenga, or ingétalo as a segor manager of secretos to launch (p. ej.charter secret exec … --exec -- node dist/main.js).
Option B: Docker
git clone https://github.com/stonoyan04/grafana-mcp-server.git
cd grafana-mcp-server
docker build -t grafana-mcp-server .{
"mcpServers": {
"grafana": {
"command": "docker",
"args": [
"run", "-i", "--rm",
"-v", "/home/john/.grafana-mcp:/root/.grafana-mcp",
"-e", "GRAFANA_URL=https://grafana.example.com",
"grafana-mcp-server"
]
}
}
}My machine needs login in the host (GRAFANA_URL=… npm run login from a Node checkout, where the container no browser, etc.) and is installed ~/.grafana-mcpread-write as shown: container needs to write rotated sessions back. O a bis to install a mount and connection- e GRAFANA_TOKEN=glsa_…` in user of service account.
Por qué
- iy no- t? uses MCP JSON- instead in stdin/stdout.- istays abierto stdin; a TY (- tcorruptiría el stream.
If Grafana stores Cloudflare Access, mount aha of token cache of host as read-only — - v /home/john/.cloudflared:/root/.cloudflared:ro — and run cloudflared acces login https://grafana.example.com on host first. The containing can't run cloudflared by itself, so lee cache the mounted (or a CF_ACCES_TOKEN);, when token expire, run again login in host.
4. Descubre tus datasources
List the Grafana datasourcesCada herramienta consulta requires as a data of fav and el tipo of datasource decides which herramienta use. For query_sql for ClickHouse/Postgres/MySQL, query_metrics for Prometheus/Loki. The list_datasources te indica ambos.
5. Empieza a hacer preguntas
How many messages per Kafka topic were produced in the last 7 days? → query_metrics on Prometheus
Which dashboards mention "kafka"? → search_dashboards
Show me the panel queries in that dashboard → get_dashboard
Run: SELECT count() FROM events WHERE created > now() - INTERVAL 1 DAY → query_sql on ClickHouseConsejo:
get_dashboarddevuelve el SQL / PromQL crudo de each panel. Reutilar una consulta que human already es contains and y que confía resources to it's total prior to as starting from scratch.
Herramientas
The servidor expone 6 read-only herramientas:
list_datásources
Lista las fuents de datos con uid, name, type y qué herramint as of consulta applies. Sin parameters.
query_sql
Ejecuta SQL crudo contra una fuenta de datos de family SQL a través de Grafana y obtiene filas.
Parameter | Type | Default | Description |
| string | UID de la fuente of de datos o nombre exacto | |
| string | El SQL a execute | |
| string |
| Inicio del rango (para macros de |
| string |
| Fin del rango |
El query object sent a /api/ds/query se construye for plugin — point-clickhouse-datasource, vertamedia-clickhouse-datasource y los Postgres/MySQL/MSSQL integrados todos need forms.
query_metrics
Ejecuta una expresión PromQL or LogQL. Omite from para una consulta instantanea.
Parameter | Type | Default | Description | |
| string | UID d la fuenta data o nombre exacto | ||
| string | Expresión PromQL / LogQL | ||
| string | Inicio del range, p. ej. | ||
| string |
| Fin del range / evaluation moment | |
| number |
|
| Step for range query |
| number |
| Limit of points per series |
search_dashboards
The definitive | Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| query | string | 20 | Subcadena del título |
| tag | string | | Tag of dashboard |
| limit | number | 20 | Maximum results |
get_dashboard
Parameter | Type | Description |
| string | UID del dashbooard from |
The vovelve los paneles (tillas aplanadas) with la fuenta de data and consultas crudas de each panel, además de las variables de plantilla and etc.
health
It compruba conexión. It sorts the two auth layers separately. failingLayer "cloudflare" means to run cloudflared access login (or login again); "grafana" means the stored session/credentials are dead or under-privileged — create una grafana-mcp-server login. `Reports who the credential corresponds to and how many datasources access to. In addition, will first be called when another of the tools stops.
Data frames are reflected in plain rows of a keyed field (Prometheus series are disambiguated by their labels), limited to GRAFANA_MAX_ROWS.
Commands
Coamn | What does it do |
| Ejecuta el MCP server en stdio — es lo que lanza el cliente de MCP |
| Ejecuta `T |
Variable | Requerido | Predeterminado | Descripción | |
| Sí | URL base de Grafana | ||
| No | Token de cuáort de servcio ( | ||
| No | Autenticación básica | ||
| No | Un valre del cooké | ||
| No | Archivo que tiene cualquiera de los anteriores; se infiere el formato, se relee en cada petición y las rotaciones de sesión se guardan de nuevo | ||
| No |
| Dónde | |
| No |
| Cuánto espera | |
| No |
|
| |
| No | auto | Token JWT de respaldo de Cloudflare Access | |
| No | (all) | Lista de las uids o nombres de allowed de datos separados por comas | |
| No |
| Filas Devueltas por cada frame | |
| No |
| Tiempo de espera de request en milisgundos |
Precedencia de las credenciales: GRAFANA_TOKEN → GRAFANA_USERNAME+PASSWORD → GRAFANA_SESSION → GRAFANA_CREDENTIAL_FILE → la sessión que guardó login → ~/.grafana-mcp-token si existe.
Lista de fuentes de datos permitidas
"ALLOWED_DATASOURCES": "OsirT4Bnz,Prometheus"list_datasources oculta todo lo rezado y las herramientas de consulta lo rechazan.
Autenticación
Grafana: iniciar sesión con tu propia cuenta (login)
grafana-mcp-server login te identifica y le pasa la sesión al server. Usa Chrome o Edge — el que esté instalado, usado solo como ventana de start stession, sin importar tu default is actual— mediante Playwright={ in a per(dicaldedicated under) — opens GRAFANA_URL/login and waits while you sign in — Google, GitHub, SAML, LDAP, or a simple password; the tool never sees or types your credentials. When Grafana sets its grafana_session cookie, the tool:
copies the session (and the
CF_Authorizationcookie, if Cloudflare Access is blocking) into~/.grafana-mcp/sessions/<host>.json(0600),remove Grafana's cookies from that browser profile, so the server is the session's unique owner,
calls
/api/uservia the server's own code and shows you who you are.
Playwright can only drive Chrome and Edge — and Arc cannot be automated at all; so the session window is always Chrome/Edge, never your default browser (which is left untouched). Only if you have neither Chrome nor Edge correctly set up doeslogin fall back on opening Grafana in your standard browser and telling you to copy the grafana_session once` from DevTools; that path also asks you to sign out of the tab afterward so it doesn't compete for session rotations.
From that moment on, the server is the one that keeps the session alive: Grafana responds to a marked stale session with 401 session.endpoint.rotate, the server calls POST /api/user/auth-tokens/rotate, saves the new cookie atomically, and retries. The session therefore lasts as long as the Grafana session's lifetime (30 days by default, 7 days of inactivity) — re-run login when health indicates failingLayer: "grafana".
Why this is the recommended path: it requires no Grafana admin. Anyone who can open Grafana in a browser can use the server, with exactly their permissions, and revoking access is the same as for anyone.
Why ahosted cookie usually dies in minutes
Grafana ≥ 10 rotates a session token every few minutes, and only one client gets the new one. If you copy grafana_session from DevTools while the tab remains open, the browser performs the rotation first and the copy is dead within minutes — that's the classic “the cookie stopped working” experience. login avoids it by removing the session from the browser; login --paste works fine as long as you then sign out (or clear the cookie) in the tab you copied from, because the server persists its own rotations.
Grafana: other credentials
Credential | Notes |
Service-account token ( | It never rotates. Requires a Grafana admin creating it (Administration → Service accounts, role Viewer) — |
Basic authentication | Only if the form is enabled — instances running on Google/GitHub OAuth usually have no password to give. |
| A session value taken directly from the environment. Works fine, but rotations can't be returned back, so it dies with the first rotation after a reboot. Prefer |
scripts/verify.sh verifies both layers and reports what the credential allows you to see — without ever printing it.
Cloudflare Access (optional)
If Grafana is behind Cloudflare Zero Trust, each request also needs a cf-access header (by the edge redirects, one page of sign in). The server solves it sol:
Reads the cached JWT from
~/.cloud flared/<hostname>-<audience>-token(which can be written viacloudflared access login).If missing or expired, execute
cloudflared access token --app=<GRAFANA_URL>(non-iterative).Uses the
CF_Authorizationcookie obtainebylogin(if not expired).Uses
CF_ACCESS_TOKENas a fallback.On a 302 from edge, drop/discard the cached token and retry only once with a fresh one.
The token is resolved lazily, in this: per request — never at start, so an expiring token corrections itself instead of failing every request until the client resties. Installing cloudflared is optional but recommended: its token refreshes on its own whenever yours active Cloudflare lasts; expired, while the cookie captured by login expires with Cloudflare session policy (generally 24h) and then needs to be signed-again.
brew install cloudflared # macOS; see Cloudflare's docs for Linux
cloudflared access login https://grafana.example.comCloudflareDirRecord dellows you may reach the host; Grafana's even have the CFREST JWT proves —, but Cloudflare does not sign you into Grafana lthe session is YOUR JWT; the CF JWT proves you can reach the host; Grafana then requests its own. A 302 / HTML answer is Cloudflare; a JSON 401 answer is Grafana. health reports which of the two succeeds.
No Cloudflare? Set GRAFANA_CF_ACCESS=off, or simply do not install cloud exported — the server be detaches the layer when it cannot find any token.
Project Structure
src/
main.ts # Entry point — `login` / `logout` commands, or the stdio MCP server
login.ts # Browser sign-in (Playwright over your default Chromium-based browser) → session store
default-browser.ts # Detect the default browser (macOS LaunchServices / xdg) and whether it can be driven
session-store.ts # ~/.grafana-mcp/sessions/<host>.json, 0600, atomic writes
grafana-client.ts # Grafana HTTP client: two auth layers, CF retry, session rotation, datasource cache
auth.ts # Grafana credential resolution (token / basic / session / file / login store)
cf-token.ts # Cloudflare Access token: cache → cloudflared → login cookie → env, lazy + retry
query-model.ts # Per-plugin /api/ds/query bodies (ClickHouse, SQL, PromQL/LogQL)
allowed-datasources.ts # Datasource allowlist
utils/
frames.ts # Data frames → rows
format-response.ts # Truncation, error results
tools/
list-datasources.tool.ts # list_datasources
query-sql.tool.ts # query_sql
query-metrics.tool.ts # query_metrics
search-dashboards.tool.ts # search_dashboards
get-dashboard.tool.ts # get_dashboard
health.tool.ts # health
scripts/
verify.sh # Check both auth layers; list what the credential can see
mint-token.sh # Turn a fresh admin browser session into a service-account tokenLicense
MIT
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- FlicenseCqualityDmaintenanceEnables AI-powered integration with Grafana instances through 52 MCP tools for dashboard management, Prometheus/Loki queries, alerting, and administrative functions. Supports complete Grafana functionality including metrics exploration, log analysis, and incident response through natural language.801
- AlicenseBqualityBmaintenanceEnables AI assistants to interact with Grafana dashboards, datasources, alerts, incidents, and monitoring data through 43 comprehensive tools. Supports querying Prometheus metrics, Loki logs, managing incidents, and dashboard operations with full authentication support.437623MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to query Prometheus metrics, monitor alerts, and analyze system health through read-only access to your Prometheus server with built-in query safety and optional AI-powered metric analysis.MIT
- AlicenseNot gradedqualityDmaintenanceQuery Grafana logs, metrics, and dashboards from Cursor. Enables the AI to call your Grafana instance via tools without leaving the editor.84Apache 2.0
Related MCP Connectors
Renders interactive Chart.js charts and dashboards inline in AI conversations.
Provide real-time data querying and visualization by integrating Tako with your agents. Generate o…
Connect AI assistants to your GitHub-hosted Obsidian vault to seamlessly access, search, and analy…
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/stonoyan04/grafana-mcp-server'
If you have feedback or need assistance with the MCP directory API, please join our Discord server