@kealthas-dev/opencode-mcp-loki 1.0.8 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,25 +1,34 @@
1
1
  # loki mcp server
2
2
 
3
- A minimal MCP server exposing three read-only tools — `loki_query_range`, `loki_labels`, `loki_label_values` — against a configured Grafana Loki instance's HTTP query API. Built directly against `@modelcontextprotocol/sdk`, same hand-rolled-against-the-raw-API pattern as `mcp-servers/oracle/`. Speaks MCP over Streamable HTTP, as a persistent process opencode connects to (`type: "remote"`) rather than spawns and owns (`type: "local"`) — same deployment shape as `mcp-servers/oracle/`.
3
+ A minimal MCP server exposing three read-only tools — `loki_query_range`, `loki_labels`, `loki_label_values` — against a configured Grafana Loki instance's HTTP query API. Written in TypeScript (`src/server.ts` + `src/types/config.ts`, compiled to `dist/` — see Run below), built directly against `@modelcontextprotocol/sdk`, same hand-rolled-against-the-raw-API pattern as `mcp-servers/oracle/`. Speaks MCP over Streamable HTTP, as a persistent process opencode connects to (`type: "remote"`) rather than spawns and owns (`type: "local"`) — same deployment shape as `mcp-servers/oracle/`.
4
4
 
5
5
  ## Design, and why it looks the way it does
6
6
 
7
7
  - **Remote, not local**, for the same reason as `mcp-servers/oracle/`: a persistent HTTP server, started independently (`npm start` under a process supervisor — see `deploy/opencode.json.example`/SETUP.md) and reachable at a fixed URL, so its uptime isn't tied to opencode's own restarts.
8
- - **Stateless HTTP, one `Server`/transport pair per request** (`sessionIdGenerator: undefined`, matching the SDK's own reference example and `mcp-servers/oracle/server.js`'s shell). No session state worth keeping between calls.
8
+ - **Stateless HTTP, one `Server`/transport pair per request** (`sessionIdGenerator: undefined`, matching the SDK's own reference example and `mcp-servers/oracle/src/server.ts`'s shell). No session state worth keeping between calls.
9
9
  - **Three tools, not one.** `loki_query_range` is the actual log query (arbitrary LogQL, full passthrough — no filtering, mirroring `oracle_query`'s "safety lives elsewhere" stance, except there's no write side here to guard against in the first place). `loki_labels`/`loki_label_values` exist because LogQL selectors need real label names/values to be useful — without a way to discover them, an agent (or a human) querying unfamiliar logs would have to guess. All three are read-only GETs; adding the two discovery tools costs nothing beyond `oracle_query`'s single-tool baseline.
10
- - **`start`/`end` accept relative and naive-local forms, not just Loki's own RFC3339/epoch.** Handing a caller (model or human) the burden of computing an exact RFC3339 offset or a 19-digit nanosecond epoch by hand is real friction, so `resolveTimeParam()` in `server.js` accepts `"now"`/`"now-1h"`/`"now-30m"`/`"now-1d"` (Grafana's own relative-time syntax for Loki/Prometheus, not invented here) and a bare `"YYYY-MM-DDTHH:MM:SS"`/`"YYYY-MM-DD HH:MM:SS"` with no timezone (assumed to be `LOKI_DEFAULT_TZ_OFFSET`, default `+08:00`), converting either into what Loki actually expects before the request goes out. An already-qualified RFC3339 offset or bare epoch still passes straight through unchanged - purely additive, not a breaking change to the original format.
11
- - **No connection lifecycle, no audit hook.** `mcp-servers/oracle/server.js`'s per-request-connection design and `auditQuery()` extension point both exist because SQL can write. Loki's query API has no write side at all, so there's nothing analogous to design around — each tool call is just a plain `fetch`, wrapped so a non-2xx response or network failure comes back as a clean `{success: false, error}` instead of a thrown error (same shape `executeQuery()` returns in `mcp-servers/oracle/server.js`, same reason: tool results should never surface as a raw MCP protocol error).
10
+ - **`start`/`end` accept relative and naive-local forms, not just Loki's own RFC3339/epoch.** Handing a caller (model or human) the burden of computing an exact RFC3339 offset or a 19-digit nanosecond epoch by hand is real friction, so `resolveTimeParam()` in `src/server.ts` accepts `"now"`/`"now-1h"`/`"now-30m"`/`"now-1d"` (Grafana's own relative-time syntax for Loki/Prometheus, not invented here) and a bare `"YYYY-MM-DDTHH:MM:SS"`/`"YYYY-MM-DD HH:MM:SS"` with no timezone (assumed to be `LOKI_DEFAULT_TZ_OFFSET`, default `+08:00`), converting either into what Loki actually expects before the request goes out. An already-qualified RFC3339 offset or bare epoch still passes straight through unchanged - purely additive, not a breaking change to the original format.
11
+ - **No connection lifecycle, no audit hook.** `mcp-servers/oracle/src/server.ts`'s per-request-connection design and `auditQuery()` extension point both exist because SQL can write. Loki's query API has no write side at all, so there's nothing analogous to design around — each tool call is just a plain `fetch`, wrapped so a non-2xx response or network failure comes back as a clean `{success: false, error}` instead of a thrown error (same shape `executeQuery()` returns in `mcp-servers/oracle/src/server.ts`, same reason: tool results should never surface as a raw MCP protocol error).
12
12
 
13
13
  ## Configuration
14
14
 
