MCP.so
登录

Grafana MCP Server (Official)

@grafana

基本信息

分类

开发工具

许可证

Apache-2.0

传输方式

stdio

作者

grafana

关于 Grafana MCP Server

适用于 Grafana 的 MCP 服务器

Grafana MCP Server 配置

使用下面的配置,将此服务器添加到你的 MCP 客户端。

{
  "mcpServers": {
    "grafana": {
      "command": "uvx",
      "args": [
        "mcp-grafana"
      ],
      "env": {
        "GRAFANA_URL": "http://localhost:3000",
        "GRAFANA_SERVICE_ACCOUNT_TOKEN": "<your service account token>"
      }
    }
  }
}

Grafana MCP Server 工具

79

Add a note (userNote activity) to an existing incident's timeline using its ID. The note body can include URLs which will be attached as context. Use this to add context to an incident.

Manage Grafana alerting routing configuration, including notification policies, contact points and time intervals. Notification policies define how alerts are grouped, routed, and which contact points receive them. Time intervals define active/mute periods for alert notifications. When to use: - Understanding how alerts are routed to contact points/receivers - Debugging why an alert went to a specific receiver - Checking grouping, timing, or mute interval settings Does not show alert rule configuration or state.

Create Grafana-managed contact points for alert notifications using operation 'create_contact_point'. Requires name, type and integration-specific settings. Returns uid, name and type without settings or secrets. Contact points remain editable in the Grafana UI by default. External Alertmanager receivers are not supported. Does not list or inspect existing contact points.

List and inspect Grafana alert rules with filtering capabilities. When to use: - Understanding why an alert is or isn't firing - Auditing alert rule configuration (queries, conditions, labels, notification settings) - Finding alert rules by state, folder, group, or name - Comparing rule versions to see what changed Read-only: does not create, update, or delete rules, and does not show notification routing.

Create, update, and delete Grafana alert rules. When to use: - Creating, updating, or deleting alert rules Operation 'update' replaces the whole rule: it takes all required fields, not only the changed ones. Does not list or inspect rules, and does not manage notification routing.

List and inspect Grafana alerting silences. A silence temporarily suppresses notifications for alerts whose labels match a set of matchers. Operations: - 'list': list existing silences. Optionally filter by rule_uid (matches the __alert_rule_uid__ label) or by matchers. - 'get': retrieve a single silence by silence_id. When to use: - Inspecting which alerts are currently silenced and why Read-only: does not create, update, or delete silences, and does not show alert rules or notification routing.

Create, update, and delete Grafana alerting silences. A silence temporarily suppresses notifications for alerts whose labels match a set of matchers, without changing the alert rules themselves. Operations: - 'create': create a new silence. Requires matchers, starts_at, ends_at (RFC3339) and comment. - 'update': modify an existing silence by silence_id. Requires matchers, starts_at, ends_at and comment. The id is only kept when the posted matchers and starts_at match the stored ones, so pass back the stored starts_at of the silence; otherwise Alertmanager expires the old silence and returns a new id. - 'delete': expire/remove a silence by silence_id. When to use: - Muting noisy or expected alerts during maintenance windows Does not list or inspect silences, change alert rules, or manage notification routing.

Audits a Loki label strategy and optionally diagnoses query performance. Returns per-label verdicts, missing base labels, normalisation issues, and a recommended set. Pass datasourceUid for live cardinality or labels for static scoring; both may be combined.

Check datasource health. Filter by type or UIDs; omit both to check all.

Create a new annotation on a dashboard or panel. Set format to 'graphite' and provide 'what' for Graphite-format annotations.

Create a datasource in two steps. Called with only the type, it returns the plugin's field schema and creates nothing. Called with the type, the display name in the top-level name argument, schemaReviewed=true, and field values in the fields map, it creates the datasource. The plugin for the type must already be installed. Secrets (passwords, tokens) are not accepted. Returns UID, health check, and a config page link.

Create a Grafana folder. Provide a title and optional UID. Returns the created folder.

Create a new Grafana incident. Requires title, severity, and room prefix. Allows setting status, labels and custom fields. Creating an incident may notify or page many people.

Create a Grafana snapshot from a full dashboard payload. Supports optional expiration and external snapshot fields.

