Loki MCP Server

repository·main·Indexed 41 days ago

https://github.com/grafana/loki-mcp

A Go-based implementation of the Model Context Protocol (MCP) that enables AI agents and clients to interact with Grafana Loki log data using LogQL queries. It supports both stdio and HTTP (SSE) communication modes and integrates with tools like Claude Desktop, Cursor, and n8n.

Tokens
4.3K
Snippets
14
Records
17
Agent score
52%

What's inside Loki MCP

  1. Query Loki using Natural Language

    main

    The Loki MCP server allows AI assistants to map natural language terms to specific Loki query parameters.

    Organization/Tenant Mapping

    Terms like organization, org, tenant, or organization ID are automatically mapped to the org parameter, which is sent as the X-Scope-OrgID header.

    Examples of effective prompts:

    • "Query Loki for logs from organization 'tenant-123' with the query {job="varlogs"}"
    • "Find all logs from customer organization 'customer-xyz' for the last hour"
    • "Switch to organization 'dev-team' and query {job="logs"}"

    General Querying

    Users can specify queries, time ranges, and limits naturally:

    • "Find error logs from the last hour in Loki using query {job="varlogs"} |= "ERROR""
    • "Show me the most recent 50 logs from Loki with job=varlogs"
    • "Query Loki for organization 'prod-cluster' from 2 hours ago to now with limit 50"
  2. Integrate Loki MCP Server with Claude Desktop

    main

    You can add Loki query capabilities to Claude Desktop using one of three methods. Docker is the recommended and most reliable approach as it packages all dependencies and environment variables.

    Option 1: Using the Compiled Binary

    1. Build the server:
    go build -o loki-mcp-server ./cmd/server
    1. Use the configuration template claude_desktop_config_binary.json in your Claude Desktop config file.

    Option 2: Using Go Run with a Shell Script

    1. Make the script executable:
    chmod +x run-mcp-server.sh
    1. Use the configuration template claude_desktop_config_script.json in your Claude Desktop config file.
    1. Build the Docker image:
    docker build -t loki-mcp-server .
    1. Use the configuration template claude_desktop_config_docker.json in your Claude Desktop config file.

    Configuration File Locations

    • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
    • Windows: %APPDATA%\Claude\claude_desktop_config.json
    • Linux: ~/.config/Claude/claude_desktop_config.json

    Note for go run users: You may need to explicitly set HOME, GOPATH, GOMODCACHE, and GOCACHE in both your script and the Claude configuration to ensure Go can locate modules and build caches.

  3. Integrate Loki MCP Server with Cursor

    main

    To use the Loki query tool within the Cursor editor, add the following configuration to your Cursor settings. This example uses the Docker method, which is the most reliable for Cursor integration.

    Note: When using Docker with Cursor, ensure you use http://host.docker.internal:3100 if your Loki instance is running on your host machine.

    {
      "mcpServers": {
        "loki-mcp-server": {
          "command": "docker",
          "args": ["run", "--rm", "-i", 
                   "-e", "LOKI_URL=http://host.docker.internal:3100", 
                   "-e", "LOKI_ORG_ID=your-default-org-id",
                   "-e", "LOKI_USERNAME=your-username",
                   "-e", "LOKI_PASSWORD=your-password",
                   "-e", "LOKI_TOKEN=your-bearer-token",
                   "loki-mcp-server:latest"]
        }
      }
    }
  4. Local testing with Docker Compose

    main

    The project includes a Docker Compose setup for local end-to-end testing, which includes Loki, Grafana, a log generator, and the MCP server.

    1. Start the environment

    docker-compose up -d

    2. Run test queries

    Use the provided shell scripts to test the setup:

    Default query (last 15 mins):

    ./test-loki-query.sh

    Query for error logs:

    ./test-loki-query.sh '{job="varlogs"} |= "ERROR"'

    Custom time range and limit:

    ./test-loki-query.sh '{job="varlogs"}' '-1h' 'now' 50

    3. Insert dummy logs

    You can manually trigger log insertion for testing:

    # Insert 20 logs with custom job and app name
    ./insert-loki-logs.sh --num 20 --job "custom-job" --app "my-app"
    # Start the Docker Compose environment
    docker-compose up -d
    
    # Run with default parameters
    ./test-loki-query.sh
    
    # Query for error logs
    ./test-loki-query.sh '{job="varlogs"} |= "ERROR"'
    
    # Specify a custom time range and limit
    ./test-loki-query.sh '{job="varlogs"}' '-1h' 'now' 50
  5. Install and run the Loki MCP Server

    main

    The Loki MCP Server is a Go-based implementation of the Model Context Protocol with Grafana Loki integration. It can be run via Go or Docker.

    Prerequisites

    • Go 1.16 or higher

    Running with Go

    Build the server binary and run it:

    go build -o loki-mcp-server ./cmd/server
    ./loki-mcp-server

    Alternatively, run it directly using go run:

    go run ./cmd/server

    Running with Docker

    You can build and run the server using Docker images:

    # Build the Docker image
    docker build -t loki-mcp-server .
    
    # Run the server
    docker run --rm -i loki-mcp-server

    To use Docker Compose:

    docker-compose up --build
    # Build the server
    go build -o loki-mcp-server ./cmd/server
    
    # Run the server
    ./loki-mcp-server
  6. Configure SSE mode and n8n integration

    main

    The server supports two communication modes:

    1. Standard input/output (stdin/stdout): Default for MCP clients like Claude Desktop.
    2. HTTP Server with Server-Sent Events (SSE): For integration with tools like n8n.

    SSE Configuration

    The HTTP server runs on port 8080 by default, which can be changed using the SSE_PORT environment variable.

    Endpoints:

    • SSE Endpoint: http://localhost:8080/sse (for real-time event streaming)
    • MCP Endpoint: http://localhost:8080/mcp (for MCP protocol messaging)

    To run with Docker and expose the SSE port:

    docker run -p 8080:8080 --rm -i loki-mcp-server

    n8n Integration

    1. Install the MCP Client Tools node in n8n.
    2. Configure the node with the SSE Endpoint (e.g., http://your-server-address:8080/sse).
    3. Select the Loki tools to expose to the AI Agent.
    4. Connect the node to an AI Agent node.
    # Run the server with port mapping
    docker run -p 8080:8080 --rm -i loki-mcp-server
  7. Run the Loki MCP Server

    main

    The Loki MCP server can be run in two modes: via stdio (standard input/output) for local MCP clients, or via HTTP (SSE or Streamable HTTP) for remote connections.

    By default, the HTTP server listens on port 8080. You can change this by setting the PORT environment variable.

    HTTP Endpoints

    • SSE (Legacy): /sse (event stream) and /mcp (message endpoint).
    • Streamable HTTP: /stream.

    Stdio Mode

    The server also supports stdio for backward compatibility, allowing it to be used as a local subprocess by MCP-compatible clients.

    # Run with default port 8080
    ./loki-mcp-server
    
    # Run on a custom port
    PORT=9000 ./loki-mcp-server
  8. Test the MCP Server with the CLI client

    main

    A test client is provided in cmd/client to interact with the MCP server.

    Build the client

    go build -o loki-mcp-client ./cmd/client

    Query Examples

    Basic query:

    ./loki-mcp-client loki_query "{job=\"varlogs\"}"

    Query with time range and limit:

    ./loki-mcp-client loki_query "{job=\"varlogs\"}" "-1h" "now" 100

    Query using environment variables (URL and Org ID):

    export LOKI_URL="http://localhost:3100"
    export LOKI_ORG_ID="tenant-123"
    ./loki-mcp-client loki_query "{job=\"varlogs\"}"

    Query using bearer token:

    export LOKI_URL="http://localhost:3100"
    export LOKI_TOKEN="your-bearer-token"
    ./loki-mcp-client loki_query "{job=\"varlogs\"}"
    # Build the client
    go build -o loki-mcp-client ./cmd/client
    
    # Loki query examples:
    ./loki-mcp-client loki_query "{job=\"varlogs\"}"
    ./loki-mcp-client loki_query "{job=\"varlogs\"}" "-1h" "now" 100
  9. Use the `loki_query` tool

    main

    The loki_query tool allows you to query Grafana Loki log data using LogQL.

    Parameters

    ParameterTypeDescription
    queryRequiredLogQL query string
    urlOptionalThe Loki server URL (defaults to LOKI_URL env var or http://localhost:3100)
    startOptionalStart time for the query (default: 1h ago)
    endOptionalEnd time for the query (default: now)
    limitOptionalMaximum number of entries to return (default: 100)
    orgOptionalOrganization ID (sent as X-Scope-OrgID header)

    Authentication via Environment Variables

    The tool supports the following environment variables for authentication and configuration:

    • LOKI_URL: Default Loki server URL
    • LOKI_ORG_ID: Default organization ID
    • LOKI_USERNAME: Default username for basic authentication
    • LOKI_PASSWORD: Default password for basic authentication
    • LOKI_TOKEN: Default bearer token for authentication
  10. Configure the Loki MCP Server via Docker Compose

    main

    The loki-mcp-server service can be configured using environment variables to specify the connection to Loki and the server port.

    Key environment variables:

    • LOKI_URL: The endpoint for the Loki instance (e.g., http://loki:3100).
    • PORT: The port on which the MCP server listens (default is 8080).

    The service exposes port 8080 to the host.

    loki-mcp-server:
      image: loki-mcp-server:latest
      ports:
        - "8080:8080"
      environment:
        - LOKI_URL=http://loki:3100
        - PORT=8080
      depends_on:
        loki:
          condition: service_healthy
  11. Run Tests for Loki MCP Server

    main

    The project uses Go's testing toolchain. Use the following commands to verify the server implementation:

    • Run all tests: go test ./...
    • Run tests with coverage: go test -coverprofile=coverage.out ./... followed by go tool cover -func=coverage.out to view results.
    • Run tests with race detection: go test -race ./...
    # Run all tests
    go test ./...
    
    # Run tests with coverage
    go test -coverprofile=coverage.out ./...
    go tool cover -func=coverage.out
    
    # Run tests with race detection
    go test -race ./...