Skip to main content
Glama
loki-tail-mcp

loki-tail-mcp

by snickery

loki-tail-mcp

An MCP server for Grafana Loki, designed around how LLMs actually query logs: compact output, hard row caps, and a fuzzy container-name rescue that turns the classic empty-result-because-wrong-name failure into an auto-corrected retry or an actionable suggestion list. Built on the Python MCP SDK (FastMCP); runs as a local stdio server or a containerized Streamable HTTP service with bearer auth.

Tools

Tool

Notes

loki_tail_container

"What is service X saying?" — the primary tool. Accepts approximate names: service vocabulary (vpn, proxy), bare names (sonarr), typos. On zero results it distinguishes valid-but-quiet from unknown name, auto-substitutes a unique fuzzy match (flagged in the output), or suggests candidates.

loki_query_range

Raw LogQL range query — multi-container correlation ({container=~"a|b"} |= "...") and metric queries (count_over_time(...)).

loki_query_instant

Instant query at a point in time (metric queries).

loki_list_containers

Durable container names (ephemeral CI/batch names hidden).

loki_list_labels / loki_list_label_values

Raw label discovery.

loki_patterns

Log pattern mining — thousands of lines → ranked recurring templates with counts. Requires the server-side pattern ingester (pattern_ingester.enabled: true).

loki_log_volume

Rank containers by log bytes over a window — "which service suddenly got noisy".

loki_detected_fields

Fields Loki can auto-extract from a stream (name/type/cardinality/parser) — discover | logfmt | status>=500 opportunities before writing LogQL.

The name-resolution design

Matching always runs against live label values, never a hardcoded list, so it survives renames. Resolution tries, in order: exact match → alias vocabulary → substring both ways → typo distance (difflib). A unique candidate is tailed automatically and flagged; multiple candidates become a ranked suggestion list. Auto-generated container names (docker/podman adjective_noun, hex-suffixed batch workers) are filtered out of discovery and suggestions but stay queryable via raw LogQL.

The built-in alias vocabulary covers the common self-hosted stack (vpn→gluetun, proxy→traefik, movies→radarr, …). Entries whose targets don't exist in your fleet are inert; extend with your own via LOKI_ALIASES.

Related MCP server: Loki MCP Server

Quick start (stdio)

// e.g. Claude Desktop claude_desktop_config.json / Claude Code .mcp.json
{
  "mcpServers": {
    "loki": {
      "command": "uv",
      "args": ["run", "--project", "/path/to/loki-tail-mcp", "loki-tail-mcp", "--stdio"],
      "env": { "LOKI_URL": "http://your-loki-host:3100" }
    }
  }
}

stdio mode has no network surface and skips bearer auth — the client owns the process.

HTTP mode (container)

The bundled Containerfile builds a Streamable HTTP server at /mcp (stateless — restarts never strand client sessions). HTTP mode refuses to start without MCP_BEARER_TOKEN; clients authenticate with Authorization: Bearer <token>.

podman build -t loki-tail-mcp .   # or: docker build -t loki-tail-mcp .
podman run -d --name loki-tail-mcp -p 8325:8325 \
  -e LOKI_URL=http://your-loki-host:3100 \
  -e MCP_BEARER_TOKEN=some-long-random-token \
  loki-tail-mcp

loki_tail_mcp.healthcheck does a full HTTP round-trip to /mcp (the 401 counts as alive); wire it to your container healthcheck. Terminate TLS at a reverse proxy — the server itself speaks plain HTTP.

Configuration

Env var

Default

Purpose

LOKI_URL

http://loki:3100

Loki base URL.

LOKI_TENANT_ID

(empty)

Sent as X-Scope-OrgID for multi-tenant Loki.

LOKI_BASIC_AUTH

(empty)

user:password for a basic-auth-fronted Loki (reverse proxy, Grafana Cloud).

LOKI_TIMEOUT

30

Upstream request timeout (s).

LOKI_DEFAULT_LIMIT / LOKI_MAX_LIMIT

100 / 1000

Row caps — Loki will happily return millions of rows; an MCP client will happily feed them to an LLM. Neither is what you want.

LOKI_ALIASES

(empty)

Extra vocabulary merged over the built-ins: term=fragment or term=frag|frag2, comma-separated (e.g. cache=redis|valkey,db=postgres).

LOKI_EPHEMERAL_PATTERNS

(built-ins)

Comma-separated regexes marking names as ephemeral; replaces the defaults when set.

PORT

8325

HTTP listen port.

MCP_BEARER_TOKEN

(empty)

Required in HTTP mode; server refuses to start without it. Not used in --stdio mode.

Testing

# Full suite — mocked HTTP + pure resolution logic, no Loki needed
uv run --extra test pytest tests/ -v

License

MIT

Available Tools

9 tools
loki_detected_fieldsA

