loki-mcp-server
Enables querying and analyzing logs from Grafana Loki, providing tools for executing LogQL queries, searching logs by keywords, and discovering log labels.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@loki-mcp-servershow errors from the last hour in production"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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 │
└─────────────────┘ └─────────────────┘ └─────────────────┘Related MCP server: Grafana MCP Server
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
Clone the repository:
git clone <repository-url>
cd loki-mcp-serverInstall 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 |
| Yes | URL of your Loki instance |
|
| No | Username for basic authentication |
|
| No | Password for basic authentication |
|
| No | Bearer token for authentication |
|
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=password123Usage
Starting the Server
Start the MCP server using the command line:
loki-mcp-serverThe 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 stringstart(optional): Start time for range queriesend(optional): End time for range querieslimit(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 forlabels(optional): Label filters as key-value pairsstart(optional): Start time for search rangeend(optional): End time for search rangelimit(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 forstart(optional): Start time for label queryend(optional): End time for label queryuse_cache(optional): Use cached results (default: true)
Development
Setup Development Environment
Clone and install:
git clone <repository-url>
cd loki-mcp-server
pip install -e ".[dev]"Run tests:
pytestRun 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 fileTesting
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:
pytestRun with coverage:
pytest --cov=app --cov-report=htmlTroubleshooting
Common Issues
Connection Errors
Verify
LOKI_URLis correct and accessibleCheck 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 --debugGetting Help
Check the troubleshooting guide in
docs/troubleshooting.mdReview example configurations in
examples/Run the test suite to verify your setup
Check Loki server logs for additional context
License
MIT License - see LICENSE file for details.
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Latest Blog Posts
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/mo-silent/loki-mcp-server'
If you have feedback or need assistance with the MCP directory API, please join our Discord server