Skip to main content
Glama
mcp-loki

mcp-loki

by mgcrea

@mgcrea/mcp-loki

A Model Context Protocol server for the Grafana Loki HTTP API: query logs and LogQL metrics, explore labels, fields, volume and patterns, with answers shaped to fit a context window.

The server is read-only. It sends only reads: Loki's push, delete-request and ruler-write endpoints are not wrapped, and the loki_request escape hatch only sends GET.

Features

  • Logs merged across streams, in time order. Labels every stream shares come once as common_labels. Each line keeps only the labels that tell its stream apart, plus level and structured metadata. Timestamps are exact RFC3339 nanoseconds, so the next cursor and loki_get_log_context anchors round-trip without loss.

  • Cheap before expensive. loki_get_stats and loki_get_volume answer from the index without reading a line. loki_list_patterns summarizes what a service logs as templates. loki_query_metric counts and ranks without returning lines.

  • Long lines are cut at max_line_chars (some services log 300 KB lines), ANSI colour codes are stripped, and the Kubernetes filename label is hidden by default.

  • Errors carry a remedy. Loki answers a rejected query with plain text. The common ones (empty-compatible matchers, parse errors, range and series limits, timeouts) come back with what to change.

  • Identity and limits up front. loki_auth_status names the tenant, the version, retention, max query length, max lines and series per query, and whether volume and patterns are enabled. Every data answer carries tenant.

Related MCP server: LGTM MCP Server

Configure

Variable

Required

Description

LOKI_URL

yes

Loki base URL (gateway, query-frontend or single binary), with any path prefix.

LOKI_USERNAME

no

Basic auth. Behind the Loki Helm chart's nginx gateway the username is the tenant.

LOKI_PASSWORD

no

Basic auth password.

LOKI_TOKEN

no

Bearer token instead of basic auth (Grafana Cloud, an OAuth proxy).

LOKI_TENANT_ID

no

Sent as X-Scope-OrgID, for a multi-tenant Loki reached directly. A gateway that maps the basic-auth username overrides it.

LOKI_HEADERS

no

Extra headers as a JSON object.

LOKI_TIMEOUT

no

HTTP timeout per request, seconds (default 60).

LOKI_MAX_RETRIES

no

Retries for 429 and proxy 502/503 (default 2). A 504 is never retried: on Loki it is a slow query, and a retry triples the load.

With nothing configured the server still starts and serves loki_auth_status, which says what to set.

Quick start

pnpm install
pnpm build

Then copy .mcp.json.example to .mcp.json and fill it in.

Tools

Tool

What it does

loki_auth_status

URL, auth, tenant, version and this tenant's limits; setup steps when unconfigured

loki_query_logs

LogQL log query over a range, lines merged across streams, with a next cursor

loki_get_log_context

The lines just before and after one line, in its own stream

loki_query_metric

LogQL metric query at an instant, ranked largest first

loki_query_metric_range

LogQL metric query over a range, on a step grid, with per-series stats

loki_list_labels

Stream labels with their cardinality

loki_list_label_values

Values of one label, optionally within a selector

loki_list_series

Streams matching a selector

loki_list_detected_fields

JSON / logfmt / structured-metadata fields in the lines, or one field's values

loki_get_volume

Bytes per namespace / app / stream from the index, largest first

loki_get_stats

Streams, chunks, lines and bytes a selector covers, from the index

loki_list_patterns

Line templates with counts, from the pattern ingester

loki_list_rules

The Loki ruler's alerting and recording rules

loki_request

