Files

435 lines
17 KiB
JavaScript

#!/usr/bin/env node
/*
* unraid-monitor — read-only MCP Server fuer die Jarvis-Instanz.
*
* Liefert Monitoring-Daten von Prometheus und Glances an OpenClaw.
*
* Sicherheitsdesign:
* - KANN NICHT SCHREIBEN. Nur HTTP GET, keine anderen Methoden.
* - Nur zwei feste Basis-URLs aus der Umgebung. Keine URL aus
* Tool-Eingaben, damit kein SSRF moeglich ist.
* - Keine Zugangsdaten, keine Auth-Header.
* - Ergebnisse sind groessenbeschraenkt, damit kein Speicherflut moeglich.
* - Keine externen Abhaengigkeiten (npm), nur Node-Standard.
*
* Transport: MCP ueber stdin/stdout, zeilenbasiertes JSON-RPC 2.0.
*/
'use strict';
const PROM_URL = (process.env.PROM_URL || 'http://YOUR_SERVER_IP:9090').replace(/\/+$/, '');
const GLANCES_URL = (process.env.GLANCES_URL || 'http://YOUR_SERVER_IP:61208').replace(/\/+$/, '');
const TIMEOUT_MS = Number(process.env.MCP_TIMEOUT_MS || 8000);
const MAX_CHARS = 40000;
const SERVER_INFO = { name: 'unraid-monitor', version: '1.0.0' };
const PROTOCOL = '2025-06-18';
// ----------------------------------------------------------------- Netzhelfer
async function getJSON(url) {
if (!/^https?:\/\//i.test(url)) throw new Error('URL nicht erlaubt');
const res = await fetch(url, {
method: 'GET',
signal: AbortSignal.timeout(TIMEOUT_MS),
headers: { accept: 'application/json' },
});
if (!res.ok) throw new Error(`HTTP ${res.status} von ${new URL(url).pathname}`);
return res.json();
}
async function prom(query) {
const url = `${PROM_URL}/api/v1/query?query=${encodeURIComponent(query)}`;
const j = await getJSON(url);
if (j.status !== 'success') throw new Error('Prometheus-Anfrage fehlgeschlagen');
return j.data.result;
}
async function glances(path) {
return getJSON(`${GLANCES_URL}${path}`);
}
const gib = (b) => `${(Number(b) / 1073741824).toFixed(1)} GiB`;
const mib = (b) => `${(Number(b) / 1048576).toFixed(0)} MiB`;
const pct = (v) => `${Number(v).toFixed(1)} %`;
const num = (v) => Number(v);
// Containername aus der cgroup-id: letztes Segment nach '/'.
function containerOf(metric) {
if (metric.container && metric.container !== '') return metric.container;
if (metric.name) return metric.name;
if (metric.id) {
const parts = String(metric.id).replace(/\/$/, '').split('/');
return parts[parts.length - 1] || '(root)';
}
return '(unbekannt)';
}
function clip(text) {
const t = String(text);
return t.length > MAX_CHARS ? `${t.slice(0, MAX_CHARS)}\n… [gekuerzt auf ${MAX_CHARS} Zeichen]` : t;
}
// -------------------------------------------------------------------- Tools
async function systemOverview() {
// shfs/fuse/rootfs sind Unraid-Aggregat- bzw. System-Mounts und zeigen
// dieselben Datentraeger mehrfach. Deshalb echte Geraete verwenden.
// PromQL-Muster sind vollstaendig verankert, deshalb "fuse.*" statt "fuse",
// sonst wird fuse.shfs nicht erfasst und shfs erscheint doppelt.
const FS = 'fstype!~"tmpfs|overlay|squashfs|iso9660|shfs|fuse.*|rootfs|nfs.*"';
const [cpu, ram, load, up, probes, ql, fsSize, fsAvail] = await Promise.all([
prom('100*(1-avg(rate(node_cpu_seconds_total{mode="idle"}[5m])))').catch(() => null),
prom('100*(1-node_memory_MemAvailable_bytes/node_memory_MemTotal_bytes)').catch(() => null),
prom('node_load1').catch(() => null),
prom('node_time_seconds - node_boot_time_seconds').catch(() => null),
prom('count by (job) (probe_success == 0)').catch(() => []),
glances('/api/4/quicklook').catch(() => null),
prom(`node_filesystem_size_bytes{${FS}}`).catch(() => []),
prom(`node_filesystem_avail_bytes{${FS}}`).catch(() => []),
]);
const out = [];
out.push('## Systemübersicht');
if (ql) {
out.push(`- CPU: ${pct(ql.cpu)} — ${ql.cpu_name || 'unbekannt'}`);
out.push(`- Kerne: ${ql.percpu ? ql.percpu.length : '?'}`);
if (ql.memavailable !== undefined && ql.memtotal) {
out.push(`- RAM: ${gib(ql.memtotal - ql.memavailable)} von ${gib(ql.memtotal)} belegt (${pct(100 * (1 - ql.memavailable / ql.memtotal))})`);
}
if (ql.swap !== undefined && ql.swoptotal) out.push(`- Swap: ${pct(100 * (1 - ql.swap / ql.swoptotal))}`);
}
if (cpu && cpu[0]) out.push(`- CPU-Last (5 Min): ${pct(cpu[0].value[1])}`);
if (ram && ram[0]) out.push(`- RAM-Auslastung: ${pct(ram[0].value[1])}`);
if (load && load[0]) out.push(`- Load (1 min): ${num(load[0].value[1]).toFixed(2)}`);
if (up && up[0]) {
const s = num(up[0].value[1]);
out.push(`- Laufzeit: ${Math.floor(s / 86400)} Tage ${Math.floor((s % 86400) / 3600)} Std`);
}
if (fsSize.length) {
const availByDev = new Map(fsAvail.map((s) => [s.metric.mountpoint, num(s.value[1])]));
const rows = fsSize
.map((s) => {
const size = num(s.value[1]);
const avail = availByDev.get(s.metric.mountpoint) ?? 0;
return { mp: s.metric.mountpoint || '?', dev: s.metric.device || '', size, used: size - avail };
})
.filter((r) => r.size > 0)
// Mehrere Mountpoints desselben Geraets vermeiden (z. B. / und /boot)
.filter((r, i, a) => a.findIndex((x) => x.dev === r.dev) === i)
.sort((a, b) => b.size - a.size)
.slice(0, 8);
if (rows.length) {
out.push('- Datenträger:');
rows.forEach((r) =>
out.push(
` ${r.mp} — ${gib(r.used)} von ${gib(r.size)} belegt (${pct((100 * r.used) / r.size)})${r.dev ? ` [${r.dev}]` : ''}`
)
);
}
}
if (probes.length) {
out.push(`- Öffentliche Dienste mit fehlgeschlagenem Probe: ${probes.reduce((n, p) => n + num(p.value[1]), 0)}`);
}
return out.join('\n');
}
// Serien mit name-Label sind echte Docker-Container. Alle uebrigen sind
// Host-Prozesse (PIDs), cgroup-Aggregatoren ('/') oder KVM-VMs — diese
// duerfen NICHT addiert werden, sonst wird doppelt gezaehlt.
const DOCKER_MEM = 'container_memory_working_set_bytes{name!=""}';
const DOCKER_CPU = 'rate(container_cpu_usage_seconds_total{name!=""}[5m])';
const VM_MEM = 'container_memory_working_set_bytes{id=~"/machine/.*"}';
function vmName(metric) {
const parts = String(metric.id || '').replace(/\/+$/, '').split('/');
const i = parts.indexOf('machine');
if (i >= 0 && parts[i + 1]) return parts[i + 1].replace(/^qemu-\d+-/, '');
return metric.name || parts[parts.length - 1] || '(VM)';
}
async function containerStats({ top = 10, sort = 'memory', includeVMs = true }) {
const limit = Math.min(Math.max(Number(top) || 10, 1), 50);
const byCpu = sort === 'cpu';
const [dMem, dCPU, vMem] = await Promise.all([
prom(DOCKER_MEM).catch(() => []),
prom(DOCKER_CPU).catch(() => []),
includeVMs ? prom(VM_MEM).catch(() => []) : Promise.resolve([]),
]);
const memMap = new Map(dMem.map((s) => [s.metric.name || containerOf(s.metric), num(s.value[1])]));
const cpuMap = new Map(dCPU.map((s) => [s.metric.name || containerOf(s.metric), num(s.value[1])]));
const rows = [...new Set([...memMap.keys(), ...cpuMap.keys()])]
.map((n) => ({ name: n, mem: memMap.get(n) || 0, cpu: (cpuMap.get(n) || 0) * 100 }))
.filter((r) => r.mem > 0 || r.cpu > 0)
.sort((a, b) => (byCpu ? b.cpu - a.cpu : b.mem - a.mem));
const out = [`## Docker-Container nach ${byCpu ? 'CPU' : 'Speicher'}`, ''];
out.push('| Container | Speicher | CPU (5m) |', '|---|---:|---:|');
rows.slice(0, limit).forEach((r) => out.push(`| ${r.name.slice(0, 44)} | ${mib(r.mem)} | ${r.cpu.toFixed(1)} % |`));
out.push('', `${rows.length} Container insgesamt gemessen.`);
if (vMem.length) {
const vms = vMem
.filter((s) => num(s.value[1]) > 1048576)
.map((s) => ({ name: vmName(s.metric), mem: num(s.value[1]) }))
.sort((a, b) => b.mem - a.mem);
// Mehrfachserien je VM (Sub-Cgroups) zur VM zusammenfassen
const agg = new Map();
vms.forEach((v) => agg.set(v.name, (agg.get(v.name) || 0) + v.mem));
out.push('', '## KVM-VMs (gesamt inkl. Sub-Cgroups)', '', '| VM | Speicher |', '|---|---:|');
[...agg.entries()].sort((a, b) => b[1] - a[1]).forEach(([n, m]) => out.push(`| ${n} | ${gib(m)} |`));
}
return clip(out.join('\n'));
}
async function serviceStatus({ includeHealthy = true }) {
const [up, probes] = await Promise.all([
prom('up').catch(() => []),
prom('probe_success').catch(() => []),
]);
const lines = ['## Scraping-Ziele', ''];
const jobs = new Map();
up.forEach((s) => {
const job = s.metric.job || 'unbekannt';
if (!jobs.has(job)) jobs.set(job, []);
jobs.get(job).push({ name: s.metric.instance || s.metric.endpoint || '?', up: s.value[1] === '1' });
});
for (const [job, list] of [...jobs.entries()].sort()) {
const down = list.filter((x) => !x.up).length;
lines.push(`- **${job}**: ${list.length} Ziele, ${down} down`);
if (down) list.filter((x) => !x.up).forEach((x) => lines.push(` DOWN: ${x.name}`));
}
lines.push('', '## HTTP-Checks (Blackbox)', '');
const bad = probes.filter((s) => s.value[1] !== '1');
lines.push(`${bad.length} von ${probes.length} Zielen nicht erreichbar.`);
bad.forEach((s) => lines.push(`- ${s.metric.instance || '?'}`));
if (includeHealthy && !bad.length) lines.push('- alle Ziele erreichbar');
return clip(lines.join('\n'));
}
async function metricsQuery({ query, limit = 50 }) {
if (typeof query !== 'string' || !query.trim()) throw new Error('query ist erforderlich');
const r = await prom(query.trim());
const lines = [`Metrik-Abfrage ergab ${r.length} Serien`, ''];
r.slice(0, Math.min(Math.max(limit, 1), 200)).forEach((s) => {
const labels = Object.entries(s.metric)
.filter(([k]) => k !== '__name__')
.map(([k, v]) => `${k}="${v}"`)
.join(', ');
lines.push(` {${labels}} ${s.value[1]}`);
});
if (r.length > 200) lines.push(` … ${r.length - 200} weitere`);
return clip(lines.join('\n'));
}
async function alerts() {
const res = await getJSON(`${PROM_URL}/api/v1/alerts`).catch(() => ({ data: { alerts: [] } }));
const a = (res.data && res.data.alerts) || [];
if (!a.length) return 'Keine aktiven Prometheus-Alerts.';
const lines = [`${a.length} aktive Alerts:`, ''];
a.forEach((x) => {
lines.push(`- **${x.labels.alertname}** (${x.state}${x.severity ? `, ${x.severity}` : ''})`);
if (x.annotations) {
if (x.annotations.summary) lines.push(` ${x.annotations.summary}`);
if (x.annotations.description) lines.push(` ${x.annotations.description}`);
}
if (x.labels.instance) lines.push(` Instance: ${x.labels.instance}`);
});
return clip(lines.join('\n'));
}
async function hostNetwork() {
const [rx, tx, disk] = await Promise.all([
prom('sum(rate(node_network_receive_bytes_total{device!~"lo|veth.*|docker.*|br-.*"}[5m]))').catch(() => []),
prom('sum(rate(node_network_transmit_bytes_total{device!~"lo|veth.*|docker.*|br-.*"}[5m]))').catch(() => []),
prom('rate(node_disk_read_bytes_total[5m]) + rate(node_disk_written_bytes_total[5m])').catch(() => []),
]);
const out = ['## Netz und Datenträger', ''];
out.push(`- Ein-/Ausgang gesamt: ${mib(rx[0]?.value[1] || 0)}/s ${mib(tx[0]?.value[1] || 0)}/s`);
const topDisk = disk.sort((a, b) => b.value[1] - a.value[1]).slice(0, 5);
topDisk.forEach((d) => out.push(`- Disk ${d.metric.device || '?'}: ${mib(d.value[1])}/s`));
return out.join('\n');
}
const TOOLS = [
{
name: 'system_overview',
description:
'Aktuelle Systemauslastung des Unraid-Hosts: CPU, RAM, Swap, Load, Laufzeit, Datenträger. ' +
'Liest nur aus Prometheus und Glances, schreibt nichts.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
handler: systemOverview,
},
{
name: 'container_stats',
description:
'Ressourcenverbrauch der Docker-Container, sortiert nach Speicher oder CPU. ' +
'Nützlich um zu finden welcher Container gerade viel Ressourcen frisst.',
inputSchema: {
type: 'object',
properties: {
top: { type: 'integer', minimum: 1, maximum: 50, default: 10, description: 'Wie viele Container anzeigt' },
sort: { type: 'string', enum: ['memory', 'cpu'], default: 'memory', description: 'Sortierung' },
includeVMs: { type: 'boolean', default: true, description: 'Auch KVM-VMs auflisten' },
},
additionalProperties: false,
},
handler: containerStats,
},
{
name: 'service_status',
description:
'Status aller überwachten Ziele: Scraping-Jobs in Prometheus und HTTP-Checks auf die ' +
'öffentlichen Dienste. Zeigt welche Dienste gerade nicht antworten.',
inputSchema: {
type: 'object',
properties: {
includeHealthy: { type: 'boolean', default: true, description: 'Auch erreichbare Ziele nennen' },
},
additionalProperties: false,
},
handler: serviceStatus,
},
{
name: 'metrics_query',
description:
'Beliebige PromQL-Abfrage gegen Prometheus ausführen (Instant Query, nur lesend). ' +
'Beispiel: rate(container_cpu_usage_seconds_total[5m]). Begrenzt auf 200 Serien.',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string', description: 'PromQL-Ausdruck' },
limit: { type: 'integer', minimum: 1, maximum: 200, default: 50 },
},
required: ['query'],
additionalProperties: false,
},
handler: metricsQuery,
},
{
name: 'alerts',
description: 'Aktive Prometheus-Alerts mit Summary und Severity. Leer wenn alles in Ordnung.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
handler: alerts,
},
{
name: 'network_throughput',
description: 'Aktuelle Netz- und Datenträger-Durchsatzraten des Hosts.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
handler: hostNetwork,
},
];
// ------------------------------------------------------------ JSON-RPC / MCP
function reply(id, result) {
return JSON.stringify({ jsonrpc: '2.0', id, result });
}
function replyErr(id, code, message) {
return JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } });
}
async function handle(msg) {
const { id, method, params } = msg || {};
const isNotification = id === undefined || id === null;
switch (method) {
case 'initialize':
return reply(id, {
protocolVersion: (params && params.protocolVersion) || PROTOCOL,
capabilities: { tools: {} },
serverInfo: SERVER_INFO,
});
case 'notifications/initialized':
case 'notifications/cancelled':
return null;
case 'ping':
return reply(id, {});
case 'tools/list':
return reply(id, {
tools: TOOLS.map(({ name, description, inputSchema }) => ({
name,
description,
inputSchema,
// Ohne Annotationen verlangt OpenClaw pro Aufruf eine Bestaetigung.
// Alle Werkzeuge hier sind ausschliesslich lesend, deshalb explizit
// readOnlyHint. destructiveHint bleibt false.
annotations: {
title: name.replace(/_/g, ' '),
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true,
},
})),
});
case 'tools/call': {
const name = params && params.name;
const tool = TOOLS.find((t) => t.name === name);
if (!tool) return reply(id, { content: [{ type: 'text', text: `Unbekanntes Werkzeug: ${name}` }], isError: true });
try {
const text = await tool.handler((params && params.arguments) || {});
return reply(id, { content: [{ type: 'text', text: typeof text === 'string' ? text : JSON.stringify(text) }] });
} catch (e) {
return reply(id, {
content: [{ type: 'text', text: `Fehler bei ${name}: ${e.message}` }],
isError: true,
});
}
}
default:
if (isNotification) return null;
return replyErr(id, -32601, `Methode nicht unterstützt: ${method}`);
}
}
async function main() {
process.stdout.write(
JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/message',
params: { level: 'info', data: `${SERVER_INFO.name} bereit` },
}) + '\n'
);
let buf = '';
process.stdin.setEncoding('utf8');
for await (const chunk of process.stdin) {
buf += chunk;
let idx;
while ((idx = buf.indexOf('\n')) >= 0) {
const line = buf.slice(0, idx).trim();
buf = buf.slice(idx + 1);
if (!line) continue;
let msg;
try {
msg = JSON.parse(line);
} catch {
process.stdout.write(replyErr(null, -32700, 'Parse-Fehler') + '\n');
continue;
}
try {
const out = await handle(msg);
if (out !== null) process.stdout.write(out + '\n');
} catch (e) {
if (msg.id !== undefined && msg.id !== null) {
process.stdout.write(replyErr(msg.id, -32603, e.message) + '\n');
}
}
}
}
}
main().catch((e) => {
process.stderr.write(`unraid-monitor fatal: ${e.message}\n`);
process.exit(1);
});