loki — плагин для Claude Code: что делает и как установить
Подключает Grafana Loki к Claude Code через MCP. Позволяет искать логи через LogQL и просматривать значения меток прямо в диалоге.
/plugin marketplace add anthropics/claude-plugins-community
/plugin install loki@claude-communityЧто делает loki
Плагин даёт Claude Code доступ к логам Grafana Loki через протокол MCP. Ассистент выполняет запросы LogQL и получает потоки логов за выбранные интервалы времени. Поддерживаются относительные интервалы вроде 1h или 30m, формат RFC3339 и ключевое слово now.
Внутри заложены готовые инструменты: loki_query для выборки записей, loki_labels для просмотра меток и loki_series для сопоставления селекторов. Есть отдельная проверка готовности через loki_ready. Для типовых задач предусмотрены шаблоны промптов, которые вычисляют частоту входящих строк или собирают ошибки по названию сервиса.
Без указания адреса плагин обращается к http://localhost:3100. Если сервер защищён авторизацией, понадобятся переменные окружения LOKI_USERNAME с LOKI_PASSWORD либо LOKI_TOKEN, а для мультитенантных систем — заголовок LOKI_ORG_ID.
Какие задачи решает
- найти ошибки сервиса через LogQL за последний час
- просмотреть список доступных меток и их значений в Loki
- посчитать частоту логов по селектору потока
- получить статистику индексов и объём записей
Примеры запросов агенту
- Найди ошибки в логах приложения nginx за последние 2 часа через loki
- Покажи все значения метки app в Loki
- Посчитай частоту логов для селектора {app="backend"} с интервалом 5m
Как установить loki
Через маркетплейс плагинов
/plugin marketplace add anthropics/claude-plugins-community/plugin install loki@claude-communityПо шагам, с командами для каждой платформы: Плагины Claude Code: маркетплейсы, установка и как собрать свой
Вопросы о loki
Как установить loki в Claude Code?
Выполните по очереди две команды: /plugin marketplace add anthropics/claude-plugins-community, затем /plugin install loki@claude-community.
Что делает плагин loki?
Он связывает Claude Code с сервером Grafana Loki по протоколу MCP. Модель может выполнять LogQL-запросы, искать потоки логов и читать конфигурацию инстанса.
Какие способы авторизации поддерживает loki?
Поддерживаются базовая аутентификация через логин и пароль, Bearer-токен и передача заголовка X-Scope-OrgID через переменную LOKI_ORG_ID для мультитенантных инсталляций.
Исходный текст
SKILL.md · BSD-3-Clause
# MCP Loki
[](https://go.dev/)
[](LICENSE)
[](https://github.com/lexfrei/mcp-loki/releases)
[](https://github.com/lexfrei/mcp-loki/actions/workflows/release.yaml)
MCP server for querying Grafana Loki logs. Enables LLMs to search and analyze logs via the Model Context Protocol.
## Features
- **LogQL Queries** — Execute range queries with flexible time ranges
- **Label Discovery** — List labels and their values for query building
- **Series Exploration** — Find log streams matching label selectors
- **Index Statistics** — Get cardinality and size metrics
- **Prompt Templates** — Ready-made LogQL patterns for common log analysis tasks
- **Multiple Auth Methods** — Basic auth, Bearer token, multi-tenant (X-Scope-OrgID)
- **Multi-arch Images** — `linux/amd64` and `linux/arm64`
- **Signed Images** — Verified with cosign keyless signing
## Quick Start
### Container (Podman/Docker)
Add to your MCP client configuration:
```json
{
"mcpServers": {
"loki": {
"command": "podman",
"args": [
"run", "--rm", "-i",
"-e", "LOKI_URL=http://loki:3100",
"ghcr.io/lexfrei/mcp-loki:latest"
]
}
}
}
```
### Go Install
```bash
go install github.com/lexfrei/mcp-loki/cmd/mcp-loki@latest
```
MCP client configuration:
```json
{
"mcpServers": {
"loki": {
"command": "mcp-loki",
"env": {
"LOKI_URL": "http://loki:3100"
}
}
}
}
```
## Configuration
All configuration is done via environment variables:
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `LOKI_URL` | No | `http://localhost:3100` | Loki server URL |
| `LOKI_USERNAME` | No | — | Basic auth username |
| `LOKI_PASSWORD` | No | — | Basic auth password |
| `LOKI_TOKEN` | No | — | Bearer token (alternative to basic auth) |
| `LOKI_ORG_ID` | No | — | X-Scope-OrgID header for multi-tenant Loki |
| `MCP_HTTP_PORT` | No | — | Enable HTTP SSE transport on this port |
### Authentication Examples
**No authentication (local Loki):**
```json
{
"command": "podman",
"args": [
"run", "--rm", "-i",
"-e", "LOKI_URL=http://loki:3100",
"ghcr.io/lexfrei/mcp-loki:latest"
]
}
```
**Basic authentication:**
```json
{
"command": "podman",
"args": [
"run", "--rm", "-i",
"-e", "LOKI_URL=https://loki.example.com",
"-e", "LOKI_USERNAME=admin",
"-e", "LOKI_PASSWORD=secret",
"ghcr.io/lexfrei/mcp-loki:latest"
]
}
```
**Bearer token (Grafana Cloud):**
```json
{
"command": "podman",
"args": [
"run", "--rm", "-i",
"-e", "LOKI_URL=https://logs-prod-us-central1.grafana.net",
"-e", "LOKI_TOKEN=glc_xxx",
"-e", "LOKI_ORG_ID=123456",
"ghcr.io/lexfrei/mcp-loki:latest"
]
}
```
## Available Tools
### loki_query
Execute LogQL queries against Loki.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | string | Yes | LogQL query string |
| `start` | string | No | Start time (RFC3339, relative like `1h`, or `now`) |
| `end` | string | No | End time (RFC3339, relative, or `now`) |
| `limit` | int | No | Maximum entries to return (default: 100) |
| `direction` | string | No | `forward` or `backward` (default: `backward`) |
**Example:**
```text
Query the last hour of nginx error logs:
- query: {app="nginx"} |= "error"
- start: 1h
- limit: 50
```
### loki_labels
Get label names or values for a specific label.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `name` | string | No | Label name to get values for (omit for all labels) |
| `start` | string | No | Start time |
| `end` | string | No | End time |
**Example:**
```text
Get all label names: (no parameters)
Get values for "app" label: name=app
```
### loki_series
Find log streams matching label selectors.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `match` | []string | Yes | Label selector(s), e.g., `{app="nginx"}` |
| `start` | string | No | Start time |
| `end` | string | No | End time |
**Example:**
```text
Find all nginx streams: match=["{app=\"nginx\"}"]
```
### loki_stats
Get index statistics for a query.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | string | Yes | LogQL selector |
| `start` | string | No | Start time |
| `end` | string | No | End time |
**Example:**
```text
Get stats for nginx logs: query={app="nginx"}
```
### loki_ready
Check if Loki is ready to accept requests. No parameters required.
### loki_config
Get Loki server configuration in YAML format. No parameters required.
## Available Prompts
### error_logs
Find error logs for a specific application.
| Argument | Required | Default | Description |
|----------|----------|---------|-------------|
| `app` | Yes | — | Application name to search errors for |
| `timerange` | No | `1h` | Time range (e.g. `1h`, `30m`, `7d`) |
### rate_query
Calculate the rate of log lines matching a selector.
| Argument | Required | Default | Description |
|----------|----------|---------|-------------|
| `selector` | Yes | — | LogQL stream selector (e.g. `{app="nginx"}`) |
| `interval` | No | `5m` | Rate interval (e.g. `5m`, `1h`) |
### top_label_values
Find top N values for a label by log volume.
| Argument | Required | Default | Description |
|----------|----------|---------|-------------|
| `selector` | Yes | — | LogQL stream selector (e.g. `{app="nginx"}`) |
| `label` | Yes | — | Label name to group by |
| `n` | No | `10` | Number of top values to return |
| `interval` | No | `5m` | Rate interval (e.g. `5m`, `1h`) |
## Time Formats
All time parameters accept:
- **RFC3339**: `2024-01-15T10:30:00Z`
- **Relative**: `30s`, `5m`, `1h`, `7d` (seconds, minutes, hours, days ago)
- **Keyword**: `now`
## Verification
Container images are signed with cosign keyless signing:
```bash
cosign verify ghcr.io/lexfrei/mcp-loki:latest \
--certificate-identity-regexp=https://github.com/lexfrei/mcp-loki \
--certificate-oidc-issuer=https://token.actions.githubusercontent.com
```
## License
[BSD-3-Clause](LICENSE)
© lexfrei · BSD-3-Clause · lexfrei/mcp-loki