15
- Copy `.env.example` to `.env` and fill in real values, or set them however the process supervisor that starts this server (see Run below) is configured. A `remote` MCP entry in `opencode.json` carries no `environment` field (just a `url`) — opencode never starts this process, so wherever it actually gets started is what needs these set:
16
-
17
- - `LOKI_BASE_URL` — base URL of the Loki instance, no trailing path (e.g. `http://192.168.1.100:3100`)
18
- - `LOKI_USERNAME` / `LOKI_PASSWORD` — optional, HTTP basic auth, only if this Loki instance requires it
19
- - `LOKI_ORG_ID` — optional, sets `X-Scope-OrgID` for multi-tenant Loki / Grafana Cloud-style setups
20
- - `LOKI_MCP_PORT` — port to listen on (optional, defaults to `8091` — the next free port after `mcp-servers/oracle/`'s `8090`)
21
-
22
- Unlike `mcp-servers/oracle/`, only `LOKI_BASE_URL` is required — Loki is commonly reachable unauthenticated on an internal LAN.
15
+ Config is file-based, not env-var-based — same two-file split as `mcp-servers/oracle/` (see its README's Configuration section for the fullest writeup of the pattern), except unlike `mcp-servers/oracle/`, the Loki config file has a default location too:
16
+
17
+ - **`$HOME/.config/kealthas-dev/opencode-mcp-loki/server.json`** — the port to listen on, at this one fixed path always. Optional: if missing, defaults to `8091`; if present, must be valid JSON or the server refuses to start. Shape (see `server.example.json`):
18
+ ```json
19
+ { "LOKI_MCP_PORT": 8091 }
20
+ ```
21
+ - **A Loki config file, normally at `$HOME/.config/kealthas-dev/opencode-mcp-loki/config.json`** — that fixed path is the default (covers the common single-Loki-instance setup with nothing to set), but `LOKI_CONFIG_FILE` overrides it with any other path when set, for multiple environments — e.g. `configs/dev.json`, `configs/prod.json`, `configs/uat.json` alongside it, switched between with `LOKI_CONFIG_FILE=.../configs/prod.json`. The server prints a sample and exits if neither the default file nor an env-var-pointed file exists, or if `LOKI_BASE_URL` is missing from whichever one is read. Shape (see `config.example.json`):
22
+ ```json
23
+ {
24
+ "LOKI_BASE_URL": "http://192.168.1.100:3100",
25
+ "LOKI_USERNAME": "username",
26
+ "LOKI_PASSWORD": "password",
27
+ "LOKI_ORG_ID": "tenant-id",
28
+ "LOKI_DEFAULT_TZ_OFFSET": "+08:00"
29
+ }
30
+ ```
31
+ Only `LOKI_BASE_URL` (no trailing path, e.g. `http://192.168.1.100:3100`) is required — Loki is commonly reachable unauthenticated on an internal LAN, unlike `mcp-servers/oracle/`. `LOKI_USERNAME`/`LOKI_PASSWORD` are HTTP basic auth; `LOKI_ORG_ID` sets `X-Scope-OrgID` for multi-tenant Loki / Grafana Cloud-style setups; `LOKI_DEFAULT_TZ_OFFSET` defaults to `+08:00` if omitted.
23
32
 
24
33
  ## Run
25
34
 
@@ -27,30 +36,34 @@ Published as `@kealthas-dev/opencode-mcp-loki` — on a real deployment, install
27
36
 
28
37
  ```bash
29
38
  npm install -g @kealthas-dev/opencode-mcp-loki
30
- LOKI_BASE_URL=... opencode-mcp-loki
39
+ LOKI_CONFIG_FILE=~/.config/kealthas-dev/opencode-mcp-loki/configs/prod.json opencode-mcp-loki
31
40
  ```
32
41
 
33
- For local dev/testing against this repo's own checkout (this directory, not the published package):
42
+ For local dev/testing against this repo's own checkout (this directory, not the published package), point `LOKI_CONFIG_FILE` at a real config file (see `config.example.json` for the shape — the sandbox's docker-entrypoint.sh generates one automatically, see Testing below):
34
43
 
35
44
  ```bash
36
45
  npm install
37
- npm start
46
+ npm run build
47
+ LOKI_CONFIG_FILE=/path/to/a/real/config.json npm start
38
48
  ```
39
49
 
40
- Either way, this starts a persistent HTTP server on `LOKI_MCP_PORT` (default `8091`), serving MCP over Streamable HTTP at `/mcp`. Point opencode at it with a `type: "remote"` entry (see `deploy/opencode.json.example`) — it needs to already be running and stay running, since opencode connects rather than spawns it (either command alone exits when its terminal closes; see `mcp-servers/oracle/README.md`'s Design section for real supervisor options — the same reasoning applies here).
50
+ `npm run dev` runs `src/server.ts` directly via `tsx watch` instead, for a compile-on-save loop.
51
+
52
+ Either way, this starts a persistent HTTP server on the configured port (default `8091`), serving MCP over Streamable HTTP at `/mcp`. Point opencode at it with a `type: "remote"` entry (see `deploy/opencode.json.example`) — it needs to already be running and stay running, since opencode connects rather than spawns it (either command alone exits when its terminal closes; see `mcp-servers/oracle/README.md`'s Design section for real supervisor options — the same reasoning applies here).
41
53
 
42
54
  ## Testing against a real Loki instance
43
55
 
44
- `docker/docker-compose.loki.yml`'s `loki` service comes up automatically via `docker/dev.sh`, no separate step needed:
56
+ `docker/docker-compose.loki.yml`'s `loki` service is a shared fixture started separately, not by `docker/dev.sh`:
45
57
 
46
58
  ```sh
59
+ docker compose -f docker/docker-compose.loki.yml up -d
47
60
  docker/dev.sh run --rm opencode-dev bash
48
61
  ```
49
62
 
50
- `LOKI_BASE_URL` is already set inside that shell — `cd mcp-servers/loki && npm install && npm start`, then hit `http://localhost:8091/mcp` from an MCP client or `curl`.
63
+ `LOKI_CONFIG_FILE` is already set inside that shell — `docker-entrypoint.sh` generates a config file from the sandbox's `LOKI_BASE_URL` compose env var and points `LOKI_CONFIG_FILE` at it. `cd mcp-servers/loki && npm install && npm run build && npm start`, then hit `http://localhost:8091/mcp` from an MCP client or `curl`.
51
64
 
52
- `loki.test.mjs` (see `tests/README.md`) doesn't need this manual dance — it starts and stops its own `server.js` process on its own port as part of the test run, and seeds its own test log lines by pushing directly to Loki's push API (not through this MCP server, which is read-only by design).
65
+ `loki.test.ts` (see `tests/README.md`) doesn't need this manual dance — it builds its own config files into a fake `$HOME` per spawned server (same pattern as `mcp-servers/oracle/oracle.test.ts`) and starts/stops its own `dist/server.js` process on its own port as part of the test run, seeding its own test log lines by pushing directly to Loki's push API (not through this MCP server, which is read-only by design).
53
66
 
54
67
  ## Status
55
68
 
56
- **Verified end-to-end and automated.** `loki.test.mjs` covers tool listing, `loki_labels`/`loki_label_values` finding pushed test data, `loki_query_range` finding a pushed log line by content, an empty-result query returning cleanly (not an error), and a malformed LogQL query returning a clean error — driven over the real Streamable HTTP transport against the sandbox's `loki` service. Wired into `deploy/opencode.json.example` (`mcp.loki`, `type: "remote"`, `enabled: true`).
69
+ **Verified end-to-end and automated.** `loki.test.ts` covers tool listing, `loki_labels`/`loki_label_values` finding pushed test data, `loki_query_range` finding a pushed log line by content, an empty-result query returning cleanly (not an error), and a malformed LogQL query returning a clean error — driven over the real Streamable HTTP transport against the sandbox's `loki` service. Wired into `deploy/opencode.json.example` (`mcp.loki`, `type: "remote"`, `enabled: true`).
package/dist/server.js ADDED
@@ -0,0 +1,302 @@
1
+ #!/usr/bin/env node
2
+ import http from "node:http";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join, resolve } from "node:path";
6
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
7
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
8
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
9
+ const DEFAULT_PORT = 8091; // the next free port after mcp-servers/oracle's 8090
10
+ const CONFIG_DIR = join(homedir(), ".config", "kealthas-dev", "opencode-mcp-loki");
11
+ const SERVER_CONFIG_PATH = join(CONFIG_DIR, "server.json");
12
+ const SAMPLE_SERVER_CONFIG = { LOKI_MCP_PORT: DEFAULT_PORT };
13
+ const SAMPLE_LOKI_CONFIG = {
14
+ LOKI_BASE_URL: "http://192.168.1.100:3100 (no trailing path)",
15
+ LOKI_USERNAME: "username (optional, HTTP basic auth)",
16
+ LOKI_PASSWORD: "password (optional)",
17
+ LOKI_ORG_ID: "tenant-id (optional, multi-tenant Loki / Grafana Cloud-style setups)",
18
+ LOKI_DEFAULT_TZ_OFFSET: "+08:00 (optional, defaults to +08:00)",
19
+ };
20
+ function printSampleConfig(label, path, sample) {
21
+ console.error(`\nExpected ${label} at: ${path}\n`);
22
+ console.error(JSON.stringify(sample, null, 2));
23
+ console.error("");
24
+ }
25
+ // server.json is infrastructure config (which port to bind) that doesn't
26
+ // vary per environment, so it lives at one fixed path rather than being
27
+ // pointed at like the Loki config below. Missing entirely just means "use
28
+ // the default port" - only a present-but-broken file is treated as a real
29
+ // error, since its existence signals intent to override the default.
30
+ function loadServerConfig() {
31
+ if (!existsSync(SERVER_CONFIG_PATH)) {
32
+ return { LOKI_MCP_PORT: DEFAULT_PORT };
33
+ }
34
+ try {
35
+ const raw = JSON.parse(readFileSync(SERVER_CONFIG_PATH, "utf8"));
36
+ const port = Number(raw.LOKI_MCP_PORT ?? DEFAULT_PORT);
37
+ if (!Number.isInteger(port) || port <= 0) {
38
+ throw new Error(`LOKI_MCP_PORT must be a positive integer, got: ${JSON.stringify(raw.LOKI_MCP_PORT)}`);
39
+ }
40
+ return { LOKI_MCP_PORT: port };
41
+ }
42
+ catch (err) {
43
+ console.error(`Failed to load server config: ${err.message}`);
44
+ printSampleConfig("server config", SERVER_CONFIG_PATH, SAMPLE_SERVER_CONFIG);
45
+ process.exit(1);
46
+ }
47
+ }
48
+ // Loki connection details are per-environment and read from whatever path
49
+ // LOKI_CONFIG_FILE points at - unrestricted filename/location, so the same
50
+ // install can be pointed at a different Loki instance just by changing this
51
+ // one env var. LOKI_CONFIG_FILE itself is optional: if unset, this falls
52
+ // back to config.json next to server.json in CONFIG_DIR, covering the
53
+ // common single-environment case without requiring the env var on every
54
+ // start - multi-environment setups still override it per deployment. Only
55
+ // LOKI_BASE_URL is required - Loki is commonly reachable unauthenticated on
56
+ // an internal LAN, unlike mcp-servers/oracle.
57
+ const DEFAULT_LOKI_CONFIG_PATH = join(CONFIG_DIR, "config.json");
58
+ function loadLokiConfig() {
59
+ const envPath = process.env.LOKI_CONFIG_FILE;
60
+ const resolvedPath = resolve(envPath ?? DEFAULT_LOKI_CONFIG_PATH);
61
+ if (!existsSync(resolvedPath)) {
62
+ if (envPath) {
63
+ console.error(`Loki config file not found: ${resolvedPath}`);
64
+ }
65
+ else {
66
+ console.error(`No LOKI_CONFIG_FILE set and no default config file at: ${resolvedPath}`);
67
+ console.error("Either create that file, or point LOKI_CONFIG_FILE at one, e.g.:");
68
+ console.error(" LOKI_CONFIG_FILE=~/.config/kealthas-dev/opencode-mcp-loki/configs/prod.json opencode-mcp-loki");
69
+ }
70
+ printSampleConfig("Loki config file", resolvedPath, SAMPLE_LOKI_CONFIG);
71
+ process.exit(1);
72
+ }
73
+ try {
74
+ const raw = JSON.parse(readFileSync(resolvedPath, "utf8"));
75
+ if (!raw.LOKI_BASE_URL) {
76
+ throw new Error("missing required key LOKI_BASE_URL");
77
+ }
78
+ return {
79
+ LOKI_BASE_URL: raw.LOKI_BASE_URL,
80
+ LOKI_USERNAME: raw.LOKI_USERNAME,
81
+ LOKI_PASSWORD: raw.LOKI_PASSWORD,
82
+ LOKI_ORG_ID: raw.LOKI_ORG_ID,
83
+ LOKI_DEFAULT_TZ_OFFSET: raw.LOKI_DEFAULT_TZ_OFFSET,
84
+ };
85
+ }
86
+ catch (err) {
87
+ console.error(`Failed to load Loki config from ${resolvedPath}: ${err.message}`);
88
+ printSampleConfig("Loki config file", resolvedPath, SAMPLE_LOKI_CONFIG);
89
+ process.exit(1);
90
+ }
91
+ }
92
+ const serverConfig = loadServerConfig();
93
+ const lokiConfig = loadLokiConfig();
94
+ const LOKI_DEFAULT_TZ_OFFSET = lokiConfig.LOKI_DEFAULT_TZ_OFFSET ?? "+08:00";
95
+ // Computing a correct start/end by hand (an exact RFC3339 offset, or -
96
+ // worse - a 19-digit nanosecond epoch) is real friction for whatever's
97
+ // calling this tool, model or human. This resolves three friendlier
98
+ // forms into whatever Loki actually accepts, so most callers never have
99
+ // to touch epoch math at all:
100
+ // - "now" / "now-<duration>" (duration is <n><unit> pairs, unit one of
101
+ // s/m/h/d, e.g. "now-1h", "now-30m", "now-1d") - the same relative-time
102
+ // convention Grafana itself uses for Loki/Prometheus time ranges, not
103
+ // an invented one.
104
+ // - a bare "YYYY-MM-DDTHH:MM:SS" or "YYYY-MM-DD HH:MM:SS" with no
105
+ // timezone - assumed to be in LOKI_DEFAULT_TZ_OFFSET and qualified
106
+ // before being sent.
107
+ // Anything else (already a full RFC3339 offset, or a bare epoch number)
108
+ // passes straight through unchanged - both were already correct inputs
109
+ // before this existed, and stay correct. An unrecognized shape also
110
+ // passes straight through rather than being rejected here - Loki's own
111
+ // parser is the final judge and returns its own clean error, same
112
+ // full-passthrough philosophy as everywhere else in this server.
113
+ const RELATIVE_TIME_RE = /^now(?:-((?:\d+[smhd])+))?$/;
114
+ const DURATION_PART_RE = /(\d+)([smhd])/g;
115
+ const NAIVE_DATETIME_RE = /^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2}(?:\.\d+)?)$/;
116
+ const UNIT_MS = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
117
+ function resolveTimeParam(value) {
118
+ if (value === undefined || value === null)
119
+ return value;
120
+ const relative = RELATIVE_TIME_RE.exec(value);
121
+ if (relative) {
122
+ let offsetMs = 0;
123
+ for (const [, amount, unit] of relative[1]?.matchAll(DURATION_PART_RE) ?? []) {
124
+ offsetMs += Number(amount) * UNIT_MS[unit];
125
+ }
126
+ return String((Date.now() - offsetMs) * 1_000_000);
127
+ }
128
+ const naive = NAIVE_DATETIME_RE.exec(value);
129
+ if (naive)
130
+ return `${naive[1]}T${naive[2]}${LOKI_DEFAULT_TZ_OFFSET}`;
131
+ return value;
132
+ }
133
+ // Loki's query API (what every tool below hits) has no write side at all -
134
+ // unlike Oracle there's no executeQuery()-style connection lifecycle or
135
+ // auditQuery() gate to design around here. Every call is a plain,
136
+ // stateless GET; this helper just centralizes URL-building, the optional
137
+ // auth headers, and turning a non-2xx/network failure into a clean
138
+ // {success: false} instead of a thrown error - mirroring the shape
139
+ // executeQuery() returns in mcp-servers/oracle/src/server.ts, for the same reason:
140
+ // tool results should never surface as a raw MCP protocol error.
141
+ async function lokiFetch(path, params) {
142
+ const url = new URL(path, lokiConfig.LOKI_BASE_URL);
143
+ for (const [key, value] of Object.entries(params ?? {})) {
144
+ if (value !== undefined && value !== null)
145
+ url.searchParams.set(key, String(value));
146
+ }
147
+ const headers = {};
148
+ if (lokiConfig.LOKI_USERNAME || lokiConfig.LOKI_PASSWORD) {
149
+ headers.Authorization = `Basic ${Buffer.from(`${lokiConfig.LOKI_USERNAME ?? ""}:${lokiConfig.LOKI_PASSWORD ?? ""}`).toString("base64")}`;
150
+ }
151
+ if (lokiConfig.LOKI_ORG_ID)
152
+ headers["X-Scope-OrgID"] = lokiConfig.LOKI_ORG_ID;
153
+ try {
154
+ const response = await fetch(url, { headers });
155
+ // Read as text first, not response.json() directly - Loki's error
156
+ // responses aren't guaranteed to be the same JSON shape as its
157
+ // success responses (sometimes plain text), so parsing is only safe
158
+ // once response.ok is known.
159
+ const text = await response.text();
160
+ if (!response.ok) {
161
+ return { success: false, error: `Loki returned ${response.status}: ${text || response.statusText}` };
162
+ }
163
+ const body = text ? JSON.parse(text) : null;
164
+ return { success: true, data: body?.data };
165
+ }
166
+ catch (err) {
167
+ return { success: false, error: err.message };
168
+ }
169
+ }
170
+ async function queryRange({ query, start, end, limit, direction, step }) {
171
+ return lokiFetch("/loki/api/v1/query_range", {
172
+ query,
173
+ start: resolveTimeParam(start),
174
+ end: resolveTimeParam(end),
175
+ limit,
176
+ direction,
177
+ step,
178
+ });
179
+ }
180
+ async function listLabels({ start, end }) {
181
+ return lokiFetch("/loki/api/v1/labels", { start: resolveTimeParam(start), end: resolveTimeParam(end) });
182
+ }
183
+ async function listLabelValues({ label, start, end }) {
184
+ return lokiFetch(`/loki/api/v1/label/${encodeURIComponent(label)}/values`, {
185
+ start: resolveTimeParam(start),
186
+ end: resolveTimeParam(end),
187
+ });
188
+ }
189
+ const TIME_PARAM_DESCRIPTION = `Accepts, in order of preference: a relative time ("now", "now-1h", "now-30m", "now-1d", ` +
190
+ `"now-1h30m" - Grafana's own relative-time syntax for Loki/Prometheus); a local datetime with ` +
191
+ `no timezone, e.g. "2026-09-15T10:00:00" or "2026-09-15 10:00:00" (assumed to be ${LOKI_DEFAULT_TZ_OFFSET}); ` +
192
+ `or an already-qualified absolute value (RFC3339 with an explicit offset, e.g. "2026-09-15T10:00:00+08:00", ` +
193
+ `or a unix epoch in seconds or nanoseconds).`;
194
+ function createMcpServer() {
195
+ const server = new Server({ name: "loki-mcp", version: "1.0.0" }, { capabilities: { tools: {} } });
196
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
197
+ tools: [
198
+ {
199
+ name: "loki_query_range",
200
+ description: "Run a LogQL query against the configured Loki instance over a time range and return matching log lines. Full passthrough - any valid LogQL expression, no restriction.",
201
+ inputSchema: {
202
+ type: "object",
203
+ properties: {
204
+ query: { type: "string", description: "LogQL query, e.g. '{app=\"api\"} |= \"error\"'" },
205
+ start: { type: "string", description: TIME_PARAM_DESCRIPTION + " Optional - Loki defaults to a recent window." },
206
+ end: { type: "string", description: TIME_PARAM_DESCRIPTION + " Optional." },
207
+ limit: { type: "number", description: "Max number of log lines to return. Optional - Loki defaults to 100." },
208
+ direction: { type: "string", enum: ["forward", "backward"], description: "Optional - Loki defaults to backward (newest first)." },
209
+ step: { type: "string", description: "Query resolution step for metric queries, e.g. '30s'. Optional." },
210
+ },
211
+ required: ["query"],
212
+ },
213
+ },
214
+ {
215
+ name: "loki_labels",
216
+ description: "List the label names known to Loki, optionally restricted to a time range. Use this to discover what's queryable before writing a LogQL selector.",
217
+ inputSchema: {
218
+ type: "object",
219
+ properties: {
220
+ start: { type: "string", description: TIME_PARAM_DESCRIPTION + " Optional." },
221
+ end: { type: "string", description: TIME_PARAM_DESCRIPTION + " Optional." },
222
+ },
223
+ },
224
+ },
225
+ {
226
+ name: "loki_label_values",
227
+ description: "List the values seen for one label name, optionally restricted to a time range. Use this after loki_labels to find a concrete value to filter on.",
228
+ inputSchema: {
229
+ type: "object",
230
+ properties: {
231
+ label: { type: "string", description: "The label name to list values for, e.g. 'app' or 'namespace'." },
232
+ start: { type: "string", description: TIME_PARAM_DESCRIPTION + " Optional." },
233
+ end: { type: "string", description: TIME_PARAM_DESCRIPTION + " Optional." },
234
+ },
235
+ required: ["label"],
236
+ },
237
+ },
238
+ ],
239
+ }));
240
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
241
+ const { name, arguments: args } = request.params;
242
+ let result;
243
+ switch (name) {
244
+ case "loki_query_range":
245
+ if (!args?.query)
246
+ return { content: [{ type: "text", text: "Missing required argument: query" }], isError: true };
247
+ result = await queryRange(args);
248
+ break;
249
+ case "loki_labels":
250
+ result = await listLabels((args ?? {}));
251
+ break;
252
+ case "loki_label_values":
253
+ if (!args?.label)
254
+ return { content: [{ type: "text", text: "Missing required argument: label" }], isError: true };
255
+ result = await listLabelValues(args);
256
+ break;
257
+ default:
258
+ return { content: [{ type: "text", text: `Unknown tool: ${name}` }], isError: true };
259
+ }
260
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
261
+ });
262
+ return server;
263
+ }
264
+ // Stateless mode (sessionIdGenerator: undefined) with a fresh Server +
265
+ // transport pair per request - same shell as mcp-servers/oracle/src/server.ts, for the
266
+ // same reason (the SDK's own reference stateless Streamable HTTP server;
267
+ // no session state worth sharing between calls, and sharing one pair would
268
+ // just mean concurrent requests fighting over the same transport).
269
+ const httpServer = http.createServer(async (req, res) => {
270
+ const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
271
+ if (url.pathname !== "/mcp") {
272
+ res.writeHead(404).end();
273
+ return;
274
+ }
275
+ if (req.method !== "POST") {
276
+ res.writeHead(405, { "Content-Type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32000, message: "Method not allowed." }, id: null }));
277
+ return;
278
+ }
279
+ const mcpServer = createMcpServer();
280
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
281
+ res.on("close", () => {
282
+ transport.close();
283
+ mcpServer.close();
284
+ });
285
+ try {
286
+ await mcpServer.connect(transport);
287
+ await transport.handleRequest(req, res);
288
+ }
289
+ catch (err) {
290
+ console.error("Error handling MCP request:", err);
291
+ if (!res.headersSent) {
292
+ res.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null }));
293
+ }
294
+ }
295
+ });
296
+ httpServer.on("error", (err) => {
297
+ console.error("Fatal server error:", err);
298
+ process.exit(1);
299
+ });
300
+ httpServer.listen(serverConfig.LOKI_MCP_PORT, () => {
301
+ console.error(`Loki MCP server listening on http://localhost:${serverConfig.LOKI_MCP_PORT}/mcp`);
302
+ });
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@kealthas-dev/opencode-mcp-loki",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
4
  "type": "module",
