Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(mcp): add lightweight node lookup tools
Nebesze8ea6857bc01
diff --git a/backend/app/api/routes/nodes.py b/backend/app/api/routes/nodes.pyindex 0ef1bc2..8d4d463 100644--- a/backend/app/api/routes/nodes.py+++ b/backend/app/api/routes/nodes.py@@ -1,4 +1,4 @@-from fastapi import APIRouter, Depends, HTTPException, status+from fastapi import APIRouter, Depends, HTTPException, Query, statusfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession@@ -55,9 +55,15 @@ async def _find_free_position(db: AsyncSession, design_id: str | None) -> tuple[@router.get("", response_model=list[NodeResponse])-async def list_nodes(db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> list[Node]:- result = await db.execute(select(Node))- return list(result.scalars().all())+async def list_nodes(+ label: str | None = Query(None, description="Case-insensitive substring filter on node label"),+ db: AsyncSession = Depends(get_db),+ _: str = Depends(get_current_user),+) -> list[Node]:+ query = select(Node)+ if label:+ query = query.where(Node.label.ilike(f"%{label}%"))+ return list((await db.execute(query)).scalars().all())@router.post("", response_model=NodeResponse, status_code=status.HTTP_201_CREATED)diff --git a/backend/tests/test_nodes.py b/backend/tests/test_nodes.pyindex a11b7e4..ce61a0c 100644--- a/backend/tests/test_nodes.py+++ b/backend/tests/test_nodes.py@@ -363,3 +363,43 @@ async def test_create_node_explicit_zero_position_preserved(client: AsyncClient,)assert res.status_code == 201assert (res.json()["pos_x"], res.json()["pos_y"]) == (0.0, 0.0)+++async def test_list_nodes_filters_by_label_exact(client: AsyncClient, headers: dict):+ await client.post("/api/v1/nodes", json={"type": "server", "label": "Proxmox", "status": "unknown"}, headers=headers)+ await client.post("/api/v1/nodes", json={"type": "router", "label": "Router", "status": "unknown"}, headers=headers)+ res = await client.get("/api/v1/nodes?label=Proxmox", headers=headers)+ assert res.status_code == 200+ assert [n["label"] for n in res.json()] == ["Proxmox"]+++async def test_list_nodes_filters_by_label_substring(client: AsyncClient, headers: dict):+ await client.post("/api/v1/nodes", json={"type": "server", "label": "pve1-node", "status": "unknown"}, headers=headers)+ await client.post("/api/v1/nodes", json={"type": "server", "label": "pve2-node", "status": "unknown"}, headers=headers)+ await client.post("/api/v1/nodes", json={"type": "router", "label": "Router", "status": "unknown"}, headers=headers)+ res = await client.get("/api/v1/nodes?label=pve", headers=headers)+ assert res.status_code == 200+ assert sorted(n["label"] for n in res.json()) == ["pve1-node", "pve2-node"]+++async def test_list_nodes_filters_by_label_case_insensitive(client: AsyncClient, headers: dict):+ await client.post("/api/v1/nodes", json={"type": "server", "label": "Proxmox", "status": "unknown"}, headers=headers)+ res = await client.get("/api/v1/nodes?label=PROXMOX", headers=headers)+ assert res.status_code == 200+ assert [n["label"] for n in res.json()] == ["Proxmox"]+++async def test_list_nodes_filters_by_label_no_match(client: AsyncClient, headers: dict):+ await client.post("/api/v1/nodes", json={"type": "server", "label": "Proxmox", "status": "unknown"}, headers=headers)+ res = await client.get("/api/v1/nodes?label=nonexistent", headers=headers)+ assert res.status_code == 200+ assert res.json() == []+++async def test_list_nodes_without_label_param_returns_all(client: AsyncClient, headers: dict):+ """Omitting label is fully backward compatible with the old unfiltered behavior."""+ for label in ("A", "B", "C"):+ await client.post("/api/v1/nodes", json={"type": "generic", "label": label, "status": "unknown"}, headers=headers)+ res = await client.get("/api/v1/nodes", headers=headers)+ assert res.status_code == 200+ assert len(res.json()) == 3diff --git a/mcp/app/tools.py b/mcp/app/tools.pyindex a47173a..ba1649f 100644--- a/mcp/app/tools.py+++ b/mcp/app/tools.py@@ -1,4 +1,5 @@import json+from urllib.parse import quotefrom mcp.server import Serverfrom mcp.types import Tool, TextContentfrom .backend_client import backend@@ -147,6 +148,17 @@ def _build_tools() -> list[Tool]:"type": "object","properties": {},}),+ Tool(name="list_node_summaries", description="List all nodes with only id/label/type/status — a lighter, lower-token alternative to list_nodes or get_canvas for when full node detail (ip, services, notes, hardware, properties, ...) isn't needed.", inputSchema={+ "type": "object",+ "properties": {},+ }),+ Tool(name="get_node", description="Get node(s) by id or by label. Provide exactly one of the two. Lookup by 'id' returns a single full node object. Lookup by 'label' is a case-insensitive substring match and returns a list of full node objects, since labels are not unique.", inputSchema={+ "type": "object",+ "properties": {+ "id": {"type": "string", "description": "Node id. Returns a single node object."},+ "label": {"type": "string", "description": "Case-insensitive substring match on label. Returns a list of matching node objects."},+ },+ }),Tool(name="list_pending_devices", description="List devices discovered by scan but not yet approved or hidden", inputSchema={"type": "object","properties": {},@@ -229,6 +241,11 @@ def _slim_canvas(raw: dict) -> dict:}+def _slim_node_summary(n: dict) -> dict:+ """Only the fields needed to identify a node and reference it in later calls."""+ return {"id": n.get("id"), "label": n.get("label"), "type": n.get("type"), "status": n.get("status")}++async def _dispatch(name: str, args: dict) -> dict:if name == "create_node":return await backend.post("/api/v1/nodes", args)@@ -266,6 +283,19 @@ async def _dispatch(name: str, args: dict) -> dict:if name == "list_nodes":return await backend.get("/api/v1/nodes")+ if name == "list_node_summaries":+ nodes = await backend.get("/api/v1/nodes")+ return [_slim_node_summary(n) for n in nodes]++ if name == "get_node":+ node_id = args.get("id")+ label = args.get("label")+ if node_id:+ return await backend.get(f"/api/v1/nodes/{node_id}")+ if label:+ return await backend.get(f"/api/v1/nodes?label={quote(label)}")+ raise ValueError("get_node requires either 'id' or 'label'")+if name == "list_pending_devices":# Backend /scan/pending returns the whole inventory: approved rows stay# listed so the frontend can show a canvas-presence badge. This tooldiff --git a/mcp/tests/test_tools.py b/mcp/tests/test_tools.pyindex 51f6f27..b7d3676 100644--- a/mcp/tests/test_tools.py+++ b/mcp/tests/test_tools.py@@ -270,6 +270,55 @@ async def test_list_nodes(mock_backend):assert result == [{"id": "1", "label": "Freebox"}]+async def test_list_node_summaries(mock_backend):+ mock_backend.get = AsyncMock(return_value=[+ {+ "id": "1", "label": "Freebox", "type": "router", "status": "online",+ "ip": "192.168.1.1", "notes": "ISP box", "properties": [{"name": "rack", "value": "A1"}],+ },+ ])+ result = await _dispatch("list_node_summaries", {})+ mock_backend.get.assert_called_once_with("/api/v1/nodes")+ assert result == [{"id": "1", "label": "Freebox", "type": "router", "status": "online"}]+++async def test_get_node_by_id(mock_backend):+ mock_backend.get = AsyncMock(return_value={"id": "42", "label": "pve1", "type": "proxmox"})+ result = await _dispatch("get_node", {"id": "42"})+ mock_backend.get.assert_called_once_with("/api/v1/nodes/42")+ assert result == {"id": "42", "label": "pve1", "type": "proxmox"}+++async def test_get_node_by_label(mock_backend):+ mock_backend.get = AsyncMock(return_value=[{"id": "1", "label": "pve1"}, {"id": "2", "label": "pve2"}])+ result = await _dispatch("get_node", {"label": "pve"})+ mock_backend.get.assert_called_once_with("/api/v1/nodes?label=pve")+ assert result == [{"id": "1", "label": "pve1"}, {"id": "2", "label": "pve2"}]+++async def test_get_node_by_label_url_encodes(mock_backend):+ mock_backend.get = AsyncMock(return_value=[])+ await _dispatch("get_node", {"label": "living room ap"})+ mock_backend.get.assert_called_once_with("/api/v1/nodes?label=living%20room%20ap")+++async def test_get_node_id_takes_precedence_over_label(mock_backend):+ mock_backend.get = AsyncMock(return_value={"id": "42"})+ await _dispatch("get_node", {"id": "42", "label": "pve"})+ mock_backend.get.assert_called_once_with("/api/v1/nodes/42")+++async def test_get_node_requires_id_or_label():+ with pytest.raises(ValueError, match="requires either"):+ await _dispatch("get_node", {})++@pytest.mark.anyioasync def test_list_pending_devices(mock_backend):mock_backend.get = AsyncMock(return_value=[{"id": "p1", "ip": "192.168.1.50"}])