mcp-loki
Provides read-only tools for querying and exploring Grafana Loki through its HTTP API, including LogQL log and metric queries, log context, labels, series, detected fields, volume, stats, patterns, and ruler rules.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mcp-loki show me error logs from the api service in the last 15 minutes"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
@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, plusleveland structured metadata. Timestamps are exact RFC3339 nanoseconds, so thenextcursor andloki_get_log_contextanchors round-trip without loss.Cheap before expensive.
loki_get_statsandloki_get_volumeanswer from the index without reading a line.loki_list_patternssummarizes what a service logs as templates.loki_query_metriccounts 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 Kubernetesfilenamelabel 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_statusnames the tenant, the version, retention, max query length, max lines and series per query, and whether volume and patterns are enabled. Every data answer carriestenant.
Related MCP server: LGTM MCP Server
Configure
Variable | Required | Description |
| yes | Loki base URL (gateway, query-frontend or single binary), with any path prefix. |
| no | Basic auth. Behind the Loki Helm chart's nginx gateway the username is the tenant. |
| no | Basic auth password. |
| no | Bearer token instead of basic auth (Grafana Cloud, an OAuth proxy). |
| no | Sent as |
| no | Extra headers as a JSON object. |
| no | HTTP timeout per request, seconds (default 60). |
| 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 buildThen copy .mcp.json.example to .mcp.json and fill it in.
Tools
Tool | What it does |
| URL, auth, tenant, version and this tenant's limits; setup steps when unconfigured |
| LogQL log query over a range, lines merged across streams, with a |
| The lines just before and after one line, in its own stream |
| LogQL metric query at an instant, ranked largest first |
| LogQL metric query over a range, on a step grid, with per-series stats |
| Stream labels with their cardinality |
| Values of one label, optionally within a selector |
| Streams matching a selector |
| JSON / logfmt / structured-metadata fields in the lines, or one field's values |
| Bytes per namespace / app / stream from the index, largest first |
| Streams, chunks, lines and bytes a selector covers, from the index |
| Line templates with counts, from the pattern ingester |
| The Loki ruler's alerting and recording rules |
| GET any other read endpoint ( |
Develop
pnpm dev # tsdown --watch
pnpm test # vitest
pnpm typecheck
pnpm lint
pnpm formatPublish
pnpm dlx release-it # bump, commit, tag
git push --follow-tags # CI publishes to npm from the tagLicense
MIT
Available Tools
14 toolsloki_auth_statusLoki: Auth StatusARead-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 ContextARead-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 StatsARead-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 VolumeARead-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 FieldsARead-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 LabelsARead-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 ValuesARead-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 PatternsARead-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 RulesARead-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 SeriesARead-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 LogsARead-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 MetricARead-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 RangeARead-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: RequestARead-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
Scored across 14 tools
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).
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.
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.
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
Related MCP Connectors
Lets AI agents analyze API metrics, request logs, and traces, and manage apps and alerts.
Read-only access to Auralogs production logs: search logs, inspect errors, review AI analyses.
Read-only access to a Lumin project's logs, metrics, uptime checks, alerts and infrastructure.
Search logs, read alerts, enable or disable them, and read dashboards in Logz.io.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables 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 PyPI29MIT
- AlicenseNot gradedqualityDmaintenanceProvides 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.1MIT
- AlicenseAqualityCmaintenanceEnables 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.4MIT
- FlicenseNot gradedqualityDmaintenanceEnables read-only querying of a local Grafana Loki instance, providing log search, service listing, and health check capabilities.-