5
- "description": "MCP server exposing read-only Loki query/label tools - see README.md for design",
6
- "main": "server.js",
5
+ "description": "MCP server exposing read-only Loki query/label tools - see README.md for design and the LOKI_CONFIG_FILE-driven config",
6
+ "main": "dist/server.js",
7
7
  "bin": {
8
- "opencode-mcp-loki": "server.js"
8
+ "opencode-mcp-loki": "dist/server.js"
9
9
  },
10
10
  "files": [
11
- "server.js"
11
+ "dist"
12
12
  ],
13
13
  "publishConfig": {
14
14
  "access": "public"
@@ -19,13 +19,17 @@
19
19
  "directory": "mcp-servers/loki"
20
20
  },
21
21
  "scripts": {
22
- "start": "node server.js",
23
- "dev": "nodemon server.js"
22
+ "build": "tsc",
23
+ "start": "node dist/server.js",
24
+ "dev": "tsx watch src/server.ts",
25
+ "test": "tsx --test loki.test.ts"
24
26
  },
25
27
  "dependencies": {
26
28
  "@modelcontextprotocol/sdk": "^1.0.0"
27
29
  },
28
30
  "devDependencies": {
29
- "nodemon": "^3.1.0"
31
+ "@types/node": "^22.0.0",
32
+ "tsx": "^4.19.0",
33
+ "typescript": "^5.6.0"
30
34
  }
