Grafana-Loki MCP Server

Grafana-Loki MCP Server

A FastMCP server for querying Grafana Loki logs via the Model Context Protocol.

18
Stars
3
Forks
18
Watchers
0
Issues
Grafana-Loki MCP Server is a FastMCP-compliant server that enables querying and formatting of Grafana Loki logs using the Model Context Protocol (MCP). It supports various transport protocols (stdio and SSE) and provides tools for querying logs, retrieving labels and label values, and formatting log results in multiple output formats. The server integrates with Grafana's API, offering both command-line and environment variable configuration options for flexibility. Designed for seamless integration into AI model context workflows, it enhances log retrieval and processing in context-aware applications.

Key Features

MCP-compliant server for Grafana Loki
Query Loki logs via Grafana API
Support for stdio and SSE transport protocols
Flexible output formatting (text, JSON, markdown)
Retrieve Loki labels and label values
Configuration via environment variables or CLI arguments
Integration with FastMCP ecosystem
Max per line log processing option
Development and testing utilities
Support for Python 3.10+ installation

Use Cases

Automating log queries for Grafana Loki through context-aware platforms
Integrating Loki log data into AI model workflows via MCP
Retrieving and formatting logs for analysis in operational scripts
Fetching label names and label values from Loki for dynamic monitoring
Providing log insights to AI assistants through MCP tools
Streamlining backend diagnostics with automated log retrieval
Facilitating observability data access for AI-powered systems
Batch processing of log data with controlled output formatting
Enhancing DevOps workflows with standardized log querying
Programmatically embedding log information in context-driven applications

README

Grafana-Loki MCP Server

Test PyPI version codecov License: MIT

A FastMCP server that allows querying Loki logs from Grafana.

MCP Server Settings

json
{
  "mcpServers": {
    "loki": {
      "command": "uvx",
      "args": [
        "grafana-loki-mcp",
        "-u",
        "GRAFANA_URL",
        "-k",
        "GRAFANA_API_KEY"
      ]
    }
  }
}
  • GRAFANA_URL: URL of your Grafana instance
  • GRAFANA_API_KEY: Grafana API key with appropriate permissions

Features

  • Query Loki logs through Grafana API
  • Get Loki labels and label values
  • Format query results in different formats (text, JSON, markdown)
  • Support for both stdio and SSE transport protocols

Requirements

  • Python 3.10+
  • FastMCP
  • Requests

Installation

Using pip

bash
pip install grafana-loki-mcp

Development Setup

  1. Clone this repository
  2. Install dependencies using uv:
bash
# Install uv
pip install uv

# Create and activate virtual environment
uv venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install dependencies
uv pip install -e ".[dev]"

Usage

Environment Variables

Set the following environment variables:

  • GRAFANA_URL: URL of your Grafana instance
  • GRAFANA_API_KEY: Grafana API key with appropriate permissions

Command Line Arguments

You can also provide these values as command line arguments:

bash
grafana-loki-mcp -u https://your-grafana-instance.com -k your-api-key

Additional options:

  • --transport: Transport protocol to use (stdio or sse, default: stdio)

Running the Server

bash
# Using environment variables
export GRAFANA_URL=https://your-grafana-instance.com
export GRAFANA_API_KEY=your-api-key
grafana-loki-mcp

# Using command line arguments
grafana-loki-mcp -u https://your-grafana-instance.com -k your-api-key

# Using SSE transport
grafana-loki-mcp --transport sse

Development

Testing

Run the test suite:

bash
pytest

Run with coverage:

bash
pytest --cov=. --cov-report=term

Linting and Formatting

bash
# Run ruff linter
ruff check .

# Run black formatter
black .

# Run type checking
mypy .

Available Tools

query_loki

Query Loki logs through Grafana.

Parameters:

  • query: Loki query string
  • start: Start time (ISO format, Unix timestamp, or Grafana-style relative time like 'now-1h', default: 1 hour ago)
  • end: End time (ISO format, Unix timestamp, or Grafana-style relative time like 'now', default: now)
  • limit: Maximum number of log lines to return (default: 100)
  • direction: Query direction ('forward' or 'backward', default: 'backward')
  • max_per_line: Maximum characters per log line (0 for unlimited, default: 100)

get_loki_labels

Get all label names from Loki.

get_loki_label_values

Get values for a specific label from Loki.

Parameters:

  • label: Label name

format_loki_results

Format Loki query results in a more readable format.

Parameters:

  • results: Loki query results from query_loki
  • format_type: Output format ('text', 'json', or 'markdown', default: 'text')
  • max_per_line: Maximum characters per log line (0 for unlimited, default: 0)

Example Usage

python
# Example client code
from mcp.client import Client

