Initial commit: Clean OpenClaw Jarvis Open-Source Template
This commit is contained in:
commit
ac4601b257
28 files changed
+7718
No files matched your search
@@ -0,0 +1,364 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* prometheus — MCP-Server fuer die lokale Prometheus-Instanz (YOUR_SERVER_IP:9090).
|
||||
*
|
||||
* Sicherheitsmodell:
|
||||
* - Feste Basis-URL aus PROM_URL (kein Host/Port aus Tool-Eingaben -> kein SSRF).
|
||||
* - Nur GET auf Lese-Endpunkte; rein lesend, keine Zugangsdaten noetig.
|
||||
* - Ergebnisgr oessen gedeckelt: max. SERIES_LIMIT Serien, Punkte-Reduktion bei Ranges,
|
||||
* MAX_CHARS als harte Grenze, Timeouts hart.
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const http = require('http');
|
||||
|
||||
const TIMEOUT_MS = 8000;
|
||||
const MAX_CHARS = 60000;
|
||||
const SERIES_LIMIT = 60;
|
||||
const PROM_BASE = process.env.PROM_URL || 'http://YOUR_SERVER_IP:9090';
|
||||
|
||||
function request(path) {
|
||||
return new Promise((resolve) => {
|
||||
const started = Date.now();
|
||||
const req = http.get(PROM_BASE + path, { timeout: TIMEOUT_MS }, (res) => {
|
||||
let data = '';
|
||||
let done = false;
|
||||
const finish = () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
let parsed = null;
|
||||
let parseError = null;
|
||||
if (data) {
|
||||
try {
|
||||
parsed = JSON.parse(data);
|
||||
} catch (e) {
|
||||
parseError = 'Antwort ist kein JSON';
|
||||
}
|
||||
}
|
||||
resolve({ code: res.statusCode || 0, ms: Date.now() - started, parsed, parseError });
|
||||
};
|
||||
res.on('data', (d) => {
|
||||
data += d;
|
||||
if (data.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' });
|
||||
});
|
||||
req.on('error', (e) => resolve({ code: 0, ms: Date.now() - started, parsed: null, parseError: String(e.message || e) }));
|
||||
});
|
||||
}
|
||||
|
||||
const TOOLS = [
|
||||
{
|
||||
name: 'query',
|
||||
description:
|
||||
'Fuehrt eine sofortige PromQL-Abfrage aus (z.B. "node_filesystem_avail_bytes{fstype!=\\"squashfs\\"}", "100 - (node_filesystem_avail_bytes{mountpoint=\\"/\\"}/node_filesystem_size_bytes{mountpoint=\\"/\\"})*100"). Liefert bis zu 60 Serien mit aktuellem Wert.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: 'PromQL-Ausdruck.' },
|
||||
limit: { type: 'integer', description: 'Maximale Serien (1-60, Standard 40).' },
|
||||
},
|
||||
required: ['query'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'query_range',
|
||||
description:
|
||||
'Zeitreihen-Abfrage: berechnet fuer jede Serie Minimum, Maximum, Mittelwert und letzten Wert ueber ein Zeitfenster (z.B. Platten-/RAM-Auslastung der letzten 24 h). Automatische Verdichtung auf max. 50 Stuetzpunkte.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: 'PromQL-Ausdruck (instantaner Vektor).' },
|
||||
hours: { type: 'integer', description: 'Fenster in Stunden (1-168, Standard 24).' },
|
||||
step_minutes: { type: 'integer', description: 'Abtast-Raster in Minuten (1-120, Standard 5).' },
|
||||
limit: { type: 'integer', description: 'Maximale Serien (1-60, Standard 20).' },
|
||||
},
|
||||
required: ['query'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'alerts',
|
||||
description:
|
||||
'Aktive Prometheus-Warnregeln (firing/Pending) mit Ausloeser-Zeit und Labeln. Leer-Lauf = keine Aktiven.',
|
||||
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
||||
},
|
||||
{
|
||||
name: 'targets',
|
||||
description:
|
||||
'Stand der Prometheus-Scraping-Ziele (up/down) inkl. letzten Fehler. Ergibt z.B. prozessgesteuertes Schwarzboard-Monitoring.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
only_problems: { type: 'boolean', description: 'Nur down/halb-down Ziele (Standard: true).' },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'metric_names',
|
||||
description:
|
||||
'Listet vorhandene Metrik-Namen (Filter fungiert als Teilstring), um passende PromQL-Abfragen zu finden.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
filter: { type: 'string', description: 'Teilstring-Filter, z.B. "node_filesystem" oder "container_".' },
|
||||
limit: { type: 'integer', description: 'Maximale Anzahl (1-300, Standard 150).' },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function fmt(n) {
|
||||
if (n === null || n === undefined || Number.isNaN(n)) return '-';
|
||||
const v = Number(n);
|
||||
if (!isFinite(v)) return String(n);
|
||||
if (Math.abs(v) >= 10000 || (Math.abs(v) < 0.01 && v !== 0)) return v.toExponential(2);
|
||||
return Math.round(v * 100) / 100;
|
||||
}
|
||||
|
||||
function metricLabel(m) {
|
||||
const skip = (k) =>
|
||||
k === 'le' || k.startsWith('container_label_') || k === 'id' || k === 'sha256' ||
|
||||
k.endsWith('.name');
|
||||
const pref = ['name', 'container', 'job', 'instance', 'mountpoint', 'device', 'fstype', 'endpoint', 'status'];
|
||||
const keys = Object.keys(m || {}).filter((k) => !skip(k) && k !== '__name__');
|
||||
keys.sort((a, b) => {
|
||||
const pa = pref.indexOf(a);
|
||||
const pb = pref.indexOf(b);
|
||||
return (pa === -1 ? 99 : pa) - (pb === -1 ? 99 : pb) || a.localeCompare(b);
|
||||
});
|
||||
const name = m.__name__ || '';
|
||||
const parts = keys.slice(0, 7).map((k) => `${k}=${String(m[k])}`);
|
||||
return parts.length ? `${name}{${parts.join(',')}}` : name;
|
||||
}
|
||||
|
||||
function parseApi(r) {
|
||||
if (r.parseError) return { error: `Prometheus antwortet nicht: ${r.parseError}` };
|
||||
if (r.code !== 200) return { error: `HTTP ${r.code}: ${(r.parsed && r.parsed.error) || ''}` };
|
||||
if (r.parsed && r.parsed.status === 'error') {
|
||||
const rd = r.parsed.errorType === 'execution' ? ' (PromQL-Syntax/Logik?)' : '';
|
||||
return { error: `Prometheus-Fehler ${r.parsed.errorType}${rd}: ${r.parsed.error || ''}` };
|
||||
}
|
||||
return { data: (r.parsed && r.parsed.data) || null };
|
||||
}
|
||||
|
||||
function fmtInstant(data, limit) {
|
||||
const result = (data && data.result) || [];
|
||||
const rows = result.slice(0, limit);
|
||||
const lines = [
|
||||
'## Prometheus — Instant (PromQL)',
|
||||
'',
|
||||
`${result.length} Serien (gezeigt: ${rows.length})`,
|
||||
'',
|
||||
'| Metrik (Labels ausschnitt) | Wert |',
|
||||
'|---|---|',
|
||||
];
|
||||
for (const s of rows) lines.push(`| ${metricLabel(s.metric)} | ${fmt(s.value && s.value[1])} |`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
async function doQuery(args) {
|
||||
const query = String((args && args.query) || '').trim();
|
||||
if (!query) return { error: true, text: 'Keine PromQL-Abfrage angegeben.' };
|
||||
const limit = Math.min(SERIES_LIMIT, Math.max(1, Number((args && args.limit) || 40)));
|
||||
const r = await request(`/api/v1/query?query=${encodeURIComponent(query)}`);
|
||||
const p = parseApi(r);
|
||||
if (p.error) return { error: true, text: p.error };
|
||||
return { error: false, text: fmtInstant(p.data, limit) };
|
||||
}
|
||||
|
||||
async function doQueryRange(args) {
|
||||
const query = String((args && args.query) || '').trim();
|
||||
if (!query) return { error: true, text: 'Keine PromQL-Abfrage angegeben.' };
|
||||
const hours = Math.min(168, Math.max(1, Number((args && args.hours) || 24)));
|
||||
const limit = Math.min(SERIES_LIMIT, Math.max(1, Number((args && args.limit) || 20)));
|
||||
let stepMin = Math.min(120, Math.max(1, Number((args && args.step_minutes) || 5)));
|
||||
const want = Math.max(1, Math.floor((hours * 60) / stepMin));
|
||||
if (want > 50) stepMin = Math.ceil((hours * 60) / 50);
|
||||
const end = new Date();
|
||||
const start = new Date(end.getTime() - hours * 3600 * 1000);
|
||||
const r = await request(
|
||||
`/api/v1/query_range?query=${encodeURIComponent(query)}&start=${encodeURIComponent(start.toISOString())}&end=${encodeURIComponent(end.toISOString())}&step=${Math.max(1, Math.round(stepMin * 60))}s`
|
||||
);
|
||||
const p = parseApi(r);
|
||||
if (p.error) return { error: true, text: p.error };
|
||||
const result = (p.data && p.data.result) || [];
|
||||
const rows = result.slice(0, limit);
|
||||
const lines = [
|
||||
'## Prometheus — Zeitraum (PromQL)',
|
||||
'',
|
||||
`Fenster: letzte ${hours} h, Schritt ${stepMin} min, ${result.length} Serien (gezeigt: ${rows.length})`,
|
||||
'',
|
||||
'| Metrik (Labels ausschnitt) | letzt | min | max | mittel |',
|
||||
'|---|---|---|---|---|',
|
||||
];
|
||||
for (const s of rows) {
|
||||
const vals = (s.values || []).map((v) => Number(v[1])).filter((v) => isFinite(v));
|
||||
if (!vals.length) {
|
||||
lines.push(`| ${metricLabel(s.metric)} | (leer) | | | |`);
|
||||
continue;
|
||||
}
|
||||
const last = vals[vals.length - 1];
|
||||
const min = Math.min(...vals);
|
||||
const max = Math.max(...vals);
|
||||
const mid = vals.reduce((a, b) => a + b, 0) / vals.length;
|
||||
lines.push(`| ${metricLabel(s.metric)} | ${fmt(last)} | ${fmt(min)} | ${fmt(max)} | ${fmt(mid)} |`);
|
||||
}
|
||||
return { error: false, text: lines.join('\n') };
|
||||
}
|
||||
|
||||
async function doAlerts() {
|
||||
const r = await request('/api/v1/alerts');
|
||||
const p = parseApi(r);
|
||||
if (p.error) return { error: true, text: p.error };
|
||||
const alerts = (p.data && p.data.alerts) || [];
|
||||
const active = alerts.filter((a) => a.state === 'firing');
|
||||
const pending = alerts.filter((a) => a.state === 'pending');
|
||||
const lines = ['## Prometheus — Alerts', '', `firing=${active.length} pending=${pending.length} gesamt=${alerts.length}`, ''];
|
||||
if (!alerts.length) lines.push('Keine Alerts definiert/aktiv. (evtl. liegen Regeln im Alertmanager oder in Grafana)');
|
||||
for (const a of active.concat(pending).slice(0, 40)) {
|
||||
const lbl = a.labels || {};
|
||||
const name = lbl.alertname || '?';
|
||||
const when = a.activeAt ? a.activeAt.replace('T', ' ').slice(0, 19) + 'Z' : '';
|
||||
lines.push(`- **[${a.state}] ${name}**${when ? ' seit ' + when : ''} ${lbl.instance ? '| ' + lbl.instance : ''}`);
|
||||
if (a.annotations && a.annotations.description) lines.push(` ${String(a.annotations.description).slice(0, 200)}`);
|
||||
}
|
||||
return { error: false, text: lines.join('\n') };
|
||||
}
|
||||
|
||||
async function doTargets(args) {
|
||||
const r = await request('/api/v1/targets');
|
||||
const p = parseApi(r);
|
||||
if (p.error) return { error: true, text: p.error };
|
||||
const active = (p.data && p.data.activeTargets) || [];
|
||||
const problems = active.filter((t) => t.health !== 'up');
|
||||
const rows = args && args.only_problems === false ? active : problems;
|
||||
const lines = [
|
||||
'## Prometheus — Targets',
|
||||
'',
|
||||
`up=${active.filter((t) => t.health === 'up').length} down=${problems.length} gesamt=${active.length}`,
|
||||
'',
|
||||
'| Zustand | Job | Ziel | Letzter Fehler |',
|
||||
'|---|---|---|---|',
|
||||
];
|
||||
for (const t of rows.slice(0, 50)) {
|
||||
lines.push(`| ${t.health} | ${(t.labels && t.labels.job) || '-'} | ${t.scrapeUrl} | ${(t.lastError || '').slice(0, 120) || '-'} |`);
|
||||
}
|
||||
return { error: false, text: lines.join('\n') };
|
||||
}
|
||||
|
||||
async function doMetricNames(args) {
|
||||
const r = await request('/api/v1/label/__name__/values');
|
||||
const p = parseApi(r);
|
||||
if (p.error) return { error: true, text: p.error };
|
||||
const all = p.data || [];
|
||||
const filter = String((args && args.filter) || '').toLowerCase();
|
||||
const limit = Math.min(300, Math.max(1, Number((args && args.limit) || 150)));
|
||||
const hit = filter ? all.filter((n) => n.toLowerCase().includes(filter)) : all;
|
||||
const rows = hit.slice(0, limit);
|
||||
const lines = [
|
||||
'## Prometheus — Metrik-Namen',
|
||||
'',
|
||||
`${all.length} gesamt, ${hit.length} passen "${filter || '(alle)'}", gezeigt ${rows.length}`,
|
||||
'',
|
||||
'```',
|
||||
rows.join('\n'),
|
||||
'```',
|
||||
];
|
||||
return { error: false, text: lines.join('\n') };
|
||||
}
|
||||
|
||||
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: 'prometheus', 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 args = (params && params.arguments) || {};
|
||||
const dispatch = {
|
||||
query: [() => doQuery(args)],
|
||||
query_range: [() => doQueryRange(args)],
|
||||
alerts: [() => doAlerts()],
|
||||
targets: [() => doTargets(args)],
|
||||
metric_names: [() => doMetricNames(args)],
|
||||
};
|
||||
const entry = dispatch[name];
|
||||
if (!entry) {
|
||||
reply(id, { content: [{ type: 'text', text: `Unbekanntes Werkzeug: ${name}` }], isError: true });
|
||||
return;
|
||||
}
|
||||
entry[0]()
|
||||
.then((r) => reply(id, { content: [{ type: 'text', text: r.text }], isError: Boolean(r.error) }))
|
||||
.catch((e) => reply(id, { content: [{ type: 'text', text: `Interner Fehler: ${e.message || e}` }], isError: true }));
|
||||
return;
|
||||
}
|
||||
replyError(id, -32601, 'Method not found');
|
||||
}
|
||||
Reference in new issue
Block a user