31
35
  }
package/server.js DELETED
@@ -1,252 +0,0 @@
1
- #!/usr/bin/env node
2
- import http from "node:http";
3
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
4
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
5
- import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
6
-
7
- const LOKI_BASE_URL = process.env.LOKI_BASE_URL;
8
- const LOKI_USERNAME = process.env.LOKI_USERNAME;
9
- const LOKI_PASSWORD = process.env.LOKI_PASSWORD;
10
- const LOKI_ORG_ID = process.env.LOKI_ORG_ID;
11
- const LOKI_MCP_PORT = Number(process.env.LOKI_MCP_PORT ?? "8091");
12
- // Only matters for the "naive" datetime case in resolveTimeParam() below -
13
- // Loki itself is never told about this, it only ever sees a fully-
14
- // qualified offset or an epoch. Defaults to Beijing time since that's
15
- // this deployment's actual timezone; override for a different one.
16
- const LOKI_DEFAULT_TZ_OFFSET = process.env.LOKI_DEFAULT_TZ_OFFSET ?? "+08:00";
17
-
18
- if (!LOKI_BASE_URL) {
19
- console.error("Missing Loki connection details. Set LOKI_BASE_URL.");
20
- process.exit(1);
21
- }
22
-
23
- // Computing a correct start/end by hand (an exact RFC3339 offset, or -
24
- // worse - a 19-digit nanosecond epoch) is real friction for whatever's
25
- // calling this tool, model or human. This resolves three friendlier
26
- // forms into whatever Loki actually accepts, so most callers never have
27
- // to touch epoch math at all:
28
- // - "now" / "now-<duration>" (duration is <n><unit> pairs, unit one of
29
- // s/m/h/d, e.g. "now-1h", "now-30m", "now-1d") - the same relative-time
30
- // convention Grafana itself uses for Loki/Prometheus time ranges, not
31
- // an invented one.
32
- // - a bare "YYYY-MM-DDTHH:MM:SS" or "YYYY-MM-DD HH:MM:SS" with no
33
- // timezone - assumed to be in LOKI_DEFAULT_TZ_OFFSET and qualified
34
- // before being sent.
35
- // Anything else (already a full RFC3339 offset, or a bare epoch number)
36
- // passes straight through unchanged - both were already correct inputs
37
- // before this existed, and stay correct. An unrecognized shape also
38
- // passes straight through rather than being rejected here - Loki's own
39
- // parser is the final judge and returns its own clean error, same
40
- // full-passthrough philosophy as everywhere else in this server.
41
- const RELATIVE_TIME_RE = /^now(?:-((?:\d+[smhd])+))?$/;
42
- const DURATION_PART_RE = /(\d+)([smhd])/g;
43
- const NAIVE_DATETIME_RE = /^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2}(?:\.\d+)?)$/;
44
- const UNIT_MS = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
45
-
46
- function resolveTimeParam(value) {
47
- if (value === undefined || value === null) return value;
48
-
49
- const relative = RELATIVE_TIME_RE.exec(value);
50
- if (relative) {
51
- let offsetMs = 0;
52
- for (const [, amount, unit] of relative[1]?.matchAll(DURATION_PART_RE) ?? []) {
53
- offsetMs += Number(amount) * UNIT_MS[unit];
54
- }
55
- return String((Date.now() - offsetMs) * 1_000_000);
56
- }
57
-
58
- const naive = NAIVE_DATETIME_RE.exec(value);
59
- if (naive) return `${naive[1]}T${naive[2]}${LOKI_DEFAULT_TZ_OFFSET}`;
60
-
61
- return value;
62
- }
63
-
64
- // Loki's query API (what every tool below hits) has no write side at all -
65
- // unlike Oracle there's no executeQuery()-style connection lifecycle or
66
- // auditQuery() gate to design around here. Every call is a plain,
67
- // stateless GET; this helper just centralizes URL-building, the optional
68
- // auth headers, and turning a non-2xx/network failure into a clean
69
- // {success: false} instead of a thrown error - mirroring the shape
70
- // executeQuery() returns in mcp-servers/oracle/server.js, for the same reason:
71
- // tool results should never surface as a raw MCP protocol error.
72
- async function lokiFetch(path, params) {
73
- const url = new URL(path, LOKI_BASE_URL);
74
- for (const [key, value] of Object.entries(params ?? {})) {
75
- if (value !== undefined && value !== null) url.searchParams.set(key, String(value));
76
- }
77
-
78
- const headers = {};
79
- if (LOKI_USERNAME || LOKI_PASSWORD) {
80
- headers.Authorization = `Basic ${Buffer.from(`${LOKI_USERNAME ?? ""}:${LOKI_PASSWORD ?? ""}`).toString("base64")}`;
81
- }
82
- if (LOKI_ORG_ID) headers["X-Scope-OrgID"] = LOKI_ORG_ID;
83
-
84
- try {
85
- const response = await fetch(url, { headers });
86
- // Read as text first, not response.json() directly - Loki's error
87
- // responses aren't guaranteed to be the same JSON shape as its
88
- // success responses (sometimes plain text), so parsing is only safe
89
- // once response.ok is known.
90
- const text = await response.text();
91
-
92
- if (!response.ok) {
93
- return { success: false, error: `Loki returned ${response.status}: ${text || response.statusText}` };
94
- }
95
-
96
- const body = text ? JSON.parse(text) : null;
97
- return { success: true, data: body?.data };
98
- } catch (err) {
99
- return { success: false, error: err.message };
100
- }
101
- }
102
-
103
- async function queryRange({ query, start, end, limit, direction, step }) {
104
- return lokiFetch("/loki/api/v1/query_range", {
105
- query,
106
- start: resolveTimeParam(start),
107
- end: resolveTimeParam(end),
108
- limit,
109
- direction,
110
- step,
111
- });
112
- }
113
-
114
- async function listLabels({ start, end }) {
115
- return lokiFetch("/loki/api/v1/labels", { start: resolveTimeParam(start), end: resolveTimeParam(end) });
116
- }
117
-
118
- async function listLabelValues({ label, start, end }) {
119
- return lokiFetch(`/loki/api/v1/label/${encodeURIComponent(label)}/values`, {
120
- start: resolveTimeParam(start),
121
- end: resolveTimeParam(end),
122
- });
123
- }
124
-
125
- const TIME_PARAM_DESCRIPTION =
126
- `Accepts, in order of preference: a relative time ("now", "now-1h", "now-30m", "now-1d", ` +
127
- `"now-1h30m" - Grafana's own relative-time syntax for Loki/Prometheus); a local datetime with ` +
128
- `no timezone, e.g. "2026-09-15T10:00:00" or "2026-09-15 10:00:00" (assumed to be ${LOKI_DEFAULT_TZ_OFFSET}); ` +
129
- `or an already-qualified absolute value (RFC3339 with an explicit offset, e.g. "2026-09-15T10:00:00+08:00", ` +
130
- `or a unix epoch in seconds or nanoseconds).`;
131
-
132
- function createMcpServer() {
133
- const server = new Server({ name: "loki-mcp", version: "1.0.0" }, { capabilities: { tools: {} } });
134
-
135
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
136
- tools: [
137
- {
138
- name: "loki_query_range",
139
- description:
140
- "Run a LogQL query against the configured Loki instance over a time range and return matching log lines. Full passthrough - any valid LogQL expression, no restriction.",
141
- inputSchema: {
142
- type: "object",
143
- properties: {
144
- query: { type: "string", description: "LogQL query, e.g. '{app=\"api\"} |= \"error\"'" },
145
- start: { type: "string", description: TIME_PARAM_DESCRIPTION + " Optional - Loki defaults to a recent window." },
146
- end: { type: "string", description: TIME_PARAM_DESCRIPTION + " Optional." },
147
- limit: { type: "number", description: "Max number of log lines to return. Optional - Loki defaults to 100." },
148
- direction: { type: "string", enum: ["forward", "backward"], description: "Optional - Loki defaults to backward (newest first)." },
149
- step: { type: "string", description: "Query resolution step for metric queries, e.g. '30s'. Optional." },
150
- },
151
- required: ["query"],
152
- },
153
- },
154
- {
155
- name: "loki_labels",
156
- description: "List the label names known to Loki, optionally restricted to a time range. Use this to discover what's queryable before writing a LogQL selector.",
157
- inputSchema: {
158
- type: "object",
159
- properties: {
160
- start: { type: "string", description: TIME_PARAM_DESCRIPTION + " Optional." },
161
- end: { type: "string", description: TIME_PARAM_DESCRIPTION + " Optional." },
162
- },
163
- },
164
- },
165
- {
166
- name: "loki_label_values",
167
- description: "List the values seen for one label name, optionally restricted to a time range. Use this after loki_labels to find a concrete value to filter on.",
168
- inputSchema: {
169
- type: "object",
170
- properties: {
171
- label: { type: "string", description: "The label name to list values for, e.g. 'app' or 'namespace'." },
172
- start: { type: "string", description: TIME_PARAM_DESCRIPTION + " Optional." },
173
- end: { type: "string", description: TIME_PARAM_DESCRIPTION + " Optional." },
174
- },
175
- required: ["label"],
176
- },
177
- },
178
- ],
179
- }));
180
-
181
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
182
- const { name, arguments: args } = request.params;
183
-
184
- let result;
185
- switch (name) {
186
- case "loki_query_range":
187
- if (!args?.query) return { content: [{ type: "text", text: "Missing required argument: query" }], isError: true };
188
- result = await queryRange(args);
189
- break;
190
- case "loki_labels":
191
- result = await listLabels(args ?? {});
192
- break;
193
- case "loki_label_values":
194
- if (!args?.label) return { content: [{ type: "text", text: "Missing required argument: label" }], isError: true };
195
- result = await listLabelValues(args);
196
- break;
197
- default:
198
- return { content: [{ type: "text", text: `Unknown tool: ${name}` }], isError: true };
199
- }
200
-
201
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
202
- });
203
-
204
- return server;
205
- }
206
-
207
- // Stateless mode (sessionIdGenerator: undefined) with a fresh Server +
208
- // transport pair per request - same shell as mcp-servers/oracle/server.js, for the
209
- // same reason (the SDK's own reference stateless Streamable HTTP server;
210
- // no session state worth sharing between calls, and sharing one pair would
211
- // just mean concurrent requests fighting over the same transport).
212
- const httpServer = http.createServer(async (req, res) => {
213
- const url = new URL(req.url, `http://${req.headers.host ?? "localhost"}`);
214
- if (url.pathname !== "/mcp") {
215
- res.writeHead(404).end();
216
- return;
217
- }
218
- if (req.method !== "POST") {
219
- res.writeHead(405, { "Content-Type": "application/json" }).end(
220
- JSON.stringify({ jsonrpc: "2.0", error: { code: -32000, message: "Method not allowed." }, id: null }),
221
- );
222
- return;
223
- }
224
-
225
- const mcpServer = createMcpServer();
226
- const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
227
- res.on("close", () => {
228
- transport.close();
229
- mcpServer.close();
230
- });
231
-
232
- try {
233
- await mcpServer.connect(transport);
234
- await transport.handleRequest(req, res);
235
- } catch (err) {
236
- console.error("Error handling MCP request:", err);
237
- if (!res.headersSent) {
238
- res.writeHead(500, { "Content-Type": "application/json" }).end(
239
- JSON.stringify({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null }),
240
- );
241
- }
242
- }
243
- });
244
-
245
- httpServer.on("error", (err) => {
246
- console.error("Fatal server error:", err);
247
- process.exit(1);
248
- });
249
-
250
- httpServer.listen(LOKI_MCP_PORT, () => {
251
- console.error(`Loki MCP server listening on http://localhost:${LOKI_MCP_PORT}/mcp`);
252
- });