GET any other read endpoint (/loki/api/v1/*, /prometheus/api/v1/*, /config)

Develop

pnpm dev            # tsdown --watch
pnpm test           # vitest
pnpm typecheck
pnpm lint
pnpm format

Publish

pnpm dlx release-it       # bump, commit, tag
git push --follow-tags    # CI publishes to npm from the tag

License

MIT

Available Tools

14 tools
loki_auth_statusLoki: Auth StatusA
Read-only

Report which Loki this server reads and whether it answers: the URL, auth mode, the tenant (and where that comes from), the Loki version, and this tenant's limits — retention, max query length, max lines per query, max series, query timeout, and whether volume and pattern endpoints are enabled. When the server is not configured, says exactly what to set. Call this first when a tool you expected is missing, when a query fails on a limit, or before trusting logs from an instance you have not checked.

Inputs: no named parameters.

loki_get_log_contextLoki: Get Log ContextA
Read-only

Show the lines around one log line — what the same stream logged just before and after it, unfiltered — the way Grafana's 'show context' does. Pass the stream selector (built from the line's common_labels plus its own labels, e.g. {namespace="payments", pod="api-7d9f-x2k4"}) and the line's exact ts. Lines come back oldest first, with the anchor line marked anchor: true.

Inputs: time (required), selector (required), after, before, +4 more.

loki_get_statsLoki: Get StatsA
Read-only

How much data a stream selector covers over a range — streams, chunks, log lines and bytes — from the index, without reading any of it. Call it before an expensive loki_query_logs or a long metric range: a selector covering tens of GB will be slow or time out, and should be narrowed first.

Inputs: selector (required), end, start.

loki_get_volumeLoki: Get VolumeA
Read-only

How many bytes of logs each service, namespace or stream produced over a range, largest first, from the index alone — no lines are read, so it is cheap over days. Use it to find the noisiest sources, to see what a selector covers before querying it, or to compare: {namespace=~".+"} by ["namespace"] ranks every namespace. Needs volume_enabled (see loki_auth_status).

Inputs: selector (required), by, end, limit, +2 more.

loki_list_detected_fieldsLoki: List Detected FieldsA
Read-only

List the fields Loki can pull out of the log lines themselves — JSON keys, logfmt keys and structured metadata — with their type, cardinality and which parser finds them, for the streams a query selects. This is how to learn what to write after | json or | logfmt (e.g. | json | status >= 500) without reading lines first. Pass field to get that field's values instead.

Inputs: query (required), end, field, limit, +2 more.

loki_list_labelsLoki: List LabelsA
Read-only

List the indexed stream labels with how many distinct values each has, optionally only for streams matching a selector. The starting point for writing any query: low-cardinality labels (namespace, app, service_name, container) make good selectors; high-cardinality ones (pod, filename) are better left to line filters or by. Then loki_list_label_values for the values of one label.

Inputs: end, start, selector.

loki_list_label_valuesLoki: List Label ValuesA
Read-only

List the values of one stream label, e.g. every namespace or every app, optionally only among streams matching a selector (the pods of one namespace). Use it to find the exact spelling to put in a selector rather than guessing with a regex.

Inputs: label (required), end, limit, start, +2 more.

loki_list_patternsLoki: List PatternsA
Read-only

Summarize what a set of streams is logging as line templates (<_> marks the variable parts) with how often each occurred, most frequent first. The fastest way to see what a service is doing, or which new message started flooding, without reading lines. Patterns are built by the pattern ingester from recent data (typically the last few hours) and need it to be enabled (see loki_auth_status).

Inputs: selector (required), end, level, limit, +3 more.

loki_list_rulesLoki: List RulesA
Read-only

List the Loki ruler's alerting and recording rules (LogQL rules evaluated by Loki itself, not Prometheus or Grafana-managed alerts), with health, last error and, for alerts, whether they are firing — firing first. Answers an empty list when no rule groups exist for this tenant, and 404 when the ruler is not deployed or not routed.

Inputs: type, state, search, include_query.

loki_list_seriesLoki: List SeriesA
Read-only

List the streams (distinct label sets) matching a selector, with the labels every one shares hoisted into common_labels. Use it to see what a selector actually covers — which pods, containers and stdout/stderr streams — before querying it. For how much each one logs, use loki_get_volume instead.

Inputs: selector (required), end, limit, start, +1 more.

loki_query_logsLoki: Query LogsA
Read-only

Run a LogQL log query over a time range and return the matching lines, newest first by default, merged across streams into one time-ordered list. Labels shared by every stream come once as common_labels; each line carries only the labels that tell its stream apart, plus level and structured-metadata fields (parsed ones with parsed_fields). When more is true, call again with next's start, end and skip to page on. To count or rank rather than read (errors per namespace, top talkers), use loki_query_metric instead: it is far cheaper than reading lines. loki_get_stats tells you how much a selector would scan.

Inputs: query (required), end, skip, limit, +5 more.

loki_query_metricLoki: Query MetricA
Read-only

Evaluate a LogQL metric query at one instant: a count, rate or total over a window written into the query, e.g. errors per namespace over the last hour sum by (namespace) (count_over_time({namespace=~".+"} |= "error" [1h])), or the top 10 topk(10, ...). The right tool for 'how many / which ones' questions — far cheaper than reading lines with loki_query_logs. Labels shared by every series come once as common_labels. Series come back largest value first: LogQL's topk() picks the top N but does not order them.

Inputs: query (required), sort, time, limit, +1 more.

loki_query_metric_rangeLoki: Query Metric RangeA
Read-only

Evaluate a LogQL metric query over a time range, for how log volume or error rates changed: a spike, when it started, which service it came from. Each series comes back with stats (min, max, avg, last) and, with view=values, one value per step on a shared grid given by start and step (null where there was nothing). The step is picked for about 60 points unless given; the range in the query ([5m]) is independent of it, and usually should match it. Aggregate with sum by — one series per stream is rarely what you want and quickly hits max_query_series.

Inputs: query (required), end, sort, step, +4 more.

loki_requestLoki: RequestA
Read-only

Escape hatch: GET any Loki read endpoint the other tools do not wrap — /loki/api/v1/index/volume_range, /loki/api/v1/format_query (pretty-prints and validates LogQL without running it), /prometheus/api/v1/alerts, or /config (this Loki's whole running configuration, as YAML). The answer is the raw data (or text), unshaped, cut at max_chars. Read-only: only GET is ever sent. Prefer the named tools, which shape their output.

Inputs: path (required), params, max_chars.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.2/5.0

    Scored across 14 tools

    Disambiguation4/5

    The tools are largely distinct: log reading, instant/range metrics, label discovery, series, fields, volume, stats, patterns, rules, and raw GET each have a clear role. The main possible confusion is among the several metric/volume/stat tools, but descriptions explicitly steer between them (e.g. query_metric vs query_metric_range vs get_stats vs get_volume).

    Naming Consistency4/5

    All names use the loki_ prefix and snake_case, with mostly verb_noun forms such as query_logs, list_labels, and get_volume. Minor deviations are loki_auth_status (noun phrase) and loki_request (bare verb), so the pattern is not perfectly uniform.

    Tool Count5/5

    14 tools is within the well-scoped range and each covers a distinct Loki read operation; there is no obvious filler. The set is appropriately sized for a read-only Loki observability server.

    Completeness4/5

    Core Loki read workflows are covered: auth/config status, log queries, context, instant/range metrics, labels/values/series, detected fields, volume, stats, patterns, rules, and a raw GET escape hatch. A live tail/streaming tool is not present, but otherwise the read surface is comprehensive.

    Maintenance

    ActivityMaintained
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables querying and formatting Loki logs from Grafana via the Model Context Protocol. It supports LogQL queries, label retrieval, and provides results in text, JSON, or markdown formats.
      750 PyPI
      29
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides read-only access to Loki, Prometheus, and Tempo APIs, enabling natural language queries for logs, metrics, and traces. Supports multiple instances and authentication via bearer tokens.
      1
      MIT
    • A
      license
      A
      quality
      C
      maintenance
      Enables read-only querying of Grafana Loki logs through tools like label discovery, LogQL queries, and recent log retrieval, without requiring knowledge of the Loki API.
      4
      MIT