async with Client() as client:
    # Query Loki logs with max_per_line limit
    results = await client.call_tool(
        "query_loki",
        {
            "query": '{app="my-app"} |= "error"',
            "limit": 50,
            "max_per_line": 100,  # Limit log lines to 100 characters
            "start": "now-6h",    # Grafana-style relative time: 6 hours ago
            "end": "now"          # Current time
        }
    )

    # Format the results
    formatted = await client.call_tool(
        "format_loki_results",
        {
            "results": results,
            "format_type": "markdown",
            "max_per_line": 100  # Can also limit at formatting time
        }
    )

    print(formatted)

License

This project is licensed under the MIT License - see the LICENSE file for details.

Star History

Star History Chart

Repository Owner

tumf
tumf

User

Repository Details

Language Python
Default Branch main
Size 193 KB
Contributors 6
License MIT License
MCP Verified Nov 12, 2025

Programming Languages

Python
93.18%
Makefile
6.82%

Tags

Join Our Newsletter

Stay updated with the latest AI tools, news, and offers by subscribing to our weekly newsletter.

We respect your privacy. Unsubscribe at any time.

Related MCPs

Discover similar Model Context Protocol servers

  • PMCP

    PMCP

    Golang Model Context Protocol server for natural language Prometheus queries

    PMCP implements a Model Context Protocol (MCP) server in Go, enabling natural language access and manipulation of Prometheus metrics. It maintains full consistency with the Prometheus HTTP API and supports a robust, type-safe interface for seamless integration with MCP-compatible clients. The server offers complete Prometheus API coverage and supports multiple transport methods, including HTTP and Server-Sent Events. Its modular architecture is designed for performance, extensibility, and effective error handling.

    • 3
    • MCP
    • yshngg/pmcp
  • VictoriaMetrics MCP Server

    VictoriaMetrics MCP Server

    Model Context Protocol server enabling advanced monitoring and observability for VictoriaMetrics.

    VictoriaMetrics MCP Server implements the Model Context Protocol (MCP) to provide seamless integration with VictoriaMetrics, allowing advanced monitoring, data exploration, and observability. It offers access to almost all read-only APIs, as well as embedded documentation for offline usage. The server facilitates comprehensive metric querying, cardinality analysis, alert and rule testing, and automation capabilities for engineers and tools.

    • 87
    • MCP
    • VictoriaMetrics-Community/mcp-victoriametrics
  • Gopher & Gemini MCP Server

    Gopher & Gemini MCP Server

    A modern Model Context Protocol server for AI-driven exploration of Gopher and Gemini resources.

    Gopher & Gemini MCP Server provides a secure and efficient bridge for AI assistants to interact with resources on vintage Gopher and modern Gemini protocols using the Model Context Protocol (MCP) standard. It is built with FastMCP, delivers structured JSON responses optimized for LLMs, and supports comprehensive protocol coverage with advanced security and performance features. The server implements robust safeguards, certificate validation, and works cross-platform with modern Python tooling.

    • 4
    • MCP
    • cameronrye/gopher-mcp
  • mcp-log-proxy

    mcp-log-proxy

    Web-based proxy for inspecting Model Context Protocol traffic in real time.

    mcp-log-proxy enables users to observe and debug messages exchanged between MCP clients and servers through a user-friendly web interface. It supports the STDIO interface and can operate multiple proxy instances, each accessible via a web dashboard. The tool allows customization of ports, web page titles, and log file locations, making it suitable for managing and troubleshooting MCP-based model communication. Installation is straightforward via Homebrew or Go, and it supports real-time switching between different running proxies.

    • 26
    • MCP
    • emicklei/mcp-log-proxy
  • @dealx/mcp-server

    @dealx/mcp-server

    MCP server enabling LLMs to search and interact with the DealX platform.

    Implements the Model Context Protocol, providing a standardized interface for large language models to interact with the DealX platform. Supports searching for ads through structured prompts and is designed for easy integration with tools like Claude and VS Code extensions. Flexible configuration options are available for environment variables, logging, and deployment. Extensible architecture supports future feature additions beyond ad search.

    • 0
    • MCP
    • DealExpress/mcp-server
  • DuckDuckGo Search MCP Server

    DuckDuckGo Search MCP Server

    A Model Context Protocol server for DuckDuckGo web search and intelligent content retrieval.

    DuckDuckGo Search MCP Server provides web search capabilities through DuckDuckGo, with advanced content fetching and parsing tailored for large language models. It supports rate limiting, error handling, and delivers results in an LLM-friendly format. The server is designed for seamless integration with AI applications and tools like Claude Desktop, enabling enhanced web search and content extraction through the Model Context Protocol.

    • 637
    • MCP
    • nickclyde/duckduckgo-mcp-server
  • Didn't find tool you were looking for?

    Be as detailed as possible for better results