Permanently delete an annotation by ID. The annotation cannot be recovered afterwards.

Delete a Grafana snapshot by snapshot key.

Compare two complete traces. Returns a compact summary and includes the full span-level patch when it is at most 64 KiB. Request trace-patch-v0 only when full details are required; full patches are not size-bounded.

Generate deeplink URLs for Grafana resources. Supports dashboards (requires dashboardUid or provisioningPreview), panels (requires dashboardUid or provisioningPreview, plus panelId), and Explore queries (requires datasourceUid and optionally queries). For dashboard and panel links, provisioningPreview points at a dashboard staged on a provisioning repository branch (e.g. a git-sync PR preview). For explore links, the time range and queries are embedded inside the Grafana explore state. Set shorten=true to also attempt a /goto/<uid> short URL; if shortening fails, the full deeplink is returned.

Get a specific alert group from Grafana OnCall by its ID. Returns the full alert group details, including the most recent alert and its raw payload when the OnCall API provides them. Alert payloads carry integration-specific fingerprints (for example Sentry's payload.data.event.hashes or Alertmanager's payload.alerts[].fingerprint) that identify recurring alerts across different alert groups.

Returns annotation tags with optional filtering by tag name. Only the provided filters are applied.

Fetch Grafana annotations using filters such as dashboard UID, time range and tags.

Get assertion summary for a given entity with its type, name, env, site, namespace, and a time range

Get the list of users currently on-call for a specific Grafana OnCall schedule ID. Returns the schedule ID, name, and a list of detailed user objects for those currently on call.

Retrieves the complete dashboard, including panels, variables, and settings, for a specific dashboard identified by its UID. Pass optional version to load a saved snapshot instead of the current dashboard. Saved snapshots are fetched through Grafana's legacy versions API, so 'apiVersion' is omitted and 'meta' is partial: only version, createdBy, and created are populated. For current (non-versioned) fetches, the response includes 'apiVersion' and 'isV2': when 'isV2' is true the dashboard uses the v2 schema (panels live under 'elements' keyed by name, arranged by 'layout'; variables under 'variables'), otherwise it is classic v1 ('panels[]' with 'templating.list'). The full JSON of a large dashboard can be very large.

Retrieve panel queries from a Grafana dashboard. Supports all datasource types (Prometheus, Loki, CloudWatch, SQL, etc.) and row-nested panels. Optionally filter to a specific panel by ID with `panelId`. Optionally provide `variables` for template variable substitution, which populates `processedQuery` and `requiredVariables` fields. Returns an array of objects with fields: title, query (raw expression), datasource (object with uid and type), and optionally processedQuery, refId, requiredVariables, and target. Targets built in a visual editor (CloudWatch metric search, InfluxDB query builder) have no string expression: those return an empty query plus `target`, the panel's raw query JSON. They can be executed as panel queries but not as standalone expressions.

Get specific parts of a dashboard using JSONPath expressions to minimize context window usage. JSONPath targets the dashboard's native schema. Classic v1 paths: '$.title' (title), '$.panels[*].title' (all panel titles), '$.panels[0]' (first panel), '$.templating.list' (variables), '$.annotations.list' (saved dashboard annotation queries/definitions), '$.tags' (tags), '$.panels[*].targets[*].expr' (all queries). v2 dashboards (isV2 true) use different paths: '$.title', '$.elements' (panels, keyed by name), '$.variables' (variables), '$.annotations'.

Get a compact summary of a dashboard including title, panel count, panel types, variables, and other metadata without the full JSON. Use this for dashboard overview and planning modifications without consuming large context windows.

Retrieves detailed information about a specific datasource by UID or name. Returns the full datasource model, including name, type, URL, access settings, JSON data, and secure JSON field status. Provide either uid or name; uid takes priority if both are given.

Fetch a Grafana documentation page. Set outline_only=true to get the heading structure first, then call again with a section name for bounded retrieval.

Get a single incident by ID. Returns the full incident details including title, status, severity, labels, custom fields, timestamps, and other metadata.

Get detailed information for a specific Grafana OnCall shift using its ID. A shift represents a designated time period within a schedule when users are actively on-call. Returns the full shift details.

