Loki MCP Server
Servidor MCP de Loki simple
El servidor MCP de Loki es una interfaz de Protocolo de Contexto de Modelo (MCP) para consultar los registros de Grafana Loki mediante logcli . El servidor permite a los asistentes de IA acceder y analizar los datos de registro de Loki directamente.
Características
Consulta de registros de Loki con compatibilidad total con LogQL
Obtener valores de etiquetas y metadatos
Soporte de autenticación y configuración a través de variables de entorno o archivos de configuración
Proporciona resultados formateados en diferentes formatos de salida (predeterminado, sin procesar, líneas JSON)
Retorno automático a la API HTTP cuando
logclino está disponible en el entorno
Related MCP server: Loki MCP Server
Prerrequisitos
Node.js v16 o superior
Mecanografiado
(Opcional) Logcli de Grafana Loki instalado y accesible en su PATH. Si
logclino está disponible, el servidor usará automáticamente la API HTTP de Loki.Acceso a una instancia del servidor Loki
Instalación
Instalación mediante herrería
Para instalar Simple Loki MCP Server para Claude Desktop automáticamente a través de Smithery :
npx -y @smithery/cli install @ghrud92/simple-loki-mcp --client claudepara MCP
{
"mcpServers": {
"simple-loki": {
"command": "npx",
"args": ["-y", "simple-loki-mcp"],
"env": {
"LOKI_ADDR": "https://loki.sup.band"
}
}
}
}npm
Clonar el repositorio:
git clone https://github.com/ghrud92/loki-mcp.git
cd loki-mcpInstalar dependencias:
npm installConstruir el proyecto:
npm run buildHerramientas MCP disponibles
consulta-loki
Consultar registros de Loki con opciones de filtrado.
Parámetros:
query(obligatoria): cadena de consulta de Loki (LogQL)from: Marca de tiempo de inicio (p. ej., "2023-01-01T12:00:00Z")to: Marca de tiempo de finalización (p. ej., "2023-01-01T13:00:00Z")limit: Número máximo de registros a devolverbatch: tamaño del lote para los resultados de la consultaoutput: Formato de salida ("predeterminado", "sin procesar" o "jsonl")quiet: suprimir metadatos de consultaforward: Mostrar los resultados en orden cronológico
obtener valores de etiqueta
Recuperar todos los valores para una etiqueta específica.
Parámetros:
label(obligatorio): Nombre de la etiqueta para la que se obtendrán los valores
obtener etiquetas
Recupere todas las etiquetas disponibles.
No se requieren parámetros.
Configuración
Puedes configurar el acceso a Loki usando:
Variables de entorno
LOKI_ADDR: Dirección del servidor Loki (URL)LOKI_USERNAME: Nombre de usuario para autenticación básicaLOKI_PASSWORD: Contraseña para autenticación básicaLOKI_TENANT_ID: ID de inquilino para Loki multiinquilinoLOKI_BEARER_TOKEN: Token portador para autenticaciónLOKI_BEARER_TOKEN_FILE: Archivo que contiene el token portadorLOKI_CA_FILE: Archivo CA personalizado para TLSLOKI_CERT_FILE: Archivo de certificado de cliente para TLSLOKI_KEY_FILE: Archivo de clave de cliente para TLSLOKI_ORG_ID: ID de organización para configuraciones multiorganizacionalesLOKI_TLS_SKIP_VERIFY: Omitir la verificación TLS ("verdadero" o "falso")LOKI_CONFIG_PATH: Ruta personalizada al archivo de configuraciónDEBUG: Habilitar el registro de depuración
Nota : Cuando el cliente utiliza el modo API HTTP (cuando
logclino está disponible), se utilizan los mismos parámetros de configuración para autenticarse y conectarse al servidor Loki.
Archivos de configuración
Alternativamente, cree un archivo logcli-config.yaml en una de estas ubicaciones:
Ruta personalizada especificada por
LOKI_CONFIG_PATHDirectorio de trabajo actual
Su directorio de inicio (
~/.logcli-config.yaml)
Ejemplo de archivo de configuración:
addr: https://loki.example.com
username: user
password: pass
tenant_id: mytenantUso
Iniciar el servidor:
npm startPara desarrollo:
npm run devDetalles de implementación
Retorno automático a la API HTTP
El servidor comprobará automáticamente si logcli está instalado y disponible en el entorno:
Si
logcliestá disponible, se utilizará para todas las consultas, proporcionando la funcionalidad completa de la herramienta CLI.Si
logclino está disponible, el servidor recurrirá automáticamente al uso de la API HTTP de Loki:No se necesita ninguna configuración adicional
Los mismos parámetros de autenticación se utilizan para la API HTTP
El formato de la respuesta es consistente con la salida de la CLI
El límite predeterminado de 1000 registros por consulta se aplica en ambos modos
Esta detección automática garantiza que el servidor funcione sin problemas en diferentes entornos sin necesidad de configuración manual.
Desarrollo
# Run linter
npm run lint
# Fix linting issues
npm run lint:fix
# Run tests
npm run testLicencia
Este proyecto está licenciado bajo la licencia MIT: consulte el archivo LICENSE.md para obtener más detalles.
Available Tools
3 toolsget_labelsD
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Tool has no description.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Tool has no description.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Tool has no description.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Tool has no description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Tool has no description.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Tool has no description.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_label_valuesD
| Name | Required | Description | Default |
|---|---|---|---|
| label | Yes | Label name to get values for |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Tool has no description.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Tool has no description.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Tool has no description.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Tool has no description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Tool has no description.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Tool has no description.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
query_lokiD
| Name | Required | Description | Default |
|---|---|---|---|
| batch | No | Batch size for query results | |
| forward | No | Display results in chronological order | |
| from | No | Start timestamp in UTC (e.g. '2023-01-01T12:00:00Z'). Relative time expressions like '1h ago' are not supported. Use ISO 8601 format. | |
| limit | No | Maximum number of logs to return. Maximum value is 1000 | |
| output | No | Output format - valid values are 'default' (formatted log lines), 'raw' (unprocessed log lines), or 'jsonl' (JSON Lines format). Note: values like 'text' or 'json' are not supported. | |
| query | Yes | Loki query string | |
| quiet | No | Suppress query metadata | |
| to | No | End timestamp in UTC (e.g. '2023-01-01T13:00:00Z'). Relative time expressions like 'now' are not supported. Use ISO 8601 format. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Tool has no description.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Tool has no description.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Tool has no description.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Tool has no description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Tool has no description.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Tool has no description.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
3 tool updates
v1.0.0- First observed
get_label_values - First observed
get_labels - First observed
query_loki
TDQS
Scored across 3 tools
Each tool has a clearly distinct purpose: get_labels retrieves label names, get_label_values fetches values for a specific label, and query_loki performs log queries. There is no overlap or ambiguity between these functions.
All tool names follow a consistent verb_noun pattern with snake_case (get_labels, get_label_values, query_loki). The naming is predictable and uniform throughout the set.
With only 3 tools, the set feels thin for a Loki server, which typically handles log management and querying. While the tools cover basic operations, more functionality (e.g., log ingestion, stream management) might be expected.
The tool surface is severely incomplete for a Loki server. It lacks essential operations like pushing logs, managing log streams, configuring settings, or performing advanced queries, leaving significant gaps that could cause agent failures.
Maintenance
Related MCP Connectors
Query application logs, traces, and metrics from your AI coding assistant via Foam's MCP server.
- SpanlyOAuthcom.spanly
MCP observability. Query live traffic, errors, duration, and alerts from your AI agent.
A paid remote MCP for AI SDK data query MCP, built to return verdicts, receipts, usage logs, and aud
The Grafbase MCP server sits in front of a GraphQL API and exposes an MCP protocol-compliant interface that allows AI agents and LLMs to explore and query GraphQL APIs using natural language. It provides tools to search schemas, introspect types and fields, and execute GraphQL queries while minimizing context bloat by returning only relevant schema subsets, with built-in support for authentication, authorization, and configurable access control.
Related MCP Servers
- AlicenseAqualityDmaintenanceA server that enables AI assistants to access and query Grafana dashboards, metrics, logs, and configurations through an MCP protocol interface.106MIT
- FlicenseNot gradedqualityDmaintenanceEnables AI models to query and analyze Kubernetes cluster logs through Grafana Loki, supporting semantic operations like error aggregation and pod restart detection. It provides tools for regex-based log searching and namespace discovery to facilitate natural language troubleshooting.-
- AlicenseNot gradedqualityBmaintenanceThis MCP server enables natural-language querying of Grafana logs by automatically detecting log sources and service labels. It provides read-only access to log data with intelligent caching for efficient repeat queries.12 npmMIT
- FlicenseNot gradedqualityDmaintenanceAn MCP server that enables AI assistants to query and analyze logs from Grafana Loki using LogQL, supporting label discovery and keyword search.4-