Loki MCP Server
Простой сервер 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"
}
}
}
}нпм
Клонируйте репозиторий:
git clone https://github.com/ghrud92/loki-mcp.git
cd loki-mcpУстановить зависимости:
npm installСоздайте проект:
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: идентификатор арендатора для многоарендного LokiLOKI_BEARER_TOKEN: Токен на предъявителя для аутентификацииLOKI_BEARER_TOKEN_FILE: Файл, содержащий токен на предъявителяLOKI_CA_FILE: Пользовательский файл CA для TLSLOKI_CERT_FILE: Файл клиентского сертификата для TLSLOKI_KEY_FILE: Файл ключа клиента для TLSLOKI_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 и доступен ли он в среде:
Если
logcliдоступен, он будет использоваться для всех запросов, обеспечивая полную функциональность инструмента CLI.Если
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 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-