grafana-mcp-server
Grafana MCP Server
MCP-сервер на базе Model Context Protocol (MCP), который предоставляет ИИ-ассистентам доступ только на чтение ко всему, что уже видит ваш Grafana: метрикам Prometheus/Loki, источникам данных ClickHouse/Postgres/MySQL и дашбордам, которые уже собрала ваша команда. Задавайте вопросы на естественном языке и получайте ответы, подтверждённые реальными данными.
Работает с Claude Code, Claude Desktop и любым MCP-совместимым клиентом. Ваш проект может быть на любом языке — этот сервер работает независимо.
Как это работает
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 … │
└───────────────────┘ └──────────────────┘ └──────────┘ └────────────┘Сервер общается только с HTTP API Grafana. Grafana проксирует запрос к источнику данных со своими учётными данными, поэтому ассистент никогда не получает пароль базы данных, и видит ровно то, что видит пользователь Grafana, — не больше. Все запросы выполняются только на чтение (чтобы это было гарантировано, используйте учётные данные с ролью Viewer).
Related MCP server: Prometheus MCP Server
Требования
Node.js >= 18 или Docker (нужны только для запуска этого MCP-сервера)
Учётная запись Grafana, в которую можно войти — Google / SSO / пароль, что бы ни использовал ваш Grafana. Права администратора, сервисный аккаунт и API-токен не требуются:
grafana-mcp-server loginвыполнит вход в браузере и передаст сессию серверу (см. Аутентификация). Токен сервисного аккаунта тоже подойдёт, если он у вас есть.Установленный Chrome или Edge (используется только в качестве окна входа; ваш повседневный браузер может быть любым). Если ни одного из них нет,
loginпереключится на пошаговоое копикопирование cookie в браузере по умолчанию.
Быстрый старт
Вариант A: Node.js
1. Клонируйте и соберите
git clone https://github.com/stonoyan04/grafana-mcp-server.git
cd grafana-mcp-server
npm install
npm run buildВ результате будет скомпилированнный ссервер по пути dist/main.js.
2. Войдите
GRAFANA_URL=https://grafana.example.com npm run loginЕсли Chrome или Edge установлены (как браузер по умолчанию или просто присутствют на машине — это подходит почти всем, каким бы ни был ваш повседневный браузер), login открывает его dedicated окно — с отдельным одноразовым, не вашим обычным, профилем — на странице входа в Grafana. Войдите так же, как делаете это всегда. В тот момент, когда Grafana выдаст сессию, команда сохранит её, удалит из профиля, проверит и выведет:
[grafana-mcp-server] ✓ signed in as jane <jane@example.com>Ничего копировать, никаких токенов, ничего секретного в конфиг-файле. Если Grafana стоит за Cloudflare Access, вы входите в него в том же окне, и его cookie тоже будет захвачена. Не закрывайте и try to not close window until you see ✓. Сессия хранится в ~/.grafana-mcp/sessions/<host>.json (режим 600).
Playwright умеет управлять только Chrome/Chromium и Edge (Arc, например, вообще не автоматизируется), поэтому
loginиспользует один из них как окно входа, независимо от вашего браузера по умолчанию — ваш браузер по умолчанию никогда не затрагивается. Только если ни Chrome, ни Edge не установлены,loginоткроет Grafana в вашем браузере по умолчанию и под руководством — сделай это 개인적 копиgrafana_sessionиз DevTools.
Почему отдельное окно, а не моя открытая вкладка? Браузер никогда не передаёт свои cookie командной строке — эта изоляция и есть суть браузера, — поэтому
loginуправляет своим экземпляром в отдельном профиле и забирает сессию из него.
Принудительно указать браузер:
npm run login -- --browser chrome(илиmsedge,chromiumпослеnpx playwright install chromium, либо путь к Chromium-бинарнику).npm run login -- --pasteчитает cookie из stdin, не открывая браузера.
3. Настройка
Claude Code — одна команда, или эквивалентный блок .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 — тот же блок в конфигурационном файле:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
Примечание: Замените
/home/john/grafana-mcp-serverна фактический путь, куда вы схлонировали репозиторий. Единственная обязательная настройка —GRAFANA_URL: учётные данные берётся из сессии, которую сохранилlogin. Перезапустите клиент после добавления сервера.
У вас токен сервисного аккаунта? Добавьте
"GRAFANA_TOKEN": "glsa_…"вenvи пропуститеlogin. Или укажитеGRAFANA_CREDENTIAL_FILEна файл с правами0600, который его содержит, либо внедрите его из секрет-менеджера при запуске (например,charter secret exec … --exec -- node dist/main.js).
Вариант 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"
]
}
}
}Запустите login на хост-машине (GRAFANA_URL=… npm run login из локальной копии Node, так как в контейнере нет браузера) и смонтируйте ~/.grafana-mcp в режиме чтения/записи, как это будут обновлённые сессии назад в контейнер. Либо вообще не монтируйте, а передайте -e GRAFANA_TOKEN=glsa_…, если у вас есть токен сервисного аккаунта.
Почему
-iи не-t? MCP работает JSON по stdin/stdout. Ключ-iудерживает stdin открытым; TTY (-t) испортит поток.
Если Grafana за Cloudflare Access, смонтируйте свой хост-кэш токенов только для чтения — -v /home/john/.cloudflared:/root/.cloudflared:ro — и сначала выполните на хост-машине cloudflared access login https://grafana.example.com. Контейнер не может сам запускать cloudflared, поэтому он читает cмонтированный кэш (или CF_ACCESS_TOKEN); когда токен истечёт, снова выполните вход на хост-машине.
4. Исследуйте источники данных
List the Grafana datasourcesКаждому инструменту запросов нужен uid источника данных, а тип источника данных определяет, какой инструмент использовать: query_metrics? напомню, для пострики, или: dashboards — (для): datasourceUid... На самом assemblage: query_sql for ClickHouse/Postgres/MySQL, query_metrics for Prometheus/Loki. list_datasources говорит и то и другое.
5. Начинайте задавать вопросы
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 ClickHouseСовет:
get_dashboardвозвращает необработанный SQL / PromQL за каждой панелью. Переиспользовать запрос, который человек уже написал и которому доверяет, лучше, чем писать с нуля.
Инструменты
Сервер предоставляет 6 инструментов только для чтения:
list_datasources
Выводит источники данных с uid, name, type и какой инструмент запросов применяется. Без параметров.
query_sql
Выполняет SQL-запрос к источником семейств данных через Grafana и получает строки.
Параметр | Тип | По умолчанию | Описание |
| string | UID источника данных или его точное имя | |
| string | SQL, который нужно выполнить | |
| string |
| Начало диапазона (для макросов вида |
| string |
| Конец диапазона |
Запрос, отправляемый в /api/ds/query, для каждого plugin grafana-clickhouse-datasource, datasource — vertamedia-clickhouse-datasource, а также для встроенных Postgres/MySQL/MSSQL — все используют разную схему.
query_metrics
Выполняет выражение PromQL или LogQL. Опустите параметр from для мгновенного запроса (instant query).
Параметр | Тип | По умолчанию | Описание |
| string | UID источника данных или его точное имя | |
| string | Выражение PromQL / LogQL | |
| string | Начало диапазона, например | |
| string |
| Конец диапазона / время вычисления |
| number |
| Шаг запроса по диапазону |
| number |
| Максимум точек на курс |
5... search_dashboards
Параметр | Тип | По умолчанию | Описание |
| string | Подстрока заголовка | |
| string | Тег дашборда | |
| number |
| Максимальное количество результатов |
1... get_dashboard
Параметр | Тип | Описание |
| string | UID дашборда из |
Возвращает все панели (flat rows), с каждой панелью — источник данных и сырой запрос, е variables, шаблонно переменные и default time range.
6... health
Проверяет связность и различает два слоя аутентификации: "failingLayer": "cloudflare" обозначает cloudflared access login (или повторите login); "failingLayer": "grafana" обозначает, что сохранённые сессия/учётные данные мертвы или имеют недостаточно прав — выполните grafana-mcp-server login. Сообщает, кем проходит учтетная запись, и количество доступных датабаз. Параметров нет. Вызовите его первым, если другой инструмент подряд отказал.
Data frames сплющиваются в простые строки, ключом поля (серия Prometheus дездамибируется по меткам), пределах до GRAFANA_MAX_ROWS.
Команды
Команда | Что делает |
| Запускает MCP-сервера на stdio — это именно то, что запускает MCт клиент |
| Открывает ваш браузер по умолчанию (отдельный профиль), выполнит вход в Grafana и сохраняет сессию для сервера |
| Принудительно |
| Сохраняет значение |
| Удаляет сохранённую сессию |
npm run login / npm run logout выполняют то же самое из локальной копии проекта.
Конфигурация
Вся конфигурация задаётся через переменные окружения. При использовании login достаточен только GRAFANA_URL.
Переменная | Обязательно | По умолчанию | Описание |
| Да | Базовый URL Grafana | |
| Нет | Токен сервисного аккаунта ( | |
| Нет | Базовая аутентификация | |
| Нет | Значение cookie | |
| Нет | Файл, содержащий любое из указанных выше значений; формат определяеся автоматически, перечитывается при каждом запросе, ротированные сессии записываются обратно | |
| Нет |
| Папка, где |
| Нет |
| Сколько |
| Нет |
|
|
| Нет | auto | Запасной Cloudflare Access JWT |
| Нет | (all) | Разрешённый список uid или имён источников данных через запятую |
| Нет |
| Строк, возвращаемых на кадр (frame) |
| Нет |
| Тайм-аут запроса в миллисекундах |
Приоритет учётных данных: GRAFANA_TOKEN → GRAFANA_USERNAME+PASSWORD → GRAFANA_SSESSION → GRAFANA_CREDENTIAL_FILE → сессия, сохранённая login, → ~/.grafana-mcp-token, если он существует.
Разрешённый список источников данных
"ALLOWED_DATASOURCES": "OsirT4Bnz,Prometheus"list_datasources скрывает всё остальное, а инстременты запросов отклоняют его.
Аутентификация
Grafana: вход с вашей учётной записью (login)
grafana-mcp-server login обеспечивает вход в вашу учётную запись и уверяет сесию на сервер. Он управляет Chrom или Edge — темом, которая установна, и используется только как окно входа, независимо от вашего браузера по умолчанию — через Playwrite в отдельном профиле по ~/.grafana-mcp/browser, открывает GRAFANA_URL/login и ждёт, пока вы входимі — Google, GitHub, SAML, LDAAP или простой чоль; интрумент никогда не видит и не вводит ваши верите ля. Когда Grafana устанают свою cookie grafana_session, интрумент:
Копирует сиюсию (и cookie
CF_Authorization, если перед Grafana есть Cloudflare Access) в~/.grafana-mcp/sessions/<host>.json(0600),удаляет cookies Grafana из этого браузерного профиля, поэтому сервис станет единственным держателем сессии,
вызывает на
капиuserчерез собственную кодопую дорогу сервера и выполняет, кто вы.
Плеврайт может управлять только Chrome и Edge, а Arc всё вообще нельзя автоматизировать — поэтому окно входа всегда работает в Chrome/Edge и никогда в вашем браузере по умолчанию (остаётся нетронутым). Только если ни Chrome, ни Edge не установлены, login открывает Grafana в вашем браузере по умолчанию и пошагово проводит вас через копирование cookie grafana_session из DevTools один раз; при этом путь также попросит выйти из вкладки после этого, чтобы она не конкурировала за ротации сессии.
С этого момента сервер сам поддерживает сессию: Grafana отвечает на устаревшую сессию через 401 session.token.required, сервер вызывает POST /api/user/auth-tokens/rotate, атомарно сохраняет новую cookie и повторяет запрос. Поэтому сессия длится столько, сколько действует вход Grafana (по умолчанию 30 дней, 7 дней бездействия) — повторно выполните login в случаях, когда health сообщает failingLayer: "grafana".
Почему этот путь рекомендуется: он не требует настроек от администратора Grafana. Любой, кто может открыть Grafana в браузере, может использовать сервер с точно своими правами, и отзыв доступа происходит так же, как для любого пользователя.
Почему вставленная cookie обычно умирает через несколько минут
Grafana ≥ 10 ротирует токен сессии каждые несколько минут, и новый получает только один клиент. Если вы скопируете grafana_session из DevTools, пока вкладка остаётся открытой, браузер первую ротирует её, и копия в течение минут перестаёт действовать — это классический синдром «cookie перестала работать». login избегает этого, забирая сессию из браузера; login --paste также действует, если вы затем выйдете (или очистите cookie) в вкладке, из которой копировали, потому что сервер сохраняет свои ротации.
Grafana: другие учётные данные
Учётные данные | Примечание |
Токен сервисного аккаунта ( | Никогда не ротируется. Требует администратора Grafana для создания (Администрирование → Сервисные аккаунты, роль Пользователь) — |
Basic auth | Только если фора входа включена — инстансы на Google/GitHub OAuth обычно не имеюют пароля для предоставления. |
| Значение сессии на прямую из env. Работает, но ротации нельзя записать обратно, поэтому он умиравает при первом ротации после перезапуска. Предпочитайте |
scripts/verify.sh проверяет оба слоя и сообщает, что может видеть учётное — не выводя само значение.
Cloudflare Access (опционально)
Если Grafana находится за Cloudflare Zero Trust, каждый запрос также требует заголосов cf-access-token, либо edge перенаправит его на страницу входа до того, как Grafana увидет вызов. Сервер обрабатывает это автоматически:
Считывает закешированный JWT из
~/.cloudflared/<hostname>-<audience>-token(записанный черезcloudflared access login);Если отсутствует или истёк, запускает
cloudflared access token --app=<GRAFANA_URL>(неинтерактивно);Использует cookie
CF_Authorization, захваченную командойlogin(если не истекла);Взвращает к запасному
CF_ACCESS_TOKEN;При 302, если edge вернет закешированный токени и повторит один раз с новым.
Tokени разъяснится лениво, для качдору — никогда не один раз при запуске — поэтому истекающий токен самовосстанавливается вместо того, чтобы качдый Чouser вадался осшибкой до перезапуска клиента. Установка cloudflared опциональна, но рекомендована: его токен обновляется сам, любой до тех пор, пока ваш вход в Cloudflare не lawfulness gone, тогда как cookie, захваченная login, истекает сроком действия policy (usually 24h) и требует повторого login.
brew install cloudflared # macOS; see Cloudflare's docs for Linux
cloudflared access login https://grafana.example.comCloudflare не за логар за вас. Х фирmэй.
Cloudflare не за логар за вас в Grafana. CF JWT доказывает, что вам разрешено обращение к хосту; после этого Grafana требует своей учётной записи. Ответ 302 / HTML — это Cloudflare; ответ JSON 401 — это Grafana. health сообщает, кто такой.
Не за Cloudflare? Установите GRAFANA_CF_ACCESS=off, либо просто не ставьте cloudflared — сервер пропускает уровень, если токен не можно найдите.
Структура проекта
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
Available Tools
6 toolsget_dashboardA
Fetch a dashboard by uid and return its panels with their datasource and raw queries (SQL / PromQL / LogQL) — the fastest way to reuse a query someone already wrote, plus its template variables.
| Name | Required | Description | Default |
|---|---|---|---|
| uid | Yes | Dashboard uid from search_dashboards |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden. It discloses the read-only nature implicitly with 'Fetch' and specifies exactly what is returned, including panels, datasource, raw query languages, and template variables, which is sufficient for a simple read operation.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
A single sentence that front-loads the core action ('Fetch a dashboard by uid') and then adds valuable details about the return payload and use case. It is efficient with no fluff, though slightly long with the parenthetical and appositive.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple tool with one parameter and no output schema, the description covers the key aspects: input, output, and purpose. It says what the dashboard fetch returns, and the schema covers the parameter source, making it complete enough for an agent to invoke it correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, with 'uid' already described as 'Dashboard uid from search_dashboards'. The description mentions 'by uid' but adds no new meaning beyond the schema, so the baseline of 3 applies.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the action 'Fetch a dashboard by uid' and the resource, then details the output: panels, datasource, raw queries, and template variables. It distinguishes itself from siblings like query_sql and search_dashboards by emphasizing query reuse rather than execution or searching.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The phrase 'the fastest way to reuse a query someone already wrote' provides clear context for when to use this tool. It implicitly excludes query execution tools, though it does not explicitly name alternatives or state when not to use it, giving clear context without exclusions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
healthA
Check Grafana connectivity and authentication: which auth layer (Cloudflare Access vs Grafana credential) is failing if any, who the credential authenticates as, and how many datasources it can see. Call this first whenever another tool fails. failingLayer=grafana means the developer must run grafana-mcp-server login again.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden of behavioral disclosure. It reveals what the tool inspects (auth layers, credential identity, datasource visibility), the meaning of the failingLayer value, and the remediation step. It does not explicitly state whether the check is read-only, but a health check's non-mutating nature is strongly implied and no contradiction exists.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Three sentences, all substantive. The main purpose is front-loaded, the diagnostic details are compactly listed, and the remediation instruction is concrete. No filler or redundancy.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a zero-parameter diagnostic tool with no output schema and no annotations, the description is complete: it states what is checked, how results are interpreted, and what action to take on a specific failure mode. It gives the agent enough to decide when to call it and what to do with its output.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The tool has zero parameters and the input schema is empty, so there is nothing for the description to clarify about parameters. Per the zero-parameter baseline, a score of 4 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description opens with a specific verb and resource: 'Check Grafana connectivity and authentication.' It enumerates exact diagnostic outputs (failing auth layer, credential identity, visible datasource count), which distinguishes this health-check tool from sibling data-access tools like query_sql and list_datasources.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description gives an explicit trigger: 'Call this first whenever another tool fails.' It also specifies a follow-up action when failingLayer=grafana. It does not spell out when not to use it, but the context makes the tool's diagnostic role clear relative to the sibling tools.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
list_datasourcesA
List Grafana datasources (uid, name, type). Start here: every query tool needs a datasource uid, and the type decides whether to call query_sql or query_metrics.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure. It correctly implies a read-only listing operation, but does not explicitly mention pagination, rate limits, or any side effects. For a simple list operation, this is adequate but not thorough; it lacks explicit confirmation of safety or response limitations.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is two compact sentences. The first states the core function and return fields; the second immediately provides actionable guidance on next steps. There is no redundancy or filler, and the critical scoping information is front-loaded.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a tool with no parameters, no output schema, and low complexity, the description fully covers what the agent needs: what it returns, and how to proceed. It is complete and self-sufficient for correct invocation and routing to sibling tools.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The tool has zero parameters, so the schema is inherently complete. The description adds no parameter details because none exist. Per the rubric, a baseline of 4 is appropriate for zero parameters, and the description does not need to explain anything about parameters.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's function: listing Grafana datasources with specific fields (uid, name, type). It also differentiates from sibling query tools by framing itself as the prerequisite step, so an agent can immediately understand what it does and how it differs.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides explicit usage guidance: it tells the agent to start here whenever querying is needed, explains that a datasource uid is required, and directs the agent to choose between query_sql and query_metrics based on the type. This clearly distinguishes when to use this tool versus the query siblings.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
query_metricsA
Run a PromQL (Prometheus/Thanos/Mimir) or LogQL (Loki) expression against a datasource through Grafana. Omit from for an instant query; pass from/to for a range query.
| Name | Required | Description | Default |
|---|---|---|---|
| to | No | Range end / instant evaluation time, e.g. "now" | now |
| expr | Yes | PromQL or LogQL expression, e.g. sum by (topic) (increase(kafka_topic_partition_current_offset[7d])) | |
| from | No | Range start, e.g. "now-24h". Omit for an instant query evaluated at `to`. | |
| stepSeconds | No | Range-query step in seconds (default 300) | |
| datasourceUid | Yes | Datasource uid (or exact name) from list_datasources | |
| maxDataPoints | No | Cap on points per series (default 1000) |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description must disclose behavioral traits such as read-only status or side effects. It only mentions the instant vs. range query modes, but does not state whether the operation is non-destructive, what it returns, or any datasource implications. This leaves the agent to assume safety on a tool that executes arbitrary expressions.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is two sentences with no filler. It front-loads the purpose and then gives a succinct behavioral directive. Every word earns its place, making it easy for an agent to parse quickly.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The description covers the essential query modes and ties to datasources, but omits any mention of return value structure or error handling, which is significant given there is no output schema. The schema documents parameters thoroughly, so the core usage is clear, but the lack of result details leaves a minor gap for such a complex query tool.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema fully documents all six parameters with descriptions, so the baseline is 3. The description adds only a rephrased note about omitting `from` for instant queries, which is already present in the schema's `from` field. It adds no new meaning for parameters like `stepSeconds` or `maxDataPoints`.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a precise action: running a PromQL or LogQL expression against a Grafana datasource. It clearly distinguishes this tool from the SQL-oriented sibling (query_sql) by explicitly naming the expression languages, leaving no ambiguity about which tool to use for metric or log queries.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description explicitly instructs when to omit or include the `from` parameter to switch between instant and range queries, providing clear context for invocation. Though it doesn't explicitly name query_sql as the SQL alternative, the expression-language distinction effectively routes the agent to the correct tool.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
query_sqlA
Run raw SQL against a SQL-family datasource (ClickHouse, Postgres, MySQL, MSSQL) through Grafana and get rows back. Use list_datasources first to get the uid. Read-only by convention — use a Viewer credential.
| Name | Required | Description | Default |
|---|---|---|---|
| to | No | Range end, e.g. "now" | now |
| sql | Yes | The SQL to run. Use the database column names, e.g. snake_case, not the app-level ones. | |
| from | No | Range start for $__timeFilter-style macros, e.g. "now-30d" or epoch ms | now-6h |
| datasourceUid | Yes | Datasource uid (or exact name) from list_datasources |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the burden of behavioral disclosure. It mentions read-only by convention and returning rows, which is helpful, but omits other traits like error handling, rate limits, or potential side effects beyond the stated convention. It adds some value but is not comprehensive.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is exactly two sentences with no redundant words. The core purpose is front-loaded, and the usage note follows immediately, making it easy to scan and internalize.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a raw SQL tool with a straightforward purpose, the description covers purpose, prerequisites, and read-only behavior. It does not detail time-range semantics (covered in schema) or return size limits, but given the tool's nature and lack of output schema, it is sufficiently complete for an agent to call it correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so the schema already documents all parameters. The description does not add new parameter-level detail; it only reinforces the datasourceUid dependency on list_datasources, which is already in the schema. Baseline 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool runs raw SQL against SQL-family datasources and returns rows, using specific verbs (run) and resources (SQL datasource). It distinctively positions itself from siblings like query_metrics by emphasizing 'raw SQL' and explicit datasource family names.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description gives a clear prerequisite ('Use list_datasources first to get the uid') and notes a read-only convention. However, it does not explicitly compare with alternatives such as query_metrics or state when not to use this tool, leaving selection to inference.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
search_dashboardsA
Search dashboards by title or tag. Use it to find what is already instrumented before writing a query from scratch, then get_dashboard to read the panel queries.
| Name | Required | Description | Default |
|---|---|---|---|
| tag | No | Filter by dashboard tag | |
| limit | No | Max results (default 20) | |
| query | No | Title substring, e.g. "kafka" |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description must disclose behavior. It states the search functionality and implies read-only use ('find what is already instrumented'), but does not mention potential limitations, pagination, or return format. It adds only minimal behavioral detail beyond the tool name and schema, leaving the agent to infer common search semantics.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is two concise sentences. The first sentence gives the core action and criteria, front-loading the most important information. The second sentence adds usage guidance with no fluff. Every word earns its place, achieving conciseness without losing substance.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple search tool with all optional parameters and no output schema, the description is mostly complete. It explains the tool's purpose and provides a usage workflow, including the next step. It does not explicitly mention the return type (e.g., a list of dashboard references), but the follow-up 'then get_dashboard' implies that the results are dashboard identifiers, making the missing detail a minor gap.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100% (all three parameters have descriptions), so the baseline is 3. The description adds usage context (e.g., 'find what is already instrumented') but does not add new semantic meaning beyond the schema's 'Title substring' and 'Filter by dashboard tag'. It reinforces but doesn't extend the parameter docs.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific verb ('Search'), resource ('dashboards'), and criteria ('by title or tag'), making the tool's purpose immediately clear. It also differentiates from get_dashboard by implying that search_dashboards finds dashboards while get_dashboard reads their content, and from query tools by focusing on discovery rather than data retrieval.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description explicitly specifies when to use the tool ('before writing a query from scratch') and provides a follow-up action ('then get_dashboard to read the panel queries'). This gives the agent a clear workflow and implies when not to use it (e.g., when querying data directly, use query_sql/query_metrics).
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
6 tool updates
v1.0.0- First observed
get_dashboard - First observed
health - First observed
list_datasources - First observed
query_metrics - First observed
query_sql - First observed
search_dashboards
TDQS
Scored across 6 tools
Each tool targets a clearly distinct action: listing datasources, querying SQL, querying metrics/logs, searching dashboards, fetching dashboards, and checking health. The only similar pair, query_sql and query_metrics, is explicitly disambiguated by datasource type in list_datasources.
All names use lowercase snake_case and mostly follow a verb_noun pattern: list_datasources, query_sql, query_metrics, search_dashboards, get_dashboard. The single outlier is health, which is a noun rather than a verb_noun name, but it is short and idiomatic enough not to cause confusion.
Six tools is a well-scoped size for a Grafana MCP server focused on querying data and reusing existing dashboards. Each tool has a distinct role, and there is no sense of bloat or an overly thin surface.
The set covers the full discovery-to-query workflow: identify datasources, run the appropriate query type, search for existing dashboards, extract panel queries, and diagnose auth/connectivity failures. For a read-oriented Grafana data exploration server, there are no obvious dead ends or missing critical operations.
Maintenance
Related MCP Connectors
Connects AI assistants to TrackingTime for querying time entries, projects, tasks, customers, and team data using natural language.
Read-only Google Search Console and Google Analytics for AI agents.
- mcpOAuthcom.vibgrate
Query your team's drift, vulnerability, and upgrade data from any AI assistant. OAuth 2.1, 51 tools.
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Related MCP Servers
- AlicenseBqualityCmaintenanceEnables 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.43715 npm3MIT
- 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.2 npm4Apache 2.0
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to query Grafana dashboards, alerts, and datasources for observability insights and incident investigation.MIT