"""MCP (Model Context Protocol) server over streamable HTTP. Implements a stateless JSON-RPC subset: initialize, ping, tools/list, tools/call, resources/list and resources/read. Point an MCP client at `POST /api/mcp` with an API key in `X-API-Key`. """ from __future__ import annotations import json from typing import Any, Dict, List, Optional from . import capacity, db, licensing, registry PROTOCOL_VERSION = "2024-11-05" TOOLS: List[Dict[str, Any]] = [ { "name": "list_assets", "description": "List managed assets with utilization, pressure, trend and days-to-full.", "inputSchema": { "type": "object", "properties": { "type": {"type": "string", "description": "Filter by asset type (hypervisor, storage, server, ...)"}, "module": {"type": "string", "description": "Filter by module id"}, "min_pressure": {"type": "number", "description": "Only return assets at or above this pressure (0-100)"}, "limit": {"type": "integer", "description": "Max results (default 50)"}, }, "additionalProperties": False, }, }, { "name": "get_asset", "description": "Get detail for one asset: metrics, trend, forecast, recommendation and alerts.", "inputSchema": { "type": "object", "properties": { "asset_id": {"type": "string", "description": "Headroom asset id, e.g. proxmox::pve-01"}, "include_series": {"type": "boolean", "description": "Include raw time series (default false)"}, }, "required": ["asset_id"], "additionalProperties": False, }, }, { "name": "capacity_summary", "description": "Fleet capacity summary: KPIs, resource pools, groups and open alerts.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}, }, { "name": "forecast_capacity", "description": "List the assets with the shortest runway and the projected storage exhaustion date.", "inputSchema": { "type": "object", "properties": {"limit": {"type": "integer", "description": "Max results (default 10)"}}, "additionalProperties": False, }, }, { "name": "simulate_capacity", "description": "What-if simulation of growth and added CPU, memory or storage over a horizon.", "inputSchema": { "type": "object", "properties": { "horizon_days": {"type": "integer", "minimum": 7, "maximum": 365}, "growth_multiplier": {"type": "number", "minimum": 0, "maximum": 5}, "add_storage_gb": {"type": "number"}, "add_cpu_cores": {"type": "number"}, "add_mem_gb": {"type": "number"}, "disable_modules": {"type": "array", "items": {"type": "string"}}, }, "additionalProperties": False, }, }, { "name": "list_alerts", "description": "List capacity alerts, open by default.", "inputSchema": { "type": "object", "properties": { "include_resolved": {"type": "boolean"}, "limit": {"type": "integer"}, }, "additionalProperties": False, }, }, { "name": "list_modules", "description": "List collector modules, their status and asset counts.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}, }, { "name": "run_module", "description": "Trigger a collection run for one module (operator role required).", "inputSchema": { "type": "object", "properties": {"module_id": {"type": "string"}}, "required": ["module_id"], "additionalProperties": False, }, }, { "name": "get_audit_log", "description": "Recent configuration and security audit events (admin only).", "inputSchema": { "type": "object", "properties": {"limit": {"type": "integer"}}, "additionalProperties": False, }, }, ] RESOURCES = [ {"uri": "headroom://overview", "name": "Fleet overview", "mimeType": "application/json", "description": "KPIs, resource pools, pressure leaders and alerts."}, {"uri": "headroom://assets", "name": "Asset inventory", "mimeType": "application/json", "description": "All active assets with utilization and forecasts."}, {"uri": "headroom://alerts", "name": "Open alerts", "mimeType": "application/json", "description": "Current capacity alerts."}, {"uri": "headroom://modules", "name": "Modules", "mimeType": "application/json", "description": "Collector module status."}, ] def _summaries() -> List[Dict[str, Any]]: assets = capacity.list_assets() latest = capacity.latest_values() slopes: Dict[Any, float] = {} out = [] for asset in assets: analysis = capacity.analyze(asset, latest.get(asset["id"], {}), slopes) out.append(capacity.summary(asset, latest.get(asset["id"], {}), analysis)) return out def tool_list_assets(args: Dict[str, Any]) -> Any: items = _summaries() type_filter = args.get("type") module = args.get("module") min_pressure = float(args.get("min_pressure") or 0) limit = max(1, min(500, int(args.get("limit") or 50))) if type_filter: items = [item for item in items if item["type"] == type_filter] if module: items = [item for item in items if item["module_id"] == module] items = [item for item in items if (item.get("pressure") or 0) >= min_pressure] items.sort(key=lambda item: item.get("pressure") or 0, reverse=True) return [capacity.compact(item) for item in items[:limit]] def tool_get_asset(args: Dict[str, Any]) -> Any: asset_id = str(args.get("asset_id", "")).strip() if not asset_id: raise ValueError("asset_id is required") detail = capacity.asset_detail(asset_id, 30) if not detail: raise ValueError(f"Asset '{asset_id}' not found") if not args.get("include_series"): detail.pop("cards", None) detail.pop("forecasts", None) return detail def tool_summary() -> Any: data = capacity.overview(7) return { "generated_at": data["generated_at"], "kpis": data["kpis"], "resources": data["resources"], "groups": [ { "name": group["name"], "module": group["module_name"], "assets": group["asset_count"], "pressure": group["pressure"], "util": group["util"], "days_to_full": group["days_to_full"], "resources": group["resources"], } for group in data["groups"] ], "alerts": data["alerts"], } def tool_forecast(args: Dict[str, Any]) -> Any: limit = max(1, min(100, int(args.get("limit") or 10))) items = [ item for item in _summaries() if item.get("days_to_full") is not None ] items.sort(key=lambda item: item["days_to_full"]) return { "nearest": [ { "asset_id": item["id"], "name": item["name"], "module": item["module_name"], "metric": item["primary_metric"], "util_pct": item["util"], "growth_pp_per_day": item["slope_per_day"], "days_to_full": item["days_to_full"], "eta_date": item["eta_date"], } for item in items[:limit] ], "storage": capacity.overview(7)["resources"]["storage"], } def tool_modules() -> Any: return [ { "id": module["id"], "name": module["name"], "version": module.get("version"), "enabled": module["enabled"], "status": module["status"], "last_run": module["last_run"], "asset_count": module["asset_count"], "source": module["source"], } for module in registry.list_modules() ] def call_tool(name: str, args: Dict[str, Any], user: Dict[str, Any]) -> Any: if name == "list_assets": return tool_list_assets(args) if name == "get_asset": return tool_get_asset(args) if name == "capacity_summary": return tool_summary() if name == "forecast_capacity": return tool_forecast(args) if name == "simulate_capacity": return capacity.simulate(args) if name == "list_alerts": return capacity.alerts( include_resolved=bool(args.get("include_resolved")), limit=max(1, min(500, int(args.get("limit") or 50))), ) if name == "list_modules": return tool_modules() if name == "run_module": if user.get("role") not in ("admin", "operator"): raise PermissionError("Operator role required to run modules") module_id = str(args.get("module_id", "")).strip() if not module_id: raise ValueError("module_id is required") result = registry.run_module(module_id, trigger="mcp") capacity.evaluate_policies() db.audit(user.get("username", "mcp"), "module.run", module_id, "triggered via MCP") return result if name == "get_audit_log": if user.get("role") != "admin": raise PermissionError("Admin role required") limit = max(1, min(500, int(args.get("limit") or 50))) return [dict(row) for row in db.query("SELECT * FROM audit ORDER BY id DESC LIMIT ?", (limit,))] raise ValueError(f"Unknown tool '{name}'") def read_resource(uri: str) -> Any: if uri == "headroom://overview": return tool_summary() if uri == "headroom://assets": return tool_list_assets({"limit": 500}) if uri == "headroom://alerts": return capacity.alerts(include_resolved=False, limit=500) if uri == "headroom://modules": return tool_modules() raise ValueError(f"Unknown resource '{uri}'") def catalog() -> Dict[str, Any]: enabled = licensing.has_feature("mcp_server") return { "enabled": enabled, "endpoint": "/api/mcp", "protocol_version": PROTOCOL_VERSION, "tools": TOOLS, "resources": RESOURCES, "auth": "Create an API key under API & AI, then send it as X-API-Key.", "example": { "claude_desktop": { "mcpServers": { "headroom": { "url": "http://127.0.0.1:8787/api/mcp", "headers": {"X-API-Key": "hr_..."}, } } } }, } def handle(payload: Dict[str, Any], user: Dict[str, Any]) -> Dict[str, Any]: request_id = payload.get("id") method = payload.get("method", "") params = payload.get("params") or {} def ok(result: Any) -> Dict[str, Any]: return {"jsonrpc": "2.0", "id": request_id, "result": result} def error(code: int, message: str, data: Optional[Any] = None) -> Dict[str, Any]: body = {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}} if data is not None: body["error"]["data"] = data return body if not licensing.has_feature("mcp_server"): return error( -32001, "The MCP server requires Headroom Enterprise (trial available).", {"code": "upgrade_required", "feature": "mcp_server"}, ) try: if method == "initialize": return ok( { "protocolVersion": PROTOCOL_VERSION, "capabilities": {"tools": {}, "resources": {}}, "serverInfo": {"name": "headroom", "version": "1.0.0"}, "instructions": ( "Headroom exposes homelab capacity data. Start with capacity_summary, " "then inspect high-pressure assets with get_asset. Use simulate_capacity " "before recommending hardware purchases." ), } ) if method in ("notifications/initialized", "ping"): return ok({}) if method == "tools/list": return ok({"tools": TOOLS}) if method == "tools/call": name = str(params.get("name", "")) args = params.get("arguments") or {} if not isinstance(args, dict): return error(-32602, "arguments must be an object") try: data = call_tool(name, args, user) return ok( { "content": [{"type": "text", "text": json.dumps(data, indent=2, default=str)}], "isError": False, } ) except PermissionError as exc: return ok( { "content": [{"type": "text", "text": f"Permission denied: {exc}"}], "isError": True, } ) except Exception as exc: return ok( { "content": [{"type": "text", "text": f"Tool failed: {type(exc).__name__}: {exc}"}], "isError": True, } ) if method == "resources/list": return ok({"resources": RESOURCES}) if method == "resources/read": uri = str(params.get("uri", "")) try: data = read_resource(uri) except ValueError as exc: return error(-32602, str(exc)) return ok( { "contents": [ { "uri": uri, "mimeType": "application/json", "text": json.dumps(data, indent=2, default=str), } ] } ) return error(-32601, f"Method not found: {method}") except Exception as exc: return error(-32603, f"Internal error: {exc}")