MCP Connector

Query and Analyze Grafana Loki Logs

MCP server for querying and searching Grafana Loki logs via LogQL, keyword search, and label discovery, with caching and auth options.

Works with grafanaloki

91
Spark score
out of 100
Updated 10 months ago
Version 1.0.0
Models
universal

Add to Favorites

Why it matters

Enable AI assistants to intelligently query, analyze, and troubleshoot logs from Grafana Loki. This asset provides structured access to log data for enhanced monitoring and debugging.

Outcomes

What it gets done

01

Execute LogQL queries against Loki

02

Search logs with advanced filtering

03

Discover available log labels for exploration

04

Monitor workflows using log data

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/vb-loki-mcp-server | bash

Capabilities

Tools your agent gets

query_logs

Execute LogQL queries directly against Loki with support for range and instant queries

search_logs

Search logs by keywords with advanced filtering and pattern matching

get_labels

Discover available labels and their values for stream exploration

Overview

Loki MCP Server

Gives AI assistants three tools to query Grafana Loki logs via LogQL, search by keyword with AND/OR filtering, and discover labels, with built-in caching, basic auth, and bearer-token support. Use when an assistant needs to query, search, or explore Loki logs for troubleshooting or monitoring; requires network access to a running Loki instance and, if secured, valid credentials.

What it does

Loki MCP Server gives AI assistants the ability to query and analyze logs from Grafana Loki over the Model Context Protocol, enabling log analysis, troubleshooting, and monitoring workflows directly in conversation. It exposes three tools. query_logs executes a LogQL query directly against Loki, accepting the query string plus optional start/end times for range queries, a result limit (default 100), and a direction of forward or backward. search_logs performs keyword-based log searching with advanced filtering: required keywords, optional label filters as key-value pairs, an optional time range, a result limit (default 100), case sensitivity control (default false), and a logical operator of AND or OR between keywords. get_labels discovers available log labels and their values for stream exploration, optionally scoped to a specific label name and time range, with cached results used by default unless disabled.

The server includes built-in caching and optimized query execution for performance, supports multiple authentication methods (basic auth and bearer tokens), and returns structured results with timestamps, labels, and context information rather than raw log dumps.

When to use - and when NOT to

Use this when an AI assistant needs to search, filter, or analyze logs stored in Grafana Loki - running an ad hoc LogQL query, doing a keyword search across log streams with AND/OR logic, or discovering what labels and label values exist before writing a more targeted query. It requires network connectivity to a running, healthy Loki instance and, depending on the deployment, either basic auth credentials or a bearer token.

Capabilities

The project structure separates a basic Loki client from an enhanced client with additional features, a dedicated LogQL query builder, and a centralized error handler for classifying failures. The test suite covers unit tests for individual components, integration tests for the MCP protocol and Loki interaction, performance benchmarks for query execution, and mock tests using simulated Loki responses - runnable via pytest, including with coverage reporting. Documented troubleshooting covers connection errors (verifying LOKI_URL and network/firewall access), authentication errors (verifying credentials or bearer token validity), and query errors (validating LogQL syntax, confirming label names/values exist, and sanity-checking the time range).

How to install

Install from source:

git clone <repository-url>
cd loki-mcp-server
pip install -e .

Required configuration is LOKI_URL, the address of the Loki instance; optional variables add basic auth (LOKI_USERNAME/LOKI_PASSWORD) or bearer-token auth (LOKI_BEARER_TOKEN), settable as environment variables or in a project .env file. The server starts via the loki-mcp-server command and listens for MCP protocol messages over stdio. For Claude Desktop, it's registered with command loki-mcp-server and the LOKI_URL (and any auth variables) passed through the env block. Development installs add the [dev] extra via pip install -e .[dev], and code quality is enforced with black/isort for formatting, mypy for type checking, and ruff for linting.

Who it's for

SRE, DevOps, and platform engineers using Grafana Loki who want an AI assistant to run LogQL queries, search logs by keyword, and explore available labels conversationally during troubleshooting or monitoring.

Source README

Loki MCP Server

A Model Context Protocol (MCP) server that provides AI assistants with the ability to query and analyze logs from Grafana Loki. This server enables seamless integration between AI assistants and Loki, allowing for intelligent log analysis, troubleshooting, and monitoring workflows.

Architecture

┌─────────────────┐    MCP Protocol    ┌─────────────────┐    HTTP/API    ┌─────────────────┐
│   AI Assistant │ ◄─────────────────► │ Loki MCP Server │ ◄─────────────►│  Grafana Loki   │
│   (Claude et al)│                    │                 │                │   Log System    │
└─────────────────┘                    └─────────────────┘                └─────────────────┘

Features

  • 🔍 Query Logs: Execute LogQL queries against Loki with support for range and instant queries
  • 🔎 Search Logs: Keyword-based log searching with advanced filtering and pattern matching
  • 🏷️ Label Discovery: Retrieve available log labels and label values for stream exploration
  • 🤖 MCP Protocol: Fully compatible with Model Context Protocol for AI assistant integration
  • Performance: Built-in caching and optimized query execution
  • 🛡️ Security: Support for multiple authentication methods (basic auth, bearer tokens)
  • 📊 Rich Results: Structured output with timestamps, labels, and context information

