Skip to main content
Glama
ghrud92

Loki MCP Server

by ghrud92

Servidor MCP de Loki simple

insignia de herrería

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 logcli no 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 logcli no 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 claude

para MCP

{
  "mcpServers": {
    "simple-loki": {
      "command": "npx",
      "args": ["-y", "simple-loki-mcp"],
      "env": {
        "LOKI_ADDR": "https://loki.sup.band"
      }
    }
  }
}

npm

  1. Clonar el repositorio:

git clone https://github.com/ghrud92/loki-mcp.git
cd loki-mcp
  1. Instalar dependencias:

npm install
  1. Construir el proyecto:

npm run build

Herramientas 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 devolver

  • batch : tamaño del lote para los resultados de la consulta

  • output : Formato de salida ("predeterminado", "sin procesar" o "jsonl")

  • quiet : suprimir metadatos de consulta

  • forward : 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ásica

  • LOKI_PASSWORD : Contraseña para autenticación básica

  • LOKI_TENANT_ID : ID de inquilino para Loki multiinquilino

  • LOKI_BEARER_TOKEN : Token portador para autenticación

  • LOKI_BEARER_TOKEN_FILE : Archivo que contiene el token portador

  • LOKI_CA_FILE : Archivo CA personalizado para TLS

  • LOKI_CERT_FILE : Archivo de certificado de cliente para TLS

  • LOKI_KEY_FILE : Archivo de clave de cliente para TLS

  • LOKI_ORG_ID : ID de organización para configuraciones multiorganizacionales

  • LOKI_TLS_SKIP_VERIFY : Omitir la verificación TLS ("verdadero" o "falso")

  • LOKI_CONFIG_PATH : Ruta personalizada al archivo de configuración

  • DEBUG : Habilitar el registro de depuración

Nota : Cuando el cliente utiliza el modo API HTTP (cuando logcli no 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_PATH

  • Directorio 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: mytenant

Uso

Iniciar el servidor:

npm start

Para desarrollo:

npm run dev

Detalles de implementación

Retorno automático a la API HTTP

El servidor comprobará automáticamente si logcli está instalado y disponible en el entorno:

  1. Si logcli está disponible, se utilizará para todas las consultas, proporcionando la funcionalidad completa de la herramienta CLI.

  2. Si logcli no 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 test

Licencia

Este proyecto está licenciado bajo la licencia MIT: consulte el archivo LICENSE.md para obtener más detalles.

Available Tools

3 tools
get_labelsD
ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

D1/5.0
Behavior1/5

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.

Conciseness1/5

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.

Completeness1/5

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.

Parameters1/5

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.

Purpose1/5

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.

Usage Guidelines1/5

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
ParametersJSON Schema
NameRequiredDescriptionDefault
labelYesLabel name to get values for

TDQS

D1/5.0
Behavior1/5

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.

Conciseness1/5

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.

Completeness1/5

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.

Parameters1/5

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.

Purpose1/5

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.

Usage Guidelines1/5

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
ParametersJSON Schema
NameRequiredDescriptionDefault
batchNoBatch size for query results
forwardNoDisplay results in chronological order
fromNoStart timestamp in UTC (e.g. '2023-01-01T12:00:00Z'). Relative time expressions like '1h ago' are not supported. Use ISO 8601 format.
limitNoMaximum number of logs to return. Maximum value is 1000
outputNoOutput 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.
queryYesLoki query string
quietNoSuppress query metadata
toNoEnd timestamp in UTC (e.g. '2023-01-01T13:00:00Z'). Relative time expressions like 'now' are not supported. Use ISO 8601 format.

TDQS

D1/5.0
Behavior1/5

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.

Conciseness1/5

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.

Completeness1/5

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.

Parameters1/5

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.

Purpose1/5

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.

Usage Guidelines1/5

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.

  1. 3 tool updatesv1.0.0
    • First observedget_label_values
    • First observedget_labels
    • First observedquery_loki

TDQS

D1.8/5.0

Scored across 3 tools

Disambiguation5/5

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.

Naming Consistency5/5

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.

Tool Count3/5

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.

Completeness2/5

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

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    A server that enables AI assistants to access and query Grafana dashboards, metrics, logs, and configurations through an MCP protocol interface.
    10
    6
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables 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.
    -
  • A
    license
    Not graded
    quality
    B
    maintenance
    This 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 npm
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    An MCP server that enables AI assistants to query and analyze logs from Grafana Loki using LogQL, supporting label discovery and keyword search.
    4
    -