Render a Grafana dashboard panel, full dashboard or Explore view as a PNG image. Returns the image as base64 encoded data. Requires the Grafana Image Renderer service to be installed. Exactly one of dashboardUid (for stored dashboards), provisioningPreview (for dashboards staged on a provisioning repository branch, e.g. a git-sync PR) or explore (an ad-hoc datasource query rendered in Explore, no saved dashboard needed) must be supplied. Use this for generating visual snapshots of dashboards for reports, alerts, or presentations.

Check whether a Grafana plugin is installed and retrieve its details (name, version, type, enabled status). Returns installed=false when the plugin is not found.

Get a Grafana snapshot by key, including snapshot metadata and dashboard payload.

Retrieve a specific trace by ID

Retrieve TraceQL reference documentation with examples, covering attribute filters, aggregates, structural operators, and metrics queries. Consult this before writing a non-trivial TraceQL query, or after one returns an error or no results.

Make an authenticated HTTP request to the Grafana API. Similar to 'gh api' for GitHub. Supports any Grafana API endpoint with optional jq-style response filtering. Use this for API endpoints that don't have a dedicated tool.

Install a Grafana plugin by its plugin ID. When version is omitted, the tool looks up the latest version and returns it without installing; supplying a version installs that version.

List alert groups from Grafana OnCall with filtering options. Supports filtering by alert group ID, route ID, integration ID, state (new, acknowledged, resolved, silenced), team ID, time range, labels, and name. For time ranges, use format '{start}_{end}' ISO 8601 timestamp range (e.g., '2025-01-19T00:00:00_2025-01-19T23:59:59' for a specific day). For labels, use format 'key:value' (e.g., ['env:prod', 'severity:high']). Returns a list of alert group objects with their details. Supports pagination.

List saved versions of a Grafana dashboard. Returns compact metadata: version number, author, timestamp, and save message. A version number can be passed to the dashboard fetch to load that snapshot.

List all configured datasources in Grafana. Use this to discover available datasources and their UIDs. Supports filtering by type and/or name (case-insensitive substring match) and pagination.

List the custom fields configured for Grafana incidents, including their type and, for select fields, the options that may be chosen.

List Grafana incidents. Allows filtering by status ('active', 'resolved') and optionally including drill incidents. Returns a preview list with basic details, and custom field values if requested.

Lists all available label/field names (keys) found in logs within a specified Loki or VictoriaLogs datasource and time range. Returns a list of unique label strings (e.g., `["app", "env", "pod"]`). If the time range is not provided, it defaults to the last hour. Optionally narrow the search to a subset of streams with `matcher` (e.g. `{namespace="prod"}`).

Retrieves all unique values associated with a specific `labelName` within a Loki or VictoriaLogs datasource and time range. Returns a list of string values (e.g., for `labelName="env"`, might return `["prod", "staging", "dev"]`). Useful for discovering filter options. Defaults to the last hour if the time range is omitted. Optionally narrow the search to a subset of streams with `matcher` (e.g. `{namespace="prod"}`) — for example, to list `service` values seen only within a specific namespace.

List Grafana OnCall schedules, optionally filtering by team ID. If a specific schedule ID is provided, retrieves details for only that schedule. Returns a list of schedule summaries including ID, name, team ID, timezone, and shift IDs. Supports pagination.

List teams configured in Grafana OnCall. Returns a list of team objects with their details. Supports pagination.

List users from Grafana OnCall. These are OnCall users (separate from Grafana users). Can retrieve all users in the OnCall directory, a specific user by ID, or filter by username. Returns a list of user objects with their details. Supports pagination.

List label names in a PromQL-compatible datasource (Prometheus, Thanos, Mimir, Cloud Monitoring, etc.). Allows filtering by series selectors and time range.

Gets the values for a specific label name in a PromQL-compatible datasource (Prometheus, Thanos, Mimir, Cloud Monitoring, etc.). Allows filtering by series selectors and time range.

List Prometheus metric metadata. Returns metadata about metrics currently scraped from targets. Note: This endpoint is experimental.

Lists metric names in a PromQL-compatible datasource (Prometheus, Thanos, Mimir, Cloud Monitoring, etc.). Filters metric names using the provided regex. Supports pagination (page * limit must not exceed 10000) and an optional time range to restrict results to metrics active within that window. Cloud Monitoring ignores the time range.