Installation

From Source

  1. Clone the repository:
git clone <repository-url>
cd loki-mcp-server
  1. Install the package:
pip install -e .

Development Installation

For development work, install with development dependencies:

pip install -e ".[dev]"

Requirements

  • Python 3.8 or higher
  • Access to a Grafana Loki instance
  • Network connectivity to your Loki server

Configuration

Environment Variables

Configure the server using these environment variables:

Variable Required Description Example
LOKI_URL Yes URL of your Loki instance http://localhost:3100
LOKI_USERNAME No Username for basic authentication admin
LOKI_PASSWORD No Password for basic authentication password123
LOKI_BEARER_TOKEN No Bearer token for authentication your-token-here

Configuration Examples

Local Development
export LOKI_URL="http://localhost:3100"
Production with Basic Auth
export LOKI_URL="https://loki.example.com"
export LOKI_USERNAME="service-account"
export LOKI_PASSWORD="secure-password"
Production with Bearer Token
export LOKI_URL="https://loki.example.com"
export LOKI_BEARER_TOKEN="your-api-token"

Configuration File (Optional)

You can also use a .env file in your project directory:

LOKI_URL=http://localhost:3100
LOKI_USERNAME=admin
LOKI_PASSWORD=password123

Usage

Starting the Server

Start the MCP server using the command line:

loki-mcp-server

The server will start and listen for MCP protocol messages via stdio.

Integration with AI Assistants

Add the server to your AI assistant's MCP configuration. Example for Claude Desktop:

{
  "mcpServers": {
    "loki": {
      "command": "loki-mcp-server",
      "env": {
        "LOKI_URL": "http://localhost:3100"
      }
    }
  }
}

Available Tools

The server provides three main tools for log analysis:

1. query_logs

Execute LogQL queries directly against Loki.

Parameters:

  • query (required): LogQL query string
  • start (optional): Start time for range queries
  • end (optional): End time for range queries
  • limit (optional): Maximum entries to return (default: 100)
  • direction (optional): Query direction ('forward' or 'backward')
2. search_logs

Search logs using keywords with advanced filtering.

Parameters:

  • keywords (required): List of keywords to search for
  • labels (optional): Label filters as key-value pairs
  • start (optional): Start time for search range
  • end (optional): End time for search range
  • limit (optional): Maximum entries to return (default: 100)
  • case_sensitive (optional): Case-sensitive search (default: false)
  • operator (optional): Logical operator ('AND' or 'OR')
3. get_labels

Discover available labels and their values.

Parameters:

  • label_name (optional): Specific label to get values for
  • start (optional): Start time for label query
  • end (optional): End time for label query
  • use_cache (optional): Use cached results (default: true)

Development

Setup Development Environment

  1. Clone and install:
git clone <repository-url>
cd loki-mcp-server
pip install -e ".[dev]"
  1. Run tests:
pytest
  1. Run specific test suites:
# Unit tests only
pytest tests/unit/

# Integration tests only  
pytest tests/integration/

# Performance tests
pytest tests/performance/

Code Quality

Run linting and formatting:

# Format code
black .
isort .

# Type checking
mypy app/

# Linting
ruff check .

Project Structure

loki-mcp-server/
├── app/          # Main package
│   ├── __init__.py
│   ├── main.py               # CLI entry point
│   ├── server.py             # MCP server implementation
│   ├── config.py             # Configuration management
│   ├── loki_client.py        # Basic Loki client
│   ├── enhanced_client.py    # Enhanced client with features
│   ├── query_builder.py      # LogQL query building
│   ├── error_handler.py      # Error classification and handling
│   ├── logging_config.py     # Logging setup
│   └── tools/                # MCP tools
│       ├── query_logs.py     # LogQL query tool
│       ├── search_logs.py    # Keyword search tool
│       └── get_labels.py     # Label discovery tool
├── tests/                    # Test suite
├── pyproject.toml           # Project configuration
└── README.md               # This file

Testing

The project includes comprehensive tests:

  • Unit Tests: Test individual components in isolation
  • Integration Tests: Test MCP protocol and Loki integration
  • Performance Tests: Benchmark query performance
  • Mock Tests: Test with simulated Loki responses

Run all tests:

pytest

Run with coverage:

pytest --cov=app --cov-report=html

Troubleshooting

Common Issues

Connection Errors
  • Verify LOKI_URL is correct and accessible
  • Check firewall and network connectivity
  • Ensure Loki is running and healthy
Authentication Errors
  • Verify credentials are correct
  • Check if Loki requires authentication
  • Ensure bearer token is valid and not expired
Query Errors
  • Validate LogQL syntax
  • Check label names and values exist
  • Verify time range is reasonable

Debug Mode

Enable debug logging by setting:

export PYTHONPATH=.
python -m app.main --debug

Getting Help

  1. Check the troubleshooting guide in docs/troubleshooting.md
  2. Review example configurations in examples/
  3. Run the test suite to verify your setup
  4. Check Loki server logs for additional context

FAQ

Common questions

Discussion

Questions & comments · 0

Sign In Sign in to leave a comment.