Files

376 lines
16 KiB
JavaScript

#!/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}`);
}