List provisioning repositories (e.g. git-sync sources) configured for this Grafana instance. Returns each repository's slug along with its source URL, branch, path, sync state, and health. The `name` is the slug used to render not-yet-applied dashboard previews.

Lists all available label names (keys) found in profiles within a specified Pyroscope datasource, time range, and optional label matchers. Label matchers are typically used to qualify a service name ({service_name="foo"}). Returns a list of unique label strings (e.g., ["app", "env", "pod"]). Label names with double underscores (e.g. __name__) are internal and rarely useful to users. If the time range is not provided, it defaults to the last hour.

Lists all available label values for a particular label name found in profiles within a specified Pyroscope datasource, time range, and optional label matchers. Label matchers are typically used to qualify a service name ({service_name="foo"}). Returns a list of unique label strings (e.g. for label name "env": ["dev", "staging", "prod"]). If the time range is not provided, it defaults to the last hour.

Lists all available profile types available in a specified Pyroscope datasource and time range. Returns a list of all available profile types (example profile type: "process_cpu:cpu:nanoseconds:cpu:nanoseconds"). A profile type has the following structure: <name>:<sample type>:<sample unit>:<period type>:<period unit>. Not all profile types are available for every service. If the time range is not provided, it defaults to the last hour.

List Grafana dashboard snapshots with optional query and result limit filters.

List available attribute names for TraceQL queries. Without a scope (resource, span, etc.) the response can be very large.

List values for a fully scoped attribute name (e.g. resource.service.name). Useful for discovering what values exist for a specific attribute.

Executes a log query against a Loki or VictoriaLogs datasource and returns matching log entries (or metric samples on Loki). Defaults to the last hour, a limit of 10 entries, and 'backward' direction (newest first). The `logql` parameter takes LogQL on Loki and LogsQL on VictoriaLogs (e.g., Loki: `{app="foo"} |= "error"`; VictoriaLogs: `{app="foo"} "error"`). To count matching log lines precisely, use a `count_over_time()` metric query with queryType='instant'. For broad queries that match many lines, set `format` to 'compact' to group results by stream and avoid repeating label metadata on every line. If this server enables the Loki cost guardrail, expensive queries are rejected before execution: query cost is bytes SCANNED, determined only by the stream selector and time range — line filters (|=) and parsers (| json) reduce what is returned, not what is scanned. Use a stream selector with at least one selective positive label matcher (never `{}`, `=~".*"`/`=~".+"`, or negative-only matchers), keep time ranges narrow; rejected queries return rewrite guidance.

Retrieves detected log patterns from a Loki datasource for a given stream selector and time range. Returns a list of patterns, each containing a pattern string and a total count of occurrences. Patterns help identify common log structures and anomalies. The `logql` parameter must be a stream selector (e.g., `{job="nginx"}`) and does not support line filters or aggregations. Defaults to the last hour if the time range is omitted. **Not supported on VictoriaLogs** datasources - use a `| stats` pipeline instead.

Retrieves index-level statistics about log streams matching a given selector within a Loki or VictoriaLogs datasource and time range. Returns an object containing the count of streams, chunks, entries, and total bytes (e.g., `{"streams": 5, "chunks": 50, "entries": 10000, "bytes": 512000}`). **Important**: the `entries` count reflects storage-level index entries (chunk metadata), NOT the number of individual log lines matching the selector. Counting actual matching log lines requires a `count_over_time()` LogQL metric query. On VictoriaLogs only `entries` is populated; the other fields remain zero. The `logql` parameter **must** be a simple label selector (e.g., `{app="nginx", env="prod"}`) and does not support line filters, parsers, or aggregations. Defaults to the last hour if the time range is omitted.

Query a PromQL-compatible datasource (Prometheus, Thanos, Mimir, Cloud Monitoring, etc.) using a PromQL expression. Supports instant queries (single point) and range queries (time range). Time: RFC3339 or relative expressions like 'now', 'now-1h'.

Query Prometheus histogram percentiles from classic histogram '_bucket' series. Generates histogram_quantile PromQL. Example: metric='http_duration', percentile=95, labels='job="api"' Time formats: 'now-1h', '2026-02-02T19:00:00Z', '1738519200000' (Unix ms)

