@kealthas-dev/opencode-mcp-loki 1.1.21 → 1.1.22

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,85 +1,58 @@
1
- # loki mcp server
1
+ # loki
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. 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/`.
3
+ Loki log queries for the agent as a command, `opencode-loki-query`, which reads a LogQL query from stdin, asks Loki (or Grafana's datasource proxy for it) and prints the result. Written in TypeScript (one file, `src/cli.ts`, no dependencies), compiled to `dist/`. There is no server to run. It is the same shape as [`oracle`](../oracle/README.md), whose README has the reasoning (why a command and not an MCP tool, why only a heredoc, why exit 0 or 1).
4
4
 
5
- ## Design, and why it looks the way it does
6
-
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.jsonc.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/src/server.ts`'s shell). No session state worth keeping between calls.
9
- - **Three tools, not one.** `loki_query_range` is the actual log query (arbitrary LogQL, full passthrough — no filtering, mirroring `oracle`'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`'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 `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
-
13
- ## Configuration
14
-
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). The config file's *location* is never user-supplied, only a short name is; see that same section for why.
16
-
17
- - **`$HOME/.config/kealthas-dev/opencode-mcp-loki/server.json`** — the port to listen on. `LOKI_MCP_PORT` env var overrides it, for running more than one instance. Otherwise 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, re-read on every tool call (no restart needed after editing it).** With no `LOKI_CONFIG_ENV` set, it's read from `$HOME/.config/kealthas-dev/opencode-mcp-loki/config.json`. For multiple environments, set `LOKI_CONFIG_ENV` to a name and it reads `config-<name>.json` instead — e.g. `LOKI_CONFIG_ENV=prod` reads `config-prod.json`. The server prints a sample and exits if the resolved file doesn't exist or `LOKI_BASE_URL` is missing from it. 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.
32
-
33
- **When Loki has no directly reachable port of its own** — a common setup where Grafana is the only thing exposed and Loki sits behind it — set `LOKI_VIA_GRAFANA: true` and `LOKI_BASE_URL` becomes Grafana's own URL instead of Loki's. Every request routes through Grafana's datasource-proxy endpoint (`/api/datasources/proxy/<id>/loki/api/v1/...`) rather than hitting a Loki API root directly. `LOKI_USERNAME`/`LOKI_PASSWORD` still work unchanged in this mode — Basic Auth against a real Grafana user account, not Loki itself (Grafana's own default is `admin`/`admin` until changed). `LOKI_GRAFANA_DATASOURCE_ID` is the Loki datasource's ID as assigned inside that Grafana instance (visible in its Data Sources page URL) — optional, defaults to `"1"`, which is what a single-datasource Grafana instance almost always has:
34
- ```json
35
- {
36
- "LOKI_BASE_URL": "http://192.168.1.100:3100",
37
- "LOKI_USERNAME": "admin",
38
- "LOKI_PASSWORD": "admin",
39
- "LOKI_VIA_GRAFANA": true,
40
- "LOKI_GRAFANA_DATASOURCE_ID": "1"
41
- }
42
- ```
43
- A telltale sign you need this mode: querying with `LOKI_VIA_GRAFANA` unset returns an HTML page (often a 404) instead of a JSON error — real Loki's own error responses are always plain text/JSON, never HTML, so an HTML response means the request landed on Grafana's own web UI instead of Loki's API.
44
-
45
- ## Run
46
-
47
- Published as `@kealthas-dev/opencode-mcp-loki` — on a real deployment, install it globally and run the resulting binary (see SETUP.md step 7):
5
+ ## Usage
48
6
 
49
7
  ```bash
50
- npm install -g @kealthas-dev/opencode-mcp-loki
51
- mkdir -p ~/.config/kealthas-dev/opencode-mcp-loki
52
- # real config at ~/.config/kealthas-dev/opencode-mcp-loki/config-prod.json (see config.example.json for the shape)
53
- LOKI_CONFIG_ENV=prod opencode-mcp-loki
54
- ```
8
+ opencode-loki-query --since 1h <<'LOGQL'
9
+ {app="api"} |= "error"
10
+ LOGQL
55
11
 
56
- For local dev/testing against this repo's own checkout (this directory, not the published package), same idea — drop a real config file at the default location, or a named `config-<name>.json` (see `config.example.json` for the shape — the sandbox's entrypoint.sh generates the default one automatically, see Testing below):
12
+ opencode-loki-query --start 2026-09-15T10:00:00+08:00 --end 2026-09-15T10:30:00+08:00 --limit 500 <<'LOGQL'
13
+ {app="api"}
14
+ LOGQL
57
15
 
58
- ```bash
59
- npm install
60
- npm run build
61
- npm start # reads ~/.config/kealthas-dev/opencode-mcp-loki/config.json
16
+ opencode-loki-query --labels --since 24h
17
+ opencode-loki-query --values app --since 24h
18
+ opencode-loki-query --help
62
19
  ```
63
20
 
64
- `npm run dev` runs `src/server.ts` directly via `tsx watch` instead, for a compile-on-save loop.
21
+ The query is read from stdin, always: use a heredoc with a quoted delimiter so the shell leaves the quotes, backticks, `$` and backslashes of LogQL alone. The options are Loki's own query parameters, passed through unchanged, so Loki's own rules and defaults apply (a recent window, 100 lines, newest first):
65
22
 
66
- 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.jsonc.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).
23
+ | Option | Loki parameter |
24
+ |---|---|
25
+ | `--since 1h` | `since`: how far back from now |
26
+ | `--start`, `--end` | `start`, `end`: RFC3339 with an offset (`2026-09-15T10:00:00+08:00`) or a unix timestamp |
27
+ | `--limit N` | `limit`: most log lines to return |
28
+ | `--labels` | the label names, instead of a query |
29
+ | `--values LABEL` | the values of one label, instead of a query |
67
30
 
68
- ## Testing against a real Loki instance
31
+ A query prints **one line of JSON per stream**, `{"stream":{...labels},"values":[["<ns timestamp>","<log line>"],...]}`; `--labels` and `--values` print one name or value per line. Only the result is printed, not Loki's envelope or its statistics block. An error from Loki is printed to stderr exactly as Loki gave it. Exit codes: `0` ok, `1` anything went wrong (stderr says what).
69
32
 
70
- `docker/docker-compose.loki.yml`'s `loki` service is a shared fixture started separately, not by `docker/dev.sh`:
33
+ ## Configuration
71
34
 
72
- ```sh
73
- docker compose -f docker/docker-compose.loki.yml up -d
74
- docker/dev.sh run --rm opencode-dev bash
35
+ Read from a file, not environment variables, at a fixed location under `$HOME/.config/kealthas-dev/opencode-mcp-loki/`: `config.json` by default, or `config-<name>.json` with `LOKI_CONFIG_ENV=<name>`. Only a short name is taken from the environment, never a path. The file is read on every run, so editing it needs nothing restarted.
36
+
37
+ ```json
38
+ {
39
+ "LOKI_BASE_URL": "http://192.168.1.100:3100",
40
+ "LOKI_USERNAME": "username",
41
+ "LOKI_PASSWORD": "password",
42
+ "LOKI_ORG_ID": "tenant-id",
43
+ "LOKI_VIA_GRAFANA": false,
44
+ "LOKI_GRAFANA_DATASOURCE_ID": "1"
45
+ }
75
46
  ```
76
47
 
77
- The default config file is already in place inside that shell — `entrypoint.sh` generates `~/.config/kealthas-dev/opencode-mcp-loki/config.json` from the sandbox's `LOKI_BASE_URL` compose env var. `cd mcp-servers/loki && npm install && npm run build && npm start`, then hit `http://localhost:8091/mcp` from an MCP client or `curl`.
48
+ Only `LOKI_BASE_URL` (no trailing path) is required: Loki is commonly reachable without authentication on an internal LAN. `LOKI_USERNAME`/`LOKI_PASSWORD` are HTTP Basic auth and `LOKI_ORG_ID` the `X-Scope-OrgID` tenant header, each only if that instance needs it.
78
49
 
79
- `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).
50
+ **If Loki has no directly reachable port and the only way in is Grafana's datasource proxy:** set `LOKI_BASE_URL` to Grafana's own URL, `LOKI_VIA_GRAFANA` to `true`, `LOKI_GRAFANA_DATASOURCE_ID` to the datasource's id (the number in `/connections/datasources/edit/...`'s API listing, `GET /api/datasources`; default `1`), and `LOKI_USERNAME`/`LOKI_PASSWORD` to a real Grafana user's Basic auth, not a Loki credential. Requests then go to `/api/datasources/proxy/<id>/loki/api/v1/...`. A Grafana that rejects the request answers with a redirect to its login page, not a 401; the command reports that redirect and what to check instead of following it. `config.example.json` shows the shape.
80
51
 
81
- ## Status
52
+ ## Installing it
82
53
 
83
- **Direct-to-Loki path 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.jsonc.example` (`mcp.loki`, `type: "remote"`, `enabled: true`).
54
+ Published as `@kealthas-dev/opencode-mcp-loki` (the name is part of the config path, so it keeps the `mcp` although there is no MCP any more). `npm install -g @kealthas-dev/opencode-mcp-loki` puts `opencode-loki-query` on `PATH`; then write the config file. See SETUP.md step 7.
55
+
56
+ ## Status
84
57
 
85
- **`LOKI_VIA_GRAFANA` verified against a fake stand-in HTTP server, now automated in `loki.test.ts`** (confirms the request lands on `/api/datasources/proxy/<id>/...` with the right Basic Auth header, and that a redirect-to-login response — real Grafana's actual failure mode for rejected auth, a 302, not a 401 — surfaces as a clean `{success: false}` diagnostic instead of an opaque JSON-parse error) — still not against a real Grafana instance. See `mcp-servers/TODO.md` for adding a real Grafana fixture to the sandbox.
58
+ `loki.test.ts` runs against a real Loki instance in the docker sandbox (see `docker/notes.md`, "Loki test instance"), seeding lines through Loki's push API and running the built command the way an agent would: a query's streams and log lines, `--since`, `--start`/`--end` and `--limit`, a query with `$`, backticks and a backslash arriving untouched, `--labels` and `--values`, a malformed query's error passed through, a query matching nothing, usage errors, an unreachable Loki, and a missing or broken config file. The Grafana path (`LOKI_VIA_GRAFANA`, Basic auth, the org header, a redirect, an error body) is checked against a throwaway HTTP server standing in for Grafana, not against a real Grafana.
package/dist/cli.js ADDED
@@ -0,0 +1,206 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ // Exit codes: 0 ok, 1 anything went wrong (stderr says what).
6
+ const EXIT_FAILURE = 1;
7
+ const NAME = "opencode-loki-query";
8
+ const CONFIG_DIR = join(homedir(), ".config", "kealthas-dev", "opencode-mcp-loki");
9
+ // fetch() has no timeout by default - without this, a Loki/Grafana host
10
+ // that accepts the TCP connection but never responds (e.g. stuck behind a
11
+ // hung reverse proxy) leaves the request pending forever.
12
+ const REQUEST_TIMEOUT_MS = 30_000;
13
+ const HELP = `Usage: ${NAME} [options] <<'LOGQL'
14
+ <LogQL query>
15
+ LOGQL
16
+ ${NAME} --labels [options]
17
+ ${NAME} --values LABEL [options]
18
+
19
+ Runs one LogQL query, read from stdin, against the configured Loki and prints the result. A query prints one line of
20
+ JSON per stream (the entries are [nanosecond timestamp, log line] pairs); --labels and --values print one name or
21
+ value per line. Errors from Loki are printed exactly as Loki gave them.
22
+
23
+ The options are Loki's own query parameters, passed through unchanged:
24
+ --since DURATION how far back from now, e.g. 1h or 30m (Loki's default is a recent window)
25
+ --start TIME start of the range: RFC3339 with an offset (2026-09-15T10:00:00+08:00) or a unix timestamp
26
+ --end TIME end of the range, same forms
27
+ --limit N most log lines to return (Loki's default is 100)
28
+ --labels list the label names instead of running a query
29
+ --values LABEL list the values of one label instead of running a query
30
+ --help this text
31
+
32
+ The query goes in a heredoc with a quoted delimiter (<<'LOGQL', as above), so the shell leaves it alone: the quotes,
33
+ backticks, $ and backslashes of LogQL all reach Loki as written.
34
+
35
+ Exit codes: 0 ok, 1 failed; stderr says why.`;
36
+ function usageError(message) {
37
+ console.error(`${NAME}: ${message}\n\n${HELP}`);
38
+ process.exit(EXIT_FAILURE);
39
+ }
40
+ function parseArgs(argv) {
41
+ if (argv.includes("--help") || argv.includes("-h")) {
42
+ console.log(HELP);
43
+ process.exit(0);
44
+ }
45
+ const opts = { labels: false };
46
+ const valueOf = (i, flag) => {
47
+ const v = argv[i + 1];
48
+ if (v === undefined)
49
+ usageError(`${flag} needs a value`);
50
+ return v;
51
+ };
52
+ for (let i = 0; i < argv.length; i++) {
53
+ const arg = argv[i];
54
+ if (arg === "--labels")
55
+ opts.labels = true;
56
+ else if (arg === "--values")
57
+ opts.values = valueOf(i++, arg);
58
+ else if (arg === "--since")
59
+ opts.since = valueOf(i++, arg);
60
+ else if (arg === "--start")
61
+ opts.start = valueOf(i++, arg);
62
+ else if (arg === "--end")
63
+ opts.end = valueOf(i++, arg);
64
+ else if (arg === "--limit")
65
+ opts.limit = valueOf(i++, arg);
66
+ else
67
+ usageError(`unknown argument ${arg} (the query is read from stdin, not given as an argument)`);
68
+ }
69
+ if (opts.labels && opts.values !== undefined)
70
+ usageError("--labels and --values are separate modes");
71
+ return opts;
72
+ }
73
+ async function readStdin() {
74
+ const chunks = [];
75
+ for await (const chunk of process.stdin)
76
+ chunks.push(chunk);
77
+ return Buffer.concat(chunks).toString("utf8");
78
+ }
79
+ // The whole of stdin is the query. There is deliberately no argument form: LogQL is full of quotes, backticks and
80
+ // sometimes $, so any shell quoting of it is a way to get it wrong.
81
+ async function readQuery() {
82
+ if (process.stdin.isTTY)
83
+ usageError("no query: give it on stdin, with a heredoc");
84
+ const query = await readStdin();
85
+ if (query.trim() === "")
86
+ usageError("the query on stdin is empty");
87
+ return query;
88
+ }
89
+ const SAMPLE_CONFIG = {
90
+ LOKI_BASE_URL: "http://192.168.1.100:3100 (no trailing path)",
91
+ LOKI_USERNAME: "username (optional, HTTP basic auth)",
92
+ LOKI_PASSWORD: "password (optional)",
93
+ LOKI_ORG_ID: "tenant-id (optional, multi-tenant Loki / Grafana Cloud-style setups)",
94
+ LOKI_VIA_GRAFANA: "true (optional - set when Loki is only reachable through Grafana's own datasource proxy, not directly; LOKI_BASE_URL becomes Grafana's URL in that case)",
95
+ LOKI_GRAFANA_DATASOURCE_ID: "1 (optional, only used when LOKI_VIA_GRAFANA is true - defaults to 1)",
96
+ };
97
+ // config.json by default, config-<name>.json when LOKI_CONFIG_ENV is set. Read on every run, so editing it
98
+ // needs nothing restarted. Only a short name is taken from the environment, never a path.
99
+ // Only LOKI_BASE_URL is required - Loki is commonly reachable unauthenticated on an internal LAN.
100
+ function loadConfig() {
101
+ const envName = process.env.LOKI_CONFIG_ENV;
102
+ const path = join(CONFIG_DIR, envName ? `config-${envName}.json` : "config.json");
103
+ const sample = `Expected Loki config file at: ${path}\n${JSON.stringify(SAMPLE_CONFIG, null, 2)}`;
104
+ if (!existsSync(path))
105
+ throw new Error(`Loki config file not found.\n${sample}`);
106
+ try {
107
+ const raw = JSON.parse(readFileSync(path, "utf8"));
108
+ if (!raw.LOKI_BASE_URL)
109
+ throw new Error("missing required key LOKI_BASE_URL");
110
+ return {
111
+ baseUrl: raw.LOKI_BASE_URL,
112
+ username: raw.LOKI_USERNAME,
113
+ password: raw.LOKI_PASSWORD,
114
+ orgId: raw.LOKI_ORG_ID,
115
+ viaGrafana: raw.LOKI_VIA_GRAFANA === true,
116
+ grafanaDatasourceId: raw.LOKI_GRAFANA_DATASOURCE_ID !== undefined ? String(raw.LOKI_GRAFANA_DATASOURCE_ID) : "1",
117
+ };
118
+ }
119
+ catch (err) {
120
+ throw new Error(`Failed to load Loki config from ${path}: ${err.message}\n${sample}`);
121
+ }
122
+ }
123
+ async function main() {
124
+ const opts = parseArgs(process.argv.slice(2));
125
+ let path;
126
+ const params = new URLSearchParams();
127
+ if (opts.labels)
128
+ path = "/loki/api/v1/labels";
129
+ else if (opts.values !== undefined)
130
+ path = `/loki/api/v1/label/${encodeURIComponent(opts.values)}/values`;
131
+ else {
132
+ path = "/loki/api/v1/query_range";
133
+ params.set("query", await readQuery());
134
+ if (opts.limit !== undefined)
135
+ params.set("limit", opts.limit);
136
+ }
137
+ for (const key of ["since", "start", "end"]) {
138
+ if (opts[key] !== undefined)
139
+ params.set(key, opts[key]);
140
+ }
141
+ let config;
142
+ try {
143
+ config = loadConfig();
144
+ }
145
+ catch (err) {
146
+ console.error(`${NAME}: ${err.message}`);
147
+ return EXIT_FAILURE;
148
+ }
149
+ const effectivePath = config.viaGrafana ? `/api/datasources/proxy/${config.grafanaDatasourceId}${path}` : path;
150
+ const url = new URL(effectivePath, config.baseUrl);
151
+ url.search = params.toString();
152
+ const headers = {};
153
+ if (config.username || config.password) {
154
+ headers.Authorization = `Basic ${Buffer.from(`${config.username ?? ""}:${config.password ?? ""}`).toString("base64")}`;
155
+ }
156
+ if (config.orgId)
157
+ headers["X-Scope-OrgID"] = config.orgId;
158
+ let response;
159
+ try {
160
+ // Manual redirect handling: a Grafana instance rejecting the request (missing/expired auth, or
161
+ // LOKI_VIA_GRAFANA off when it should be on) responds with a 302 to its own login page, not a 401. Node's
162
+ // fetch follows that by default, landing on the login page's HTML with a misleadingly successful 200.
163
+ response = await fetch(url, { headers, redirect: "manual", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
164
+ }
165
+ catch (err) {
166
+ console.error(err.message);
167
+ return EXIT_FAILURE;
168
+ }
169
+ if (response.status >= 300 && response.status < 400) {
170
+ const location = response.headers.get("location") ?? "(no Location header)";
171
+ const hint = config.viaGrafana
172
+ ? "check LOKI_USERNAME/LOKI_PASSWORD (must be a real Grafana user's Basic Auth) and LOKI_GRAFANA_DATASOURCE_ID"
173
+ : "if this Loki is only reachable through Grafana's datasource proxy, set LOKI_VIA_GRAFANA: true (see README's Configuration section)";
174
+ console.error(`${NAME}: the request was redirected (${response.status}) to ${location} instead of returning data - ${hint}.`);
175
+ return EXIT_FAILURE;
176
+ }
177
+ // Text first, not response.json() - Loki's error responses aren't guaranteed to be JSON.
178
+ const text = await response.text();
179
+ if (!response.ok) {
180
+ console.error(text.trim() || `HTTP ${response.status} ${response.statusText}`); // Loki's own words
181
+ return EXIT_FAILURE;
182
+ }
183
+ // Only the result is printed: the envelope and the statistics block (a few KB per query) are not data.
184
+ const data = (text ? JSON.parse(text) : null)?.data;
185
+ const lines = Array.isArray(data) ? data : data?.result;
186
+ if (Array.isArray(lines)) {
187
+ for (const item of lines)
188
+ console.log(typeof item === "string" ? item : JSON.stringify(item));
189
+ }
190
+ else {
191
+ console.log(JSON.stringify(lines ?? data ?? null));
192
+ }
193
+ return 0;
194
+ }
195
+ // `... | head` closes the pipe early; that is not an error.
196
+ process.stdout.on("error", (err) => {
197
+ if (err.code === "EPIPE")
198
+ process.exit(0);
199
+ throw err;
200
+ });
201
+ main().then((code) => {
202
+ process.exitCode = code;
203
+ }, (err) => {
204
+ console.error(`${NAME}: ${err.message}`);
205
+ process.exitCode = EXIT_FAILURE;
206
+ });
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@kealthas-dev/opencode-mcp-loki",
3
- "version": "1.1.21",
3
+ "version": "1.1.22",
4
4
  "type": "module",
5
- "description": "MCP server exposing read-only Loki query/label tools - see README.md for design and the config.json-driven config",
6
- "main": "dist/server.js",
5
+ "description": "Loki log queries for the agent as a command, `opencode-loki-query`, reading the LogQL from stdin and connecting straight to Loki (or Grafana's datasource proxy) - see README.md for the design and the config.json-driven config",
6
+ "main": "dist/cli.js",
7
7
  "bin": {
8
- "opencode-mcp-loki": "dist/server.js"
8
+ "opencode-loki-query": "dist/cli.js"
9
9
  },
10
10
  "files": [
11
11
  "dist"
@@ -20,14 +20,8 @@
20
20
  },
21
21
  "scripts": {
22
22
  "build": "tsc",
23
- "start": "node dist/server.js",
24
- "dev": "tsx watch src/server.ts",
25
23
  "test": "tsx --test loki.test.ts"
26
24
  },
27
- "dependencies": {
28
- "@modelcontextprotocol/sdk": "^1.0.0",
29
- "zod": "^3.25 || ^4.0"
30
- },
31
25
  "devDependencies": {
32
26
  "@types/node": "^22.0.0",
33
27
  "tsx": "^4.19.0",
package/dist/server.js DELETED
@@ -1,265 +0,0 @@
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 } from "node:path";
6
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
8
- import { z } from "zod";
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
- LOKI_VIA_GRAFANA: "true (optional - set when Loki is only reachable through Grafana's own datasource proxy, not directly; LOKI_BASE_URL becomes Grafana's URL in that case)",
20
- LOKI_GRAFANA_DATASOURCE_ID: "1 (optional, only used when LOKI_VIA_GRAFANA is true - defaults to 1)",
21
- };
22
- function printSampleConfig(label, path, sample) {
23
- console.error(`\nExpected ${label} at: ${path}\n`);
24
- console.error(JSON.stringify(sample, null, 2));
25
- console.error("");
26
- }
27
- // LOKI_MCP_PORT env var overrides server.json, for running several
28
- // instances (different projects/ports) without separate port files.
29
- function loadServerConfig() {
30
- if (process.env.LOKI_MCP_PORT !== undefined) {
31
- const port = Number(process.env.LOKI_MCP_PORT);
32
- if (!Number.isInteger(port) || port <= 0) {
33
- console.error(`LOKI_MCP_PORT must be a positive integer, got: ${JSON.stringify(process.env.LOKI_MCP_PORT)}`);
34
- process.exit(1);
35
- }
36
- return { LOKI_MCP_PORT: port };
37
- }
38
- if (!existsSync(SERVER_CONFIG_PATH)) {
39
- return { LOKI_MCP_PORT: DEFAULT_PORT };
40
- }
41
- try {
42
- const raw = JSON.parse(readFileSync(SERVER_CONFIG_PATH, "utf8"));
43
- const port = Number(raw.LOKI_MCP_PORT ?? DEFAULT_PORT);
44
- if (!Number.isInteger(port) || port <= 0) {
45
- throw new Error(`LOKI_MCP_PORT must be a positive integer, got: ${JSON.stringify(raw.LOKI_MCP_PORT)}`);
46
- }
47
- return { LOKI_MCP_PORT: port };
48
- }
49
- catch (err) {
50
- console.error(`Failed to load server config: ${err.message}`);
51
- printSampleConfig("server config", SERVER_CONFIG_PATH, SAMPLE_SERVER_CONFIG);
52
- process.exit(1);
53
- }
54
- }
55
- // config.json by default, config-<name>.json when LOKI_CONFIG_ENV is set.
56
- // Only LOKI_BASE_URL is required - Loki is commonly reachable unauthenticated
57
- // on an internal LAN, unlike mcp-servers/oracle.
58
- function loadLokiConfig() {
59
- const envName = process.env.LOKI_CONFIG_ENV;
60
- const resolvedPath = join(CONFIG_DIR, envName ? `config-${envName}.json` : "config.json");
61
- if (!existsSync(resolvedPath)) {
62
- console.error(`Loki config file not found: ${resolvedPath}`);
63
- printSampleConfig("Loki config file", resolvedPath, SAMPLE_LOKI_CONFIG);
64
- process.exit(1);
65
- }
66
- try {
67
- const raw = JSON.parse(readFileSync(resolvedPath, "utf8"));
68
- if (!raw.LOKI_BASE_URL) {
69
- throw new Error("missing required key LOKI_BASE_URL");
70
- }
71
- return {
72
- LOKI_BASE_URL: raw.LOKI_BASE_URL,
73
- LOKI_USERNAME: raw.LOKI_USERNAME,
74
- LOKI_PASSWORD: raw.LOKI_PASSWORD,
75
- LOKI_ORG_ID: raw.LOKI_ORG_ID,
76
- LOKI_DEFAULT_TZ_OFFSET: raw.LOKI_DEFAULT_TZ_OFFSET,
77
- LOKI_VIA_GRAFANA: raw.LOKI_VIA_GRAFANA === true,
78
- LOKI_GRAFANA_DATASOURCE_ID: raw.LOKI_GRAFANA_DATASOURCE_ID !== undefined ? String(raw.LOKI_GRAFANA_DATASOURCE_ID) : "1",
79
- };
80
- }
81
- catch (err) {
82
- console.error(`Failed to load Loki config from ${resolvedPath}: ${err.message}`);
83
- printSampleConfig("Loki config file", resolvedPath, SAMPLE_LOKI_CONFIG);
84
- process.exit(1);
85
- }
86
- }
87
- const serverConfig = loadServerConfig();
88
- // Hand-computing a correct start/end (an RFC3339 offset, or a 19-digit
89
- // nanosecond epoch) is real friction, so this resolves two friendlier forms
90
- // into what Loki accepts:
91
- // - "now"/"now-<duration>" (s/m/h/d units, e.g. "now-1h") - Grafana's own
92
- // relative-time convention, not an invented one.
93
- // - a bare "YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DD HH:MM:SS" with no timezone -
94
- // assumed to be LOKI_DEFAULT_TZ_OFFSET and qualified before sending.
95
- // Anything else (already RFC3339, a bare epoch, or unrecognized) passes
96
- // straight through - Loki's own parser is the final judge, same
97
- // full-passthrough philosophy as everywhere else in this server.
98
- const RELATIVE_TIME_RE = /^now(?:-((?:\d+[smhd])+))?$/;
99
- const DURATION_PART_RE = /(\d+)([smhd])/g;
100
- const NAIVE_DATETIME_RE = /^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2}(?:\.\d+)?)$/;
101
- const UNIT_MS = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
102
- function resolveTimeParam(value, tzOffset) {
103
- if (value === undefined || value === null)
104
- return value;
105
- const relative = RELATIVE_TIME_RE.exec(value);
106
- if (relative) {
107
- let offsetMs = 0;
108
- for (const [, amount, unit] of relative[1]?.matchAll(DURATION_PART_RE) ?? []) {
109
- offsetMs += Number(amount) * UNIT_MS[unit];
110
- }
111
- return String((Date.now() - offsetMs) * 1_000_000);
112
- }
113
- const naive = NAIVE_DATETIME_RE.exec(value);
114
- if (naive)
115
- return `${naive[1]}T${naive[2]}${tzOffset}`;
116
- return value;
117
- }
118
- // fetch() has no timeout by default - without this, a Loki/Grafana host
119
- // that accepts the TCP connection but never responds (e.g. stuck behind a
120
- // hung reverse proxy) leaves the request pending forever.
121
- const REQUEST_TIMEOUT_MS = 30_000;
122
- // Loki's API is read-only, so unlike Oracle there's no connection lifecycle
123
- // or audit gate here - just a stateless GET. Centralizes URL-building, auth
124
- // headers, and turning a non-2xx/network failure into {success: false}
125
- // rather than a thrown error, so tool results never surface as a raw MCP error.
126
- async function lokiFetch(path, params) {
127
- const lokiConfig = loadLokiConfig();
128
- const effectivePath = lokiConfig.LOKI_VIA_GRAFANA
129
- ? `/api/datasources/proxy/${lokiConfig.LOKI_GRAFANA_DATASOURCE_ID}${path}`
130
- : path;
131
- const url = new URL(effectivePath, lokiConfig.LOKI_BASE_URL);
132
- for (const [key, value] of Object.entries(params ?? {})) {
133
- if (value !== undefined && value !== null)
134
- url.searchParams.set(key, String(value));
135
- }
136
- const headers = {};
137
- if (lokiConfig.LOKI_USERNAME || lokiConfig.LOKI_PASSWORD) {
138
- headers.Authorization = `Basic ${Buffer.from(`${lokiConfig.LOKI_USERNAME ?? ""}:${lokiConfig.LOKI_PASSWORD ?? ""}`).toString("base64")}`;
139
- }
140
- if (lokiConfig.LOKI_ORG_ID)
141
- headers["X-Scope-OrgID"] = lokiConfig.LOKI_ORG_ID;
142
- try {
143
- // Manual redirect handling: a Grafana instance rejecting the request
144
- // (missing/expired auth, or LOKI_VIA_GRAFANA off when it should be on)
145
- // responds with a 302 to its own login page, not a 401. Node's fetch
146
- // follows that by default, landing on the login page's HTML with a
147
- // misleadingly "successful" 200 status - the JSON.parse below would
148
- // then fail with an opaque syntax error instead of a diagnosable one.
149
- const response = await fetch(url, { headers, redirect: "manual", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
150
- if (response.status >= 300 && response.status < 400) {
151
- const location = response.headers.get("location") ?? "(no Location header)";
152
- const hint = lokiConfig.LOKI_VIA_GRAFANA
153
- ? "check LOKI_USERNAME/LOKI_PASSWORD (must be a real Grafana user's Basic Auth) and LOKI_GRAFANA_DATASOURCE_ID"
154
- : "if this Loki is only reachable through Grafana's datasource proxy, set LOKI_VIA_GRAFANA: true (see README's Configuration section)";
155
- return { success: false, error: `Request was redirected (${response.status}) to ${location} instead of returning data - ${hint}.` };
156
- }
157
- // Text first, not response.json() - Loki's error responses aren't
158
- // guaranteed the same JSON shape as success (sometimes plain text).
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
- const tzOffset = loadLokiConfig().LOKI_DEFAULT_TZ_OFFSET ?? "+08:00";
172
- return lokiFetch("/loki/api/v1/query_range", {
173
- query,
174
- start: resolveTimeParam(start, tzOffset),
175
- end: resolveTimeParam(end, tzOffset),
176
- limit,
177
- direction,
178
- step,
179
- });
180
- }
181
- async function listLabels({ start, end }) {
182
- const tzOffset = loadLokiConfig().LOKI_DEFAULT_TZ_OFFSET ?? "+08:00";
183
- return lokiFetch("/loki/api/v1/labels", { start: resolveTimeParam(start, tzOffset), end: resolveTimeParam(end, tzOffset) });
184
- }
185
- async function listLabelValues({ label, start, end }) {
186
- const tzOffset = loadLokiConfig().LOKI_DEFAULT_TZ_OFFSET ?? "+08:00";
187
- return lokiFetch(`/loki/api/v1/label/${encodeURIComponent(label)}/values`, {
188
- start: resolveTimeParam(start, tzOffset),
189
- end: resolveTimeParam(end, tzOffset),
190
- });
191
- }
192
- function createMcpServer() {
193
- const tzOffset = loadLokiConfig().LOKI_DEFAULT_TZ_OFFSET ?? "+08:00";
194
- const TIME_PARAM_DESCRIPTION = `Accepts, in order of preference: a relative time ("now", "now-1h", "now-30m", "now-1d", ` +
195
- `"now-1h30m" - Grafana's own relative-time syntax for Loki/Prometheus); a local datetime with ` +
196
- `no timezone, e.g. "2026-09-15T10:00:00" or "2026-09-15 10:00:00" (assumed to be ${tzOffset}); ` +
197
- `or an already-qualified absolute value (RFC3339 with an explicit offset, e.g. "2026-09-15T10:00:00+08:00", ` +
198
- `or a unix epoch in seconds or nanoseconds).`;
199
- const server = new McpServer({ name: "loki-mcp", version: "1.0.0" });
200
- const respond = (result) => ({ content: [{ type: "text", text: JSON.stringify(result, null, 2) }] });
201
- server.registerTool("loki_query_range", {
202
- 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.",
203
- inputSchema: {
204
- query: z.string().describe("LogQL query, e.g. '{app=\"api\"} |= \"error\"'"),
205
- start: z.string().optional().describe(TIME_PARAM_DESCRIPTION + " Optional - Loki defaults to a recent window."),
206
- end: z.string().optional().describe(TIME_PARAM_DESCRIPTION + " Optional."),
207
- limit: z.number().optional().describe("Max number of log lines to return. Optional - Loki defaults to 100."),
208
- direction: z.enum(["forward", "backward"]).optional().describe("Optional - Loki defaults to backward (newest first)."),
209
- step: z.string().optional().describe("Query resolution step for metric queries, e.g. '30s'. Optional."),
210
- },
211
- }, async (args) => respond(await queryRange(args)));
212
- server.registerTool("loki_labels", {
213
- 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.",
214
- inputSchema: {
215
- start: z.string().optional().describe(TIME_PARAM_DESCRIPTION + " Optional."),
216
- end: z.string().optional().describe(TIME_PARAM_DESCRIPTION + " Optional."),
217
- },
218
- }, async (args) => respond(await listLabels(args)));
219
- server.registerTool("loki_label_values", {
220
- 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.",
221
- inputSchema: {
222
- label: z.string().describe("The label name to list values for, e.g. 'app' or 'namespace'."),
223
- start: z.string().optional().describe(TIME_PARAM_DESCRIPTION + " Optional."),
224
- end: z.string().optional().describe(TIME_PARAM_DESCRIPTION + " Optional."),
225
- },
226
- }, async (args) => respond(await listLabelValues(args)));
227
- return server;
228
- }
229
- // Stateless mode: fresh Server+transport pair per request, same shape and
230
- // reason as oracle/src/server.ts - no session state to share, and reusing
231
- // one pair would mean requests fighting over it.
232
- const httpServer = http.createServer(async (req, res) => {
233
- const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
234
- if (url.pathname !== "/mcp") {
235
- res.writeHead(404).end();
236
- return;
237
- }
238
- if (req.method !== "POST") {
239
- res.writeHead(405, { "Content-Type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32000, message: "Method not allowed." }, id: null }));
240
- return;
241
- }
242
- const mcpServer = createMcpServer();
243
- const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
244
- res.on("close", () => {
245
- transport.close();
246
- mcpServer.close();
247
- });
248
- try {
249
- await mcpServer.connect(transport);
250
- await transport.handleRequest(req, res);
251
- }
252
- catch (err) {
253
- console.error("Error handling MCP request:", err);
254
- if (!res.headersSent) {
255
- res.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null }));
256
- }
257
- }
258
- });
259
- httpServer.on("error", (err) => {
260
- console.error("Fatal server error:", err);
261
- process.exit(1);
262
- });
263
- httpServer.listen(serverConfig.LOKI_MCP_PORT, () => {
264
- console.error(`Loki MCP server listening on http://localhost:${serverConfig.LOKI_MCP_PORT}/mcp`);
265
- });
@@ -1 +0,0 @@
1
- export {};