#!/usr/bin/env node /** * service-health — MCP-Server fuer unauthentifizierte Service-Health-Endpunkte. * * Sicherheitsmodell (bewusst eng): * - Nur HTTP GET, feste Basis-URLs aus der harten Tabelle unten. * - Keine URL, kein Host, kein Port aus Tool-Eingaben -> kein SSRF. * - Keine Auth-Kopfzeilen, keine Zugangsdaten. * - Ergebnisse auf MAX_CHARS begrenzt, Timeouts hart. */ 'use strict'; const http = require('http'); const fs = require('fs'); const TIMEOUT_MS = 6000; const MAX_CHARS = 40000; const SERVICES = [ { name: 'grafana', label: 'Grafana', url: 'http://YOUR_SERVER_IP:3300/api/health' }, { name: 'gitea', label: 'Gitea', url: 'http://YOUR_SERVER_IP:30005/api/v1/version' }, { name: 'gotify', label: 'Gotify', url: 'http://YOUR_SERVER_IP:8070/health' }, { name: 'n8n', label: 'n8n', url: 'http://YOUR_SERVER_IP:5678/healthz' }, { name: 'vaultwarden', label: 'Vaultwarden', url: 'http://YOUR_SERVER_IP:4743/alive' }, { name: 'openwebui', label: 'Open WebUI', url: 'http://YOUR_SERVER_IP:8088/health' }, { name: 'memos', label: 'Memos', url: 'http://YOUR_SERVER_IP:5230/healthz' }, { name: 'ff-api', label: 'FleetForge API', url: 'http://YOUR_SERVER_IP:8001/' }, { name: 'prometheus', label: 'Prometheus', url: 'http://YOUR_SERVER_IP:9090/-/healthy' }, { name: 'glances', label: 'Glances', url: 'http://YOUR_SERVER_IP:61208/api/4/uptime' }, ]; const SERVICE_NAMES = new Set(SERVICES.map((s) => s.name)); /** * Liest das Grafana-Lesetoken aus einer Datei (nicht aus dem Config-Text). * Die Datei muss uid 1000 und Modus 600 haben; liegt sie nicht vor oder ist * sie unzulaessig, liefert das Werkzeug eine klare Fehlermeldung statt eines * Zugriffsversuchs. */ function readGrafanaToken() { const p = process.env.GRAFANA_TOKEN_FILE; if (!p) return { error: 'GRAFANA_TOKEN_FILE ist nicht gesetzt.' }; let st; try { st = fs.statSync(p); } catch (e) { return { error: `Token-Datei nicht lesbar: ${p}` }; } if ((st.mode & 0o077) !== 0) return { error: `Token-Datei ist nicht restriktiv berechtigt (Modus ${st.mode & 0o777}).` }; if (st.uid !== 1000) return { error: `Token-Datei gehoert uid ${st.uid}, erwartet 1000.` }; try { const t = fs.readFileSync(p, 'utf8').trim(); if (!t) return { error: 'Token-Datei ist leer.' }; return { token: t }; } catch (e) { return { error: 'Token-Datei konnte nicht gelesen werden.' }; } } function fetchJson(url, token) { return new Promise((resolve) => { const started = Date.now(); const headers = token ? { Authorization: `Bearer ${token}` } : {}; const req = http.get(url, { timeout: TIMEOUT_MS, headers }, (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 = 'Antwort ist kein JSON'; } } resolve({ code: res.statusCode || 0, ms: Date.now() - started, parsed, parseError, body: 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' }); }); req.on('error', (e) => resolve({ code: 0, ms: Date.now() - started, parsed: null, parseError: String(e.message || e) })); }); } const TOOLS = [ { name: 'health_overview', description: 'Prueft alle registrierten Dienste auf ihren unauthentifizierten Health-Endpunkt und liefert Statuscode, Antwortzeit und geparste Antwort je Dienst. Rein lesend, keine Zugangsdaten.', inputSchema: { type: 'object', properties: { only_failing: { type: 'boolean', description: 'Nur Dienste zurueckgeben, die nicht antworten oder nicht ok sind.', }, }, additionalProperties: false, }, }, { name: 'service_detail', description: 'Liefert die vollstaendige Health-Antwort eines einzelnen Diensts. Der Dienst wird ueber einen festen Namen aus der Dienste-Liste gewaehlt, nicht ueber eine URL.', inputSchema: { type: 'object', properties: { service: { type: 'string', description: 'Dienstname, z.B. grafana, gitea, gotify, n8n, vaultwarden.', }, }, required: ['service'], additionalProperties: false, }, }, { name: 'prometheus_targets', description: 'Listet von Prometheus gescrapte Ziele (Targets) mit Zustand und Fehlern auf: sucht nach "down"/halb down und laufenden Jobs. Rein lesend, kein Login.', inputSchema: { type: 'object', properties: { only_problems: { type: 'boolean', description: 'Nur Ziele anzeigen, die down oder angekratzt sind.', }, }, additionalProperties: false, }, }, { name: 'grafana_overview', description: 'Liefert den lesenden Ueberblick ueber Grafana: Systemzustand, Dashboards, Datenquellen und Alert-Regeln. Nutzt ein Viewer-Token aus einer Datei; rein lesend, keine Schreibrechte.', inputSchema: { type: 'object', properties: { limit: { type: 'integer', description: 'Anzahl der Dashboards (1-50, Standard 15).' }, }, additionalProperties: false, }, }, { name: 'grafana_dashboard', description: 'Liefert die Metadaten eines einzelnen Grafana-Dashboards (Panels, Aktualisierung, Datasource-Bezuege) ueber seine UID. Lesend.', inputSchema: { type: 'object', properties: { uid: { type: 'string', description: 'Dashboard-UID, z.B. unraid-docker.' }, }, required: ['uid'], additionalProperties: false, }, }, ]; function fetchText(url) { return new Promise((resolve) => { const started = Date.now(); const req = http.get(url, { timeout: TIMEOUT_MS }, (res) => { let body = ''; let done = false; const finish = (extra) => { if (done) return; done = true; resolve({ code: res.statusCode || 0, ms: Date.now() - started, body: body.slice(0, MAX_CHARS), truncated: body.length > MAX_CHARS, ...extra, }); }; 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({ error: 'read error' })); }); req.on('timeout', () => { req.destroy(); resolve({ code: 0, ms: Date.now() - started, body: '', error: 'timeout' }); }); req.on('error', (e) => { resolve({ code: 0, ms: Date.now() - started, body: '', error: String(e.message || e) }); }); }); } function classify(svc, r) { if (r.error && r.code === 0) return 'down'; if (r.code >= 200 && r.code < 400) return 'ok'; return 'failing'; } function summarizeBody(body) { const t = body.trim(); if (!t) return ''; try { const j = JSON.parse(t); return JSON.stringify(j, null, 2); } catch (e) { return t.length > 500 ? t.slice(0, 500) + ' …' : t; } } async function healthOverview(args) { const results = await Promise.all( SERVICES.map(async (svc) => { const r = await fetchText(svc.url); const status = classify(svc, r); return { service: svc.name, label: svc.label, endpoint: svc.url, status, code: r.code, ms: r.ms, error: r.error || null, detail: status === 'ok' ? summarizeBody(r.body) : summarizeBody(r.body || r.error || ''), }; }) ); const rows = args && args.only_failing ? results.filter((r) => r.status !== 'ok') : results; const counts = results.reduce((a, r) => ((a[r.status] = (a[r.status] || 0) + 1), a), {}); const lines = [ '## Service-Health (unauthentifizierte Endpunkte)', '', `ok=${counts.ok || 0} failing=${counts.failing || 0} down=${counts.down || 0} gesamt=${results.length}`, '', '| Dienst | Status | Code | ms |', '|---|---|---|---|', ]; for (const r of rows) lines.push(`| ${r.label} | ${r.status} | ${r.code} | ${r.ms} |`); const detailed = rows.filter((r) => r.status !== 'ok'); if (detailed.length) { lines.push('', '### Details der Stoerungen'); for (const r of detailed) { lines.push(`- **${r.label}** (${r.code || 'kein Status'}): ${r.detail || r.error || 'keine Antwort'}`); } } return lines.join('\n'); } async function serviceDetail(args) { const name = String((args && args.service) || '').trim().toLowerCase(); if (!SERVICE_NAMES.has(name)) { return { error: true, text: `Unbekannter Dienst "${name}". Erlaubt sind ausschliesslich feste Namen, keine URLs: ` + SERVICES.map((s) => s.name).join(', '), }; } const svc = SERVICES.find((s) => s.name === name); const r = await fetchText(svc.url); const status = classify(svc, r); const text = [ `## ${svc.label}`, '', `- Endpunkt: ${svc.url}`, `- Status: **${status}** (HTTP ${r.code || 'kein'}, ${r.ms} ms)`, r.error ? `- Fehler: ${r.error}` : null, '', '### Antwort', '```', summarizeBody(r.body || r.error || ''), '```', ] .filter((l) => l !== null) .join('\n'); return { error: status !== 'ok', text }; } const GRAFANA_BASE = process.env.GRAFANA_URL || 'http://YOUR_SERVER_IP:3300'; const PROM_BASE = process.env.PROM_URL || 'http://YOUR_SERVER_IP:9090'; async function prometheusTargets(args) { const r = await fetchJson(`${PROM_BASE}/api/v1/targets`); if (r.parseError) return { error: true, text: `Prometheus antwortet nicht: ${r.parseError}` }; const active = (r.parsed && r.parsed.data && r.parsed.data.activeTargets) || []; const counts = active.reduce((a, t) => ((a[t.health] = (a[t.health] || 0) + 1), a), {}); const problems = active.filter((t) => t.health !== 'up'); const rows = args && args.only_problems ? problems : active; const lines = [ '## Prometheus Target-Zustaende', '', `up=${counts.up || 0} down=${counts.down || 0} unknown=${counts.unknown || 0} gesamt=${active.length}`, '', '| Zustand | Job | Instanz | Dauer down | Zuletzt gescrapt |', '|---|---|---|---|---|', ]; rows.forEach((t) => { const d = t.lastScrapeDuration ? Math.round(t.lastScrapeDuration * 1000) + ' ms' : '-'; const scrape = t.lastScrape ? t.lastScrape.replace('T', ' ').slice(0, 19) + 'Z' : '-'; lines.push( `| ${t.health} | ${t.labels && t.labels.job ? t.labels.job : '-'} | ${t.scrapeUrl} | ${d} | ${scrape} |` ); }); for (const t of problems.slice(0, 15)) { const err = (t.lastError || '').replace(/"/g, "'").slice(0, 300); if (err) lines.push(`- **${t.labels && t.labels.job}**: ${err}`); } return lines.join('\n'); } async function grafanaOverview(args) { const auth = readGrafanaToken(); if (auth.error) return { error: true, text: `Grafana-Lesetoken nicht verfuegbar: ${auth.error}` }; const limit = Math.min(50, Math.max(1, Number((args && args.limit) || 15))); const [health, dash, ds, rules, alerts] = await Promise.all([ fetchJson(`${GRAFANA_BASE}/api/health`), fetchJson(`${GRAFANA_BASE}/api/search?type=dash-db&limit=${limit}`, auth.token), fetchJson(`${GRAFANA_BASE}/api/datasources`, auth.token), fetchJson(`${GRAFANA_BASE}/api/prometheus/grafana/api/v1/rules`, auth.token), fetchJson(`${GRAFANA_BASE}/api/alertmanager/grafana/api/v2/alerts?active=true&silenced=false`, auth.token), ]); const bad = []; if (health.code !== 200) bad.push(`health HTTP ${health.code}`); if (dash.code !== 200) bad.push(`dashboards HTTP ${dash.code}`); if (ds.code !== 200) bad.push(`datasources HTTP ${ds.code}`); const lines = ['## Grafana (Viewer, lesend)', '']; if (health.parsed) { lines.push(`- Version: ${health.parsed.version || '?'} | Datenbank: ${health.parsed.database || '?'}`); } else { lines.push(`- Health: HTTP ${health.code} (${health.parseError || 'keine JSON-Antwort'})`); } lines.push(`- Berechtigung: Viewer, Token aus Datei, keine Schreibrechte`); const items = Array.isArray(dash.parsed) ? dash.parsed : []; lines.push('', `### Dashboards (${items.length} von max. ${limit})`); for (const d of items) { lines.push(`- \`${d.uid}\` ${d.title} (${d.folderTitle || 'Root'}${d.updatedAt ? ', ' + d.updatedAt.slice(0, 10) : ''})`); } if (dash.code !== 200) lines.push(`- Dashboards konnten nicht gelesen werden: HTTP ${dash.code}`); const dss = Array.isArray(ds.parsed) ? ds.parsed : []; lines.push('', `### Datenquellen (${dss.length})`); for (const d of dss) lines.push(`- ${d.name} (${d.type})${d.readOnly ? ', schreibgeschuetzt' : ''}`); if (rules.code === 200 && rules.parsed && rules.parsed.data) { const groups = rules.parsed.data.groups || []; let ruleCount = 0; for (const g of groups) ruleCount += (g.rules || []).length; lines.push('', `### Alert-Regeln: ${ruleCount} Regeln in ${groups.length} Gruppen`); for (const g of groups.slice(0, 8)) { const firing = (g.rules || []).filter((r) => r.state === 'firing' || (r.health && r.health !== 'ok')); if (firing.length) lines.push(`- Gruppe ${g.name}: ${firing.length} Warnregel(n) nicht ok`); } } else if (rules.code === 403) { lines.push('', '### Alert-Regeln: Zugriff verweigert (403)'); } if (alerts.code === 200 && Array.isArray(alerts.parsed)) { lines.push('', `### Aktive Alerts: ${alerts.parsed.length}`); for (const a of alerts.parsed.slice(0, 10)) { const labels = (a.labels && (a.labels.alertname || a.labels.job)) || ''; lines.push(`- [${a.status && a.status.state}] ${labels || a.alertname || 'unbekannt'}`); } } else if (alerts.code === 403) { lines.push('', '### Aktive Alerts: Zugriff verweigert (403)'); } if (bad.length) lines.push('', `**Hinweis:** ${bad.join(', ')}`); return { error: bad.length > 0, text: lines.join('\n') }; } async function grafanaDashboard(args) { const auth = readGrafanaToken(); if (auth.error) return { error: true, text: `Grafana-Lesetoken nicht verfuegbar: ${auth.error}` }; const uid = String((args && args.uid) || '').trim(); if (!/^[A-Za-z0-9._-]{1,64}$/.test(uid)) { return { error: true, text: `UID "${uid}" ist nicht zulaessig (erlaubt: Buchstaben, Ziffern, . _ - , max. 64).` }; } const r = await fetchJson(`${GRAFANA_BASE}/api/dashboards/uid/${uid}`, auth.token); if (r.code !== 200 || !r.parsed || !r.parsed.dashboard) { return { error: true, text: `Dashboard \`${uid}\` nicht lesbar: HTTP ${r.code}${r.parseError ? ' (' + r.parseError + ')' : ''}` }; } const d = r.parsed.dashboard; const panels = Array.isArray(d.panels) ? d.panels : []; const lines = [ `## ${d.title}`, '', `- UID: \`${uid}\` | Version: ${d.version} | aktualisiert: ${r.parsed.meta && r.parsed.meta.updated ? r.parsed.meta.updated : 'unbekannt'}`, `- Ordner: ${(r.parsed.meta && r.parsed.meta.folderTitle) || 'Root'}`, `- Beschreibung: ${d.description || 'keine'}`, `- Panels: ${panels.length}`, '', '### Panels', ]; for (const p of panels) { if (p.type === 'row' && !(p.panels && p.panels.length)) { lines.push(`- **Zeile: ${p.title || 'ohne Titel'}**`); continue; } const targets = Array.isArray(p.targets) ? p.targets : []; const expr = targets.map((t) => (t.expr || '').trim()).filter(Boolean); lines.push(`- ${p.title || p.type} (${p.type})${expr.length ? ' — ' + expr[0].slice(0, 140) : ''}`); } 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: 'service-health', 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 run = async () => { if (name === 'health_overview') return { content: [{ type: 'text', text: await healthOverview(args) }] }; if (name === 'service_detail') { const r = await serviceDetail(args); return { content: [{ type: 'text', text: r.text }], isError: Boolean(r.error) }; } if (name === 'prometheus_targets') { return { content: [{ type: 'text', text: await prometheusTargets(args) }] }; } if (name === 'grafana_overview') { const r = await grafanaOverview(args); return { content: [{ type: 'text', text: r.text }], isError: Boolean(r.error) }; } if (name === 'grafana_dashboard') { const r = await grafanaDashboard(args); return { content: [{ type: 'text', text: r.text }], isError: Boolean(r.error) }; } return { content: [{ type: 'text', text: `Unbekanntes Werkzeug: ${name}` }], isError: true }; }; 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}`); }