Unified Pyroscope query tool for fetching profiles or metrics from Pyroscope. Profile data shows WHICH functions consume resources; metrics data shows WHEN consumption spiked. Use query_type="both" for complete analysis in one call. query_type options (extends Grafana's PyroscopeQueryType): - "profile": returns profile data (shape controlled by format) - "metrics": returns time-series data points - "both" (default): returns both profile and metrics in one response format options (shape of the profile data): - "table" (default): per-function table with flat (self) and cumulative values, ranked by flat - "dot": call graph in Graphviz DOT format; nodes are per source line, so one function may span several nodes

Compute trace-derived metrics using a TraceQL metrics query. The syntax is unlike PromQL. Use type 'instant' for a single value or 'range' for a time series (default). Instant queries over large time ranges may timeout — keep the window under 15 minutes for instant, or use range instead.

Search Grafana dashboards by query and/or folderUid, tag, and starred. Returns matching dashboards with title, UID, folder, tags, and URL.

Search Grafana documentation. Returns matching pages with title, URL, description, and product. Call with no query to list available product groups.

Search for Grafana folders by a query string. Returns matching folders with details like title, UID, and URL.

Search the Grafana plugin catalog by keyword, purpose, or partial name (e.g. 'azure monitoring', 'loki', 'database'). Returns results sorted by trust: official Grafana Labs plugins first, then commercial partner plugins, then community plugins, each with its exact pluginId. Results include warnings for enterprise-only or Angular-based plugins.

Search for traces using TraceQL queries

Generates an Alloy loki.process snippet enforcing an approved label set via stage.label_keep, with optional log-level normalisation and soft-enforcement placeholders.

Update the state of a Grafana OnCall alert group: acknowledge, unacknowledge, resolve, or unresolve it by ID. Returns the alert group's resulting OnCall state (one of new, acknowledged, resolved, silenced), or a stateWarning explaining why that state could not be read back after a successful update.

Updates the provided properties of an annotation by ID. Only fields included in the request are modified; omitted fields are left unchanged.

Create or update a dashboard. Returns the saved dashboard UID and dashboard link in the 'url' field, using the instance public URL when available. Two modes: (1) Full JSON — provide 'dashboard' for new dashboards or complete replacements. (2) Patch — provide 'uid' + 'operations' to make targeted changes to an existing dashboard. One of these two modes is required; 'folderUid', 'message', and 'overwrite' are supplementary and do nothing on their own. Dashboard authoring guidance: if a saved query must support one, many, or All values from a multi-select variable inside a regex expression or matcher, save '${var:regex}' rather than plain '$var'. Saved dashboard annotation queries/definitions live in dashboard JSON under 'annotations.list'; annotation events are stored separately and are not part of the dashboard JSON. For stat panels over the current dashboard range, make the query return the range-level result the stat should display; panel-side reduction only reduces returned series and does not compute peak-over-range or ratio-of-peaks semantics for you. Patch operations support JSONPaths like '$.panels[0].targets[0].expr', '$.panels[1].title', '$.panels[2].targets[0].datasource', '$.templating.list/-', and '$.annotations.list/-'. Append to arrays with '/- ' syntax: '$.panels/- '. Remove by index: {"op": "remove", "path": "$.panels[2]"}. Multiple removes on the same array are automatically reordered to avoid index-shifting issues. Note: only numeric array indices are supported in patch paths; filter expressions like [?(@.id==2)] and wildcards like [*] are not supported. Schema: prefer v2 for new dashboards; if this Grafana lacks v2 the save fails saying so, then send v1. Keep an existing dashboard in its stored schema (indicated by 'isV2'/'apiVersion' on the fetched dashboard). A body with top-level 'elements'/'layout' is saved as v2. Minimal v2 body: {"title":"T","timeSettings":{"from":"now-6h","to":"now"},"variables":[],"elements":{"p1":{"kind":"Panel","spec":{"id":1,"title":"Up","vizConfig":{"kind":"VizConfig","group":"timeseries","spec":{}},"data":{"kind":"QueryGroup","spec":{"queries":[{"kind":"PanelQuery","spec":{"refId":"A","query":{"kind":"DataQuery","group":"prometheus","datasource":{"name":"<ds uid>"},"spec":{"expr":"up"}}}}]}}}}},"layout":{"kind":"GridLayout","spec":{"items":[{"kind":"GridLayoutItem","spec":{"x":0,"y":0,"width":24,"height":8,"element":{"kind":"ElementReference","name":"p1"}}}]}}}. For tabs, layout is {"kind":"TabsLayout","spec":{"tabs":[{"kind":"TabsLayoutTab","spec":{"title":"A","layout":<GridLayout>}}]}}.

Update non-secret datasource fields by UID in two steps. Called with only the uid, it returns the datasource's field schema and changes nothing. Called with the uid, schemaReviewed=true, and the changed values in the fields map, it applies the update. Omitted fields are preserved. Secrets (passwords, tokens) cannot be changed. Returns an update message and a health check.

Update an existing Grafana incident by ID. Allows changing the status ('active' or 'resolved'), the severity, the title, and custom field values. Only the provided fields are changed. Use this to resolve an incident, to correct its severity or title, or to fill in custom fields as part of an on-call workflow.

Get information about the current Grafana identity: login, email, name, whether it is a Grafana (server) admin, the current organization, and the organizations it can access (with roles). Call this to discover which orgId values are valid before targeting a specific organization, and to understand the identity's capabilities.

Validate a file in a provisioning repository at a given branch or commit by dry-run applying it. Returns whether the file would be accepted (valid), what resource action would result (create/update), the target resource type, and any structured validation errors. Use to confirm a draft dashboard or other resource will be accepted before merging or applying a PR — this is the same validation surface that Grafana's PR commenter reports.

概览

什么是 Grafana MCP Server (Official)?

Grafana MCP Server (Official) 是 Grafana Labs 官方开源的 Grafana MCP server(grafana/mcp-grafana),让 AI 助手可以在你的 Grafana 实例中搜索仪表板、查询 Prometheus、Loki 等数据源,并管理告警、事件(Incident)和 OnCall。

它默认通过 stdio 在本地运行(也可以作为 HTTP 服务运行),并使用服务账号令牌(service account token)向 Grafana 认证。它同时支持自托管 Grafana 和 Grafana Cloud,完整功能需要 Grafana 9.0 或更高版本。Grafana Cloud 用户也可以改用 Grafana 单独托管的 Cloud MCP Server,详见下文。

如何使用 Grafana MCP Server (Official)?

前置条件

  1. 一个 Grafana 实例(9.0+)或 Grafana Cloud stack。
  2. 一个带令牌的 Grafana 服务账号。按你要使用的工具为它授予相应的 RBAC 权限;README 提到,直接分配内置的 Editor 角色更简单,但限制更少。
  3. 推荐使用 uvx 安装,需要 uv;也可以使用 Docker 或 mcp-grafana 二进制文件。

设置两个环境变量:GRAFANA_URL(例如 http://localhost:3000,Grafana Cloud 则为 https://myinstance.grafana.net)和 GRAFANA_SERVICE_ACCOUNT_TOKEN。旧的 GRAFANA_API_KEY 变量已弃用。多组织环境下可用 GRAFANA_ORG_ID 指定组织。

Claude Desktop

在 MCP 客户端配置中加入:

{
  "mcpServers": {
    "grafana": {
      "command": "uvx",
      "args": ["mcp-grafana"],
      "env": {
        "GRAFANA_URL": "http://localhost:3000",
        "GRAFANA_SERVICE_ACCOUNT_TOKEN": "<your service account token>"
      }
    }
  }
}

如果改用 Docker,必须用 -t stdio 把镜像切换到 stdio 模式,因为它的默认入口运行的是 SSE:

{
  "mcpServers": {
    "grafana": {
      "command": "docker",
      "args": ["run", "--rm", "-i", "-e", "GRAFANA_URL", "-e", "GRAFANA_SERVICE_ACCOUNT_TOKEN", "grafana/mcp-grafana", "-t", "stdio"],
      "env": {
        "GRAFANA_URL": "http://localhost:3000",
        "GRAFANA_SERVICE_ACCOUNT_TOKEN": "<your service account token>"
      }
    }
  }
}

Cursor

Cursor 使用与上面相同的 mcpServers JSON(README 的 Quick Start 点名了 Claude Desktop 和 Cursor)。将其放入 Cursor 的 MCP 配置即可。

Claude Code

用 Claude Code CLI 注册同一条 uvx 命令:

claude mcp add grafana \
  -e GRAFANA_URL=http://localhost:3000 \
  -e GRAFANA_SERVICE_ACCOUNT_TOKEN=<your service account token> \
  -- uvx mcp-grafana

VS Code

如果你把服务器作为 SSE 服务运行(例如在 8000 端口运行 Docker 镜像),README 给出的 .vscode/settings.json 配置如下:

"mcp": {
  "servers": {
    "grafana": {
      "type": "sse",
      "url": "http://localhost:8000/sse"
    }
  }
}

其他安装方式

README 还介绍了 release 二进制文件、go install github.com/grafana/mcp-grafana/v2/cmd/mcp-grafana@latest,以及用于 Kubernetes 的 Helm chart(grafana/grafana-mcp)。在 SSE 或 streamable-http 模式下,请设置 MCP_GRAFANA_SERVER_TOKEN,要求客户端发送 bearer token。

Grafana MCP Server (Official) 的主要功能

  • 仪表板搜索、获取、版本历史、更新和补丁,并提供节省上下文的工具,如 get_dashboard_summary 和 get_dashboard_property(JSONPath)。
  • 针对 Prometheus 和 Loki 执行 PromQL 和 LogQL 查询,并可发现标签、指标名称和日志模式等元数据。
  • Tempo 链路搜索与 TraceQL 指标,以及 Pyroscope 性能剖析查询。
  • 告警规则、静默(silence)和通知路由管理,以及 Grafana Incident 和 Grafana OnCall 工具。
  • 可选启用的类别:SQL 数据源(ClickHouse、Snowflake、Athena、MySQL、PostgreSQL、MSSQL)、CloudWatch、Elasticsearch/OpenSearch、InfluxDB、Graphite、Quickwit、Google Cloud Logging 以及 admin/RBAC。
  • 生成深度链接(deeplink),并将面板渲染为 PNG(渲染需要 Grafana Image Renderer)。
  • 安全控制:--disable-write(只读模式)、--disable-query、按类别的 --disable-<category> 参数以及 --enabled-tools。
  • 传输方式:stdio(默认)、SSE 和 streamable HTTP,支持 TLS、调用方认证、Prometheus 指标和 OpenTelemetry 链路追踪。

Grafana MCP Server (Official) 工具

mcp.so 页面列出了 79 个工具,按 Grafana 功能分组:

  • 仪表板和文件夹:search_dashboards、get_dashboard_by_uid、get_dashboard_summary、get_dashboard_panel_queries、update_dashboard、create_folder。处理大型仪表板时请使用 summary 或 property 工具。
  • 数据源和查询:list_datasources、check_datasources_health、query_prometheus、query_prometheus_histogram、query_loki_logs、query_loki_patterns、search_tempo_traces、query_pyroscope。
  • 告警:alerting_rules_read、alerting_rules_write、alerting_silences_read、alerting_silences_write、alerting_manage_routing。
  • Incident 和 OnCall:create_incident、list_incidents、add_activity_to_incident、list_oncall_schedules、get_current_oncall_users、list_alert_groups。
  • 注释、快照和渲染:create_annotation、get_annotations、create_snapshot、get_panel_image。
  • 导航、文档与通用接口:generate_deeplink、search_docs、get_doc、user_info,以及可调用任何没有专用工具的 Grafana API 端点的 grafana_api_request。

部分类别(admin、SQL、CloudWatch、Elasticsearch、runpanelquery、examples 等)默认禁用,需要加入 --enabled-tools 才能使用。

Grafana MCP Server (Official) 的使用场景

  • 事件排查:“现在有哪些告警规则在触发?payments 排班当前谁在值班?”
  • 日志调查:“查询 Loki 中 checkout 服务过去一小时的错误日志,并总结其中的模式。”
  • 无需建面板即可回答指标问题:“过去 24 小时 API 的 p95 请求延迟是多少?”
  • 仪表板维护:“总结 Kubernetes overview 仪表板,并添加一个 Pod 重启次数的面板。”
  • 维护窗口:“为 env=staging 的告警创建一个静默,持续到今天下午 6 点。”
  • 共享上下文:“为该面板生成过去 6 小时的深度链接”,或将其渲染为 PNG 用于报告。

Grafana MCP Server (Official) 与替代方案对比

  • Grafana Cloud MCP Server(托管版):Grafana 还在 https://mcp.grafana.com/mcp 提供仅面向 Grafana Cloud 的托管服务器。它使用 OAuth 浏览器授权而非服务账号令牌,需要你的 stack 启用 Grafana Assistant,且用量计入 Assistant 计费。开源的 mcp-grafana 服务器则支持自托管 Grafana,并让你完全掌控工具和权限。
  • 社区版 Grafana MCP 服务器:也存在其他非官方的 Grafana 服务器;grafana/mcp-grafana 是由 Grafana Labs 维护的版本。
  • 相邻的可观测性服务器:如果需要的是错误追踪而非指标和日志,可以看看 Sentry MCP Server。

Grafana MCP Server (Official) 常见问题排查

  • get datasource by uid ... "id is invalid"(400):你的 Grafana 版本低于 9.0,缺少 /datasources/uid/{uid} 端点。请升级到 9.0+。
  • Claude Desktop 中出现 Error: spawn mcp-grafana ENOENT:在 command 中填写 mcp-grafana 二进制文件的完整路径。
  • Docker 容器在 stdio 下无法使用工具:加上 -t stdio 和 -i;镜像默认是 SSE 模式。
  • 某些工具报权限错误:服务账号缺少该工具所需的 RBAC 操作或范围(例如某个数据源 UID 上的 datasources:query)。请授予相应权限,或使用 Editor 角色。
  • 处理仪表板时上下文窗口被占满:优先使用 get_dashboard_summary 和 get_dashboard_property,而不是 get_dashboard_by_uid,并禁用不需要的类别。加上 --debug 可以记录与 Grafana 之间的 HTTP 流量。

常见问题

1

Grafana MCP server 是官方的吗?

是的。`github.com/grafana/mcp-grafana` 由 Grafana Labs 发布,采用 Apache-2.0 许可证,Grafana 文档称其为 OSS MCP Server。

2

Grafana MCP server 免费吗?

开源服务器可以免费运行。根据 Grafana 文档,单独托管的 Grafana Cloud MCP Server 的用量计入 Grafana Assistant 计费。

3

Grafana MCP server 需要哪些凭据?

需要 Grafana URL(`GRAFANA_URL`)和服务账号令牌(`GRAFANA_SERVICE_ACCOUNT_TOKEN`)。也支持用户名和密码(`GRAFANA_USERNAME`、`GRAFANA_PASSWORD`);`GRAFANA_API_KEY` 已弃用。

4

它支持 Grafana Cloud 吗?

支持。将 `GRAFANA_URL` 设为你的 stack URL,例如 `https://myinstance.grafana.net`。Grafana Cloud 用户也可以使用托管服务器 `https://mcp.grafana.com/mcp`。

5

Grafana MCP server 能在 Claude Code、Cursor 和 VS Code 中使用吗?

可以。它是标准的 stdio MCP 服务器,任何 MCP 客户端都可以启动 `uvx mcp-grafana`。VS Code 也可以通过 SSE 或 streamable HTTP 连接。

6

可以以只读模式运行 Grafana MCP server 吗?

可以。使用 `--disable-write` 启动即可移除创建、更新和删除类工具;除非传入 `--enable-query`,原始 SQL 查询工具也会被移除。`--disable-query` 会移除所有数据源查询工具。

7

需要哪个 Grafana 版本?

Grafana 9.0 或更高版本。部分数据源操作在更早的版本上会失败。

8

它是远程服务器还是本地服务器?

默认通过 stdio 在本地运行,但也可以通过 Docker、二进制文件或 Helm 作为 SSE 或 streamable-HTTP 服务运行。在网络上暴露时,请设置 `MCP_GRAFANA_SERVER_TOKEN`。

评论

开发工具 分类下的更多 MCP 服务器