Discover the fields Loki can auto-extract from a container's logs (name, type, cardinality, parser — e.g. logfmt/json). Use this before writing a LogQL parse stage in loki_query_range, e.g. finding that a service logs logfmt with a status field enables {container="x"} | logfmt | status>=500.

container: exact container name. minutes: window to sample. Default 60. limit: max fields. Default 20.

Inputs: container (required), limit, minutes. Returns: result

loki_list_containersA

List durable container names actively logging in the lookback window.

Hides ephemeral noise — podman auto-names (adoring_neumann) and hex-suffixed batch workers (transcode-ffmpeg-<hash>) number in the thousands over 24h and would swamp the response. They remain queryable via loki_query_range; use loki_list_label_values('container') for the raw unfiltered list.

lookback: Duration (1h, 24h, 7d). Default 1h.

Inputs: lookback. Returns: result

loki_list_labelsA

List all label names Loki has seen in the given lookback window.

lookback: Duration (1h, 24h, 7d). Default 1h. Shorter is faster.

Inputs: lookback. Returns: result

loki_list_label_valuesA

List all values seen for a given label in the lookback window.

label: Label name (e.g. container, service_name, job, host). lookback: Duration (1h, 24h, 7d). Default 1h.

Inputs: label (required), lookback. Returns: result

loki_log_volumeA

Rank containers by log volume (bytes) — "which service suddenly got noisy". Leave container empty to rank the whole fleet; set it to scope to one container.

minutes: window to measure. Default 60. limit: max rows. Default 10.

Inputs: limit, minutes, container. Returns: result

loki_patternsA

Mine a container's recent logs into recurring patterns — the fastest way to summarize what a noisy service is saying. One call turns thousands of lines into a ranked list of templates (<_> marks the variable parts) with occurrence counts.

container: exact container name (use loki_list_containers / loki_tail_container to find it). minutes: how far back to mine. Default 60.

Requires the Loki pattern ingester; only logs ingested after it was enabled are mined, so a small window right after enablement is normal.

Inputs: container (required), minutes. Returns: result

loki_query_instantA

Run a LogQL instant query at a single point in time.

Best for metric queries like count_over_time({container="crowdsec"}[5m]). For raw log search, prefer loki_query_range.

Inputs: query (required), time, limit. Returns: result

loki_query_rangeA

Run a LogQL range query against Loki.

query: LogQL expression, e.g. {container="nginx"} |= "ERROR" or a metric query like rate({container="traefik"}[5m]). start: Duration back from now (15m, 2h, 3d), RFC3339 timestamp, or ns-since-epoch. Default 1h. end: Same format as start. Default now. limit: Max log lines to return (clamped to server max, default 100). direction: backward (newest first) or forward. Default backward.

Returns compact timestamp [labels] message lines, newest first. For metric queries returns {labels} ts:val ts:val ... per series.

Inputs: query (required), end, limit, start, +1 more. Returns: result

loki_tail_containerA

Tail the most recent log lines for a single container.

container: Container name (e.g. nginx, traefik, arr-sonarr). Exact names work best; an unknown name is resolved against live container names (service vocabulary like vpn works) — a unique match is tailed automatically and flagged in the output, otherwise candidate names are returned. minutes: How far back to look. Default 15. limit: Max lines to return. Default 200. filter: Optional substring filter applied as LogQL |= "filter". Case-sensitive. Leave empty for no filter.

Inputs: container (required), limit, filter, minutes. Returns: result

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A4.3/5.0

    Scored across 9 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose. The two query tools (instant vs range) are explicitly differentiated in their descriptions, and the discovery/analysis tools (labels, patterns, volume, fields, containers) do not overlap. Even tail_container is clearly a convenience wrapper for a specific use case.

    Naming Consistency4/5

    Six of nine tools follow a consistent loki_verb_noun pattern (query_instant, query_range, tail_container, list_labels, list_label_values, list_containers). Three tools (patterns, log_volume, detected_fields) use noun phrases, breaking the verb-first convention. This is a minor inconsistency that doesn't hinder usability.

    Tool Count5/5

    Nine tools is a well-scoped number for a Loki exploration server. Each tool serves a distinct purpose without redundancy, covering querying, metadata discovery, log analysis, and container navigation. The count is neither too small nor overwhelming.

    Completeness5/5

    The tool set covers the full range of Loki interactions: instant queries, range queries, metadata discovery (labels, values), container listing and tailing, pattern mining, volume ranking, and field detection for parsing. There are no obvious gaps for a read-only log exploration workflow.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      An MCP server that enables querying logs and metrics from Graylog, Prometheus, and InfluxDB 2.x. It provides tools for executing Lucene log searches, PromQL queries, and Flux queries directly within MCP-compatible clients.
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      This MCP server enables natural-language querying of Grafana logs by automatically detecting log sources and service labels. It provides read-only access to log data with intelligent caching for efficient repeat queries.
      90 npm
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      An MCP server that enables AI assistants to query and analyze logs from Grafana Loki using LogQL, supporting label discovery and keyword search.
      4
      -