---
title: "Observability (metrics, tracing, and logs) | Grafana documentation"
description: "Expose Prometheus metrics and OpenTelemetry tracing and logs from the Grafana MCP server."
---

> For a curated documentation index, see [llms.txt](/llms.txt). For the complete documentation index, see [llms-full.txt](/llms-full.txt).

# Observability (metrics, tracing, and logs)

The MCP server can expose **Prometheus metrics** and supports [**OpenTelemetry**](https://opentelemetry.io/) distributed tracing and log export, following the [OTel MCP semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/mcp/).

Metrics require the **SSE** or **streamable-http** transport. Tracing and log export use standard `OTEL_*` environment variables and work with any transport, independently of `--metrics`.

**Note**: mcp-grafana currently only supports the OTLP/gRPC transport for both traces and logs. `OTEL_EXPORTER_OTLP_PROTOCOL` (and its `_TRACES_PROTOCOL` / `_LOGS_PROTOCOL` variants) are not honored — gRPC is used regardless.

## What you’ll achieve

You can scrape MCP operation metrics (HTTP transports only) and export traces and logs to Tempo, Loki, or Grafana Cloud under any transport, including stdio.

## Before you begin

- The server running with **SSE** or **streamable-http** (metrics are not available with stdio).

## Enable Prometheus metrics

When using SSE or streamable HTTP transports, enable Prometheus metrics with `--metrics`:

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
# Metrics on the main server at /metrics
./mcp-grafana -t streamable-http --metrics
```

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
# Metrics on a separate listen address
./mcp-grafana -t streamable-http --metrics --metrics-address :9090
```

**Available metrics:**

Expand table

| Metric                                  | Type      | Description                                                                                                                                                                                                                                    |
|-----------------------------------------|-----------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `mcp_server_operation_duration_seconds` | Histogram | MCP operation duration (labels: `mcp_method_name`, `gen_ai_tool_name`, `error_type`, `network_transport`, `mcp_protocol_version`, and — for `tools/call` on selected tools — `mcp_tool_operation`, `mcp_tool_resource_type`, `mcp_tool_phase`) |
| `mcp_server_session_duration_seconds`   | Histogram | MCP client session duration (labels: `network_transport`, `mcp_protocol_version`)                                                                                                                                                              |
| `http_server_request_duration_seconds`  | Histogram | HTTP server request duration (from otelhttp)                                                                                                                                                                                                   |

**Note**: Metrics are only available when using SSE or streamable HTTP transports. They are **not** available with stdio transport.

### Tool-call dimension labels

For `tools/call`, `mcp_server_operation_duration_seconds` can carry up to three extra low-cardinality labels so durations are sliceable by what the call was doing:

Expand table

| Label                    | Source                          | Notes                                                                                                              |
|--------------------------|---------------------------------|--------------------------------------------------------------------------------------------------------------------|
| `mcp_tool_operation`     | the tool’s `operation` argument | Multiplexer tools only (e.g. `alerting_rules_write`); one of the tool’s declared operations, else `other`.         |
| `mcp_tool_resource_type` | the tool’s `type` argument      | e.g. the datasource plugin type on `create_datasource`; a plugin type the server ships a schema for, else `other`. |
| `mcp_tool_phase`         | the tool’s result `_meta`       | Phase of a multi-call flow (e.g. `create_datasource` schema guidance vs. actual creation).                         |

Arguments are raw client input, so the two argument-derived labels are allowlisted by tool **and** by value: unlisted tools emit neither, and unlisted values collapse into one `other` bucket, giving each label a fixed maximum series count. Tool validation alone would not bound them — a rejected `operation` is still instrumented, and `create_datasource`’s `type` is free text that succeeds for unknown values. `mcp_tool_phase` is exempt: the tool sets it on its own result, and tools must keep that value set small.

The high-cardinality **target** of a call (the datasource `uid`, else `name`) is never a metric label — it is span-only as `mcp.tool.target`, and empty for calls that name no entity (see below).

### Metric-name discovery

Expand table

| Metric                                 | Type             | Description                                                                                |
|----------------------------------------|------------------|--------------------------------------------------------------------------------------------|
| `mcp_metric_names_response_size_bytes` | Native histogram | Bytes consumed from complete successful discovery HTTP responses, after HTTP decompression |
| `mcp_metric_names_count`               | Native histogram | Number of metric names decoded successfully before local filtering and pagination          |

These metrics help us understand the responses we get from prometheus-type backends when discovering available metric names. The metrics only measure the sizes of successful responses. The bounded `backend` label distinguishes `prometheus` (including compatible backends) from `cloud_monitoring`. Unlike the prometheus backend, Cloud Monitoring measures the full descriptor response, which contain more than just names, so comparing response byte sizes between the two backends is not meaningful.

For example, the p95 response size over the last hour is:

promql ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```promql
histogram_quantile(0.95, sum by (backend) (rate(mcp_metric_names_response_size_bytes[1h])))
```

These metrics use Native Histograms, so the scraper must also support native histograms.

### Loki cost guardrail metrics

When the [Loki query cost guardrail](https://grafana.com/docs/grafana/latest/ai-tools/mcp/configure/command-line-flags/) is enabled (`--loki-guardrail-mode` is `shadow` or `enforce`), every `query_loki_logs` call it evaluates increments exactly one of four counters:

Expand table

| Metric                                 | Type    | Incremented when                                               |
|----------------------------------------|---------|----------------------------------------------------------------|
| `mcp_loki_guardrail_admitted_total`    | Counter | The query passed every enabled check                           |
| `mcp_loki_guardrail_would_block_total` | Counter | The query failed a check in `shadow` mode and ran anyway       |
| `mcp_loki_guardrail_blocked_total`     | Counter | The query failed a check in `enforce` mode and was rejected    |
| `mcp_loki_guardrail_fail_open_total`   | Counter | The guardrail could not reach a verdict and admitted the query |

The four partition the guarded population, so their sum is the number of calls the guardrail evaluated, and each is a query count rather than a check count.

**Labels:**

Expand table

| Label     | On                       | Values                                                                                                                               |
|-----------|--------------------------|--------------------------------------------------------------------------------------------------------------------------------------|
| `reason`  | `would_block`, `blocked` | `selector` (no selective label matcher), `range` (effective time range over the cap), `bytes` (index/stats estimate over the budget) |
| `cause`   | `fail_open`              | `unparseable` (no stream selector the scanner recognises), `estimate_failed` (index/stats unavailable)                               |
| `backend` | all four                 | `loki`, `victorialogs`, `unknown`                                                                                                    |

A query can trip more than one check. It is counted **once**, labelled with the check that ran first — `selector`, then `range`, then `bytes`. That ordering is deliberate: the selectivity check is unconditional, so a query attributed to `selector` would not be admitted by raising `--loki-guardrail-max-range` or `--loki-guardrail-max-bytes`. When promoting from `shadow` to `enforce`, read `sum(rate(mcp_loki_guardrail_would_block_total[5m]))` for the size of the affected population and `sum by (reason) (...)` for whether tuning the bounds would shrink it.

Watch `mcp_loki_guardrail_fail_open_total` alongside them: a quiet `would_block` rate means “nothing would be blocked” only if the fail-open rate is also low. A high `cause="unparseable"` rate on `backend="loki"` means the guardrail’s LogQL scanner does not recognise the query shapes in use, which calls for improving the scanner rather than tuning the bounds. On `backend="victorialogs"` a high `unparseable` rate is expected — brace-less LogsQL is the normal shape there, and the byte-budget check never runs on that backend at all, which is why `backend` is a label rather than being folded together.

Neither the stream selector nor the LogQL is exported as a label: both are unbounded, and line filters can carry sensitive literals. The extracted selectors are logged at `WARN` and the full query at `DEBUG` instead.

### Prometheus guardrail metrics

When the [Prometheus query guardrail](https://grafana.com/docs/grafana/latest/ai-tools/mcp/configure/command-line-flags/) is enabled (`--prometheus-guardrail-mode` is `shadow` or `enforce`), every PromQL query it evaluates increments exactly one of four counters:

Expand table

| Metric                                       | Type    | Incremented when                                                                  |
|----------------------------------------------|---------|-----------------------------------------------------------------------------------|
| `mcp_prometheus_guardrail_admitted_total`    | Counter | The query passed every enabled check                                              |
| `mcp_prometheus_guardrail_would_block_total` | Counter | The query failed a check in `shadow` mode and ran anyway                          |
| `mcp_prometheus_guardrail_blocked_total`     | Counter | The query failed a check in `enforce` mode and was rejected                       |
| `mcp_prometheus_guardrail_fail_open_total`   | Counter | No check failed, but parsing or an enabled cardinality assessment was unavailable |

**Labels:**

Expand table

| Label    | On                       | Values                                                                                                                                                                                                                                                                                                                                                |
|----------|--------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `reason` | `would_block`, `blocked` | `selector` (a vector selector lacks a selective positive label constraint when the selector policy is enabled), `range` (effective time range over `--prometheus-guardrail-max-range`), `points` (requested points per series over `--prometheus-guardrail-max-points`), `cardinality` (a known high-cardinality metric lacks an exact scope matcher) |
| `reason` | `fail_open`              | `unparseable`, `cardinality_unknown` (metric cardinality or TSDB metadata unavailable)                                                                                                                                                                                                                                                                |

The diagnostic OTel counter `mcp.prometheus_guardrail.cardinality_fail_open` (unit `{query}`, exported as `mcp_prometheus_guardrail_cardinality_fail_open_total`) increments once only when the final decision is `fail_open{reason="cardinality_unknown"}`. It is a subset of the existing fail-open counter, not a fifth decision counter; do not add it to the four decision counters when counting queries. Its only attribute is the bounded `cause`:

Expand table

| `cause`                  | Meaning                                                                                                                        |
|--------------------------|--------------------------------------------------------------------------------------------------------------------------------|
| `not_in_top_n`           | Metadata was valid, but an exact metric name was absent from the TSDB top-N statistics                                         |
| `unresolved_metric_name` | A selector’s exact metric name could not be resolved, for example a regex or name-less selector                                |
| `metadata_unavailable`   | Backend resolution or metadata access failed, including unsupported endpoints, timeouts, invalid responses and cached failures |
| `fetch_slots_saturated`  | All local TSDB fetch slots were occupied; no metadata HTTP request was started for this lookup                                 |

Cause selection is deterministic: when exact names require metadata, a fetch-slot or metadata failure takes precedence over unresolved names; with valid metadata, unresolved names take precedence over missing top-N entries. Known cardinality violations still take precedence over unknown selectors and produce `blocked` or `would_block` without incrementing this diagnostic counter. Static checks, `off` mode and scoped selectors retain their existing behavior. Saturation is not cached, so the same request can retry metadata lookup as soon as a slot is free. Cached metadata failures still increment the diagnostic counter per final query decision, rather than per HTTP attempt. Legacy proxy fallback can make two HTTP attempts for one decision.

Metric names, PromQL, datasource UIDs and error strings are never attributes of this diagnostic counter.

A query that fails multiple checks is counted once, under the first failure in the order `selector`, `range`, `points`, `cardinality`. Selector checks are enabled independently of the numeric budgets. The time range and step are checked even when the expression does not parse, so a macro-bearing query over too long a range is still blocked rather than counted as a fail-open. Unlike the Loki counters, these have no `backend` label. Static checks apply to every Prometheus-compatible backend; unsupported TSDB metadata fails open for the opt-in cardinality policy.

Built-in Grafana macros such as `$__rate_interval` are substituted before parsing. A steady `fail_open` rate can indicate unresolved dashboard variables such as `$window` or unsupported syntax; a low `would_block` rate is meaningful only alongside a low fail-open rate. The guardrail has these limits:

- The optional selector check is a static heuristic, not a bound on series count or backend work. Neither query text nor label names/values are exported as metric attributes.
- The cardinality policy requires exact scope for known high-cardinality metrics from cached TSDB top-N statistics. It does not estimate matched series; missing metrics are unknown, and a scope matcher can still select many series. Watch `cardinality_unknown` alongside blocks when evaluating coverage.
- The points check budgets the requested resolution, `floor(range / step) + 1`. It does not bound the number of series, samples, or subquery evaluations, and Grafana may align the range or widen the step.
- `offset` and `@` modifiers are ignored. `offset` shifts a window without widening it; ignoring `@` can only overestimate.
- Expressions that need Grafana macro substitution or a dialect-only feature fail open on the expression part.

The expression is never a label. Blocked queries are logged at `WARN` with the reasons, and the expression is logged at `DEBUG` only.

#### Roll out the cardinality policy

Start with a build that includes the [cardinality policy](https://grafana.com/docs/grafana/latest/ai-tools/mcp/configure/command-line-flags/#prometheus-cardinality-policy) and its [fail-open diagnostics](https://github.com/grafana/mcp-grafana/pull/1583). Check the deployed version with `./mcp-grafana --version` and its release notes; v2.3.0 predates these diagnostics. If building from source, use a revision containing that change. An absent diagnostic metric alone does not establish whether the deployed build supports it.

Using your existing Grafana connection and authentication settings, enable metrics and start in shadow mode:

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
./mcp-grafana -t streamable-http --metrics \
  --prometheus-guardrail-mode=shadow \
  --prometheus-guardrail-max-metric-cardinality=100000
```

The threshold is an example, not a recommended limit for every deployment. Choose it and the scope labels for your workload. Configure Prometheus to scrape `/metrics` from the server’s HTTP listener (or the separate `--metrics-address` listener). Metrics require an HTTP transport; stdio does not expose this endpoint.

Observe a representative workload before enforcing. The following queries group by the Prometheus scrape label `job`, assuming each job contains instances with the same build and guardrail settings. Filter to the deployment under evaluation. If jobs span clusters or policies, retain the relevant scrape labels in every aggregation and on both sides of a ratio. Guardrail counters have no datasource or mode label, so a combined fleet view cannot identify an individual datasource or separate shadow from enforce traffic.

Read the number of queries per second that end with each cardinality fail-open cause:

promql ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```promql
sum by (job, cause) (
  rate(mcp_prometheus_guardrail_cardinality_fail_open_total[5m])
)
```

To see the percentage of all evaluated guardrail decisions that end with cardinality unknown:

promql ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```promql
100 *
sum by (job) (
  rate(mcp_prometheus_guardrail_cardinality_fail_open_total[5m])
)
/
(
  sum by (job) (
    label_replace(
      rate(mcp_prometheus_guardrail_admitted_total[5m]), "__tmp_guardrail_decision", "admitted", "job", ".*"
    )
    or label_replace(
      rate(mcp_prometheus_guardrail_would_block_total[5m]), "__tmp_guardrail_decision", "would_block", "job", ".*"
    )
    or label_replace(
      rate(mcp_prometheus_guardrail_blocked_total[5m]), "__tmp_guardrail_decision", "blocked", "job", ".*"
    )
    or label_replace(
      rate(mcp_prometheus_guardrail_fail_open_total[5m]), "__tmp_guardrail_decision", "fail_open", "job", ".*"
    )
  ) > 0
)
```

Only the four final decision counters belong in the denominator. Adding the diagnostic counter would count those fail-open queries twice. This percentage describes the evaluated query population, not the fraction of selectors whose cardinality is known: scoped selectors need no metadata, static violations skip the cardinality check, and a known violation takes precedence over unknown selectors. It also excludes calls that never reach the guardrail and calls made with the guardrail off.

`rate()` drops the metric name. During a shadow-to-enforce rollout, `would_block` and `blocked` samples can share the same labels within the rate window. Calculating each rate separately and adding a temporary decision label keeps both series distinct until the sum. The `or` includes the rates that are present even when some counters have yet to emit samples.

In shadow mode, inspect which checks would reject traffic:

promql ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```promql
sum by (job, reason) (
  rate(mcp_prometheus_guardrail_would_block_total[5m])
)
```

Use `reason="cardinality"` to focus on this policy, while reviewing the other reasons before switching modes. `--prometheus-guardrail-mode` controls the enabled selector, range and points checks too; promoting to enforce changes their behavior as well.

Counters can be absent until their first event. `rate` also needs at least two samples. A missing cause series is not proof of working metadata or a reason to treat missing scrapes as zero. Check scrape health, the deployed build, nonzero evaluated traffic and the opt-in threshold. With existing samples but no traffic, the positive-denominator filter omits the percentage instead of dividing by zero. Keep `rate` inside `sum` so counter resets from individual process restarts are handled before aggregation. A low would-block rate is useful only alongside the fail-open rates and an understanding of the queries that bypass metadata.

#### Respond to cardinality fail-open causes

Use sustained rates and a minimum traffic volume appropriate to the deployment when setting alerts. Establish a baseline in shadow mode before choosing thresholds. Separate metadata availability and local capacity signals from limitations of the policy’s coverage:

Expand table

| Cause                    | Check                                                                                                                                                                                                     | Response                                                                                                                                                                                                                                                                                      |
|--------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `metadata_unavailable`   | Does the backend expose `/api/v1/status/tsdb` through the Grafana datasource proxy for the same caller and tenant? Check datasource resolution, permissions, HTTP status, latency and response format.    | Repair the route, authorization or backend problem. An unsupported endpoint is an expected coverage limitation; static checks still apply. Failures are cached for up to the smaller of the configured cache TTL and 30 seconds, so diagnostic increments are not metadata HTTP error counts. |
| `fetch_slots_saturated`  | Are slow metadata fetches or simultaneous misses across distinct authentication/tenant cache keys occupying the eight local slots? Custom transports and TLS client certificates bypass the shared cache. | Investigate backend latency and bursts of uncached lookups. Saturation is not cached; a later query can retry when a slot is free. Do not assume that increasing concurrency would reduce backend load.                                                                                       |
| `not_in_top_n`           | Is the exact metric absent from otherwise valid TSDB top-10 statistics?                                                                                                                                   | Treat the count as unknown. This does not prove low cardinality and is not, by itself, a metadata outage. Review the workload and retain backend query limits.                                                                                                                                |
| `unresolved_metric_name` | Does the selector use a regex metric name or omit an exact metric name?                                                                                                                                   | Review whether the intended query can name a metric explicitly without changing its meaning. An exact name can still be absent from the top 10; changing it does not guarantee an assessment. Do not classify this cause as a backend outage.                                                 |

The metadata timeout is two seconds, with a 1 MiB response limit. After a backend repair, queries can continue to see a cached failure until its shorter failure TTL expires. Successful snapshots default to a ten-minute cache TTL, so changed series counts may also take time to appear. The counter records final query decisions: two queries sharing one cached metadata failure produce two diagnostic increments but only one metadata fetch; a legacy proxy fallback can instead make two HTTP attempts for one lookup. Known violations produce `would_block` or `blocked` without a diagnostic increment, even when another selector is unknown.

After investigating the causes and reviewing would-be blocks, test representative queries: a known high-cardinality unscoped metric, an intended exact scope, and an unavailable-metadata case. Confirm that scope labels match the intended workload boundaries. An exact scope matcher is a policy exemption, not a bound on matched series or query cost.

Promote a limited deployment to `--prometheus-guardrail-mode=enforce` while keeping its other settings unchanged. Watch `blocked` by reason, fail-open causes, tool errors and backend query behavior. Queries whose cardinality remains unknown still fail open in enforce mode. If valid traffic is rejected unexpectedly, restore `--prometheus-guardrail-mode=shadow` using the same deployment mechanism and investigate the policy before expanding enforcement. Returning to shadow permits would-be blocked queries to run; backend query limits remain necessary in both modes.

## Enable OpenTelemetry tracing

When `OTEL_EXPORTER_OTLP_ENDPOINT` (or the signal-specific `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`) is set, the server exports traces via OTLP/gRPC.

Local example:

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
# Send traces to a local Tempo instance
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 \
OTEL_EXPORTER_OTLP_INSECURE=true \
./mcp-grafana -t streamable-http
```

Grafana Cloud example:

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
# Send traces to Grafana Cloud with authentication
OTEL_EXPORTER_OTLP_ENDPOINT=https://tempo-us-central1.grafana.net:443 \
OTEL_EXPORTER_OTLP_HEADERS="Authorization=Basic ..." \
./mcp-grafana -t streamable-http
```

Tool call spans follow naming like `tools/call <tool_name>` and include attributes such as `gen_ai.tool.name`, `mcp.method.name`, and `mcp.session.id`. The server supports W3C trace context propagation from the `_meta` field of tool call requests.

### Trace context propagation

Under an HTTP transport (SSE or streamable-http) the server takes part in [W3C trace context](https://www.w3.org/TR/trace-context/) propagation on both sides, so a caller, mcp-grafana, and Grafana appear as one connected trace:

- **Inbound**: a `traceparent`/`tracestate` header on the incoming request (from an MCP client or an upstream proxy) parents the server span, continuing the caller’s trace instead of starting a new one.
- **Outbound**: requests to the Grafana API carry a `traceparent` naming mcp-grafana’s own span, so Grafana’s spans hang off ours.

Propagation is always active — it does not require `OTEL_EXPORTER_OTLP_ENDPOINT`. With trace export off, no spans are recorded but an inbound trace context is still passed through to Grafana rather than dropped.

The propagators used are configured with the standard [`OTEL_PROPAGATORS`](https://opentelemetry.io/docs/languages/sdk-configuration/general/#otel_propagators) environment variable, defaulting to `tracecontext,baggage`. Set it to interoperate with a non-W3C system (`b3`, `b3multi`, `jaeger`, `xray`, `ottrace`, in any comma-separated combination) or to `none` to disable propagation entirely.

Tool call requests may also carry `traceparent`/`tracestate` in their MCP `_meta` field; when present, that context parents the tool span. This is the only propagation channel available under stdio, where there is no HTTP request to read headers from.

Listing `traceparent` or `tracestate` in `GRAFANA_FORWARD_HEADERS` is not needed and no longer has an effect: forwarding the *caller’s* `traceparent` verbatim would parent Grafana’s spans onto the caller and cut mcp-grafana out of the middle of the trace, so a forwarded value never overrides the propagated one. Forwarded trace headers still apply when propagation is disabled with `OTEL_PROPAGATORS=none`.

Tool-call spans also carry the [tool-call dimensions](https://grafana.com/docs/grafana/latest/ai-tools/mcp/developer/observability-metrics-and-tracing/#tool-call-dimension-labels) `mcp.tool.operation`, `mcp.tool.resource_type`, and `mcp.tool.phase`, plus the span-only `mcp.tool.target` (the datasource `uid`, else `name`) for grouping the spans that touch one entity. `mcp.tool.target` is empty when a call names no entity — notably `create_datasource`’s `phase=schema` call, where the datasource does not exist yet — so stitching that call to the later `phase=created` one relies on the shared trace (when the client propagates context via `_meta`) or on `mcp.session.id` plus `mcp_tool_resource_type`, rather than on the target. Unlike the metric labels, these are attached for **all** tools with their **raw** values (no allowlist, no `other` bucket), since traces are high-cardinality by design. They require an **HTTP transport** (SSE or streamable-http, so a server span exists to enrich) **and tracing enabled**, but **not** `--metrics`; with stdio or tracing off, enrichment is a no-op.

## Enable OpenTelemetry logs

When `OTEL_EXPORTER_OTLP_ENDPOINT` (or the signal-specific `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`) is set, the server also exports structured logs via OTLP/gRPC in addition to the existing plain-text stderr output. Logs carry `trace_id` and `span_id` from the active span so they correlate with exported traces.

Traces and logs resolve their endpoints independently, so the two signals can be enabled separately:

- Setting only `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` enables tracing **without** log export.
- Setting only `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` enables log export without tracing.
- Setting the generic `OTEL_EXPORTER_OTLP_ENDPOINT` enables both.

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
# Send logs and traces to a local OTel collector
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 \
OTEL_EXPORTER_OTLP_INSECURE=true \
./mcp-grafana -t streamable-http
```

Stderr logging continues unchanged; operators can pipe stderr to `/dev/null` if they only want logs going to the OTel collector.

Logs can be sent directly to any managed backend that accepts OTLP/gRPC — for example, Grafana Cloud — by pointing `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` (or the generic `OTEL_EXPORTER_OTLP_ENDPOINT`) at the remote gRPC endpoint and supplying auth via `OTEL_EXPORTER_OTLP_LOGS_HEADERS` (or `OTEL_EXPORTER_OTLP_HEADERS`), mirroring the tracing example above. A local OTel collector is optional — useful for fan-out, batching, or multi-backend routing, but not required.

The signal-specific variants `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`, `OTEL_EXPORTER_OTLP_LOGS_HEADERS`, `OTEL_EXPORTER_OTLP_LOGS_INSECURE`, `OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE`, `OTEL_EXPORTER_OTLP_LOGS_TIMEOUT`, and `OTEL_EXPORTER_OTLP_LOGS_COMPRESSION` are honored and override their generic `OTEL_EXPORTER_OTLP_*` counterparts — see the [OTel exporter spec](https://opentelemetry.io/docs/specs/otel/protocol/exporter/) for the full list and precedence rules.

**Note**: If the configured collector is unreachable, log records are buffered in memory (default queue: 2048) and the oldest records are dropped once the queue fills. The process continues without blocking the service. Configure a local OTel collector if you need lossless buffering during outages.

Logs are also exported under the stdio transport, which makes it easy to centralize logs from local `mcp-grafana` instances invoked by IDE clients.

## Run with Docker (metrics, tracing, and logs)

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
docker run --rm -p 8000:8000 \
  -e GRAFANA_URL=http://localhost:3000 \
  -e GRAFANA_SERVICE_ACCOUNT_TOKEN=<your token> \
  -e OTEL_EXPORTER_OTLP_ENDPOINT=http://tempo:4317 \
  -e OTEL_EXPORTER_OTLP_INSECURE=true \
  grafana/mcp-grafana \
  -t streamable-http --metrics
```

## Next steps

- [Build, test, and lint](https://grafana.com/docs/grafana/latest/ai-tools/mcp/developer/build-and-test/)
- [Transports and addresses](https://grafana.com/docs/grafana/latest/ai-tools/mcp/configure/transports-and-addresses/)
- [Command-line flags](https://grafana.com/docs/grafana/latest/ai-tools/mcp/configure/command-line-flags/)
