Initial commit: Clean OpenClaw Jarvis Open-Source Template

This commit is contained in:
jarvis-bot committed 2026-11-06 21:59:47 +00:00
commit ac4601b257
28 files changed
+7718

No files matched your search

+409
View File
@@ -0,0 +1,409 @@
#!/usr/bin/env node
/**
* glances — MCP-Server fuer die Glances-RestAPI (ohne Login, LAN).
*
* Sicherheitsmodell wie service-health.js:
* - Nur HTTP GET auf eine feste Basis-URL; kein Host/Port/URL aus Tool-Eingaben
* -> kein SSRF.
* - Keine Zugangsdaten, Timeouts hart, Ausgaben auf MAX_CHARS begrenzt.
* - Rein lesend.
*/
'use strict';
const http = require('http');
const BASE = process.env.GLANCES_URL || 'http://YOUR_SERVER_IP:61208';
const TIMEOUT_MS = 8000;
const MAX_CHARS = 40000;
function fetchPlugin(plugin) {
return new Promise((resolve) => {
const started = Date.now();
const url = `${BASE}/api/4/${plugin}`;
const req = http.get(url, { timeout: TIMEOUT_MS }, (res) => {
let body = '';
let done = false;
const finish = () => {
if (done) return;
done = true;
let parsed = null;
let parseError = null;
if (body) {
try {
parsed = JSON.parse(body);
} catch (e) {
parseError = 'kein JSON';
}
}
resolve({ code: res.statusCode || 0, ms: Date.now() - started, parsed, parseError, raw: body.slice(0, MAX_CHARS) });
};
res.on('data', (d) => {
body += d;
if (body.length > MAX_CHARS * 2) {
res.destroy();
finish();
}
});
res.on('end', finish);
res.on('close', finish);
res.on('error', finish);
});
req.on('timeout', () => {
req.destroy();
resolve({ code: 0, ms: Date.now() - started, parsed: null, parseError: 'timeout', raw: '' });
});
req.on('error', (e) =>
resolve({ code: 0, ms: Date.now() - started, parsed: null, parseError: String(e.message || e), raw: '' })
);
});
}
function num(v) {
if (typeof v === 'number' && isFinite(v)) return v;
if (v && typeof v === 'object') {
if (typeof v.value === 'number') return v.value;
if (typeof v.avg === 'number') return v.avg;
if (typeof v.total === 'number') return v.total;
}
return null;
}
function fmtBytes(v) {
const n = num(v);
if (n === null) return '-';
const u = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
let i = 0;
let x = n;
while (x >= 1024 && i < u.length - 1) {
x /= 1024;
i++;
}
return `${x.toFixed(x >= 10 || i === 0 ? 0 : 1)} ${u[i]}`;
}
function pctStr(v) {
const n = num(v);
if (n === null) return '-';
const p = n <= 1.0001 && n > 0 && !Number.isInteger(n) ? n * 100 : n;
return `${p.toFixed(1)} %`;
}
function asArray(v) {
if (Array.isArray(v)) return v;
if (v && typeof v === 'object') return [v];
return [];
}
function jsonBlock(v) {
let s;
try {
s = JSON.stringify(v, null, 2);
} catch (e) {
s = String(v);
}
if (s.length > MAX_CHARS - 400) s = s.slice(0, MAX_CHARS - 400) + '\n … gekuerzt';
return '```json\n' + s + '\n```';
}
async function grab(plugins) {
const out = {};
await Promise.all(
plugins.map(async (p) => {
out[p] = await fetchPlugin(p);
})
);
return out;
}
function failLines(what, r) {
return [
`**${what}** nicht lesbar: HTTP ${r.code || 'kein'}${r.parseError ? ` (${r.parseError})` : ''}${
r.parseError && r.raw ? ` — ${r.raw.slice(0, 200)}` : ''
}`,
];
}
async function systemOverview() {
const r = await grab(['cpu', 'mem', 'load', 'system', 'uptime', 'swap']);
const lines = ['## System-Ueberblick (Glances)', ''];
const errs = [];
const cpu = r.cpu.parsed;
if (cpu) {
const list = asArray(cpu);
const cores = list.length > 1 ? list : [cpu];
const total = cores.length === 1 ? cores[0] : null;
if (total && num(total.total) !== null) {
lines.push(
`- CPU gesamt: **${pctStr(total.total)}** ` +
`(user ${pctStr(total.user)}, system ${pctStr(total.system)}, idle ${pctStr(total.idle)})`
);
} else {
let sum = 0;
let n = 0;
for (const c of cores) {
const t = num(c.total);
if (t !== null) {
sum += t;
n++;
}
}
lines.push(`- CPU: **${n ? pctStr(sum / n) : '-'}** (Mittel ueber ${n || 0} Kerne)`);
}
if (num(r.cpu.parsed && r.cpu.parsed['cpu_idle']) !== null) lines.push(`- loadavg: ${jsonBlock(cpu)}`);
} else errs.push(...failLines('cpu', r.cpu));
const mem = r.mem.parsed;
if (mem) {
lines.push(
`- RAM: **${pctStr(mem.percent || mem.used)}** — ${fmtBytes(mem.used)} von ${fmtBytes(mem.total)} belegt, ` +
`${fmtBytes(mem.available)} verfuegbar`
);
} else errs.push(...failLines('mem', r.mem));
const swap = r.swap.parsed;
if (swap) lines.push(`- Swap: ${pctStr(swap.percent || swap.used)} (${fmtBytes(swap.used)} / ${fmtBytes(swap.size)})`);
const load = r.load.parsed;
if (load) {
const l = asArray(load);
const one = l.length === 1 ? l[0] : load;
if (one && (num(one.min1) !== null || num(one['min1']) !== null)) {
lines.push(`- Load: ${num(one.min1)} / ${num(one.min5)} / ${num(one.min15)} (1/5/15 min)`);
} else lines.push(`- Load: ${jsonBlock(load)}`);
}
const sys = r.system.parsed;
if (sys) {
const s = asArray(sys)[0] || sys;
lines.push(`- Host: ${s.hostname || '-'} | OS: ${s.linux_distro || s.os || '-'} | Kernel: ${s.kernel_version || '-'}`);
}
const up = r.uptime.parsed;
if (up) {
const u = asArray(up)[0] || up;
lines.push(`- Uptime: ${u.uptime ? Math.round(u.uptime / 3600) + ' h' : JSON.stringify(u)}`);
}
if (errs.length) lines.push('', errs.join('\n'));
return lines.join('\n');
}
async function filesystems() {
const r = await fetchPlugin('fs');
const rows = asArray(r.parsed);
if (!rows.length) return { error: true, text: failLines('fs', r).join('\n') };
const lines = ['## Dateisysteme (Glances)', '', '| Mount | Geraet | Typ | groesse | belegt | frei | Auslastung |', '|---|---|---|---|---|---|---|'];
const warn = [];
const sorted = rows.slice().sort((a, b) => (num(b.percent) || 0) - (num(a.percent) || 0));
for (const f of sorted) {
const p = num(f.percent) || 0;
const mark = p >= 90 ? '**KRITISCH**' : p >= 75 ? '*hoch*' : '';
if (p >= 90) warn.push(`${f.mnt_point} zu ${p.toFixed(1)} % belegt`);
lines.push(
`| ${f.mnt_point} | ${f.device_name || '-'} | ${f.fs_type || '-'} | ${fmtBytes(f.size)} | ${fmtBytes(f.used)} | ${fmtBytes(f.free)} | ${p.toFixed(1)} %${mark ? ' ' + mark : ''} |`
);
}
if (warn.length) lines.push('', '> Warnung: ' + warn.join('; '));
return lines.join('\n');
}
async function containers() {
const r = await fetchPlugin('containers');
const rows = asArray(r.parsed);
if (!rows.length && r.code !== 200) return { error: true, text: failLines('containers', r).join('\n') };
const lines = [`## Container (${rows.length})`, '', '| Name | Status | CPU | RAM |', '|---|---|---|---|'];
const sorted = rows
.slice()
.sort((a, b) => String(a.name || '').localeCompare(String(b.name || '')));
for (const c of sorted.slice(0, 60)) {
lines.push(
`| ${c.name || c.id || '-'} | ${c.status || '-'} | ${pctStr(c.cpu_percent)} | ${fmtBytes(c.mem_usage)} / ${fmtBytes(c.mem_limit)} |`
);
}
if (sorted.length > 60) lines.push('', `_${sorted.length - 60} weitere nicht angezeigt_`);
return lines.join('\n');
}
async function sensors() {
const r = await fetchPlugin('sensors');
const rows = asArray(r.parsed);
if (!rows.length && r.code !== 200) return { error: true, text: failLines('sensors', r).join('\n') };
const temps = rows.filter((s) => (s.unit || '').match(/C|F/i) && num(s.value) !== null);
const fans = rows.filter((s) => (s.unit || '').match(/rpm/i));
const others = rows.filter((s) => !temps.includes(s) && !fans.includes(s));
const lines = ['## Sensoren (Glances)', ''];
const hot = [];
if (temps.length) {
lines.push('### Temperaturen', '', '| Sensor | Wert | Warnschwelle | Kritisch |', '|---|---|---|---|');
for (const t of temps.sort((a, b) => (num(b.value) || 0) - (num(a.value) || 0)).slice(0, 30)) {
const v = num(t.value);
if (v >= 75 || (num(t.critical) && v >= num(t.critical))) hot.push(`${t.label} ${v}${t.unit || 'C'}`);
lines.push(`| ${t.label || '-'} | ${v}${t.unit || ''} | ${num(t.warning) ?? '-'} | ${num(t.critical) ?? '-'} |`);
}
}
if (fans.length) {
lines.push('', '### Luefter', '', '| Sensor | Wert |', '|---|---|');
for (const f of fans.slice(0, 20)) lines.push(`| ${f.label || '-'} | ${num(f.value)} ${f.unit || ''} |`);
}
if (others.length) lines.push('', `_${others.length} weitere Sensoren (Spannungen u.a.) nicht aufgefuehlt_`);
if (hot.length) lines.push('', '> Hitzewarnung: ' + hot.join('; '));
if (!temps.length && !fans.length && !others.length) return { error: true, text: failLines('sensors', r).join('\n') };
return lines.join('\n');
}
async function storageHealth() {
const [smart, raid] = await grab(['smart', 'raid']);
const lines = ['## Speicher-Zustand (Glances)', ''];
const disks = asArray(smart.parsed);
if (disks.length) {
lines.push('### SMART', '', '| Geraet | Temp | Verschleiss | Reserve | Gesundheit |', '|---|---|---|---|---|');
for (const d of disks) {
const device = d.device || d.name || d.id || '-';
const health = d.health || d.smart_status || d.status;
lines.push(
`| ${device} | ${num(d.temperature) ?? '-'}${d.temperature ? ' C' : ''} | ` +
`${num(d.percentage_used ?? d.wear) ?? '-'} | ${num(d.available_spare) ?? '-'} | ${typeof health === 'object' ? JSON.stringify(health) : health ?? '-'} |`
);
}
} else {
lines.push('SMART:', failLines('smart', smart).join(' '));
}
const raids = asArray(raid.parsed);
lines.push('', '### RAID');
if (raids.length) {
for (const x of raids) {
lines.push(
`- ${x.name || '-'}: status=${x.status || '-'} level=${x.level ?? '-'} disks=${x.disks ?? x.nb_disks ?? '-'} size=${fmtBytes(x.size)}`
);
}
} else {
lines.push('- keine RAID-Array-Daten (oder nicht konfiguriert)');
}
if (raid.raw) lines.push('', `_Rohdaten_: \`${raid.raw.slice(0, 600)}\``);
return lines.join('\n');
}
async function alerts() {
const r = await fetchPlugin('alert');
const rows = asArray(r.parsed);
if (r.code !== 200 && !rows.length) return { error: true, text: failLines('alert', r).join('\n') };
if (!rows.length) return '## Glances-Meldungen\n\n_keine aktiven Meldungen_';
const lines = [`## Glances-Meldungen (${rows.length})`, ''];
for (const a of rows.slice(0, 50)) {
const lvl = a.level ?? a.state ?? '?';
lines.push(`- **[${lvl}]** ${a.service || a.plugin || '-'}: ${a.title || a.message || JSON.stringify(a).slice(0, 200)}`);
}
return lines.join('\n');
}
const TOOLS = [
{
name: 'system_overview',
description:
'CPU-, RAM-, Swap-, Load-, Host- und Uptime-Werte des Unraid-Servers aus Glances. Rein lesend, kein Login noetig.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'filesystems',
description:
'Alle eingehaengten Dateisysteme mit Belegung, sortiert nach Auslastung; ab 75 % "hoch", ab 90 % "KRITISCH" markiert. Rein lesend.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'containers',
description: 'Alle Docker-Container mit Status, CPU- und RAM-Verbrauch (bis 60 Zeilen, nach Name sortiert). Rein lesend.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'sensors',
description:
'Temperaturen, Luefterdrehzahlen und sonstige Sensoren; heisse Werte werden als Hitzewarnung hervorgehoben. Rein lesend.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'storage_health',
description: 'SMART-Daten der Datentraeger (Temperatur, Verschleiss, Gesundheit) und RAID-Array-Status. Rein lesend.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'alerts',
description: 'Aktive Glances-Meldungen (Schwellenverletzungen wie volle Platten, hohe Temperatur). Rein lesend.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
];
function reply(id, result) {
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\n');
}
function replyError(id, code, message) {
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } }) + '\n');
}
let buf = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', (chunk) => {
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;
handle(line);
}
});
function handle(line) {
let msg;
try {
msg = JSON.parse(line);
} catch (e) {
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }) + '\n');
return;
}
const { id, method, params } = msg;
if (method === 'notifications/initialized' || (id === undefined && method)) return;
if (method === 'initialize') {
reply(id, {
protocolVersion: (params && params.protocolVersion) || '2024-11-05',
capabilities: { tools: {} },
serverInfo: { name: 'glances', version: '1.0.0' },
});
return;
}
if (method === 'ping') {
reply(id, {});
return;
}
if (method === 'tools/list') {
reply(id, {
tools: TOOLS.map(({ name, description, inputSchema }) => ({
name,
description,
inputSchema,
annotations: { title: name.replace(/_/g, ' '), readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
})),
});
return;
}
if (method === 'tools/call') {
const name = params && params.name;
const run = async () => {
let out;
if (name === 'system_overview') out = await systemOverview();
else if (name === 'filesystems') out = await filesystems();
else if (name === 'containers') out = await containers();
else if (name === 'sensors') out = await sensors();
else if (name === 'storage_health') out = await storageHealth();
else if (name === 'alerts') out = await alerts();
else return { content: [{ type: 'text', text: `Unbekanntes Werkzeug: ${name}` }], isError: true };
if (typeof out === 'string') return { content: [{ type: 'text', text: out }] };
return { content: [{ type: 'text', text: out.text }], isError: Boolean(out.error) };
};
run()
.then((r) => reply(id, r))
.catch((e) => reply(id, { content: [{ type: 'text', text: String(e && e.message) }], isError: true }));
return;
}
if (id !== undefined) replyError(id, -32601, `Method not found: ${method}`);
}