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

+593
View File
@@ -0,0 +1,593 @@
#!/usr/bin/env node
/**
* bitwarden — MCP-Server fuer das Vaultwarden-Passworttresor (https://bitwarden.your-domain.com).
*
* Zweck: Jarvis liest, sucht und verwaltet Passwort-Eintraege des KONTOS
* [email protected] (SSO-Login, Session/Unlock ueber config/mcp/.bw-masterpass).
*
* Sicherheitsmodell:
* - Jeder bw-Befehl laeuft mit einem expliziten Session-Schluessel (BW_SESSION), den
* der Server genau EINMAL nach Prozessstart oder nach einem Lock via
* "bw unlock --raw --passwordfile <BW_MP_FILE>" holt. Der Schluessel wird nur im
* Speicher gehalten und nie geloggt/persistiert.
* - bw_list_items/bw_search: KEINE Passwoerter/TOTP (nur Metadaten + Username/URI).
* - bw_get_item: vollstaendiger Eintrag inkl. Passwort nur auf Anforderung
* (include_secrets, Standard aus).
* - create/update/delete: beabsichtigte Schreibzugriffe. Die Werte fuer den Server
* werden als BASE64-JSON auf stdin uebergeben (bw 2025.x decodiert Base64); der
* Server konstruiert das JSON selbst, nie aus Freitext-Befehlen.
* - Passwörter und Session-Schluessel werden nie protokolliert; Ausgaben auf
* MAX_CHARS begrenzt, hartes Timeout.
*/
'use strict';
const { execFileSync } = require('child_process');
const fs = require('fs');
const TIMEOUT_MS = 20000;
const MAX_CHARS = 50000;
const MAX_ITEMS = 500;
const DATA_DIR = process.env.BW_DATA_DIR || '/home/node/.openclaw/bw-data';
const CLI = process.env.BW_CLI || '/home/node/.openclaw/bw-cli/node_modules/@bitwarden/cli/build/bw.js';
const MP_FILE = process.env.BW_MP_FILE || '/home/node/.openclaw/mcp/.bw-masterpass';
const TYPE_NAMES = { 1: 'login', 2: 'secureNote', 3: 'card', 4: 'identity', 5: 'sshKey', 6: 'masterPassword' };
let sessionKey = null;
function bwEnv(withSession) {
const env = { ...process.env, BITWARDENCLI_APPDATA_DIR: DATA_DIR };
if (withSession && sessionKey) env.BW_SESSION = sessionKey;
return env;
}
function runBw(args, input, withSession) {
return execFileSync(CLI, args, {
env: bwEnv(withSession !== false),
input,
timeout: TIMEOUT_MS,
maxBuffer: 8 * 1024 * 1024,
stdio: ['pipe', 'pipe', 'pipe'],
}).toString('utf8');
}
function b64(s) {
return Buffer.from(String(s), 'utf8').toString('base64');
}
function readMasterpass() {
let st;
try {
st = fs.statSync(MP_FILE);
} catch (e) {
return { error: `Master-Passwort-Datei nicht lesbar: ${MP_FILE}` };
}
if ((st.mode & 0o077) !== 0) return { error: `Master-Passwort-Datei nicht restriktiv berechtigt (Modus ${st.mode & 0o777}).` };
if (st.uid !== 1000) return { error: `Master-Passwort-Datei gehoert uid ${st.uid}, erwartet 1000.` };
try {
const t = fs.readFileSync(MP_FILE, 'utf8').trim();
if (!t) return { error: 'Master-Passwort-Datei ist leer.' };
return { password: t };
} catch (e) {
return { error: 'Master-Passwort-Datei konnte nicht gelesen werden.' };
}
}
function statusNow() {
try {
const raw = runBw(['status']);
return JSON.parse(raw);
} catch (e) {
return { status: sessionKey ? 'locked' : 'unreadable', error: String(e.message || e) };
}
}
function ensureSession() {
if (sessionKey) {
const s = statusNow();
if (s.status === 'unlocked') return { ok: true };
sessionKey = null;
}
const mp = readMasterpass();
if (mp.error) return { error: `Entsperren nicht moeglich: ${mp.error}` };
let key;
try {
key = runBw(['unlock', '--raw', '--passwordfile', MP_FILE], undefined, false).trim();
} catch (e) {
return { error: `bw unlock fehlgeschlagen: ${String(e.stderr || e.message || e)}` };
}
if (!key) return { error: 'bw unlock gab keinen Session-Schluessel zurueck.' };
sessionKey = key;
const s = statusNow();
if (s.status !== 'unlocked') {
sessionKey = null;
return { error: `bw ist nach unlock nicht entsperrt (status=${s.status}).` };
}
try { runBw(['sync']); } catch (e) { /* Sync-Fehler sind nicht kritisch */ }
return { ok: true };
}
function shortId(id) {
return String(id || '').slice(0, 8);
}
function typeName(t) {
return TYPE_NAMES[t] || String(t || '?');
}
function relTime(iso) {
if (!iso) return '-';
return String(iso).replace('T', ' ').replace('Z', 'U').slice(0, 16);
}
function sanitizeItem(i) {
const login = i.login || {};
const uris = Array.isArray(login.uris) ? login.uris.map((u) => u.uri).filter(Boolean) : [];
return {
id: i.id,
name: i.name || '(ohne Namen)',
type: typeName(i.type),
username: login.username || '',
uris,
favorite: Boolean(i.favorite),
folderId: i.folderId || null,
revisionDate: i.revisionDate || null,
};
}
function itemsJson() {
const raw = runBw(['list', 'items']);
const arr = JSON.parse(raw);
return Array.isArray(arr) ? arr.filter((x) => x && x.id) : [];
}
function buildItemPayload(args) {
const type = args.type || 'login';
const num = Number(Object.keys(TYPE_NAMES).find((k) => TYPE_NAMES[k] === type));
const p = { type: num || 1, name: String(args.name || ''), notes: args.notes || null, favorite: Boolean(args.favorite), folderId: args.folder_id || null };
if (type === 'login') {
p.login = {
username: args.username || '',
password: args.password || '',
uris: args.uris && args.uris.length ? args.uris.map((u) => ({ uri: u })) : [],
};
} else if (type === 'secureNote') {
p.secureNote = { type: 0 };
}
return p;
}
const TOOLS = [
{
name: 'bw_status',
description:
'Zeigt den Zustand des Bitwarden/Vaultwarden-Logins: verbundener Server, Konto (E-Mail), Status unlocked/locked, Synchronisationszeit. Lesend.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'bw_list_items',
description:
'Listet Vault-Eintraege aus dem lokalen Cache (Standard 50, max. 500). Nur Metadaten: Name, Typ, Benutzername, URIs, Favorit. KEINE Passwoerter. Optional nach Typ gefiltert. Lesend.',
inputSchema: {
type: 'object',
properties: {
type: { type: 'string', enum: ['login', 'secureNote', 'card', 'identity'], description: 'Nur Eintraege dieses Typs.' },
limit: { type: 'integer', description: 'Anzahl (1-500, Standard 50).' },
},
additionalProperties: false,
},
},
{
name: 'bw_search',
description:
'Durchsucht Eintraege nach Text im Namen, Benutzernamen oder einer URI (Gross-/Kleinschreibung egal). Ergebnis als Metadaten-Tabelle ohne Passwoerter. Lesend.',
inputSchema: {
type: 'object',
properties: {
text: { type: 'string', description: 'Suchtext (Teilstring).' },
limit: { type: 'integer', description: 'Max. Treffer (1-100, Standard 20).' },
},
required: ['text'],
additionalProperties: false,
},
},
{
name: 'bw_get_item',
description:
'Liefert einen einzelnen Vault-Eintrag vollstaendig: Typ, Name, Notiz, Benutzername, URIs, benutzerdefinierte Felder. Mit include_secrets=true (Standard) zusaetzlich das Passwort bzw. TOTP-Secret. Lesend.',
inputSchema: {
type: 'object',
properties: {
id: { type: 'string', description: 'Eintrags-ID (ganz oder erste 8 Zeichen, z.B. "a9d9d037").' },
include_secrets: { type: 'boolean', description: 'Passwort/TOTP mitliefern (Standard true).' },
},
required: ['id'],
additionalProperties: false,
},
},
{
name: 'bw_create_item',
description:
'Legt einen neuen Vault-Eintrag an (Typ login oder secureNote). Bei login mit username/password und optional uris. Liefert die neue Eintrags-ID. SCHREIBEND.',
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Anzeigename, z.B. "Externer Dienst".' },
type: { type: 'string', enum: ['login', 'secureNote'], description: 'Eintragstyp (Standard login).' },
username: { type: 'string', description: 'Bei login: Benutzername.' },
password: { type: 'string', description: 'Bei login: Passwort (bw_generate zum Erzeugen).' },
uris: { type: 'array', items: { type: 'string' }, description: 'Bei login: Webadresse(n).' },
folder_id: { type: 'string', description: 'Ordner-ID (optional; ohne wird "No Folder" verwendet).' },
notes: { type: 'string', description: 'Notiz (optional).' },
favorite: { type: 'boolean', description: 'Favorit (Standard false).' },
},
required: ['name'],
additionalProperties: false,
},
},
{
name: 'bw_update_item',
description:
'Aendert einen vorhandenen Vault-Eintrag. uebergib id plus die zu aendernden Felder; nicht genannte bleiben unveraendert. SCHREIBEND.',
inputSchema: {
type: 'object',
properties: {
id: { type: 'string', description: 'Eintrags-ID (ganz oder erste 8 Zeichen).' },
name: { type: 'string', description: 'Neuer Anzeigename.' },
type: { type: 'string', enum: ['login', 'secureNote'], description: 'Eintragstyp.' },
username: { type: 'string', description: 'Neuer Benutzername.' },
password: { type: 'string', description: 'Neues Passwort.' },
uris: { type: 'array', items: { type: 'string' }, description: 'Neue URI-Liste.' },
folder_id: { type: 'string', description: 'Neue Ordner-ID (leerer String = kein Ordner).' },
notes: { type: 'string', description: 'Neue Notiz.' },
favorite: { type: 'boolean', description: 'Favorit-Status.' },
},
required: ['id'],
additionalProperties: false,
},
},
{
name: 'bw_delete_item',
description:
'Loescht einen Vault-Eintrag unwiderruflich. VORHER mit bw_get_item bestaetigen, dass die richtige ID gewaehlt wurde. SCHREIBEND.',
inputSchema: {
type: 'object',
properties: {
id: { type: 'string', description: 'Eintrags-ID (ganz oder erste 8 Zeichen).' },
},
required: ['id'],
additionalProperties: false,
},
},
{
name: 'bw_generate',
description:
'Erzeugt ein starkes Zufallspasswort ueber bw generate (Laenge, Klein-/Gross-/Ziffern/Sonderzeichen, optional ohne mehrdeutige Zeichen; oder als Passphrase). Speichert NICHT in den Tresor. Lesend.',
inputSchema: {
type: 'object',
properties: {
length: { type: 'integer', description: 'Laenge (5-128, Standard 24).' },
upper: { type: 'boolean', description: 'Grossbuchstaben (Standard true).' },
lower: { type: 'boolean', description: 'Kleinbuchstaben (Standard true).' },
number: { type: 'boolean', description: 'Ziffern (Standard true).' },
special: { type: 'boolean', description: 'Sonderzeichen (Standard true).' },
ambiguous: { type: 'boolean', description: 'Mehrdeutige Zeichen (0/o/l/I/1) vermeiden (Standard false).' },
passphrase: { type: 'boolean', description: 'Stattdessen Passphrase erzeugen (Standard false).' },
},
additionalProperties: false,
},
},
];
async function bwStatus() {
// Status is also the user's access check: refresh the in-memory session before
// reporting locked, otherwise a fresh MCP process falsely looks disconnected.
const session = ensureSession();
if (session.error) return { error: true, text: session.error };
const s = statusNow();
if (s.status === 'unreadable') return { error: true, text: `bw status nicht lesbar: ${s.error || ''}` };
const lines = [
'## Bitwarden/Vaultwarden',
'',
`- Server: ${s.serverUrl || '-'}`,
`- Konto: ${s.userEmail || '-'} ${s.userId ? '(' + shortId(s.userId) + ')' : ''}`,
`- Status: **${s.status === 'unlocked' ? 'entsperrt' : s.status}**`,
`- Letzte Sync: ${relTime(s.lastSync)}`,
];
return { error: false, text: lines.join('\n') };
}
async function listItems(args) {
const u = ensureSession();
if (u.error) return { error: true, text: u.error };
let items;
try {
items = itemsJson();
} catch (e) {
return { error: true, text: `Vault nicht lesbar: ${String(e.stderr || e.message || e)}` };
}
const type = args && args.type;
if (type) {
const num = Object.keys(TYPE_NAMES).find((k) => TYPE_NAMES[k] === type);
items = items.filter((i) => i.type === (num ? Number(num) : type));
}
items.sort((a, b) => String(a.name || '').localeCompare(String(b.name || '')));
const limit = Math.min(500, Math.max(1, Number((args && args.limit) || 50)));
const shown = items.slice(0, limit);
const lines = [
'## Vault-Eintraege',
'',
`Gesamt: ${items.length}${items.length > shown.length ? `, angezeigt: ${shown.length}` : ''}`,
'',
'| ID | Typ | Name | Benutzer | URI | Festgelegt |',
'|---|---|---|---|---|---|',
];
for (const s of shown.map(sanitizeItem)) {
lines.push(`| ${shortId(s.id)} | ${s.type} | ${String(s.name).replace(/\|/g, '\\|')} | ${s.username || '-'} | ${(s.uris[0] || '-').replace(/\|/g, '\\|')} | ${s.favorite ? 'ja' : ''} |`);
}
lines.push('', `Passwoerter liefert bw_get_item mit der jeweiligen ID (${shortId(shown[0] ? shown[0].id : '')}...).`);
return { error: false, text: lines.join('\n') };
}
async function searchItems(args) {
const u = ensureSession();
if (u.error) return { error: true, text: u.error };
const text = String((args && args.text) || '').trim().toLowerCase();
if (!text) return { error: true, text: 'Suchtext fehlt.' };
let items;
try {
items = itemsJson();
} catch (e) {
return { error: true, text: `Vault nicht lesbar: ${String(e.stderr || e.message || e)}` };
}
const hits = items
.map(sanitizeItem)
.filter((s) => {
const hay = [s.name, s.username, ...s.uris].join(' ').toLowerCase();
return hay.indexOf(text) >= 0;
});
hits.sort((a, b) => String(a.name).localeCompare(String(b.name)));
const limit = Math.min(100, Math.max(1, Number((args && args.limit) || 20)));
const shown = hits.slice(0, limit);
const lines = [
'## Suche: ' + (args.text) + '',
'',
`Gefunden: ${hits.length}${hits.length > shown.length ? `, angezeigt: ${shown.length}` : ''}`,
'',
'| ID | Typ | Name | Benutzer | URI |',
'|---|---|---|---|---|',
];
for (const s of shown) {
lines.push(`| ${shortId(s.id)} | ${s.type} | ${String(s.name).replace(/\|/g, '\\|')} | ${s.username || '-'} | ${(s.uris[0] || '-').replace(/\|/g, '\\|')} |`);
}
if (!hits.length) lines.push('| (keine Treffer) |');
return { error: false, text: lines.join('\n') };
}
async function getItem(args) {
const u = ensureSession();
if (u.error) return { error: true, text: u.error };
const id = String((args && args.id) || '').trim();
if (!id) return { error: true, text: 'Eintrags-ID fehlt.' };
const wantSecrets = (args && args.include_secrets) !== false;
let item;
try {
const raw = runBw(['get', 'item', id]);
item = JSON.parse(raw);
} catch (e) {
return { error: true, text: `Eintrag ${id} nicht lesbar: ${String(e.stderr || e.message || e)}` };
}
if (!item || item.error) return { error: true, text: `Eintrag ${id} nicht gefunden.` };
const login = item.login || {};
const lines = [
`## Eintrag ${item.name || '(ohne Namen)'}`,
'',
`- ID: ${item.id}`,
`- Typ: ${typeName(item.type)}`,
`- Ordner: ${item.folderId || '(kein)'}`,
`- Favorit: ${item.favorite ? 'ja' : 'nein'}`,
`- Erstellt: ${relTime(item.creationDate)}`,
`- Geaendert: ${relTime(item.revisionDate)}`,
];
if (login.username) lines.push(`- Benutzer: ${login.username}`);
const uris = Array.isArray(login.uris) ? login.uris.map((x) => x.uri).filter(Boolean) : [];
if (uris.length) lines.push('- URIs: ' + uris.join(', '));
if (wantSecrets) {
if (login.password) lines.push(`- **Passwort: \`${login.password}\`**`);
if (login.totp) lines.push(`- TOTP: ${login.totp}`);
}
if (item.notes) lines.push('', '- Notiz:', '', String(item.notes).slice(0, MAX_CHARS));
const fields = Array.isArray(item.fields) ? item.fields.filter((f) => f && f.name) : [];
if (fields.length) {
lines.push('', '### Benutzerdefinierte Felder', '');
for (const f of fields) {
const val = wantSecrets ? f.value : (f.type === 1 ? '**verborgen**' : f.value);
lines.push(`- ${f.name}: ${val}`);
}
}
return { error: false, text: lines.join('\n') };
}
async function createItem(args) {
const u = ensureSession();
if (u.error) return { error: true, text: u.error };
const name = String((args && args.name) || '').trim();
if (!name) return { error: true, text: 'Name fehlt.' };
const payload = buildItemPayload(args);
let created;
try {
const raw = runBw(['create', 'item'], b64(JSON.stringify(payload)));
created = JSON.parse(raw);
} catch (e) {
return { error: true, text: `Anlegen fehlgeschlagen: ${String(e.stderr || e.message || e)}` };
}
return {
error: false,
text: `## Angelegt: ${created.name || name}\n\n- ID: ${created.id}\n- Typ: ${typeName(created.type)}\n- Benutzer: ${(created.login || {}).username || '-'}\n- Ordner: ${created.folderId || '(kein)'}`,
};
}
async function updateItem(args) {
const u = ensureSession();
if (u.error) return { error: true, text: u.error };
const id = String((args && args.id) || '').trim();
if (!id) return { error: true, text: 'Eintrags-ID fehlt.' };
let cur;
try {
cur = JSON.parse(runBw(['get', 'item', id]));
} catch (e) {
return { error: true, text: `Eintrag ${id} nicht lesbar: ${String(e.stderr || e.message || e)}` };
}
if (!cur || cur.error) return { error: true, text: `Eintrag ${id} nicht gefunden.` };
if (args.name !== undefined) cur.name = String(args.name);
if (args.notes !== undefined) cur.notes = args.notes || null;
if (args.favorite !== undefined) cur.favorite = Boolean(args.favorite);
if (args.folder_id !== undefined) cur.folderId = args.folder_id ? String(args.folder_id) : null;
const login = cur.login || {};
if (args.username !== undefined) login.username = String(args.username);
if (args.password !== undefined) login.password = String(args.password);
if (args.uris !== undefined) login.uris = args.uris.length ? args.uris.map((u) => ({ uri: u })) : [];
if (cur.type === 1 && Object.keys(login).length) cur.login = login;
let updated;
try {
const raw = runBw(['edit', 'item', id], b64(JSON.stringify(cur)));
updated = JSON.parse(raw);
} catch (e) {
return { error: true, text: `Aendern fehlgeschlagen: ${String(e.stderr || e.message || e)}` };
}
return {
error: false,
text: `## Geaendert: ${updated.name || cur.name}\n\n- ID: ${updated.id}\n- Benutzer: ${(updated.login || {}).username || '-'}\n- Revision: ${relTime(updated.revisionDate)}`,
};
}
async function deleteItem(args) {
const u = ensureSession();
if (u.error) return { error: true, text: u.error };
const id = String((args && args.id) || '').trim();
if (!id) return { error: true, text: 'Eintrags-ID fehlt.' };
let name = '-';
try {
const raw = runBw(['get', 'item', id]);
const got = JSON.parse(raw);
if (got && got.name) name = got.name;
} catch (e) { /* id existiert evtl. nicht */ }
try {
runBw(['delete', 'item', id]);
} catch (e) {
return { error: true, text: `Loeschen fehlgeschlagen: ${String(e.stderr || e.message || e)}` };
}
return { error: false, text: `## Geloescht: ${name}\n\n- ID: ${id}` };
}
async function generate(args) {
const u = ensureSession();
if (u.error) return { error: true, text: u.error };
const args2 = [];
if (args && args.passphrase) {
args2.push('--passphrase');
args2.push('--words', String(Math.min(64, Math.max(3, Number((args && args.length) || 5)))));
} else {
const len = Math.min(128, Math.max(5, Number((args && args.length) || 24)));
args2.push('--length', String(len));
if ((args && args.upper) !== false) args2.push('--uppercase');
if ((args && args.lower) !== false) args2.push('--lowercase');
if ((args && args.number) !== false) args2.push('--number');
if ((args && args.special) !== false) args2.push('--special');
if (args && args.ambiguous) args2.push('--ambiguous');
}
let pw;
try {
pw = runBw(['generate', ...args2]).trim();
} catch (e) {
return { error: true, text: `Erzeugen fehlgeschlagen: ${String(e.stderr || e.message || e)}` };
}
if (!pw) return { error: true, text: 'bw generate gab nichts zurueck.' };
return { error: false, text: `## Generiertes Passwort\n\n\`${pw}\`` };
}
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: 'bitwarden', version: '1.2.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: /^bw_(status|list_items|search|get_item|generate)$/.test(name),
destructiveHint: name === 'bw_delete_item',
idempotentHint: !/delete/.test(name),
openWorldHint: true,
},
})),
});
return;
}
if (method === 'tools/call') {
const name = params && params.name;
const args = (params && params.arguments) || {};
const dispatch = {
bw_status: () => bwStatus(),
bw_list_items: () => listItems(args),
bw_search: () => searchItems(args),
bw_get_item: () => getItem(args),
bw_create_item: () => createItem(args),
bw_update_item: () => updateItem(args),
bw_delete_item: () => deleteItem(args),
bw_generate: () => generate(args),
};
const fn = dispatch[name];
if (!fn) {
reply(id, { content: [{ type: 'text', text: `Unbekanntes oder nicht freigegebenes Werkzeug: ${name}` }], isError: true });
return;
}
fn()
.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');
}
+333
View File
@@ -0,0 +1,333 @@
#!/usr/bin/env node
/**
* cat — MCP-Server fuer Jarvis: Katzen-Erkennung und Enrollment.
*
* Der Server ist ein duenner Client gegen den cat-service (YOLO-Detektor +
* DINOv2-Embeddings, CPU):
* CAT_URL Basis-URL des Dienstes (Standard http://cat-service:8080).
*
* Zusaetzlich kann er selbst ein Standbild von Home-Assistant-Kameras holen
* (HA_URL + HA_TOKEN_FILE) und dann direkt an den cat-service schicken
* (cat_recognize_camera / cat_enroll_camera).
*
* Bilder koennen als Dateipfad (image_path, z.B. aus camera_snapshot) ODER als
* Base64 (image_base64) uebergeben werden.
*/
'use strict';
const fs = require('fs');
const CAT_URL = (process.env.CAT_URL || 'http://cat-service:8080').replace(/\/+$/, '');
const CAT_TIMEOUT_MS = Number(process.env.CAT_TIMEOUT_MS || 180000);
const HA_URL = (process.env.HA_URL || 'http://YOUR_SERVER_IP:8123').replace(/\/+$/, '');
const HA_TOKEN_FILE = process.env.HA_TOKEN_FILE || '/home/node/.openclaw/mcp/.ha-token';
function readHaToken() {
try {
const t = fs.readFileSync(HA_TOKEN_FILE, 'utf8').trim();
if (t) return t;
} catch (e) {}
return (process.env.HA_TOKEN || '').trim();
}
async function catFetch(pathname, opts, timeoutMs) {
return await fetch(CAT_URL + pathname, {
...(opts || {}),
headers: { 'Content-Type': 'application/json', ...((opts && opts.headers) || {}) },
signal: AbortSignal.timeout(timeoutMs || CAT_TIMEOUT_MS),
});
}
async function catJson(pathname, opts, timeoutMs) {
let res;
try {
res = await catFetch(pathname, opts, timeoutMs);
} catch (e) {
throw new Error(`cat-service nicht erreichbar (${CAT_URL}${pathname}): ${(e && e.message) || e}`);
}
const body = await res.text();
let data = null;
try {
data = body ? JSON.parse(body) : {};
} catch (e) {}
if (!res.ok) {
const detail = (data && (data.detail || data.message)) || body || '';
throw new Error(`cat-service ${pathname}: HTTP ${res.status}${detail ? ` - ${detail}` : ''}`);
}
return data || {};
}
async function haSnapshot(entity) {
const token = readHaToken();
if (!token) throw new Error(`HA-Zugriffstoken fehlt (${HA_TOKEN_FILE}).`);
const res = await fetch(HA_URL + `/api/camera_proxy/${encodeURIComponent(entity)}`, {
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
signal: AbortSignal.timeout(25000),
});
if (!res.ok) throw new Error(`HA camera_proxy ${entity}: HTTP ${res.status}`);
const buf = Buffer.from(await res.arrayBuffer());
if (buf.length < 200) throw new Error(`Kamera ${entity} liefert kein brauchbares Bild (${buf.length} B).`);
let friendly = entity;
try {
const st = await fetch(HA_URL + `/api/states/${encodeURIComponent(entity)}`, {
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
signal: AbortSignal.timeout(10000),
});
if (st.ok) {
const j = await st.json();
friendly = (j.attributes && j.attributes.friendly_name) || entity;
}
} catch (e) {}
return { buf, friendly };
}
function imageFromArgs(args) {
const p = args && args.image_path ? String(args.image_path).trim() : '';
const b64 = args && args.image_base64 ? String(args.image_base64).trim() : '';
if (p) {
if (!fs.existsSync(p)) throw new Error(`image_path existiert nicht: ${p}`);
const buf = fs.readFileSync(p);
return { b64: buf.toString('base64'), bytes: buf.length, source: `Datei ${p}` };
}
if (b64) {
const clean = b64.startsWith('data:') && b64.includes(',') ? b64.split(',', 1)[1] : b64;
return { b64: clean, bytes: Math.floor((clean.length * 3) / 4), source: 'image_base64' };
}
throw new Error('Bild fehlt: bitte image_path oder image_base64 angeben.');
}
function fmtRecognize(data, context) {
const lines = [`## Katzenerkennung${context ? `: ${context}` : ''}`, ''];
if (data.enrolled_cats === 0) {
lines.push('Es ist noch **keine Katze eingelernt**. Nutze `cat_enroll`/`cat_enroll_camera`, um eine zu speichern.');
return lines.join('\n');
}
if (!data.count) {
lines.push('Keine Katze im Bild erkannt.');
return lines.join('\n');
}
data.cats.forEach((f, i) => {
const label = f.matched ? `**${f.name}**` : 'unbekannt';
const sim = f.score === null || f.score === undefined ? 'nicht eingelernt' : `Ähnlichkeit ${f.score}`;
lines.push(`- Katze ${i + 1}: ${label} (${sim}, Detektor ${f.det_score})`);
});
const known = data.cats.filter((f) => f.matched).map((f) => f.name);
if (known.length) lines.push('', `Erkannt: ${[...new Set(known)].join(', ')}.`);
else lines.push('', 'Keine der eingelernten Katzen erkannt.');
if (Array.isArray(data.auto_learned) && data.auto_learned.length) {
lines.push('');
data.auto_learned.forEach((a) => {
lines.push(`Dazugelernt: **${a.name}** (Ähnlichkeit ${a.score}) → jetzt ${a.total} Trainingsbild(er).`);
});
}
return lines.join('\n');
}
// ---------------------------------------------------------------- tools
async function catList() {
const data = await catJson('/cats');
if (!data.count) return { text: '## Eingelernte Katzen\n\nNoch keine Katzen gespeichert. Mit `cat_enroll` (Name + Bild) oder `cat_enroll_camera` (Name + Kamera) anlegen.' };
const rows = data.cats.map((f) => `- **${f.name}** — ${f.samples} Bild(er), angelegt ${f.created || '?'}`).join('\n');
return { text: `## Eingelernte Katzen (${data.count})\n\n${rows}` };
}
async function catRecognize(args) {
const img = imageFromArgs(args);
const auto = args && args.auto_learn !== undefined ? Boolean(args.auto_learn) : false;
const data = await catJson('/recognize', { method: 'POST', body: JSON.stringify({ image: img.b64, threshold: args && args.threshold, auto_learn: auto }) });
const text = fmtRecognize(data, img.source);
return { text, content: [{ type: 'text', text }] };
}
async function catRecognizeCamera(args) {
const entity = String((args && args.entity_id) || '').trim();
if (!/^camera\.[\w-]+$/.test(entity)) return { isError: true, text: `cat_recognize_camera: ungueltige entity_id "${entity}".` };
const auto = args && args.auto_learn !== undefined ? Boolean(args.auto_learn) : true;
const snap = await haSnapshot(entity);
const data = await catJson('/recognize', { method: 'POST', body: JSON.stringify({ image: snap.buf.toString('base64'), threshold: args && args.threshold, auto_learn: auto }) });
const text = fmtRecognize(data, `Kamera ${snap.friendly}`);
const content = [{ type: 'text', text }];
if (args && args.as_image !== false) content.push({ type: 'image', data: snap.buf.toString('base64'), mimeType: 'image/jpeg' });
return { text, content };
}
async function catEnroll(args) {
const name = String((args && args.name) || '').trim();
if (!name) return { isError: true, text: 'cat_enroll: name fehlt.' };
const img = imageFromArgs(args);
const data = await catJson('/enroll', { method: 'POST', body: JSON.stringify({ name, image: img.b64 }) });
return { text: `## Katze gespeichert\n\n- Name: **${data.name}**\n- Gesamtbilder: ${data.total}\n- Detektor-Score: ${data.det_score}\n- Quelle: ${img.source}` };
}
async function catEnrollCamera(args) {
const name = String((args && args.name) || '').trim();
const entity = String((args && args.entity_id) || '').trim();
if (!name) return { isError: true, text: 'cat_enroll_camera: name fehlt.' };
if (!/^camera\.[\w-]+$/.test(entity)) return { isError: true, text: `cat_enroll_camera: ungueltige entity_id "${entity}".` };
const snap = await haSnapshot(entity);
const data = await catJson('/enroll', { method: 'POST', body: JSON.stringify({ name, image: snap.buf.toString('base64') }) });
return { text: `## Katze gespeichert\n\n- Name: **${data.name}**\n- Kamera: ${snap.friendly} (\`${entity}\`)\n- Gesamtbilder: ${data.total}\n- Detektor-Score: ${data.det_score}` };
}
async function catDelete(args) {
const name = String((args && args.name) || '').trim();
if (!name) return { isError: true, text: 'cat_delete: name fehlt.' };
await catJson(`/cats/${encodeURIComponent(name)}`, { method: 'DELETE' });
return { text: `Katze **${name}** entfernt.` };
}
const TOOLS = [
{
name: 'cat_list',
description: 'Listet alle eingelernten Katzen der Katzenerkennung mit Anzahl der Bilder.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'cat_recognize',
description:
'Erkennt Katzen in einem Bild und vergleicht sie mit den eingelernten Katzen. Quelle: image_path (Dateipfad, z.B. aus camera_snapshot) ODER image_base64.',
inputSchema: {
type: 'object',
properties: {
image_path: { type: 'string', description: 'Pfad zu einer Bilddatei im Container.' },
image_base64: { type: 'string', description: 'Bild als Base64 (JPEG/PNG).' },
threshold: { type: 'number', description: 'Optionale Kosinus-Schwelle (Standard aus dem Dienst, 0.55).' },
auto_learn: { type: 'boolean', description: 'Erkannte Katze automatisch als Trainingsbild speichern (Standard false).' },
},
additionalProperties: false,
},
},
{
name: 'cat_recognize_camera',
description:
'Holt ein Standbild einer Home-Assistant-Kamera und erkennt darauf die Katzen. Ideal fuer "Welche Katze ist auf der Kamera?".',
inputSchema: {
type: 'object',
properties: {
entity_id: { type: 'string', description: 'Kamera-Entity, z.B. "camera.lsc_smart_connect_1080p_ip_indoor_mini".' },
threshold: { type: 'number', description: 'Optionale Kosinus-Schwelle.' },
auto_learn: { type: 'boolean', description: 'Erkannte Katze automatisch als Trainingsbild speichern, wenn Aehnlichkeit >= 0.70 (Standard true).' },
as_image: { type: 'boolean', description: 'Standbild mitliefern (Standard true).' },
},
required: ['entity_id'],
additionalProperties: false,
},
},
{
name: 'cat_enroll',
description: 'Speichert eine neue Katze unter einem Namen. Quelle: image_path ODER image_base64. Erkennt die groesste Katze im Bild.',
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Name der Katze, z.B. "Mimi".' },
image_path: { type: 'string', description: 'Pfad zu einer Bilddatei im Container.' },
image_base64: { type: 'string', description: 'Bild als Base64.' },
},
required: ['name'],
additionalProperties: false,
},
},
{
name: 'cat_enroll_camera',
description:
'Speichert eine Katze ein, indem ein frisches Standbild einer Home-Assistant-Kamera aufgenommen wird. Wenn keine Kamera genannt ist, zuerst camera_list aufrufen.',
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Name der Katze.' },
entity_id: { type: 'string', description: 'Kamera-Entity, z.B. "camera.lsc_smart_connect_1080p_ip_indoor_mini".' },
},
required: ['name', 'entity_id'],
additionalProperties: false,
},
},
{
name: 'cat_delete',
description: 'Entfernt eine eingelernte Katze samt Bildern.',
inputSchema: {
type: 'object',
properties: { name: { type: 'string', description: 'Name der Katze.' } },
required: ['name'],
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: 'cat', 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: name === 'cat_list' || name === 'cat_recognize' || name === 'cat_recognize_camera', destructiveHint: name === 'cat_delete', idempotentHint: false, openWorldHint: true },
})),
});
return;
}
if (method === 'tools/call') {
const name = params && params.name;
const args = (params && params.arguments) || {};
const run = async () => {
if (name === 'cat_list') return await catList();
if (name === 'cat_recognize') return await catRecognize(args);
if (name === 'cat_recognize_camera') return await catRecognizeCamera(args);
if (name === 'cat_enroll') return await catEnroll(args);
if (name === 'cat_enroll_camera') return await catEnrollCamera(args);
if (name === 'cat_delete') return await catDelete(args);
return { isError: true, text: `Unbekanntes Werkzeug: ${name}` };
};
run()
.then((r) => {
const content = r.content || [{ type: 'text', text: r.text }];
reply(id, { content, isError: Boolean(r.isError) });
})
.catch((e) => reply(id, { content: [{ type: 'text', text: String((e && e.message) || e) }], isError: true }));
return;
}
if (id !== undefined) replyError(id, -32601, `Method not found: ${method}`);
}
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env node
"use strict";
const http = require("node:http");
const GLANCES_URL = process.env.GLANCES_URL || "http://YOUR_SERVER_IP:61208";
function request(pathStr) {
return new Promise((resolve) => {
const url = GLANCES_URL + pathStr;
const req = http.get(url, { timeout: 8000 }, (res) => {
let body = "";
res.on("data", (chunk) => { body += chunk; });
res.on("end", () => {
try {
resolve({ status: res.statusCode, data: JSON.parse(body) });
} catch {
resolve({ status: res.statusCode, raw: body });
}
});
});
req.on("error", (err) => resolve({ status: 0, error: err.message }));
req.on("timeout", () => { req.destroy(); resolve({ status: 0, error: "Timeout" }); });
});
}
function result(text, error = false) {
return { text: typeof text === "string" ? text : JSON.stringify(text, null, 2), error };
}
async function dockerContainerList() {
const res = await request("/api/4/containers");
if (res.status === 200 && Array.isArray(res.data)) {
const list = res.data.map(c => ({
name: c.name,
status: c.status,
image: c.image,
cpu_percent: c.cpu?.total !== undefined ? c.cpu.total : c.cpu_percent,
memory_usage_mb: c.memory?.usage ? Math.round(c.memory.usage / 1024 / 1024) : undefined,
uptime: c.uptime
}));
return result(list);
}
return result(`Container-Liste nicht verfuegbar (${res.status}): ${res.error || res.raw}`, true);
}
async function dockerContainerInspect(args) {
const target = String(args.name || "").trim().toLowerCase();
if (!target) return result("Container-Name erforderlich.", true);
const res = await request("/api/4/containers");
if (res.status === 200 && Array.isArray(res.data)) {
const found = res.data.find(c => String(c.name || "").toLowerCase() === target || String(c.id || "").startsWith(target));
if (found) return result(found);
return result(`Container "${target}" nicht gefunden.`, true);
}
return result(`Abfrage fehlgeschlagen: ${res.error || res.status}`, true);
}
async function dockerContainerHealth() {
const res = await request("/api/4/containers");
if (res.status === 200 && Array.isArray(res.data)) {
const total = res.data.length;
const running = res.data.filter(c => String(c.status || "").toLowerCase().includes("running") || c.status === "OK" || c.status === "running").length;
const stopped = total - running;
return result({
total_containers: total,
running_containers: running,
stopped_or_unhealthy: stopped,
status: stopped === 0 ? "ALL_HEALTHY" : "DEGRADED"
});
}
return result(`Health-Check fehlgeschlagen (${res.status}): ${res.error || res.raw}`, true);
}
const TOOLS = [
{ name: "docker_container_list", description: "Listet alle Docker-Container mit Status, CPU und RAM. Lesend.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
{ name: "docker_container_inspect", description: "Zeigt Detailstatistiken eines einzelnen Docker-Containers. Lesend.", inputSchema: { type: "object", properties: { name: { type: "string" } }, required: ["name"], additionalProperties: false } },
{ name: "docker_container_health", description: "Fuehrt ein zusammenfassendes Docker-Cluster-Health-Audit durch. Lesend.", inputSchema: { type: "object", properties: {}, additionalProperties: false } }
];
async function call(name, args) {
try {
if (name === "docker_container_list") return await dockerContainerList();
if (name === "docker_container_inspect") return await dockerContainerInspect(args);
if (name === "docker_container_health") return await dockerContainerHealth();
return result("Unbekanntes Werkzeug.", true);
} catch (err) {
return result(String(err.message || err), true);
}
}
function send(id, value) { process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result: value }) + "\n"); }
function reply(id, value) { send(id, { content: [{ type: "text", text: value.text }], isError: value.error }); }
let buffer = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
buffer += chunk;
let end;
while ((end = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, end).trim();
buffer = buffer.slice(end + 1);
if (!line) continue;
let message;
try { message = JSON.parse(line); } catch { continue; }
if (message.method === "initialize") send(message.id, { protocolVersion: message.params?.protocolVersion || "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "docker-control", version: "1.0.0" } });
else if (message.method === "tools/list") send(message.id, { tools: TOOLS });
else if (message.method === "tools/call") call(message.params?.name, message.params?.arguments || {}).then(res => reply(message.id, res));
}
});
+336
View File
@@ -0,0 +1,336 @@
#!/usr/bin/env node
/**
* face — MCP-Server fuer Jarvis: Gesichtserkennung und Enrollment.
*
* Der Server ist ein duenner Client gegen den face-service (InsightFace, CPU):
* FACE_URL Basis-URL des Dienstes (Standard http://face-service:8080).
*
* Zusaetzlich kann er selbst ein Standbild von Home-Assistant-Kameras holen
* (HA_URL + HA_TOKEN_FILE) und dann direkt an den face-service schicken
* (face_recognize_camera / face_enroll_camera) - so kann Jarvis eine Kamera
* auswaehlen, ohne dass ein UI-Bild vorliegt.
*
* Bilder koennen als Dateipfad (image_path, z.B. aus camera_snapshot) ODER als
* Base64 (image_base64) uebergeben werden.
*/
'use strict';
const fs = require('fs');
const path = require('path');
const FACE_URL = (process.env.FACE_URL || 'http://face-service:8080').replace(/\/+$/, '');
const FACE_TIMEOUT_MS = Number(process.env.FACE_TIMEOUT_MS || 120000);
const HA_URL = (process.env.HA_URL || 'http://YOUR_SERVER_IP:8123').replace(/\/+$/, '');
const HA_TOKEN_FILE = process.env.HA_TOKEN_FILE || '/home/node/.openclaw/mcp/.ha-token';
const SNAP_DIR = process.env.HA_SNAPSHOT_DIR || '/home/node/.openclaw/workspaces/jarvis/camera-snapshots';
function readHaToken() {
try {
const t = fs.readFileSync(HA_TOKEN_FILE, 'utf8').trim();
if (t) return t;
} catch (e) {}
return (process.env.HA_TOKEN || '').trim();
}
async function faceFetch(pathname, opts, timeoutMs) {
const res = await fetch(FACE_URL + pathname, {
...(opts || {}),
headers: { 'Content-Type': 'application/json', ...((opts && opts.headers) || {}) },
signal: AbortSignal.timeout(timeoutMs || FACE_TIMEOUT_MS),
});
return res;
}
async function faceJson(pathname, opts, timeoutMs) {
let res;
try {
res = await faceFetch(pathname, opts, timeoutMs);
} catch (e) {
throw new Error(`face-service nicht erreichbar (${FACE_URL}${pathname}): ${(e && e.message) || e}`);
}
const body = await res.text();
let data = null;
try {
data = body ? JSON.parse(body) : {};
} catch (e) {}
if (!res.ok) {
const detail = (data && (data.detail || data.message)) || body || '';
throw new Error(`face-service ${pathname}: HTTP ${res.status}${detail ? ` - ${detail}` : ''}`);
}
return data || {};
}
async function haSnapshot(entity) {
const token = readHaToken();
if (!token) throw new Error(`HA-Zugriffstoken fehlt (${HA_TOKEN_FILE}).`);
const res = await fetch(HA_URL + `/api/camera_proxy/${encodeURIComponent(entity)}`, {
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
signal: AbortSignal.timeout(25000),
});
if (!res.ok) throw new Error(`HA camera_proxy ${entity}: HTTP ${res.status}`);
const buf = Buffer.from(await res.arrayBuffer());
if (buf.length < 200) throw new Error(`Kamera ${entity} liefert kein brauchbares Bild (${buf.length} B).`);
let friendly = entity;
try {
const st = await fetch(HA_URL + `/api/states/${encodeURIComponent(entity)}`, {
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
signal: AbortSignal.timeout(10000),
});
if (st.ok) {
const j = await st.json();
friendly = (j.attributes && j.attributes.friendly_name) || entity;
}
} catch (e) {}
return { buf, friendly };
}
function imageFromArgs(args) {
const p = args && args.image_path ? String(args.image_path).trim() : '';
const b64 = args && args.image_base64 ? String(args.image_base64).trim() : '';
if (p) {
if (!fs.existsSync(p)) throw new Error(`image_path existiert nicht: ${p}`);
const buf = fs.readFileSync(p);
return { b64: buf.toString('base64'), bytes: buf.length, source: `Datei ${p}` };
}
if (b64) {
const clean = b64.startsWith('data:') && b64.includes(',') ? b64.split(',', 1)[1] : b64;
return { b64: clean, bytes: Math.floor((clean.length * 3) / 4), source: 'image_base64' };
}
throw new Error('Bild fehlt: bitte image_path oder image_base64 angeben.');
}
function fmtRecognize(data, context) {
const lines = [`## Gesichtserkennung${context ? `: ${context}` : ''}`, ''];
if (data.enrolled_people === 0) {
lines.push('Es sind noch **keine Personen eingelernt**. Nutze `face_enroll`/`face_enroll_camera`, um jemanden zu speichern.');
return lines.join('\n');
}
if (!data.count) {
lines.push('Keine Gesichter im Bild erkannt.');
return lines.join('\n');
}
data.faces.forEach((f, i) => {
const label = f.matched ? `**${f.name}**` : 'unbekannt';
const sim = f.score === null || f.score === undefined ? 'nicht eingelernt' : `Ähnlichkeit ${f.score}`;
lines.push(`- Gesicht ${i + 1}: ${label} (${sim}, Detektor ${f.det_score})`);
});
const known = data.faces.filter((f) => f.matched).map((f) => f.name);
if (known.length) lines.push('', `Erkannt: ${[...new Set(known)].join(', ')}.`);
else lines.push('', 'Niemand aus der Datenbank erkannt.');
if (Array.isArray(data.auto_learned) && data.auto_learned.length) {
lines.push('');
data.auto_learned.forEach((a) => {
lines.push(`Dazugelernt: **${a.name}** (Ähnlichkeit ${a.score}) → jetzt ${a.total} Trainingsbild(er).`);
});
}
return lines.join('\n');
}
// ---------------------------------------------------------------- tools
async function faceList() {
const data = await faceJson('/faces');
if (!data.count) return { text: '## Eingelernte Personen\n\nNoch keine Personen gespeichert. Mit `face_enroll` (Name + Bild) oder `face_enroll_camera` (Name + Kamera) anlegen.' };
const rows = data.faces.map((f) => `- **${f.name}** — ${f.samples} Bild(er), angelegt ${f.created || '?'}`).join('\n');
return { text: `## Eingelernte Personen (${data.count})\n\n${rows}` };
}
async function faceRecognize(args) {
const img = imageFromArgs(args);
const auto = args && args.auto_learn !== undefined ? Boolean(args.auto_learn) : false;
const data = await faceJson('/recognize', { method: 'POST', body: JSON.stringify({ image: img.b64, threshold: args && args.threshold, auto_learn: auto }) });
const text = fmtRecognize(data, img.source);
return { text, content: [{ type: 'text', text }] };
}
async function faceRecognizeCamera(args) {
const entity = String((args && args.entity_id) || '').trim();
if (!/^camera\.[\w-]+$/.test(entity)) return { isError: true, text: `face_recognize_camera: ungueltige entity_id "${entity}".` };
const auto = args && args.auto_learn !== undefined ? Boolean(args.auto_learn) : true;
const snap = await haSnapshot(entity);
const data = await faceJson('/recognize', { method: 'POST', body: JSON.stringify({ image: snap.buf.toString('base64'), threshold: args && args.threshold, auto_learn: auto }) });
const text = fmtRecognize(data, `Kamera ${snap.friendly}`);
const content = [{ type: 'text', text }];
if (args && args.as_image !== false) content.push({ type: 'image', data: snap.buf.toString('base64'), mimeType: 'image/jpeg' });
return { text, content };
}
async function faceEnroll(args) {
const name = String((args && args.name) || '').trim();
if (!name) return { isError: true, text: 'face_enroll: name fehlt.' };
const img = imageFromArgs(args);
const data = await faceJson('/enroll', { method: 'POST', body: JSON.stringify({ name, image: img.b64 }) });
return { text: `## Gesicht gespeichert\n\n- Person: **${data.name}**\n- Gesamtbilder: ${data.total}\n- Detektor-Score: ${data.det_score}\n- Quelle: ${img.source}` };
}
async function faceEnrollCamera(args) {
const name = String((args && args.name) || '').trim();
const entity = String((args && args.entity_id) || '').trim();
if (!name) return { isError: true, text: 'face_enroll_camera: name fehlt.' };
if (!/^camera\.[\w-]+$/.test(entity)) return { isError: true, text: `face_enroll_camera: ungueltige entity_id "${entity}".` };
const snap = await haSnapshot(entity);
const data = await faceJson('/enroll', { method: 'POST', body: JSON.stringify({ name, image: snap.buf.toString('base64') }) });
return { text: `## Gesicht gespeichert\n\n- Person: **${data.name}**\n- Kamera: ${snap.friendly} (\`${entity}\`)\n- Gesamtbilder: ${data.total}\n- Detektor-Score: ${data.det_score}` };
}
async function faceDelete(args) {
const name = String((args && args.name) || '').trim();
if (!name) return { isError: true, text: 'face_delete: name fehlt.' };
await faceJson(`/faces/${encodeURIComponent(name)}`, { method: 'DELETE' });
return { text: `Person **${name}** entfernt.` };
}
const TOOLS = [
{
name: 'face_list',
description: 'Listet alle eingelernten Personen der Gesichtserkennung mit Anzahl der Bilder.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'face_recognize',
description:
'Erkennt Gesichter in einem Bild und vergleicht sie mit den eingelernten Personen. Quelle: image_path (Dateipfad, z.B. aus camera_snapshot) ODER image_base64.',
inputSchema: {
type: 'object',
properties: {
image_path: { type: 'string', description: 'Pfad zu einer Bilddatei im Container.' },
image_base64: { type: 'string', description: 'Bild als Base64 (JPEG/PNG).' },
threshold: { type: 'number', description: 'Optionale Kosinus-Schwelle (Standard aus dem Dienst, 0.38).' },
auto_learn: { type: 'boolean', description: 'Erkanntes Gesicht automatisch als Trainingsbild speichern (Standard false).' },
},
additionalProperties: false,
},
},
{
name: 'face_recognize_camera',
description:
'Holt ein Standbild einer Home-Assistant-Kamera und erkennt darauf die Personen. Ideal fuer "Wer ist auf der Wohnzimmerkamera?".',
inputSchema: {
type: 'object',
properties: {
entity_id: { type: 'string', description: 'Kamera-Entity, z.B. "camera.lsc_smart_connect_1080p_ip_indoor_mini".' },
threshold: { type: 'number', description: 'Optionale Kosinus-Schwelle.' },
auto_learn: { type: 'boolean', description: 'Erkanntes Gesicht automatisch als Trainingsbild speichern, wenn Aehnlichkeit >= 0.60 (Standard true).' },
as_image: { type: 'boolean', description: 'Standbild mitliefern (Standard true).' },
},
required: ['entity_id'],
additionalProperties: false,
},
},
{
name: 'face_enroll',
description: 'Speichert ein neues Gesicht unter einem Namen. Quelle: image_path ODER image_base64. Erkennt das groesste Gesicht im Bild.',
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Name der Person, z.B. "Pascal".' },
image_path: { type: 'string', description: 'Pfad zu einer Bilddatei im Container.' },
image_base64: { type: 'string', description: 'Bild als Base64.' },
},
required: ['name'],
additionalProperties: false,
},
},
{
name: 'face_enroll_camera',
description:
'Speichert eine Person ein, indem ein frisches Standbild einer Home-Assistant-Kamera aufgenommen wird. Wenn keine Kamera genannt ist, zuerst camera_list aufrufen.',
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Name der Person.' },
entity_id: { type: 'string', description: 'Kamera-Entity, z.B. "camera.lsc_smart_connect_1080p_ip_indoor_mini".' },
},
required: ['name', 'entity_id'],
additionalProperties: false,
},
},
{
name: 'face_delete',
description: 'Entfernt eine eingelernte Person samt Bildern.',
inputSchema: {
type: 'object',
properties: { name: { type: 'string', description: 'Name der Person.' } },
required: ['name'],
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: 'face', version: '1.1.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: name === 'face_list' || name === 'face_recognize', destructiveHint: name === 'face_delete', idempotentHint: false, openWorldHint: true },
})),
});
return;
}
if (method === 'tools/call') {
const name = params && params.name;
const args = (params && params.arguments) || {};
const run = async () => {
if (name === 'face_list') return await faceList();
if (name === 'face_recognize') return await faceRecognize(args);
if (name === 'face_recognize_camera') return await faceRecognizeCamera(args);
if (name === 'face_enroll') return await faceEnroll(args);
if (name === 'face_enroll_camera') return await faceEnrollCamera(args);
if (name === 'face_delete') return await faceDelete(args);
return { isError: true, text: `Unbekanntes Werkzeug: ${name}` };
};
run()
.then((r) => {
const content = r.content || [{ type: 'text', text: r.text }];
reply(id, { content, isError: Boolean(r.isError) });
})
.catch((e) => reply(id, { content: [{ type: 'text', text: String((e && e.message) || e) }], isError: true }));
return;
}
if (id !== undefined) replyError(id, -32601, `Method not found: ${method}`);
}
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env node
"use strict";
const http = require("node:http");
const GITEA_URL = process.env.GITEA_URL || "http://YOUR_SERVER_IP:30005/api/v1";
function request(pathStr) {
return new Promise((resolve) => {
const url = GITEA_URL + pathStr;
const req = http.get(url, { timeout: 8000 }, (res) => {
let body = "";
res.on("data", (chunk) => { body += chunk; });
res.on("end", () => {
try {
resolve({ status: res.statusCode, data: JSON.parse(body) });
} catch {
resolve({ status: res.statusCode, raw: body });
}
});
});
req.on("error", (err) => resolve({ status: 0, error: err.message }));
req.on("timeout", () => { req.destroy(); resolve({ status: 0, error: "Timeout" }); });
});
}
function result(text, error = false) {
return { text: typeof text === "string" ? text : JSON.stringify(text, null, 2), error };
}
async function giteaVersion() {
const res = await request("/version");
if (res.status === 200 && res.data?.version) {
return result(`Gitea Version: ${res.data.version} (Status 200 OK)`);
}
return result(`Gitea Status: ${res.status} (${res.error || res.raw || "Fehler"})`, true);
}
async function giteaListRepos() {
const res = await request("/repos/search?limit=20");
if (res.status === 200 && Array.isArray(res.data?.data)) {
const repos = res.data.data.map(r => ({
name: r.full_name,
stars: r.stars_count,
forks: r.forks_count,
private: r.private,
url: r.html_url,
default_branch: r.default_branch
}));
return result(repos);
}
return result(`Fehler beim Abrufen der Repositories: ${res.error || res.raw || res.status}`, true);
}
async function giteaSearchRepos(args) {
const q = encodeURIComponent(String(args.query || "").trim());
const res = await request(`/repos/search?q=${q}&limit=10`);
if (res.status === 200 && Array.isArray(res.data?.data)) {
const repos = res.data.data.map(r => ({
name: r.full_name,
description: r.description,
url: r.html_url,
updated_at: r.updated_at
}));
return result(repos);
}
return result(`Suche fehlgeschlagen: ${res.error || res.status}`, true);
}
async function giteaListIssues(args) {
const owner = encodeURIComponent(String(args.owner || "").trim());
const repo = encodeURIComponent(String(args.repo || "").trim());
if (!owner || !repo) return result("owner und repo sind erforderlich.", true);
const res = await request(`/repos/${owner}/${repo}/issues?state=all&limit=20`);
if (res.status === 200 && Array.isArray(res.data)) {
const issues = res.data.map(i => ({
number: i.number,
title: i.title,
state: i.state,
author: i.user?.username,
created_at: i.created_at
}));
return result(issues);
}
return result(`Issues konnten nicht gelesen werden (${res.status}): ${res.error || res.raw}`, true);
}
async function giteaListCommits(args) {
const owner = encodeURIComponent(String(args.owner || "").trim());
const repo = encodeURIComponent(String(args.repo || "").trim());
if (!owner || !repo) return result("owner und repo sind erforderlich.", true);
const res = await request(`/repos/${owner}/${repo}/commits?limit=10`);
if (res.status === 200 && Array.isArray(res.data)) {
const commits = res.data.map(c => ({
sha: c.sha?.slice(0, 7),
author: c.commit?.author?.name,
message: c.commit?.message?.split("\n")[0],
date: c.commit?.author?.date
}));
return result(commits);
}
return result(`Commits konnten nicht gelesen werden (${res.status}): ${res.error || res.raw}`, true);
}
const TOOLS = [
{ name: "gitea_version", description: "Prueft Gitea-Version und API-Verfuegbarkeit. Lesend.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
{ name: "gitea_list_repos", description: "Listet oeffentliche Repositories auf Gitea. Lesend.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
{ name: "gitea_search_repos", description: "Sucht nach Repositories in Gitea. Lesend.", inputSchema: { type: "object", properties: { query: { type: "string" } }, required: ["query"], additionalProperties: false } },
{ name: "gitea_list_issues", description: "Listet Issues eines Repositories auf Gitea. Lesend.", inputSchema: { type: "object", properties: { owner: { type: "string" }, repo: { type: "string" } }, required: ["owner", "repo"], additionalProperties: false } },
{ name: "gitea_list_commits", description: "Listet letzte Commits eines Repositories. Lesend.", inputSchema: { type: "object", properties: { owner: { type: "string" }, repo: { type: "string" } }, required: ["owner", "repo"], additionalProperties: false } }
];
async function call(name, args) {
try {
if (name === "gitea_version") return await giteaVersion();
if (name === "gitea_list_repos") return await giteaListRepos();
if (name === "gitea_search_repos") return await giteaSearchRepos(args);
if (name === "gitea_list_issues") return await giteaListIssues(args);
if (name === "gitea_list_commits") return await giteaListCommits(args);
return result("Unbekanntes Werkzeug.", true);
} catch (err) {
return result(String(err.message || err), true);
}
}
function send(id, value) { process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result: value }) + "\n"); }
function reply(id, value) { send(id, { content: [{ type: "text", text: value.text }], isError: value.error }); }
let buffer = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
buffer += chunk;
let end;
while ((end = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, end).trim();
buffer = buffer.slice(end + 1);
if (!line) continue;
let message;
try { message = JSON.parse(line); } catch { continue; }
if (message.method === "initialize") send(message.id, { protocolVersion: message.params?.protocolVersion || "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "gitea-workflow", version: "1.0.0" } });
else if (message.method === "tools/list") send(message.id, { tools: TOOLS });
else if (message.method === "tools/call") call(message.params?.name, message.params?.arguments || {}).then(res => reply(message.id, res));
}
});
+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}`);
}
+375
View File
@@ -0,0 +1,375 @@
#!/usr/bin/env node
/**
* homeassistant — MCP-Server fuer Jarvis: Kameras, Zustaende und Geraetesteuerung aus Home Assistant.
*
* Design:
* - Zugriff ueber die HA-REST-API mit einem langlebigen Zugriffstoken.
* Token liegt in HA_TOKEN_FILE (Datei, 600) und wird nie geloggt.
* - Lesende Werkzeuge: camera_list, camera_snapshot, state_get, states_list.
* - Steuernde Werkzeuge: call_service (generisch, nur freigegebene Domains) und
* light_control (Bequemlichkeit fuer Lampen: on/off/toggle inkl. Helligkeit/Farbe).
* Domains ausserhalb HA_SERVICE_DOMAINS werden abgelehnt.
* - camera_snapshot holt das aktuelle Standbild ueber /api/camera_proxy/<entity>,
* speichert es als JPEG im Workspace und gibt den Pfad + das Bild zurueck.
* Text-only-Modelle sehen das Bild ueber das Tool `view_image` (Pfad).
*/
'use strict';
const fs = require('fs');
const path = require('path');
const HA_URL = (process.env.HA_URL || 'http://YOUR_SERVER_IP:8123').replace(/\/+$/, '');
const TOKEN_FILE = process.env.HA_TOKEN_FILE || '/home/node/.openclaw/mcp/.ha-token';
const SNAP_DIR = process.env.HA_SNAPSHOT_DIR || '/home/node/.openclaw/workspaces/jarvis/camera-snapshots';
const TIMEOUT_MS = Number(process.env.HA_TIMEOUT_MS || 15000);
function readToken() {
try {
const t = fs.readFileSync(TOKEN_FILE, 'utf8').trim();
if (t) return t;
} catch (e) {}
return (process.env.HA_TOKEN || '').trim();
}
async function ha(pathname, opts = {}) {
const token = readToken();
if (!token) throw new Error(`HA-Zugriffstoken fehlt (${TOKEN_FILE}).`);
const headers = { Authorization: `Bearer ${token}`, Accept: 'application/json' };
const init = {
method: opts.method || 'GET',
headers,
signal: AbortSignal.timeout(opts.timeoutMs || TIMEOUT_MS),
};
if (opts.body !== undefined) {
headers['Content-Type'] = 'application/json';
init.body = JSON.stringify(opts.body);
}
return fetch(HA_URL + pathname, init);
}
async function getStates() {
const res = await ha('/api/states');
if (res.status === 401) throw new Error('HA-Token ungueltig (401). Neues Token in HA erstellen.');
if (!res.ok) throw new Error(`HA /api/states: HTTP ${res.status}`);
return res.json();
}
const isCamera = (s) => s && typeof s.entity_id === 'string' && s.entity_id.startsWith('camera.');
const nameOf = (s) => (s && s.attributes && s.attributes.friendly_name) || (s && s.entity_id) || '?';
async function cameraList() {
const states = await getStates();
const cams = states.filter(isCamera);
if (!cams.length) return { text: '## Kameras\n\nKeine `camera.*`-Entitaeten in Home Assistant gefunden.' };
const rows = cams
.sort((a, b) => String(nameOf(a)).localeCompare(String(nameOf(b)), 'de'))
.map((c) => `- **${nameOf(c)}** — \`${c.entity_id}\` (Status: ${c.state})`)
.join('\n');
return { text: `## Kameras in Home Assistant (${cams.length})\n\n${rows}\n\nMit \`camera_snapshot\` (Argument: \`entity_id\`) ein Standbild holen.` };
}
async function cameraSnapshot(args) {
const entity = String((args && args.entity_id) || '').trim();
if (!/^camera\.[\w-]+$/.test(entity)) {
return { isError: true, text: `camera_snapshot: ungueltige entity_id "${entity}". Erwartet z.B. "camera.wohnzimmer".` };
}
const res = await ha(`/api/camera_proxy/${encodeURIComponent(entity)}`, { timeoutMs: 25000 });
if (!res.ok) {
let extra = '';
if (res.status === 404) {
try {
const cams = (await getStates()).filter(isCamera).map((c) => `- ${nameOf(c)} — \`${c.entity_id}\``);
extra = `\n\nVerfuegbare Kameras:\n${cams.join('\n')}`;
} catch (e) {}
}
return { isError: true, text: `camera_snapshot ${entity}: HTTP ${res.status} (404 = Entitaet existiert nicht oder ist keine Kamera).${extra}` };
}
const buf = Buffer.from(await res.arrayBuffer());
if (buf.length < 200) return { isError: true, text: `camera_snapshot ${entity}: Bild zu klein (${buf.length} B) - Kamera liefert evtl. gerade kein Bild.` };
const mime = res.headers.get('content-type') || 'image/jpeg';
fs.mkdirSync(SNAP_DIR, { recursive: true });
const ts = new Date().toISOString().replace(/[:.]/g, '-');
const file = path.join(SNAP_DIR, `${entity}-${ts}.jpg`);
fs.writeFileSync(file, buf);
let friendly = entity;
try {
const st = await ha(`/api/states/${encodeURIComponent(entity)}`);
if (st.ok) friendly = nameOf(await st.json());
} catch (e) {}
const text =
`## Kamera-Standbild: ${friendly}\n\n` +
`- Entitaet: \`${entity}\`\n` +
`- Datei: \`${file}\`\n` +
`- Groesse: ${buf.length} B, Typ ${mime}\n` +
`- Aufnahmezeit: ${new Date().toISOString()}\n\n` +
`Bild ansehen: Rufe \`view_image\` mit path="${file}" auf und beschreibe, was zu sehen ist.`;
const content = [{ type: 'text', text }];
if (args && args.as_image === false) {
// kein Bildblock
} else if (/^image\//.test(mime)) {
content.push({ type: 'image', data: buf.toString('base64'), mimeType: mime });
}
return { text, content };
}
async function stateGet(args) {
const entity = String((args && args.entity_id) || '').trim();
if (!entity) return { isError: true, text: 'state_get: entity_id fehlt.' };
const res = await ha(`/api/states/${encodeURIComponent(entity)}`);
if (res.status === 404) return { isError: true, text: `state_get ${entity}: nicht gefunden.` };
if (!res.ok) return { isError: true, text: `state_get ${entity}: HTTP ${res.status}` };
const s = await res.json();
const attrs = s.attributes || {};
const keep = ['friendly_name', 'unit_of_measurement', 'device_class', 'battery_level', 'motion', 'state_class'];
const lines = keep.filter((k) => attrs[k] !== undefined).map((k) => `- ${k}: ${JSON.stringify(attrs[k])}`);
return { text: `## ${nameOf(s)}\n\n- Entitaet: \`${s.entity_id}\`\n- Zustand: **${s.state}**\n- Zuletzt geaendert: ${s.last_changed}\n${lines.join('\n')}` };
}
async function statesList(args) {
const domain = String((args && args.domain) || '').trim().replace(/\.$/, '');
const q = String((args && args.name) || '').trim().toLowerCase();
const states = await getStates();
let items = states;
if (domain) items = items.filter((s) => s.entity_id.startsWith(domain + '.'));
if (q) items = items.filter((s) => nameOf(s).toLowerCase().includes(q) || s.entity_id.toLowerCase().includes(q));
if (!items.length) return { text: `## Zustaende\n\nKeine Treffer${domain ? ` fuer Domain \`${domain}\`` : ''}${q ? ` / "${q}"` : ''}.` };
const capped = items.slice(0, 100);
const rows = capped.map((s) => `- **${nameOf(s)}** — \`${s.entity_id}\` = ${s.state}`).join('\n');
return { text: `## Zustaende (${items.length}${items.length > capped.length ? `, zeige ${capped.length}` : ''})\n\n${rows}` };
}
const SAFE_DOMAINS = (
process.env.HA_SERVICE_DOMAINS ||
'light,switch,fan,cover,climate,media_player,scene,script,input_boolean,input_number,input_select,number,select,button,vacuum,lock,siren,notify,camera'
)
.split(',')
.map((s) => s.trim())
.filter(Boolean);
function entityList(v) {
if (Array.isArray(v)) return v.map((x) => String(x).trim()).filter(Boolean);
return String(v || '')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
}
async function serviceResult(res, domain, service, entity) {
if (res.status === 401) return { isError: true, text: `call_service ${domain}.${service}: HA-Token ungueltig (401).` };
if (res.status === 404) return { isError: true, text: `call_service ${domain}.${service}: nicht gefunden (404).` };
if (!res.ok) {
let t = '';
try {
t = (await res.text()).slice(0, 300);
} catch (e) {}
return { isError: true, text: `call_service ${domain}.${service}: HTTP ${res.status} ${t}` };
}
let changed = [];
try {
const j = await res.json();
if (Array.isArray(j)) changed = j.map((s) => `**${nameOf(s)}** (\`${s.entity_id}\`) = ${s.state}`);
} catch (e) {}
const ent = entity && entity.length ? ` fuer ${entity.map((e) => `\`${e}\``).join(', ')}` : '';
const body = changed.length ? changed.map((x) => `- ${x}`).join('\n') : 'OK (Home Assistant meldet keine Zustandsaenderung zurueck).';
return { text: `## Dienst ausgefuehrt: \`${domain}.${service}\`${ent}\n\n${body}` };
}
async function callService(args) {
const domain = String((args && args.domain) || '').trim().toLowerCase();
const service = String((args && args.service) || '').trim().toLowerCase();
if (!/^[a-z_]+$/.test(domain) || !/^[a-z_]+$/.test(service)) {
return { isError: true, text: 'call_service: domain und service sind Pflicht (z.B. "light"/"turn_on").' };
}
if (SAFE_DOMAINS.length && !SAFE_DOMAINS.includes(domain)) {
return { isError: true, text: `call_service: Domain "${domain}" ist nicht freigegeben. Erlaubt: ${SAFE_DOMAINS.join(', ')}.` };
}
const entity = entityList(args && args.entity_id);
const data = args && args.data && typeof args.data === 'object' && !Array.isArray(args.data) ? { ...args.data } : {};
if (entity.length) data.entity_id = entity.length === 1 ? entity[0] : entity;
const res = await ha(`/api/services/${encodeURIComponent(domain)}/${encodeURIComponent(service)}`, { method: 'POST', body: data });
return await serviceResult(res, domain, service, entity);
}
async function lightControl(args) {
const entity = String((args && args.entity_id) || '').trim();
const action = String((args && args.action) || 'on').trim().toLowerCase();
if (!/^light\.[\w-]+$/.test(entity)) {
return { isError: true, text: `light_control: ungueltige entity_id "${entity}". Erwartet z.B. "light.wohnzimmer_lampe".` };
}
const svc = action === 'on' ? 'turn_on' : action === 'off' ? 'turn_off' : action === 'toggle' ? 'toggle' : null;
if (!svc) return { isError: true, text: `light_control: action muss "on", "off" oder "toggle" sein (erhalten: "${action}").` };
const data = { entity_id: entity };
if (svc !== 'turn_off') {
if (args && args.brightness_pct != null) {
const b = Number(args.brightness_pct);
if (b >= 0 && b <= 100) data.brightness_pct = b;
}
if (args && args.color_temp_kelvin != null) {
const k = Number(args.color_temp_kelvin);
if (k > 0) data.color_temp_kelvin = k;
}
if (args && Array.isArray(args.rgb_color) && args.rgb_color.length === 3) data.rgb_color = args.rgb_color.map((n) => Number(n));
}
const res = await ha(`/api/services/light/${svc}`, { method: 'POST', body: data });
return await serviceResult(res, 'light', svc, [entity]);
}
const TOOLS = [
{
name: 'camera_list',
description: 'Listet alle Kameras (camera.*) aus Home Assistant mit Name und Entity-ID.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'camera_snapshot',
description:
'Holt ein aktuelles Standbild einer HA-Kamera und speichert es als JPEG. Gibt den Dateipfad zurueck; das Bild wird auch direkt mitgeliefert. Fuer text-only-Modelle danach `view_image` mit dem Pfad aufrufen.',
inputSchema: {
type: 'object',
properties: {
entity_id: { type: 'string', description: 'Kamera-Entity, z.B. "camera.wohnzimmer".' },
as_image: { type: 'boolean', description: 'Bild direkt mitliefern (Standard true).' },
},
required: ['entity_id'],
additionalProperties: false,
},
},
{
name: 'state_get',
description: 'Liefert den Zustand und wichtige Attribute einer Home-Assistant-Entitaet (z.B. Bewegungsmelder, Tuer-/Fenstersensor).',
inputSchema: {
type: 'object',
properties: { entity_id: { type: 'string', description: 'Entity-ID, z.B. "binary_sensor.wohnzimmer_bewegung".' } },
required: ['entity_id'],
additionalProperties: false,
},
},
{
name: 'states_list',
description: 'Sucht Entitaeten nach Domain (z.B. "binary_sensor", "sensor", "light") und/oder Namensteil.',
inputSchema: {
type: 'object',
properties: {
domain: { type: 'string', description: 'Domain, z.B. "binary_sensor" oder "sensor".' },
name: { type: 'string', description: 'Namens- oder Entity-Teilstring (optional).' },
},
additionalProperties: false,
},
},
{
name: 'call_service',
description:
'Ruft einen Home-Assistant-Dienst auf (Steuerung). Nur freigegebene Domains (u.a. light, switch, fan, cover, climate, media_player, scene, script, input_boolean). Beispiel: domain="light", service="turn_on", entity_id="light.wohnzimmer_lampe".',
inputSchema: {
type: 'object',
properties: {
domain: { type: 'string', description: 'Dienst-Domain, z.B. "light" oder "switch".' },
service: { type: 'string', description: 'Dienstname, z.B. "turn_on", "turn_off", "toggle".' },
entity_id: { type: ['string', 'array'], items: { type: 'string' }, description: 'Eine oder mehrere Entity-IDs.' },
data: { type: 'object', description: 'Zusaetzliche Dienst-Daten (z.B. brightness_pct, color_temp_kelvin).' },
},
required: ['domain', 'service'],
additionalProperties: false,
},
annotations: { title: 'call service', readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
},
{
name: 'light_control',
description:
'Schaltet eine Lampe (light.*). action="on" (optional brightness_pct 0-100, color_temp_kelvin, rgb_color[3]) | "off" | "toggle".',
inputSchema: {
type: 'object',
properties: {
entity_id: { type: 'string', description: 'Lampen-Entity, z.B. "light.wohnzimmer_lampe".' },
action: { type: 'string', enum: ['on', 'off', 'toggle'], description: 'on, off oder toggle (Standard on).' },
brightness_pct: { type: 'number', description: 'Helligkeit in Prozent (0-100), nur bei on.' },
color_temp_kelvin: { type: 'number', description: 'Farbtemperatur in Kelvin, nur bei on.' },
rgb_color: { type: 'array', items: { type: 'number' }, description: 'RGB-Farbe [r,g,b] (0-255), nur bei on.' },
},
required: ['entity_id', 'action'],
additionalProperties: false,
},
annotations: { title: 'light control', readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
},
];
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: 'homeassistant', version: '1.1.0' },
});
return;
}
if (method === 'ping') {
reply(id, {});
return;
}
if (method === 'tools/list') {
reply(id, {
tools: TOOLS.map(({ name, description, inputSchema, annotations }) => ({
name,
description,
inputSchema,
annotations:
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 === 'camera_list') return await cameraList();
if (name === 'camera_snapshot') return await cameraSnapshot(args);
if (name === 'state_get') return await stateGet(args);
if (name === 'states_list') return await statesList(args);
if (name === 'call_service') return await callService(args);
if (name === 'light_control') return await lightControl(args);
return { isError: true, text: `Unbekanntes Werkzeug: ${name}` };
};
run()
.then((r) => {
const content = r.content || [{ type: 'text', text: r.text }];
reply(id, { content, isError: Boolean(r.isError) });
})
.catch((e) => reply(id, { content: [{ type: 'text', text: String((e && e.message) || e) }], isError: true }));
return;
}
if (id !== undefined) replyError(id, -32601, `Method not found: ${method}`);
}
+332
View File
@@ -0,0 +1,332 @@
#!/usr/bin/env python3
"""Read-only IMAP MCP server for a delegated grommunio mailbox."""
import base64
import email
import hashlib
import html
import imaplib
import json
import os
import re
import socket
import ssl
import stat
import sys
from email.header import decode_header, make_header
from email.policy import default
HOST = os.environ.get("MAIL_IMAP_HOST", "mail.your-domain.com")
PORT = int(os.environ.get("MAIL_IMAP_PORT", "993"))
TARGET = os.environ.get("MAIL_TARGET_MAILBOX", "[email protected]")
CREDENTIALS_FILE = os.environ.get("MAIL_CREDENTIALS_FILE", "/home/node/.openclaw/mcp/.mail-credentials")
CERT_SHA256 = re.sub(r"[^A-Fa-f0-9]", "", os.environ.get("MAIL_CERT_SHA256", "")).upper()
MAX_MESSAGE_BYTES = 131072
def read_credentials():
try:
info = os.stat(CREDENTIALS_FILE)
except OSError as exc:
raise RuntimeError("Mail-Credential-Datei ist nicht lesbar.") from exc
if stat.S_IMODE(info.st_mode) & 0o077:
raise RuntimeError(f"Mail-Credential-Datei ist nicht restriktiv (Modus {oct(stat.S_IMODE(info.st_mode))}).")
if info.st_uid != 1000:
raise RuntimeError(f"Mail-Credential-Datei gehoert uid {info.st_uid}, erwartet 1000.")
with open(CREDENTIALS_FILE, encoding="utf-8") as handle:
lines = handle.read().splitlines()
if len(lines) != 2 or not lines[0] or not lines[1]:
raise RuntimeError("Mail-Credential-Datei muss genau Benutzername und Kennwort enthalten.")
return lines[0], lines[1]
def tls_context():
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
return context
def verify_certificate():
if not CERT_SHA256:
raise RuntimeError("Kein SHA-256-Fingerprint fuer das IMAP-Zertifikat konfiguriert.")
context = tls_context()
with socket.create_connection((HOST, PORT), timeout=15) as raw:
with context.wrap_socket(raw, server_hostname=HOST) as tls:
actual = hashlib.sha256(tls.getpeercert(binary_form=True)).hexdigest().upper()
if actual != CERT_SHA256:
raise RuntimeError("IMAP-Zertifikat stimmt nicht mit dem konfigurierten Fingerprint ueberein.")
class Mailbox:
def __enter__(self):
verify_certificate()
username, password = read_credentials()
self.client = imaplib.IMAP4_SSL(HOST, PORT, ssl_context=tls_context(), timeout=20)
self.client.login(f"{username}!{TARGET}", password)
return self.client
def __exit__(self, *_args):
try:
self.client.logout()
except Exception:
pass
def decode_text(value):
if not value:
return ""
try:
return str(make_header(decode_header(value)))
except Exception:
return str(value)
def decode_modified_utf7(value):
result = []
index = 0
for match in re.finditer(r"&([^-]*)-", value):
result.append(value[index:match.start()])
token = match.group(1)
if not token:
result.append("&")
else:
padded = token.replace(",", "/") + "=" * ((4 - len(token) % 4) % 4)
result.append(base64.b64decode(padded).decode("utf-16-be"))
index = match.end()
result.append(value[index:])
return "".join(result)
def encode_modified_utf7(value):
chunks = []
pending = []
def flush():
if pending:
raw = "".join(pending).encode("utf-16-be")
chunks.append("&" + base64.b64encode(raw).decode("ascii").rstrip("=").replace("/", ",") + "-")
pending.clear()
for character in value:
code = ord(character)
if 0x20 <= code <= 0x7E:
flush()
chunks.append("&-" if character == "&" else character)
else:
pending.append(character)
flush()
return "".join(chunks)
def quote_mailbox(folder):
folder = str(folder or "INBOX").strip()
if not folder or "\r" in folder or "\n" in folder:
raise RuntimeError("Ungueltiger Mailordner.")
return encode_modified_utf7(folder)
def select_readonly(client, folder):
status, data = client.select(quote_mailbox(folder), readonly=True)
if status != "OK":
raise RuntimeError(f"Mailordner nicht lesbar: {folder}")
return int(data[0] or 0)
def list_folders_raw(client):
status, rows = client.list()
if status != "OK":
raise RuntimeError("Mailordner konnten nicht gelesen werden.")
folders = []
for row in rows or []:
line = row.decode("utf-8", "replace")
match = re.search(r'("(?:[^"\\]|\\.)*"|\S+)$', line)
if not match:
continue
raw = match.group(1)
if raw.startswith('"'):
raw = raw[1:-1].replace('\\"', '"').replace('\\\\', '\\')
folders.append(decode_modified_utf7(raw))
return folders
def parse_header(payload):
message = email.message_from_bytes(payload, policy=default)
return {
"date": decode_text(message.get("Date")),
"from": decode_text(message.get("From")),
"to": decode_text(message.get("To")),
"cc": decode_text(message.get("Cc")),
"subject": decode_text(message.get("Subject")) or "(ohne Betreff)",
"message_id": decode_text(message.get("Message-ID")),
}
def message_rows(client, uids):
rows = []
fields = "BODY.PEEK[HEADER.FIELDS (DATE FROM TO CC SUBJECT MESSAGE-ID)] FLAGS RFC822.SIZE INTERNALDATE"
for uid in uids:
status, data = client.uid("FETCH", uid, f"({fields})")
if status != "OK" or not data or not isinstance(data[0], tuple):
continue
metadata, payload = data[0]
item = parse_header(payload)
item["uid"] = uid.decode("ascii", "replace") if isinstance(uid, bytes) else str(uid)
meta = metadata.decode("utf-8", "replace")
item["unread"] = "\\Seen" not in meta
size = re.search(r"RFC822\.SIZE (\d+)", meta)
item["size_bytes"] = int(size.group(1)) if size else None
rows.append(item)
return rows
def status_tool(_args):
with Mailbox() as client:
folders = list_folders_raw(client)
status, data = client.status("INBOX", "(MESSAGES UNSEEN UIDNEXT)")
summary = data[0].decode("utf-8", "replace") if status == "OK" and data else "unbekannt"
return f"## Grommunio Mail\n\n- Server: {HOST}:{PORT} (IMAPS, Zertifikat gepinnt)\n- Zielpostfach: {TARGET}\n- Zugriff: read-only via IMAP EXAMINE/BODY.PEEK\n- Ordner: {len(folders)}\n- INBOX: {summary}"
def folders_tool(_args):
with Mailbox() as client:
folders = list_folders_raw(client)
return "## Mailordner\n\n" + "\n".join(f"- {folder}" for folder in folders)
def list_messages_tool(args):
folder = str(args.get("folder", "INBOX"))
limit = max(1, min(int(args.get("limit", 20)), 100))
unread_only = bool(args.get("unread_only", False))
with Mailbox() as client:
total = select_readonly(client, folder)
status, data = client.uid("SEARCH", None, "UNSEEN" if unread_only else "ALL")
if status != "OK":
raise RuntimeError("Nachrichtenliste konnte nicht gelesen werden.")
uids = list(reversed((data[0] or b"").split()))[:limit]
rows = message_rows(client, uids)
return json.dumps({"mailbox": TARGET, "folder": folder, "total": total, "returned": len(rows), "messages": rows}, ensure_ascii=False, indent=2)
def search_messages_tool(args):
folder = str(args.get("folder", "INBOX"))
query = str(args.get("query", "")).strip()
limit = max(1, min(int(args.get("limit", 20)), 100))
if not query or len(query) > 200 or "\r" in query or "\n" in query:
raise RuntimeError("Suchtext fehlt oder ist ungueltig.")
if not query.isascii():
raise RuntimeError("Die IMAP-Suche unterstuetzt auf diesem Server nur ASCII-Suchtext.")
escaped = query.replace("\\", "\\\\").replace('"', '\\"')
with Mailbox() as client:
select_readonly(client, folder)
status, data = client.uid("SEARCH", None, f'TEXT "{escaped}"')
if status != "OK":
raise RuntimeError("Nachrichtensuche ist fehlgeschlagen.")
uids = list(reversed((data[0] or b"").split()))[:limit]
rows = message_rows(client, uids)
return json.dumps({"mailbox": TARGET, "folder": folder, "query": query, "returned": len(rows), "messages": rows}, ensure_ascii=False, indent=2)
def extract_body(message):
plain = []
rich = []
parts = message.walk() if message.is_multipart() else [message]
for part in parts:
if part.get_content_disposition() == "attachment":
continue
content_type = part.get_content_type()
if content_type not in ("text/plain", "text/html"):
continue
try:
content = part.get_content()
except Exception:
raw = part.get_payload(decode=True) or b""
content = raw.decode(part.get_content_charset() or "utf-8", "replace")
if content_type == "text/plain":
plain.append(str(content))
else:
rich.append(re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", str(content)))).strip())
return "\n\n".join(plain or rich).strip()
def read_message_tool(args):
folder = str(args.get("folder", "INBOX"))
uid = str(args.get("uid", "")).strip()
if not uid.isdigit():
raise RuntimeError("Eine numerische IMAP-UID ist erforderlich.")
with Mailbox() as client:
select_readonly(client, folder)
status, data = client.uid("FETCH", uid, f"(BODY.PEEK[]<0.{MAX_MESSAGE_BYTES}> FLAGS RFC822.SIZE)")
if status != "OK" or not data or not isinstance(data[0], tuple):
raise RuntimeError("Nachricht wurde nicht gefunden.")
metadata, payload = data[0]
message = email.message_from_bytes(payload, policy=default)
headers = parse_header(payload)
body = extract_body(message)
attachments = [decode_text(part.get_filename()) for part in message.walk() if part.get_content_disposition() == "attachment"]
result = {"mailbox": TARGET, "folder": folder, "uid": uid, **headers, "body": body[:60000], "attachments": attachments, "truncated": len(payload) >= MAX_MESSAGE_BYTES}
return json.dumps(result, ensure_ascii=False, indent=2)
TOOLS = [
{"name": "mail_status", "description": "Prueft den read-only IMAP-Zugriff auf Pascals delegiertes grommunio-Postfach.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
{"name": "mail_list_folders", "description": "Listet die Ordner in Pascals delegiertem Postfach. Lesend.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
{"name": "mail_list_messages", "description": "Listet die neuesten Nachrichten eines Mailordners ohne sie als gelesen zu markieren.", "inputSchema": {"type": "object", "properties": {"folder": {"type": "string"}, "limit": {"type": "integer", "minimum": 1, "maximum": 100}, "unread_only": {"type": "boolean"}}, "additionalProperties": False}},
{"name": "mail_search_messages", "description": "Durchsucht Nachrichten eines Mailordners nach ASCII-Text, ohne den Postfachzustand zu veraendern.", "inputSchema": {"type": "object", "properties": {"folder": {"type": "string"}, "query": {"type": "string"}, "limit": {"type": "integer", "minimum": 1, "maximum": 100}}, "required": ["query"], "additionalProperties": False}},
{"name": "mail_read_message", "description": "Liest eine Nachricht anhand von Ordner und IMAP-UID mit BODY.PEEK, ohne sie als gelesen zu markieren.", "inputSchema": {"type": "object", "properties": {"folder": {"type": "string"}, "uid": {"type": "string"}}, "required": ["uid"], "additionalProperties": False}},
]
DISPATCH = {
"mail_status": status_tool,
"mail_list_folders": folders_tool,
"mail_list_messages": list_messages_tool,
"mail_search_messages": search_messages_tool,
"mail_read_message": read_message_tool,
}
def send(message):
sys.stdout.write(json.dumps(message, ensure_ascii=True, separators=(",", ":")) + "\n")
sys.stdout.flush()
def handle(message):
request_id = message.get("id")
method = message.get("method")
params = message.get("params") or {}
if method == "notifications/initialized" or (request_id is None and method):
return
if method == "initialize":
send({"jsonrpc": "2.0", "id": request_id, "result": {"protocolVersion": params.get("protocolVersion", "2024-11-05"), "capabilities": {"tools": {}}, "serverInfo": {"name": "grommunio-mail", "version": "1.0.0"}}})
elif method == "ping":
send({"jsonrpc": "2.0", "id": request_id, "result": {}})
elif method == "tools/list":
tools = []
for tool in TOOLS:
item = dict(tool)
item["annotations"] = {"title": tool["name"].replace("_", " "), "readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": True}
tools.append(item)
send({"jsonrpc": "2.0", "id": request_id, "result": {"tools": tools}})
elif method == "tools/call":
name = params.get("name")
function = DISPATCH.get(name)
if not function:
send({"jsonrpc": "2.0", "id": request_id, "result": {"content": [{"type": "text", "text": f"Unbekanntes Mail-Werkzeug: {name}"}], "isError": True}})
return
try:
text = function(params.get("arguments") or {})
send({"jsonrpc": "2.0", "id": request_id, "result": {"content": [{"type": "text", "text": text}], "isError": False}})
except Exception as exc:
send({"jsonrpc": "2.0", "id": request_id, "result": {"content": [{"type": "text", "text": f"Mail-Fehler: {exc}"}], "isError": True}})
else:
send({"jsonrpc": "2.0", "id": request_id, "error": {"code": -32601, "message": "Method not found"}})
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
handle(json.loads(line))
except json.JSONDecodeError:
send({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}})
+468
View File
@@ -0,0 +1,468 @@
#!/usr/bin/env node
/**
* memos — MCP-Server fuer die Memos-Instanz (http://YOUR_SERVER_IP:5230, v0.25.2).
*
* Zweck: Changelog-Pflege und Notizen auf der vom User betriebenen Memos-Plattform.
*
* Sicherheitsmodell:
* - Feste Basis-URL aus MEMOS_URL (kein Host/Port aus Tool-Eingaben -> kein SSRF).
* - Personal-Access-Token (JWT, nie-ablaufend) liegt in einer Datei (MEMOS_TOKEN_FILE,
* uid 1000, Modus 600), nie im Config-Text; wird nie geloggt.
* - Texte auf MAX_CHARS begrenzt, Timeouts hart. Loschen/Anlegen/Aendern sind klar
* als Schreibwerkzeuge annotiert.
*/
'use strict';
const http = require('http');
const fs = require('fs');
const TIMEOUT_MS = 8000;
const MAX_CHARS = 50000;
const MEMOS_BASE = process.env.MEMOS_URL || 'http://YOUR_SERVER_IP:5230';
const VIS = ['PUBLIC', 'PROTECTED', 'PRIVATE'];
function readMemosToken() {
const p = process.env.MEMOS_TOKEN_FILE;
if (!p) return { error: 'MEMOS_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 request(path, token, options) {
return new Promise((resolve) => {
const started = Date.now();
const method = (options && options.method) || 'GET';
const body = options && options.body;
const headers = { Authorization: `Bearer ${token}`, ...(body ? { 'Content-Type': 'application/json' } : {}) };
const req = http.request(MEMOS_BASE + path, { timeout: TIMEOUT_MS, method, headers }, (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, body: data.slice(0, MAX_CHARS) });
};
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) }));
if (body) req.write(JSON.stringify(body));
req.end();
});
}
function apiError(r, fallback) {
let desc = fallback;
if (r.parsed && typeof r.parsed === 'object') {
const e = [];
if (r.parsed.message) e.push(String(r.parsed.message));
if (r.parsed.code !== undefined) e.push(`code=${r.parsed.code}`);
if (e.length) desc = e.join('; ');
}
if (!desc && r.parseError) desc = r.parseError;
return desc;
}
function memoId(args) {
let id = String(((args && args.id) || (args && args.name) || '')).trim();
return id.replace(/^memos\//, '');
}
function fmtTime(iso) {
if (!iso) return '-';
return String(iso).replace('T', ' ').replace('Z', 'U').slice(0, 16);
}
function fmtVisibility(v) {
const s = String(v || '?').toLowerCase();
if (s === 'public') return 'oeffentlich';
if (s === 'private') return 'privat';
if (s === 'protected') return 'geschuetzt';
return String(v || '?');
}
const TOOLS = [
{
name: 'me',
description:
'Zeigt, mit welchem Memos-Konto Jarvis schreibt (Username, Rolle ADMIN/NORMAL, Anzeigename, E-Mail). Lesend.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'list_memos',
description:
'Listet die neuesten Memos (Standard: 10, max. 100). Ausgabe als Tabelle mit ID, Zeit, Sichtbarkeit und Textanriss. Lesend.',
inputSchema: {
type: 'object',
properties: {
limit: { type: 'integer', description: 'Anzahl (1-100, Standard 10).' },
page_token: { type: 'string', description: 'Paginierung: nextPageToken aus einem frueheren Aufruf.' },
},
additionalProperties: false,
},
},
{
name: 'get_memo',
description:
'Liefert ein einzelnes Memo im Volltext (Markdown), mit Sichtbarkeit, Erstell-/Aenderzeitpunkt und optionalen Struktur-Feldern. Lesend.',
inputSchema: {
type: 'object',
properties: {
id: { type: 'string', description: 'Memo-ID oder vollstaendiger Name, z.B. "memos/KB4xxxx" oder "KB4xxxx".' },
},
required: ['id'],
additionalProperties: false,
},
},
{
name: 'search_memos',
description:
'Durchsucht Memos nach einem Textfragment (Gross-/Kleinschreibung egal). Arbeitet ueber die letzten Seiten und filtert clientseitig. Lesend.',
inputSchema: {
type: 'object',
properties: {
text: { type: 'string', description: 'Suchtext (Substring im Inhalt).' },
limit: { type: 'integer', description: 'Scantiefe (Anzahl zu pruefender Memos, max. 500, Standard 100).' },
},
required: ['text'],
additionalProperties: false,
},
},
{
name: 'create_memo',
description:
'Legt ein neues Memo/Changelog-Notiz auf der Memos-Plattform an. Standard-Sichtbarkeit "PUBLIC" (Changelog). Liefert die neue Memo-ID.',
inputSchema: {
type: 'object',
properties: {
content: { type: 'string', description: 'Inhalt als Markdown. Tags koennen als "#name" oder "memos/name" geschrieben werden.' },
visibility: { type: 'string', enum: ['PUBLIC', 'PROTECTED', 'PRIVATE'], description: 'Sichtbarkeit (Standard PUBLIC).' },
},
required: ['content'],
additionalProperties: false,
},
},
{
name: 'update_memo',
description:
'Aendert Inhalt und/oder Sichtbarkeit eines bestehenden Memos (genaues AIP-updateMask). Liefert den neuen Zustand.',
inputSchema: {
type: 'object',
properties: {
id: { type: 'string', description: 'Memo-ID oder Name, z.B. "memos/KB4xxxx".' },
content: { type: 'string', description: 'Neuer Inhalt (Markdown).' },
visibility: { type: 'string', enum: ['PUBLIC', 'PROTECTED', 'PRIVATE'], description: 'Neue Sichtbarkeit.' },
},
required: ['id'],
additionalProperties: false,
},
},
{
name: 'delete_memo',
description:
'Loescht ein Memo dauerhaft (nur eigenes Konto, Rolle ADMIN/NORMAL). Vorsicht: nicht rueckgaengig. Liefert Bestaetigung oder Fehler.',
inputSchema: {
type: 'object',
properties: {
id: { type: 'string', description: 'Memo-ID oder Name, z.B. "memos/KB4xxxx".' },
},
required: ['id'],
additionalProperties: false,
},
},
];
async function me() {
const auth = readMemosToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const r = await request('/api/v1/auth/sessions/current', auth.token);
if (r.code !== 200 || !r.parsed || !r.parsed.user) {
return { error: true, text: `Identitaet nicht lesbar: HTTP ${r.code} (${apiError(r, '')})` };
}
const u = r.parsed.user;
const lines = [
'## Memos-Konto',
'',
`- Username: **${u.username || '?'}**`,
`- Name: ${u.displayName || '-'}`,
`- Rolle: ${u.role === 'ADMIN' ? 'Administrator' : u.role || '-'}`,
`- E-Mail: ${u.email || '-'}`,
`- Resource: ${u.name || '-'}`,
`- Zustand: ${u.state || '-'}`,
];
return { error: false, text: lines.join('\n') };
}
async function listMemos(args) {
const auth = readMemosToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const limit = Math.min(100, Math.max(1, Number((args && args.limit) || 10)));
const pt = (args && args.page_token) ? encodeURIComponent(String(args.page_token)) : '';
const r = await request(`/api/v1/memos?pageSize=${limit}${pt ? '&pageToken=' + pt : ''}`, auth.token);
if (r.code !== 200 || !r.parsed) {
return { error: true, text: `Liste nicht lesbar: HTTP ${r.code} (${apiError(r, '')})` };
}
const memos = Array.isArray(r.parsed.memos) ? r.parsed.memos : [];
const lines = [
'## Memos',
'',
`Angezeigt: ${memos.length}${r.parsed.nextPageToken ? ' (weitere Seiten vorhanden)' : ''}`,
'',
'| ID | Zeit | Sichtbarkeit | Inhalt (Anriss) |',
'|---|---|---|---|',
];
for (const m of memos) {
const id = String(m.name || '').replace(/^memos\//, '');
lines.push(`| ${id} | ${fmtTime(m.displayTime || m.createTime)} | ${fmtVisibility(m.visibility)} | ${String(m.content || '').replace(/\n+/g, ' ').slice(0, 80)} |`);
}
if (r.parsed.nextPageToken) lines.push('', `Naechste Seite: page_token=\`${r.parsed.nextPageToken}\``);
return { error: false, text: lines.join('\n') };
}
async function getMemo(args) {
const auth = readMemosToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const id = memoId(args);
if (!id) return { error: true, text: 'Memo-ID fehlt.' };
const r = await request(`/api/v1/memos/${encodeURIComponent(id)}`, auth.token);
if (r.code !== 200 || !r.parsed) {
return { error: true, text: `Memo ${id} nicht lesbar: HTTP ${r.code} (${apiError(r, '')})` };
}
const m = r.parsed;
const lines = [
`## Memo ${id}`,
'',
`- Sichtbarkeit: ${fmtVisibility(m.visibility)}`,
`- Erstellt: ${fmtTime(m.createTime)}`,
m.updateTime ? `- Geaendert: ${fmtTime(m.updateTime)}` : null,
`- Angezeigt: ${fmtTime(m.displayTime)}`,
m.creator ? `- Autor: ${m.creator}` : null,
'',
'### Inhalt',
'',
String(m.content || '(leer)').slice(0, MAX_CHARS),
].filter((l) => l !== null);
return { error: false, text: lines.join('\n') };
}
async function searchMemos(args) {
const auth = readMemosToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const text = String((args && args.text) || '').trim().toLowerCase();
if (!text) return { error: true, text: 'Suchtext fehlt.' };
const scan = Math.min(500, Math.max(1, Number((args && args.limit) || 100)));
const hits = [];
let pageToken = '';
let fetched = 0;
while (fetched < scan) {
const size = Math.min(100, scan - fetched);
const path = `/api/v1/memos?pageSize=${size}${pageToken ? '&pageToken=' + encodeURIComponent(pageToken) : ''}`;
const r = await request(path, auth.token);
if (r.code !== 200 || !r.parsed) {
return { error: true, text: `Suche fehlgeschlagen: HTTP ${r.code} (${apiError(r, '')})` };
}
const memos = Array.isArray(r.parsed.memos) ? r.parsed.memos : [];
for (const m of memos) {
if (String(m.content || '').toLowerCase().indexOf(text) >= 0) hits.push(m);
}
fetched += memos.length;
pageToken = r.parsed.nextPageToken || '';
if (!pageToken) break;
}
const lines = ['## Suche: ' + (args.text) + '', '', `Gefunden: ${hits.length} Treffer (gescannt: ${fetched})`, ''];
if (fetched > scan) lines.splice(1, 0, '', `(Scan auf ${scan} begrenzt, weitere Seiten moeglich)`, '');
if (hits.length) {
lines.push('| ID | Zeit | Inhalt |', '|---|---|---|');
for (const m of hits.slice(0, 30)) {
const id = String(m.name || '').replace(/^memos\//, '');
lines.push(`| ${id} | ${fmtTime(m.displayTime || m.createTime)} | ${String(m.content || '').replace(/\n+/g, ' ').slice(0, 100)} |`);
}
}
return { error: false, text: lines.join('\n') };
}
async function createMemo(args) {
const auth = readMemosToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const content = String((args && args.content) || '').trim();
if (!content) return { error: true, text: 'Inhalt fehlt (content).' };
let vis = String((args && args.visibility) || 'PUBLIC').toUpperCase();
if (!VIS.includes(vis)) return { error: true, text: `Ungueltige Sichtbarkeit "${vis}". Erlaubt: ${VIS.join(', ')}.` };
const r = await request('/api/v1/memos', auth.token, { method: 'POST', body: { content, visibility: vis } });
if (r.code !== 200 || !r.parsed || !r.parsed.name) {
return { error: true, text: `Anlegen fehlgeschlagen: HTTP ${r.code} (${apiError(r, '')})` };
}
const id = String(r.parsed.name).replace(/^memos\//, '');
return {
error: false,
text: `## Memo angelegt\n\n- ID: ${id}\n- Sichtbarkeit: ${fmtVisibility(vis)}\n- Erstellt: ${fmtTime(r.parsed.createTime)}\n\nAbrufbar mit get_memo (id=${id}).`,
};
}
async function updateMemo(args) {
const auth = readMemosToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const id = memoId(args);
if (!id) return { error: true, text: 'Memo-ID fehlt.' };
const body = {};
const mask = [];
if (args && args.content !== undefined) {
body.content = String(args.content);
mask.push('content');
}
if (args && args.visibility !== undefined) {
let vis = String(args.visibility).toUpperCase();
if (!VIS.includes(vis)) return { error: true, text: `Ungueltige Sichtbarkeit "${vis}".` };
body.visibility = vis;
mask.push('visibility');
}
if (!mask.length) return { error: true, text: 'Nichts zu aendern (content und/oder visibility angeben).' };
const r = await request(`/api/v1/memos/${encodeURIComponent(id)}?updateMask=${mask.join(',')}`, auth.token, {
method: 'PATCH',
body,
});
if (r.code !== 200 || !r.parsed) {
return { error: true, text: `Aendern fehlgeschlagen: HTTP ${r.code} (${apiError(r, '')})` };
}
const m = r.parsed;
return {
error: false,
text: `## Memo aktualisiert\n\n- ID: ${String(m.name || '').replace(/^memos\//, '')}\n- Sichtbarkeit: ${fmtVisibility(m.visibility)}\n- Geaendert: ${fmtTime(m.updateTime)}`.replace('## Memo aktualisiert\n\n- ID: \n', '## Memo aktualisiert\n\n- ID: ' + id + '\n'),
};
}
async function deleteMemo(args) {
const auth = readMemosToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const id = memoId(args);
if (!id) return { error: true, text: 'Memo-ID fehlt.' };
const r = await request(`/api/v1/memos/${encodeURIComponent(id)}`, auth.token, { method: 'DELETE' });
if (r.code !== 200 && r.code !== 204) {
return { error: true, text: `Loeschen fehlgeschlagen: HTTP ${r.code} (${apiError(r, '')})` };
}
return { error: false, text: `Memo ${id} geloescht.` };
}
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 toolAnnotations(name) {
const write = ['create_memo', 'update_memo', 'delete_memo'].includes(name);
return {
title: name.replace(/_/g, ' '),
readOnlyHint: !write,
destructiveHint: name === 'delete_memo',
idempotentHint: name === 'delete_memo' || name === 'update_memo',
openWorldHint: true,
};
}
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: 'memos', 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: toolAnnotations(name),
})),
});
return;
}
if (method === 'tools/call') {
const name = params && params.name;
const args = (params && params.arguments) || {};
const dispatch = {
me: [false, () => me()],
list_memos: [false, () => listMemos(args)],
get_memo: [false, () => getMemo(args)],
search_memos: [false, () => searchMemos(args)],
create_memo: [false, () => createMemo(args)],
update_memo: [false, () => updateMemo(args)],
delete_memo: [false, () => deleteMemo(args)],
};
const entry = dispatch[name];
if (!entry) {
reply(id, { content: [{ type: 'text', text: `Unbekanntes Werkzeug: ${name}` }], isError: true });
return;
}
entry[1]()
.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');
}
+461
View File
@@ -0,0 +1,461 @@
#!/usr/bin/env node
/**
* obsidian — MCP-Server fuer Self-hosted LiveSync (CouchDB) oben auf
* https://vpn.your-domain.com/obsidiannotes (Konto jarvis).
*
* Der Tresor ist Jarvis' Haupt-Dokumentationsbereich (Obsidian/Markdown). Der
* Server liest und schreibt direkt im CouchDB-Datenbankschema von
* Self-hosted LiveSync 1.0 (Protocol v2):
* - Eine Datei = ein Metadata-Dokument { path, ctime, mtime, size, eden,
* children, type: "plain" | "newnote" }, _id = klein-gefalteter Pfad.
* - Ihr Inhalt = ein oder mehrere Chunk-Dokumente { type: "leaf", data }.
* Bei type "plain" ist data literal (decode = direkt), bei "newnote"
* Base64 (decode = base64). children referenziert die Chunks in
* Reihenfolge; Konkatenieren ergibt den Dateiinhalt.
*
* Sicherheitsmodell:
* - Nur der dedizierte CouchDB-User jarvis (kein Admin). Zugangsdaten aus
* der Datei OBSIDIAN_PASSFILE (600, uid 1000) — nie im Config-Text.
* - TLS-Verifizierung wird bewusst NICHT deaktiviert (Zertifikat von
* vpn.your-domain.com wird normal geprueft; falls das Zert an Stelle der
* Einrichtung abweicht: OBSIDIAN_TLS_INSECURE=1 im Server-Env setzen).
* - create/update/delete nur als beabsichtigte Schreibzugriffe. Lesungen
* liefern keine geheimen Werte ausser Notizinhalt.
* - Session-/Zugangsdaten werden nie geloggt.
*/
'use strict';
const https = require('https');
const fs = require('fs');
const { pathToFileURL } = require('url');
const URL = (process.env.OBSIDIAN_COUCH_URL || 'https://vpn.your-domain.com').replace(/\/$/, '');
const DB = process.env.OBSIDIAN_COUCH_DB || 'obsidiannotes';
const PASSFILE = process.env.OBSIDIAN_PASSFILE || '/home/node/.openclaw/mcp/.couchpass';
const COMMONLIB = process.env.OBSIDIAN_COMMONLIB || '/home/node/.openclaw/obsidian-commonlib/node_modules/@vrtmrz/livesync-commonlib/dist/index.js';
const TLS_INSECURE = String(process.env.OBSIDIAN_TLS_INSECURE || '0') === '1';
const TIMEOUT_MS = 20000;
// stdout belongs exclusively to MCP JSON-RPC; Commonlib emits diagnostics via console.
console.log = () => {};
console.info = () => {};
console.debug = () => {};
let cachedAuth = null;
let manipulatorPromise = null;
function readAuth() {
if (cachedAuth) return cachedAuth;
let st;
try { st = fs.statSync(PASSFILE); } catch (e) { throw new Error(`Passwortdatei nicht lesbar: ${PASSFILE}`); }
if ((st.mode & 0o077) !== 0) throw new Error(`Passwortdatei nicht restriktiv (Modus ${st.mode & 0o777}).`);
if (st.uid !== 1000) throw new Error(`Passwortdatei gehoert uid ${st.uid}, erwartet 1000.`);
const t = fs.readFileSync(PASSFILE, 'utf8').trim();
const idx = t.indexOf(':');
if (idx <= 0) throw new Error('Passwortdatei hat ungueltiges Format (user:pass).');
cachedAuth = { user: t.slice(0, idx), pass: t.slice(idx + 1) };
return cachedAuth;
}
function request(method, path, body) {
return new Promise((resolve, reject) => {
const auth = readAuth();
const data = body === undefined ? undefined : JSON.stringify(body);
const timeout = setTimeout(() => { r.destroy(new Error('Timeout')); }, TIMEOUT_MS);
const r = https.request({
hostname: URL.replace(/^https:\/\//, ''),
port: 443,
path,
method,
rejectUnauthorized: !TLS_INSECURE,
headers: {
Authorization: 'Basic ' + Buffer.from(`${auth.user}:${auth.pass}`).toString('base64'),
Accept: 'application/json',
...(data ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) } : {}),
},
}, (res) => {
let s = '';
res.on('data', (c) => { s += c; });
res.on('end', () => {
clearTimeout(timeout);
let j = null;
try { j = JSON.parse(s); } catch (e) { /* non-JSON */ }
resolve({ status: res.statusCode, json: j });
});
});
r.on('error', (e) => { clearTimeout(timeout); reject(e); });
if (data) r.write(data);
r.end();
});
}
function enc(p) { return encodeURIComponent(p); }
async function getDoc(id) {
const r = await request('GET', `/${DB}/${enc(id)}`);
if (r.status === 404) return null;
if (r.status < 200 || r.status >= 300) throw new Error(`GET ${id}: ${r.status}`);
return r.json;
}
async function allDocs() {
const r = await request('GET', `/${DB}/_all_docs?include_docs=true`);
const rows = r.json && r.json.rows ? r.json.rows.map((x) => x.doc) : [];
return rows.filter((d) => d && d._id && !d._deleted);
}
function isFileMeta(d) {
return Boolean(d && d.path && !d._deleted && (d.type === 'plain' || d.type === 'newnote') && typeof d.children === 'object');
}
async function findMeta(path) {
const docs = await allDocs();
return docs.find((d) => isFileMeta(d) && d.path === path) ||
docs.find((d) => isFileMeta(d) && String(d.path).toLowerCase() === String(path).toLowerCase());
}
async function getManipulator() {
if (manipulatorPromise) return manipulatorPromise;
manipulatorPromise = (async () => {
const milestone = await request('GET', `/${DB}/${enc('_local/obsydian_livesync_milestone')}`);
const preferred = milestone.json && milestone.json.tweak_values && milestone.json.tweak_values.PREFERRED;
if (!preferred) throw new Error('LiveSync-PREFERRED-Einstellungen fehlen im Milestone-Dokument.');
if (preferred.encrypt || preferred.usePathObfuscation || preferred.enableCompression) {
throw new Error('Verschluesselung, Pfadverschleierung oder Kompression ist aktiv; Schreiben wird sicherheitshalber verweigert.');
}
const { DirectFileManipulator } = await import(pathToFileURL(COMMONLIB).href);
const auth = readAuth();
const client = new DirectFileManipulator({
url: URL,
username: auth.user,
password: auth.pass,
database: DB,
passphrase: undefined,
obfuscatePassphrase: undefined,
idDerivationVersion: preferred.idDerivationVersion ?? 0,
encryptInternalMetadata: preferred.encryptInternalMetadata ?? false,
useDynamicIterationCount: preferred.useDynamicIterationCount ?? false,
customChunkSize: preferred.customChunkSize ?? 0,
minimumChunkSize: preferred.minimumChunkSize ?? 20,
hashAlg: preferred.hashAlg || 'xxhash64',
useEden: preferred.useEden ?? false,
maxChunksInEden: preferred.maxChunksInEden ?? 10,
maxTotalLengthInEden: preferred.maxTotalLengthInEden ?? 1024,
maxAgeInEden: preferred.maxAgeInEden ?? 10,
enableCompression: false,
handleFilenameCaseSensitive: preferred.handleFilenameCaseSensitive ?? false,
chunkSplitterVersion: preferred.chunkSplitterVersion || 'v3-rabin-karp',
E2EEAlgorithm: preferred.E2EEAlgorithm || 'v2',
});
await client.ready.promise;
return client;
})();
return manipulatorPromise;
}
function fmtTime(ms) {
if (!ms) return '-';
return new Date(ms).toISOString().replace('T', ' ').replace('Z', 'UTC').slice(0, 19);
}
function fmtBytes(n) {
if (n >= 1024 * 1024) return (n / 1048576).toFixed(2) + ' MiB';
if (n >= 1024) return (n / 1024).toFixed(1) + ' KiB';
return n + ' B';
}
/* ---------- Werkzeuge ---------- */
async function status() {
const u = await request('GET', '/');
const db = await request('GET', `/${DB}`);
return {
error: false,
text: [
'## Obsidian / LiveSync (CouchDB)',
'',
`- Server: ${URL} (CouchDB ${u.json && u.json.version ? u.json.version : '?'})`,
`- Datenbank: ${DB} (Dokumente: ${db.json ? db.json.doc_count : '?'})`,
`- Konto: ${readAuth().user}`,
'',
'Haupt-Dokumentationsbereich (Jarvis) — Markdown-Notizen, syncen per LiveSync zu allen Obsidian-Geraeten.',
].join('\n'),
};
}
async function listNotes(args) {
const docs = await allDocs();
const files = docs.filter(isFileMeta)
.map((d) => ({ path: d.path, size: d.size || 0, mtime: d.mtime || 0, type: d.type === 'newnote' ? 'binar' : 'text', chunks: Array.isArray(d.children) ? d.children.length : 0 }))
.sort((a, b) => a.path.localeCompare(b.path));
const prefix = args && args.prefix ? String(args.prefix) : '';
const filtered = prefix ? files.filter((f) => f.path.toLowerCase().startsWith(prefix.toLowerCase())) : files;
const limit = Math.min(1000, Math.max(1, Number((args && args.limit) || 200)));
const shown = filtered.slice(0, limit);
const totalBytes = filtered.reduce((s, f) => s + (f.size || 0), 0);
const lines = [
'## Obsidian-Notizen',
'',
`Dateien: ${filtered.length} (${fmtBytes(totalBytes)})${filtered.length > shown.length ? ', angezeigt ' + shown.length : ''}`,
'',
'| Pfad | Groesse | Geaendert | Chunks |',
'|---|---|---|---|',
];
for (const f of shown) {
lines.push(`| ${f.path.replace(/\|/g, '\\|')} | ${fmtBytes(f.size)} | ${fmtTime(f.mtime)} | ${f.chunks} |`);
}
if (!shown.length) lines.push('| (keine Notizen) |');
return { error: false, text: lines.join('\n') };
}
async function readNote(args) {
const path = String((args && args.path) || '').trim();
if (!path) return { error: true, text: 'Pfad fehlt.' };
const meta = await findMeta(path);
if (!meta) return { error: true, text: `Notiz nicht gefunden: ${path}` };
const chunks = [];
for (const id of meta.children || []) {
const c = await getDoc(id);
if (!c) throw new Error(`Chunk ${id} von ${path} fehlt.`);
chunks.push(c.data || '');
}
let content = chunks.join('');
if (meta.type === 'newnote') content = Buffer.from(content, 'base64').toString('utf8');
if (content.length > 60000) content = content.slice(0, 60000) + '\n\n… (gekuerzt)';
return {
error: false,
text: [
`## ${path}`,
'',
`_${fmtTime(meta.mtime)}, ${fmtBytes(meta.size)}_`,
'',
content,
].join('\n'),
};
}
async function writeNote(args) {
const path = String((args && args.path) || '').trim();
const content = String((args && args.content) === undefined ? '' : args.content);
if (!path) return { error: true, text: 'Pfad fehlt (z. B. "Doku/Projekt.md").' };
if (!path.toLowerCase().endsWith('.md')) return { error: true, text: 'Schreiben ist auf Markdown-Notizen (.md) begrenzt.' };
const existing = await findMeta(path);
const now = Date.now();
const size = Buffer.byteLength(content, 'utf8');
const client = await getManipulator();
const ok = await client.put(path, new Blob([content], { type: 'text/plain' }), {
ctime: existing ? existing.ctime : now,
mtime: now,
size,
}, 'plain');
if (!ok) throw new Error(`LiveSync-Commonlib konnte ${path} nicht speichern.`);
const saved = await findMeta(path);
if (!saved) throw new Error(`Gespeicherte Metadata fuer ${path} nicht gefunden.`);
return {
error: false,
text: `## Gespeichert: ${path}\n\n- Dokument: ${saved._id}\n- Groesse: ${fmtBytes(size)} (${saved.children.length} Chunk(s))\n- Zeit: ${fmtTime(now)}\n- Writer: LiveSync Commonlib 0.1.36\n\n${content.length > 400 ? content.slice(0, 400) + '\n…' : content}`,
};
}
async function deleteNote(args) {
const path = String((args && args.path) || '').trim();
if (!path) return { error: true, text: 'Pfad fehlt.' };
const meta = await findMeta(path);
if (!meta) return { error: true, text: `Notiz nicht gefunden: ${path}` };
const client = await getManipulator();
const ok = await client.delete(path);
if (!ok) throw new Error(`LiveSync-Commonlib konnte ${path} nicht loeschen.`);
return { error: false, text: `## Geloescht: ${path}\n\n(LiveSync-konforme Loeschung ueber Commonlib; Chunks bleiben fuer Sync/GC erhalten.)` };
}
async function searchNotes(args) {
const text = String((args && args.text) || '').trim().toLowerCase();
const limit = Math.min(50, Math.max(1, Number((args && args.limit) || 10)));
if (!text) return { error: true, text: 'Suchtext fehlt.' };
const docs = await allDocs();
const files = docs.filter(isFileMeta);
const hits = [];
outer:
for (const meta of files) {
if (hits.length >= limit) break;
const chunks = [];
for (const id of meta.children || []) {
const c = await getDoc(id);
if (c) chunks.push(c.data || '');
}
let content = chunks.join('');
if (meta.type === 'newnote') content = Buffer.from(content, 'base64').toString('utf8');
const idx = content.toLowerCase().indexOf(text);
if (idx >= 0) {
const start = Math.max(0, idx - 60);
const snippet = (start > 0 ? '…' : '') + content.slice(start, idx + text.length + 120).replace(/\n+/g, ' ').replace(/\|/g, '\\|');
hits.push({ path: meta.path, snippet });
}
}
const lines = [
`## Suche: ${(args && args.text)}`,
'',
`Treffer: ${hits.length}${hits.length >= limit ? ' (Limit)' : ''}`,
'',
...hits.map((h) => `- **${h.path}**: ${h.snippet}`),
];
if (!hits.length) lines.push('(keine Treffer)');
return { error: false, text: lines.join('\n') };
}
const TOOLS = [
{
name: 'obsidian_status',
description: 'Zeigt Server- und Vaultzustand (CouchDB-Version, Datenbank, Dokumentanzahl, Konto). Lesend.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'obsidian_list_notes',
description: 'Listet Obsidian-Notizen (Pfad, Groesse, Aenderungszeit, Chunk-Anzahl), optional gefiltert nach Pfad-Praefix. Lesend.',
inputSchema: {
type: 'object',
properties: {
prefix: { type: 'string', description: 'Nur Notizen unter diesem Pfad-Praefix, z. B. "Doku/".' },
limit: { type: 'integer', description: 'Max. Zeilen (1-1000, Standard 200).' },
},
additionalProperties: false,
},
},
{
name: 'obsidian_read_note',
description: 'Liest eine Obsidian-Notiz vollstaendig (Markdown) anhand ihres Pfads, z. B. "Projekt/X.md". Lesend.',
inputSchema: {
type: 'object',
properties: {
path: { type: 'string', description: 'Vault-Pfad der Notiz (inkl. .md).' },
},
required: ['path'],
additionalProperties: false,
},
},
{
name: 'obsidian_search_notes',
description: 'Durchsucht Notizinhalte nach einem Text (Gross-/Kleinschreibung egal) und liefert Pfad + Trefferschnipsel. Lesend.',
inputSchema: {
type: 'object',
properties: {
text: { type: 'string', description: 'Suchtext.' },
limit: { type: 'integer', description: 'Max. Treffer (1-50, Standard 10).' },
},
required: ['text'],
additionalProperties: false,
},
},
{
name: 'obsidian_write_note',
description:
'Legt eine Notiz an oder ueberschreibt sie (Markdown) unter dem angegebenen Pfad — Jarvis\' Haupt-Dokumentation. Inhalt wird als Chunk-Dokumente schema-konform im LiveSync-Vault gespeichert. SCHREIBEND.',
inputSchema: {
type: 'object',
properties: {
path: { type: 'string', description: 'Vault-Pfad, z. B. "Doku/Projekt.md".' },
content: { type: 'string', description: 'Markdown-Inhalt (ueberschreibt die Notiz).' },
},
required: ['path', 'content'],
additionalProperties: false,
},
},
{
name: 'obsidian_delete_note',
description: 'Loescht eine Obsidian-Notiz (Pfad). Vorher mit obsidian_read_note bestaetigen. SCHREIBEND, destruktiv.',
inputSchema: {
type: 'object',
properties: {
path: { type: 'string', description: 'Vault-Pfad der zu loeschenden Notiz.' },
},
required: ['path'],
additionalProperties: false,
},
},
];
/* ---------- MCP-Rahmen (wie bitwarden.js) ---------- */
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) {
replyError(null, -32700, 'Parse error');
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: 'obsidian', 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: /^obsidian_(status|list_notes|read_note|search_notes)$/.test(name),
destructiveHint: name === 'obsidian_delete_note',
idempotentHint: name !== 'obsidian_delete_note',
openWorldHint: true,
},
})),
});
return;
}
if (method === 'tools/call') {
const name = params && params.name;
const args = (params && params.arguments) || {};
const dispatch = {
obsidian_status: () => status(),
obsidian_list_notes: () => listNotes(args),
obsidian_read_note: () => readNote(args),
obsidian_search_notes: () => searchNotes(args),
obsidian_write_note: () => writeNote(args),
obsidian_delete_note: () => deleteNote(args),
};
const fn = dispatch[name];
if (!fn) {
reply(id, { content: [{ type: 'text', text: `Unbekanntes oder nicht freigegebenes Werkzeug: ${name}` }], isError: true });
return;
}
fn()
.then((r) => {
if (r.error) reply(id, { content: [{ type: 'text', text: r.text }], isError: true });
else reply(id, { content: [{ type: 'text', text: r.text }], isError: false });
})
.catch((e) => reply(id, { content: [{ type: 'text', text: `Interner Fehler: ${e.message || e}` }], isError: true }));
return;
}
replyError(id, -32601, 'Method not found');
}
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env node
"use strict";
const fs = require("node:fs");
const path = require("node:path");
const { execFileSync } = require("node:child_process");
const HOME = process.env.OPENCLAW_STATE_DIR || "/home/node/.openclaw";
const CONFIG = path.join(HOME, "openclaw.json");
const BACKUPS = path.join(HOME, "self-edit", "backups");
function result(text, error = false) {
return { text: typeof text === "string" ? text : JSON.stringify(text, null, 2), error };
}
function diagnosticsConfigAudit() {
try {
const raw = fs.readFileSync(CONFIG, "utf8");
const parsed = JSON.parse(raw);
const agentCount = Object.keys(parsed.agents?.entries || {}).length;
const mcpCount = Object.keys(parsed.mcp?.servers || parsed.mcpServers || {}).length;
let validateOutput = "OK";
try {
validateOutput = execFileSync("openclaw", ["config", "validate"], {
env: process.env,
timeout: 15000,
stdio: ["ignore", "pipe", "pipe"]
}).toString("utf8").trim();
} catch (e) {
validateOutput = String(e.stderr || e.message || e);
}
return result({
config_path: CONFIG,
config_size_bytes: raw.length,
agents_configured: agentCount,
mcp_servers_configured: mcpCount,
validation_result: validateOutput
});
} catch (err) {
return result(`Config-Audit fehlgeschlagen: ${err.message}`, true);
}
}
function diagnosticsBackupHistory() {
try {
let files = [];
if (fs.existsSync(BACKUPS)) {
files = fs.readdirSync(BACKUPS).map(f => {
const full = path.join(BACKUPS, f);
const stat = fs.statSync(full);
return { name: f, size_bytes: stat.size, mtime: stat.mtime };
});
}
const rootBackups = fs.readdirSync(HOME).filter(f => f.startsWith("openclaw.json.bak")).map(f => {
const full = path.join(HOME, f);
const stat = fs.statSync(full);
return { name: f, size_bytes: stat.size, mtime: stat.mtime };
});
return result({
self_edit_backups: files.slice(-10),
root_backups: rootBackups.slice(-10)
});
} catch (err) {
return result(`Backup-History konnte nicht gelesen werden: ${err.message}`, true);
}
}
function diagnosticsSystemSummary() {
try {
const memory = process.memoryUsage();
return result({
node_version: process.version,
platform: process.platform,
arch: process.arch,
uptime_seconds: Math.round(process.uptime()),
memory_heap_used_mb: Math.round(memory.heapUsed / 1024 / 1024),
memory_heap_total_mb: Math.round(memory.heapTotal / 1024 / 1024),
rss_mb: Math.round(memory.rss / 1024 / 1024)
});
} catch (err) {
return result(`System-Summary fehlgeschlagen: ${err.message}`, true);
}
}
const TOOLS = [
{ name: "diagnostics_config_audit", description: "Auditiert die aktuelle OpenClaw-Konfiguration, Agenten und MCP-Server. Lesend.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
{ name: "diagnostics_backup_history", description: "Listet vorhandene Konfigurations-Backups und Revisionshistorie auf. Lesend.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
{ name: "diagnostics_system_summary", description: "Liefert eine Laufzeit- und Speicherübersicht des Node.js-Prozesses. Lesend.", inputSchema: { type: "object", properties: {}, additionalProperties: false } }
];
function call(name, args) {
try {
if (name === "diagnostics_config_audit") return diagnosticsConfigAudit();
if (name === "diagnostics_backup_history") return diagnosticsBackupHistory();
if (name === "diagnostics_system_summary") return diagnosticsSystemSummary();
return result("Unbekanntes Werkzeug.", true);
} catch (err) {
return result(String(err.message || err), true);
}
}
function send(id, value) { process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result: value }) + "\n"); }
function reply(id, value) { send(id, { content: [{ type: "text", text: value.text }], isError: value.error }); }
let buffer = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
buffer += chunk;
let end;
while ((end = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, end).trim();
buffer = buffer.slice(end + 1);
if (!line) continue;
let message;
try { message = JSON.parse(line); } catch { continue; }
if (message.method === "initialize") send(message.id, { protocolVersion: message.params?.protocolVersion || "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "openclaw-diagnostics", version: "1.0.0" } });
else if (message.method === "tools/list") send(message.id, { tools: TOOLS });
else if (message.method === "tools/call") reply(message.id, call(message.params?.name, message.params?.arguments || {}));
}
});
+237
View File
@@ -0,0 +1,237 @@
#!/usr/bin/env node
// Session-gated OpenClaw configuration editor. No arbitrary shell or target paths.
"use strict";
const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");
const { execFileSync } = require("node:child_process");
const HOME = process.env.OPENCLAW_STATE_DIR || "/home/node/.openclaw";
const CONFIG = path.join(HOME, "openclaw.json");
const LEASE = process.env.JARVIS_SELF_EDIT_LEASE || "/run/jarvis-self-edit/self-edit-lease.json";
const PROJECTS = "/home/node/.openclaw/workspaces/jarvis/projects";
const GENERATED_MCP = path.join(HOME, "mcp", "generated");
const BACKUPS = path.join(HOME, "self-edit", "backups");
const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
const MODEL = /^[a-z0-9_-]+\/[A-Za-z0-9._:/-]{1,160}$/i;
function result(text, error = false) { return { text, error }; }
function revision(raw) { return crypto.createHash("sha256").update(raw).digest("hex"); }
function load() {
const raw = fs.readFileSync(CONFIG, "utf8");
return { raw, config: JSON.parse(raw), revision: revision(raw) };
}
function activeLease(token) {
try {
const lease = JSON.parse(fs.readFileSync(LEASE, "utf8"));
if (lease.mode !== "self-edit" || lease.expiresAt <= Date.now()) return null;
const left = Buffer.from(String(lease.token || ""));
const right = Buffer.from(String(token || ""));
if (left.length !== right.length || !crypto.timingSafeEqual(left, right)) return null;
return lease;
} catch { return null; }
}
function mutationGuard(args, current) {
if (args.confirm !== true) return "Aenderung benoetigt confirm=true.";
if (!activeLease(args.lease)) return "Self-Edit-Lease fehlt, ist ungueltig oder abgelaufen.";
if (args.expected_revision !== current.revision) return "Konfiguration wurde zwischenzeitlich geaendert. Bitte neu auflisten und mit der aktuellen Revision erneut versuchen.";
return null;
}
function validateCandidate(file) {
try {
return execFileSync("openclaw", ["config", "validate"], {
env: { ...process.env, OPENCLAW_CONFIG_PATH: file },
timeout: 120_000,
stdio: ["ignore", "pipe", "pipe"],
}).toString("utf8").trim();
} catch (error) {
throw new Error(String(error.stderr || error.message || error).slice(0, 2000));
}
}
function applyConfig(args, mutate, summary) {
const current = load();
const blocked = mutationGuard(args, current);
if (blocked) return result(blocked, true);
const next = structuredClone(current.config);
mutate(next);
const text = JSON.stringify(next, null, 2) + "\n";
const dir = path.dirname(CONFIG);
const candidate = path.join(dir, `.openclaw.self-edit-${crypto.randomUUID()}.json`);
fs.mkdirSync(BACKUPS, { recursive: true, mode: 0o700 });
fs.writeFileSync(candidate, text, { mode: 0o600, flag: "wx" });
try {
validateCandidate(candidate);
const latest = fs.readFileSync(CONFIG, "utf8");
if (revision(latest) !== current.revision) throw new Error("Konfiguration wurde waehrend der Validierung geaendert.");
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
fs.writeFileSync(path.join(BACKUPS, `${stamp}-${current.revision.slice(0, 12)}.json`), current.raw, { mode: 0o600, flag: "wx" });
fs.renameSync(candidate, CONFIG);
return result(`${summary}\nNeue Revision: ${revision(text)}\nBackup wurde erstellt; OpenClaw kann die validierte Konfiguration neu laden.`);
} catch (error) {
try { fs.rmSync(candidate, { force: true }); } catch {}
return result(`Aenderung nicht angewendet: ${String(error.message || error)}`, true);
}
}
function modelValue(primary, fallbacks) {
if (!MODEL.test(String(primary || ""))) throw new Error("Ungueltige Modell-ID. Erwartet wird provider/model.");
const list = Array.isArray(fallbacks) ? fallbacks.map(String) : [];
if (list.length > 5 || list.some((x) => !MODEL.test(x))) throw new Error("Ungueltige Fallback-Modellliste.");
return { primary: String(primary), fallbacks: [...new Set(list)] };
}
function listAgents() {
try {
const current = load();
const entries = current.config.agents?.entries || {};
const agents = Object.entries(entries).map(([id, a]) => ({ id, name: a.name || id, model: a.model || current.config.agents?.defaults?.model, toolProfile: a.tools?.profile || "inherit" }));
return result(JSON.stringify({ revision: current.revision, agents }, null, 2));
} catch (error) { return result(`Agenten konnten nicht gelesen werden: ${error.message}`, true); }
}
function addAgent(args) {
if (!ID.test(String(args.id || ""))) return result("Ungueltige Agent-ID.", true);
const name = String(args.name || "").trim().slice(0, 80);
const purpose = String(args.purpose || "").trim().slice(0, 2000);
if (!name || !purpose) return result("Name und Aufgabe sind erforderlich.", true);
const profile = ["minimal", "coding", "messaging"].includes(args.tool_profile) ? args.tool_profile : "minimal";
const workspace = path.join(HOME, "workspaces", args.id);
if (fs.existsSync(workspace)) return result("Der Agent-Workspace existiert bereits; er wird nicht ueberschrieben.", true);
try {
const model = args.primary_model ? modelValue(args.primary_model, args.fallback_models) : undefined;
const applied = applyConfig(args, (cfg) => {
cfg.agents ||= {};
cfg.agents.entries ||= {};
if (cfg.agents.entries[args.id]) throw new Error("Agent existiert bereits.");
cfg.agents.entries[args.id] = {
name,
workspace: `/home/node/.openclaw/workspaces/${args.id}`,
agentDir: `/home/node/.openclaw/agents/${args.id}/agent`,
...(model ? { model } : {}),
tools: { profile },
};
}, `Agent ${args.id} wurde angelegt.`);
if (!applied.error) {
fs.mkdirSync(workspace, { recursive: true, mode: 0o700 });
const guide = `# ${name}\n\n## Aufgabe\n\n${purpose}\n\n## Grenzen\n\n- Arbeite nur an explizit delegierten Aufgaben.\n- Gib keine Zugangsdaten aus.\n- Produktive oder destruktive Aenderungen benoetigen eine ausdrueckliche Freigabe.\n`;
fs.writeFileSync(path.join(workspace, "AGENTS.md"), guide, { mode: 0o600, flag: "wx" });
}
return applied;
} catch (error) { return result(String(error.message || error), true); }
}
function changeModel(args) {
if (!ID.test(String(args.id || ""))) return result("Ungueltige Agent-ID.", true);
try {
const model = modelValue(args.primary_model, args.fallback_models);
return applyConfig(args, (cfg) => {
const agent = cfg.agents?.entries?.[args.id];
if (!agent) throw new Error("Agent nicht gefunden.");
agent.model = model;
}, `Modell fuer ${args.id} wurde auf ${model.primary} gesetzt.`);
} catch (error) { return result(String(error.message || error), true); }
}
function listMcp() {
try {
const current = load();
const servers = Object.entries(current.config.mcp?.servers || {}).map(([id, s]) => ({ id, enabled: s.enabled !== false, transport: s.transport || "stdio", tools: s.toolFilter?.include || [] }));
return result(JSON.stringify({ revision: current.revision, servers }, null, 2));
} catch (error) { return result(`MCP-Server konnten nicht gelesen werden: ${error.message}`, true); }
}
function installMcp(args) {
if (!ID.test(String(args.id || ""))) return result("Ungueltige MCP-ID.", true);
let source;
try {
const projectsReal = fs.realpathSync(PROJECTS);
source = fs.realpathSync(path.resolve(PROJECTS, String(args.source_file || "")));
if (!source.startsWith(`${projectsReal}${path.sep}`)) return result("Quelle muss unter projects/ liegen.", true);
} catch { return result("MCP-Quelldatei nicht gefunden.", true); }
if (path.extname(source) !== ".js") return result("Quelle muss eine .js-Datei unter projects/ sein.", true);
let stat;
try { stat = fs.lstatSync(source); } catch { return result("MCP-Quelldatei nicht gefunden.", true); }
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 512 * 1024) return result("MCP-Quelle muss eine regulaere Datei bis 512 KiB sein.", true);
const tools = Array.isArray(args.tools) ? [...new Set(args.tools.map(String))] : [];
if (!tools.length || tools.length > 100 || tools.some((x) => !/^[a-z][a-z0-9_-]{0,127}$/.test(x))) return result("Mindestens ein gueltiger Tool-Name ist erforderlich.", true);
const target = path.join(GENERATED_MCP, `${args.id}.js`);
if (fs.existsSync(target)) return result("Ein generierter MCP-Server mit dieser ID existiert bereits.", true);
const current = load();
const blocked = mutationGuard(args, current);
if (blocked) return result(blocked, true);
fs.mkdirSync(GENERATED_MCP, { recursive: true, mode: 0o700 });
fs.copyFileSync(source, target, fs.constants.COPYFILE_EXCL);
fs.chmodSync(target, 0o700);
const applied = applyConfig(args, (cfg) => {
cfg.mcp ||= {};
cfg.mcp.servers ||= {};
if (cfg.mcp.servers[args.id]) throw new Error("MCP-Server existiert bereits in der Konfiguration.");
cfg.mcp.servers[args.id] = { enabled: true, command: "node", args: [target], transport: "stdio", toolFilter: { include: tools }, connectionTimeoutMs: 30000, requestTimeoutMs: 120000, supportsParallelToolCalls: false };
}, `MCP-Server ${args.id} wurde installiert und registriert.`);
if (applied.error) try { fs.rmSync(target, { force: true }); } catch {}
return applied;
}
function editConfig(args) {
const allowed = {
"agents.defaults.userTimezone": (v) => typeof v === "string" && /^[A-Za-z_]+\/[A-Za-z_+-]+$/.test(v),
"agents.defaults.timeoutSeconds": (v) => Number.isInteger(v) && v >= 30 && v <= 1800,
"agents.defaults.maxConcurrent": (v) => Number.isInteger(v) && v >= 1 && v <= 8,
"tools.web.search.enabled": (v) => typeof v === "boolean",
"tools.web.search.maxResults": (v) => Number.isInteger(v) && v >= 1 && v <= 20,
"gateway.reload.mode": (v) => ["off", "hot", "restart", "hybrid"].includes(v),
};
const changes = Array.isArray(args.changes) ? args.changes : [];
if (!changes.length || changes.length > 20) return result("Zwischen 1 und 20 Aenderungen sind erforderlich.", true);
for (const change of changes) if (!allowed[change.field]?.(change.value)) return result(`Nicht erlaubtes oder ungueltiges Feld: ${change.field}`, true);
return applyConfig(args, (cfg) => {
for (const change of changes) {
const parts = change.field.split(".");
let node = cfg;
for (const part of parts.slice(0, -1)) node = node[part] ||= {};
node[parts.at(-1)] = change.value;
}
}, `${changes.length} freigegebene Konfigurationsaenderung(en) wurden angewendet.`);
}
function validateCurrent() {
try { return result(`${validateCandidate(CONFIG)}\nRevision: ${load().revision}`); }
catch (error) { return result(`Konfiguration ist ungueltig: ${error.message}`, true); }
}
const commonMutation = {
lease: { type: "string" }, expected_revision: { type: "string", pattern: "^[a-f0-9]{64}$" }, confirm: { type: "boolean" },
};
const TOOLS = [
{ name: "list_agents", description: "Listet OpenClaw-Agenten und die aktuelle Konfigurationsrevision. Lesend.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
{ name: "add_agent", description: "Legt im aktiven Self-Edit-Modus nach Bestaetigung einen neuen Spezialagenten mit eigenem Workspace an.", inputSchema: { type: "object", properties: { ...commonMutation, id: { type: "string" }, name: { type: "string" }, purpose: { type: "string" }, tool_profile: { type: "string", enum: ["minimal", "coding", "messaging"] }, primary_model: { type: "string" }, fallback_models: { type: "array", items: { type: "string" } } }, required: ["lease", "expected_revision", "confirm", "id", "name", "purpose"], additionalProperties: false } },
{ name: "change_agent_model", description: "Aendert nach Bestaetigung das Modell eines vorhandenen Agenten.", inputSchema: { type: "object", properties: { ...commonMutation, id: { type: "string" }, primary_model: { type: "string" }, fallback_models: { type: "array", items: { type: "string" } } }, required: ["lease", "expected_revision", "confirm", "id", "primary_model"], additionalProperties: false } },
{ name: "list_mcp_servers", description: "Listet registrierte MCP-Server ohne Secrets und die aktuelle Revision. Lesend.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
{ name: "install_mcp_server", description: "Installiert nach Bestaetigung eine gepruefte JavaScript-MCP-Datei aus dem Jarvis-Projektbereich und registriert nur angegebene Tools.", inputSchema: { type: "object", properties: { ...commonMutation, id: { type: "string" }, source_file: { type: "string" }, tools: { type: "array", items: { type: "string" } } }, required: ["lease", "expected_revision", "confirm", "id", "source_file", "tools"], additionalProperties: false } },
{ name: "edit_config", description: "Aendert nach Bestaetigung ausschliesslich freigegebene, begrenzte OpenClaw-Konfigurationsfelder.", inputSchema: { type: "object", properties: { ...commonMutation, changes: { type: "array", items: { type: "object", properties: { field: { type: "string" }, value: {} }, required: ["field", "value"], additionalProperties: false } } }, required: ["lease", "expected_revision", "confirm", "changes"], additionalProperties: false } },
{ name: "validate_config", description: "Validiert die aktuelle OpenClaw-Konfiguration. Lesend.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
];
function call(name, args) {
try {
if (name === "list_agents") return listAgents();
if (name === "add_agent") return addAgent(args);
if (name === "change_agent_model") return changeModel(args);
if (name === "list_mcp_servers") return listMcp();
if (name === "install_mcp_server") return installMcp(args);
if (name === "edit_config") return editConfig(args);
if (name === "validate_config") return validateCurrent();
return result("Unbekanntes Werkzeug.", true);
} catch (error) { return result(String(error.message || error).slice(0, 2000), true); }
}
function send(id, value) { process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result: value }) + "\n"); }
function reply(id, value) { send(id, { content: [{ type: "text", text: value.text }], isError: value.error }); }
let buffer = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
buffer += chunk;
let end;
while ((end = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, end).trim();
buffer = buffer.slice(end + 1);
if (!line) continue;
let message;
try { message = JSON.parse(line); } catch { continue; }
if (message.method === "initialize") send(message.id, { protocolVersion: message.params?.protocolVersion || "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "openclaw-self-edit", version: "1.0.0" } });
else if (message.method === "tools/list") send(message.id, { tools: TOOLS });
else if (message.method === "tools/call") reply(message.id, call(message.params?.name, message.params?.arguments || {}));
}
});
+232
View File
@@ -0,0 +1,232 @@
#!/usr/bin/env node
/** Read-only MCP server for the local OPNsense API. */
'use strict';
const fs = require('fs');
const https = require('https');
const BASE = new URL(process.env.OPNSENSE_URL || 'https://YOUR_FIREWALL_IP');
const CREDENTIALS_FILE = process.env.OPNSENSE_CREDENTIALS_FILE || '/home/node/.openclaw/mcp/.opnsense-credentials';
const CERT_SHA256 = normalizeFingerprint(process.env.OPNSENSE_CERT_SHA256 || '');
const TIMEOUT_MS = 15000;
const MAX_ROWS = 500;
let cachedAuth = null;
function normalizeFingerprint(value) {
return String(value).replace(/[^a-fA-F0-9]/g, '').toUpperCase();
}
function readAuth() {
if (cachedAuth) return cachedAuth;
let st;
try { st = fs.statSync(CREDENTIALS_FILE); } catch { throw new Error(`Credential-Datei nicht lesbar: ${CREDENTIALS_FILE}`); }
if ((st.mode & 0o077) !== 0) throw new Error(`Credential-Datei ist nicht restriktiv (Modus ${st.mode & 0o777}).`);
if (st.uid !== 1000) throw new Error(`Credential-Datei gehoert uid ${st.uid}, erwartet 1000.`);
const lines = fs.readFileSync(CREDENTIALS_FILE, 'utf8').split(/\r?\n/).map((x) => x.trim()).filter(Boolean);
if (lines.length !== 2) throw new Error('Credential-Datei muss genau API-Key und API-Secret enthalten.');
cachedAuth = { key: lines[0], secret: lines[1] };
return cachedAuth;
}
function api(path) {
return new Promise((resolve, reject) => {
const auth = readAuth();
let settled = false;
const finish = (fn, value) => {
if (settled) return;
settled = true;
fn(value);
};
const req = https.request({
protocol: BASE.protocol,
hostname: BASE.hostname,
port: BASE.port || 443,
path,
method: 'GET',
rejectUnauthorized: false,
agent: false,
headers: {
Authorization: 'Basic ' + Buffer.from(`${auth.key}:${auth.secret}`).toString('base64'),
Accept: 'application/json',
},
}, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
body += chunk;
if (body.length > 8 * 1024 * 1024) req.destroy(new Error('OPNsense-Antwort ist zu gross.'));
});
res.on('end', () => {
if (res.statusCode < 200 || res.statusCode >= 300) {
finish(reject, new Error(`OPNsense API antwortete mit HTTP ${res.statusCode}.`));
return;
}
try { finish(resolve, JSON.parse(body)); } catch { finish(reject, new Error('OPNsense API lieferte kein gueltiges JSON.')); }
});
});
req.setTimeout(TIMEOUT_MS, () => req.destroy(new Error('OPNsense API Timeout.')));
req.on('socket', (socket) => {
socket.once('secureConnect', () => {
const actual = normalizeFingerprint((socket.getPeerCertificate() || {}).fingerprint256 || '');
if (!CERT_SHA256) req.destroy(new Error('Kein OPNsense-Zertifikat-Fingerprint konfiguriert.'));
else if (actual !== CERT_SHA256) req.destroy(new Error('OPNsense-Zertifikat stimmt nicht mit dem konfigurierten Fingerprint ueberein.'));
});
});
req.on('error', (error) => finish(reject, error));
req.end();
});
}
function escapeCell(value) {
return String(value ?? '-').replace(/\r?\n/g, ', ').replace(/\|/g, '\\|');
}
function yesNo(value) {
return value === true || value === 1 || value === '1' ? 'ja' : 'nein';
}
async function status() {
const [system, services, interfaces, gateways] = await Promise.all([
api('/api/core/system/status'),
api('/api/core/service/search'),
api('/api/interfaces/overview/interfacesInfo'),
api('/api/routes/gateway/status'),
]);
const serviceRows = services.rows || [];
const interfaceRows = interfaces.rows || [];
const gatewayRows = gateways.items || [];
const message = system.metadata && system.metadata.system ? system.metadata.system.message : 'unbekannt';
return [
'## OPNsense Status', '',
`- API: ${BASE.origin}`,
`- System: ${message}`,
`- Dienste: ${serviceRows.filter((x) => Number(x.running) === 1).length}/${serviceRows.length} laufen`,
`- Interfaces: ${interfaceRows.filter((x) => x.status === 'up').length}/${interfaceRows.length} up`,
`- Gateways: ${gatewayRows.filter((x) => x.status_translated === 'Online').length}/${gatewayRows.length} online`,
'- Zugriff: read-only MCP; Zertifikat SHA-256-gepinnt',
].join('\n');
}
async function services(args) {
let rows = (await api('/api/core/service/search')).rows || [];
if (args && args.running_only) rows = rows.filter((x) => Number(x.running) === 1);
rows.sort((a, b) => String(a.name).localeCompare(String(b.name)));
const lines = ['## OPNsense Dienste', '', `Dienste: ${rows.length}`, '', '| Dienst | Beschreibung | Laeuft | Gesperrt |', '|---|---|---:|---:|'];
for (const row of rows) lines.push(`| ${escapeCell(row.name)} | ${escapeCell(row.description)} | ${yesNo(row.running)} | ${yesNo(row.locked)} |`);
return lines.join('\n');
}
async function interfaces(args) {
let rows = (await api('/api/interfaces/overview/interfacesInfo')).rows || [];
if (args && args.assigned_only) rows = rows.filter((x) => x.identifier);
rows.sort((a, b) => String(a.description).localeCompare(String(b.description)));
const lines = ['## OPNsense Interfaces', '', `Interfaces: ${rows.length}`, '', '| Name | Geraet | Status | IPv4 | IPv6 | MTU | Medium |', '|---|---|---|---|---|---:|---|'];
for (const row of rows) {
const ipv4 = (row.ipv4 || []).map((x) => x.ipaddr).join(', ') || '-';
const ipv6 = (row.ipv6 || []).map((x) => x.ipaddr).join(', ') || '-';
lines.push(`| ${escapeCell(row.description || row.identifier || 'Unassigned')} | ${escapeCell(row.device)} | ${escapeCell(row.status)} | ${escapeCell(ipv4)} | ${escapeCell(ipv6)} | ${escapeCell(row.mtu)} | ${escapeCell(row.media)} |`);
}
return lines.join('\n');
}
async function gateways() {
const data = await api('/api/routes/gateway/status');
const rows = data.items || [];
const lines = ['## OPNsense Gateways', '', `Status: ${data.status || '-'}, Gateways: ${rows.length}`, '', '| Name | Adresse | Status | Verlust | Latenz |', '|---|---|---|---:|---:|'];
for (const row of rows) lines.push(`| ${escapeCell(row.name)} | ${escapeCell(row.address)} | ${escapeCell(row.status_translated)} | ${escapeCell(row.loss)} | ${escapeCell(row.delay)} |`);
return lines.join('\n');
}
async function firewallRules(args) {
const params = new URLSearchParams({ current: '1', rowCount: String(MAX_ROWS) });
const search = String((args && args.search) || '').trim();
if (search) params.set('searchPhrase', search);
const data = await api('/api/firewall/filter/searchRule?' + params.toString());
const rows = data.rows || [];
const lines = [
'## OPNsense Automation-Firewallregeln', '',
`Regeln: ${data.total ?? rows.length}${search ? `, Filter: ${search}` : ''}`,
'',
'> Diese API zeigt nur Regeln aus Firewall > Automation, nicht zwingend alle klassischen GUI-Regeln.', '',
'| Beschreibung | Interface | Richtung | Aktion | Protokoll | Quelle | Ziel | Aktiv |',
'|---|---|---|---|---|---|---|---:|',
];
for (const row of rows) {
lines.push(`| ${escapeCell(row.description)} | ${escapeCell(row.interface)} | ${escapeCell(row.direction)} | ${escapeCell(row.action)} | ${escapeCell(row.protocol)} | ${escapeCell(row.source_net || row.source)} | ${escapeCell(row.destination_net || row.destination)} | ${yesNo(row.enabled)} |`);
}
if (!rows.length) lines.push('| (keine Automation-Regeln) | | | | | | | |');
return lines.join('\n');
}
async function aliases(args) {
const params = new URLSearchParams({ current: '1', rowCount: String(MAX_ROWS) });
const search = String((args && args.search) || '').trim();
if (search) params.set('searchPhrase', search);
const includeContent = Boolean(args && args.include_content);
const data = await api('/api/firewall/alias/searchItem?' + params.toString());
const rows = data.rows || [];
const lines = ['## OPNsense Aliase', '', `Aliase: ${data.total ?? rows.length}${search ? `, Filter: ${search}` : ''}`, '', includeContent ? '| Name | Typ | Aktiv | Inhalt |' : '| Name | Typ | Aktiv | Eintraege | Geaendert |', includeContent ? '|---|---|---:|---|' : '|---|---|---:|---:|---|'];
for (const row of rows) {
if (includeContent) lines.push(`| ${escapeCell(row.name)} | ${escapeCell(row['%type'] || row.type)} | ${yesNo(row.enabled)} | ${escapeCell(row.content || '-')} |`);
else lines.push(`| ${escapeCell(row.name)} | ${escapeCell(row['%type'] || row.type)} | ${yesNo(row.enabled)} | ${escapeCell(row.current_items || '-')} | ${escapeCell(row.last_updated || '-')} |`);
}
return lines.join('\n');
}
const TOOLS = [
{ name: 'opnsense_status', description: 'Kompakter Zustand von OPNsense, Diensten, Interfaces und Gateways. Lesend.', inputSchema: { type: 'object', properties: {}, additionalProperties: false } },
{ name: 'opnsense_services', description: 'Listet OPNsense-Dienste mit Lauf- und Sperrstatus. Lesend.', inputSchema: { type: 'object', properties: { running_only: { type: 'boolean', description: 'Nur laufende Dienste anzeigen.' } }, additionalProperties: false } },
{ name: 'opnsense_interfaces', description: 'Listet Interfaces mit Status, IP-Adressen, MTU und Medium. Lesend.', inputSchema: { type: 'object', properties: { assigned_only: { type: 'boolean', description: 'Nur zugewiesene Interfaces anzeigen.' } }, additionalProperties: false } },
{ name: 'opnsense_gateways', description: 'Listet Gateways mit Online-Status, Verlust und Latenz. Lesend.', inputSchema: { type: 'object', properties: {}, additionalProperties: false } },
{ name: 'opnsense_firewall_rules', description: 'Listet Regeln der OPNsense Firewall-Automation. Zeigt nicht zwingend klassische GUI-Regeln. Lesend.', inputSchema: { type: 'object', properties: { search: { type: 'string', description: 'Optionaler Suchtext.' } }, additionalProperties: false } },
{ name: 'opnsense_aliases', description: 'Listet Firewall-Aliase. Inhalte nur explizit mit include_content=true; Credential-Felder werden nie ausgegeben. Lesend.', inputSchema: { type: 'object', properties: { search: { type: 'string', description: 'Optionaler Suchtext.' }, include_content: { type: 'boolean', description: 'Alias-Inhalte anzeigen (Standard false).' } }, 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 buffer = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', (chunk) => {
buffer += chunk;
let index;
while ((index = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, index).trim();
buffer = buffer.slice(index + 1);
if (line) handle(line);
}
});
function handle(line) {
let message;
try { message = JSON.parse(line); } catch { replyError(null, -32700, 'Parse error'); return; }
const { id, method, params } = message;
if (method === 'notifications/initialized' || (id === undefined && method)) return;
if (method === 'initialize') {
reply(id, { protocolVersion: (params && params.protocolVersion) || '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'opnsense', version: '1.0.0' } });
return;
}
if (method === 'ping') { reply(id, {}); return; }
if (method === 'tools/list') {
reply(id, { tools: TOOLS.map((tool) => ({ ...tool, annotations: { title: tool.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 = {
opnsense_status: () => status(),
opnsense_services: () => services(args),
opnsense_interfaces: () => interfaces(args),
opnsense_gateways: () => gateways(),
opnsense_firewall_rules: () => firewallRules(args),
opnsense_aliases: () => aliases(args),
};
const fn = dispatch[name];
if (!fn) { reply(id, { content: [{ type: 'text', text: `Unbekanntes Werkzeug: ${name}` }], isError: true }); return; }
fn().then((text) => reply(id, { content: [{ type: 'text', text }], isError: false }))
.catch((error) => reply(id, { content: [{ type: 'text', text: `Interner Fehler: ${error.message || error}` }], isError: true }));
return;
}
replyError(id, -32601, 'Method not found');
}
+364
View File
@@ -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');
}
+526
View File
@@ -0,0 +1,526 @@
#!/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}`);
}
+298
View File
@@ -0,0 +1,298 @@
#!/usr/bin/env node
/**
* shell-tools — MCP-Server mit begrenzter Shell-/SSH-Faehigkeit fuer Jarvis.
*
* Design:
* - ssh_host bindet mit einem **eingeschraenkten SSH-Schluessel** an den Host.
* Der Schluessel erzwingt auf dem Host das Waechter-Skript
* (command="..." in authorized_keys, root-eigentuemer). Der Waechter protokolliert
* jeden Befehl nach /var/log/jarvis-ssh.log und blockt: Aenderungen am eigenen
* Zugang/Schutz, global destruktive Befehle, Aenderungen an der Trading-Instanz
* (ai-orchestrator-*, /mnt/disk1/Development-DATA/AI-Platform/openclaw/) und an
* der eigenen Policy (…/openclaw-jarvis/config/openclaw.json, config/mcp/) sowie
* destruktive Docker-Befehle.
*
* Ehrliche Grenze: Das ist Schutz vor Fehlern/Fluegelbruch, keine echte Sandbox.
* Ein Bewusst/Boedwilliger Koennte mit root-Shell konstruierte Umgehungen bauen.
* Deshalb: jede Ausfuehrung wird lokal (AUDIT_FILE) und hostseitig protokolliert.
*
* - exec_local fuehrt Befehle im Container (uid 1000, Workspace) aus. Der lokale
* Schutz greift fuer die eigene Policy-Konfiguration (openclaw.json, mcp/),
* ist aber nur eine Denylist (keine Sandbox).
*/
'use strict';
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const HOST = process.env.SSH_HOST || 'YOUR_SERVER_IP';
const USER = process.env.SSH_USER || 'root';
const KEY = process.env.SSH_KEY_FILE || '/home/node/.openclaw/ssh/id_ed25519';
const KHOSTS = process.env.SSH_KNOWN_HOSTS || '/home/node/.openclaw/ssh/known_hosts';
const AUDIT = process.env.AUDIT_FILE || '/home/node/.openclaw/workspaces/jarvis/.shell-audit.log';
const WORKSPACE = process.env.WORKSPACE || '/home/node/.openclaw/workspaces/jarvis';
const MAX_CHARS = 40000;
function audit(entry) {
try {
fs.mkdirSync(path.dirname(AUDIT), { recursive: true });
fs.appendFileSync(AUDIT, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n');
} catch (e) {
// Audit darf den Aufruf nicht unterbrechen.
}
}
// ------------------------- Denylists (lokal, ergaenzend) -------------------------
const LOCAL_DESTRUCT = [
/mkfs/i,
/wipefs/i,
/blkdiscard/i,
/dd[^\n]*of=\/dev\//i,
/shutdown/i,
/reboot/i,
/poweroff/i,
/(^|[[:space:]])(halt)([[:space:]]|$)/i,
/rm\s+-[a-zA-Z]*r[a-zA-Z]*f\s+\//i,
/systemctl\s+(stop|restart|mask|disable)/i,
];
const SELF_POLICY = [/openclaw-jarvis\/config\/openclaw\.json/i, /openclaw-jarvis\/config\/mcp\//i];
function blockedLocal(cmd) {
if (!cmd || !cmd.trim()) return 'leerer Befehl';
if (LOCAL_DESTRUCT.some((re) => re.test(cmd))) return 'global destruktiv';
if (SELF_POLICY.some((re) => re.test(cmd))) return 'eigene Policy (openclaw.json/mcp) ist tabu';
return null;
}
// ------------------------- Gemeinsame Runner -------------------------
function run(args, opts) {
return new Promise((resolve) => {
const timeoutMs = opts.timeoutMs || 30000;
const p = spawn(args[0], args.slice(1), {
env: { ...process.env, LANG: 'C', LC_ALL: 'C' },
stdio: ['ignore', 'pipe', 'pipe'],
});
let out = '';
let done = false;
const finish = (code, extra) => {
if (done) return;
done = true;
resolve({ code: code === null ? -1 : code, out: out.slice(0, MAX_CHARS), truncated: out.length > MAX_CHARS, ...extra });
};
const t = setTimeout(() => {
try {
p.kill('SIGKILL');
} catch (e) {}
finish(-2, { error: `timeout nach ${timeoutMs} ms` });
}, timeoutMs + 2000);
p.on('exit', (c, s) => {
clearTimeout(t);
finish(c === null ? (s && s.code) || -1 : c);
});
p.on('error', (e) => {
clearTimeout(t);
finish(-1, { error: String(e.message || e) });
});
p.stdout.on('data', (d) => (out += d));
p.stderr.on('data', (d) => (out += d));
});
}
async function execLocal(args) {
const cmd = String((args && args.command) || '').trim();
const timeout = Math.min(60, Math.max(3, Number((args && args.timeout_seconds) || 30))) * 1000;
const block = blockedLocal(cmd);
if (block) {
audit({ tool: 'exec_local', command: cmd, blocked: block });
return {
isError: true,
text: `exec_local VERWEIGERT (lokaler Schutz: ${block}). Aenderungen an der eigenen Konfiguration (openclaw.json, config/mcp/) und global destruktive Befehle sind nicht erlaubt.`,
};
}
const r = await run(['sh', '-c', cmd], { timeoutMs: timeout });
audit({ tool: 'exec_local', command: cmd, exit: r.code, ms: r.ms || 0, out_len: r.out.length, error: r.error || null });
const body = r.error ? `\n(FEHLER: ${r.error})` : '';
const out = (r.out || '').trim() || '(keine Ausgabe)';
return {
text: `## exec_local (Container, uid 1000, Workspace)\n\n- Befehl: \`${cmd}\`\n- Exit-Code: ${r.code}${r.truncated ? ', Ausgabe gekuerzt' : ''}\n\n\`\`\`\n${out}${body}\n\`\`\``,
isError: r.code !== 0,
};
}
async function sshHost(args) {
const cmd = String((args && args.command) || '').trim();
const timeout = Math.min(60, Math.max(3, Number((args && args.timeout_seconds) || 30))) * 1000;
if (!cmd) return { isError: true, text: 'ssh_host: Befehl fehlt.' };
const sshArgs = [
'ssh',
'-i', KEY,
'-o', 'BatchMode=yes',
'-o', 'StrictHostKeyChecking=accept-new',
'-o', `UserKnownHostsFile=${KHOSTS}`,
'-o', 'ConnectTimeout=8',
'-o', 'LogLevel=ERROR',
`${USER}@${HOST}`,
cmd,
];
const r = await run(sshArgs, { timeoutMs: timeout });
audit({ tool: 'ssh_host', host: HOST, command: cmd, exit: r.code, ms: r.ms || 0, out_len: r.out.length, error: r.error || null, blocked: (r.out || '').match(/^VERWEIGERT/) ? true : null });
const out = (r.out || '').trim() || '(keine Ausgabe)';
let note = '';
if (/^VERWEIGERT/.test(out)) note = '\n> Der Host-Waechter hat diesen Befehl abgelehnt (Log: /var/log/jarvis-ssh.log).';
else if (r.error) note = `\n(FEHLER: ${r.error})`;
return {
text: `## ssh_host (${USER}@${HOST}, bewaucht & protokolliert)\n\n- Befehl: \`${cmd}\`\n- Exit-Code: ${r.code}${r.truncated ? ', Ausgabe gekuerzt' : ''}\n\n\`\`\`\n${out}\n\`\`\`${note}`,
isError: r.code !== 0,
};
}
function shellAudit(args) {
const n = Math.min(200, Math.max(1, Number((args && args.tail_lines) || 30)));
let data = '';
try {
data = fs.readFileSync(AUDIT, 'utf8');
} catch (e) {
return { text: `## Shell-Audit\n\n_Keine Eintraege (${AUDIT} nicht vorhanden)_` };
}
const lines = data.trim().split('\n').filter(Boolean);
const tail = lines.slice(-n);
const pretty = tail.map((l) => {
try {
const j = JSON.parse(l);
return `[${j.ts}] ${j.tool} exit=${j.exit ?? '?'}${j.blocked ? ' BLOCKIERT(' + j.blocked + ')' : ''}: ${(j.command || '').slice(0, 300)}`;
} catch (e) {
return l;
}
});
return {
text: `## Shell-Audit (letzte ${tail.length} von ${lines.length})\n\n${pretty.map((l) => '- ' + l).join('\n')}`,
};
}
const TOOLS = [
{
name: 'ssh_host',
description:
'Fuehrt einen Befehl als root auf dem Unraid-Host aus. Der Host-Waechter protokolliert alles und blockt Aenderungen an der Trading-Instanz (ai-orchestrator-*, …/AI-Platform/openclaw/), an der eigenen OpenClaw-Policy (…/openclaw-jarvis/config/openclaw.json und config/mcp/), global destruktive Befehle und destruktive Docker-Befehle. Lesen ist erlaubt (ls, cat, tail, grep, docker inspect/logs/stats, smartctl …).',
inputSchema: {
type: 'object',
properties: {
command: { type: 'string', description: 'Vollstaendiger Shell-Befehl, z.B. "uptime" oder "df -h /mnt/disk1".' },
timeout_seconds: { type: 'integer', description: 'Timeout 3-60 s (Standard 30).' },
},
required: ['command'],
additionalProperties: false,
},
},
{
name: 'exec_local',
description:
'Fuehrt einen Befehl im eigenen Container aus (uid 1000, Working-Dir = Workspace). Nuetztlich fuer node/curl/Datei-Proben. Aenderungen an openclaw.json und config/mcp/ sind lokal gesperrt.',
inputSchema: {
type: 'object',
properties: {
command: { type: 'string', description: 'Shell-Befehl im Container, z.B. "df -h /home/node" oder "node -e \"...\""' },
timeout_seconds: { type: 'integer', description: 'Timeout 3-60 s (Standard 30).' },
},
required: ['command'],
additionalProperties: false,
},
},
{
name: 'shell_audit',
description: 'Zeigt die letzten Eintraege der Shell-Ausfuehrungsprotokolle (lokal; hostseitig /var/log/jarvis-ssh.log per ssh_host lesbar).',
inputSchema: {
type: 'object',
properties: {
tail_lines: { type: 'integer', description: 'Anzahl der letzten Eintraege (1-200, Standard 30).' },
},
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: 'shell-tools', version: '1.0.0' },
});
return;
}
if (method === 'ping') {
reply(id, {});
return;
}
if (method === 'tools/list') {
reply(id, {
tools: TOOLS.map(({ name, description, inputSchema }) => {
const destructive = name === 'ssh_host' || name === 'exec_local';
return {
name,
description,
inputSchema,
annotations: {
title: name.replace(/_/g, ' '),
readOnlyHint: !destructive,
destructiveHint: destructive,
idempotentHint: true,
openWorldHint: true,
},
};
}),
});
return;
}
if (method === 'tools/call') {
const name = params && params.name;
const args = (params && params.arguments) || {};
const run = async () => {
let out;
if (name === 'ssh_host') out = await sshHost(args);
else if (name === 'exec_local') out = await execLocal(args);
else if (name === 'shell_audit') out = shellAudit(args);
else return { text: `Unbekanntes Werkzeug: ${name}`, isError: true };
return { content: [{ type: 'text', text: out.text }], isError: Boolean(out.isError) };
};
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}`);
}
+435
View File
@@ -0,0 +1,435 @@
#!/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);
});
+721
View File
@@ -0,0 +1,721 @@
#!/usr/bin/env node
// Controlled static deployment for the PDEV-WEB VM.
// Credentials are read inside this MCP process from Bitwarden and never become tool output.
"use strict";
const { execFileSync } = require("node:child_process");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const crypto = require("node:crypto");
const BW_DATA_DIR = process.env.BW_DATA_DIR || "/home/node/.openclaw/bw-data";
const BW_CLI = process.env.BW_CLI || "/home/node/.openclaw/bw-cli/node_modules/@bitwarden/cli/build/bw.js";
const BW_MP_FILE = process.env.BW_MP_FILE || "/home/node/.openclaw/mcp/.bw-masterpass";
const PROJECT_ROOT = "/home/node/.openclaw/workspaces/jarvis/projects";
const HOST = "YOUR_WEBHOST_IP";
const CLOUDFLARE_TOKEN_FILE = process.env.CLOUDFLARE_TOKEN_FILE || "/home/node/.openclaw/mcp/.cloudflare-api-token";
const KEYHELP_TOKEN_FILE = process.env.KEYHELP_TOKEN_FILE || "/home/node/.openclaw/mcp/.keyhelp-api-key";
const TIMEOUT = 90_000;
let bwSession;
let cachedKeyHelpAuth;
function runBw(args, input, withSession = true) {
const env = { ...process.env, BITWARDENCLI_APPDATA_DIR: BW_DATA_DIR };
if (withSession && bwSession) env.BW_SESSION = bwSession;
return execFileSync(BW_CLI, args, { env, input, timeout: 20_000, maxBuffer: 8 * 1024 * 1024, stdio: ["pipe", "pipe", "pipe"] }).toString("utf8");
}
function ensureBitwarden() {
try {
const master = fs.readFileSync(BW_MP_FILE, "utf8").trim();
if (!master) return "Das Bitwarden-Masterpasswort-File ist leer.";
let lastError = "unbekannter Fehler";
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
bwSession = runBw(["unlock", "--raw", "--passwordfile", BW_MP_FILE], undefined, false).trim();
if (bwSession) return null;
lastError = "kein Session-Schlüssel zurückgegeben";
} catch (error) {
const stderr = error?.stderr ? String(error.stderr).trim() : "";
lastError = stderr || String(error?.message || error);
}
}
return `Bitwarden konnte nicht entsperrt werden: ${lastError}`;
} catch (error) {
return `Bitwarden konnte nicht entsperrt werden: ${String(error?.message || error)}`;
}
}
function readBwJson(args) {
let lastError;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
const output = runBw(args).trim();
if (!output) throw new Error("Bitwarden lieferte eine leere Antwort.");
return JSON.parse(output);
} catch (error) {
lastError = error;
bwSession = undefined;
const unlockError = ensureBitwarden();
if (unlockError) lastError = new Error(unlockError);
}
}
throw lastError;
}
function credential() {
const problem = ensureBitwarden();
if (problem) return { error: problem };
try {
// Shared organization items may not exist in the local CLI cache after a fresh login.
try { runBw(["sync"]); } catch {}
const items = readBwJson(["list", "items"]);
const hit = items.find((item) => {
const login = item.login || {};
const uris = (login.uris || []).map((u) => String(u.uri || "").toLowerCase());
const hay = `${item.name || ""} ${login.username || ""} ${uris.join(" ")}`.toLowerCase();
return hay.includes("webhost.your-domain.com") || hay.includes("pdev - webhost") || hay.includes("pdev-web") || hay.includes("webhost ssh");
});
if (!hit?.id) return { error: "Kein dedizierter Webhost-Eintrag gefunden. Bitte einen Bitwarden-Eintrag mit webhost.your-domain.com oder PDEV-WEB anlegen." };
const full = readBwJson(["get", "item", hit.id]);
const login = full.login || {};
if (!login.password) return { error: "Der Webhost-Eintrag enthält kein Passwort." };
// The vault item is the shared PDEV credential; the VM account is deliberately
// fixed to the confirmed deployment user, not the Bitwarden/SSO email field.
return { user: "administrator", password: String(login.password) };
} catch (error) {
return { error: `Webhost-Eintrag konnte nicht gelesen werden: ${String(error.stderr || error.message || error)}` };
}
}
function keyHelpApiKey() {
if (cachedKeyHelpAuth) return cachedKeyHelpAuth;
try {
const key = fs.readFileSync(KEYHELP_TOKEN_FILE, "utf8").trim();
if (key) return cachedKeyHelpAuth = { key, source: `Datei ${KEYHELP_TOKEN_FILE}`, length: key.length };
} catch {}
const problem = ensureBitwarden();
if (!problem) {
try {
try { runBw(["sync"]); } catch {}
const items = readBwJson(["list", "items"]);
const hit = items.find((item) => /keyhelp.*api|api.*keyhelp/i.test(String(item.name || "")));
if (hit?.id) {
const full = readBwJson(["get", "item", hit.id]);
const fields = full.fields || [];
const field = fields.find((candidate) => /api.?key|token/i.test(String(candidate.name || "")));
const key = field?.value || full.login?.password || full.notes;
const normalized = key ? String(key).trim() : "";
const location = field ? `Feld ${field.name}` : full.login?.password ? "Login-Passwort" : "Notiz";
if (normalized) return cachedKeyHelpAuth = { key: normalized, source: `Bitwarden-Eintrag ${hit.name}, ${location}`, length: normalized.length };
}
} catch {}
}
return { error: problem || `Kein KeyHelp-API-Key gefunden. Lege ihn in ${KEYHELP_TOKEN_FILE} oder als Bitwarden-Eintrag mit \"KeyHelp API\" im Namen ab.` };
}
async function keyHelpRequest(endpoint, init = {}) {
const auth = keyHelpApiKey();
if (auth.error) throw new Error(auth.error);
const c = credential();
if (c.error) throw new Error(c.error);
if (!/^\/[A-Za-z0-9_?&=/%.-]+$/.test(endpoint) || /[\r\n]/.test(endpoint)) throw new Error("Ungueltiger KeyHelp-API-Endpunkt.");
const escapeConfig = (value) => String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/[\r\n]+/g, " ");
const method = String(init.method || "GET").toUpperCase();
if (!["GET", "POST", "PUT", "DELETE"].includes(method)) throw new Error("Ungueltige KeyHelp-API-Methode.");
const makeConfig = (host) => [
`url = "https://${host}/api/v2${escapeConfig(endpoint)}"`,
'header = "Host: webhost.your-domain.com"',
`header = "X-API-Key: ${escapeConfig(auth.key)}"`,
'header = "Accept: application/json"',
'header = "Content-Type: application/json"',
`request = "${method}"`,
"insecure",
"silent",
"show-error",
...(init.body ? [`data = "${escapeConfig(init.body)}"`] : []),
].join("\n") + "\n";
const parse = (output) => {
const match = output.match(/\n(\d{3})\s*$/);
if (!match) throw new Error("KeyHelp-API lieferte keinen HTTP-Status.");
const status = Number(match[1]);
const text = output.slice(0, match.index);
let body;
try { body = text ? JSON.parse(text) : null; } catch { body = text; }
return { status, body };
};
let response = parse(execFileSync("curl", ["--config", "-", "--write-out", "\n%{http_code}"], {
input: makeConfig(HOST), timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 4 * 1024 * 1024,
}).toString("utf8"));
if (response.status === 401) {
response = parse(withAskpass(c.password, (env, common) => execFileSync(
"ssh",
[...common, `${c.user}@${HOST}`, "curl --config - --write-out '\\n%{http_code}'"],
{ env, input: makeConfig("127.0.0.1"), timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 4 * 1024 * 1024 },
).toString("utf8")));
}
if (response.status < 200 || response.status >= 300) throw new Error(`KeyHelp HTTP ${response.status}: ${typeof response.body === "string" ? response.body : response.body?.message || response.body?.code || "unbekannter Fehler"}`);
return response.body;
}
async function keyHelpApiProbe() {
const auth = keyHelpApiKey();
if (auth.error) return { error: true, text: `KeyHelp-API nicht bereit: ${auth.error}` };
try {
const clients = await keyHelpRequest("/clients");
const domains = await keyHelpRequest("/domains");
const safeClients = (Array.isArray(clients) ? clients : []).map(({ id, username, document_root, status }) => ({ id, username, document_root, status }));
const safeDomains = (Array.isArray(domains) ? domains : []).map(({ id, id_user, domain, target, status }) => ({ id, id_user, domain, target, status }));
return { error: false, text: JSON.stringify({ api: "ready", clients: safeClients, domains: safeDomains }, null, 2) };
} catch (error) {
return { error: true, text: `KeyHelp-API nicht bereit: ${String(error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 1600)}\nKey-Quelle: ${auth.source}; Laenge: ${auth.length} Zeichen.` };
}
}
function withAskpass(password, fn) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "jarvis-web-deploy-"));
const askpass = path.join(dir, "askpass.sh");
const knownHosts = path.join(dir, "known_hosts");
fs.writeFileSync(askpass, "#!/bin/sh\nprintf '%s\\n' \"$JARVIS_WEBHOST_PASSWORD\"\n", { mode: 0o700 });
const env = { ...process.env, DISPLAY: ":99", SSH_ASKPASS: askpass, SSH_ASKPASS_REQUIRE: "force", JARVIS_WEBHOST_PASSWORD: password };
const common = ["-o", "StrictHostKeyChecking=accept-new", "-o", `UserKnownHostsFile=${knownHosts}`, "-o", "ConnectTimeout=12", "-o", "NumberOfPasswordPrompts=1", "-o", "PreferredAuthentications=password", "-o", "PubkeyAuthentication=no"];
try {
return fn(env, common);
} finally {
try { fs.rmSync(dir, { recursive: true, force: true }); } catch {}
}
}
function sourcePath(raw) {
const full = path.resolve(PROJECT_ROOT, raw || "");
if (!raw || (full !== PROJECT_ROOT && !full.startsWith(`${PROJECT_ROOT}${path.sep}`))) return null;
try { if (!fs.statSync(full).isDirectory()) return null; } catch { return null; }
return full;
}
function shellQuote(value) {
return `'${String(value).replace(/'/g, `'"'"'`)}'`;
}
function loadDeployManifest(source) {
const manifestPath = path.join(source, "jarvis.deploy.json");
if (!fs.existsSync(manifestPath)) throw new Error("jarvis.deploy.json fehlt im Projektverzeichnis.");
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
const domain = String(manifest.domain || "").toLowerCase();
const client = String(manifest.client || "");
const runtime = String(manifest.runtime || "static");
const webRoot = String(manifest.web_root || (runtime === "php" ? "public" : "."));
const healthPath = String(manifest.health_path || "/");
if (!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+your_username44\.dev$/.test(domain)) throw new Error("Manifest-Domain muss eine gueltige Subdomain unter your-domain.com sein.");
if (!/^[a-z][a-z0-9_-]{0,31}$/.test(client)) throw new Error("Ungueltiger KeyHelp-Client im Manifest.");
if (!["static", "php"].includes(runtime)) throw new Error("runtime muss static oder php sein.");
if (webRoot !== "." && !/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(webRoot)) throw new Error("Ungueltiges web_root im Manifest.");
if (!/^\/[A-Za-z0-9_./?=&%-]*$/.test(healthPath) || healthPath.includes("..")) throw new Error("Ungueltiger health_path im Manifest.");
if (manifest.migration && manifest.migration !== "laravel") throw new Error("Unterstuetzt wird nur migration=laravel.");
return { ...manifest, domain, client, runtime, webRoot, healthPath };
}
function prepareArtifact(source, manifest) {
const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "jarvis-release-"));
const project = path.join(workspace, "project");
fs.cpSync(source, project, { recursive: true, filter: (entry) => ![".git", "node_modules", ".next"].includes(path.basename(entry)) });
if (manifest.runtime === "static" && fs.existsSync(path.join(project, "package.json"))) {
const pkg = JSON.parse(fs.readFileSync(path.join(project, "package.json"), "utf8"));
if (pkg.scripts?.build) {
const installArgs = fs.existsSync(path.join(project, "package-lock.json")) ? ["ci", "--ignore-scripts"] : ["install", "--ignore-scripts"];
execFileSync("npm", installArgs, { cwd: project, timeout: 5 * 60_000, stdio: ["ignore", "pipe", "pipe"] });
execFileSync("npm", ["run", "build"], { cwd: project, timeout: 10 * 60_000, stdio: ["ignore", "pipe", "pipe"] });
}
}
const configured = manifest.artifact_dir ? path.resolve(project, String(manifest.artifact_dir)) : null;
if (configured && (!configured.startsWith(`${project}${path.sep}`) || !fs.existsSync(configured))) {
fs.rmSync(workspace, { recursive: true, force: true });
throw new Error("Das konfigurierte artifact_dir fehlt oder liegt ausserhalb des Projekts.");
}
const candidates = [configured, path.join(project, "dist"), path.join(project, "build"), path.join(project, "out"), project].filter(Boolean);
const artifact = manifest.runtime === "php" ? project : candidates.find((candidate) => candidate === project || fs.existsSync(candidate));
if (!artifact || (artifact !== project && !artifact.startsWith(`${project}${path.sep}`)) || !fs.statSync(artifact).isDirectory()) {
fs.rmSync(workspace, { recursive: true, force: true });
throw new Error("Build-Artefakt fehlt oder liegt ausserhalb des Projekts.");
}
return { workspace, artifact };
}
async function ensureKeyHelpDomain(manifest, target) {
const client = await keyHelpRequest(`/clients/name/${encodeURIComponent(manifest.client)}`);
if (!client?.id) throw new Error(`KeyHelp-Client ${manifest.client} wurde nicht gefunden.`);
const payload = {
id_user: client.id,
domain: manifest.domain,
is_email_domain: false,
is_dns_disabled: true,
target: { target },
security: { lets_encrypt: manifest.lets_encrypt === true, is_prefer_https: manifest.prefer_https !== false },
};
try {
const domain = await keyHelpRequest(`/domains/name/${encodeURIComponent(manifest.domain)}`);
await keyHelpRequest(`/domains/${domain.id}`, { method: "PUT", body: JSON.stringify(payload) });
return { created: false, id: domain.id, client, previousTarget: domain.target?.target, payload };
} catch (error) {
if (!String(error.message || error).includes("HTTP 404")) throw error;
const created = await keyHelpRequest("/domains", { method: "POST", body: JSON.stringify({ ...payload, create_www_subdomain: false }) });
return { created: true, id: created?.id, client, payload };
}
}
async function deployRelease(args) {
if (args.confirm !== true) return { error: true, text: "Produktiv-Deploy benoetigt confirm=true." };
const source = sourcePath(String(args.source_dir || ""));
if (!source) return { error: true, text: `Quellverzeichnis muss unter ${PROJECT_ROOT} liegen und existieren.` };
let prepared;
try {
const manifest = loadDeployManifest(source);
if (manifest.migration && args.confirm_migration !== true) return { error: true, text: "Datenbankmigration benoetigt zusaetzlich confirm_migration=true." };
prepared = prepareArtifact(source, manifest);
const c = credential();
if (c.error) throw new Error(c.error);
const releaseId = `${new Date().toISOString().replace(/[-:.TZ]/g, "").slice(0, 14)}-${crypto.randomBytes(4).toString("hex")}`;
const root = `/home/users/${manifest.client}/www/.jarvis-deploy/${manifest.domain}`;
const release = `${root}/releases/${releaseId}`;
const stage = `/tmp/jarvis-release-${crypto.randomUUID()}`;
const target = `/.jarvis-deploy/${manifest.domain}/releases/${releaseId}${manifest.webRoot === "." ? "" : `/${manifest.webRoot}`}/`;
await withAskpass(c.password, async (env, common) => {
execFileSync("ssh", [...common, `${c.user}@${HOST}`, `mkdir -p ${shellQuote(stage)}`], { env, timeout: TIMEOUT, stdio: ["ignore", "pipe", "pipe"] });
execFileSync("scp", [...common, "-r", `${prepared.artifact}${path.sep}.`, `${c.user}@${HOST}:${stage}`], { env, timeout: 10 * 60_000, stdio: ["ignore", "pipe", "pipe"] });
const envFile = `/home/users/${manifest.client}/files/jarvis-env/${manifest.domain}.env`;
const setup = [
"set -eu",
"sudo -S -p '' -v",
`sudo install -d -o ${manifest.client} -g ${manifest.client} ${shellQuote(root)} ${shellQuote(`${root}/releases`)}`,
`sudo rm -rf ${shellQuote(release)}`,
`sudo mv ${shellQuote(stage)} ${shellQuote(release)}`,
`sudo chown -R ${manifest.client}:${manifest.client} ${shellQuote(release)}`,
manifest.shared_env === true ? `sudo test -f ${shellQuote(envFile)} && sudo -u ${manifest.client} ln -s ${shellQuote(envFile)} ${shellQuote(`${release}/.env`)}` : "true",
manifest.runtime === "php" && manifest.composer !== false ? `sudo -u ${manifest.client} composer install --no-dev --no-interaction --prefer-dist --optimize-autoloader --working-dir=${shellQuote(release)}` : "true",
].join("; ");
execFileSync("ssh", [...common, `${c.user}@${HOST}`, setup], { env, input: `${c.password}\n`, timeout: 10 * 60_000, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 2 * 1024 * 1024 });
});
let domainResult;
let migrationApplied = false;
try {
if (manifest.migration === "laravel") {
await withAskpass(c.password, (env, common) => {
const migrate = `sudo -S -p '' -v; sudo -u ${manifest.client} php ${shellQuote(`${release}/artisan`)} migrate --force`;
execFileSync("ssh", [...common, `${c.user}@${HOST}`, migrate], { env, input: `${c.password}\n`, timeout: 10 * 60_000, stdio: ["pipe", "pipe", "pipe"] });
});
migrationApplied = true;
}
domainResult = await ensureKeyHelpDomain(manifest, target);
await withAskpass(c.password, (env, common) => {
const health = `for attempt in $(seq 1 12); do curl -kfsS --max-time 20 --resolve ${shellQuote(`${manifest.domain}:443:127.0.0.1`)} ${shellQuote(`https://${manifest.domain}${manifest.healthPath}`)} >/dev/null && exit 0; sleep 5; done; exit 1`;
execFileSync("ssh", [...common, `${c.user}@${HOST}`, health], { env, timeout: 30_000, stdio: ["ignore", "pipe", "pipe"] });
});
} catch (activationError) {
if (domainResult) {
try {
if (domainResult.created) await keyHelpRequest(`/domains/${domainResult.id}`, { method: "DELETE" });
else if (domainResult.previousTarget) await keyHelpRequest(`/domains/${domainResult.id}`, { method: "PUT", body: JSON.stringify({ ...domainResult.payload, target: { target: domainResult.previousTarget } }) });
} catch {}
}
await withAskpass(c.password, (env, common) => {
const rollback = `sudo -S -p '' -v; ${migrationApplied ? `sudo -u ${manifest.client} php ${shellQuote(`${release}/artisan`)} migrate:rollback --force || true;` : ""} sudo rm -rf ${shellQuote(release)}`;
execFileSync("ssh", [...common, `${c.user}@${HOST}`, rollback], { env, input: `${c.password}\n`, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"] });
});
throw new Error(`KeyHelp-Aktivierung oder Healthcheck fehlgeschlagen; Release wurde zurueckgerollt: ${String(activationError.stderr || activationError.message || activationError).slice(0, 1000)}`);
}
await withAskpass(c.password, (env, common) => {
const cleanup = `sudo -S -p '' -v; sudo find ${shellQuote(`${root}/releases`)} -mindepth 1 -maxdepth 1 -type d -printf '%T@ %p\\n' | sort -rn | tail -n +6 | cut -d' ' -f2- | xargs -r sudo rm -rf --`;
execFileSync("ssh", [...common, `${c.user}@${HOST}`, cleanup], { env, input: `${c.password}\n`, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"] });
});
return { error: false, text: `Release ${releaseId} erfolgreich fuer ${manifest.domain} deployt. KeyHelp-Domain ${domainResult.created ? "angelegt" : "aktualisiert"}; Healthcheck erfolgreich.` };
} catch (error) {
return { error: true, text: `Release-Deploy fehlgeschlagen: ${String(error.stderr || error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 2000)}` };
} finally {
if (prepared?.workspace) try { fs.rmSync(prepared.workspace, { recursive: true, force: true }); } catch {}
}
}
function probeHost() {
const c = credential();
if (c.error) return { error: true, text: c.error };
return withAskpass(c.password, (env, common) => {
try {
const result = execFileSync("ssh", [...common, `${c.user}@${HOST}`, "printf 'USER='; id -un; printf 'HOME_DIRS\\n'; find /home/users -maxdepth 4 -type d -path '*/www/*' -print 2>/dev/null | head -30"], { env, timeout: TIMEOUT, stdio: ["ignore", "pipe", "pipe"] }).toString("utf8").trim();
return { error: false, text: result || "SSH erreichbar, aber keine KeyHelp-Webroot gefunden." };
} catch (error) {
return { error: true, text: `SSH erreichbar? Nein oder kein Zugriff: ${String(error.stderr || error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 1000)}` };
}
});
}
function discoverKeyHelp() {
const c = credential();
if (c.error) return { error: true, text: c.error };
return withAskpass(c.password, (env, common) => {
const command = [
"printf '%s\\n' '== IDENTITY =='",
"id",
"getent passwd $(id -un) || true",
"printf '%s\\n' '== SUDO =='",
"sudo -S -p '' -v >/dev/null 2>&1 && sudo -n -l || echo SUDO_UNAVAILABLE",
"printf '%s\\n' '== KEYHELP PATHS =='",
"sudo -n ls -la /home/keyhelp/www 2>/dev/null || true",
"sudo -n find /home/keyhelp/www/keyhelp /etc/keyhelp /usr/local/keyhelp -maxdepth 4 -type f 2>/dev/null | grep -Ei 'api|route|console|command|config|domain' | head -160 || true",
"printf '%s\\n' '== APACHE VHOSTS =='",
"sudo -n apache2ctl -S 2>/dev/null | head -120 || true",
"printf '%s\\n' '== WEBROOTS =='",
"sudo -n find /home/users -maxdepth 5 -type d -path '*/www/*' -printf '%u:%g %m %p\\n' 2>/dev/null | head -120 || true",
"printf '%s\\n' '== COMMANDS =='",
"for x in keyhelp keyhelp-cli kh php composer node npm apache2ctl nginx; do command -v $x 2>/dev/null || true; done",
"printf '%s\\n' '== SERVICES =='",
"sudo -n systemctl list-unit-files --type=service 2>/dev/null | grep -Ei 'keyhelp|apache|nginx|php.*fpm|mariadb|mysql' | head -80 || true",
"printf '%s\\n' '== OS =='",
"cat /etc/os-release 2>/dev/null || true",
].join("; ");
try {
const output = execFileSync("ssh", [...common, `${c.user}@${HOST}`, command], { env, input: `${c.password}\n`, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 2 * 1024 * 1024 }).toString("utf8").trim();
return { error: false, text: output || "Keine KeyHelp-Metadaten gefunden." };
} catch (error) {
return { error: true, text: `KeyHelp-Erkennung fehlgeschlagen: ${String(error.stderr || error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 2000)}` };
}
});
}
function keyHelpApiSchema() {
const c = credential();
if (c.error) return { error: true, text: c.error };
return withAskpass(c.password, (env, common) => {
try {
const output = execFileSync("ssh", [...common, `${c.user}@${HOST}`, "sudo -S -p '' cat /home/keyhelp/www/keyhelp/api/openapi.json"], { env, input: `${c.password}\n`, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 8 * 1024 * 1024 }).toString("utf8");
const schema = JSON.parse(output);
const paths = Object.fromEntries(Object.entries(schema.paths || {}).filter(([name]) => /domain|client|certificate/i.test(name)).map(([name, operations]) => [name, Object.fromEntries(Object.entries(operations).map(([method, operation]) => [method, { summary: operation.summary, parameters: operation.parameters, requestBody: operation.requestBody, responses: operation.responses, security: operation.security }]))]));
const schemas = schema.components?.schemas || {};
const selectedSchemas = Object.fromEntries(Object.entries(schemas).filter(([name]) => /^(domain|client|certificate|created|error)$/i.test(name)));
return { error: false, text: JSON.stringify({ info: schema.info, servers: schema.servers, security: schema.security, securitySchemes: schema.components?.securitySchemes, paths, schemas: selectedSchemas }, null, 2).slice(0, 60000) };
} catch (error) {
return { error: true, text: `KeyHelp-API-Schema konnte nicht gelesen werden: ${String(error.stderr || error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 2000)}` };
}
});
}
function keyHelpApiDiagnose() {
const c = credential();
if (c.error) return { error: true, text: c.error };
return withAskpass(c.password, (env, common) => {
const command = [
"sudo -S -p '' -v",
"printf '%s\\n' '== RECENT API ACCESS =='",
"sudo grep -h '/api/v2/' /var/log/apache2/keyhelp/access.log /var/log/apache2/*access*.log 2>/dev/null | tail -20 || true",
"printf '%s\\n' '== KEYHELP LOG TARGETS =='",
"sudo grep -R -n -E 'CustomLog|ErrorLog' /etc/apache2/keyhelp 2>/dev/null | head -80 || true",
"printf '%s\\n' '== API IMPLEMENTATION REFERENCES =='",
"sudo grep -R -n -E 'ip.?restriction|allowed.?ip|api.?key' /home/keyhelp/www/keyhelp/core/Api /home/keyhelp/www/keyhelp/pages/admin_api.php 2>/dev/null | head -80 || true",
"printf '%s\\n' '== API DATABASE TABLES =='",
"sudo mariadb --batch --skip-column-names -e \"SELECT TABLE_SCHEMA, TABLE_NAME FROM information_schema.TABLES WHERE LOWER(TABLE_NAME) LIKE '%api%' OR LOWER(TABLE_NAME) LIKE '%key%';\" 2>/dev/null | head -80 || true",
"printf '%s\\n' '== KEYHELP API COLUMNS =='",
"sudo mariadb --batch --skip-column-names -e \"SELECT COLUMN_NAME, DATA_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='keyhelp' AND TABLE_NAME='api_keys' ORDER BY ORDINAL_POSITION;\" 2>/dev/null || true",
"printf '%s\\n' '== KEYHELP API KEY METADATA =='",
"sudo mariadb --batch --skip-column-names -e \"SELECT id, name, ips, created_at, COALESCE(last_access, 'never'), CHAR_LENGTH(api_key) FROM keyhelp.api_keys ORDER BY id;\" 2>/dev/null || true",
"printf '%s\\n' '== KEYHELP ACCOUNT TABLES =='",
"sudo mariadb --batch --skip-column-names -e \"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='keyhelp' AND (LOWER(TABLE_NAME) LIKE '%user%' OR LOWER(TABLE_NAME) LIKE '%admin%');\" 2>/dev/null || true",
"printf '%s\\n' '== KEYHELP ACCOUNT COLUMNS =='",
"sudo mariadb --batch --skip-column-names -e \"SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='keyhelp' AND (LOWER(TABLE_NAME) LIKE '%user%' OR LOWER(TABLE_NAME) LIKE '%admin%') AND (LOWER(COLUMN_NAME) LIKE '%name%' OR LOWER(COLUMN_NAME) LIKE '%admin%' OR LOWER(COLUMN_NAME) LIKE '%role%' OR LOWER(COLUMN_NAME)='id') ORDER BY TABLE_NAME, ORDINAL_POSITION;\" 2>/dev/null | head -120 || true",
"printf '%s\\n' '== KEYHELP ADMIN ACCOUNTS =='",
"sudo mariadb --batch --skip-column-names -e \"SELECT id, username, is_admin, is_main_admin FROM keyhelp.users WHERE is_admin=1 OR is_main_admin=1 ORDER BY id;\" 2>/dev/null || true",
].join("; ");
try {
const output = execFileSync("ssh", [...common, `${c.user}@${HOST}`, command], { env, input: `${c.password}\n`, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 2 * 1024 * 1024 }).toString("utf8").trim();
return { error: false, text: output || "Keine API-Diagnosedaten gefunden." };
} catch (error) {
return { error: true, text: `KeyHelp-API-Diagnose fehlgeschlagen: ${String(error.stderr || error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 2000)}` };
}
});
}
function compareKeyHelpApiKey() {
const c = credential();
if (c.error) return { error: true, text: c.error };
return withAskpass(c.password, (env, common) => {
try {
const problem = ensureBitwarden();
if (problem) return { error: true, text: problem };
const items = readBwJson(["list", "items"]);
const hit = items.find((item) => /keyhelp.*api|api.*keyhelp/i.test(String(item.name || "")));
if (!hit?.id) return { error: true, text: "Kein KeyHelp-API-Eintrag in Bitwarden gefunden." };
const full = readBwJson(["get", "item", hit.id]);
const field = (full.fields || []).find((candidate) => /api.?key|token/i.test(String(candidate.name || "")));
const vaultKey = String(field?.value || full.login?.password || full.notes || "").trim();
const command = "sudo -S -p '' mariadb --batch --skip-column-names -e \"SELECT api_key FROM keyhelp.api_keys WHERE name='Jarvis' ORDER BY id DESC LIMIT 1;\"";
const stored = execFileSync("ssh", [...common, `${c.user}@${HOST}`, command], { env, input: `${c.password}\n`, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 64 * 1024 }).toString("utf8").trim();
const sha256 = crypto.createHash("sha256").update(vaultKey).digest("hex");
const result = {
vaultLength: vaultKey.length,
storedLength: stored.length,
exactMatch: crypto.timingSafeEqual(Buffer.from(crypto.createHash("sha256").update(vaultKey).digest()), Buffer.from(crypto.createHash("sha256").update(stored).digest())),
sha256Match: stored === sha256 || stored.endsWith(sha256),
vaultContainsWhitespace: /\s/.test(vaultKey),
};
return { error: false, text: JSON.stringify(result, null, 2) };
} catch (error) {
return { error: true, text: `KeyHelp-API-Key-Vergleich fehlgeschlagen: ${String(error.stderr || error.message || error).replace(/password|secret|token|api[_ -]?key/gi, "[redacted]").slice(0, 1200)}` };
}
});
}
function keyHelpVaultMetadata() {
const problem = ensureBitwarden();
if (problem) return { error: true, text: problem };
try {
try { runBw(["sync"]); } catch {}
const items = readBwJson(["list", "items"]);
const hit = items.find((item) => /keyhelp.*api|api.*keyhelp/i.test(String(item.name || "")));
if (!hit?.id) return { error: true, text: "Kein KeyHelp-API-Eintrag in Bitwarden gefunden." };
const full = readBwJson(["get", "item", hit.id]);
const metadata = {
name: hit.name,
loginUsernameLength: String(full.login?.username || "").length,
loginPasswordLength: String(full.login?.password || "").trim().length,
notesLength: String(full.notes || "").trim().length,
fields: (full.fields || []).map((field) => ({ name: String(field.name || ""), length: String(field.value || "").trim().length })),
};
return { error: false, text: JSON.stringify(metadata, null, 2) };
} catch (error) {
return { error: true, text: `Bitwarden-Metadaten konnten nicht gelesen werden: ${String(error.stderr || error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 1200)}` };
}
}
function inspectKeyHelpApiPanel() {
const c = credential();
if (c.error) return { error: true, text: c.error };
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "jarvis-keyhelp-panel-"));
const cookies = path.join(dir, "cookies.txt");
const escapeConfig = (value) => String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/[\r\n]+/g, " ");
const common = (url) => [
`url = "https://${HOST}/${url}"`,
'header = "Host: webhost.your-domain.com"',
`cookie = "${escapeConfig(cookies)}"`,
`cookie-jar = "${escapeConfig(cookies)}"`,
"insecure",
"silent",
"show-error",
"location",
];
try {
const loginConfig = [
...common("index.php"),
'header = "Content-Type: application/x-www-form-urlencoded"',
`data = "submit=1&username=keyadmin&password=${escapeConfig(encodeURIComponent(c.password))}"`,
].join("\n") + "\n";
execFileSync("curl", ["--config", "-"], { input: loginConfig, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 4 * 1024 * 1024 });
const fetchPage = (url) => execFileSync("curl", ["--config", "-"], { input: common(url).join("\n") + "\n", timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 8 * 1024 * 1024 }).toString("utf8");
const describe = (html) => ({
page: html.match(/"app\.page"\s*:\s*"([^"]*)"/)?.[1] || "unknown",
forms: [...html.matchAll(/<form\b([^>]*)>/gi)].map((match) => ({
id: match[1].match(/\bid="([^"]*)"/i)?.[1] || "",
action: match[1].match(/\baction="([^"]*)"/i)?.[1].replace(/&amp;/g, "&") || "",
method: match[1].match(/\bmethod="([^"]*)"/i)?.[1] || "GET",
})),
inputs: [...html.matchAll(/<input\b([^>]*)>/gi)].map((match) => {
const attributes = match[1];
const name = attributes.match(/\bname="([^"]*)"/i)?.[1] || "";
const type = attributes.match(/\btype="([^"]*)"/i)?.[1] || "text";
const value = attributes.match(/\bvalue="([^"]*)"/i)?.[1] || "";
return { name, type, valueLength: value.length, checked: /\bchecked\b/i.test(attributes) };
}).filter((input) => input.name),
textareas: [...html.matchAll(/<textarea\b([^>]*)>([\s\S]*?)<\/textarea>/gi)].map((match) => ({ name: match[1].match(/\bname="([^"]*)"/i)?.[1] || "", valueLength: match[2].trim().length })),
links: [...new Set([...html.matchAll(/\bhref="([^"]*admin_api[^"]*)"/gi)].map((match) => match[1].replace(/&amp;/g, "&")))],
buttons: [...html.matchAll(/<button\b([^>]*)>([\s\S]*?)<\/button>/gi)].map((match) => ({
name: match[1].match(/\bname="([^"]*)"/i)?.[1] || "",
value: match[1].match(/\bvalue="([^"]*)"/i)?.[1] || "",
type: match[1].match(/\btype="([^"]*)"/i)?.[1] || "submit",
text: match[2].replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim().slice(0, 120),
})),
});
const html = fetchPage("index.php?page=admin_api");
const loggedIn = /"is_logged_in"\s*:\s*true/.test(html) && !/id="form-login"/.test(html);
const result = { loggedIn, overview: describe(html) };
if (loggedIn) {
result.add = describe(fetchPage("index.php?page=admin_api&action=add"));
result.edit = describe(fetchPage("index.php?page=admin_api&action=edit&id=1"));
}
return { error: !loggedIn, text: JSON.stringify(result, null, 2).slice(0, 30000) };
} catch (error) {
return { error: true, text: `KeyHelp-Panel konnte nicht read-only geprueft werden: ${String(error.stderr || error.message || error).replace(/password|secret|token|csrf/gi, "[redacted]").slice(0, 1500)}` };
} finally {
try { fs.rmSync(dir, { recursive: true, force: true }); } catch {}
}
}
function rotateKeyHelpApiKey(args) {
if (args.confirm !== true) return { error: true, text: "Neuer KeyHelp-API-Key benoetigt confirm=true." };
const c = credential();
if (c.error) return { error: true, text: c.error };
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "jarvis-keyhelp-rotate-"));
const cookies = path.join(dir, "cookies.txt");
const escapeConfig = (value) => String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/[\r\n]+/g, " ");
const common = (url) => [
`url = "https://${HOST}/${url}"`,
'header = "Host: webhost.your-domain.com"',
`cookie = "${escapeConfig(cookies)}"`,
`cookie-jar = "${escapeConfig(cookies)}"`,
"insecure", "silent", "show-error", "location",
];
const curl = (config) => execFileSync("curl", ["--config", "-"], { input: config.join("\n") + "\n", timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 8 * 1024 * 1024 }).toString("utf8");
try {
curl([...common("index.php"), 'header = "Content-Type: application/x-www-form-urlencoded"', `data = "submit=1&username=keyadmin&password=${escapeConfig(encodeURIComponent(c.password))}"`]);
const addHtml = curl(common("index.php?page=admin_api&action=add"));
if (!/"is_logged_in"\s*:\s*true/.test(addHtml)) return { error: true, text: "KeyHelp-Panel-Anmeldung fuer die API-Key-Erstellung fehlgeschlagen." };
const csrf = addHtml.match(/name="_csrf_token"[^>]*value="([^"]+)"/i)?.[1];
if (!csrf) return { error: true, text: "KeyHelp-CSRF-Token fuer die API-Key-Erstellung fehlt." };
const response = curl([
...common("index.php?page=admin_api&action=add"),
'header = "Content-Type: application/x-www-form-urlencoded"',
`data = "submit=1&id=&_csrf_token=${escapeConfig(encodeURIComponent(csrf))}&name=${escapeConfig(encodeURIComponent("Jarvis Deploy"))}&ips=${escapeConfig(encodeURIComponent("YOUR_SERVER_IP\n127.0.0.1"))}"`,
]);
const candidates = [...new Set([
...[...response.matchAll(/value="([A-Za-z0-9._~+\/=:-]{64,200})"/g)].map((match) => match[1]),
...[...response.matchAll(/\b([A-Za-z0-9._~+\/=:-]{100,200})\b/g)].map((match) => match[1]),
])].filter((value) => value !== csrf).sort((a, b) => Math.abs(a.length - 120) - Math.abs(b.length - 120));
let verified;
for (const candidate of candidates.slice(0, 8)) {
const config = [
`url = "https://${HOST}/api/v2/clients"`,
'header = "Host: webhost.your-domain.com"',
`header = "X-API-Key: ${escapeConfig(candidate)}"`,
'header = "Accept: application/json"',
"insecure", "silent", "show-error",
].join("\n") + "\n";
try {
const status = execFileSync("curl", ["--config", "-", "--output", process.platform === "win32" ? "NUL" : "/dev/null", "--write-out", "%{http_code}"], { input: config, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"] }).toString("utf8").trim();
if (status === "200") { verified = candidate; break; }
} catch {}
}
if (!verified) return { error: true, text: `KeyHelp hat den neuen Eintrag verarbeitet, aber kein einmalig angezeigter Key konnte verifiziert werden (${candidates.length} Kandidaten erkannt).` };
const temp = `${KEYHELP_TOKEN_FILE}.${process.pid}.tmp`;
fs.writeFileSync(temp, `${verified}\n`, { mode: 0o600, flag: "wx" });
fs.renameSync(temp, KEYHELP_TOKEN_FILE);
fs.chmodSync(KEYHELP_TOKEN_FILE, 0o600);
cachedKeyHelpAuth = { key: verified, source: `Datei ${KEYHELP_TOKEN_FILE}`, length: verified.length };
return { error: false, text: `Neuer KeyHelp-API-Key wurde im Panel angelegt, gegen /clients verifiziert und sicher gespeichert (${verified.length} Zeichen, Modus 0600).` };
} catch (error) {
return { error: true, text: `KeyHelp-API-Key-Erstellung fehlgeschlagen: ${String(error.stderr || error.message || error).replace(/password|secret|token|csrf|api[_ -]?key/gi, "[redacted]").slice(0, 1500)}` };
} finally {
try { fs.rmSync(dir, { recursive: true, force: true }); } catch {}
}
}
async function cloudflareDnsUpsert(args) {
if (args.confirm !== true) return { error: true, text: "DNS-Änderung benötigt confirm=true." };
const hostname = String(args.hostname || "").toLowerCase().replace(/\.$/, "");
const type = String(args.type || "CNAME").toUpperCase();
const content = String(args.content || "").trim();
if (!hostname.endsWith(".your-domain.com") || hostname === "your-domain.com") return { error: true, text: "Erlaubt sind nur Subdomains unter your-domain.com." };
if (!["A", "AAAA", "CNAME"].includes(type)) return { error: true, text: "Nur A, AAAA oder CNAME sind erlaubt." };
if (!content || /[\r\n]/.test(content)) return { error: true, text: "DNS-Ziel fehlt oder ist ungültig." };
let token;
try { token = fs.readFileSync(CLOUDFLARE_TOKEN_FILE, "utf8").trim(); } catch { return { error: true, text: "Cloudflare-Token ist auf dem Deploy-Host nicht verfügbar." }; }
if (!token) return { error: true, text: "Cloudflare-Token ist leer." };
const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" };
const api = async (url, init = {}) => {
const response = await fetch(`https://api.cloudflare.com/client/v4${url}`, { ...init, headers: { ...headers, ...(init.headers || {}) } });
const body = await response.json();
if (!response.ok || !body.success) throw new Error(body.errors?.map((e) => e.message).join(", ") || `Cloudflare HTTP ${response.status}`);
return body.result;
};
try {
const zones = await api(`/zones?name=your-domain.com&status=active`);
const zone = zones[0];
if (!zone?.id) return { error: true, text: "Cloudflare-Zone your-domain.com nicht gefunden." };
const records = await api(`/zones/${zone.id}/dns_records?type=${type}&name=${encodeURIComponent(hostname)}`);
const record = { type, name: hostname, content, ttl: 1, proxied: args.proxied !== false };
const saved = records[0]
? await api(`/zones/${zone.id}/dns_records/${records[0].id}`, { method: "PUT", body: JSON.stringify(record) })
: await api(`/zones/${zone.id}/dns_records`, { method: "POST", body: JSON.stringify(record) });
return { error: false, text: `DNS-Record ${saved.name} (${saved.type}) wurde ${records[0] ? "aktualisiert" : "angelegt"}.` };
} catch (error) {
return { error: true, text: `Cloudflare-DNS-Änderung fehlgeschlagen: ${String(error.message || error).replace(/token|secret/gi, "[redacted]")}` };
}
}
const TOOLS = [
{
name: "webhost_probe",
description: "Prüft den internen SSH-Zugang zur PDEV-WEB-VM über Bitwarden, ohne Dateien zu ändern.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
},
{
name: "cloudflare_dns_upsert",
description: "Legt nach ausdrücklicher Bestätigung einen A-, AAAA- oder CNAME-Record für eine Subdomain unter your-domain.com an oder aktualisiert ihn.",
inputSchema: { type: "object", properties: { hostname: { type: "string" }, type: { type: "string", enum: ["A", "AAAA", "CNAME"] }, content: { type: "string" }, proxied: { type: "boolean" }, confirm: { type: "boolean" } }, required: ["hostname", "type", "content", "confirm"], additionalProperties: false },
},
{
name: "keyhelp_discover",
description: "Ermittelt read-only KeyHelp-Pfade, Webroots, Dienste und die fuer administrator erlaubten sudo-Kommandos.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
},
{
name: "keyhelp_api_schema",
description: "Liest read-only das lokale KeyHelp-OpenAPI-Schema fuer Domains, Clients und Zertifikate.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
},
{
name: "keyhelp_api_probe",
description: "Prueft read-only KeyHelp-API-Key, API-Aktivierung sowie sichtbare Clients und Domains, ohne Secrets auszugeben.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
},
{
name: "keyhelp_api_diagnose",
description: "Liest read-only die letzten KeyHelp-API-Zugriffsquellen und relevante IP-Prueflogik, ohne API-Keys auszugeben.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
},
{
name: "keyhelp_api_compare",
description: "Vergleicht den Bitwarden-Key mit dem KeyHelp-Pruefwert ausschliesslich ueber Laengen und Hashes, ohne Secrets auszugeben.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
},
{
name: "keyhelp_vault_metadata",
description: "Zeigt ausschliesslich Feldnamen und Laengen des KeyHelp-API-Bitwarden-Eintrags, niemals Feldinhalte.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
},
{
name: "keyhelp_panel_api_inspect",
description: "Meldet sich read-only am KeyHelp-Panel an und zeigt nur API-Formularstruktur sowie Wertlaengen, niemals Secrets.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
},
{
name: "keyhelp_api_rotate",
description: "Legt nach Bestaetigung ueber das KeyHelp-Panel einen IP-begrenzten Deploy-Key an, verifiziert und speichert ihn ohne Ausgabe des Secrets.",
inputSchema: { type: "object", properties: { confirm: { type: "boolean" } }, required: ["confirm"], additionalProperties: false },
},
{
name: "webhost_deploy_release",
description: "Fuehrt einen bestaetigten manifestgesteuerten KeyHelp-Produktivdeploy mit Build, atomarem Release, optionaler Laravel-Migration, Healthcheck und Rollback aus.",
inputSchema: { type: "object", properties: { source_dir: { type: "string" }, confirm: { type: "boolean" }, confirm_migration: { type: "boolean" } }, required: ["source_dir", "confirm"], additionalProperties: false },
},
];
function send(id, result) { process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\n"); }
function replyText(id, text, error = false) { send(id, { content: [{ type: "text", text }], isError: error }); }
let buffer = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
buffer += chunk;
let i;
while ((i = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, i).trim();
buffer = buffer.slice(i + 1);
if (!line) continue;
let msg;
try { msg = JSON.parse(line); } catch { continue; }
if (msg.method === "initialize") send(msg.id, { protocolVersion: msg.params?.protocolVersion || "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "web-deploy", version: "1.0.0" } });
else if (msg.method === "tools/list") send(msg.id, { tools: TOOLS });
else if (msg.method === "tools/call") {
const name = msg.params?.name;
const result = name === "webhost_probe" ? probeHost() : name === "webhost_deploy_release" ? deployRelease(msg.params?.arguments || {}) : name === "cloudflare_dns_upsert" ? cloudflareDnsUpsert(msg.params?.arguments || {}) : name === "keyhelp_discover" ? discoverKeyHelp() : name === "keyhelp_api_schema" ? keyHelpApiSchema() : name === "keyhelp_api_probe" ? keyHelpApiProbe() : name === "keyhelp_api_diagnose" ? keyHelpApiDiagnose() : name === "keyhelp_api_compare" ? compareKeyHelpApiKey() : name === "keyhelp_vault_metadata" ? keyHelpVaultMetadata() : name === "keyhelp_panel_api_inspect" ? inspectKeyHelpApiPanel() : name === "keyhelp_api_rotate" ? rotateKeyHelpApiKey(msg.params?.arguments || {}) : { error: true, text: "Unbekanntes Werkzeug." };
Promise.resolve(result).then((value) => replyText(msg.id, value.text, value.error));
}
}
});
+389
View File
@@ -0,0 +1,389 @@
#!/usr/bin/env python3
"""Bitwarden-backed Windows Server administration over WinRM and RDP metadata."""
import hashlib
import json
import os
import re
import socket
import ssl
import stat
import subprocess
import sys
import time
from datetime import datetime, timezone
from urllib.parse import urlparse
DEPENDENCIES = os.environ.get("WINDOWS_PYTHON_PATH", "/home/node/.openclaw/windows-python")
sys.path.insert(0, DEPENDENCIES)
BW_DATA_DIR = os.environ.get("BW_DATA_DIR", "/home/node/.openclaw/bw-data")
BW_CLI = os.environ.get("BW_CLI", "/home/node/.openclaw/bw-cli/node_modules/@bitwarden/cli/build/bw.js")
BW_MP_FILE = os.environ.get("BW_MP_FILE", "/home/node/.openclaw/mcp/.bw-masterpass")
AUDIT_FILE = os.environ.get("WINDOWS_AUDIT_FILE", "/home/node/.openclaw/mcp/.windows-audit.jsonl")
MAX_OUTPUT = 60000
TARGET_CACHE_SECONDS = 120
_bw_session = None
_target_cache = None
_target_cache_at = 0.0
def _safe_error(value):
return re.sub(r"(?i)(password|secret|token|session)\S*", "[redacted]", str(value))[:2000]
def _read_masterpass():
st = os.stat(BW_MP_FILE)
if stat.S_IMODE(st.st_mode) & 0o077 or st.st_uid != 1000:
raise RuntimeError("Bitwarden-Masterpasswortdatei hat unsichere Berechtigungen.")
value = open(BW_MP_FILE, encoding="utf-8").read().strip()
if not value:
raise RuntimeError("Bitwarden-Masterpasswortdatei ist leer.")
def _bw(args, with_session=True, timeout=120):
env = dict(os.environ)
env["BITWARDENCLI_APPDATA_DIR"] = BW_DATA_DIR
if with_session and _bw_session:
env["BW_SESSION"] = _bw_session
completed = subprocess.run(
[BW_CLI] + list(args),
env=env,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=timeout,
check=False,
)
if completed.returncode:
raise RuntimeError(_safe_error(completed.stderr.decode("utf-8", errors="replace") or "Bitwarden CLI fehlgeschlagen"))
return completed.stdout.decode("utf-8", errors="replace")
def _ensure_bw():
global _bw_session
if _bw_session:
return
_read_masterpass()
_bw_session = _bw(["unlock", "--raw", "--passwordfile", BW_MP_FILE], with_session=False).strip()
if not _bw_session:
raise RuntimeError("Bitwarden lieferte keine Session.")
try:
_bw(["sync"])
except Exception:
pass
def _fields(item):
return {str(field.get("name", "")).strip().lower(): str(field.get("value", "")).strip() for field in item.get("fields", []) if field.get("name")}
def _endpoint_from_uri(uri):
parsed = urlparse(uri)
scheme = parsed.scheme.lower()
if scheme == "winrm":
return f"http://{parsed.hostname}:{parsed.port or 5985}{parsed.path or '/wsman'}"
if scheme == "winrms":
return f"https://{parsed.hostname}:{parsed.port or 5986}{parsed.path or '/wsman'}"
if scheme in {"http", "https"} and (parsed.port in {5985, 5986} or parsed.path.rstrip("/").endswith("wsman")):
return uri
return None
def _parse_target(item):
name = str(item.get("name", "")).strip()
fields = _fields(item)
login = item.get("login") or {}
uris = [str(value.get("uri", "")).strip() for value in login.get("uris", []) if value.get("uri")]
marked = fields.get("jarvis.windows.target", "").lower() in {"1", "true", "yes", "ja"}
domain_account = bool(re.match(r"^pdev\s*-\s*dom", name, re.I))
if not marked and not domain_account and not re.match(r"^(windows|winrm)\s*[-:]", name, re.I) and not any(urlparse(uri).scheme.lower() in {"winrm", "winrms", "rdp"} for uri in uris):
return None
bare_host = next((uri for uri in uris if re.match(r"^[A-Za-z0-9._-]+$", uri)), "")
endpoint = fields.get("winrm_url") or next((value for value in (_endpoint_from_uri(uri) for uri in uris) if value), "") or (f"http://{bare_host}:5985/wsman" if bare_host else "")
rdp_uri = next((urlparse(uri) for uri in uris if urlparse(uri).scheme.lower() == "rdp"), None)
endpoint_uri = urlparse(endpoint) if endpoint else None
host = fields.get("rdp_host") or (rdp_uri.hostname if rdp_uri else None) or (endpoint_uri.hostname if endpoint_uri else None) or bare_host
if not host or not re.match(r"^[A-Za-z0-9._:-]+$", host):
return None
alias = fields.get("alias") or (name.split("-", 1)[0].strip() if domain_account else re.sub(r"^(windows|winrm)\s*[-:]\s*", "", name, flags=re.I).strip()) or host
username = str(login.get("username", "")).strip()
password = str(login.get("password", ""))
if not username or not password:
return None
fingerprint = re.sub(r"[^0-9a-f]", "", fields.get("winrm_cert_sha256", ""), flags=re.I).upper()
return {
"alias": alias[:80],
"name": name[:120],
"host": host,
"rdp_port": int(fields.get("rdp_port", rdp_uri.port if rdp_uri else 3389)),
"endpoint": endpoint,
"fingerprint": fingerprint,
"username": username,
"password": password,
"transport": "ntlm",
}
def targets(force=False):
global _target_cache, _target_cache_at
if not force and _target_cache is not None and time.monotonic() - _target_cache_at < TARGET_CACHE_SECONDS:
return _target_cache
_ensure_bw()
if force:
try:
_bw(["sync"])
except Exception:
pass
items = json.loads(_bw(["list", "items"]))
parsed = [target for item in items if (target := _parse_target(item))]
aliases = set()
for target in parsed:
key = target["alias"].casefold()
if key in aliases:
raise RuntimeError(f"Bitwarden enthaelt den Windows-Alias mehrfach: {target['alias']}")
aliases.add(key)
_target_cache = parsed
_target_cache_at = time.monotonic()
return parsed
def target_for(alias):
wanted = str(alias or "").strip().casefold()
found = next((target for target in targets() if target["alias"].casefold() == wanted), None)
if not found:
raise RuntimeError("Windows-Ziel nicht gefunden. Zuerst windows_targets verwenden und den Bitwarden-Alias exakt uebernehmen.")
return found
def _tcp(host, port, timeout=5):
started = time.monotonic()
try:
with socket.create_connection((host, port), timeout=timeout):
return True, round((time.monotonic() - started) * 1000)
except OSError:
return False, round((time.monotonic() - started) * 1000)
def _verify_certificate(target):
endpoint = target["endpoint"]
parsed = urlparse(endpoint)
if parsed.scheme != "https":
return None
if len(target["fingerprint"]) != 64:
raise RuntimeError("HTTPS-WinRM benoetigt im Bitwarden-Eintrag das Feld winrm_cert_sha256.")
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
with socket.create_connection((parsed.hostname, parsed.port or 5986), timeout=8) as raw:
with context.wrap_socket(raw, server_hostname=parsed.hostname) as tls:
actual = hashlib.sha256(tls.getpeercert(binary_form=True)).hexdigest().upper()
if actual != target["fingerprint"]:
raise RuntimeError("Windows-WinRM-Zertifikat stimmt nicht mit dem Bitwarden-Fingerprint ueberein.")
return actual
def _run_ps(target, script):
if not target["endpoint"]:
raise RuntimeError("Der Bitwarden-Eintrag enthaelt keine WinRM-URL.")
_verify_certificate(target)
try:
import winrm
except ImportError as exc:
raise RuntimeError(f"pywinrm fehlt unter {DEPENDENCIES}.") from exc
session = winrm.Session(
target["endpoint"],
auth=(target["username"], target["password"]),
transport=target["transport"],
server_cert_validation="ignore",
operation_timeout_sec=60,
read_timeout_sec=75,
)
response = session.run_ps("$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; " + script)
stdout = response.std_out.decode("utf-8", errors="replace").strip()
stderr = response.std_err.decode("utf-8", errors="replace").strip()
if response.status_code != 0:
raise RuntimeError(f"Remote PowerShell endete mit Code {response.status_code}: {(stderr or stdout or 'keine Details')[:4000]}")
if stderr:
stdout = f"{stdout}\n\nWarnungen:\n{stderr}".strip()
return stdout[:MAX_OUTPUT] + ("\n... (Ausgabe gekuerzt)" if len(stdout) > MAX_OUTPUT else "")
def _ps_literal(value):
return "'" + str(value).replace("'", "''") + "'"
def _json_result(title, target, script):
output = _run_ps(target, script)
try:
output = json.dumps(json.loads(output), ensure_ascii=False, indent=2)
except (json.JSONDecodeError, TypeError):
pass
return f"## {title}\n\n```json\n{output or '(keine Daten)'}\n```"
def _audit(action, target, details):
record = {"timestamp": datetime.now(timezone.utc).isoformat(), "action": action, "target": target["alias"], "endpoint": target["endpoint"], "details": details}
fd = os.open(AUDIT_FILE, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
with os.fdopen(fd, "a", encoding="utf-8") as handle:
handle.write(json.dumps(record, ensure_ascii=True) + "\n")
os.chmod(AUDIT_FILE, 0o600)
def windows_targets(_args):
data = [{"alias": t["alias"], "name": t["name"], "host": t["host"], "winrm": t["endpoint"] or None, "rdpPort": t["rdp_port"], "httpsPinned": bool(t["fingerprint"])} for t in targets(force=True)]
if not data:
return "Keine Windows-Ziele in Bitwarden freigegeben. Erwartet wird ein Login-Eintrag 'Windows - <Alias>' mit winrm://, winrms:// oder rdp:// URI."
return "## Freigegebene Windows-Ziele\n\n```json\n" + json.dumps(data, ensure_ascii=False, indent=2) + "\n```"
def windows_probe(args):
target = target_for(args.get("target"))
parsed = urlparse(target["endpoint"]) if target["endpoint"] else None
winrm_port = parsed.port or (5986 if parsed and parsed.scheme == "https" else 5985)
winrm_ok, winrm_ms = _tcp(target["host"], winrm_port) if parsed else (False, 0)
rdp_ok, rdp_ms = _tcp(target["host"], target["rdp_port"])
fingerprint = None
if winrm_ok and parsed and parsed.scheme == "https":
fingerprint = _verify_certificate(target)
return json.dumps({"target": target["alias"], "host": target["host"], "winrm": {"configured": bool(parsed), "reachable": winrm_ok, "port": winrm_port, "latencyMs": winrm_ms, "certificateSha256": fingerprint}, "rdp": {"reachable": rdp_ok, "port": target["rdp_port"], "latencyMs": rdp_ms}}, indent=2)
def windows_status(args):
target = target_for(args.get("target"))
return _json_result("Windows Server Status", target, r"""
$os = Get-CimInstance Win32_OperatingSystem
$cs = Get-CimInstance Win32_ComputerSystem
$cpu = Get-CimInstance Win32_Processor | Select-Object -First 1
[pscustomobject]@{ ComputerName=$env:COMPUTERNAME; Domain=$cs.Domain; Windows=$os.Caption; Version=$os.Version; Build=$os.BuildNumber; LastBoot=$os.LastBootUpTime.ToString('o'); UptimeHours=[math]::Round(((Get-Date)-$os.LastBootUpTime).TotalHours,1); Cpu=$cpu.Name; LogicalProcessors=$cs.NumberOfLogicalProcessors; MemoryTotalGiB=[math]::Round($cs.TotalPhysicalMemory/1GB,2); MemoryFreeGiB=[math]::Round($os.FreePhysicalMemory*1KB/1GB,2) } | ConvertTo-Json -Compress
""")
def windows_services(args):
target = target_for(args.get("target"))
search = _ps_literal(str(args.get("search", "")).strip())
limit = max(1, min(500, int(args.get("limit", 100))))
return _json_result("Windows Dienste", target, f"$q={search}; @(Get-CimInstance Win32_Service | Where-Object {{ -not $q -or $_.Name -like \"*$q*\" -or $_.DisplayName -like \"*$q*\" }} | Sort-Object DisplayName | Select-Object -First {limit} Name,DisplayName,State,StartMode,StartName) | ConvertTo-Json -Compress")
def windows_service_control(args):
target = target_for(args.get("target"))
name = str(args.get("service", ""))
action = str(args.get("action", ""))
if args.get("confirm") != "APPLY" or action not in {"start", "stop", "restart"} or not re.match(r"^[A-Za-z0-9_.-]{1,128}$", name):
raise RuntimeError('Dienststeuerung erfordert gueltigen Dienst, Aktion und confirm="APPLY".')
command = {"start": "Start-Service", "stop": "Stop-Service", "restart": "Restart-Service"}[action]
_audit("service." + action, target, {"service": name})
return _json_result("Windows Dienststeuerung", target, f"{command} -Name {_ps_literal(name)}; Get-Service -Name {_ps_literal(name)} | Select-Object Name,DisplayName,Status,StartType | ConvertTo-Json -Compress")
def windows_event_log(args):
target = target_for(args.get("target"))
log_name = str(args.get("log_name", "System"))
if log_name not in {"System", "Application", "Security"}:
raise RuntimeError("Ungueltiges Event Log.")
hours = max(1, min(168, int(args.get("hours", 24))))
limit = max(1, min(200, int(args.get("limit", 50))))
return _json_result(f"Windows Event Log: {log_name}", target, f"$start=(Get-Date).AddHours(-{hours}); @(Get-WinEvent -FilterHashtable @{{LogName={_ps_literal(log_name)};StartTime=$start;Level=@(1,2,3)}} -ErrorAction SilentlyContinue | Select-Object -First {limit} TimeCreated,Id,LevelDisplayName,ProviderName,MachineName,Message) | ConvertTo-Json -Compress -Depth 3")
def windows_storage(args):
target = target_for(args.get("target"))
return _json_result("Windows Datentraeger", target, r"""@(Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object { [pscustomobject]@{ Drive=$_.DeviceID; Label=$_.VolumeName; FileSystem=$_.FileSystem; SizeGiB=[math]::Round($_.Size/1GB,2); FreeGiB=[math]::Round($_.FreeSpace/1GB,2); FreePercent=if($_.Size){[math]::Round($_.FreeSpace*100/$_.Size,1)}else{$null} } }) | ConvertTo-Json -Compress""")
def windows_processes(args):
target = target_for(args.get("target"))
limit = max(1, min(100, int(args.get("limit", 25))))
sort_by = str(args.get("sort_by", "memory"))
prop = "WorkingSet64" if sort_by == "memory" else "CPU"
if sort_by not in {"memory", "cpu"}:
raise RuntimeError("sort_by muss memory oder cpu sein.")
return _json_result("Windows Prozesse", target, f"@(Get-Process | Sort-Object {prop} -Descending | Select-Object -First {limit} Id,ProcessName,@{{N='CpuSeconds';E={{if($_.CPU){{[math]::Round($_.CPU,1)}}else{{$null}}}}}},@{{N='MemoryMiB';E={{[math]::Round($_.WorkingSet64/1MB,1)}}}},StartTime) | ConvertTo-Json -Compress")
def windows_rdp_sessions(args):
target = target_for(args.get("target"))
output = _run_ps(target, "$rows = quser.exe 2>$null; [pscustomobject]@{ RdpHost=$env:COMPUTERNAME; RdpPort=" + str(target["rdp_port"]) + "; Sessions=@($rows) } | ConvertTo-Json -Compress")
return f"## RDP-Sitzungen\n\n```json\n{output}\n```"
def windows_rdp_logoff(args):
target = target_for(args.get("target"))
session_id = int(args.get("session_id", -1))
if args.get("confirm") != "LOGOFF" or session_id < 0 or session_id > 65535:
raise RuntimeError('RDP-Abmeldung erfordert session_id und confirm="LOGOFF".')
_audit("rdp.logoff", target, {"sessionId": session_id})
_run_ps(target, f"logoff.exe {session_id}")
return f"RDP-Sitzung {session_id} auf {target['alias']} wurde abgemeldet."
def windows_run_powershell(args):
target = target_for(args.get("target"))
script = str(args.get("script", "")).strip()
if args.get("confirm") != "EXECUTE" or not script or len(script) > 20000:
raise RuntimeError('Administrative PowerShell erfordert ein Skript bis 20000 Zeichen und confirm="EXECUTE".')
_audit("powershell", target, {"sha256": hashlib.sha256(script.encode()).hexdigest(), "script": script})
output = _run_ps(target, script)
return f"## Administrative PowerShell-Ausgabe\n\n```text\n{output or '(keine Ausgabe)'}\n```"
TARGET = {"target": {"type": "string", "description": "Exakter Alias aus windows_targets."}}
TOOLS = [
{"name": "windows_targets", "description": "Listet die in Bitwarden fuer Jarvis freigegebenen Windows-Ziele ohne Zugangsdaten.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
{"name": "windows_probe", "description": "Prueft WinRM- und RDP-Erreichbarkeit eines freigegebenen Windows-Ziels. Lesend.", "inputSchema": {"type": "object", "properties": TARGET, "required": ["target"], "additionalProperties": False}},
{"name": "windows_status", "description": "Liest OS, Domaene, Uptime, CPU und RAM ueber WinRM.", "inputSchema": {"type": "object", "properties": TARGET, "required": ["target"], "additionalProperties": False}},
{"name": "windows_services", "description": "Listet Windows-Dienste. Lesend.", "inputSchema": {"type": "object", "properties": {**TARGET, "search": {"type": "string"}, "limit": {"type": "integer", "minimum": 1, "maximum": 500}}, "required": ["target"], "additionalProperties": False}},
{"name": "windows_service_control", "description": "Startet, stoppt oder startet einen Windows-Dienst nach expliziter Bestaetigung neu.", "inputSchema": {"type": "object", "properties": {**TARGET, "service": {"type": "string"}, "action": {"type": "string", "enum": ["start", "stop", "restart"]}, "confirm": {"type": "string", "enum": ["APPLY"]}}, "required": ["target", "service", "action", "confirm"], "additionalProperties": False}},
{"name": "windows_event_log", "description": "Liest Warnungen und Fehler aus Windows Event Logs.", "inputSchema": {"type": "object", "properties": {**TARGET, "log_name": {"type": "string", "enum": ["System", "Application", "Security"]}, "hours": {"type": "integer", "minimum": 1, "maximum": 168}, "limit": {"type": "integer", "minimum": 1, "maximum": 200}}, "required": ["target"], "additionalProperties": False}},
{"name": "windows_storage", "description": "Liest Windows-Datentraeger und freien Speicher.", "inputSchema": {"type": "object", "properties": TARGET, "required": ["target"], "additionalProperties": False}},
{"name": "windows_processes", "description": "Listet Prozesse nach CPU oder Speicher. Lesend.", "inputSchema": {"type": "object", "properties": {**TARGET, "sort_by": {"type": "string", "enum": ["memory", "cpu"]}, "limit": {"type": "integer", "minimum": 1, "maximum": 100}}, "required": ["target"], "additionalProperties": False}},
{"name": "windows_rdp_sessions", "description": "Liest aktive RDP-Sitzungen ueber WinRM und gibt RDP-Verbindungsdaten ohne Passwort aus.", "inputSchema": {"type": "object", "properties": TARGET, "required": ["target"], "additionalProperties": False}},
{"name": "windows_rdp_logoff", "description": "Meldet eine RDP-Sitzung nach expliziter Bestaetigung ab.", "inputSchema": {"type": "object", "properties": {**TARGET, "session_id": {"type": "integer"}, "confirm": {"type": "string", "enum": ["LOGOFF"]}}, "required": ["target", "session_id", "confirm"], "additionalProperties": False}},
{"name": "windows_run_powershell", "description": "Fuehrt nach expliziter Bestaetigung administrative PowerShell auf einem freigegebenen Bitwarden-Ziel aus. Vollstaendig auditiert.", "inputSchema": {"type": "object", "properties": {**TARGET, "script": {"type": "string"}, "confirm": {"type": "string", "enum": ["EXECUTE"]}}, "required": ["target", "script", "confirm"], "additionalProperties": False}},
]
DISPATCH = {name: fn for name, fn in {
"windows_targets": windows_targets, "windows_probe": windows_probe, "windows_status": windows_status,
"windows_services": windows_services, "windows_service_control": windows_service_control,
"windows_event_log": windows_event_log, "windows_storage": windows_storage,
"windows_processes": windows_processes, "windows_rdp_sessions": windows_rdp_sessions,
"windows_rdp_logoff": windows_rdp_logoff, "windows_run_powershell": windows_run_powershell,
}.items()}
def send(message):
sys.stdout.write(json.dumps(message, ensure_ascii=True, separators=(",", ":")) + "\n")
sys.stdout.flush()
def handle(message):
request_id = message.get("id")
method = message.get("method")
params = message.get("params") or {}
if method == "notifications/initialized" or (request_id is None and method):
return
if method == "initialize":
send({"jsonrpc": "2.0", "id": request_id, "result": {"protocolVersion": params.get("protocolVersion", "2024-11-05"), "capabilities": {"tools": {}}, "serverInfo": {"name": "windows", "version": "2.0.0"}}})
elif method == "ping":
send({"jsonrpc": "2.0", "id": request_id, "result": {}})
elif method == "tools/list":
destructive = {"windows_service_control", "windows_rdp_logoff", "windows_run_powershell"}
tools = [{**tool, "annotations": {"title": tool["name"].replace("_", " "), "readOnlyHint": tool["name"] not in destructive, "destructiveHint": tool["name"] in destructive, "idempotentHint": tool["name"] not in destructive, "openWorldHint": True}} for tool in TOOLS]
send({"jsonrpc": "2.0", "id": request_id, "result": {"tools": tools}})
elif method == "tools/call":
name = params.get("name")
try:
if name not in DISPATCH:
raise RuntimeError("Unbekanntes Windows-Werkzeug.")
text = DISPATCH[name](params.get("arguments") or {})
send({"jsonrpc": "2.0", "id": request_id, "result": {"content": [{"type": "text", "text": text}], "isError": False}})
except Exception as exc:
send({"jsonrpc": "2.0", "id": request_id, "result": {"content": [{"type": "text", "text": _safe_error(exc)}], "isError": True}})
for line in sys.stdin:
try:
handle(json.loads(line))
except Exception:
continue
+548
View File
@@ -0,0 +1,548 @@
#!/usr/bin/env node
/**
* youtrack — MCP-Server fuer die jetbrains/youtrack-Instanz (http://YOUR_SERVER_IP:8089).
*
* Sicherheitsmodell:
* - Feste Basis-URL aus YOUTRACK_URL (kein Host/Port aus Tool-Eingaben -> kein SSRF).
* - Permanent-Token kommt aus einer Datei (YOUTRACK_TOKEN_FILE, uid 1000, Modus 600),
* nie aus dem Config-Text; wird nie geloggt.
* - Suchen und Einzelzugriffe mit expliziten Feldern, um Riesenantworten zu vermeiden;
* Texte auf MAX_CHARS begrenzt, Timeouts hart.
*/
'use strict';
const http = require('http');
const fs = require('fs');
const TIMEOUT_MS = 8000;
const MAX_CHARS = 60000;
const YT_BASE = process.env.YOUTRACK_URL || 'http://YOUR_SERVER_IP:8089';
const INT_NAMES = [...new Set(['Type', 'Priority', 'State', 'Assignee', 'Subsystem', 'Fix versions', 'Affected versions'])];
const DEFAULT_TYPES = {
Type: 'SingleEnumIssueCustomField',
Priority: 'SingleEnumIssueCustomField',
State: 'StateIssueCustomField',
Assignee: 'SingleUserIssueCustomField',
};
function readYoutrackToken() {
const p = process.env.YOUTRACK_TOKEN_FILE;
if (!p) return { error: 'YOUTRACK_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 request(path, token, options) {
return new Promise((resolve) => {
const started = Date.now();
const method = (options && options.method) || 'GET';
const body = options && options.body;
const headers = { Authorization: `Bearer ${token}`, ...(body ? { 'Content-Type': 'application/json' } : {}) };
const req = http.request(YT_BASE + path, { timeout: TIMEOUT_MS, method, headers }, (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, body: data.slice(0, MAX_CHARS) });
};
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) }));
if (body) req.write(JSON.stringify(body));
req.end();
});
}
function apiError(r, fallback) {
let desc = fallback;
if (r.parsed && typeof r.parsed === 'object') {
const e = [];
if (r.parsed.error_description || r.parsed.error) e.push(String(r.parsed.error_description || r.parsed.error));
if (r.parsed.error_field) e.push(`Feld: ${r.parsed.error_field}`);
if (e.length) desc = e.join('; ');
}
if (!desc && r.parseError) desc = r.parseError;
return desc;
}
const TOOLS = [
{
name: 'me',
description:
'Identitaet und Eigenschaften des YouTrack-Accounts, mit dem Jarvis zugreift (Login, Name, E-Mail, ob Gast). Lesend.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'list_projects',
description:
'Listet alle sichtbaren YouTrack-Projekte (Kurzname + Anzeigename). Lesend.',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
{
name: 'search_issues',
description:
'Durchsucht YouTrack mit der nativen Suchsyntax (z.B. "projekt PDEVHDI", "assignee: mich", "Diskuze: tasks", "erstellt: d-7d"). Liefert eine Tabelle mit Kurz-ID, Projekt und (offen/erledigt) und Zusammenfassung.',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string', description: 'YouTrack-Suchabfrage. Leer = alle sichtbaren Issues.' },
max: { type: 'integer', description: 'Maximale Anzahl Treffer (1-50, Standard 10).' },
},
additionalProperties: false,
},
},
{
name: 'get_issue',
description:
'Liefert ein einzelnes YouTrack-Issue mit Zusammenfassung, Beschreibung, Reporter, angepassten Feldern (Typ/Status/Prioritaet/…) und optionalen Kommentaren. Lesend.',
inputSchema: {
type: 'object',
properties: {
id: { type: 'string', description: 'Kurz-ID, z.B. PDEVHDI-3.' },
include_comments: { type: 'boolean', description: 'Kommentare mit ausgeben (Standard: false).' },
},
required: ['id'],
additionalProperties: false,
},
},
{
name: 'create_issue',
description:
'Legt ein neues YouTrack-Issue an. Erforderlich: Projekt-Kurzname und Zusammenfassung. Optionale anpassbare Felder als Liste {"name":"Type","value":"Task"} u.ae. (Werte finden sich via get_issue an einem bestehenden Issue des Projekts). Liefert die neue Kurz-ID.',
inputSchema: {
type: 'object',
properties: {
project: { type: 'string', description: 'Projekt-Kurzname, z.B. PDEVHDI.' },
summary: { type: 'string', description: 'Titel des Issues.' },
description: { type: 'string', description: 'Details/Markdown.' },
custom_fields: {
type: 'array',
items: {
type: 'object',
properties: {
name: { type: 'string', description: 'Feldname, z.B. Type, State, Priority, Assignee.' },
value: { description: 'Feldwert: Enum-Name als String oder Objekt (z.B. {"id":"…"}).' },
},
required: ['name', 'value'],
additionalProperties: false,
},
},
},
required: ['project', 'summary'],
additionalProperties: false,
},
},
{
name: 'add_comment',
description:
'Fuegt einem YouTrack-Issue einen Kommentar hinzu (z.B. Monitoring-Erkenntnisse). Liefert Kommentar-IDs/Bestatigung.',
inputSchema: {
type: 'object',
properties: {
id: { type: 'string', description: 'Kurz-ID, z.B. PDEVHDI-3.' },
text: { type: 'string', description: 'Kommentartext (Markdown moeglich).' },
},
required: ['id', 'text'],
additionalProperties: false,
},
},
{
name: 'update_issue_fields',
description:
'Aendert anpassbare Felder eines bestehenden YouTrack-Issues, z.B. State auf "Solved" (Status/State Bundle), Assignee, Priority. Liefert den neuen Feldzustand.',
inputSchema: {
type: 'object',
properties: {
id: { type: 'string', description: 'Kurz-ID, z.B. PDEVHDI-3.' },
custom_fields: {
type: 'array',
items: {
type: 'object',
properties: {
name: { type: 'string', description: 'Feldname, z.B. State, Assignee, Priority.' },
value: { description: 'Feldwert: Enum-Name als String oder Objekt.' },
},
required: ['name', 'value'],
additionalProperties: false,
},
},
},
required: ['id', 'custom_fields'],
additionalProperties: false,
},
},
];
function fmtValue(v) {
if (v === null || v === undefined) return '-';
if (typeof v === 'boolean') return v ? 'ja' : 'nein';
if (typeof v === 'object') {
if (v.name) return String(v.name);
if (v.login) return String(v.login);
if (v.seconds !== undefined) return Math.round(v.seconds / 3600) + ' h';
try {
return JSON.stringify(v);
} catch (e) {
return '?';
}
}
return String(v);
}
async function me() {
const auth = readYoutrackToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const r = await request('/api/users/me?fields=id,name,login,email,guest,$type', auth.token);
if (r.code !== 200 || !r.parsed) return { error: true, text: `Identitaet nicht lesbar: HTTP ${r.code} (${apiError(r, '')})` };
const u = r.parsed;
const lines = [
'## YouTrack-Account',
'',
`- Login: **${u.login || '?'}**`,
`- Name: ${u.name || '-'}`,
`- E-Mail: ${u.email || '-'}`,
`- Gast: ${u.guest ? 'ja' : 'nein'}`,
`- ID: ${u.id || '-'}`,
];
return { error: false, text: lines.join('\n') };
}
async function listProjects() {
const auth = readYoutrackToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const r = await request('/api/admin/projects?fields=shortName,name,description', auth.token);
if (r.code === 403) return { error: true, text: 'Projektliste nicht sichtbar (403) fuer diesen Account.' };
if (r.code !== 200 || !Array.isArray(r.parsed)) {
return { error: true, text: `Projektliste nicht lesbar: HTTP ${r.code} (${apiError(r, '')})` };
}
const lines = ['## YouTrack-Projekte', '', '| Kurzname | Name |', '|---|---|'];
for (const p of r.parsed) lines.push(`| ${p.shortName} | ${p.name || ''} |`);
return { error: false, text: lines.join('\n') };
}
async function searchIssues(args) {
const auth = readYoutrackToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const q = String((args && args.query) || '').trim();
const max = Math.min(50, Math.max(1, Number((args && args.max) || 10)));
const query = q ? `query=${encodeURIComponent(q)}&` : 'query=&';
const r = await request(
`/api/issues?${query}$top=${max}&fields=idReadable,summary,resolved,created,project(shortName,name)`,
auth.token
);
if (r.code !== 200 || !Array.isArray(r.parsed)) {
return { error: true, text: `Suche fehlgeschlagen: HTTP ${r.code} (${apiError(r, '')})` };
}
const lines = [
'## YouTrack-Issues',
'',
`Suche: \`${q || '(alle)'}\` — ${r.parsed.length} Treffer`,
'',
'| ID | Projekt | Zustand | Zusammenfassung |',
'|---|---|---|---|',
];
for (const i of r.parsed) {
const state = i.resolved ? 'erledigt' : 'offen';
const proj = (i.project && i.project.shortName) || '-';
lines.push(`| ${i.idReadable || i.id} | ${proj} | ${state} | ${String(i.summary || '').slice(0, 90)} |`);
}
return { error: false, text: lines.join('\n') };
}
async function getIssue(args) {
const auth = readYoutrackToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const id = String((args && args.id) || '').trim();
if (!/^[A-Z0-9]+-\d+$/i.test(id)) return { error: true, text: `Ungueltige Kurz-ID "${id}".` };
const withComments = !!(args && args.include_comments);
const fields = [
'idReadable',
'summary',
'description',
'created',
'updated',
'resolved',
'reporter(login,name)',
'project(shortName,name)',
'customFields(id,name,$type,value(name,login))',
];
if (withComments) fields.push('comments(id,text,created,author(login,name))');
const r = await request(`/api/issues/${encodeURIComponent(id)}?fields=${encodeURIComponent(fields.join(','))}`, auth.token);
if (r.code !== 200 || !r.parsed) {
return { error: true, text: `Issue ${id} nicht lesbar: HTTP ${r.code} (${apiError(r, '')})` };
}
const i = r.parsed;
const lines = [
`## ${i.idReadable || id} — ${i.summary || '(ohne Zusammenfassung)'}`,
'',
`- Projekt: ${(i.project && (i.project.shortName + ' ' + (i.project.name || ''))) || '-'}`,
`- Reporter: ${(i.reporter && (i.reporter.login || i.reporter.name)) || '-'}`,
`- Erstellt: ${i.created ? new Date(i.created).toISOString().replace('T', ' ').slice(0, 16) + 'U' : '-'}`,
i.updated ? `- Geaendert: ${new Date(i.updated).toISOString().replace('T', ' ').slice(0, 16) + 'U'}` : null,
`- Status: **${i.resolved ? 'erledigt' : 'offen'}**`,
'',
'### Angepasste Felder',
].filter((l) => l !== null);
const cfs = Array.isArray(i.customFields) ? i.customFields : [];
if (cfs.length) {
lines.push('', '| Feld | Wert |', '|---|---|');
for (const cf of cfs) lines.push(`| ${cf.name} | ${fmtValue(cf.value)} |`);
} else {
lines.push('', '(keine)');
}
lines.push('', '### Beschreibung');
lines.push(String(i.description || '*(leer)*').slice(0, MAX_CHARS / 2));
if (withComments) {
lines.push('', `### Kommentare (${Array.isArray(i.comments) ? i.comments.length : 0})`);
const cs = Array.isArray(i.comments) ? i.comments : [];
for (const c of cs.slice(0, 30)) {
const who = (c.author && (c.author.login || c.author.name)) || '?';
const when = c.created ? new Date(c.created).toISOString().replace('T', ' ').slice(0, 16) + 'U' : '?';
lines.push(`- **${who}** (${when}): ${String(c.text || '').slice(0, 600)}`);
}
}
return { error: false, text: lines.join('\n') };
}
async function resolveTypesFor(project, token) {
const r = await request(
`/api/issues?query=${encodeURIComponent(`project: ${project}`)}&$top=1&fields=customFields(id,name,$type)`,
token
);
const map = {};
if (r.code === 200 && Array.isArray(r.parsed) && r.parsed.length) {
for (const cf of r.parsed[0].customFields || []) if (cf.name && cf.$type) map[cf.name] = cf.$type;
}
return map;
}
function normaliseCustomFields(fields, types) {
return (fields || []).map((f) => {
const name = String(f.name || '').trim();
let value = f.value;
if (value !== null && typeof value === 'object' && !value.name && !value.id) {
throw new Error(`Feld "${name}": Wert muss ein String (Enum-Name) oder Objekt mit id/name sein.`);
}
if (typeof value === 'string') value = { name: value };
return {
name,
$type: (types && types[name]) || DEFAULT_TYPES[name] || 'SingleEnumIssueCustomField',
value,
};
});
}
async function createIssue(args) {
const auth = readYoutrackToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const project = String((args && args.project) || '').trim();
const summary = String((args && args.summary) || '').trim();
if (!project) return { error: true, text: 'Projekt-Kurzname fehlt.' };
if (!summary) return { error: true, text: 'Zusammenfassung fehlt.' };
const types = await resolveTypesFor(project, auth.token);
const body = { project: { shortName: project }, summary };
if (args && args.description) body.description = String(args.description);
if (args && args.custom_fields && args.custom_fields.length) {
try {
body.customFields = normaliseCustomFields(args.custom_fields, types);
} catch (e) {
return { error: true, text: e.message };
}
}
const r = await request(`/api/issues?fields=idReadable,summary,created,customFields(id,name,$type,value(name))`, auth.token, {
method: 'POST',
body,
});
if (r.code !== 200 || !r.parsed || !r.parsed.idReadable) {
return { error: true, text: `Anlegen fehlgeschlagen: HTTP ${r.code} (${apiError(r, 'Pflichtfelder evtl. unvollstaendig')})` };
}
const lines = [
`## Issue angelegt: ${r.parsed.idReadable}`,
'',
`- Zusammenfassung: ${r.parsed.summary}`,
];
for (const cf of r.parsed.customFields || []) lines.push(`- ${cf.name}: ${fmtValue(cf.value)}`);
lines.push('', `Tipp: Details liest du mit get_issue (id=${r.parsed.idReadable}).`);
return { error: false, text: lines.join('\n') };
}
async function addComment(args) {
const auth = readYoutrackToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const id = String((args && args.id) || '').trim();
const text = String((args && args.text) || '').trim();
if (!/^[A-Z0-9]+-\d+$/i.test(id)) return { error: true, text: `Ungueltige Kurz-ID "${id}".` };
if (!text) return { error: true, text: 'Kommentartext fehlt.' };
const r = await request(`/api/issues/${encodeURIComponent(id)}/comments?fields=id,text,author(login)`, auth.token, {
method: 'POST',
body: { text },
});
if (r.code !== 200 || !r.parsed) {
return { error: true, text: `Kommentar fehlgeschlagen: HTTP ${r.code} (${apiError(r, '')})` };
}
return {
error: false,
text: `Kommentar zu ${id} hinzugefuegt (von ${r.parsed.author ? r.parsed.author.login : '?'}).`,
};
}
async function updateFields(args) {
const auth = readYoutrackToken();
if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` };
const id = String((args && args.id) || '').trim();
if (!/^[A-Z0-9]+-\d+$/i.test(id)) return { error: true, text: `Ungueltige Kurz-ID "${id}".` };
const f = (args && args.custom_fields) || [];
if (!Array.isArray(f) || !f.length) return { error: true, text: 'Keine Felder angegeben.' };
const cur = await request(
`/api/issues/${encodeURIComponent(id)}?fields=customFields(id,name,$type)`,
auth.token
);
const types = {};
if (cur.code === 200 && cur.parsed && Array.isArray(cur.parsed.customFields)) {
for (const cf of cur.parsed.customFields) if (cf.name && cf.$type) types[cf.name] = cf.$type;
}
let customFields;
try {
customFields = normaliseCustomFields(f, types);
} catch (e) {
return { error: true, text: e.message };
}
const r = await request(
`/api/issues/${encodeURIComponent(id)}?fields=idReadable,customFields(name,value(name,login))`,
auth.token,
{ method: 'POST', body: { customFields } }
);
if (r.code !== 200 || !r.parsed) {
return { error: true, text: `Aendern fehlgeschlagen: HTTP ${r.code} (${apiError(r, '')})` };
}
const lines = ['## Felder aktualisiert', '', `- Issue: ${r.parsed.idReadable || id}`, '', '| Feld | Wert |', '|---|---|'];
for (const cf of r.parsed.customFields || []) lines.push(`| ${cf.name} | ${fmtValue(cf.value)} |`);
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 toolAnnotations(name) {
const read = !['create_issue', 'add_comment', 'update_issue_fields'].includes(name);
return {
title: name.replace(/_/g, ' '),
readOnlyHint: read,
destructiveHint: false,
idempotentHint: read,
openWorldHint: true,
};
}
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: 'youtrack', 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: toolAnnotations(name),
})),
});
return;
}
if (method === 'tools/call') {
const name = params && params.name;
const args = (params && params.arguments) || {};
const dispatch = {
me: [false, () => me()],
list_projects: [false, () => listProjects()],
search_issues: [false, () => searchIssues(args)],
get_issue: [false, () => getIssue(args)],
create_issue: [false, () => createIssue(args)],
add_comment: [false, () => addComment(args)],
update_issue_fields: [false, () => updateFields(args)],
};
const entry = dispatch[name];
if (!entry) {
reply(id, { content: [{ type: 'text', text: `Unbekanntes Werkzeug: ${name}` }], isError: true });
return;
}
entry[1]()
.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');
}