release: MUA 2026.11.21.r037
Lite profile for small models - /mcp/lite (or ?profile=lite, default via MUA_PROFILE) exposes the same functions as 9 grouped tools with an `action` field instead of 49 single tools. Schema size: read-only preset ~1.6k vs 2.9k tokens, full access ~3.3k vs 6.9k tokens. - Schemas are generated per request from the enabled tools only; permission checks always use the underlying full-profile tool. - Tolerates common mix-ups (name/container, cmd/command, action spelling), drops and reports unknown parameters, names missing required parameters. Names of both profiles work in both profiles. unraid_overview - One call: array/parity, disks (errors, temperature, fill level), RAM/CPU/temperatures, crashed or unhealthy containers, updates and important notifications, sorted by severity, each with a ready-made `next` call in the client's profile. Reads only enabled sources and reports "unknown" (never "ok") when nothing could be read. Container names - Read actions resolve unique partial names (plex -> binhex-plex); write actions require the exact name and answer with a suggestion. - Batch update accepts names separated by | or comma, or an array. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b8d89ffd9c
commit
a244195b94
17 files changed
+1248
-33
No files matched your search
@@ -7,7 +7,8 @@ Kompiliertes Bun-Binary (TypeScript), läuft als SysVinit-Service auf Unraid.
|
||||
- **Health-Check:** `http://UNRAID-IP:3002/health` (offen; Version/Port nur mit Bearer-Token)
|
||||
- **Config-Server:** `http://127.0.0.1:3013/config` (localhost + separater Admin-Token)
|
||||
- **Auth:** API-Key (Bearer-Token) für `/mcp`
|
||||
- **Tools:** 48 (Docker, Community Applications, Netzwerk, Unraid-System und optionale Toolbox)
|
||||
- **Profile:** `full` (alle Einzeltools, Standard) und `lite` (`/mcp/lite`, ~9 gebündelte Tools für kleine Modelle)
|
||||
- **Tools:** 49 (Docker, Community Applications, Netzwerk, Unraid-System und optionale Toolbox)
|
||||
|
||||
---
|
||||
|
||||
@@ -197,6 +198,39 @@ URL: http://UNRAID-IP:3002/mcp
|
||||
Auth: Authorization: Bearer <dein-api-key>
|
||||
```
|
||||
|
||||
### Profil wählen: `full` oder `lite`
|
||||
|
||||
| URL | Profil | Für |
|
||||
|---|---|---|
|
||||
| `http://UNRAID-IP:3002/mcp` | Standard (`MUA_PROFILE`, sonst `full`) | |
|
||||
| `http://UNRAID-IP:3002/mcp/full` | alle 49 Einzeltools | große Modelle (Claude, GPT-4-Klasse) |
|
||||
| `http://UNRAID-IP:3002/mcp/lite` | ~9 Gruppen-Tools mit `action` | kleine/lokale Modelle (7B–32B) |
|
||||
|
||||
`?profile=lite|full` an der URL funktioniert ebenfalls. Das Lite-Profil
|
||||
bündelt **dieselben** Funktionen: `unraid_docker` (`action: list|logs|restart|update|…`),
|
||||
`unraid_storage`, `unraid_network`, `unraid_system`, `unraid_apps`, `unraid_shell`,
|
||||
`unraid_toolbox`, dazu unverändert `unraid_overview` und `unraid_shell_readonly`.
|
||||
|
||||
- Es enthält nur freigegebene Aktionen. Die `action`-Liste wird pro Anfrage aus
|
||||
den Tool-Freigaben erzeugt; es entsteht keine neue Berechtigung.
|
||||
- Schema-Größe gemessen: „Nur Lesen“ ≈ 1,6k statt 2,9k Tokens, Vollzugriff
|
||||
≈ 3,3k statt 6,9k Tokens.
|
||||
- Typische Verwechslungen werden toleriert (`name` statt `container`,
|
||||
`cmd` statt `command`, `Update-Status` statt `update_status`); unbekannte
|
||||
Parameter werden ignoriert und im Ergebnis genannt.
|
||||
- Namen aus beiden Profilen sind in beiden Profilen aufrufbar.
|
||||
|
||||
**Einstieg für jedes Modell: `unraid_overview`.** Ein Aufruf liefert Array/Parity,
|
||||
Disks (Fehler, Temperatur, Füllstand), RAM/CPU/Temperaturen, abgestürzte oder
|
||||
unhealthy Container, Updates und wichtige Benachrichtigungen – sortiert nach
|
||||
Schwere, jeweils mit fertigem Folgeaufruf (`next`) im Profil des Clients. Es
|
||||
liest nur Quellen, deren eigenes Tool freigegeben ist.
|
||||
|
||||
**Container-Namen:** Lesende Aktionen lösen eindeutige Teilnamen auf
|
||||
(`plex` → `binhex-plex`, Hinweis im Ergebnis). Schreibende Aktionen
|
||||
(start/stop/restart/update/…) akzeptieren nur den exakten Namen oder abweichende
|
||||
Groß-/Kleinschreibung und antworten sonst mit „Did you mean …?“.
|
||||
|
||||
MUA läuft direkt auf Unraid und spricht **Streamable HTTP**. Ein SSH-Wrapper
|
||||
ist weder erforderlich noch empfohlen. Dadurch bleiben Verbindungen kompakt
|
||||
und routinemäßige Tool-Aufrufe erzeugen keine SSH-Anmeldungen im Unraid-Syslog.
|
||||
@@ -355,6 +389,7 @@ Prozess startet automatisch. Zusätzlich führt der POST-INSTALL-Hook im
|
||||
MUA_API_KEY=a1b2c3d4...
|
||||
MUA_ENABLED_TOOLS=unraid_docker_list,unraid_docker_inspect,unraid_network_list
|
||||
MUA_TOOLBOX_ENABLED=false
|
||||
MUA_PROFILE=full
|
||||
```
|
||||
|
||||
Sonderwerte: `all` aktiviert ausdrücklich alles, `none` deaktiviert alles.
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
625e56d3725e40479ec89e38c738728bf7e84724de5404dde8f5a43ebfec157d mua-2026.11.20.r036-x86_64-1.txz
|
||||
BIN
Binary file not shown.
@@ -0,0 +1 @@
|
||||
3ead78bbccbe9f3e8d629c2abfb7878bf3780ffbd815cef2c38cb56b5cfeb828 mua-2026.11.21.r037-x86_64-1.txz
|
||||
@@ -65,6 +65,10 @@ nebenbei oder nur zur Diagnose erfolgen.
|
||||
|
||||
## 3. MUA im zentralen Hermes-Gateway registrieren
|
||||
|
||||
Für kleine/lokale Modelle das kompakte Profil verwenden: URL
|
||||
`http://UNRAID-IP:3002/mcp/lite` statt `/mcp` (gleiche Funktionen, ~9 statt 49
|
||||
Tools). Erster Aufruf in einer Sitzung: `unraid_overview`.
|
||||
|
||||
Im Hermes-Container liegt die CLI in dieser Installation unter
|
||||
`/opt/hermes/bin/hermes`. Mit einem korrekt gesetzten `PATH` genügt `hermes`.
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mua",
|
||||
"version": "2026.11.20.r036",
|
||||
"version": "2026.11.21.r037",
|
||||
"description": "Mikes Unraid Agent - MCP over HTTP(S) (Streamable HTTP) for Unraid",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
|
||||
+12
-4
@@ -2,13 +2,13 @@
|
||||
<!DOCTYPE PLUGIN [
|
||||
<!ENTITY name "mua">
|
||||
<!ENTITY author "Michael">
|
||||
<!ENTITY version "2026.11.20.r036">
|
||||
<!ENTITY version "2026.11.21.r037">
|
||||
<!ENTITY launch "Settings/mua">
|
||||
<!ENTITY pluginURL "https://git.casaderoll.de/michael/MUA-Mikes-Unraid-Agent/raw/branch/main/plugin/mua.plg">
|
||||
<!ENTITY pluginLOC "/boot/config/plugins/&name;">
|
||||
<!ENTITY emhttpLOC "/usr/local/emhttp/plugins/&name;">
|
||||
<!ENTITY txzURL "https://git.casaderoll.de/michael/MUA-Mikes-Unraid-Agent/raw/branch/main/dist/mua-2026.11.20.r036-x86_64-1.txz">
|
||||
<!ENTITY txzSHA256 "625e56d3725e40479ec89e38c738728bf7e84724de5404dde8f5a43ebfec157d">
|
||||
<!ENTITY txzURL "https://git.casaderoll.de/michael/MUA-Mikes-Unraid-Agent/raw/branch/main/dist/mua-2026.11.21.r037-x86_64-1.txz">
|
||||
<!ENTITY txzSHA256 "3ead78bbccbe9f3e8d629c2abfb7878bf3780ffbd815cef2c38cb56b5cfeb828">
|
||||
]>
|
||||
|
||||
<PLUGIN name="&name;"
|
||||
@@ -23,6 +23,14 @@
|
||||
>
|
||||
|
||||
<CHANGES>
|
||||
### 2026.11.21.r037
|
||||
- Neues kompaktes Profil für kleine Modelle unter `/mcp/lite` (oder `?profile=lite`, Standard per `MUA_PROFILE`): dieselben Funktionen in 9 Gruppen-Tools mit `action` statt 49 Einzeltools. Bei „Nur Lesen“ ca. 1,6k statt 2,9k Tokens Schema, bei Vollzugriff ca. 3,3k statt 6,9k.
|
||||
- Lite-Schemas enthalten nur freigegebene Aktionen; Berechtigungen werden immer am zugrunde liegenden Tool geprüft. Typische Verwechslungen (name/container, cmd/command, Schreibweise der Aktion) werden toleriert, fehlende Pflichtparameter klar benannt.
|
||||
- Neues Einstiegs-Tool `unraid_overview`: Array/Parity, Disks (Fehler, Temperatur, Füllstand), RAM/CPU/Temperaturen, abgestürzte/unhealthy Container, Updates und wichtige Benachrichtigungen in einem Aufruf – nach Schwere sortiert, jeweils mit fertigem Folgeaufruf. Liest nur freigegebene Quellen; ist nichts lesbar, lautet der Status „unknown“, nie „ok“.
|
||||
- Fehlertolerante Container-Namen: Lesende Aktionen lösen eindeutige Teilnamen auf (plex → binhex-plex); schreibende Aktionen verlangen den exakten Namen und antworten sonst mit einem Vorschlag.
|
||||
- Batch-Update akzeptiert Namen getrennt durch | oder Komma oder als Liste.
|
||||
- WebGUI zeigt zusätzlich die Lite-URL.
|
||||
|
||||
### 2026.11.20.r036
|
||||
- Readonly-Shell versteht jetzt eine normale Befehlszeile (`command`): Quotes, Pipes zwischen erlaubten Programmen, `;`/`&&`/`||`, Globs in absoluten Pfaden; `2>&1` wird toleriert. Kleine Modelle kommen so in einem Aufruf zum Ergebnis.
|
||||
- Schließt Umgehungen der Readonly-Shell: `ip`-Abkürzungen (`ip a a`, `ip r d`, `ip link s`), `dmesg -c`/`-Tc`/`--console-level=`, `ss -tK`/`-D`, `date`-Operanden, `sort -o`, `uniq` mit Ausgabedatei, `file -C`. Optionen werden je Programm inkl. kombinierter Kurzflags und GNU-Abkürzungen geprüft.
|
||||
@@ -222,7 +230,7 @@ Das .txz enthält:
|
||||
install/doinst.sh (läuft nach Installation)
|
||||
===========================================
|
||||
-->
|
||||
<FILE Name="/boot/config/plugins/&name;/mua-2026.11.20.r036-x86_64-1.txz" Run="upgradepkg --install-new" Mode="755" Min="7.0.0">
|
||||
<FILE Name="/boot/config/plugins/&name;/mua-2026.11.21.r037-x86_64-1.txz" Run="upgradepkg --install-new" Mode="755" Min="7.0.0">
|
||||
<URL>&txzURL;</URL>
|
||||
<SHA256>&txzSHA256;</SHA256>
|
||||
</FILE>
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "mua",
|
||||
"author": "Michael",
|
||||
"version": "2026.11.20.r036",
|
||||
"version": "2026.11.21.r037",
|
||||
"minver": "7.0.0",
|
||||
"pluginDirectory": "/usr/local/emhttp/plugins/mua",
|
||||
"configDirectory": "/boot/config/plugins/mua",
|
||||
|
||||
+1
-1
@@ -177,7 +177,7 @@ $active_count = $all_tools_enabled ? count($all_tools) : count($enabled_tools);
|
||||
<div class="mua-card"><h3>Authentifizierung</h3><p class="mua-summary"><?= $config_ok ? '✅ Bearer-Key aktiv' : '❌ Verwaltung nicht erreichbar' ?></p><div class="mua-muted"><?= htmlspecialchars($config['apiKeyMasked'] ?? 'nicht verfügbar') ?></div></div>
|
||||
</div>
|
||||
|
||||
<div class="mua-card"><h3>MCP-Endpunkt</h3><code class="mua-endpoint"><?= htmlspecialchars($endpoint) ?></code><p class="mua-muted">Streamable HTTP · JSON-RPC 2.0 · Bearer-Authentifizierung erforderlich</p></div>
|
||||
<div class="mua-card"><h3>MCP-Endpunkt</h3><code class="mua-endpoint"><?= htmlspecialchars($endpoint) ?></code><p class="mua-muted">Streamable HTTP · JSON-RPC 2.0 · Bearer-Authentifizierung erforderlich</p><?php if ($health_ok): ?><p class="mua-muted">Kompakt für kleine Modelle: <code><?= htmlspecialchars($endpoint . '/lite') ?></code></p><?php endif; ?></div>
|
||||
|
||||
<div class="mua-section"><h2>HTTPS / TLS</h2><div class="mua-card">
|
||||
<p>Aktiver Transport: <strong><?= $health_ok ? strtoupper($scheme) : 'unbekannt' ?></strong>. TLS schützt denselben MCP-Port inklusive <code>/health</code>; Bearer-Key und Toolfreigaben bleiben unverändert.</p>
|
||||
|
||||
+21
@@ -33,6 +33,8 @@ export interface MUAConfig {
|
||||
enabledTools: string[];
|
||||
allToolsEnabled: boolean;
|
||||
toolboxEnabled: boolean;
|
||||
/** Standardprofil für /mcp ohne Profilangabe. */
|
||||
defaultProfile?: "full" | "lite";
|
||||
/**
|
||||
* Tools, die beim Laden aus Kompatibilitätsgründen automatisch ergänzt
|
||||
* wurden (nicht in der Datei, aber durch eine bereits erteilte, gleich
|
||||
@@ -45,6 +47,7 @@ export interface MUAConfig {
|
||||
// Netzwerkscans und die Root-Shell müssen ausdrücklich in der GUI aktiviert
|
||||
// werden.
|
||||
export const SAFE_DEFAULT_TOOLS = [
|
||||
"unraid_overview",
|
||||
"unraid_docker_list",
|
||||
"unraid_docker_inspect",
|
||||
"unraid_docker_logs",
|
||||
@@ -107,6 +110,8 @@ export function parseConfig(content: string): MUAConfig {
|
||||
.filter((s) => s.length > 0);
|
||||
cfg.allToolsEnabled = false;
|
||||
}
|
||||
} else if (key === "MUA_PROFILE") {
|
||||
cfg.defaultProfile = value.toLowerCase() === "lite" ? "lite" : "full";
|
||||
} else if (key === "MUA_TOOLBOX_ENABLED") {
|
||||
cfg.toolboxEnabled = ["1", "true", "yes", "on"].includes(value.toLowerCase());
|
||||
}
|
||||
@@ -122,6 +127,14 @@ export function parseConfig(content: string): MUAConfig {
|
||||
// less powerful than the already-enabled read-only shell and avoids many
|
||||
// repeated ls/find calls, so existing read-only installations may receive
|
||||
// it without granting a new write capability.
|
||||
// r037: Die Übersicht liest nur Quellen, deren eigenes Tool freigegeben
|
||||
// ist; sie gewährt also nie mehr als bereits erlaubt.
|
||||
if (!cfg.allToolsEnabled && [
|
||||
"unraid_system_health", "unraid_storage_status", "unraid_docker_list",
|
||||
"unraid_docker_update_status", "unraid_notifications_list",
|
||||
].some((t) => cfg.enabledTools.includes(t))) {
|
||||
grant("unraid_overview");
|
||||
}
|
||||
if (!cfg.allToolsEnabled && cfg.enabledTools.includes("unraid_system_shell_readonly")) {
|
||||
grant("unraid_files_inventory");
|
||||
}
|
||||
@@ -214,6 +227,8 @@ function writeConfigFile(cfg: MUAConfig): void {
|
||||
`MUA_ENABLED_TOOLS=${toolsValue}`,
|
||||
"# Optionalen, per Docker-Label erkannten Werkzeugcontainer bekanntgeben",
|
||||
`MUA_TOOLBOX_ENABLED=${cfg.toolboxEnabled ? "true" : "false"}`,
|
||||
"# Standardprofil für /mcp: full (alle Einzeltools) oder lite (kompakt für kleine Modelle)",
|
||||
`MUA_PROFILE=${cfg.defaultProfile ?? "full"}`,
|
||||
"",
|
||||
].join("\n");
|
||||
writeFileSync(CONFIG_FILE, content, { mode: 0o600 });
|
||||
@@ -275,6 +290,12 @@ export function setEnabledTools(names: string[], allToolsEnabled = false): void
|
||||
saveConfig(cfg);
|
||||
}
|
||||
|
||||
export function getDefaultProfile(): "full" | "lite" {
|
||||
const env = process.env["MUA_PROFILE"]?.toLowerCase();
|
||||
if (env === "lite" || env === "full") return env;
|
||||
return loadConfig().defaultProfile ?? "full";
|
||||
}
|
||||
|
||||
export function getToolboxEnabled(): boolean {
|
||||
return loadConfig().toolboxEnabled;
|
||||
}
|
||||
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* MUA — Mikes Unraid Agent
|
||||
* dispatch.ts — Gemeinsame Tool-Auswahl für beide Profile.
|
||||
*
|
||||
* - tools/list: volles Profil oder Lite-Profil (nur Freigegebenes).
|
||||
* - tools/call: Lite-Namen → Ziel-Tool; Berechtigungsprüfung immer gegen
|
||||
* das Ziel-Tool des vollen Profils.
|
||||
* - Fehlertolerante Container-Namen: Lesende Aktionen lösen eindeutige
|
||||
* Teilnamen auf ("plex" → "binhex-plex"). Schreibende Aktionen
|
||||
* akzeptieren nur exakte Namen bzw. abweichende Groß-/Kleinschreibung und
|
||||
* liefern sonst "Meintest du …?" — niemals eine Aktion auf Verdacht.
|
||||
*/
|
||||
|
||||
import { TOOLS, getToolRisk, type ToolDef } from "./tools";
|
||||
import { buildLiteTools, isLiteTool, LiteCallError, resolveLiteCall, type Profile } from "./profiles";
|
||||
|
||||
export class DispatchError extends Error {}
|
||||
|
||||
export interface DispatchContext {
|
||||
profile: Profile;
|
||||
isAvailable: (tool: string) => boolean;
|
||||
/** Liefert alle Containernamen (nur bei Bedarf aufgerufen). */
|
||||
listContainers: () => Promise<string[]>;
|
||||
}
|
||||
|
||||
export function listTools(ctx: Pick<DispatchContext, "profile" | "isAvailable">): ToolDef[] {
|
||||
if (ctx.profile === "lite") return buildLiteTools(TOOLS, ctx.isAvailable, getToolRisk);
|
||||
return TOOLS.filter((t) => ctx.isAvailable(t.name));
|
||||
}
|
||||
|
||||
// ── Container-Namen ──────────────────────────────────────────────────────
|
||||
|
||||
type Mode = "read" | "write";
|
||||
const CONTAINER_PARAMS: Record<string, { param: string; mode: Mode; list?: boolean }> = {
|
||||
unraid_docker_inspect: { param: "container", mode: "read" },
|
||||
unraid_docker_logs: { param: "container", mode: "read" },
|
||||
unraid_docker_analyze_logs: { param: "container", mode: "read" },
|
||||
unraid_docker_processes: { param: "container", mode: "read" },
|
||||
unraid_docker_start: { param: "container", mode: "write" },
|
||||
unraid_docker_stop: { param: "container", mode: "write" },
|
||||
unraid_docker_restart: { param: "container", mode: "write" },
|
||||
unraid_docker_modify: { param: "container", mode: "write" },
|
||||
unraid_docker_update: { param: "container", mode: "write" },
|
||||
unraid_docker_rebuild: { param: "container", mode: "write" },
|
||||
unraid_docker_update_verified_batch: { param: "containers", mode: "write", list: true },
|
||||
};
|
||||
|
||||
const squash = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
|
||||
|
||||
function editDistance(a: string, b: string): number {
|
||||
const dp = Array.from({ length: b.length + 1 }, (_, i) => i);
|
||||
for (let i = 1; i <= a.length; i++) {
|
||||
let prev = dp[0];
|
||||
dp[0] = i;
|
||||
for (let j = 1; j <= b.length; j++) {
|
||||
const tmp = dp[j];
|
||||
dp[j] = Math.min(dp[j] + 1, dp[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
||||
prev = tmp;
|
||||
}
|
||||
}
|
||||
return dp[b.length];
|
||||
}
|
||||
|
||||
export interface NameResolution { name: string; note?: string }
|
||||
|
||||
/** Löst einen (ungenauen) Containernamen auf oder wirft mit Vorschlägen. */
|
||||
export function resolveContainerName(raw: string, names: string[], mode: Mode): NameResolution {
|
||||
const wanted = raw.trim().replace(/^\//, "");
|
||||
if (names.includes(wanted)) return { name: wanted };
|
||||
const ci = names.filter((n) => n.toLowerCase() === wanted.toLowerCase());
|
||||
if (ci.length === 1) return { name: ci[0], note: `container '${raw}' → '${ci[0]}'` };
|
||||
|
||||
const key = squash(wanted);
|
||||
const partial = key ? names.filter((n) => squash(n).includes(key)) : [];
|
||||
const suggestions = partial.length > 0
|
||||
? partial.slice(0, 5)
|
||||
: [...names].sort((a, b) => editDistance(squash(a), key) - editDistance(squash(b), key)).slice(0, 3);
|
||||
|
||||
if (mode === "read" && partial.length === 1) {
|
||||
return { name: partial[0], note: `container '${raw}' → '${partial[0]}'` };
|
||||
}
|
||||
if (partial.length > 1) {
|
||||
throw new DispatchError(`Container '${raw}' is ambiguous. Did you mean: ${suggestions.join(", ")}?`);
|
||||
}
|
||||
if (mode === "write" && partial.length === 1) {
|
||||
throw new DispatchError(`No container named exactly '${raw}'. Did you mean '${partial[0]}'? Repeat the call with that exact name.`);
|
||||
}
|
||||
throw new DispatchError(`No container named '${raw}'.${suggestions.length ? ` Closest: ${suggestions.join(", ")}.` : ""} Use list to see all containers.`);
|
||||
}
|
||||
|
||||
async function resolveContainers(
|
||||
tool: string,
|
||||
args: Record<string, unknown>,
|
||||
listContainers: () => Promise<string[]>,
|
||||
): Promise<string[]> {
|
||||
const spec = CONTAINER_PARAMS[tool];
|
||||
const value = spec ? args[spec.param] : undefined;
|
||||
if (!spec || typeof value !== "string" || value.trim() === "") return [];
|
||||
let names: string[];
|
||||
try {
|
||||
names = await listContainers();
|
||||
} catch {
|
||||
return []; // Docker nicht erreichbar: Original-Tool meldet den Fehler selbst.
|
||||
}
|
||||
const notes: string[] = [];
|
||||
if (spec.list) {
|
||||
const parts = value.split(/[|,]/).map((p) => p.trim()).filter(Boolean);
|
||||
args[spec.param] = parts.map((p) => {
|
||||
const r = resolveContainerName(p, names, spec.mode);
|
||||
if (r.note) notes.push(r.note);
|
||||
return r.name;
|
||||
}).join("|");
|
||||
} else {
|
||||
const r = resolveContainerName(value, names, spec.mode);
|
||||
if (r.note) notes.push(r.note);
|
||||
args[spec.param] = r.name;
|
||||
}
|
||||
return notes;
|
||||
}
|
||||
|
||||
// ── Aufruf vorbereiten ───────────────────────────────────────────────────
|
||||
|
||||
export interface PreparedCall {
|
||||
tool: ToolDef;
|
||||
args: Record<string, unknown>;
|
||||
/** Hinweise für das Modell (aufgelöste Namen, ignorierte Parameter). */
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
export async function prepareCall(
|
||||
name: string,
|
||||
rawArgs: Record<string, unknown>,
|
||||
ctx: DispatchContext,
|
||||
): Promise<PreparedCall> {
|
||||
let toolName = name;
|
||||
let args: Record<string, unknown> = { ...rawArgs };
|
||||
const notes: string[] = [];
|
||||
|
||||
// Lite-Namen funktionieren in beiden Profilen (und umgekehrt), damit ein
|
||||
// Profilwechsel bestehende Clients nicht bricht.
|
||||
if (isLiteTool(name)) {
|
||||
try {
|
||||
const resolved = resolveLiteCall(name, rawArgs, TOOLS, ctx.isAvailable);
|
||||
toolName = resolved.tool;
|
||||
args = resolved.args;
|
||||
if (resolved.ignored.length) notes.push(`ignored unknown parameter(s): ${resolved.ignored.join(", ")}`);
|
||||
} catch (error) {
|
||||
if (error instanceof LiteCallError) throw new DispatchError(error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const tool = TOOLS.find((t) => t.name === toolName);
|
||||
if (!tool) throw new DispatchError(`Unknown tool: ${name}. Call tools/list to see available tools.`);
|
||||
if (!ctx.isAvailable(toolName)) throw new DispatchError(`Tool disabled: ${toolName}. It can be enabled in the MUA settings.`);
|
||||
|
||||
notes.push(...await resolveContainers(toolName, args, ctx.listContainers));
|
||||
if (toolName === "unraid_overview") args["__profile"] = ctx.profile;
|
||||
return { tool, args, notes };
|
||||
}
|
||||
+1
-1
@@ -19,7 +19,7 @@ import { redactKnownSecrets } from "./redact";
|
||||
|
||||
// ── Konstanten ──────────────────────────────────────────────────────────
|
||||
export const MUA_SERVER_NAME = "mua";
|
||||
export const MUA_VERSION = "2026.11.20.r036";
|
||||
export const MUA_VERSION = "2026.11.21.r037";
|
||||
export const MUA_PROTOCOL_VERSION = "2025-03-26";
|
||||
export const PHP_HELPER = "/usr/local/bin/unraid-docker-mcp-helper.php";
|
||||
export const STATUS_HELPER = "/usr/local/bin/unraid-mcp-status-helper.php";
|
||||
|
||||
+39
-23
@@ -19,11 +19,14 @@ import {
|
||||
MUA_PROTOCOL_VERSION,
|
||||
discoverToolboxContainers,
|
||||
invalidateToolboxCache,
|
||||
dockerExec,
|
||||
pruneFinishedJobs,
|
||||
} from "./helpers";
|
||||
import { killForegroundGroups, runInProcessScope } from "./process-group";
|
||||
import { listTools, prepareCall, type PreparedCall } from "./dispatch";
|
||||
import { profileFromUrl, type Profile } from "./profiles";
|
||||
import { registerSecret } from "./redact";
|
||||
import { TOOLS, toolByName, getToolRisk } from "./tools";
|
||||
import { TOOLS, getToolRisk } from "./tools";
|
||||
import {
|
||||
checkAuth,
|
||||
isToolEnabled,
|
||||
@@ -35,6 +38,7 @@ import {
|
||||
getToolboxEnabled,
|
||||
setToolboxEnabled,
|
||||
getAutoGrantedTools,
|
||||
getDefaultProfile,
|
||||
safeEqual,
|
||||
} from "./auth";
|
||||
import { randomBytes } from "node:crypto";
|
||||
@@ -107,6 +111,16 @@ function isToolAvailable(name: string, toolboxEnabled: boolean): boolean {
|
||||
return TOOLBOX_TOOL_NAMES.has(name) ? toolboxEnabled : isToolEnabled(name);
|
||||
}
|
||||
|
||||
/** /mcp (Standardprofil), /mcp/lite, /mcp/full und / (Altlast). */
|
||||
function isMcpPath(path: string): boolean {
|
||||
return path === "/" || /^\/mcp(\/(lite|full))?\/?$/.test(path);
|
||||
}
|
||||
|
||||
async function listContainerNames(): Promise<string[]> {
|
||||
const raw = await dockerExec("ps -a --format '{{.Names}}'", 15);
|
||||
return raw.split("\n").map((n) => n.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
// ── JSON-RPC Helpers ────────────────────────────────────────────────────
|
||||
function rpcResult(id: number | string | null, result: unknown) {
|
||||
return { jsonrpc: "2.0", id, result };
|
||||
@@ -187,6 +201,7 @@ function deleteSession(id: string | null) {
|
||||
async function handleMcpRequest(
|
||||
message: Record<string, unknown>,
|
||||
sessionId: string | null,
|
||||
profile: Profile = "full",
|
||||
): Promise<{ response: unknown; sessionId: string } | null> {
|
||||
const method = (message["method"] as string) ?? "";
|
||||
const id = message["id"] as number | string | null;
|
||||
@@ -218,8 +233,8 @@ async function handleMcpRequest(
|
||||
if (method === "tools/list") {
|
||||
if (sessionId) touchSession(sessionId);
|
||||
const toolbox = await toolboxGuidance();
|
||||
// Tool-Filter: nur aktive Tools anzeigen
|
||||
const activeTools = TOOLS.filter((t) => isToolAvailable(t.name, toolbox.enabled));
|
||||
// Nur freigegebene Tools; im Lite-Profil gebündelt und dynamisch gefiltert.
|
||||
const activeTools = listTools({ profile, isAvailable: (name) => isToolAvailable(name, toolbox.enabled) });
|
||||
return {
|
||||
response: rpcResult(id, {
|
||||
tools: activeTools.map((t) => ({
|
||||
@@ -235,29 +250,27 @@ async function handleMcpRequest(
|
||||
// ── tools/call ────────────────────────────────────────────────────────
|
||||
if (method === "tools/call") {
|
||||
if (sessionId) touchSession(sessionId);
|
||||
const toolName = (params["name"] as string) ?? "";
|
||||
const args = (params["arguments"] as Record<string, unknown>) ?? {};
|
||||
const tool = toolByName(toolName);
|
||||
if (!tool) {
|
||||
return {
|
||||
response: rpcResult(id, {
|
||||
content: [{ type: "text", text: `ERROR: Unknown tool: ${toolName}` }],
|
||||
isError: true,
|
||||
}),
|
||||
sessionId: sessionId ?? "",
|
||||
};
|
||||
}
|
||||
// Tool-Filter: deaktivierte Tools ablehnen
|
||||
const requestedName = (params["name"] as string) ?? "";
|
||||
const rawArgs = (params["arguments"] as Record<string, unknown>) ?? {};
|
||||
const toolbox = await toolboxGuidance();
|
||||
if (!isToolAvailable(toolName, toolbox.enabled)) {
|
||||
let prepared: PreparedCall;
|
||||
try {
|
||||
prepared = await prepareCall(requestedName, rawArgs, {
|
||||
profile,
|
||||
isAvailable: (name) => isToolAvailable(name, toolbox.enabled),
|
||||
listContainers: listContainerNames,
|
||||
});
|
||||
} catch (e) {
|
||||
return {
|
||||
response: rpcResult(id, {
|
||||
content: [{ type: "text", text: `ERROR: Tool disabled: ${toolName}` }],
|
||||
content: [{ type: "text", text: `ERROR: ${e instanceof Error ? e.message : String(e)}` }],
|
||||
isError: true,
|
||||
}),
|
||||
sessionId: sessionId ?? "",
|
||||
};
|
||||
}
|
||||
const { tool, args, notes } = prepared;
|
||||
const toolName = tool.name;
|
||||
const timeoutMs = hardTimeoutMs(args);
|
||||
const lease = toolCallGate.acquire(toolName, timeoutMs + 5000);
|
||||
if (!lease) {
|
||||
@@ -285,7 +298,10 @@ async function handleMcpRequest(
|
||||
} catch { /* textual success */ }
|
||||
auditTool(toolName, !failed, Date.now() - startedAt);
|
||||
const result: Record<string, unknown> = {
|
||||
content: [{ type: "text", text }],
|
||||
content: [
|
||||
{ type: "text", text },
|
||||
...(notes.length ? [{ type: "text", text: `Note: ${notes.join("; ")}` }] : []),
|
||||
],
|
||||
...(failed ? { isError: true } : {}),
|
||||
};
|
||||
// JSON-Ausgaben zusätzlich strukturiert bereitstellen. Reiner Text
|
||||
@@ -392,7 +408,7 @@ try {
|
||||
}
|
||||
|
||||
// ── Auth-Check für /mcp (POST + DELETE) — Bearer-Token ─────────────
|
||||
if (path === "/mcp" || path === "/") {
|
||||
if (isMcpPath(path)) {
|
||||
const client = server.requestIP(req)?.address ?? "unknown";
|
||||
if (!allowRequest(client)) {
|
||||
return Response.json(
|
||||
@@ -419,11 +435,11 @@ try {
|
||||
}
|
||||
|
||||
// ── MCP-Endpunkt ────────────────────────────────────────────────────
|
||||
if ((path === "/mcp" || path === "/") && sessionHeader !== null && sessionHeader !== ""
|
||||
if ((isMcpPath(path)) && sessionHeader !== null && sessionHeader !== ""
|
||||
&& !SESSION_ID_PATTERN.test(sessionHeader)) {
|
||||
return Response.json(rpcError(null, -32600, "Invalid Mcp-Session-Id"), { status: 400, headers: corsHeaders });
|
||||
}
|
||||
if (path === "/mcp" || path === "/") {
|
||||
if (isMcpPath(path)) {
|
||||
// POST: JSON-RPC Request
|
||||
if (method === "POST") {
|
||||
const contentLength = Number(req.headers.get("content-length") ?? 0);
|
||||
@@ -459,7 +475,7 @@ try {
|
||||
);
|
||||
}
|
||||
|
||||
const result = await handleMcpRequest(message, sessionHeader);
|
||||
const result = await handleMcpRequest(message, sessionHeader, profileFromUrl(url, getDefaultProfile()));
|
||||
|
||||
// Notification (kein Response nötig)
|
||||
if (result === null) {
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { DispatchError, listTools, prepareCall, resolveContainerName } from "./dispatch";
|
||||
import { callHint, joinContainers, profileFromUrl } from "./profiles";
|
||||
import { buildOverview } from "./overview";
|
||||
import { parseConfig, SAFE_DEFAULT_TOOLS } from "./auth";
|
||||
import { TOOLS } from "./tools";
|
||||
|
||||
const ALL = () => true;
|
||||
const only = (...names: string[]) => (n: string) => names.includes(n);
|
||||
const NAMES = ["binhex-plex", "Sonarr", "radarr", "radarr-4k", "nginx-proxy-manager"];
|
||||
const ctx = (isAvailable: (n: string) => boolean, profile: "full" | "lite" = "lite") =>
|
||||
({ profile, isAvailable, listContainers: async () => NAMES });
|
||||
const schemaSize = (tools: any[]) =>
|
||||
JSON.stringify(tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema }))).length;
|
||||
|
||||
describe("lite profile: tools/list", () => {
|
||||
test("bundles all functions into few tools and is much smaller", () => {
|
||||
const full = listTools({ profile: "full", isAvailable: ALL });
|
||||
const lite = listTools({ profile: "lite", isAvailable: ALL });
|
||||
expect(lite.map((t) => t.name)).toEqual([
|
||||
"unraid_overview", "unraid_shell_readonly", "unraid_docker", "unraid_storage",
|
||||
"unraid_network", "unraid_system", "unraid_apps", "unraid_shell", "unraid_toolbox",
|
||||
]);
|
||||
expect(schemaSize(lite)).toBeLessThan(schemaSize(full) * 0.55);
|
||||
});
|
||||
|
||||
test("every full-profile tool is reachable through a listed lite tool/action", async () => {
|
||||
const lite = listTools({ profile: "lite", isAvailable: ALL });
|
||||
for (const t of TOOLS) {
|
||||
const hint = callHint(t.name, {}, "lite");
|
||||
const liteTool = lite.find((l) => l.name === hint.tool);
|
||||
expect(liteTool).toBeDefined();
|
||||
const actions: string[] | undefined = (liteTool!.inputSchema as any).properties?.action?.enum;
|
||||
if (actions) {
|
||||
expect(actions).toContain(hint.arguments["action"] as string);
|
||||
// Rückweg: die Aktion landet wieder beim selben Tool (Batch-Update ausgenommen: Fallback).
|
||||
if (t.name !== "unraid_docker_update") {
|
||||
const required = Object.fromEntries(((t.inputSchema as any).required ?? []).map((r: string) => [r, r === "containers" ? "Sonarr" : r === "container" ? "Sonarr" : "x"]));
|
||||
const back = await prepareCall(hint.tool, { ...callHint(t.name, required, "lite").arguments }, ctx(ALL));
|
||||
expect(back.tool.name).toBe(t.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("only enabled actions are listed; groups without any are hidden", () => {
|
||||
const lite = listTools({ profile: "lite", isAvailable: only("unraid_docker_list", "unraid_docker_logs", "unraid_overview") });
|
||||
expect(lite.map((t) => t.name)).toEqual(["unraid_overview", "unraid_docker"]);
|
||||
const docker = lite.find((t) => t.name === "unraid_docker")!;
|
||||
expect((docker.inputSchema as any).properties.action.enum).toEqual(["list", "logs"]);
|
||||
expect(docker.description).toContain("logs(container*, tail)");
|
||||
expect(docker.description).not.toContain("stop");
|
||||
expect(Object.keys((docker.inputSchema as any).properties)).not.toContain("approval_ticket");
|
||||
});
|
||||
|
||||
test("risk is marked in the action list", () => {
|
||||
const docker = listTools({ profile: "lite", isAvailable: ALL }).find((t) => t.name === "unraid_docker")!;
|
||||
expect(docker.description).toMatch(/restart\(container\*\): restart \[changes state\]/);
|
||||
expect(docker.description).toMatch(/rebuild\(container\*\): .*\[critical\]/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("lite profile: tools/call", () => {
|
||||
test("maps action and tolerates common parameter mix-ups", async () => {
|
||||
const logs = await prepareCall("unraid_docker", { action: "logs", name: "plex", lines: 50 }, ctx(ALL));
|
||||
expect(logs.tool.name).toBe("unraid_docker_logs");
|
||||
expect(logs.args).toEqual({ container: "binhex-plex", tail: 50 });
|
||||
expect(logs.notes[0]).toContain("'plex' → 'binhex-plex'");
|
||||
|
||||
const diag = await prepareCall("unraid_storage", { action: "diagnose", operation: "smart", target: "disk1" }, ctx(ALL));
|
||||
expect(diag.tool.name).toBe("unraid_storage_diagnostics");
|
||||
expect(diag.args).toEqual({ action: "smart", target: "disk1" });
|
||||
|
||||
const perms = await prepareCall("unraid_storage", { action: "share_permissions", share: "media" }, ctx(ALL));
|
||||
expect(perms.args).toEqual({ name: "media" });
|
||||
const inspect = await prepareCall("unraid_storage", { action: "share", name: "media" }, ctx(ALL));
|
||||
expect(inspect.args).toEqual({ share: "media" });
|
||||
|
||||
const shell = await prepareCall("unraid_shell", { action: "run", cmd: "uptime" }, ctx(ALL));
|
||||
expect(shell.tool.name).toBe("unraid_system_shell");
|
||||
expect(shell.args).toEqual({ command: "uptime" });
|
||||
});
|
||||
|
||||
test("action names are normalised (case, spaces, dashes)", async () => {
|
||||
const r = await prepareCall("unraid_docker", { action: "Update-Status" }, ctx(ALL));
|
||||
expect(r.tool.name).toBe("unraid_docker_update_status");
|
||||
});
|
||||
|
||||
test("unknown parameters are dropped and reported", async () => {
|
||||
const r = await prepareCall("unraid_docker", { action: "list", container: "x", state: "running" }, ctx(ALL));
|
||||
expect(r.args).toEqual({ state: "running" });
|
||||
expect(r.notes.join()).toContain("ignored unknown parameter(s): container");
|
||||
});
|
||||
|
||||
test("helpful errors: missing action, unknown action, disabled action, missing parameter", async () => {
|
||||
const c = ctx(only("unraid_docker_list", "unraid_docker_logs"));
|
||||
await expect(prepareCall("unraid_docker", {}, c)).rejects.toThrow(/Missing 'action'.*list, logs/);
|
||||
await expect(prepareCall("unraid_docker", { action: "explode" }, c)).rejects.toThrow(/Unknown action 'explode'.*list, logs/);
|
||||
await expect(prepareCall("unraid_docker", { action: "stop", container: "Sonarr" }, c)).rejects.toThrow(/disabled.*list, logs/);
|
||||
await expect(prepareCall("unraid_docker", { action: "logs" }, c)).rejects.toThrow(/needs: container\. Parameters: container\*, tail/);
|
||||
});
|
||||
|
||||
test("update accepts one name, a list or an array and uses | for the batch tool", async () => {
|
||||
expect(joinContainers({ containers: ["a", "b"] })).toEqual({ containers: "a|b" });
|
||||
expect(joinContainers({ container: "a, b" })).toEqual({ containers: "a|b" });
|
||||
const r = await prepareCall("unraid_docker", { action: "update", containers: "Sonarr, radarr" }, ctx(ALL));
|
||||
expect(r.tool.name).toBe("unraid_docker_update_verified_batch");
|
||||
expect(r.args).toEqual({ containers: "Sonarr|radarr" });
|
||||
});
|
||||
|
||||
test("update falls back to the single-container tool when only that is enabled", async () => {
|
||||
const c = ctx(only("unraid_docker_update"));
|
||||
const r = await prepareCall("unraid_docker", { action: "update", containers: "Sonarr" }, c);
|
||||
expect(r.tool.name).toBe("unraid_docker_update");
|
||||
expect(r.args).toEqual({ container: "Sonarr" });
|
||||
await expect(prepareCall("unraid_docker", { action: "update", containers: "Sonarr|radarr" }, c)).rejects.toThrow(/once per container/);
|
||||
});
|
||||
|
||||
test("permissions are always checked against the underlying tool", async () => {
|
||||
await expect(prepareCall("unraid_shell", { action: "run", command: "id" }, ctx(only("unraid_system_job_status"))))
|
||||
.rejects.toThrow(/disabled/);
|
||||
await expect(prepareCall("unraid_system_shell", { command: "id" }, ctx(only("unraid_docker_list"))))
|
||||
.rejects.toThrow(/Tool disabled/);
|
||||
});
|
||||
|
||||
test("lite and full names work in both profiles", async () => {
|
||||
expect((await prepareCall("unraid_docker_list", {}, ctx(ALL, "lite"))).tool.name).toBe("unraid_docker_list");
|
||||
expect((await prepareCall("unraid_docker", { action: "list" }, ctx(ALL, "full"))).tool.name).toBe("unraid_docker_list");
|
||||
expect((await prepareCall("unraid_shell_readonly", { command: "df -h" }, ctx(ALL))).tool.name).toBe("unraid_system_shell_readonly");
|
||||
});
|
||||
|
||||
test("the overview learns the client's profile for its hints", async () => {
|
||||
const r = await prepareCall("unraid_overview", {}, ctx(ALL, "lite"));
|
||||
expect(r.args["__profile"]).toBe("lite");
|
||||
});
|
||||
});
|
||||
|
||||
describe("container name resolution", () => {
|
||||
test("read actions resolve unique fuzzy names", () => {
|
||||
expect(resolveContainerName("binhex-plex", NAMES, "read")).toEqual({ name: "binhex-plex" });
|
||||
expect(resolveContainerName("sonarr", NAMES, "read").name).toBe("Sonarr");
|
||||
expect(resolveContainerName("plex", NAMES, "read").name).toBe("binhex-plex");
|
||||
expect(resolveContainerName("nginx proxy", NAMES, "read").name).toBe("nginx-proxy-manager");
|
||||
});
|
||||
|
||||
test("write actions never act on a guessed container", () => {
|
||||
expect(resolveContainerName("sonarr", NAMES, "write").name).toBe("Sonarr"); // nur Groß/klein
|
||||
expect(() => resolveContainerName("plex", NAMES, "write")).toThrow(/Did you mean 'binhex-plex'\?/);
|
||||
});
|
||||
|
||||
test("ambiguous and unknown names give suggestions", () => {
|
||||
expect(() => resolveContainerName("radarr", ["radarr-a", "radarr-b"], "read")).toThrow(/ambiguous.*radarr-a, radarr-b/);
|
||||
expect(() => resolveContainerName("sonar", ["radarr", "Sonarr"], "read")).not.toThrow();
|
||||
expect(() => resolveContainerName("jellyfn", ["jellyfin", "radarr"], "read")).toThrow(/Closest: jellyfin/);
|
||||
});
|
||||
|
||||
test("exact names win over partial matches (radarr vs radarr-4k)", async () => {
|
||||
const r = await prepareCall("unraid_docker", { action: "restart", container: "radarr" }, ctx(ALL));
|
||||
expect(r.args).toEqual({ container: "radarr" });
|
||||
expect(r.notes).toEqual([]);
|
||||
});
|
||||
|
||||
test("full profile write tools reject guesses too", async () => {
|
||||
await expect(prepareCall("unraid_docker_stop", { container: "plex" }, ctx(ALL, "full"))).rejects.toThrow(DispatchError);
|
||||
});
|
||||
|
||||
test("Docker being unavailable does not block the call", async () => {
|
||||
const r = await prepareCall("unraid_docker_logs", { container: "x" }, {
|
||||
profile: "full", isAvailable: ALL, listContainers: async () => { throw new Error("docker down"); },
|
||||
});
|
||||
expect(r.args).toEqual({ container: "x" });
|
||||
});
|
||||
});
|
||||
|
||||
test("profile selection from URL", () => {
|
||||
const u = (s: string) => new URL(`http://h${s}`);
|
||||
expect(profileFromUrl(u("/mcp"), "full")).toBe("full");
|
||||
expect(profileFromUrl(u("/mcp"), "lite")).toBe("lite");
|
||||
expect(profileFromUrl(u("/mcp/lite"), "full")).toBe("lite");
|
||||
expect(profileFromUrl(u("/mcp?profile=lite"), "full")).toBe("lite");
|
||||
expect(profileFromUrl(u("/mcp/lite?profile=full"), "lite")).toBe("full");
|
||||
});
|
||||
|
||||
describe("config", () => {
|
||||
test("overview is in the safe default and follows any enabled status source", () => {
|
||||
expect(SAFE_DEFAULT_TOOLS).toContain("unraid_overview");
|
||||
const cfg = parseConfig("MUA_API_KEY=x\nMUA_ENABLED_TOOLS=unraid_docker_list\n");
|
||||
expect(cfg.enabledTools).toContain("unraid_overview");
|
||||
expect(cfg.autoGranted).toContain("unraid_overview");
|
||||
expect(parseConfig("MUA_API_KEY=x\nMUA_ENABLED_TOOLS=unraid_network_list\n").enabledTools).not.toContain("unraid_overview");
|
||||
});
|
||||
|
||||
test("MUA_PROFILE is parsed", () => {
|
||||
expect(parseConfig("MUA_PROFILE=lite\n").defaultProfile).toBe("lite");
|
||||
expect(parseConfig("MUA_PROFILE=bogus\n").defaultProfile).toBe("full");
|
||||
expect(parseConfig("").defaultProfile).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Overview ──────────────────────────────────────────────────────────────
|
||||
|
||||
const healthy = {
|
||||
unraid_system_health: { hostname: "tower", uptime_seconds: 90061, cpu_logical: 8, load_average: { fifteen: 1.2 },
|
||||
memory: { used_percent: 41 }, temperatures: [{ sensor: "coretemp:Package id 0", celsius: 48 }] },
|
||||
unraid_storage_status: { array_state: "STARTED", alerts: [], parity: { running: false },
|
||||
disks: [
|
||||
{ name: "parity", device: "sdb", status: "DISK_OK", temperature_c: 34, errors: 0, size_bytes: 0 },
|
||||
{ name: "disk1", device: "sdc", status: "DISK_OK", temperature_c: 36, errors: 0, size_bytes: 8e12, free_bytes: 3e12, used_percent: 62.5 },
|
||||
{ name: "disk2", device: "", status: "DISK_NP", temperature_c: 0, errors: 0, size_bytes: 0 },
|
||||
] },
|
||||
unraid_docker_list: { running_count: 2, stopped_count: 1, containers: [
|
||||
{ name: "plex", state: "running", status: "Up 3 days (healthy)" },
|
||||
{ name: "Sonarr", state: "running", status: "Up 3 days" },
|
||||
{ name: "old", state: "exited", status: "Exited (137) 2 weeks ago" },
|
||||
] },
|
||||
unraid_docker_update_status: { containers: [{ container: "plex", status: "up-to-date" }] },
|
||||
unraid_notifications_list: { notifications: [{ importance: "alert", subject: "old, archived", archived: true }] },
|
||||
};
|
||||
|
||||
function deps(data: Record<string, unknown>, profile: "full" | "lite" = "full", enabled: (n: string) => boolean = ALL) {
|
||||
return {
|
||||
profile, isEnabled: enabled, timeoutMs: 200,
|
||||
run: async (tool: string) => {
|
||||
const v = data[tool];
|
||||
if (v === "hang") return new Promise<string>(() => {});
|
||||
if (v instanceof Error) throw v;
|
||||
return JSON.stringify(v ?? {});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("unraid_overview", () => {
|
||||
test("a healthy server reports ok with a compact summary", async () => {
|
||||
const o = JSON.parse(await buildOverview(deps(healthy)));
|
||||
expect(o.status).toBe("ok");
|
||||
expect(o.attention).toEqual([]);
|
||||
expect(o.summary.system.uptime).toBe("1d 1h");
|
||||
expect(o.summary.docker).toEqual({ running: 2, stopped: 1, unhealthy: 0, updates_available: 0 });
|
||||
expect(o.summary.storage.parity).toBe("idle");
|
||||
});
|
||||
|
||||
test("problems are found, sorted by severity and carry ready-made next calls", async () => {
|
||||
const data = structuredClone(healthy) as any;
|
||||
data.unraid_storage_status.disks.push(
|
||||
{ name: "disk3", device: "sdd", status: "DISK_DSBL", temperature_c: 0, errors: 12, size_bytes: 0 },
|
||||
{ name: "cache", device: "nvme0n1", status: "DISK_OK", temperature_c: 72, errors: 0, size_bytes: 1e12, free_bytes: 2e10, used_percent: 98 },
|
||||
);
|
||||
data.unraid_docker_list.containers.push(
|
||||
{ name: "binhex-plex", state: "running", status: "Up 1 hour (unhealthy)" },
|
||||
{ name: "loop", state: "restarting", status: "Restarting (1) 5 seconds ago" },
|
||||
{ name: "crashy", state: "exited", status: "Exited (1) 3 hours ago" },
|
||||
);
|
||||
data.unraid_docker_update_status.containers.push({ container: "Sonarr", status: "update-available" });
|
||||
data.unraid_notifications_list.notifications.push({ importance: "warning", subject: "Parity check finished with 3 errors", archived: false, timestamp: 1763600000 });
|
||||
data.unraid_system_health.memory.used_percent = 93;
|
||||
|
||||
const o = JSON.parse(await buildOverview(deps(data, "lite")));
|
||||
expect(o.status).toBe("critical");
|
||||
const messages = o.attention.map((a: any) => a.message);
|
||||
expect(messages).toContain("Disk disk3: DISK_DSBL");
|
||||
expect(messages).toContain("loop is restarting in a loop");
|
||||
expect(messages.some((m: string) => m.startsWith("cache 98% full"))).toBe(true);
|
||||
expect(messages).toContain("Disk cache: 72°C"); // NVMe: Warnung ab 70
|
||||
expect(messages).toContain("crashy stopped with an error: Exited (1) 3 hours ago");
|
||||
expect(messages.join()).not.toContain("old"); // Exit 137 = normal gestoppt
|
||||
expect(messages.join()).not.toContain("disk2"); // leerer Slot
|
||||
expect(messages.join()).toContain("Parity check finished with 3 errors");
|
||||
expect(messages.join()).not.toContain("archived");
|
||||
expect(messages).toContain("RAM 93% used");
|
||||
|
||||
const ranks = o.attention.map((a: any) => ({ critical: 0, warning: 1, info: 2 } as any)[a.severity]);
|
||||
expect([...ranks].sort()).toEqual(ranks);
|
||||
|
||||
const unhealthy = o.attention.find((a: any) => a.message.startsWith("binhex-plex"));
|
||||
expect(unhealthy.next).toEqual({ tool: "unraid_docker", arguments: { action: "logs", container: "binhex-plex", tail: 100 } });
|
||||
const disk = o.attention.find((a: any) => a.message === "Disk disk3: DISK_DSBL");
|
||||
expect(disk.next).toEqual({ tool: "unraid_storage", arguments: { action: "disks", disk: "disk3" } });
|
||||
});
|
||||
|
||||
test("full profile hints use the full tool names", async () => {
|
||||
const data = structuredClone(healthy) as any;
|
||||
data.unraid_docker_list.containers.push({ name: "bad", state: "running", status: "Up (unhealthy)" });
|
||||
const o = JSON.parse(await buildOverview(deps(data, "full")));
|
||||
expect(o.attention[0].next).toEqual({ tool: "unraid_docker_logs", arguments: { container: "bad", tail: 100 } });
|
||||
});
|
||||
|
||||
test("disabled sources are skipped, not read; hints to disabled tools are omitted", async () => {
|
||||
const enabled = only("unraid_docker_list", "unraid_storage_status");
|
||||
const data = structuredClone(healthy) as any;
|
||||
data.unraid_docker_list.containers.push({ name: "bad", state: "running", status: "Up (unhealthy)" });
|
||||
let calls: string[] = [];
|
||||
const d = deps(data, "full", enabled);
|
||||
const run = d.run;
|
||||
d.run = async (tool: string) => { calls.push(tool); return run(tool); };
|
||||
const o = JSON.parse(await buildOverview(d));
|
||||
expect(calls.sort()).toEqual(["unraid_docker_list", "unraid_storage_status"]);
|
||||
expect(o.skipped.join()).toContain("unraid_system_health not enabled");
|
||||
expect(o.attention[0].next).toBeUndefined(); // logs nicht freigegeben
|
||||
});
|
||||
|
||||
test("a failing or hanging source does not break the overview", async () => {
|
||||
const data = { ...healthy, unraid_system_health: new Error("php crashed"), unraid_docker_list: "hang" } as any;
|
||||
const o = JSON.parse(await buildOverview(deps(data)));
|
||||
expect(o.unavailable.system).toContain("php crashed");
|
||||
expect(o.headline).toContain("Could not read: system, docker");
|
||||
expect(o.unavailable.docker).toContain("timed out");
|
||||
expect(o.summary.storage.array).toBe("STARTED");
|
||||
});
|
||||
|
||||
test("nothing readable is 'unknown', never 'ok'", async () => {
|
||||
const data = Object.fromEntries(Object.keys(healthy).map((k) => [k, new Error("down")]));
|
||||
const o = JSON.parse(await buildOverview(deps(data)));
|
||||
expect(o.status).toBe("unknown");
|
||||
expect(o.headline).toContain("No status source could be read");
|
||||
});
|
||||
|
||||
test("stopped array and running parity are reported", async () => {
|
||||
const data = structuredClone(healthy) as any;
|
||||
data.unraid_storage_status.array_state = "STOPPED";
|
||||
data.unraid_storage_status.parity = { running: true, action: "check P", position: 250, size: 1000, corrections: 0 };
|
||||
const o = JSON.parse(await buildOverview(deps(data)));
|
||||
expect(o.status).toBe("warning");
|
||||
expect(o.summary.storage.parity).toBe("check P running 25%");
|
||||
});
|
||||
});
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* MUA — Mikes Unraid Agent
|
||||
* overview.ts — unraid_overview: "Wie geht's dem Server?" in einem Aufruf.
|
||||
*
|
||||
* Fasst System, Storage, Container, Updates und Benachrichtigungen zusammen
|
||||
* und liefert eine priorisierte `attention`-Liste. Jeder Eintrag enthält einen
|
||||
* fertigen Folgeaufruf (`next`) im Profil des Clients, sodass auch kleine
|
||||
* Modelle nur noch der Empfehlung folgen müssen.
|
||||
*
|
||||
* Berechtigungen: Es werden nur Quellen gelesen, deren eigenes Tool
|
||||
* freigegeben ist. Fehlt eine Freigabe, steht der Bereich unter `skipped`.
|
||||
*/
|
||||
|
||||
import { callHint, type Profile } from "./profiles";
|
||||
|
||||
export type Severity = "critical" | "warning" | "info";
|
||||
|
||||
export interface AttentionItem {
|
||||
severity: Severity;
|
||||
area: "storage" | "system" | "docker" | "notifications";
|
||||
message: string;
|
||||
next?: { tool: string; arguments: Record<string, unknown> };
|
||||
}
|
||||
|
||||
export interface OverviewDeps {
|
||||
/** Ruft ein Tool des vollen Profils auf und liefert dessen Text. */
|
||||
run: (tool: string, args?: Record<string, unknown>) => Promise<string>;
|
||||
isEnabled: (tool: string) => boolean;
|
||||
profile: Profile;
|
||||
/** Zeitlimit je Quelle in ms. */
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
const SOURCES = {
|
||||
system: "unraid_system_health",
|
||||
storage: "unraid_storage_status",
|
||||
docker: "unraid_docker_list",
|
||||
updates: "unraid_docker_update_status",
|
||||
notifications: "unraid_notifications_list",
|
||||
} as const;
|
||||
|
||||
const RANK: Record<Severity, number> = { critical: 0, warning: 1, info: 2 };
|
||||
const MAX_ITEMS = 15;
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise<never>((_, reject) => setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms)),
|
||||
]);
|
||||
}
|
||||
|
||||
function gib(bytes: number): string {
|
||||
if (!Number.isFinite(bytes) || bytes <= 0) return "0 GB";
|
||||
const tb = bytes / 1e12;
|
||||
return tb >= 1 ? `${tb.toFixed(1)} TB` : `${(bytes / 1e9).toFixed(1)} GB`;
|
||||
}
|
||||
|
||||
function duration(seconds: number): string {
|
||||
const d = Math.floor(seconds / 86400);
|
||||
const h = Math.floor((seconds % 86400) / 3600);
|
||||
return d > 0 ? `${d}d ${h}h` : `${h}h ${Math.floor((seconds % 3600) / 60)}m`;
|
||||
}
|
||||
|
||||
/** Exit-Codes, die beim normalen Stoppen entstehen (SIGKILL/SIGTERM). */
|
||||
const NORMAL_EXIT = new Set([0, 137, 143]);
|
||||
|
||||
export async function buildOverview(deps: OverviewDeps): Promise<string> {
|
||||
const timeoutMs = deps.timeoutMs ?? 20_000;
|
||||
const attention: AttentionItem[] = [];
|
||||
const summary: Record<string, unknown> = {};
|
||||
const skipped: string[] = [];
|
||||
const unavailable: Record<string, string> = {};
|
||||
const hint = (tool: string, args: Record<string, unknown> = {}) =>
|
||||
deps.isEnabled(tool) ? callHint(tool, args, deps.profile) : undefined;
|
||||
const add = (item: AttentionItem) => attention.push(item);
|
||||
|
||||
const load = async (key: keyof typeof SOURCES, args?: Record<string, unknown>): Promise<any | null> => {
|
||||
const tool = SOURCES[key];
|
||||
if (!deps.isEnabled(tool)) { skipped.push(`${key} (${tool} not enabled)`); return null; }
|
||||
try {
|
||||
return JSON.parse(await withTimeout(deps.run(tool, args), timeoutMs));
|
||||
} catch (error) {
|
||||
unavailable[key] = (error instanceof Error ? error.message : String(error)).slice(0, 200);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const [system, storage, docker, updates, notifications] = await Promise.all([
|
||||
load("system"),
|
||||
load("storage"),
|
||||
load("docker", { state: "all" }),
|
||||
load("updates"),
|
||||
load("notifications", { limit: 30, importance: "all" }),
|
||||
]);
|
||||
|
||||
// ── System ────────────────────────────────────────────────────────────
|
||||
if (system) {
|
||||
const mem = system.memory ?? {};
|
||||
const cpus = Number(system.cpu_logical) || 0;
|
||||
const load15 = Number(system.load_average?.fifteen ?? 0);
|
||||
const temps: { sensor: string; celsius: number }[] = Array.isArray(system.temperatures) ? system.temperatures : [];
|
||||
const hottest = temps.reduce<{ sensor: string; celsius: number } | null>((a, t) => (!a || t.celsius > a.celsius ? t : a), null);
|
||||
summary["system"] = {
|
||||
hostname: system.hostname,
|
||||
uptime: duration(Number(system.uptime_seconds) || 0),
|
||||
load_15m: load15,
|
||||
cpus,
|
||||
ram_used_percent: mem.used_percent,
|
||||
hottest_sensor: hottest ? `${hottest.sensor} ${hottest.celsius}°C` : null,
|
||||
};
|
||||
const ramPct = Number(mem.used_percent) || 0;
|
||||
if (ramPct >= 95) add({ severity: "critical", area: "system", message: `RAM ${ramPct}% used`, next: hint("unraid_docker_stats") });
|
||||
else if (ramPct >= 90) add({ severity: "warning", area: "system", message: `RAM ${ramPct}% used`, next: hint("unraid_docker_stats") });
|
||||
if (cpus > 0 && load15 > cpus * 1.5) {
|
||||
add({ severity: "warning", area: "system", message: `High CPU load: ${load15} (15 min) on ${cpus} threads`, next: hint("unraid_docker_stats") });
|
||||
}
|
||||
if (hottest && hottest.celsius >= 90) add({ severity: "critical", area: "system", message: `Temperature ${hottest.sensor} at ${hottest.celsius}°C`, next: hint("unraid_system_health") });
|
||||
else if (hottest && hottest.celsius >= 80) add({ severity: "warning", area: "system", message: `Temperature ${hottest.sensor} at ${hottest.celsius}°C`, next: hint("unraid_system_health") });
|
||||
}
|
||||
|
||||
// ── Storage ───────────────────────────────────────────────────────────
|
||||
if (storage) {
|
||||
const disks: any[] = Array.isArray(storage.disks) ? storage.disks : [];
|
||||
const parity = storage.parity ?? {};
|
||||
const parityPct = parity.running && Number(parity.size) > 0
|
||||
? Math.round((Number(parity.position) / Number(parity.size)) * 1000) / 10 : null;
|
||||
summary["storage"] = {
|
||||
array: storage.array_state,
|
||||
disks: disks.length,
|
||||
parity: parity.running ? `${parity.action || "check"} running ${parityPct ?? "?"}%` : "idle",
|
||||
};
|
||||
for (const alert of Array.isArray(storage.alerts) ? storage.alerts : []) {
|
||||
add({ severity: "critical", area: "storage", message: String(alert), next: hint("unraid_disk_health") });
|
||||
}
|
||||
if (storage.array_state && storage.array_state !== "STARTED") {
|
||||
add({ severity: "warning", area: "storage", message: `Array is ${storage.array_state} (not started); shares and containers on the array are unavailable`, next: hint("unraid_storage_status") });
|
||||
}
|
||||
if (parity.running) {
|
||||
add({ severity: "info", area: "storage", message: `Parity ${parity.action || "operation"} running (${parityPct ?? "?"}%), corrections so far: ${parity.corrections ?? 0}`, next: hint("unraid_storage_status") });
|
||||
}
|
||||
for (const disk of disks) {
|
||||
const name = String(disk.name ?? "?");
|
||||
const diskStatus = String(disk.status ?? "");
|
||||
// DISK_NP = leerer Slot (normal). Nur fehlende/deaktivierte Disks melden.
|
||||
if (diskStatus === "DISK_NP") continue;
|
||||
const errors = Number(disk.errors) || 0;
|
||||
const temp = Number(disk.temperature_c) || 0;
|
||||
const used = Number(disk.used_percent) || 0;
|
||||
const nvme = String(disk.device ?? "").startsWith("nvme");
|
||||
const [warnT, critT] = nvme ? [70, 80] : [55, 60];
|
||||
if (/DSBL|INVALID|WRONG|MISSING/i.test(diskStatus)) {
|
||||
add({ severity: "critical", area: "storage", message: `Disk ${name}: ${diskStatus}`, next: hint("unraid_disk_health", { disk: name }) });
|
||||
}
|
||||
if (errors > 0) add({ severity: "warning", area: "storage", message: `Disk ${name}: ${errors} read/write errors`, next: hint("unraid_disk_health", { disk: name }) });
|
||||
if (temp >= critT) add({ severity: "critical", area: "storage", message: `Disk ${name}: ${temp}°C`, next: hint("unraid_disk_health", { disk: name }) });
|
||||
else if (temp >= warnT) add({ severity: "warning", area: "storage", message: `Disk ${name}: ${temp}°C`, next: hint("unraid_disk_health", { disk: name }) });
|
||||
if (Number(disk.size_bytes) > 0) {
|
||||
const free = gib(Number(disk.free_bytes));
|
||||
if (used >= 97) add({ severity: "critical", area: "storage", message: `${name} ${used}% full (${free} free)`, next: hint("unraid_shares_list") });
|
||||
else if (used >= 90) add({ severity: "warning", area: "storage", message: `${name} ${used}% full (${free} free)`, next: hint("unraid_shares_list") });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Docker ────────────────────────────────────────────────────────────
|
||||
if (docker) {
|
||||
const rows: any[] = Array.isArray(docker.containers) ? docker.containers : [];
|
||||
const unhealthy = rows.filter((c) => /\(unhealthy\)/i.test(String(c.status)));
|
||||
const restarting = rows.filter((c) => String(c.state) === "restarting");
|
||||
const crashed = rows.filter((c) => {
|
||||
const m = /^Exited \((\d+)\)/.exec(String(c.status));
|
||||
return m !== null && !NORMAL_EXIT.has(Number(m[1]));
|
||||
});
|
||||
summary["docker"] = {
|
||||
running: docker.running_count,
|
||||
stopped: docker.stopped_count,
|
||||
unhealthy: unhealthy.length,
|
||||
};
|
||||
for (const c of restarting) add({ severity: "critical", area: "docker", message: `${c.name} is restarting in a loop`, next: hint("unraid_docker_logs", { container: c.name, tail: 100 }) });
|
||||
for (const c of unhealthy) add({ severity: "warning", area: "docker", message: `${c.name} is unhealthy (${c.status})`, next: hint("unraid_docker_logs", { container: c.name, tail: 100 }) });
|
||||
for (const c of crashed) add({ severity: "warning", area: "docker", message: `${c.name} stopped with an error: ${c.status}`, next: hint("unraid_docker_logs", { container: c.name, tail: 100 }) });
|
||||
}
|
||||
if (updates) {
|
||||
const available = (Array.isArray(updates.containers) ? updates.containers : [])
|
||||
.filter((c: any) => c.status === "update-available").map((c: any) => String(c.container));
|
||||
const dockerSummary = (summary["docker"] ??= {}) as Record<string, unknown>;
|
||||
dockerSummary["updates_available"] = available.length;
|
||||
if (available.length > 0) {
|
||||
add({
|
||||
severity: "info", area: "docker",
|
||||
message: `Updates available for ${available.length} container(s): ${available.slice(0, 8).join(", ")}${available.length > 8 ? ", …" : ""}`,
|
||||
next: hint("unraid_docker_update_status"),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── Benachrichtigungen ────────────────────────────────────────────────
|
||||
if (notifications) {
|
||||
const active: any[] = (Array.isArray(notifications.notifications) ? notifications.notifications : [])
|
||||
.filter((n: any) => !n.archived);
|
||||
const important = active.filter((n) => n.importance === "alert" || n.importance === "warning");
|
||||
summary["notifications"] = { active: active.length, alerts: active.filter((n) => n.importance === "alert").length, warnings: active.filter((n) => n.importance === "warning").length };
|
||||
for (const n of important.slice(0, 5)) {
|
||||
const when = Number(n.timestamp) > 0 ? new Date(Number(n.timestamp) * 1000).toISOString().slice(0, 16).replace("T", " ") : "";
|
||||
add({
|
||||
severity: n.importance === "alert" ? "critical" : "warning",
|
||||
area: "notifications",
|
||||
message: `${when ? `[${when}] ` : ""}${String(n.subject || n.event || "notification").slice(0, 140)}`,
|
||||
next: hint("unraid_notifications_list", { importance: n.importance, limit: 10 }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
attention.sort((a, b) => RANK[a.severity] - RANK[b.severity]);
|
||||
const loaded = [system, storage, docker, updates, notifications].filter((x) => x !== null).length;
|
||||
const missing = Object.keys(unavailable);
|
||||
const count = (s: Severity) => attention.filter((a) => a.severity === s).length;
|
||||
// Ohne gelesene Quelle darf niemals "ok" gemeldet werden.
|
||||
const status: Severity | "ok" | "unknown" = loaded === 0
|
||||
? "unknown"
|
||||
: count("critical") > 0 ? "critical" : count("warning") > 0 ? "warning" : "ok";
|
||||
const shown = attention.slice(0, MAX_ITEMS);
|
||||
const partial = missing.length > 0 ? ` Could not read: ${missing.join(", ")} (see unavailable).` : "";
|
||||
|
||||
const result: Record<string, unknown> = {
|
||||
status,
|
||||
headline: status === "unknown"
|
||||
? `No status source could be read.${partial}`
|
||||
: attention.length === 0
|
||||
? `No problems found.${partial}`
|
||||
: `${count("critical")} critical, ${count("warning")} warning(s), ${count("info")} info.${partial}`,
|
||||
attention: shown,
|
||||
summary,
|
||||
};
|
||||
if (attention.length > MAX_ITEMS) result["more"] = attention.length - MAX_ITEMS;
|
||||
if (skipped.length) result["skipped"] = skipped;
|
||||
if (Object.keys(unavailable).length) result["unavailable"] = unavailable;
|
||||
result["how_to_use"] = "Handle attention items top-down. Each `next` is a ready-to-use tool call.";
|
||||
return JSON.stringify(result);
|
||||
}
|
||||
+387
@@ -0,0 +1,387 @@
|
||||
/**
|
||||
* MUA — Mikes Unraid Agent
|
||||
* profiles.ts — Kompaktes "lite"-Profil für kleine Modelle.
|
||||
*
|
||||
* Das volle Profil hat ~48 Einzeltools (≈6–7k Tokens Schema). Kleine Modelle
|
||||
* wählen dabei oft falsche Tools oder erfinden Parameter. Das Lite-Profil
|
||||
* bündelt dieselben Funktionen in wenigen Gruppen-Tools mit `action`-Feld.
|
||||
*
|
||||
* - Keine neue Berechtigung: Jede Aktion ist exakt auf ein bestehendes
|
||||
* Tool abgebildet und nur sichtbar/aufrufbar, wenn dieses freigegeben ist.
|
||||
* - Das Schema wird dynamisch erzeugt: Die `action`-Liste und die Parameter
|
||||
* enthalten nur freigegebene Aktionen.
|
||||
* - Häufige Parameter-Verwechslungen werden toleriert (name ↔ container,
|
||||
* share ↔ name, cmd → command …).
|
||||
*/
|
||||
|
||||
import type { ToolDef } from "./tools";
|
||||
|
||||
export type Profile = "full" | "lite";
|
||||
|
||||
interface LiteAction {
|
||||
/** Ziel-Tool im vollen Profil. */
|
||||
tool: string;
|
||||
/** Ein Satz für die Gruppenbeschreibung. */
|
||||
summary: string;
|
||||
/** Lite-Parametername → Parametername des Ziel-Tools. */
|
||||
rename?: Record<string, string>;
|
||||
/** Ausweich-Ziel, falls `tool` nicht freigegeben ist. */
|
||||
fallback?: string;
|
||||
/** Eingaben vor dem Aufruf anpassen (nach rename). */
|
||||
prepare?: (args: Record<string, unknown>) => Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface LiteGroup {
|
||||
name: string;
|
||||
intro: string;
|
||||
actions: Record<string, LiteAction>;
|
||||
/** Alternative Parameternamen → kanonischer Lite-Name. */
|
||||
aliases?: Record<string, string>;
|
||||
}
|
||||
|
||||
const OPERATION = { operation: "action" };
|
||||
|
||||
/** ["a","b"] / "a, b" / "a|b" / "a" → "a|b", wie unraid_docker_update_verified_batch es erwartet. */
|
||||
export function joinContainers(args: Record<string, unknown>): Record<string, unknown> {
|
||||
const out = { ...args };
|
||||
const list = out["containers"] ?? out["container"];
|
||||
const parts = Array.isArray(list) ? list.map(String) : typeof list === "string" ? list.split(/[|,]/) : [];
|
||||
const names = parts.map((p) => p.trim()).filter(Boolean);
|
||||
if (names.length) out["containers"] = names.join("|");
|
||||
delete out["container"];
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nur Parameter, deren Format nicht selbsterklärend ist, behalten im
|
||||
* Lite-Schema eine (kurze) Beschreibung. Alles andere steht bereits in der
|
||||
* Aktionsliste der Gruppe. Spart gut die Hälfte der Schema-Tokens.
|
||||
*/
|
||||
const LITE_PARAM_HINTS: Record<string, string> = {
|
||||
state: "running | stopped (= not running) | all",
|
||||
detail: "more fields; default compact/summary",
|
||||
tail: "lines, default 200",
|
||||
since: "e.g. 2h, 24h (default 24h)",
|
||||
focus_terms: "words a line must contain (any)",
|
||||
containers: "one or more names, separated by | or ,",
|
||||
value: "format depends on field, e.g. 8080:80 for port",
|
||||
template_name: "saved Unraid template name, e.g. Sonarr",
|
||||
query: "app names or purposes, separated by |",
|
||||
overrides: "Config target → value, e.g. {\"8080\":\"18080\"}",
|
||||
approval_ticket: "from the matching *_preview call",
|
||||
confirm: "true only after the user approved",
|
||||
relative_path: "path below the share, never absolute",
|
||||
name_contains: "case-insensitive name fragment",
|
||||
target: "pool/dataset/disk name",
|
||||
access: "{user: read|write|none}",
|
||||
disk: "e.g. disk1, parity, cache",
|
||||
importance: "all | normal | warning | alert",
|
||||
command: "shell command or multi-line script",
|
||||
timeout_seconds: "seconds",
|
||||
job_id: "from job_start",
|
||||
programs: "program names to check",
|
||||
};
|
||||
|
||||
export const LITE_GROUPS: LiteGroup[] = [
|
||||
{
|
||||
name: "unraid_docker",
|
||||
intro: "Docker containers on Unraid.",
|
||||
aliases: { name: "container", id: "container", lines: "tail" },
|
||||
actions: {
|
||||
list: { tool: "unraid_docker_list", summary: "containers with state (filter by state)" },
|
||||
inspect: { tool: "unraid_docker_inspect", summary: "config, ports, mounts (env values redacted)" },
|
||||
logs: { tool: "unraid_docker_logs", summary: "last log lines" },
|
||||
analyze_logs: { tool: "unraid_docker_analyze_logs", summary: "find errors/warnings in logs, one or all containers" },
|
||||
processes: { tool: "unraid_docker_processes", summary: "processes inside a container" },
|
||||
stats: { tool: "unraid_docker_stats", summary: "CPU/RAM/IO of running containers" },
|
||||
info: { tool: "unraid_docker_info", summary: "Docker engine info" },
|
||||
update_status: { tool: "unraid_docker_update_status", summary: "which containers have updates" },
|
||||
start: { tool: "unraid_docker_start", summary: "start" },
|
||||
stop: { tool: "unraid_docker_stop", summary: "stop" },
|
||||
restart: { tool: "unraid_docker_restart", summary: "restart" },
|
||||
update: {
|
||||
tool: "unraid_docker_update_verified_batch", fallback: "unraid_docker_update",
|
||||
summary: "pull new image and recreate (one or comma-separated list)", prepare: joinContainers,
|
||||
},
|
||||
create: { tool: "unraid_docker_create", summary: "create from a saved Unraid template" },
|
||||
modify: { tool: "unraid_docker_modify", summary: "change port/env/volume/network/privileged" },
|
||||
rebuild: { tool: "unraid_docker_rebuild", summary: "recreate from its template" },
|
||||
template_preview: { tool: "unraid_docker_template_preview", rename: OPERATION, summary: "preview creating/removing a template; returns approval_ticket" },
|
||||
template_apply: { tool: "unraid_docker_template_apply", summary: "apply a previewed template change" },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unraid_storage",
|
||||
intro: "Array, disks, pools and shares.",
|
||||
aliases: { share_name: "share", disk_name: "disk", path: "relative_path" },
|
||||
actions: {
|
||||
status: { tool: "unraid_storage_status", summary: "array, parity, pools, disk alerts" },
|
||||
disks: { tool: "unraid_disk_health", summary: "SMART/errors/temperature, one or all disks" },
|
||||
diagnose: { tool: "unraid_storage_diagnostics", rename: OPERATION, summary: "zfs_pool|zfs_dataset|zfs_snapshots|smart|parity_history" },
|
||||
shares: { tool: "unraid_shares_list", summary: "all shares with usage" },
|
||||
share: { tool: "unraid_share_inspect", summary: "one share in detail" },
|
||||
files: { tool: "unraid_files_inventory", summary: "list folders/files inside a share (metadata only)" },
|
||||
share_users: { tool: "unraid_share_users", summary: "SMB users" },
|
||||
share_permissions: { tool: "unraid_share_permissions", summary: "who can access a share" },
|
||||
share_preview: { tool: "unraid_share_preview", rename: OPERATION, summary: "preview create/permissions/remove; returns approval_ticket" },
|
||||
share_apply: { tool: "unraid_share_apply", summary: "apply a previewed share change" },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unraid_network",
|
||||
intro: "Networking of host and containers.",
|
||||
aliases: { target: "host", ip: "host" },
|
||||
actions: {
|
||||
inventory: { tool: "unraid_network_inventory", summary: "interfaces, IPs, container networks" },
|
||||
list: { tool: "unraid_network_list", summary: "Docker networks" },
|
||||
inspect: { tool: "unraid_network_inspect", summary: "one Docker network" },
|
||||
host_state: { tool: "unraid_network_host_state", summary: "routes, DNS, listening ports" },
|
||||
audit_tcp: { tool: "unraid_network_audit_tcp", summary: "test reachability of published TCP ports" },
|
||||
probe: { tool: "unraid_network_lan_probe", summary: "TCP connect test to host:port" },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unraid_system",
|
||||
intro: "Host health and notifications.",
|
||||
actions: {
|
||||
health: { tool: "unraid_system_health", summary: "CPU load, RAM, temperatures, uptime" },
|
||||
notifications: { tool: "unraid_notifications_list", summary: "recent Unraid notifications" },
|
||||
connection_test: { tool: "unraid_system_connection_test", summary: "check MUA can run commands" },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unraid_apps",
|
||||
intro: "Community Applications (app store).",
|
||||
aliases: { name: "container_name", app: "app_id", search: "query", q: "query" },
|
||||
actions: {
|
||||
search: { tool: "unraid_ca_search", summary: "find apps" },
|
||||
install_preview: { tool: "unraid_ca_install_preview", summary: "preview an install; returns approval_ticket" },
|
||||
install: { tool: "unraid_ca_install", summary: "install after preview" },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unraid_shell",
|
||||
intro: "Root shell on the Unraid host (critical). For read-only diagnosis prefer unraid_shell_readonly.",
|
||||
aliases: { cmd: "command", script: "command", id: "job_id", timeout: "timeout_seconds" },
|
||||
actions: {
|
||||
run: { tool: "unraid_system_shell", summary: "run a command/script as root (≤30 min)" },
|
||||
job_start: { tool: "unraid_system_job_start", summary: "start a long job in background, returns job_id" },
|
||||
job_status: { tool: "unraid_system_job_status", summary: "state and output tail of a job" },
|
||||
job_cancel: { tool: "unraid_system_job_cancel", summary: "stop a running job" },
|
||||
job_cleanup: { tool: "unraid_system_job_cleanup", summary: "delete logs of a finished job" },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unraid_toolbox",
|
||||
intro: "Optional agent toolbox container (ffmpeg, yt-dlp, …).",
|
||||
aliases: { cmd: "command", timeout: "timeout_seconds" },
|
||||
actions: {
|
||||
status: { tool: "unraid_toolbox_status", summary: "which programs are installed" },
|
||||
exec: { tool: "unraid_toolbox_exec", summary: "run a command inside the toolbox" },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Einzeltools, die im Lite-Profil unverändert bleiben (Name im Lite-Profil). */
|
||||
const LITE_PASSTHROUGH: Record<string, string> = {
|
||||
unraid_overview: "unraid_overview",
|
||||
unraid_shell_readonly: "unraid_system_shell_readonly",
|
||||
};
|
||||
|
||||
const groupByName = new Map(LITE_GROUPS.map((g) => [g.name, g]));
|
||||
|
||||
type Schema = { type: "object"; properties?: Record<string, any>; required?: string[]; additionalProperties?: boolean };
|
||||
|
||||
function targetFor(action: LiteAction, isAvailable: (tool: string) => boolean): string | null {
|
||||
if (isAvailable(action.tool)) return action.tool;
|
||||
if (action.fallback && isAvailable(action.fallback)) return action.fallback;
|
||||
return null;
|
||||
}
|
||||
|
||||
function liteParamName(action: LiteAction, targetParam: string): string {
|
||||
for (const [lite, target] of Object.entries(action.rename ?? {})) if (target === targetParam) return lite;
|
||||
return targetParam;
|
||||
}
|
||||
|
||||
/** Erzeugt die Lite-Tools für die aktuell freigegebenen Ziel-Tools. */
|
||||
export function buildLiteTools(
|
||||
tools: ToolDef[],
|
||||
isAvailable: (tool: string) => boolean,
|
||||
riskOf: (tool: string) => string = () => "read",
|
||||
): ToolDef[] {
|
||||
const byName = new Map(tools.map((t) => [t.name, t]));
|
||||
const out: ToolDef[] = [];
|
||||
|
||||
for (const [liteName, target] of Object.entries(LITE_PASSTHROUGH)) {
|
||||
const tool = byName.get(target);
|
||||
if (tool && isAvailable(target)) out.push({ ...tool, name: liteName });
|
||||
}
|
||||
|
||||
for (const group of LITE_GROUPS) {
|
||||
const enabled: [string, LiteAction, ToolDef][] = [];
|
||||
for (const [actionName, action] of Object.entries(group.actions)) {
|
||||
const target = targetFor(action, isAvailable);
|
||||
const tool = target ? byName.get(target) : undefined;
|
||||
if (tool) enabled.push([actionName, action, tool]);
|
||||
}
|
||||
if (enabled.length === 0) continue;
|
||||
|
||||
const properties: Record<string, any> = {
|
||||
action: { type: "string", enum: enabled.map(([n]) => n), description: "What to do (see tool description)" },
|
||||
};
|
||||
const lines: string[] = [];
|
||||
for (const [actionName, action, tool] of enabled) {
|
||||
const schema = tool.inputSchema as Schema;
|
||||
const required = new Set(schema.required ?? []);
|
||||
const params: string[] = [];
|
||||
for (const [param, spec] of Object.entries(schema.properties ?? {})) {
|
||||
const liteName = liteParamName(action, param);
|
||||
params.push(required.has(param) ? `${liteName}*` : liteName);
|
||||
if (!properties[liteName]) {
|
||||
const { description: _d, ...rest } = spec as Record<string, unknown>;
|
||||
const hint = LITE_PARAM_HINTS[liteName];
|
||||
properties[liteName] = hint ? { ...rest, description: hint } : rest;
|
||||
} else if (Array.isArray(properties[liteName].enum) && Array.isArray((spec as any).enum)) {
|
||||
properties[liteName] = {
|
||||
...properties[liteName],
|
||||
enum: [...new Set([...properties[liteName].enum, ...(spec as any).enum])],
|
||||
};
|
||||
}
|
||||
}
|
||||
const level = riskOf(tool.name);
|
||||
const risk = level === "critical" ? " [critical]" : level === "write" ? " [changes state]" : "";
|
||||
lines.push(`- ${actionName}${params.length ? `(${params.join(", ")})` : ""}: ${action.summary}${risk}`);
|
||||
}
|
||||
out.push({
|
||||
name: group.name,
|
||||
description: `${group.intro} Pick an action; * = required.\n${lines.join("\n")}`,
|
||||
inputSchema: { type: "object", properties, required: ["action"], additionalProperties: false },
|
||||
handler: async () => { throw new Error("lite group tools are dispatched, not called directly"); },
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface ResolvedCall {
|
||||
tool: string;
|
||||
args: Record<string, unknown>;
|
||||
/** Ignorierte, unbekannte Parameter (für einen Hinweis). */
|
||||
ignored: string[];
|
||||
}
|
||||
|
||||
export class LiteCallError extends Error {}
|
||||
|
||||
/** true, wenn `name` ein Lite-Gruppen- oder Passthrough-Tool ist. */
|
||||
export function isLiteTool(name: string): boolean {
|
||||
return groupByName.has(name) || Object.prototype.hasOwnProperty.call(LITE_PASSTHROUGH, name);
|
||||
}
|
||||
|
||||
/** Übersetzt einen Lite-Aufruf in das freigegebene Ziel-Tool samt Argumenten. */
|
||||
export function resolveLiteCall(
|
||||
name: string,
|
||||
rawArgs: Record<string, unknown>,
|
||||
tools: ToolDef[],
|
||||
isAvailable: (tool: string) => boolean,
|
||||
): ResolvedCall {
|
||||
if (Object.prototype.hasOwnProperty.call(LITE_PASSTHROUGH, name)) {
|
||||
return { tool: LITE_PASSTHROUGH[name], args: rawArgs, ignored: [] };
|
||||
}
|
||||
const group = groupByName.get(name);
|
||||
if (!group) throw new LiteCallError(`Unknown tool: ${name}`);
|
||||
|
||||
const enabledActions = Object.entries(group.actions).filter(([, a]) => targetFor(a, isAvailable));
|
||||
const actionName = String(rawArgs["action"] ?? "").trim().toLowerCase().replace(/[\s-]+/g, "_");
|
||||
const action = group.actions[actionName];
|
||||
const target = action ? targetFor(action, isAvailable) : null;
|
||||
if (!action || !target) {
|
||||
const known = enabledActions.map(([n]) => n).join(", ");
|
||||
throw new LiteCallError(actionName
|
||||
? (action ? `Action '${actionName}' is disabled in the MUA settings. Enabled actions: ${known}`
|
||||
: `Unknown action '${actionName}' for ${name}. Use one of: ${known}`)
|
||||
: `Missing 'action' for ${name}. Use one of: ${known}`);
|
||||
}
|
||||
|
||||
const tool = tools.find((t) => t.name === target)!;
|
||||
const schema = tool.inputSchema as Schema;
|
||||
const known = new Set(Object.keys(schema.properties ?? {}));
|
||||
const knownLite = new Set([...known].map((p) => liteParamName(action, p)));
|
||||
|
||||
// Aliase → kanonische Lite-Namen (nur wenn das Ziel den Originalnamen
|
||||
// nicht selbst kennt, z.B. braucht template_preview wirklich `name`),
|
||||
// dann Lite → Ziel-Namen.
|
||||
const lite: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(rawArgs)) {
|
||||
if (key === "action") continue;
|
||||
const canonical = knownLite.has(key) ? key : group.aliases?.[key] ?? key;
|
||||
if (!(canonical in lite) || key === canonical) lite[canonical] = value;
|
||||
}
|
||||
let args: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(lite)) args[action.rename?.[key] ?? key] = value;
|
||||
if (action.prepare && target === action.tool) {
|
||||
args = action.prepare(args);
|
||||
} else if (target === action.fallback && known.has("container") && args["container"] === undefined && args["containers"] !== undefined) {
|
||||
// Ausweich-Tool kennt nur einen Container (z.B. Einzel-Update).
|
||||
const names = (Array.isArray(args["containers"]) ? args["containers"].map(String) : String(args["containers"]).split(/[|,]/))
|
||||
.map((n) => n.trim()).filter(Boolean);
|
||||
if (names.length > 1) {
|
||||
throw new LiteCallError(`${name} action '${actionName}': only single-container updates are enabled; call it once per container.`);
|
||||
}
|
||||
args["container"] = names[0];
|
||||
delete args["containers"];
|
||||
}
|
||||
// Verwechslungen innerhalb einer Gruppe: share ↔ name
|
||||
if (!known.has("share") && known.has("name") && args["share"] !== undefined && args["name"] === undefined) {
|
||||
args["name"] = args["share"]; delete args["share"];
|
||||
}
|
||||
if (!known.has("name") && known.has("share") && args["name"] !== undefined && args["share"] === undefined) {
|
||||
args["share"] = args["name"]; delete args["name"];
|
||||
}
|
||||
const ignored = Object.keys(args).filter((k) => !known.has(k));
|
||||
for (const k of ignored) delete args[k];
|
||||
const missing = (schema.required ?? []).filter((r) => args[r] === undefined || args[r] === "");
|
||||
if (missing.length > 0) {
|
||||
const params = [...known].map((p) => {
|
||||
const liteName = liteParamName(action, p);
|
||||
return (schema.required ?? []).includes(p) ? `${liteName}*` : liteName;
|
||||
});
|
||||
throw new LiteCallError(
|
||||
`${name} action '${actionName}' needs: ${missing.map((m) => liteParamName(action, m)).join(", ")}. ` +
|
||||
`Parameters: ${params.join(", ") || "none"}${ignored.length ? `. Ignored unknown: ${ignored.join(", ")}` : ""}`,
|
||||
);
|
||||
}
|
||||
return { tool: target, args, ignored: ignored.map((k) => liteParamName(action, k)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Wie ruft man `fullTool` im gegebenen Profil auf? Für Next-Step-Hinweise.
|
||||
* Liefert null, wenn das Tool im Profil nicht erreichbar ist.
|
||||
*/
|
||||
export function callHint(
|
||||
fullTool: string,
|
||||
args: Record<string, unknown>,
|
||||
profile: Profile,
|
||||
): { tool: string; arguments: Record<string, unknown> } {
|
||||
if (profile === "full") return { tool: fullTool, arguments: args };
|
||||
for (const [liteName, target] of Object.entries(LITE_PASSTHROUGH)) {
|
||||
if (target === fullTool) return { tool: liteName, arguments: args };
|
||||
}
|
||||
for (const group of LITE_GROUPS) {
|
||||
for (const [actionName, action] of Object.entries(group.actions)) {
|
||||
if (action.tool === fullTool || action.fallback === fullTool) {
|
||||
const mapped: Record<string, unknown> = { action: actionName };
|
||||
for (const [k, v] of Object.entries(args)) mapped[liteParamName(action, k)] = v;
|
||||
return { tool: group.name, arguments: mapped };
|
||||
}
|
||||
}
|
||||
}
|
||||
return { tool: fullTool, arguments: args };
|
||||
}
|
||||
|
||||
/** Profil aus URL bestimmen: /mcp/lite, ?profile=lite, sonst Standard. */
|
||||
export function profileFromUrl(url: URL, fallback: Profile): Profile {
|
||||
const query = url.searchParams.get("profile")?.toLowerCase();
|
||||
if (query === "lite" || query === "full") return query;
|
||||
if (/^\/mcp\/lite\/?$/.test(url.pathname)) return "lite";
|
||||
if (/^\/mcp\/full\/?$/.test(url.pathname)) return "full";
|
||||
return fallback;
|
||||
}
|
||||
@@ -34,6 +34,8 @@ import {
|
||||
toolboxExec,
|
||||
} from "./helpers";
|
||||
import { READ_ONLY_PROGRAMS } from "./readonly";
|
||||
import { buildOverview } from "./overview";
|
||||
import { isToolEnabled } from "./auth";
|
||||
|
||||
export interface ToolDef {
|
||||
name: string;
|
||||
@@ -103,6 +105,23 @@ function validateShellCommand(value: unknown): string {
|
||||
}
|
||||
|
||||
export const TOOLS: ToolDef[] = [
|
||||
{
|
||||
name: "unraid_overview",
|
||||
description:
|
||||
"START HERE. One-call health summary of the Unraid server: array/parity, disks (errors, temperature, fill level), " +
|
||||
"RAM/CPU/temperatures, crashed or unhealthy containers, available updates and important notifications. " +
|
||||
"Returns `attention` items sorted by severity, each with a ready-to-use `next` tool call.",
|
||||
inputSchema: empty,
|
||||
handler: (a) => buildOverview({
|
||||
run: (tool, args = {}) => {
|
||||
const def = toolByName(tool);
|
||||
if (!def) return Promise.reject(new Error(`unknown tool ${tool}`));
|
||||
return def.handler(args);
|
||||
},
|
||||
isEnabled: isToolEnabled,
|
||||
profile: a["__profile"] === "lite" ? "lite" : "full",
|
||||
}),
|
||||
},
|
||||
...ADMIN_TOOLS,
|
||||
// These two tools are exposed dynamically only when a labeled toolbox is
|
||||
// present and the dedicated WebGUI switch is enabled (see index.ts).
|
||||
|
||||
Reference in new issue
Block a user