Skip to main content
Glama
ghrud92

Loki MCP Server

by ghrud92

Простой сервер Loki MCP

значок кузнеца

Loki MCP Server — это интерфейс Model Context Protocol (MCP) для запроса журналов Grafana Loki с помощью logcli . Сервер позволяет помощникам ИИ получать доступ к данным журналов Loki и анализировать их напрямую.

Функции

  • Запрос журналов Loki с полной поддержкой LogQL

  • Получить значения меток и метаданные

  • Поддержка аутентификации и настройки через переменные среды или файлы конфигурации

  • Предоставляет отформатированные результаты в различных форматах вывода (по умолчанию, необработанные, строки JSON)

  • Автоматический возврат к HTTP API, если logcli недоступен в среде

Related MCP server: Loki MCP Server

Предпосылки

  • Node.js v16 или выше

  • Машинопись

  • (Необязательно) Grafana Loki logcli установлен и доступен в вашем PATH. Если logcli недоступен, сервер автоматически будет использовать Loki HTTP API вместо этого

  • Доступ к экземпляру сервера Loki

Установка

Установка через Smithery

Чтобы автоматически установить Simple Loki MCP Server для Claude Desktop через Smithery :

npx -y @smithery/cli install @ghrud92/simple-loki-mcp --client claude

для МКП

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

нпм

  1. Клонируйте репозиторий:

git clone https://github.com/ghrud92/loki-mcp.git
cd loki-mcp
  1. Установить зависимости:

npm install
  1. Создайте проект:

npm run build

Доступные инструменты MCP

запрос-локи

Запрос журналов из Loki с возможностью фильтрации.

Параметры:

  • query (обязательно): строка запроса Loki (LogQL)

  • from : начальная временная метка (например, "2023-01-01T12:00:00Z")

  • to : конечная временная метка (например, «2023-01-01T13:00:00Z»)

  • limit : Максимальное количество возвращаемых журналов

  • batch : Размер пакета для результатов запроса

  • output : Формат вывода («по умолчанию», «сырой» или «jsonl»)

  • quiet : Подавить метаданные запроса

  • forward : Отображать результаты в хронологическом порядке

получить-метки-значения

Получить все значения для определенной метки.

Параметры:

  • label (обязательно): Имя метки для получения значений

получить-метки

Получить все доступные метки.

Параметры не требуются.

Конфигурация

Вы можете настроить доступ к Loki, используя:

Переменные среды

  • LOKI_ADDR : адрес сервера Loki (URL)

  • LOKI_USERNAME : Имя пользователя для базовой аутентификации

  • LOKI_PASSWORD : Пароль для базовой аутентификации

  • LOKI_TENANT_ID : идентификатор арендатора для многоарендного Loki

  • LOKI_BEARER_TOKEN : Токен на предъявителя для аутентификации

  • LOKI_BEARER_TOKEN_FILE : Файл, содержащий токен на предъявителя

  • LOKI_CA_FILE : Пользовательский файл CA для TLS

  • LOKI_CERT_FILE : Файл клиентского сертификата для TLS

  • LOKI_KEY_FILE : Файл ключа клиента для TLS

  • LOKI_ORG_ID : идентификатор организации для многоорганизационных настроек

  • LOKI_TLS_SKIP_VERIFY : Пропустить проверку TLS («истина» или «ложь»)

  • LOKI_CONFIG_PATH : Пользовательский путь к файлу конфигурации

  • DEBUG : включить ведение журнала отладки

Примечание : когда клиент использует режим HTTP API (когда logcli недоступен), для аутентификации и подключения к серверу Loki используются те же параметры конфигурации.

Файлы конфигурации

Либо создайте файл logcli-config.yaml в одном из следующих мест:

  • Пользовательский путь, указанный LOKI_CONFIG_PATH

  • Текущий рабочий каталог

  • Ваш домашний каталог ( ~/.logcli-config.yaml )

Пример файла конфигурации:

addr: https://loki.example.com
username: user
password: pass
tenant_id: mytenant

Использование

Запустите сервер:

npm start

Для разработки:

npm run dev

Подробности реализации

Автоматический возврат к HTTP API

Сервер автоматически проверит, установлен ли logcli и доступен ли он в среде:

  1. Если logcli доступен, он будет использоваться для всех запросов, обеспечивая полную функциональность инструмента CLI.

  2. Если logcli недоступен, сервер автоматически вернется к использованию Loki HTTP API:

    • Никакой дополнительной настройки не требуется.

    • Для HTTP API используются те же параметры аутентификации.

    • Форматирование ответа соответствует выходным данным CLI.

    • В обоих режимах применяется ограничение по умолчанию в 1000 журналов на запрос.

Автоматическое обнаружение гарантирует бесперебойную работу сервера в различных средах без необходимости ручной настройки.

Разработка

# Run linter
npm run lint

# Fix linting issues
npm run lint:fix

# Run tests
npm run test

Лицензия

Данный проект лицензирован по лицензии MIT — подробности смотрите в файле LICENSE.md .

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
    -