Install
$ agentstack add mcp-jpetrucciani-loki-mcp ✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ● Network access Used
- ✓ Filesystem access No
- ✓ Shell / process execution No
- ✓ Environment & secrets No
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
Verified badge
Passed review? Show it. Paste this badge into your README, it links to the public security report.
Reliability & compatibility
Declared compatibility
Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.
We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.
How agent discovery & health will work →About
loki-mcp
[](https://github.com/jpetrucciani/loki-mcp/actions/workflows/build.yml) [](https://github.com/jpetrucciani/loki-mcp/actions/workflows/release.yml) [](LICENSE) [](https://nixos.org/)
loki-mcp is a Model Context Protocol (MCP) server for querying Grafana Loki, built for AI agents and automation.
Features
- 16 read-only MCP tools for discovery, querying, analysis, and health checks
- Config layering with validation:
TOML -> env -> CLI - Loki auth modes:
none,basic,bearer - Optional static-header auth for MCP and debug endpoints
- Optional CORS allowlist for browser-based MCP clients
- Guardrails for bytes/streams limits with fail-closed behavior
- Per-tool and per-identity rate limiting
- Response modes for large result sets:
raw,truncated,summary,smart - Built-in observability:
/healthz,/readyz,/metrics, request ids, recent action tracking - CI coverage for test/build/format/clippy, plus tagged release automation
MCP Tool Surface
Discovery:
loki_describe_schemaloki_list_labelsloki_label_valuesloki_search_label_valuesloki_series
Query and execution:
loki_query_logsloki_query_metricsloki_build_queryloki_tailloki_run_saved_queryloki_query_stats
Analysis and authoring:
loki_detect_patternsloki_compare_rangesloki_explain_queryloki_suggest_metric_rule
Utility:
loki_check_health
Installation
Option 1: Release binaries
Download the archive for your platform from GitHub Releases, extract it, and place loki-mcp on your PATH.
Option 2: Build from source
cargo build --release
./target/release/loki-mcp --help
Option 3: Container image
Tagged releases publish multi-arch images to GHCR:
docker run --rm -p 8080:8080 \
-v "$PWD/config.toml:/config.toml:ro" \
ghcr.io/jpetrucciani/loki-mcp:vX.Y.Z \
--config /config.toml
Quickstart
This section assumes loki-mcp is on your PATH. If not, use ./target/release/loki-mcp.
- Copy the example config:
cp config.example.toml config.toml
- Edit
config.tomland setloki.urland auth fields for your environment. - Start the server:
loki-mcp --config config.toml
- Verify local endpoints:
curl -fsS http://127.0.0.1:8080/healthz
curl -fsS http://127.0.0.1:8080/readyz
curl -fsS http://127.0.0.1:8080/metrics | head
MCP transport endpoint: http://127.0.0.1:8080/mcp
Configuration
config.example.toml is the reference template.
Precedence (lowest to highest):
- TOML file
- Environment variables
- CLI flags
Examples:
# explicit config path
loki-mcp --config /etc/loki-mcp/config.toml
# config path via env
LOKI_MCP_CONFIG=/etc/loki-mcp/config.toml loki-mcp
# CLI override
loki-mcp --config config.toml --listen 0.0.0.0:8080 --loki-url https://loki:3100
# enable static-header auth for /mcp and /debug/*
loki-mcp --config config.toml --auth-token "$LOKI_MCP_TOKEN"
# allow a browser-based MCP client origin
loki-mcp --config config.toml --cors-allowed-origin http://localhost:6274
# flattened env aliases
LOKI_MCP_LOKI_URL=https://loki:3100 LOKI_MCP_LISTEN=0.0.0.0:8080 loki-mcp
LOKI_MCP_AUTH_TOKEN="$LOKI_MCP_TOKEN" loki-mcp
LOKI_MCP_CORS_ALLOWED_ORIGINS=http://localhost:6274,https://app.example.com loki-mcp
# nested env form (double underscore)
LOKI_MCP_LOKI__URL=https://loki:3100 LOKI_MCP_SERVER__LISTEN=0.0.0.0:8080 loki-mcp
Common env keys:
LOKI_MCP_LISTENLOKI_MCP_TIMEZONELOKI_MCP_LOG_LEVELLOKI_MCP_IDENTITY_HEADERLOKI_MCP_AUTH_HEADERLOKI_MCP_AUTH_TOKENLOKI_MCP_CORS_ALLOWED_ORIGINSLOKI_MCP_LOKI_URLLOKI_MCP_LOKI_TENANT_IDLOKI_MCP_LOKI_AUTH_TYPELOKI_MCP_LOKI_USERNAMELOKI_MCP_LOKI_PASSWORDLOKI_MCP_LOKI_TOKENLOKI_MCP_LOKI_CA_CERTLOKI_MCP_RATE_LIMIT_RPSLOKI_MCP_GUARDRAILS_MAX_BYTES_SCANNEDLOKI_MCP_RECENT_ACTIONS_ENABLED
Security and Trust Model
Loki auth:
loki.auth_type=noneloki.auth_type=basicrequiresusernameandpasswordloki.auth_type=bearerrequirestoken
Use environment variables for secrets instead of committing credentials to TOML.
MCP auth:
- Static-header auth is disabled unless
server.auth_tokenis set. - When enabled,
GETandPOST /mcpand/debug/*requests must include the configured header with the exact token value. - The default header is
x-loki-mcp-token; override it withserver.auth_header,--auth-header, orLOKI_MCP_AUTH_HEADER. GET /healthz,GET /readyz, andGET /metricsremain unauthenticated for probes and scraping.- For OIDC/JWT/mTLS or per-user authorization, deploy
loki-mcpbehind a trusted reverse proxy/ingress. - When using a proxy, strip spoofable inbound identity headers, forward a trusted identity header, and set
server.identity_headerto match.
Example:
LOKI_MCP_AUTH_TOKEN="$LOKI_MCP_TOKEN" loki-mcp
curl -H "x-loki-mcp-token: $LOKI_MCP_TOKEN" http://127.0.0.1:8080/mcp
CORS:
- CORS is disabled unless
server.cors_allowed_originsis non-empty. - Allowed origins must be origins only, for example
http://localhost:6274, not paths likehttp://localhost:6274/mcp. - Use
server.cors_allowed_origins = ["*"],--cors-allowed-origin '*', orLOKI_MCP_CORS_ALLOWED_ORIGINS='*'to allow any browser origin. - Wildcard CORS is useful for local inspection, but exact origins are better for shared deployments.
- CORS preflight requests are handled before static-header auth, because browsers do not send custom auth headers on preflight.
MCP Inspector often runs a browser UI from a localhost origin that differs from loki-mcp. If the Inspector reports CORS failures, start loki-mcp with the Inspector origin, or use wildcard CORS for local debugging:
LOKI_MCP_CORS_ALLOWED_ORIGINS='*' loki-mcp
Rate limiting identity keys are resolved in this order:
- configured
identity_header - first hop in
x-forwarded-for - remote IP
Runtime Behavior
Time handling:
- If
startandendare omitted on query tools, default range is last30mending atnow startandendaccept RFC3339, modern Unix epoch seconds, durations like15m,now,today,yesterday, andsince 2pm- Tools with
start/endalso acceptrange, for example{"range": "10m"}for the last 10 minutes.rangemay be combined withend, but not withstart
Label discovery:
loki_label_valuessupportsprefixandpatternsubstring filters in addition to Loki'squeryselector scopingloki_search_label_valuessearches across all labels, or a providedlabelslist, and returns only values matchingprefixorpatternloki_tailaccepts eitherlabelsor a LogQLquery, for example{cluster="cy1-service-01",service_name=~"bot.*"}
Response modes (loki_query_logs, loki_build_query, loki_tail, loki_run_saved_query):
raw,truncated,summary,smart(default)smartthresholds areraw,51-500=>truncated,> 500=>summary`
Guardrails:
- Pre-checks query cost via
/loki/api/v1/index/stats - Falls back to runtime stats if needed
- Fails closed when estimates are unavailable
- Tuned via
[guardrails](max_bytes_scanned,max_streams, and related skips)
Cache and recent actions:
- In-memory cache controlled by
[cache] /readyzresult is cached briefly to reduce probe load- Optional bounded recent action history via
[recent_actions](/debug/recent-actions)
HTTP Endpoints
GET /healthz, livenessGET /readyz, readiness (200healthy,503unhealthy)GET /metrics, Prometheus metricsGETandPOST /mcp, MCP Streamable HTTP, static-header protected whenserver.auth_tokenis setGET /debug/recent-actions?limit=100, recent tool activity (404when disabled), static-header protected whenserver.auth_tokenis set
Every HTTP response includes x-request-id.
Metrics use [metrics].prefix (default: loki_mcp):
_http_requests_total_tool_calls_total{tool,outcome}_tool_cache_total{tool,result}_tool_guardrail_rejections_total{tool}_tool_rate_limited_total{tool}_readiness_cache_total{result}
CLI Testing
CLI tools are not subject to browser CORS checks. Use curl to separate MCP/auth failures from browser-origin failures.
Check CORS preflight behavior:
curl -i -X OPTIONS http://127.0.0.1:8080/mcp \
-H 'Origin: http://localhost:6274' \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: content-type,x-loki-mcp-token,mcp-session-id'
Expected with a matching CORS allowlist: 204 No Content and an access-control-allow-origin header.
Send an MCP initialize request:
curl -i http://127.0.0.1:8080/mcp \
-H 'content-type: application/json' \
-H 'accept: application/json, text/event-stream' \
-H "x-loki-mcp-token: $LOKI_MCP_TOKEN" \
--data '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-03-26",
"capabilities": {},
"clientInfo": {"name": "curl", "version": "0.0.0"}
}
}'
If static-header auth is disabled, omit the x-loki-mcp-token header.
Development
Nix-first local shell:
nix-shell
CI parity checks:
cargo fmt -- --check
cargo clippy --all --benches --tests --examples --all-features -- -D warnings -W clippy::collapsible_else_if
cargo test --verbose
Integration tests require a local loki binary on PATH.
Real-Loki integration tests are opt-in:
LOKI_MCP_RUN_REAL_LOKI_TESTS=1 cargo test --test loki_client_it --test tool_router_it --verbose
Troubleshooting
guardrail pre-check failed ..., Loki could not provide cost estimates, narrow selector/range or adjust guardrailsquery rejected by guardrail ..., query exceeded configured bytes/streams limitsrate limit exceeded ..., increase[rate_limit]limits or configure a strongeridentity_headerloki process did not become readyin tests, verifyloki --versionand loopback port availabilityloki_check_healthreports/ready404, often expected behind gateways/proxies when other Loki APIs are reachable- TLS failures against Loki, set
loki.ca_certfor private CAs /debug/recent-actionsreturns 404, set[recent_actions].enabled=true/mcpor/debug/*returns 401, send the configured auth header or unsetserver.auth_token- MCP Inspector reports CORS errors, add its browser origin to
server.cors_allowed_originsor use["*"]for local debugging
Source & license
This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.
- Author: jpetrucciani
- Source: jpetrucciani/loki-mcp
- License: MIT
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet, be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.