Loki MCP Server
Grafana Loki is the industry-standard log aggregation system for cloud-native environments — but querying it effectively requires deep domain knowledge. Writing correct LogQL, managing stream label cardinality, configuring JSON and logfmt parser stages, and avoiding unbounded queries that exhaust memory each demand specialized operator expertise. When generic AI assistants try to query Loki, they routinely hallucinate non-existent label names, write inefficient stream selectors, or execute unconstrained full-table scans that overwhelm backend queriers.
The TalkOps Loki MCP Server fixes this. It provides AI assistants (Claude, Cline, Cursor, or TalkOps autonomous controllers) with structured, discovery-first, and production-safe tools to manage and query Grafana Loki natively:
- Discovery-First Schema Exploration. The AI discovers global label taxonomies, valid stream values, and active series counts before constructing queries — completely eliminating label hallucination.
- Log Structure & Field Analysis. Inspect log line shapes without streaming raw gigabytes: auto-discover JSON/logfmt keys, data types, estimated cardinality, and recommended parser expressions (
| json,| logfmt,| pattern "<pattern>"). - Production-Safe Query Guardrails. Preflight cost estimation analyzes streams, chunks, and bytes before execution. Hard byte limits (5 GB default) and time-window clamping protect both your LLM's context window and the Loki cluster.
- Unified LogQL Stream & Metric Queries. Execute raw log stream lookups or calculate real-time metrics (
rate(),count_over_time(),quantile_over_time()) with automatic result downsampling and error handling. - Interactive A2UI Log Tables. Stream structured log entries directly into dynamic UI tables with interactive filtering and severity highlighting.
The Observability Trifecta
The Loki MCP Server represents the Logs Pillar of the TalkOps cloud-native observability stack:
┌────────────────────────────────────────────────────────┐
│ TalkOps Observability Stack │
├───────────────────┬───────────────────┬────────────────┤
│ PROMETHEUS MCP │ LOKI MCP │ TEMPO MCP │
│ (Metrics) │ (Logs) │ (Traces) │
│ 28 Tools · TSDB │ 9 Tools · LogQL │ 16 Tools · TraceQL│
└───────────────────┴───────────────────┴────────────────┘
▲
│ Pipeline Plumbing
┌─────────────────────────────┐
│ OPENTELEMETRY MCP │
│ (Collector & Instrumentation)│
└─────────────────────────────┘
Key Features
Schema & Label Taxonomy Discovery
- Global label taxonomy inspection (
get_cluster_labels) - Scoped label value enumeration across namespaces and apps (
get_label_values) - Active stream verification and cardinality tracking (
get_active_series)
Log Structure Discovery & Pattern Analysis
- Structural pattern detection via Loki's pattern ingester (
get_log_patterns) - Detected field discovery: JSON/logfmt keys, data types, and parser hints (
get_detected_fields) - Automated LogQL parser stage recommendations
Production-Safe Query Execution
- Preflight cost estimation: streams, chunks, entries, and bytes touched (
get_query_stats) - Configurable guardrails: maximum byte caps (5 GB default), maximum time windows (14 days), and log line limits (5,000)
- High-cardinality selector warnings and automatic query rejection
Unified LogQL Execution
- Instant point-in-time scalar queries (
execute_logql_instant) - Comprehensive range queries for logs and metric series (
execute_logql_query) - Interactive frontend visualization integration (
loki_query_a2ui)
Multi-Tenancy & Security
- Native support for
X-Scope-OrgIDmulti-tenant header injection - Bearer token and HTTP Basic authentication
- Strict client-side parameter validation and rate limiting
Architecture
How it works:
- Your AI assistant connects over HTTP, SSE, or stdio and initializes the session.
- The agent reads
loki://system/healthto confirm Loki backend reachability. - The AI follows a discovery-first methodology: labels → values → field structure → preflight cost → execute.
- The service layer (
loki_service) handles HTTP calls with connection pooling, tenant header injection (X-Scope-OrgID), and response downsampling.
Tech Stack
| Category | Technologies |
|---|---|
| Language | Python 3.12+ |
| MCP Framework | FastMCP ≥ 2.13.3 |
| Protocol | Model Context Protocol (MCP) |
| Target Engine | Grafana Loki 2.9+ / 3.0+ · LogQL v2 |
| Multi-Tenancy | X-Scope-OrgID Header Injection · Basic Auth · Bearer Tokens |
| Transport Modes | stdio · http · sse · streamable-http |
| Packaging | Docker · uv |
Available Tools Summary
| Tool | Category | Description |
|---|---|---|
get_cluster_labels | Discovery | Discover global label names in the Loki cluster before querying. |
get_label_values | Discovery | Enumerate valid label values (namespaces, apps, clusters) for given selectors. |
get_active_series | Discovery | Validate active streams and inspect per-label cardinality. |
get_log_patterns | Structure | Discover recurring log shapes and auto-suggested parser pipelines. |
get_detected_fields | Structure | Discover structured JSON/logfmt fields, types, and cardinality. |
get_query_stats | Safety | Preflight query cost estimation (streams, chunks, bytes). |
execute_logql_instant | Execution | Execute point-in-time LogQL scalar and aggregation queries. |
execute_logql_query | Execution | Primary range query tool for log streams and metric time-series. |
loki_query_a2ui | UI | Format LogQL queries for interactive frontend log tables. |
Quick Start
Running with Docker
docker run --rm -it \
-p 8770:8770 \
-e MCP_TRANSPORT=http \
-e LOKI_URL=http://loki.monitoring:3100 \
talkopsai/loki-mcp-server:latest
Connect to Claude Desktop, Cursor, or Cline
Add the server to your MCP configuration file (claude_desktop_config.json or .cursor/mcp.json):
{
"mcpServers": {
"loki": {
"url": "http://localhost:8770/mcp",
"description": "TalkOps Loki MCP Server for Log Observability"
}
}
}
Or run via stdio using uvx:
{
"mcpServers": {
"loki": {
"command": "uvx",
"args": ["loki-mcp-server"],
"env": {
"LOKI_URL": "http://localhost:3100",
"MCP_LOG_LEVEL": "INFO"
}
}
}
}
Security Considerations
- Guardrail Protection: Default query limits (
LOKI_MAX_QUERY_BYTES=5000000000) reject accidental whole-cluster searches before they execute on your queriers. - Tenant Isolation: When operating in multi-tenant environments, configure
LOKI_ORG_IDto restrict the agent's query scope to authorized tenant boundaries. - Network Boundaries: Place the Loki MCP server in the same private network/VPC as your Loki querier or gateway; do not expose without authentication.
Project Layout
loki-mcp-server/
├── loki_mcp_server/
│ ├── tools/ # 9 MCP Tools across 4 functional areas
│ ├── resources/ # 8 MCP Resources (loki:// URIs)
│ ├── prompts/ # 5 Guided triage workflow prompts
│ ├── services/ # Loki HTTP API wrapper with connection pooling
│ ├── server/ # FastMCP server setup & guardrail middleware
│ ├── models/ # Pydantic data schemas & LogQL models
│ ├── config.py # Environment variables & frozen configuration
│ └── main.py # Server entry point
├── tests/ # Unit and integration test suites
├── docs/ # Workflow guides and test fixtures
├── Dockerfile
├── pyproject.toml
└── README.md
Next Steps
- Configuration — Environment variables, multi-tenancy, and guardrail settings.
- Tools Reference — Complete parameter specifications and LogQL examples for all 9 tools.
- Resources Reference — 8 read-only
loki://URIs for schema discovery and static LogQL guides. - Workflows — Step-by-step incident response and query building workflows.
- Examples & Scenarios — Real-world conversational scenarios and troubleshooting examples.