Files
MUA-Mikes-Unraid-Agent/src/tools.ts
T

938 lines
38 KiB
TypeScript

import { ADMIN_TOOLS } from "./admin";
/**
* MUA — Mikes Unraid Agent
* tools.ts — MCP Tool-Definitionen
*
* Portiert von mcp/tools.php. Schema: unraid_<kategorie>_<aktion>
* Kategorien: docker (14), network (6), system (2).
*/
import {
containerRuntimeSummary,
compactContainerInspect,
dockerExec,
sanitizeLogOutput,
analyzeContainerLogs,
runPhpHelper,
compactNetworkInventory,
hostState,
auditAllTcpEndpoints,
probeDualstack,
connectionTest,
validateName,
runShell,
startShellJob,
shellJobStatus,
cleanupShellJob,
cancelShellJob,
runReadOnlyInput,
runStatusHelper,
searchCommunityApps,
previewCommunityAppInstall,
installCommunityApp,
toolboxStatus,
toolboxExec,
} from "./helpers";
import { READ_ONLY_PROGRAMS } from "./readonly";
import { buildOverview } from "./overview";
import {
cacheStatus, dockerStorage, moverStart, notificationArchive, notifySend, parityControl, parityStatus,
vmAutostart, vmControl, vmInspect, vmList,
} from "./host";
import { isToolEnabled } from "./auth";
export interface ToolDef {
name: string;
description: string;
inputSchema: object;
handler: (args: Record<string, unknown>) => Promise<string>;
}
export type ToolRisk = "read" | "active" | "write" | "critical";
const CRITICAL_TOOLS = new Set([
"unraid_docker_create",
"unraid_docker_modify",
"unraid_docker_update",
"unraid_docker_update_verified_batch",
"unraid_docker_rebuild",
"unraid_system_shell",
"unraid_toolbox_exec",
"unraid_system_job_start",
"unraid_system_job_cancel",
"unraid_system_job_cleanup",
"unraid_ca_install",
"unraid_share_apply",
"unraid_docker_template_apply",
"unraid_vm_force_stop",
]);
const WRITE_TOOLS = new Set([
"unraid_docker_start",
"unraid_docker_stop",
"unraid_docker_restart",
"unraid_vm_control",
"unraid_vm_autostart",
"unraid_mover_start",
"unraid_parity_control",
"unraid_notify",
"unraid_notification_archive",
]);
/** In r039 hinzugekommene Werkzeuge (für den Hinweis in der WebGUI). */
export const NEW_IN_RELEASE = [
"unraid_vm_list", "unraid_vm_inspect", "unraid_vm_control", "unraid_vm_force_stop", "unraid_vm_autostart",
"unraid_cache_status", "unraid_mover_start", "unraid_parity_status", "unraid_parity_control",
"unraid_docker_storage", "unraid_notify", "unraid_notification_archive",
];
const ACTIVE_TOOLS = new Set([
"unraid_network_audit_tcp",
"unraid_network_lan_probe",
"unraid_ca_search",
"unraid_ca_install_preview",
"unraid_share_preview",
"unraid_docker_template_preview",
]);
export function getToolRisk(name: string): ToolRisk {
if (CRITICAL_TOOLS.has(name)) return "critical";
if (WRITE_TOOLS.has(name)) return "write";
if (ACTIVE_TOOLS.has(name)) return "active";
return "read";
}
const str = (desc: string) => ({ type: "string", description: desc });
const int = (desc: string) => ({ type: "integer", description: desc });
const num = (desc: string) => ({ type: "number", description: desc });
const bool = (desc: string) => ({ type: "boolean", description: desc });
const empty = { type: "object", properties: {}, additionalProperties: false } as const;
const MAX_SHELL_COMMAND_CHARS = 262_144;
const shellCommand = (description: string) => ({
type: "string",
minLength: 1,
maxLength: MAX_SHELL_COMMAND_CHARS,
description,
});
function validateShellCommand(value: unknown): string {
const command = typeof value === "string" ? value : "";
if (command.trim() === "") throw new Error("command is required");
if (command.length > MAX_SHELL_COMMAND_CHARS) {
throw new Error(`command must not exceed ${MAX_SHELL_COMMAND_CHARS} characters`);
}
return command;
}
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",
}),
},
// ── r039: VMs, Cache/Mover, Parity, docker.img, Benachrichtigungen ──────
{
name: "unraid_vm_list",
description: "List virtual machines (libvirt) with state, vCPUs, memory and autostart.",
inputSchema: empty,
handler: () => vmList(),
},
{
name: "unraid_vm_inspect",
description: "Details of one VM: state, disks, network, PCI/USB passthrough, graphics (no passwords) and existing snapshots. Partial names are resolved.",
inputSchema: { type: "object", properties: { vm: str("VM name as shown by unraid_vm_list") }, required: ["vm"], additionalProperties: false },
handler: (a) => vmInspect(a["vm"]),
},
{
name: "unraid_vm_control",
description: "Start, gracefully shut down (ACPI), reboot, suspend or resume a VM. Checks the current state first and reports the new state. Requires the exact VM name.",
inputSchema: {
type: "object",
properties: {
vm: str("Exact VM name"),
operation: { type: "string", enum: ["start", "shutdown", "reboot", "suspend", "resume"] },
},
required: ["vm", "operation"],
additionalProperties: false,
},
handler: (a) => vmControl(a["vm"], String(a["operation"] ?? "")),
},
{
name: "unraid_vm_force_stop",
description: "CRITICAL: Power off a VM immediately (like pulling the plug; unsaved guest data is lost). Use only when a graceful shutdown hangs and the user agreed.",
inputSchema: { type: "object", properties: { vm: str("Exact VM name") }, required: ["vm"], additionalProperties: false },
handler: (a) => vmControl(a["vm"], "force_stop"),
},
{
name: "unraid_vm_autostart",
description: "Enable or disable autostart of a VM when the array starts.",
inputSchema: {
type: "object",
properties: { vm: str("Exact VM name"), enabled: bool("true = start automatically") },
required: ["vm", "enabled"],
additionalProperties: false,
},
handler: (a) => vmAutostart(a["vm"], a["enabled"]),
},
{
name: "unraid_cache_status",
description: "Explain cache/pool usage: fill level per pool, which shares occupy it (with their cache setting), mover state, schedule and recent mover log, plus findings such as files the mover will never move.",
inputSchema: empty,
handler: () => cacheStatus(),
},
{
name: "unraid_mover_start",
description: "Start the Unraid mover now (same as the Move button). Refuses if it is already running.",
inputSchema: empty,
handler: () => moverStart(),
},
{
name: "unraid_parity_status",
description: "Parity operation state and progress, the configured schedule (correcting or not) and the last parity checks with duration and errors.",
inputSchema: empty,
handler: () => parityStatus(),
},
{
name: "unraid_parity_control",
description: "Start, pause, resume or cancel a parity check. start is non-correcting unless correct=true (only if the user explicitly wants corrections written).",
inputSchema: {
type: "object",
properties: {
operation: { type: "string", enum: ["start", "pause", "resume", "cancel"] },
correct: bool("start only: write corrections to parity (default false)"),
},
required: ["operation"],
additionalProperties: false,
},
handler: (a) => parityControl(String(a["operation"] ?? ""), a["correct"]),
},
{
name: "unraid_docker_storage",
description: "Fill level of docker.img / the Docker directory and what uses it (images, containers, volumes, build cache, reclaimable).",
inputSchema: empty,
handler: () => dockerStorage(),
},
{
name: "unraid_notify",
description: "Send an Unraid notification (shown in the WebGUI and forwarded to configured agents such as e-mail, ntfy, Discord). Use it to report results of longer tasks.",
inputSchema: {
type: "object",
properties: {
subject: str("Short subject"),
description: str("One-line description"),
message: str("Optional longer text"),
importance: { type: "string", enum: ["normal", "warning", "alert"] },
link: str("Optional WebGUI path, e.g. /Docker"),
},
required: ["subject"],
additionalProperties: false,
},
handler: (a) => notifySend(a),
},
{
name: "unraid_notification_archive",
description: "Archive (mark as read) one unread Unraid notification by its file name from the notifications list, or all unread ones (optionally of one importance).",
inputSchema: {
type: "object",
properties: {
file: str("File name from unraid_notifications_list"),
all: bool("Archive all unread notifications"),
importance: { type: "string", enum: ["normal", "warning", "alert"] },
},
additionalProperties: false,
},
handler: (a) => notificationArchive(a),
},
...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).
{
name: "unraid_toolbox_status",
description:
"Discover the optional labeled agent toolbox on Unraid and check whether command-line programs such as ffmpeg, ffprobe, yt-dlp or mediainfo are installed there. Use this first when a required CLI program may be missing; do not probe the local Hermes or MCP-client container.",
inputSchema: {
type: "object",
properties: {
programs: {
type: "array",
items: { type: "string", minLength: 1, maxLength: 128, pattern: "^[A-Za-z0-9._+-]+$" },
maxItems: 32,
description: "Optional command names to check inside the running toolbox",
},
},
additionalProperties: false,
},
handler: (a) => {
const raw = a["programs"] ?? [];
if (!Array.isArray(raw) || raw.some((item) => typeof item !== "string")) {
throw new Error("programs must be an array of strings");
}
return toolboxStatus(raw as string[]);
},
},
{
name: "unraid_toolbox_exec",
description:
"Run a command directly inside the labeled agent toolbox on Unraid. Use it for media and download utilities and to install a missing package inside that toolbox when the user requests the job. Never install helper programs into Hermes or the MCP client. The toolbox container is selected dynamically by Docker label, not by a hard-coded name.",
inputSchema: {
type: "object",
properties: {
command: shellCommand("Command or multi-line shell script to run inside the toolbox"),
timeout_seconds: int("Timeout in seconds (1-1800, default 300)"),
container: str("Optional toolbox container name; required only if multiple labeled toolboxes are running"),
},
required: ["command"],
additionalProperties: false,
},
handler: (a) => {
const command = validateShellCommand(a["command"]);
const timeout = Number(a["timeout_seconds"] ?? 300);
if (!Number.isInteger(timeout) || timeout < 1 || timeout > 1800) {
throw new Error("timeout_seconds must be between 1 and 1800");
}
const container = a["container"] === undefined
? undefined
: validateName(a["container"], "container");
return toolboxExec(command, timeout, container);
},
},
// ── Docker (14) ───────────────────────────────────────────────────────
{
name: "unraid_docker_list",
description:
"List Docker containers and return authoritative server-side counts. For questions about active/currently running containers, ALWAYS use state='running'. Defaults to a compact response without performance statistics to avoid large tool output. Use include_stats=true only when CPU, RAM or I/O values are explicitly needed.",
inputSchema: {
type: "object",
properties: {
state: {
type: "string",
enum: ["all", "running", "stopped", "created", "exited"],
description: "Filter by container state. Use 'running' for active/running containers; 'stopped' means every non-running container. Default: all.",
},
include_stats: bool("Include live CPU, RAM, network and block-I/O statistics. Expensive and verbose; default false."),
detail: {
type: "string",
enum: ["compact", "full"],
description: "compact returns name/status/state; full additionally returns ID, image and ports. Default: compact.",
},
},
additionalProperties: false,
},
handler: (a) => containerRuntimeSummary({
state: (a["state"] as "all" | "running" | "stopped" | "created" | "exited" | undefined),
includeStats: a["include_stats"] === true,
detail: (a["detail"] as "compact" | "full" | undefined),
}),
},
{
name: "unraid_docker_inspect",
description:
"Inspect one known Docker container directly. Default summary returns state, image, network mode and ports only. Use detail='full' only when redacted environment variable names or mounts are required. Secret values are never returned.",
inputSchema: {
type: "object",
properties: {
container: str("Container name or ID"),
detail: {
type: "string",
enum: ["summary", "full"],
description: "summary is compact; full additionally returns environment variable names and mounts. Default: summary.",
},
},
required: ["container"],
additionalProperties: false,
},
handler: (a) => compactContainerInspect(
validateName(a["container"], "container"),
(a["detail"] as "summary" | "full" | undefined),
),
},
{
name: "unraid_docker_logs",
description: "Get recent logs from a Docker container (with timestamps).",
inputSchema: {
type: "object",
properties: {
container: str("Container name or ID"),
tail: int("Number of lines (1-2000, default 200)"),
},
required: ["container"],
},
handler: async (a) => {
const container = validateName(a["container"], "container");
const tail = Number(a["tail"] ?? 200);
if (tail < 1 || tail > 2000) throw new Error("tail must be between 1 and 2000");
const raw = await dockerExec(`logs --timestamps --tail ${tail} ${container}`, 60);
return sanitizeLogOutput(raw);
},
},
{
name: "unraid_docker_analyze_logs",
description:
"Analyze container logs server-side for errors/warnings in one bounded call. Use optional focus_terms to restrict results to components such as hass_mcp, yaml or zigbee instead of issuing multiple grep/shell calls. Returns pattern counts and sample matches.",
inputSchema: {
type: "object",
properties: {
severity: {
type: "string",
enum: ["error", "warn", "info"],
description: "Log severity to scan for",
},
container: str("Container name (optional, scans all running containers if omitted)"),
since: str("Time filter (default 24h)"),
scan_tail: int("Max lines to scan (default 1000)"),
max_results: int("Max sample matches (default 50)"),
focus_terms: {
type: "array",
items: { type: "string", minLength: 1, maxLength: 80 },
maxItems: 12,
description:
"Optional literal component/topic terms. A log line must contain at least one term, case-insensitively. Bundle related terms in one call.",
},
},
required: ["severity"],
},
handler: (a) => {
const severity = (a["severity"] as string) ?? "error";
const container = a["container"] as string | null | undefined;
if (container !== undefined && container !== null && typeof container !== "string") {
throw new Error("container must be a string");
}
const since = (a["since"] as string) ?? "24h";
const scanTail = Number(a["scan_tail"] ?? 1000);
const maxResults = Number(a["max_results"] ?? 50);
const focusTerms = Array.isArray(a["focus_terms"])
? (a["focus_terms"] as unknown[]).filter(
(item): item is string => typeof item === "string",
)
: [];
return analyzeContainerLogs(
severity,
container ?? null,
since,
scanTail,
maxResults,
focusTerms,
);
},
},
{
name: "unraid_docker_processes",
description: "List processes running inside a Docker container (docker top).",
inputSchema: {
type: "object",
properties: { container: str("Container name or ID") },
required: ["container"],
},
handler: (a) =>
dockerExec(
`top ${validateName(a["container"], "container")} -eo pid,ppid,user,stat,lstart,etime,args`,
),
},
{
name: "unraid_docker_stats",
description: "Get live CPU/memory/network/block I/O stats for all running containers.",
inputSchema: empty,
handler: () => dockerExec(`stats --no-stream --format '{{json .}}'`),
},
{
name: "unraid_docker_info",
description:
"Get Docker daemon information (version, storage driver, container counts, etc.).",
inputSchema: empty,
handler: () => dockerExec(`info --format '{{json .}}'`),
},
{
name: "unraid_docker_update_status",
description:
"Read Unraid's cached Docker image update state and return a compact per-container summary. Does not pull or update images. Treat updates_available as exhaustive only when status_complete is true; otherwise it is a known minimum and every unknown container must be disclosed.",
inputSchema: empty,
handler: () => runStatusHelper("docker-update-status"),
},
{
name: "unraid_docker_start",
description: "Start a Docker container.",
inputSchema: {
type: "object",
properties: { container: str("Container name or ID") },
required: ["container"],
},
handler: (a) => dockerExec(`start ${validateName(a["container"], "container")}`),
},
{
name: "unraid_docker_stop",
description: "Stop a Docker container.",
inputSchema: {
type: "object",
properties: { container: str("Container name or ID") },
required: ["container"],
},
handler: (a) => dockerExec(`stop ${validateName(a["container"], "container")}`),
},
{
name: "unraid_docker_restart",
description: "Restart a Docker container.",
inputSchema: {
type: "object",
properties: { container: str("Container name or ID") },
required: ["container"],
},
handler: (a) => dockerExec(`restart ${validateName(a["container"], "container")}`),
},
{
name: "unraid_docker_create",
description: "Create a Docker container from a template (pulls image, creates container).",
inputSchema: {
type: "object",
properties: {
template_name: str('Existing user-template name (e.g. Nextcloud), not an image repository'),
},
required: ["template_name"],
},
handler: (a) => runPhpHelper("create", validateName(a["template_name"], "template_name")),
},
{
name: "unraid_docker_modify",
description:
"Modify a container template (port, env, volume, network, privileged) and rebuild.",
inputSchema: {
type: "object",
properties: {
container: str("Container/template name"),
field: {
type: "string",
enum: ["port", "env", "volume", "network", "privileged"],
},
value: str("New value (format depends on field)"),
},
required: ["container", "field", "value"],
},
handler: (a) => {
const container = validateName(a["container"], "container");
const field = (a["field"] as string) ?? "";
const value = (a["value"] as string) ?? "";
if (!["port", "env", "volume", "network", "privileged"].includes(field)) {
throw new Error("field must be one of: port, env, volume, network, privileged");
}
return runPhpHelper("modify", container, field, value);
},
},
{
name: "unraid_docker_update",
description:
"Update one explicitly named container (pull latest image and rebuild). For two or more containers, or when update status may be stale, use unraid_docker_update_verified_batch instead.",
inputSchema: {
type: "object",
properties: { container: str("Container/template name") },
required: ["container"],
},
handler: (a) => runPhpHelper("update", validateName(a["container"], "container")),
},
{
name: "unraid_docker_update_verified_batch",
description:
"Authoritative one-call Docker image update workflow for 1-25 explicitly named Unraid containers. Pulls each configured image, compares immutable image IDs, skips already-current containers even if Unraid's cached status is stale, rebuilds only when the image actually changed, preserves every original running/stopped state, and returns compact post-verification (container ID change, state, restart count and health). Use this after read-only update discovery when the user explicitly requested the updates.",
inputSchema: {
type: "object",
properties: {
containers: str(
"One to 25 exact container names separated by |, as returned by Unraid inventory/update status",
),
},
required: ["containers"],
additionalProperties: false,
},
handler: (a) => {
const raw = String(a["containers"] ?? "");
const containers = raw.split("|").map((name) => name.trim()).filter(Boolean);
if (containers.length < 1 || containers.length > 25) {
throw new Error("containers must contain 1-25 names separated by |");
}
const unique = [...new Set(containers.map((name) => validateName(name, "container")))];
return runPhpHelper("update-verified-batch", unique.join("|"));
},
},
{
name: "unraid_docker_rebuild",
description:
"Rebuild a container from its template (without pulling new image).",
inputSchema: {
type: "object",
properties: { container: str("Container/template name") },
required: ["container"],
},
handler: (a) => runPhpHelper("rebuild", validateName(a["container"], "container")),
},
// ── Community Applications ──────────────────────────────────────────
{
name: "unraid_ca_search",
description:
"Search the official Unraid Community Applications feed in one bounded pass. Returns compact app metadata and a stable app_id; does not install anything. Put up to five useful name/spelling/purpose variants in one query separated by | instead of making repeated synonym calls.",
inputSchema: {
type: "object",
properties: {
query: str("One to five application names, images, repositories or purposes separated by |"),
limit: int("Maximum results (1-25, default 10)"),
},
required: ["query"],
additionalProperties: false,
},
handler: (a) => searchCommunityApps(String(a["query"] ?? ""), Number(a["limit"] ?? 10)),
},
{
name: "unraid_ca_install_preview",
description:
"Prepare and preview installation of an exact Community Applications entry as an Unraid GUI-managed container. Returns a short-lived approval ticket and performs no writes.",
inputSchema: {
type: "object",
properties: {
app_id: str("Exact app_id returned by unraid_ca_search"),
container_name: str("New unique Unraid container name"),
overrides: {
type: "object",
additionalProperties: { type: "string" },
description: "Optional Config Target to value overrides, e.g. {\"8080\":\"18080\"}",
},
start_after_install: bool("Start the container after installation (default false)"),
},
required: ["app_id", "container_name"],
additionalProperties: false,
},
handler: (a) => previewCommunityAppInstall(
String(a["app_id"] ?? ""),
String(a["container_name"] ?? ""),
a["overrides"] ?? {},
Boolean(a["start_after_install"] ?? false),
),
},
{
name: "unraid_ca_install",
description:
"CRITICAL: Install a previously previewed Community Applications entry. Writes an Unraid user template, pulls the image and creates the container so it remains manageable through the Unraid GUI. Requires an exact, unexpired approval ticket and confirm=true.",
inputSchema: {
type: "object",
properties: {
app_id: str("Exact app_id returned by unraid_ca_search"),
container_name: str("New unique Unraid container name"),
overrides: { type: "object", additionalProperties: { type: "string" } },
start_after_install: bool("Start the container after installation"),
confirm: bool("Must be true after explicit user approval"),
approval_ticket: str("Ticket returned by unraid_ca_install_preview"),
},
required: ["app_id", "container_name", "confirm", "approval_ticket"],
additionalProperties: false,
},
handler: (a) => installCommunityApp(
String(a["app_id"] ?? ""),
String(a["container_name"] ?? ""),
a["overrides"] ?? {},
Boolean(a["start_after_install"] ?? false),
Boolean(a["confirm"] ?? false),
String(a["approval_ticket"] ?? ""),
),
},
// ── Netzwerk (6) ──────────────────────────────────────────────────────
{
name: "unraid_network_inventory",
description: "Compact Docker network inventory (all networks with container counts).",
inputSchema: empty,
handler: () => compactNetworkInventory(),
},
{
name: "unraid_network_list",
description: "List all Docker networks.",
inputSchema: empty,
handler: () => dockerExec(`network ls --no-trunc --format '{{json .}}'`),
},
{
name: "unraid_network_inspect",
description: "Inspect a Docker network in detail.",
inputSchema: {
type: "object",
properties: { network: str("Network name or ID") },
required: ["network"],
},
handler: (a) => dockerExec(`network inspect -- ${validateName(a["network"], "network")}`),
},
{
name: "unraid_network_host_state",
description:
"Get host network state (IPv4/IPv6 addresses, routes, listening sockets).",
inputSchema: empty,
handler: () => hostState(),
},
{
name: "unraid_network_audit_tcp",
description:
"Audit all TCP endpoints: probe IPv4/IPv6 reachability for every published port. Returns classification (dualstack/ipv4-only/ipv6-only/unreachable).",
inputSchema: {
type: "object",
properties: {
timeout_seconds: num("Probe timeout (0.2-10, default 2)"),
include_all_endpoints: bool("Include all endpoints (default false, only problems)"),
},
},
handler: (a) => {
const timeout = Number(a["timeout_seconds"] ?? 2);
if (timeout < 0.2 || timeout > 10) {
throw new Error("timeout_seconds must be between 0.2 and 10");
}
const includeAll = Boolean(a["include_all_endpoints"] ?? false);
return auditAllTcpEndpoints(timeout, includeAll);
},
},
{
name: "unraid_network_lan_probe",
description:
"Probe a specific host:port for IPv4 and IPv6 reachability (dualstack test).",
inputSchema: {
type: "object",
properties: {
host: str("Hostname or IP"),
port: int("Port (1-65535)"),
timeout_seconds: num("Timeout (0.2-10, default 3)"),
},
required: ["host", "port"],
},
handler: (a) => {
const host = validateName(a["host"], "host");
const port = Number(a["port"] ?? 0);
const timeout = Number(a["timeout_seconds"] ?? 3);
if (port < 1 || port > 65535 || timeout < 0.2 || timeout > 10) {
throw new Error("Invalid port or timeout");
}
return probeDualstack(host, port, timeout);
},
},
// ── System (3) ────────────────────────────────────────────────────────
{
name: "unraid_system_health",
description:
"Get compact host health: uptime, load averages, logical CPUs, memory use and available temperature sensors.",
inputSchema: empty,
handler: () => runStatusHelper("system-health"),
},
{
name: "unraid_storage_status",
description:
"Get compact Unraid array, parity, pool and disk status including disabled, missing or invalid disk alerts. Serial numbers are omitted.",
inputSchema: empty,
handler: () => runStatusHelper("storage-status"),
},
{
name: "unraid_disk_health",
description:
"Get compact cached SMART health and important error/wear attributes for one disk or all disks. Does not start a SMART test or spin up disks explicitly.",
inputSchema: {
type: "object",
properties: { disk: str("Optional Unraid disk or pool member name, e.g. disk1") },
additionalProperties: false,
},
handler: (a) => runStatusHelper("disk-health", typeof a["disk"] === "string" ? a["disk"] : ""),
},
{
name: "unraid_notifications_list",
description:
"List recent Unraid notifications with compact, secret-redacted subjects and descriptions.",
inputSchema: {
type: "object",
properties: {
limit: int("Number of notifications (1-50, default 20)"),
importance: { type: "string", enum: ["all", "normal", "warning", "alert"] },
},
additionalProperties: false,
},
handler: (a) => runStatusHelper(
"notifications",
String(Math.max(1, Math.min(50, Number(a["limit"] ?? 20)))),
String(a["importance"] ?? "all"),
),
},
{
name: "unraid_shares_list",
description:
"List Unraid shares with pool placement and compact capacity information. Does not list files or file contents.",
inputSchema: empty,
handler: () => runStatusHelper("shares-list"),
},
{
name: "unraid_share_inspect",
description:
"Inspect one Unraid share's allocation, pool/cache placement and capacity. Does not list or read files.",
inputSchema: {
type: "object",
properties: { share: str("Exact Unraid share name") },
required: ["share"],
additionalProperties: false,
},
handler: (a) => runStatusHelper("share-inspect", String(a["share"] ?? "")),
},
{
name: "unraid_files_inventory",
description:
"Inventory file and directory names below one exact Unraid share in a bounded read-only call. Use this instead of repeated ls/find calls for media-library audits and missing-episode checks. It never reads file contents. To locate a collection, first search directories with name_contains; then call this tool once more with the returned directory as relative_path and an empty name_contains to inventory that collection.",
inputSchema: {
type: "object",
properties: {
share: str("Exact Unraid share name, for example Audiobooks"),
relative_path: str("Optional path below the share; never use /mnt/user or an absolute path"),
name_contains: str("Optional case-insensitive basename fragment, for example 'drei'. A matching directory is returned as a collection root and pruned from further discovery; use a second call on that directory with an empty filter to list its descendants"),
max_depth: int("Maximum directory depth below relative_path (1-20, default 10)"),
max_entries: int("Maximum returned entries (1-5000, default 2000)"),
include_files: { type: "boolean", description: "Include files (default true)" },
include_directories: { type: "boolean", description: "Include directories (default true)" },
},
required: ["share"],
additionalProperties: false,
},
handler: (a) => runStatusHelper(
"files-inventory",
String(a["share"] ?? ""),
String(a["relative_path"] ?? ""),
String(a["name_contains"] ?? ""),
String(Math.max(1, Math.min(20, Number(a["max_depth"] ?? 10)))),
String(Math.max(1, Math.min(5000, Number(a["max_entries"] ?? 2000)))),
a["include_files"] === false ? "0" : "1",
a["include_directories"] === false ? "0" : "1",
),
},
{
name: "unraid_system_connection_test",
description:
"Diagnose this authenticated MCP invocation and local command execution on the Unraid host. Reports transport arrival, authentication dispatch and command execution separately. MUA runs as a host plugin, without SSH; a local spawn/interpreter error is not a failed host connection. Includes hostname, kernel, Unraid version and execution location.",
inputSchema: empty,
handler: () => connectionTest(),
},
{
name: "unraid_system_shell_readonly",
description:
"Run read-only diagnostic commands on the Unraid host (safe, no root shell). " +
"Simplest: pass one command line in `command`, e.g. \"tail -n 100 /var/log/syslog\", " +
"\"ps aux | grep -i plex\", \"df -h; free -m\", \"grep -i error /var/log/*.log\". " +
"Supports quotes, pipes between allowed programs, ; && || and globs in absolute paths. " +
"No redirects, variables or $(). Prefer targeted reads (grep, tail -n) over whole files. " +
`Allowed programs: ${READ_ONLY_PROGRAMS.join(" ")}.`,
inputSchema: {
type: "object",
properties: {
command: str("Full command line, e.g. \"tail -n 50 /var/log/syslog | grep -i error\". Use this OR program+args."),
program: str("Single program name (alternative to command), e.g. \"tail\""),
args: {
type: "array",
items: { type: "string", maxLength: 4096 },
maxItems: 256,
description: "Arguments for program, passed literally (no shell)",
},
timeout_seconds: int("Timeout in seconds (1-120, default 30)"),
max_output_chars: int("Output limit (1000-30000, default 12000). Raise only if really needed."),
},
additionalProperties: false,
},
handler: (a) => {
const timeout = Number(a["timeout_seconds"] ?? 30);
if (!Number.isFinite(timeout) || timeout < 1 || timeout > 120) {
throw new Error("timeout_seconds must be between 1 and 120");
}
const maxOutputChars = Number(a["max_output_chars"] ?? 12_000);
if (!Number.isInteger(maxOutputChars) || maxOutputChars < 1_000 || maxOutputChars > 30_000) {
throw new Error("max_output_chars must be between 1000 and 30000");
}
return runReadOnlyInput(
{ command: a["command"], program: a["program"], args: a["args"] },
timeout,
maxOutputChars,
);
},
},
{
name: "unraid_system_shell",
description:
"Direct terminal on the Unraid host as root. Prefer the typed share and Docker-template preview/apply tools for their supported operations. When the user explicitly asks to create or edit host files, run Docker commands, install software, or administer Unraid, use this tool directly. Do not inspect MUA internals and do not proxy the command through Hermes' local container terminal. Multi-line shell scripts are accepted. Commands may run for up to 30 minutes; use unraid_system_job_start only for work expected to take longer.",
inputSchema: {
type: "object",
properties: {
command: shellCommand(
"Command or multi-line shell script to execute directly on the Unraid host via /bin/sh -c (maximum 262144 characters)",
),
timeout_seconds: int("Timeout in seconds (1-1800, default 300)"),
},
required: ["command"],
additionalProperties: false,
},
handler: (a) => {
const command = validateShellCommand(a["command"]);
const timeout = Number(a["timeout_seconds"] ?? 300);
if (timeout < 1 || timeout > 1800) {
throw new Error("timeout_seconds must be between 1 and 1800");
}
return runShell(command, timeout);
},
},
{
name: "unraid_system_job_start",
description:
"Start a direct asynchronous terminal job on the Unraid host for work expected to exceed 30 minutes. For normal Docker, file and administration commands use unraid_system_shell instead. Accepts multi-line scripts and returns a job_id immediately.",
inputSchema: {
type: "object",
properties: {
command: shellCommand("Long-running command or multi-line shell script to execute on Unraid via /bin/sh (maximum 262144 characters)"),
},
required: ["command"],
additionalProperties: false,
},
handler: (a) => startShellJob(validateShellCommand(a["command"])),
},
{
name: "unraid_system_job_status",
description:
"Poll one asynchronous Unraid shell job by job_id. Returns running/finished state, exit code and compact stdout/stderr tails. Do not start a duplicate job while this reports running.",
inputSchema: {
type: "object",
properties: { job_id: str("Job identifier returned by unraid_system_job_start") },
required: ["job_id"],
additionalProperties: false,
},
handler: (a) => shellJobStatus(String(a["job_id"] ?? "")),
},
{
name: "unraid_system_job_cancel",
description:
"CRITICAL: Stop a running asynchronous Unraid shell job by job_id, including every process it started. Use it when a job hangs or was started by mistake.",
inputSchema: {
type: "object",
properties: { job_id: str("Job identifier returned by unraid_system_job_start") },
required: ["job_id"],
additionalProperties: false,
},
handler: (a) => cancelShellJob(String(a["job_id"] ?? "")),
},
{
name: "unraid_system_job_cleanup",
description:
"CRITICAL: Remove the private MUA metadata/log directory for one completed asynchronous job. This never removes the command's own output files. Refuses cleanup while the job is running.",
inputSchema: {
type: "object",
properties: { job_id: str("Completed job identifier") },
required: ["job_id"],
additionalProperties: false,
},
handler: (a) => cleanupShellJob(String(a["job_id"] ?? "")),
},
];
export function toolByName(name: string): ToolDef | undefined {
return TOOLS.find((t) => t.name === name);
}