Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

feat(mcp): expose the rack canvas and the inventory write routes

Pouzor4c8831d5df18
diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml
index 87f3b45..5db1c02 100644
--- a/.github/workflows/quality.yml
+++ b/.github/workflows/quality.yml
@@ -61,10 +61,13 @@ jobs:
- run: mypy app/
- run: pytest
- # Also guards the NODE_TYPES / EDGE_TYPES enums in mcp/app/tools.py against
- # drift from frontend/src/types/index.ts (test_node_types_sync.py,
- # test_edge_types_sync.py) — those tests need the frontend sources, so this
- # job runs from a full checkout rather than the mcp Docker context.
+ # Also guards the copies the MCP server keeps of frontend data against drift:
+ # NODE_TYPES / EDGE_TYPES in mcp/app/tools.py against frontend/src/types/index.ts,
+ # and the faceplate catalog in mcp/app/faceplates.py against
+ # frontend/src/rack/faceplates.ts (test_node_types_sync.py,
+ # test_edge_types_sync.py, test_faceplates_sync.py) — those tests need the
+ # frontend sources, so this job runs from a full checkout rather than the mcp
+ # Docker context.
mcp:
runs-on: ubuntu-latest
defaults:
diff --git a/FEATURES.md b/FEATURES.md
index 7d84415..7a8aebc 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -258,7 +258,7 @@ Widget snippet lives in the [README](./README.md#gethomepage-widget-read-only-st
2. `docker compose up -d mcp` (listens on `:8001`). No Docker? `sudo bash scripts/lxc-mcp-install.sh`.
3. Point your client at `http://<your-homelab-ip>:8001/mcp` with header `X-API-Key: <your key>`.
-The AI can list nodes/edges/canvas/pending/scans, add/update/delete nodes and edges, kick off scans, and approve or hide devices. Keep port 8001 firewalled to your LAN. Full setup in the [README](./README.md#mcp-server-ai-integration-optional).
+The AI can list nodes/edges/canvas/zones/designs/inventory/scans, add/update/delete nodes, edges and zones, kick off scans, triage and edit inventory entries, and work a rack canvas — create racks, mount and move gear, patch cables. Keep port 8001 firewalled to your LAN. Full setup in the [README](./README.md#mcp-server-ai-integration-optional).
---
diff --git a/README.md b/README.md
index f93d243..b3d6d1d 100644
--- a/README.md
+++ b/README.md
@@ -336,8 +336,8 @@ Homelable can exposes a [Model Context Protocol](https://modelcontextprotocol.io
| | Action |
|---|---|
-| **Read** | List all nodes, edges, full canvas, pending devices, scan history |
-| **Write** | Add / update / delete nodes and edges, trigger a network scan, approve or hide discovered devices |
+| **Read** | List all nodes, edges, full canvas, zones, designs, the device inventory and scan history — and the rack canvases: racks, mounted gear, patched cables |
+| **Write** | Add / update / delete nodes, edges and zones, trigger a network scan, approve / hide / restore discovered devices, create and edit inventory entries, build racks and mount, move and patch the gear in them |
### Setup
@@ -413,6 +413,8 @@ Or add it manually to `~/.claude.json`:
- *"Add a new LXC container named `pihole` at 192.168.1.5, connected to my switch."*
- *"Trigger a network scan on 192.168.1.0/24 and show me the pending devices."*
- *"Show me the full canvas topology."*
+- *"How much free U is left in the garage rack?"*
+- *"Mount the NAS in rack 1 and patch its first port to port 12 of the patch panel."*
### Security
diff --git a/docs/rack-canvas.md b/docs/rack-canvas.md
index 07ffdf6..2b2bcf7 100644
--- a/docs/rack-canvas.md
+++ b/docs/rack-canvas.md
@@ -236,7 +236,8 @@ diagram's online/offline tally. **PNG export** works here too.
- No power draw or outlet budgeting.
- No undo/redo on a rack canvas (the diagram canvas keeps its own).
- Rack canvases are not shown by the read-only [Live View](../README.md#live-view-read-only-public-canvas).
-- The MCP server exposes diagram nodes and links only, not racks.
+- The MCP server can read and edit a rack canvas, but its save is last-writer-wins:
+ an AI write while you have the canvas open with unsaved changes loses one side.
---
diff --git a/mcp/app/devices.py b/mcp/app/devices.py
new file mode 100644
index 0000000..c9e6fb5
--- /dev/null
+++ b/mcp/app/devices.py
@@ -0,0 +1,166 @@
+"""Device Inventory write tools.
+
+The inventory (`device_inventory`) is what a scan finds plus what the user
+documents by hand. `tools.py` already reads and triages it; these are the write
+routes behind the inventory UI — create, edit, delete, the bulk actions, the
+per-device deep rescan and the scan configuration.
+"""
+
+from typing import Any
+
+from mcp.types import Tool
+
+from .backend_client import backend
+
+# Fields shared by create and update, mirroring InventoryDeviceCreate /
+# InventoryDeviceUpdate (backend/app/schemas/scan.py). `_dispatch` forwards args
+# verbatim, so anything advertised here is what the backend already validates.
+_DEVICE_FIELDS = {
+ "ip": {"type": "string"},
+ "mac": {"type": "string"},
+ "os": {"type": "string"},
+ "suggested_type": {"type": "string", "description": "What kind of hardware this is (server, switch, nas, ...). Drives the icon, the filters and the rack faceplate suggestion."},
+ "model": {"type": "string"},
+ "vendor": {"type": "string"},
+ "friendly_name": {"type": "string", "description": "Display name, preferred over the hostname everywhere the device is listed."},
+ "device_subtype": {"type": "string"},
+ "label": {"type": "string"},
+ "type": {"type": "string"},
+ "notes": {"type": "string"},
+ "services": {"type": "array", "items": {"type": "object"}, "description": "Services running on the device: [{port, protocol, service_name, category}]."},
+ # Same shape as a node's: `key` is the identity the backend merges on.
+ "properties": {"type": "array", "items": {"type": "object"}, "description": "Key/value metadata: [{key, value, icon, visible}]. `key` is required — keyless properties collapse into one."},
+ "cpu_count": {"type": "integer"},
+ "cpu_model": {"type": "string"},
+ "ram_gb": {"type": "number"},
+ "disk_gb": {"type": "number"},
+ "show_hardware": {"type": "boolean"},
+ "check_method": {"type": "string", "description": "Status check method (ping, http, https, ssh, prometheus, tcp)."},
+ "check_target": {"type": "string"},
+}
+
+# The front panel the device wears in every rack. Editable from the inventory as
+# well as from a rack canvas; sending `rack_faceplate_id` is what models a device.
+_RACK_MODEL_FIELDS = {
+ "rack_faceplate_id": {"type": "string", "description": "Faceplate the device wears in a rack. Call list_faceplates for ids."},
+ "rack_u_height": {"type": "integer"},
+ "rack_col_span": {"type": "integer"},
+ "rack_color": {"type": "string"},
+ "rack_ports": {"type": "array", "items": {"type": "object"}, "description": "Ports on the faceplate: [{id, label, type, x, y}]."},
+}
+
+DEVICE_TOOLS = [
+ Tool(name="create_device", description="Add hardware to the Device Inventory by hand — a dumb switch, a patch panel, a machine no scan can reach. Merges into the existing entry when the ip or mac is already known.", inputSchema={
+ "type": "object",
+ "required": ["hostname"],
+ "properties": {
+ "hostname": {"type": "string", "description": "Host name, or any name when the device has none."},
+ "discovery_source": {"type": "string", "enum": ["manual", "rack"], "default": "manual", "description": "'rack' marks a placeholder created for a rack plate; it can never be approved onto a logical canvas."},
+ **_DEVICE_FIELDS,
+ },
+ }),
+ Tool(name="update_device", description="Edit an inventory entry: the device facts and its rack faceplate. Only the fields sent are applied. Lifecycle (pending/approved/hidden) is owned by the approve/hide/restore tools.", inputSchema={
+ "type": "object",
+ "required": ["id"],
+ "properties": {
+ "id": {"type": "string"},
+ "hostname": {"type": "string"},
+ **_DEVICE_FIELDS,
+ **_RACK_MODEL_FIELDS,
+ },
+ }),
+ Tool(name="delete_device", description="Delete an inventory entry outright. A canvas node drawing it survives with its link cleared; use hide_device instead to keep the entry out of the way without losing it.", inputSchema={
+ "type": "object",
+ "required": ["id"],
+ "properties": {"id": {"type": "string"}},
+ }),
+ Tool(name="bulk_approve_devices", description="Approve several discovered devices at once, creating a node for each on the target canvas. Devices created from a rack are skipped — they never go on a logical canvas.", inputSchema={
+ "type": "object",
+ "required": ["device_ids"],
+ "properties": {
+ "device_ids": {"type": "array", "items": {"type": "string"}},
+ "design_id": {"type": "string", "description": "Canvas the nodes land on. Omit for the default (first) canvas."},
+ },
+ }),
+ Tool(name="bulk_hide_devices", description="Hide several pending devices at once, taking them out of the inventory listing.", inputSchema={
+ "type": "object",
+ "required": ["device_ids"],
+ "properties": {"device_ids": {"type": "array", "items": {"type": "string"}}},
+ }),
+ Tool(name="bulk_restore_devices", description="Un-hide several devices at once, returning them to pending.", inputSchema={
+ "type": "object",
+ "required": ["device_ids"],
+ "properties": {"device_ids": {"type": "array", "items": {"type": "string"}}},
+ }),
+ Tool(name="rescan_device", description="Deep-rescan one known device to refresh its services. Sweeps every TCP port by default, which is slow; recorded as a scan run like any other.", inputSchema={
+ "type": "object",
+ "required": ["id"],
+ "properties": {
+ "id": {"type": "string"},
+ "full_ports": {"type": "boolean", "default": True, "description": "Sweep all 65535 TCP ports."},
+ "ports": {"type": "string", "description": "Narrow the sweep, e.g. '80,443' or '1-1024'. Wins over full_ports."},
+ "http_probe_enabled": {"type": "boolean", "description": "Probe HTTP(S) services for banners and titles."},
+ "verify_tls": {"type": "boolean"},
+ },
+ }),
+ Tool(name="list_proxmox_children", description="Inventory entries for the VMs and containers a Proxmox host runs. Empty for anything that is not a host.", inputSchema={
+ "type": "object",
+ "required": ["id"],
+ "properties": {"id": {"type": "string", "description": "Inventory id of the Proxmox host."}},
+ }),
+ Tool(name="get_scan_config", description="The persisted scan defaults: the ranges swept, and the HTTP probe settings.", inputSchema={
+ "type": "object",
+ "properties": {},
+ }),
+ Tool(name="update_scan_config", description="Replace the persisted scan defaults. `ranges` is the full list, not an addition.", inputSchema={
+ "type": "object",
+ "required": ["ranges"],
+ "properties": {
+ "ranges": {"type": "array", "items": {"type": "string"}, "description": "CIDR ranges to sweep, e.g. ['192.168.1.0/24']."},
+ "http_ranges": {"type": "array", "items": {"type": "string"}, "description": "Port ranges probed for HTTP, e.g. ['80,443', '8000-8100']."},
+ "http_probe_enabled": {"type": "boolean"},
+ "verify_tls": {"type": "boolean"},
+ },
+ }),
+]
+
+DEVICE_TOOL_NAMES = {tool.name for tool in DEVICE_TOOLS}
+
+
+async def dispatch_device(name: str, args: dict) -> Any:
+ if name == "create_device":
+ return await backend.post("/api/v1/scan/pending", args)
+
+ if name == "update_device":
+ body = {k: v for k, v in args.items() if k != "id"}
+ return await backend.patch(f"/api/v1/scan/pending/{args['id']}", body)
+
+ if name == "delete_device":
+ return await backend.delete(f"/api/v1/scan/pending/{args['id']}")
+
+ if name == "bulk_approve_devices":
+ approval: dict[str, Any] = {"device_ids": args["device_ids"]}
+ if args.get("design_id"):
+ approval["design_id"] = args["design_id"]
+ return await backend.post("/api/v1/scan/pending/bulk-approve", approval)
+
+ if name == "bulk_hide_devices":
+ return await backend.post("/api/v1/scan/pending/bulk-hide", {"device_ids": args["device_ids"]})
+
+ if name == "bulk_restore_devices":
+ return await backend.post("/api/v1/scan/pending/bulk-restore", {"device_ids": args["device_ids"]})
+
+ if name == "rescan_device":
+ options = {k: v for k, v in args.items() if k != "id"}
+ return await backend.post(f"/api/v1/scan/pending/{args['id']}/rescan", options)
+
+ if name == "list_proxmox_children":
+ return await backend.get(f"/api/v1/scan/pending/{args['id']}/proxmox-children")
+
+ if name == "get_scan_config":
+ return await backend.get("/api/v1/scan/config")
+
+ if name == "update_scan_config":
+ return await backend.post("/api/v1/scan/config", args)
+
+ raise ValueError(f"Unknown device tool: {name}")
diff --git a/mcp/app/faceplates.py b/mcp/app/faceplates.py
new file mode 100644
index 0000000..178511a
--- /dev/null
+++ b/mcp/app/faceplates.py
@@ -0,0 +1,350 @@
+"""Faceplate catalog — a data-only port of frontend/src/rack/faceplates.ts.
+
+The rack renderer draws a plate from an SVG element list; MCP never draws, so
+only the parts a mount needs are copied here: the plate's footprint (`u_height`,
+`col_span`) and the ports it seeds. Kept in sync manually, enforced by
+mcp/tests/test_faceplates_sync.py.
+"""
+
+from math import ceil
+from typing import Any
+
+# 12-column horizontal grid, mirroring RACK_COLUMNS in frontend/src/types/rack.ts
+# and backend/app/schemas/racks.py.
+RACK_COLUMNS = 12
+
+# Desktop NAS boxes stand ~3U in metal but the canvas compresses the vertical
+# axis ~1.8x, so they are drawn 5U tall. See the NAS_U comment in faceplates.ts.
+NAS_U = 5
+# Bottom strip of a desktop NAS: the badge, the LED and the sockets sit on it.
+NAS_BAND = 0.86
+
+
+def bank(
+ type: str,
+ count: int,
+ x: float,
+ w: float,
+ per_row: int | None = None,
+ prefix: str = "P",
+ start: int = 1,
+) -> list[dict[str, Any]]:
+ """Evenly spread `count` ports across a horizontal band.
+
+ Same arithmetic as `bank()` in faceplates.ts:31 — rows are centred
+ vertically, so a plate seeded here lands its ports where the renderer draws
+ them and a cable endpoint is where the user sees the socket.
+ """
+ per_row = count if per_row is None else per_row
+ rows = max(1, ceil(count / per_row))
+ step_x = w / per_row
+
+ ports = []
+ for i in range(count):
+ row = i // per_row
+ col = i % per_row
+ ports.append({
+ "label": f"{prefix}{start + i}",
+ "type": type,
+ "x": x + step_x * (col + 0.5),
+ "y": (row + 1) / (rows + 1),
+ })
+ return ports
+
+
+def _nas_ports(ports: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Drop a bank onto the NAS bottom strip — `bank` centres rows on the plate."""
+ return [{**p, "y": NAS_BAND} for p in ports]
+
+
+# Order matters: it is the catalog order the frontend picker shows, and the sync
+# test compares the sequence.
+FACEPLATES: list[dict[str, Any]] = [
+ # --- Servers ------------------------------------------------------------
+ {
+ "id": "server-1u",
+ "label": "Server 1U",
+ "kind": "device",
+ "group": "Servers",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS,
+ "ports": bank(type="rj45", count=2, x=0.79, w=0.16, prefix="eth"),
+ },
+ {
+ "id": "server-1u-bays",
+ "label": "Server 1U — 4 bays",
+ "kind": "device",
+ "group": "Servers",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS,
+ "ports": bank(type="rj45", count=2, x=0.79, w=0.16, prefix="eth"),
+ },
+ {
+ "id": "server-2u-bays",
+ "label": "Server 2U — 8 bays",
+ "kind": "device",
+ "group": "Servers",
+ "u_height": 2,
+ "col_span": RACK_COLUMNS,
+ "ports": [
+ *bank(type="rj45", count=4, x=0.78, w=0.13, per_row=2, prefix="eth"),
+ *bank(type="sfp+", count=2, x=0.92, w=0.06, per_row=1, prefix="sfp"),
+ ],
+ },
+ {
+ "id": "server-4u-storage",
+ "label": "Storage 4U — 12 bays",
+ "kind": "device",
+ "group": "Servers",
+ "u_height": 4,
+ "col_span": RACK_COLUMNS,
+ "ports": bank(type="rj45", count=2, x=0.8, w=0.14, prefix="eth"),
+ },
+ {
+ "id": "sff-half",
+ "label": "SFF / mini PC (half width)",
+ "kind": "device",
+ "group": "Servers",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS // 2,
+ "ports": bank(type="rj45", count=1, x=0.82, w=0.12, prefix="eth"),
+ },
+ {
+ "id": "mini-third",
+ "label": "Mini node (third width)",
+ "kind": "device",
+ "group": "Servers",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS // 3,
+ "ports": bank(type="rj45", count=1, x=0.8, w=0.14, prefix="eth"),
+ },
+
+ # --- Network ------------------------------------------------------------
+ {
+ "id": "switch-8",
+ "label": "Switch 8 ports",
+ "kind": "device",
+ "group": "Network",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS,
+ "ports": [
+ *bank(type="rj45", count=8, x=0.33, w=0.4, prefix=""),
+ *bank(type="sfp", count=1, x=0.79, w=0.08, prefix="sfp"),
+ ],
+ },
+ {
+ "id": "switch-24",
+ "label": "Switch 24 ports + 2 SFP",
+ "kind": "device",
+ "group": "Network",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS,
+ "ports": [
+ *bank(type="rj45", count=24, x=0.23, w=0.53, per_row=12, prefix=""),
+ *bank(type="sfp+", count=2, x=0.8, w=0.12, prefix="sfp"),
+ ],
+ },
+ {
+ "id": "switch-48",
+ "label": "Switch 48 ports + 4 SFP+",
+ "kind": "device",
+ "group": "Network",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS,
+ "ports": [
+ *bank(type="rj45", count=48, x=0.22, w=0.54, per_row=24, prefix=""),
+ *bank(type="sfp+", count=4, x=0.79, w=0.14, per_row=2, prefix="sfp"),
+ ],
+ },
+ {
+ "id": "router-1u",
+ "label": "Router / firewall 1U",
+ "kind": "device",
+ "group": "Network",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS,
+ "ports": [
+ *bank(type="rj45", count=6, x=0.35, w=0.38, prefix="lan"),
+ *bank(type="sfp+", count=1, x=0.79, w=0.08, prefix="sfp"),
+ ],
+ },
+ {
+ "id": "patch-24",
+ "label": "Patch panel 24",
+ "kind": "device",
+ "group": "Network",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS,
+ "ports": bank(type="rj45", count=24, x=0.21, w=0.76, per_row=24, prefix=""),
+ },
+ {
+ "id": "patch-fiber-12",
+ "label": "Fiber panel 12 (LC)",
+ "kind": "device",
+ "group": "Network",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS,
+ "ports": bank(type="sfp", count=12, x=0.21, w=0.58, prefix="lc"),
+ },
+
+ # --- Storage / power ----------------------------------------------------
+ {
+ "id": "nas-2u",
+ "label": "NAS 2U — 8 bays",
+ "kind": "device",
+ "group": "Storage",
+ "u_height": 2,
+ "col_span": RACK_COLUMNS,
+ "ports": [
+ *bank(type="rj45", count=2, x=0.79, w=0.12, per_row=1, prefix="eth"),
+ *bank(type="sfp+", count=1, x=0.93, w=0.05, prefix="sfp"),
+ ],
+ },
+ {
+ "id": "nas-desktop-2",
+ "label": "Desktop NAS — 2 bays",
+ "kind": "device",
+ "group": "Storage",
+ "u_height": NAS_U,
+ # Two doors side by side is a slim tower — a sixth of the rack.
+ "col_span": RACK_COLUMNS // 6,
+ "ports": _nas_ports(bank(type="rj45", count=1, x=0.7, w=0.26, prefix="eth")),
+ },
+ {
+ "id": "nas-desktop-4",
+ "label": "Desktop NAS — 4 bays",
+ "kind": "device",
+ "group": "Storage",
+ "u_height": NAS_U,
+ "col_span": RACK_COLUMNS // 3,
+ "ports": _nas_ports(bank(type="rj45", count=2, x=0.6, w=0.34, prefix="eth")),
+ },
+ {
+ "id": "nas-desktop-5",
+ "label": "Desktop NAS — 5 bays",
+ "kind": "device",
+ "group": "Storage",
+ "u_height": NAS_U,
+ "col_span": RACK_COLUMNS // 3,
+ "ports": _nas_ports([
+ *bank(type="rj45", count=2, x=0.58, w=0.24, prefix="eth"),
+ *bank(type="sfp+", count=1, x=0.84, w=0.12, prefix="sfp"),
+ ]),
+ },
+ {
+ "id": "ups-2u",
+ "label": "UPS 2U",
+ "kind": "device",
+ "group": "Power",
+ "u_height": 2,
+ "col_span": RACK_COLUMNS,
+ # Outlets are artwork only — power cabling is out of v1.
+ "ports": [],
+ },
+ {
+ "id": "pdu-1u",
+ "label": "PDU 1U — 8 outlets",
+ "kind": "device",
+ "group": "Power",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS,
+ "ports": [],
+ },
+
+ # --- Accessories --------------------------------------------------------
+ {
+ "id": "blank-1u",
+ "label": "Blank panel 1U",
+ "kind": "accessory",
+ "group": "Accessories",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS,
+ "ports": [],
+ },
+ {
+ "id": "shelf-1u",
+ "label": "Shelf 1U",
+ "kind": "accessory",
+ "group": "Accessories",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS,
+ "ports": [],
+ },
+ {
+ "id": "cable-manager-1u",
+ "label": "Cable manager 1U",
+ "kind": "accessory",
+ "group": "Accessories",
+ "u_height": 1,
+ "col_span": RACK_COLUMNS,
+ "ports": [],
+ },
+]
+
+_BY_ID = {f["id"]: f for f in FACEPLATES}
+
+FACEPLATE_IDS = [f["id"] for f in FACEPLATES]
+
+
+def get_faceplate(faceplate_id: str) -> dict[str, Any] | None:
+ """The plate, or None. Unlike the frontend's `getFaceplate` this does not
+ fall back to the first template: a tool given an unknown id must say so
+ rather than silently mount the wrong hardware."""
+ return _BY_ID.get(faceplate_id)
+
+
+# Faceplate proposed when an inventory device is dropped into a rack, keyed on
+# the device's free-form `suggested_type` (faceplates.ts:476).
+FACEPLATE_BY_DEVICE_TYPE = {
+ "server": "server-1u-bays",
+ "proxmox": "server-2u-bays",
+ "nas": "nas-2u",
+ "switch": "switch-24",
+ "router": "router-1u",
+ "firewall": "router-1u",
+ "ap": "sff-half",
+ "computer": "sff-half",
+ "docker_host": "server-1u",
+ "ups": "ups-2u",
+ "pdu": "pdu-1u",
+ "patch_panel": "patch-24",
+ "printer": "shelf-1u",
+ "camera": "mini-third",
+ "iot": "mini-third",
+ "cpl": "mini-third",
+}
+
+
+def suggest_faceplate(device_type: str | None) -> str:
+ """Plate for a device type; a plain 1U server for anything unknown."""
+ return FACEPLATE_BY_DEVICE_TYPE.get(device_type or "", "server-1u")
+
+
+# The other direction: what kind of hardware a plate represents. A device
+# created from a rack has no discovery behind it, so the plate is the only thing
+# that says what it is (faceplates.ts:513).
+DEVICE_TYPE_BY_FACEPLATE = {
+ "server-1u": "server",
+ "server-1u-bays": "server",
+ "server-2u-bays": "server",
+ "server-4u-storage": "server",
+ "sff-half": "computer",
+ "mini-third": "computer",
+ "switch-8": "switch",
+ "switch-24": "switch",
+ "switch-48": "switch",
+ "router-1u": "router",
+ "patch-24": "patch_panel",
+ "patch-fiber-12": "patch_panel",
+ "nas-2u": "nas",
+ "nas-desktop-2": "nas",
+ "nas-desktop-4": "nas",
+ "nas-desktop-5": "nas",
+ "ups-2u": "ups",
+ "pdu-1u": "pdu",
+}
+
+
+def device_type_for_faceplate(faceplate_id: str) -> str | None:
+ """None for accessories, which are rack furniture and never inventory rows."""
+ return DEVICE_TYPE_BY_FACEPLATE.get(faceplate_id)
diff --git a/mcp/app/rack_layout.py b/mcp/app/rack_layout.py
new file mode 100644
index 0000000..4e22bfb
--- /dev/null
+++ b/mcp/app/rack_layout.py
@@ -0,0 +1,107 @@
+"""Rack grid geometry — a port of frontend/src/rack/layout.ts.
+
+Only the placement half: `is_in_bounds`, `can_place`, `find_slot`, `free_units`.
+The pixel maths (`uToY`, `portPosition`, …) is the renderer's business.
+
+The backend re-checks fit, the column grid and overlap when the state is saved
+(backend/app/schemas/racks.py), so this is here to *choose* a slot, not to police
+one — a payload that slips through still gets a 422.
+"""
+
+from typing import Any
+
+from .faceplates import RACK_COLUMNS
+
+# A placement is a dict with u_start, u_height, col_start, col_span — the same
+# snake_case shape the API speaks, so a mount row is its own placement.
+Placement = dict[str, Any]
+
+
+def _overlaps(a: Placement, b: Placement) -> bool:
+ u_overlap = (
+ a["u_start"] < b["u_start"] + b["u_height"]
+ and b["u_start"] < a["u_start"] + a["u_height"]
+ )
+ col_overlap = (
+ a["col_start"] < b["col_start"] + b["col_span"]
+ and b["col_start"] < a["col_start"] + a["col_span"]
+ )
+ return u_overlap and col_overlap
+
+
+def clamp(value: int, low: int, high: int) -> int:
+ return max(low, min(high, value))
+
+
+def is_in_bounds(rack: dict[str, Any], p: Placement) -> bool:
+ """True when the placement fits inside the rack bounds."""
+ return (
+ p["u_start"] >= 1
+ and p["u_height"] >= 1
+ and p["u_start"] + p["u_height"] - 1 <= rack["u_height"]
+ and p["col_start"] >= 0
+ and p["col_span"] >= 1
+ and p["col_start"] + p["col_span"] <= RACK_COLUMNS
+ )
+
+
+def can_place(
+ rack: dict[str, Any],
+ devices: list[dict[str, Any]],
+ p: Placement,
+ ignore_id: str | None = None,
+) -> bool:
+ """True when the placement fits and collides with nothing.
+
+ `ignore_id` skips the mount being moved, so a no-op move stays valid.
+ """
+ if not is_in_bounds(rack, p):
+ return False
+ return not any(
+ d["rack_id"] == rack["id"] and d.get("id") != ignore_id and _overlaps(p, d)
+ for d in devices
+ )
+
+
+def find_slot(
+ rack: dict[str, Any],
+ devices: list[dict[str, Any]],
+ desired: Placement,
+ ignore_id: str | None = None,
+) -> Placement | None:
+ """Nearest valid placement for `desired`, searching the target U first and
+ then walking outwards. None when the rack has no room at all."""
+ max_u = rack["u_height"] - desired["u_height"] + 1
+ if max_u < 1:
+ return None
+
+ col_start = clamp(desired["col_start"], 0, RACK_COLUMNS - desired["col_span"])
+ target_u = clamp(desired["u_start"], 1, max_u)
+
+ for offset in range(rack["u_height"]):
+ candidates_u = [target_u] if offset == 0 else [target_u - offset, target_u + offset]
+ for u in candidates_u:
+ if u < 1 or u > max_u:
+ continue
+ candidate = {**desired, "u_start": u, "col_start": col_start}
+ if can_place(rack, devices, candidate, ignore_id):
+ return candidate
+ # Same U may still have room on another column run.
+ for c in range(RACK_COLUMNS - desired["col_span"] + 1):
+ shifted = {**desired, "u_start": u, "col_start": c}
+ if can_place(rack, devices, shifted, ignore_id):
+ return shifted
+ return None
+
+
+def free_units(rack: dict[str, Any], devices: list[dict[str, Any]]) -> int:
+ """Free U count, counting a U as free only when every column is free."""
+ free = 0
+ for u in range(1, rack["u_height"] + 1):
+ busy = any(
+ d["rack_id"] == rack["id"] and u >= d["u_start"] and u < d["u_start"] + d["u_height"]
+ for d in devices
+ )
+ if not busy:
+ free += 1
+ return free
diff --git a/mcp/app/racks.py b/mcp/app/racks.py
new file mode 100644
index 0000000..22855e6
--- /dev/null
+++ b/mcp/app/racks.py
@@ -0,0 +1,737 @@
+"""Rack canvas tools.
+
+The rack canvas is a design whose `design_type` is `rack`: racks, the gear
+mounted in them, and port-to-port cables. Its persistence is one full-state
+endpoint — `POST /api/v1/racks/save` upserts what it is sent and prunes the rest
+— so every write here is load, mutate, save the whole thing back.
+
+Two consequences worth knowing:
+
+* The save is last-writer-wins with no versioning. A write made while the user
+ has the rack canvas open with unsaved changes loses one side's work. The
+ load/save window is a single dispatch, so it is small, not zero.
+* A mount's plate, colour and ports belong to the *inventory row*, not to the
+ mount: `/racks/save` writes them through to `device_inventory` itself
+ (backend/app/api/routes/racks.py:360), so nothing here has to patch the
+ inventory to make a faceplate change stick.
+"""
+
+import uuid
+from typing import Any, cast
+from urllib.parse import quote
+
+from mcp.types import Tool
+
+from .backend_client import backend
+from .faceplates import (
+ FACEPLATES,
+ RACK_COLUMNS,
+ get_faceplate,
+ suggest_faceplate,
+)
+from .rack_layout import can_place, find_slot, free_units
+
+# Capacity the UI allows. The backend accepts 1..100; the rack canvas stops at
+# 48, and a rack this side of that bound is one the user can still edit by hand.
+MIN_RACK_U = 1
+MAX_RACK_U = 48
+
+DEFAULT_RACK_STYLE = {
+ "frame": "#1c2129",
+ "rail": "#39424f",
+ "interior": "#0d1117",
+ "showNumbers": True,
+ "enclosed": False,
+}
+
+# Cable type implied by the port a patch starts from, and the sheath colour that
+# goes with it (frontend/src/rack/rackDefaults.ts).
+PORT_CABLE_TYPE = {"rj45": "ethernet", "sfp": "fiber", "sfp+": "fiber"}
+CABLE_COLORS = {"ethernet": "#39d353", "fiber": "#f0a500"}
+
+WIDTH_STANDARDS = ["19", "10"]
+NUMBERINGS = ["bottom-up", "top-down"]
+
+_DESIGN_ID = {
+ "design_id": {"type": "string", "description": "Rack design id. Use list_designs to find one (design_type 'rack')."},
+}
+
+
+# --- State round-trip -------------------------------------------------------
+# GET returns rows carrying `design_id`; the save schemas do not have that field
+# (it is top-level on the request), so echoing a row back verbatim is a 422.
+def _savable(row: dict[str, Any]) -> dict[str, Any]:
+ return {k: v for k, v in row.items() if k != "design_id"}
+
+
+async def _load_state(design_id: str) -> dict[str, Any]:
+ return cast(dict[str, Any], await backend.get(f"/api/v1/racks?design_id={quote(design_id)}"))
+
+
+async def _save_state(design_id: str, state: dict[str, Any]) -> dict[str, Any]:
+ return await backend.post("/api/v1/racks/save", {
+ "design_id": design_id,
+ "racks": [_savable(r) for r in state["racks"]],
+ "devices": [_savable(d) for d in state["devices"]],
+ "cables": [_savable(c) for c in state["cables"]],
+ # Pan/zoom shares the design's CanvasState row and is overwritten on
+ # every save: not echoing what the load returned resets the user's view.
+ "viewport": state.get("viewport") or {},
+ })
+
+
+def _rack_or_raise(state: dict[str, Any], rack_id: str) -> dict[str, Any]:
+ for rack in state["racks"]:
+ if rack["id"] == rack_id:
+ return rack
+ known = ", ".join(f"{r['id']} ({r['name']})" for r in state["racks"]) or "none"
+ raise ValueError(f"Unknown rack {rack_id}. Racks on this design: {known}")
+
+
+def _mount_or_raise(state: dict[str, Any], mount_id: str) -> dict[str, Any]:
+ for device in state["devices"]:
+ if device["id"] == mount_id:
+ return device
+ raise ValueError(f"Unknown mount {mount_id}. Call get_rack to list the mounts.")
+
+
+def _placement(row: dict[str, Any]) -> dict[str, Any]:
+ return {k: row[k] for k in ("u_start", "u_height", "col_start", "col_span")}
+
+
+# --- Slimming ---------------------------------------------------------------
+def _slim_rack(rack: dict[str, Any], devices: list[dict[str, Any]]) -> dict[str, Any]:
+ mounted = [d for d in devices if d["rack_id"] == rack["id"]]
+ return {
+ "id": rack["id"],
+ "name": rack["name"],
+ "u_height": rack["u_height"],
+ "width_standard": rack["width_standard"],
+ "numbering": rack["numbering"],
+ "location": rack.get("location"),
+ "mount_count": len(mounted),
+ "free_u": free_units(rack, devices),
+ }
+
+
+def _slim_mount(device: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "id": device["id"],
+ "label": device["label"],
+ "u_start": device["u_start"],
+ "u_height": device["u_height"],
+ "col_start": device["col_start"],
+ "col_span": device["col_span"],
+ "faceplate_id": device["faceplate_id"],
+ "status": device.get("status"),
+ "device_id": device.get("device_id"),
+ "node_id": device.get("node_id"),
+ "ports": [
+ {"id": p.get("id"), "label": p.get("label"), "type": p.get("type")}
+ for p in device.get("ports") or []
+ if isinstance(p, dict)
+ ],
+ }
+
+
+def _slim_cable(cable: dict[str, Any], by_mount: dict[str, dict[str, Any]]) -> dict[str, Any]:
+ def endpoint(mount_id: str, port_id: str) -> dict[str, Any]:
+ mount = by_mount.get(mount_id) or {}
+ port = next(
+ (p for p in mount.get("ports") or [] if isinstance(p, dict) and p.get("id") == port_id),
+ {},
+ )
+ return {
+ "mount_id": mount_id,
+ "device": mount.get("label"),
+ "port_id": port_id,
+ "port": port.get("label"),
+ }
+
+ return {
+ "id": cable["id"],
+ "type": cable["type"],
+ "color": cable.get("color"),
+ "label": cable.get("label"),
+ "from": endpoint(cable["from_device_id"], cable["from_port_id"]),
+ "to": endpoint(cable["to_device_id"], cable["to_port_id"]),
+ }
+
+
+def _slim_inventory_item(item: dict[str, Any]) -> dict[str, Any]:
+ out = {
+ "id": item["id"],
+ "label": item["label"],
+ "suggested_type": item.get("suggested_type"),
+ "ip": item.get("ip"),
+ "status": item.get("status"),
+ "discovery_source": item.get("discovery_source"),
+ "racked": item.get("racked", False),
+ # Already wearing a front panel: mount_device reuses it as-is.
+ "modelled": bool(item.get("rack_faceplate_id")),
+ }
+ if item.get("rack_faceplate_id"):
+ out["faceplate_id"] = item["rack_faceplate_id"]
+ if item.get("node_id"):
+ out["node_id"] = item["node_id"]
+ return out
+
+
+# --- Ports ------------------------------------------------------------------
+def _seed_ports(plate: dict[str, Any]) -> list[dict[str, Any]]:
+ """Template ports with fresh ids — the ids are the device's, and a cable is
+ the only thing that ever refers to one."""
+ return [{**port, "id": str(uuid.uuid4())} for port in plate["ports"]]
+
+
+def _resolve_port(mount: dict[str, Any], ref: str) -> dict[str, Any]:
+ """A port named by id, or case-insensitively by label (`eth1`, `P12`)."""
+ ports = [p for p in mount.get("ports") or [] if isinstance(p, dict)]
+ for port in ports:
+ if port.get("id") == ref:
+ return port
+ matches = [p for p in ports if str(p.get("label", "")).lower() == ref.lower()]
+ if len(matches) == 1:
+ return matches[0]
+ labels = ", ".join(str(p.get("label")) for p in ports) or "none"
+ if len(matches) > 1:
+ raise ValueError(f"Port '{ref}' is ambiguous on {mount['label']}. Use the port id.")
+ raise ValueError(f"Unknown port '{ref}' on {mount['label']}. Ports: {labels}")
+
+
+def _cable_on_port(state: dict[str, Any], mount_id: str, port_id: str) -> dict[str, Any] | None:
+ for cable in state["cables"]:
+ if (cable["from_device_id"] == mount_id and cable["from_port_id"] == port_id) or (
+ cable["to_device_id"] == mount_id and cable["to_port_id"] == port_id
+ ):
+ return cable
+ return None
+
+
+# --- Tools ------------------------------------------------------------------
+_GEOMETRY_FIELDS = {
+ "u_start": {"type": "integer", "description": "1-based U, counted from the bottom rail. Omit to take the first free slot."},
+ "col_start": {"type": "integer", "description": f"Left column, 0..{RACK_COLUMNS - 1}. Default 0."},
+ "col_span": {"type": "integer", "description": f"Width in columns of the {RACK_COLUMNS}-column grid (full 12, half 6, third 4, quarter 3). Default: the faceplate's."},
+ "u_height": {"type": "integer", "description": "Height in U. Default: the faceplate's."},
+}
+
+RACK_TOOLS = [
+ Tool(name="list_racks", description="List the racks on a rack design with their capacity, mount count and free U.", inputSchema={
+ "type": "object",
+ "required": ["design_id"],
+ "properties": {**_DESIGN_ID},
+ }),
+ Tool(name="get_rack", description="Full contents of a rack design: every rack, the gear mounted in it with its ports, and the cables patched between them.", inputSchema={
+ "type": "object",
+ "required": ["design_id"],
+ "properties": {
+ **_DESIGN_ID,
+ "rack_id": {"type": "string", "description": "Narrow to one rack. Omit for every rack on the design."},
+ },
+ }),
+ Tool(name="list_rack_inventory", description="Device Inventory entries that can be racked on this design, each flagged with whether it is already mounted and whether it already has a faceplate.", inputSchema={
+ "type": "object",
+ "required": ["design_id"],
+ "properties": {**_DESIGN_ID},
+ }),
+ Tool(name="list_faceplates", description="The faceplate catalog: plate id, what it represents, its height in U and its width in columns. Pick an id from here rather than guessing one.", inputSchema={
+ "type": "object",
+ "properties": {},
+ }),
+ Tool(name="create_rack", description="Add an empty rack to a rack design.", inputSchema={
+ "type": "object",
+ "required": ["design_id", "name"],
+ "properties": {
+ **_DESIGN_ID,
+ "name": {"type": "string"},
+ "u_height": {"type": "integer", "description": f"Capacity in U, {MIN_RACK_U}..{MAX_RACK_U}. Default 24."},
+ "width_standard": {"type": "string", "enum": WIDTH_STANDARDS, "description": "Rack width in inches. Default 19."},
+ "numbering": {"type": "string", "enum": NUMBERINGS, "description": "Which way the printed U labels run. Default bottom-up."},
+ "location": {"type": "string", "description": "Where the rack physically is (room, site)."},
+ "pos_x": {"type": "number", "description": "Canvas position. Default: to the right of the last rack."},
+ "pos_y": {"type": "number"},
+ },
+ }),
+ Tool(name="update_rack", description="Rename, resize, relocate or move a rack. A shrink relocates the mounts it would push above the top rail, and is refused when one has nowhere to go.", inputSchema={
+ "type": "object",
+ "required": ["design_id", "rack_id"],
+ "properties": {
+ **_DESIGN_ID,
+ "rack_id": {"type": "string"},
+ "name": {"type": "string"},
+ "u_height": {"type": "integer", "description": f"New capacity in U, clamped to {MIN_RACK_U}..{MAX_RACK_U}."},
+ "width_standard": {"type": "string", "enum": WIDTH_STANDARDS},
+ "numbering": {"type": "string", "enum": NUMBERINGS},
+ "location": {"type": "string"},
+ "pos_x": {"type": "number"},
+ "pos_y": {"type": "number"},
+ },
+ }),
+ Tool(name="delete_rack", description="Delete a rack, the gear mounted in it and the cables patched to that gear. The Device Inventory is untouched.", inputSchema={
+ "type": "object",
+ "required": ["design_id", "rack_id"],
+ "properties": {**_DESIGN_ID, "rack_id": {"type": "string"}},
+ }),
+ Tool(name="mount_device", description="Mount a Device Inventory entry in a rack. The faceplate defaults to the one the device already wears, else the one its type suggests; the slot defaults to the lowest that fits.", inputSchema={
+ "type": "object",
+ "required": ["design_id", "rack_id", "inventory_device_id"],
+ "properties": {
+ **_DESIGN_ID,
+ "rack_id": {"type": "string"},
+ "inventory_device_id": {"type": "string", "description": "Inventory entry to mount. Call list_rack_inventory for ids."},
+ "faceplate_id": {"type": "string", "description": "Override the faceplate. Call list_faceplates for ids."},
+ "label": {"type": "string", "description": "Override the plate's printed name. Defaults to the inventory label."},
+ **_GEOMETRY_FIELDS,
+ },
+ }),
+ Tool(name="mount_accessory", description="Mount rack furniture that has no inventory entry behind it: a blank panel, a shelf, a cable manager.", inputSchema={
+ "type": "object",
+ "required": ["design_id", "rack_id", "faceplate_id"],
+ "properties": {
+ **_DESIGN_ID,
+ "rack_id": {"type": "string"},
+ "faceplate_id": {"type": "string", "description": "Call list_faceplates; the 'Accessories' group is what belongs here."},
+ "label": {"type": "string", "description": "Printed name. Defaults to the faceplate's."},
+ **_GEOMETRY_FIELDS,
+ },
+ }),
+ Tool(name="unmount_device", description="Take gear out of a rack, along with the cables patched to it. The Device Inventory entry survives.", inputSchema={
+ "type": "object",
+ "required": ["design_id", "mount_id"],
+ "properties": {**_DESIGN_ID, "mount_id": {"type": "string", "description": "Mount id from get_rack — not the inventory device id."}},
+ }),
+ Tool(name="move_device", description="Move a mount to another slot, or to another rack on the same design. Refused when the target is occupied or out of bounds.", inputSchema={
+ "type": "object",
+ "required": ["design_id", "mount_id"],
+ "properties": {
+ **_DESIGN_ID,
+ "mount_id": {"type": "string"},
+ "rack_id": {"type": "string", "description": "Move to this rack. Omit to stay in the current one."},
+ "u_start": {"type": "integer", "description": "1-based U, counted from the bottom rail."},
+ "col_start": {"type": "integer", "description": f"Left column, 0..{RACK_COLUMNS - 1}."},
+ },
+ }),
+ Tool(name="set_device_faceplate", description="Give a mount a different faceplate. Reseeds its ports (dropping the cables patched to the old ones) and relocates the mount when the new plate no longer fits where it sits.", inputSchema={
+ "type": "object",
+ "required": ["design_id", "mount_id", "faceplate_id"],
+ "properties": {
+ **_DESIGN_ID,
+ "mount_id": {"type": "string"},
+ "faceplate_id": {"type": "string"},
+ },
+ }),
+ Tool(name="patch_cable", description="Patch a cable between two ports. Ports are named by label (eth1, P12) or by id. One cable per port; the cable type follows the port it starts from.", inputSchema={
+ "type": "object",
+ "required": ["design_id", "from_mount_id", "from_port", "to_mount_id", "to_port"],
+ "properties": {
+ **_DESIGN_ID,
+ "from_mount_id": {"type": "string"},
+ "from_port": {"type": "string", "description": "Port label or id on the source mount."},
+ "to_mount_id": {"type": "string"},
+ "to_port": {"type": "string", "description": "Port label or id on the target mount."},
+ "color": {"type": "string", "description": "Sheath colour, e.g. '#39d353'. Defaults to the type's."},
+ "label": {"type": "string", "description": "Cable label, e.g. a patch reference."},
+ "label_visible": {"type": "boolean", "description": "Print the label on the run. Default false."},
+ },
+ }),
+ Tool(name="unpatch_cable", description="Remove a patched cable.", inputSchema={
+ "type": "object",
+ "required": ["design_id", "cable_id"],
+ "properties": {**_DESIGN_ID, "cable_id": {"type": "string"}},
+ }),
+]
+
+RACK_TOOL_NAMES = {tool.name for tool in RACK_TOOLS}
+
+
+async def dispatch_rack(name: str, args: dict) -> Any:
+ design_id: str = args.get("design_id") or ""
+
+ # --- Reads --------------------------------------------------------------
+ if name == "list_faceplates":
+ return [
+ {
+ "id": plate["id"],
+ "label": plate["label"],
+ "group": plate["group"],
+ "kind": plate["kind"],
+ "u_height": plate["u_height"],
+ "col_span": plate["col_span"],
+ "port_count": len(plate["ports"]),
+ }
+ for plate in FACEPLATES
+ ]
+
+ if name == "list_racks":
+ state = await _load_state(design_id)
+ return [_slim_rack(r, state["devices"]) for r in state["racks"]]
+
+ if name == "get_rack":
+ state = await _load_state(design_id)
+ rack_id = args.get("rack_id")
+ racks = [r for r in state["racks"] if rack_id is None or r["id"] == rack_id]
+ if rack_id is not None and not racks:
+ _rack_or_raise(state, rack_id)
+ wanted = {r["id"] for r in racks}
+ mounts = [d for d in state["devices"] if d["rack_id"] in wanted]
+ by_mount = {d["id"]: d for d in state["devices"]}
+ mount_ids = {d["id"] for d in mounts}
+ return {
+ "racks": [
+ {
+ **_slim_rack(rack, state["devices"]),
+ "devices": [_slim_mount(d) for d in mounts if d["rack_id"] == rack["id"]],
+ }
+ for rack in racks
+ ],
+ "cables": [
+ _slim_cable(c, by_mount)
+ for c in state["cables"]
+ if c["from_device_id"] in mount_ids or c["to_device_id"] in mount_ids
+ ],
+ }
+
+ if name == "list_rack_inventory":
+ data = cast(dict[str, Any], await backend.get(f"/api/v1/racks/inventory?design_id={quote(design_id)}"))
+ return [_slim_inventory_item(item) for item in data.get("items", [])]
+
+ # --- Writes -------------------------------------------------------------
+ if name == "create_rack":
+ state = await _load_state(design_id)
+ u_height = _clamp_u(args.get("u_height", 24))
+ # Lay a new rack out to the right of the last one, as the canvas does.
+ count = len(state["racks"])
+ rack = {
+ "id": str(uuid.uuid4()),
+ "name": args["name"],
+ "u_height": u_height,
+ "width_standard": args.get("width_standard", "19"),
+ "numbering": args.get("numbering", "bottom-up"),
+ "location": args.get("location"),
+ "style": dict(DEFAULT_RACK_STYLE),
+ "pos_x": args.get("pos_x", 80 + count * 620),
+ "pos_y": args.get("pos_y", 60),
+ }
+ state["racks"].append(rack)
+ await _save_state(design_id, state)
+ return {"rack_id": rack["id"], "name": rack["name"], "u_height": u_height}
+
+ if name == "update_rack":
+ state = await _load_state(design_id)
+ rack = _rack_or_raise(state, args["rack_id"])
+ previous_height = rack["u_height"]
+
+ for field in ("name", "width_standard", "numbering", "location", "pos_x", "pos_y"):
+ if field in args:
+ rack[field] = args[field]
+ if "u_height" in args:
+ rack["u_height"] = _clamp_u(args["u_height"])
+
+ if rack["u_height"] < previous_height:
+ _relocate_after_shrink(state, rack)
+
+ await _save_state(design_id, state)
+ return {"rack_id": rack["id"], "name": rack["name"], "u_height": rack["u_height"]}
+
+ if name == "delete_rack":
+ state = await _load_state(design_id)
+ rack = _rack_or_raise(state, args["rack_id"])
+ dropped = {d["id"] for d in state["devices"] if d["rack_id"] == rack["id"]}
+ state["racks"] = [r for r in state["racks"] if r["id"] != rack["id"]]
+ state["devices"] = [d for d in state["devices"] if d["id"] not in dropped]
+ cables_before = len(state["cables"])
+ state["cables"] = [
+ c
+ for c in state["cables"]
+ if c["from_device_id"] not in dropped and c["to_device_id"] not in dropped
+ ]
+ await _save_state(design_id, state)
+ return {
+ "deleted": rack["id"],
+ "unmounted": len(dropped),
+ "cables_removed": cables_before - len(state["cables"]),
+ }
+
+ if name == "mount_device":
+ return await _mount_device(design_id, args)
+
+ if name == "mount_accessory":
+ state = await _load_state(design_id)
+ rack = _rack_or_raise(state, args["rack_id"])
+ plate = _plate_or_raise(args["faceplate_id"])
+ slot = _slot_or_raise(rack, state["devices"], args, plate)
+ mount = {
+ "id": str(uuid.uuid4()),
+ "rack_id": rack["id"],
+ "device_id": None,
+ "node_id": None,
+ "label": args.get("label") or plate["label"],
+ "faceplate_id": plate["id"],
+ "color": None,
+ "status": "unknown",
+ "port_visibility": "auto",
+ "ports": _seed_ports(plate),
+ **slot,
+ }
+ state["devices"].append(mount)
+ await _save_state(design_id, state)
+ return {"mount_id": mount["id"], "rack_id": rack["id"], "faceplate_id": plate["id"], **slot}
+
+ if name == "unmount_device":
+ state = await _load_state(design_id)
+ mount = _mount_or_raise(state, args["mount_id"])
+ state["devices"] = [d for d in state["devices"] if d["id"] != mount["id"]]
+ cables_before = len(state["cables"])
+ state["cables"] = [
+ c
+ for c in state["cables"]
+ if c["from_device_id"] != mount["id"] and c["to_device_id"] != mount["id"]
+ ]
+ await _save_state(design_id, state)
+ return {
+ "unmounted": mount["id"],
+ "label": mount["label"],
+ "cables_removed": cables_before - len(state["cables"]),
+ "inventory_device_id": mount.get("device_id"),
+ }
+
+ if name == "move_device":
+ state = await _load_state(design_id)
+ mount = _mount_or_raise(state, args["mount_id"])
+ rack = _rack_or_raise(state, args.get("rack_id") or mount["rack_id"])
+ target = {
+ **_placement(mount),
+ **({"u_start": args["u_start"]} if "u_start" in args else {}),
+ **({"col_start": args["col_start"]} if "col_start" in args else {}),
+ }
+ if not can_place(rack, state["devices"], {**target, "rack_id": rack["id"]}, mount["id"]):
+ raise ValueError(
+ f"{mount['label']} does not fit at U {target['u_start']}, column "
+ f"{target['col_start']} in {rack['name']}: out of bounds or occupied. "
+ "Call get_rack to see what is there."
+ )
+ mount["rack_id"] = rack["id"]
+ mount.update(target)
+ await _save_state(design_id, state)
+ return {"mount_id": mount["id"], "rack_id": rack["id"], **target}
+
+ if name == "set_device_faceplate":
+ state = await _load_state(design_id)
+ mount = _mount_or_raise(state, args["mount_id"])
+ rack = _rack_or_raise(state, mount["rack_id"])
+ plate = _plate_or_raise(args["faceplate_id"])
+
+ desired = {
+ "u_start": mount["u_start"],
+ "u_height": plate["u_height"],
+ "col_start": mount["col_start"],
+ "col_span": plate["col_span"],
+ }
+ placed = find_slot(rack, state["devices"], desired, mount["id"])
+ if placed is None:
+ raise ValueError(
+ f"{rack['name']} has no free slot for a {plate['u_height']}U x "
+ f"{plate['col_span']}-column plate. Free some room or pick a smaller faceplate."
+ )
+ mount["faceplate_id"] = plate["id"]
+ mount["ports"] = _seed_ports(plate)
+ mount.update(placed)
+
+ # Cables point at port ids that no longer exist on this mount.
+ cables_before = len(state["cables"])
+ state["cables"] = [
+ c
+ for c in state["cables"]
+ if c["from_device_id"] != mount["id"] and c["to_device_id"] != mount["id"]
+ ]
+ await _save_state(design_id, state)
+ return {
+ "mount_id": mount["id"],
+ "faceplate_id": plate["id"],
+ "cables_removed": cables_before - len(state["cables"]),
+ **placed,
+ }
+
+ if name == "patch_cable":
+ state = await _load_state(design_id)
+ source = _mount_or_raise(state, args["from_mount_id"])
+ target = _mount_or_raise(state, args["to_mount_id"])
+ from_port = _resolve_port(source, args["from_port"])
+ to_port = _resolve_port(target, args["to_port"])
+ if source["id"] == target["id"] and from_port["id"] == to_port["id"]:
+ raise ValueError("A cable cannot patch a port to itself.")
+
+ for mount, port in ((source, from_port), (target, to_port)):
+ existing = _cable_on_port(state, mount["id"], port["id"])
+ if existing is not None:
+ raise ValueError(
+ f"{mount['label']} port {port['label']} is already patched "
+ f"(cable {existing['id']}). Unpatch it first."
+ )
+
+ cable_type = PORT_CABLE_TYPE.get(str(from_port.get("type")), "ethernet")
+ cable = {
+ "id": str(uuid.uuid4()),
+ "from_device_id": source["id"],
+ "from_port_id": from_port["id"],
+ "to_device_id": target["id"],
+ "to_port_id": to_port["id"],
+ "type": cable_type,
+ "color": args.get("color") or CABLE_COLORS[cable_type],
+ "label": args.get("label"),
+ "label_visible": args.get("label_visible", False),
+ "properties": [],
+ }
+ state["cables"].append(cable)
+ await _save_state(design_id, state)
+ return {
+ "cable_id": cable["id"],
+ "type": cable_type,
+ "from": f"{source['label']} {from_port['label']}",
+ "to": f"{target['label']} {to_port['label']}",
+ }
+
+ if name == "unpatch_cable":
+ state = await _load_state(design_id)
+ cable_id = args["cable_id"]
+ if not any(c["id"] == cable_id for c in state["cables"]):
+ raise ValueError(f"Unknown cable {cable_id}. Call get_rack to list the cables.")
+ state["cables"] = [c for c in state["cables"] if c["id"] != cable_id]
+ await _save_state(design_id, state)
+ return {"unpatched": cable_id}
+
+ raise ValueError(f"Unknown rack tool: {name}")
+
+
+def _clamp_u(value: Any) -> int:
+ """The rack canvas' own capacity bounds. The backend takes up to 100 U, but a
+ rack outside 1..48 is one the UI's own controls cannot edit back."""
+ return max(MIN_RACK_U, min(MAX_RACK_U, int(value)))
+
+
+def _plate_or_raise(faceplate_id: str) -> dict[str, Any]:
+ plate = get_faceplate(faceplate_id)
+ if plate is None:
+ raise ValueError(f"Unknown faceplate '{faceplate_id}'. Call list_faceplates for the catalog.")
+ return plate
+
+
+def _slot_or_raise(
+ rack: dict[str, Any],
+ devices: list[dict[str, Any]],
+ args: dict[str, Any],
+ plate: dict[str, Any],
+ u_height: int | None = None,
+ col_span: int | None = None,
+) -> dict[str, Any]:
+ desired = {
+ "u_start": args.get("u_start", 1),
+ "u_height": args.get("u_height") or u_height or plate["u_height"],
+ "col_start": args.get("col_start", 0),
+ "col_span": args.get("col_span") or col_span or plate["col_span"],
+ }
+ slot = find_slot(rack, devices, desired)
+ if slot is None:
+ raise ValueError(
+ f"{rack['name']} has no free slot for a {desired['u_height']}U x "
+ f"{desired['col_span']}-column plate ({free_units(rack, devices)}U free)."
+ )
+ return slot
+
+
+def _relocate_after_shrink(state: dict[str, Any], rack: dict[str, Any]) -> None:
+ """Move the mounts a shrink pushed above the top rail down into the rack.
+
+ Placed one at a time against the layout decided so far, so two relocated
+ mounts cannot be handed the same slot. Refuses the whole edit when one has
+ nowhere to go, rather than dropping a mount off the rack — the rule the
+ canvas applies (frontend/src/rack/store.ts:492).
+ """
+ mounted = [d for d in state["devices"] if d["rack_id"] == rack["id"]]
+ pushed_out = [d for d in mounted if d["u_start"] + d["u_height"] - 1 > rack["u_height"]]
+ if not pushed_out:
+ return
+
+ pushed_ids = {d["id"] for d in pushed_out}
+ settled = [d for d in mounted if d["id"] not in pushed_ids]
+ for device in pushed_out:
+ slot = find_slot(
+ rack, settled, {**_placement(device), "u_start": rack["u_height"]}, device["id"]
+ )
+ if slot is None:
+ raise ValueError(
+ f"Cannot shrink {rack['name']} to {rack['u_height']}U: {device['label']} "
+ "would sit above the top rail and there is no free slot left for it."
+ )
+ device.update(slot)
+ settled.append(device)
+
+
+async def _mount_device(design_id: str, args: dict[str, Any]) -> dict[str, Any]:
+ state = await _load_state(design_id)
+ rack = _rack_or_raise(state, args["rack_id"])
+
+ inventory = cast(
+ dict[str, Any], await backend.get(f"/api/v1/racks/inventory?design_id={quote(design_id)}")
+ )
+ item = next(
+ (i for i in inventory.get("items", []) if i["id"] == args["inventory_device_id"]), None
+ )
+ if item is None:
+ raise ValueError(
+ f"Unknown inventory device {args['inventory_device_id']}, or its type cannot be "
+ "racked. Call list_rack_inventory for what is available."
+ )
+ if item.get("racked"):
+ raise ValueError(
+ f"{item['label']} is already mounted on this design. Use move_device to "
+ "relocate it, or unmount_device first."
+ )
+
+ # The inventory row owns the front panel: a device racked before keeps the
+ # plate it wears, and only a never-racked one falls back to its type's.
+ plate_id = args.get("faceplate_id") or item.get("rack_faceplate_id") or suggest_faceplate(
+ item.get("suggested_type")
+ )
+ plate = _plate_or_raise(plate_id)
+ # The stored size and ports only apply to the plate they were measured on.
+ modelled = item.get("rack_faceplate_id") == plate["id"]
+
+ slot = _slot_or_raise(
+ rack,
+ state["devices"],
+ args,
+ plate,
+ u_height=item.get("rack_u_height") if modelled else None,
+ col_span=item.get("rack_col_span") if modelled else None,
+ )
+ ports = (
+ [dict(p) for p in item.get("rack_ports") or []]
+ if modelled
+ else _seed_ports(plate)
+ )
+
+ mount = {
+ "id": str(uuid.uuid4()),
+ "rack_id": rack["id"],
+ "device_id": item["id"],
+ "node_id": item.get("node_id"),
+ "label": args.get("label") or item["label"],
+ "faceplate_id": plate["id"],
+ "color": item.get("rack_color") if modelled else None,
+ "status": item.get("status", "unknown"),
+ "port_visibility": "auto",
+ "ports": ports,
+ **slot,
+ }
+ state["devices"].append(mount)
+ await _save_state(design_id, state)
+ return {
+ "mount_id": mount["id"],
+ "rack_id": rack["id"],
+ "label": mount["label"],
+ "faceplate_id": plate["id"],
+ "ports": len(ports),
+ **slot,
+ }
diff --git a/mcp/app/tools.py b/mcp/app/tools.py
index 272067d..e376df5 100644
--- a/mcp/app/tools.py
+++ b/mcp/app/tools.py
@@ -3,6 +3,8 @@ from urllib.parse import quote
from mcp.server import Server
from mcp.types import Tool, TextContent
from .backend_client import backend
+from .devices import DEVICE_TOOL_NAMES, DEVICE_TOOLS, dispatch_device
+from .racks import RACK_TOOL_NAMES, RACK_TOOLS, dispatch_rack
# Kept in sync manually with frontend/src/types/index.ts NodeType (device types only —
@@ -137,7 +139,7 @@ def _build_tools() -> list[Tool]:
"ranges": {"type": "array", "items": {"type": "string"}, "description": "CIDR ranges to scan (uses configured defaults if omitted)"},
},
}),
- Tool(name="approve_device", description="Approve a pending discovered device and create a node", inputSchema={
+ Tool(name="approve_device", description="Approve a pending discovered device and create a node. A device created from a rack canvas (discovery_source 'rack') is refused with a 409 — passive rack gear never goes on a logical canvas.", inputSchema={
"type": "object",
"required": ["id"],
"properties": {
@@ -177,7 +179,7 @@ def _build_tools() -> list[Tool]:
"type": "object",
"properties": {},
}),
- Tool(name="list_inventory", description="List the full device inventory (everything scanned except user-hidden devices): both pending devices awaiting triage and already-approved devices. Each row carries a 'status' field. Use the optional 'status' filter to narrow the result.", inputSchema={
+ Tool(name="list_inventory", description="List the full device inventory (everything scanned except user-hidden devices): both pending devices awaiting triage and already-approved devices. Each row carries a 'status' field. Use the optional 'status' filter to narrow the result. Gear created from a rack canvas is listed here too, tagged discovery_source 'rack'.", inputSchema={
"type": "object",
"properties": {
"status": {"type": "string", "enum": ["all", "pending", "approved"], "default": "all", "description": "Filter inventory by status. 'all' returns pending + approved."},
@@ -249,7 +251,9 @@ def _build_tools() -> list[Tool]:
]
-TOOLS = _build_tools()
+# The rack canvas and the inventory write routes live in their own modules —
+# both are big enough to bury the logical-canvas tools this file is about.
+TOOLS = _build_tools() + RACK_TOOLS + DEVICE_TOOLS
def register_tools(server: Server):
@@ -336,6 +340,12 @@ def _is_ancestor(nodes_by_id: dict[str, dict], maybe_ancestor_id: str, node_id:
async def _dispatch(name: str, args: dict) -> dict:
+ if name in RACK_TOOL_NAMES:
+ return await dispatch_rack(name, args)
+
+ if name in DEVICE_TOOL_NAMES:
+ return await dispatch_device(name, args)
+
if name == "create_node":
return await backend.post("/api/v1/nodes", args)
diff --git a/mcp/tests/test_devices.py b/mcp/tests/test_devices.py
new file mode 100644
index 0000000..35d6651
--- /dev/null
+++ b/mcp/tests/test_devices.py
@@ -0,0 +1,138 @@
+import pytest
+from unittest.mock import AsyncMock, patch
+
+from app.devices import DEVICE_TOOLS, dispatch_device
+
+
+def mock_backend():
+ with patch("app.devices.backend") as m:
+ m.post = AsyncMock(return_value={"id": "d1"})
+ m.patch = AsyncMock(return_value={"id": "d1"})
+ m.delete = AsyncMock(return_value={"deleted": True})
+ m.get = AsyncMock(return_value=[])
+ yield m
+
+
+async def test_create_device(mock_backend):
+ args = {"hostname": "sw-core", "suggested_type": "switch", "ip": "192.168.1.2"}
+ result = await dispatch_device("create_device", dict(args))
+ mock_backend.post.assert_called_once_with("/api/v1/scan/pending", args)
+ assert result == {"id": "d1"}
+
+
+async def test_create_device_from_a_rack(mock_backend):
+ await dispatch_device(
+ "create_device", {"hostname": "patch-a", "discovery_source": "rack"}
+ )
+ _, body = mock_backend.post.call_args[0]
+ assert body["discovery_source"] == "rack"
+
+
+async def test_update_device_sends_everything_but_the_id(mock_backend):
+ await dispatch_device("update_device", {"id": "d1", "notes": "in the garage", "ram_gb": 64})
+ mock_backend.patch.assert_called_once_with(
+ "/api/v1/scan/pending/d1", {"notes": "in the garage", "ram_gb": 64}
+ )
+
+
+async def test_update_device_carries_the_rack_model(mock_backend):
+ """The faceplate belongs to the inventory row, so it is edited here too."""
+ await dispatch_device("update_device", {
+ "id": "d1", "rack_faceplate_id": "switch-48", "rack_u_height": 1, "rack_col_span": 12,
+ })
+ _, body = mock_backend.patch.call_args[0]
+ assert body["rack_faceplate_id"] == "switch-48"
+
+
+async def test_delete_device(mock_backend):
+ await dispatch_device("delete_device", {"id": "d1"})
+ mock_backend.delete.assert_called_once_with("/api/v1/scan/pending/d1")
+
+
+async def test_bulk_approve_devices(mock_backend):
+ await dispatch_device(
+ "bulk_approve_devices", {"device_ids": ["a", "b"], "design_id": "canvas-1"}
+ )
+ mock_backend.post.assert_called_once_with(
+ "/api/v1/scan/pending/bulk-approve", {"device_ids": ["a", "b"], "design_id": "canvas-1"}
+ )
+
+
+async def test_bulk_approve_devices_without_a_design(mock_backend):
+ """No design_id means the backend's default (first) canvas — sending a null
+ would not be the same thing."""
+ await dispatch_device("bulk_approve_devices", {"device_ids": ["a"]})
+ _, body = mock_backend.post.call_args[0]
+ assert body == {"device_ids": ["a"]}
+
+
+async def test_bulk_hide_devices(mock_backend):
+ await dispatch_device("bulk_hide_devices", {"device_ids": ["a", "b"]})
+ mock_backend.post.assert_called_once_with(
+ "/api/v1/scan/pending/bulk-hide", {"device_ids": ["a", "b"]}
+ )
+
+
+async def test_bulk_restore_devices(mock_backend):
+ await dispatch_device("bulk_restore_devices", {"device_ids": ["a"]})
+ mock_backend.post.assert_called_once_with(
+ "/api/v1/scan/pending/bulk-restore", {"device_ids": ["a"]}
+ )
+
+
+async def test_rescan_device(mock_backend):
+ await dispatch_device("rescan_device", {"id": "d1", "ports": "80,443", "verify_tls": True})
+ mock_backend.post.assert_called_once_with(
+ "/api/v1/scan/pending/d1/rescan", {"ports": "80,443", "verify_tls": True}
+ )
+
+
+async def test_list_proxmox_children(mock_backend):
+ await dispatch_device("list_proxmox_children", {"id": "pve1"})
+ mock_backend.get.assert_called_once_with("/api/v1/scan/pending/pve1/proxmox-children")
+
+
+async def test_get_scan_config(mock_backend):
+ await dispatch_device("get_scan_config", {})
+ mock_backend.get.assert_called_once_with("/api/v1/scan/config")
+
+
+async def test_update_scan_config(mock_backend):
+ args = {"ranges": ["192.168.1.0/24"], "http_probe_enabled": True}
+ await dispatch_device("update_scan_config", dict(args))
+ mock_backend.post.assert_called_once_with("/api/v1/scan/config", args)
+
+
+async def test_unknown_device_tool(mock_backend):
+ with pytest.raises(ValueError, match="Unknown device tool"):
+ await dispatch_device("frobnicate_device", {})
+
+
+def test_create_device_only_offers_the_manual_sources():
+ """`rack` and `manual` are the only sources the backend accepts by hand —
+ a device may not claim to have been discovered by a scan."""
+ create = next(t for t in DEVICE_TOOLS if t.name == "create_device")
+ assert create.inputSchema["properties"]["discovery_source"]["enum"] == ["manual", "rack"]
+
+
+async def test_device_tools_are_reachable_from_the_main_dispatch(mock_backend):
+ from app.tools import _dispatch
+
+ await _dispatch("delete_device", {"id": "d1"})
+ mock_backend.delete.assert_called_once_with("/api/v1/scan/pending/d1")
diff --git a/mcp/tests/test_faceplates_sync.py b/mcp/tests/test_faceplates_sync.py
new file mode 100644
index 0000000..88f12a7
--- /dev/null
+++ b/mcp/tests/test_faceplates_sync.py
@@ -0,0 +1,156 @@
+"""The Python faceplate catalog is a hand copy of the frontend one.
+
+A plate added, resized or reported here drifts silently otherwise: a mount would
+be seeded with the wrong footprint or the wrong ports, and the renderer would
+draw something else than the tool said it mounted. This parses faceplates.ts and
+compares, the way test_node_types_sync.py does for NODE_TYPES.
+"""
+
+import re
+from pathlib import Path
+
+import pytest
+
+from app.faceplates import (
+ DEVICE_TYPE_BY_FACEPLATE,
+ FACEPLATE_BY_DEVICE_TYPE,
+ FACEPLATES,
+ NAS_BAND,
+ bank,
+)
+
+FRONTEND_FACEPLATES = (
+ Path(__file__).resolve().parents[2] / "frontend" / "src" / "rack" / "faceplates.ts"
+)
+
+# Constants faceplates.ts writes its dimensions in terms of.
+_CONSTANTS = {"RACK_COLUMNS": 12, "NAS_U": 5}
+
+
+def _number(expression: str) -> int:
+ """`RACK_COLUMNS / 6` and friends, resolved to the int the TS produces.
+
+ A literal, a named constant, or a constant divided by a literal — the only
+ three shapes the catalog uses. Parsed rather than evaluated.
+ """
+ resolved = expression.strip().rstrip(",")
+ match = re.fullmatch(r"(\w+)(?:\s*/\s*(\d+))?", resolved)
+ assert match, f"Unparsable dimension {expression!r} in faceplates.ts"
+ term, divisor = match.group(1), match.group(2)
+ value = _CONSTANTS[term] if term in _CONSTANTS else int(term)
+ return value // int(divisor) if divisor else value
+
+
+def _entries() -> list[str]:
+ source = FRONTEND_FACEPLATES.read_text()
+ start = source.index("export const FACEPLATES")
+ end = source.index("\n]\n", start)
+ body = source[start:end]
+ # Every catalog entry is an object opened at two-space indentation.
+ entries = body.split("\n {\n")[1:]
+ assert entries, (
+ "Could not split the FACEPLATES array in frontend/src/rack/faceplates.ts — "
+ "update this parser if the file's shape changed."
+ )
+ return entries
+
+
+def _bank_calls(ports_source: str) -> list[dict]:
+ """Every `bank({...})` in a plate's `ports:` value, as Python kwargs."""
+ calls = []
+ for raw in re.findall(r"bank\(\{([^}]*)\}\)", ports_source):
+ kwargs: dict = {}
+ for key, quoted, number in re.findall(r"(\w+):\s*(?:'([^']*)'|([\d.]+))", raw):
+ kwargs[key] = quoted if number == "" else float(number)
+ calls.append({
+ "type": kwargs["type"],
+ "count": int(kwargs["count"]),
+ "x": kwargs["x"],
+ "w": kwargs["w"],
+ "per_row": int(kwargs["perRow"]) if "perRow" in kwargs else None,
+ "prefix": kwargs.get("prefix", "P"),
+ "start": int(kwargs.get("start", 1)),
+ })
+ return calls
+
+
+def _parse(entry: str) -> dict:
+ plate = {
+ "id": re.search(r"id: '([^']+)'", entry).group(1),
+ "label": re.search(r"label: '([^']+)'", entry).group(1),
+ "kind": re.search(r"kind: '([^']+)'", entry).group(1),
+ "group": re.search(r"group: '([^']+)'", entry).group(1),
+ "u_height": _number(re.search(r"uHeight: ([^,\n]+)", entry).group(1)),
+ "col_span": _number(re.search(r"colSpan: ([^,\n]+)", entry).group(1)),
+ }
+ # `ports:` is the last key of every entry, so everything after it is the
+ # port declaration — and nothing from `elements:` (which has `count:` of its
+ # own, for outlets) can leak in.
+ ports_source = entry[entry.index("ports:"):]
+ ports: list[dict] = []
+ for call in _bank_calls(ports_source):
+ ports.extend(bank(**call))
+ if "nasPorts(" in ports_source:
+ ports = [{**p, "y": NAS_BAND} for p in ports]
+ plate["ports"] = ports
+ return plate
+
+
+def test_faceplates_in_sync_with_frontend():
+ frontend = [_parse(entry) for entry in _entries()]
+ frontend_ids = [p["id"] for p in frontend]
+ catalog_ids = [p["id"] for p in FACEPLATES]
+
+ assert catalog_ids == frontend_ids, (
+ "mcp/app/faceplates.py FACEPLATES is out of sync with "
+ "frontend/src/rack/faceplates.ts.\n"
+ f"Missing: {[i for i in frontend_ids if i not in catalog_ids]}\n"
+ f"Extra: {[i for i in catalog_ids if i not in frontend_ids]}\n"
+ "(order matters — it is the order the picker shows)"
+ )
+
+ by_id = {p["id"]: p for p in FACEPLATES}
+ for expected in frontend:
+ plate = by_id[expected["id"]]
+ for field in ("label", "kind", "group", "u_height", "col_span"):
+ assert plate[field] == expected[field], (
+ f"Faceplate '{expected['id']}' {field}: catalog has {plate[field]!r}, "
+ f"faceplates.ts has {expected[field]!r}"
+ )
+ assert len(plate["ports"]) == len(expected["ports"]), (
+ f"Faceplate '{expected['id']}' has {len(plate['ports'])} ports, "
+ f"faceplates.ts declares {len(expected['ports'])}"
+ )
+ for port, want in zip(plate["ports"], expected["ports"]):
+ assert port["label"] == want["label"] and port["type"] == want["type"], (
+ f"Faceplate '{expected['id']}' port {port['label']}/{port['type']} "
+ f"does not match {want['label']}/{want['type']}"
+ )
+ assert port["x"] == pytest.approx(want["x"]), f"{expected['id']} {port['label']} x"
+ assert port["y"] == pytest.approx(want["y"]), f"{expected['id']} {port['label']} y"
+
+
+def _ts_record(name: str) -> dict[str, str]:
+ source = FRONTEND_FACEPLATES.read_text()
+ match = re.search(rf"const {name}: Record<string, string> = \{{(.*?)\n\}}", source, re.S)
+ assert match, f"Could not locate {name} in frontend/src/rack/faceplates.ts"
+ return dict(re.findall(r"'?([\w-]+)'?:\s*'([^']+)'", match.group(1)))
+
+
+def test_faceplate_suggestion_maps_in_sync():
+ assert FACEPLATE_BY_DEVICE_TYPE == _ts_record("FACEPLATE_BY_DEVICE_TYPE"), (
+ "mcp/app/faceplates.py FACEPLATE_BY_DEVICE_TYPE is out of sync with faceplates.ts"
+ )
+ assert DEVICE_TYPE_BY_FACEPLATE == _ts_record("DEVICE_TYPE_BY_FACEPLATE"), (
+ "mcp/app/faceplates.py DEVICE_TYPE_BY_FACEPLATE is out of sync with faceplates.ts"
+ )
+
+
+def test_every_faceplate_is_reachable_by_id():
+ """A plate the catalog lists but `get_faceplate` cannot return would make
+ every tool that names it fail."""
+ from app.faceplates import get_faceplate
+
+ for plate in FACEPLATES:
+ assert get_faceplate(plate["id"]) is plate
+ assert get_faceplate("no-such-plate") is None
diff --git a/mcp/tests/test_layout_parity.py b/mcp/tests/test_layout_parity.py
new file mode 100644
index 0000000..fc0496c
--- /dev/null
+++ b/mcp/tests/test_layout_parity.py
@@ -0,0 +1,136 @@
+"""app/rack_layout.py is a port of frontend/src/rack/layout.ts.
+
+The cases are the frontend's own (frontend/src/rack/__tests__/layout.test.ts,
+`occupancy` / `findSlot` / `freeUnits`), transcribed so the two implementations
+answer the same questions the same way. A tool that picks a slot the canvas
+would refuse mounts hardware where the user cannot see or drag it.
+"""
+
+from app.faceplates import RACK_COLUMNS
+from app.rack_layout import can_place, find_slot, free_units, is_in_bounds
+
+
+def make_rack(**patch):
+ return {"id": "r1", "name": "Rack", "u_height": 10, **patch}
+
+
+def make_device(**patch):
+ return {
+ "id": "d1",
+ "rack_id": "r1",
+ "label": "dev",
+ "u_start": 1,
+ "u_height": 1,
+ "col_start": 0,
+ "col_span": RACK_COLUMNS,
+ **patch,
+ }
+
+
+def placement(u_start, u_height=1, col_start=0, col_span=RACK_COLUMNS):
+ return {
+ "u_start": u_start,
+ "u_height": u_height,
+ "col_start": col_start,
+ "col_span": col_span,
+ }
+
+
+# --- occupancy --------------------------------------------------------------
+def test_rejects_placements_outside_the_rack():
+ rack = make_rack()
+ assert is_in_bounds(rack, placement(0)) is False
+ assert is_in_bounds(rack, placement(10, u_height=2)) is False
+ assert is_in_bounds(rack, placement(1, col_start=6)) is False
+ assert is_in_bounds(rack, placement(9, u_height=2)) is True
+
+
+def test_detects_a_full_width_collision():
+ rack = make_rack()
+ devices = [make_device(u_start=3)]
+ assert can_place(rack, devices, placement(3)) is False
+
+
+def test_two_half_width_devices_share_one_u():
+ rack = make_rack()
+ devices = [make_device(u_start=3, col_start=0, col_span=6)]
+ assert can_place(rack, devices, placement(3, col_start=6, col_span=6)) is True
+ assert can_place(rack, devices, placement(3, col_start=4, col_span=6)) is False
+
+
+def test_three_third_width_devices_share_one_u():
+ rack = make_rack()
+ devices = [
+ make_device(id="a", u_start=2, col_start=0, col_span=4),
+ make_device(id="b", u_start=2, col_start=4, col_span=4),
+ ]
+ assert can_place(rack, devices, placement(2, col_start=8, col_span=4)) is True
+
+
+def test_catches_a_multi_u_overlap_from_either_direction():
+ rack = make_rack()
+ devices = [make_device(u_start=4, u_height=3)] # U4..U6
+ assert can_place(rack, devices, placement(6, u_height=2)) is False
+ assert can_place(rack, devices, placement(2, u_height=3)) is False
+ assert can_place(rack, devices, placement(7, u_height=2)) is True
+
+
+def test_ignores_the_device_being_moved():
+ rack = make_rack()
+ devices = [make_device(id="d1", u_start=5)]
+ assert can_place(rack, devices, placement(5)) is False
+ assert can_place(rack, devices, placement(5), "d1") is True
+
+
+def test_ignores_devices_mounted_in_another_rack():
+ rack = make_rack()
+ devices = [make_device(rack_id="other", u_start=5)]
+ assert can_place(rack, devices, placement(5)) is True
+
+
+# --- find_slot --------------------------------------------------------------
+def test_keeps_the_requested_u_when_it_is_free():
+ slot = find_slot(make_rack(), [], placement(4, u_height=2))
+ assert slot == placement(4, u_height=2)
+
+
+def test_slides_to_a_free_u_when_the_target_is_taken():
+ devices = [make_device(u_start=4)]
+ slot = find_slot(make_rack(), devices, placement(4))
+ assert slot is not None
+ assert slot["u_start"] != 4
+
+
+def test_uses_free_columns_on_the_target_u_before_moving_away():
+ devices = [make_device(u_start=4, col_start=0, col_span=6)]
+ slot = find_slot(make_rack(), devices, placement(4, col_start=7, col_span=6))
+ assert slot == placement(4, col_start=6, col_span=6)
+
+
+def test_clamps_a_request_that_would_overflow_the_top():
+ slot = find_slot(make_rack(), [], placement(10, u_height=3))
+ assert slot is not None
+ assert slot["u_start"] == 8
+
+
+def test_none_when_the_device_is_taller_than_the_rack():
+ assert find_slot(make_rack(u_height=2), [], placement(1, u_height=4)) is None
+
+
+def test_none_when_the_rack_is_full():
+ rack = make_rack(u_height=2)
+ devices = [make_device(id="a", u_start=1), make_device(id="b", u_start=2)]
+ assert find_slot(rack, devices, placement(1)) is None
+
+
+# --- free_units -------------------------------------------------------------
+def test_counts_a_partially_filled_u_as_busy():
+ rack = make_rack(u_height=4)
+ devices = [make_device(u_start=2, col_start=0, col_span=6)]
+ assert free_units(rack, devices) == 3
+
+
+def test_counts_multi_u_devices_once_per_occupied_u():
+ rack = make_rack(u_height=4)
+ devices = [make_device(u_start=1, u_height=3)]
+ assert free_units(rack, devices) == 1
diff --git a/mcp/tests/test_racks.py b/mcp/tests/test_racks.py
new file mode 100644
index 0000000..b4cc8df
--- /dev/null
+++ b/mcp/tests/test_racks.py
@@ -0,0 +1,602 @@
+import copy
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from app.faceplates import get_faceplate
+from app.racks import dispatch_rack
+
+DESIGN = "design-rack"
+VIEWPORT = {"x": 5, "y": 6, "zoom": 2}
+
+
+def api_rack(rack_id="r1", **patch):
+ """A rack as GET /api/v1/racks reports it — `design_id` included."""
+ return {
+ "id": rack_id,
+ "design_id": DESIGN,
+ "name": "Rack 1",
+ "u_height": 10,
+ "width_standard": "19",
+ "numbering": "bottom-up",
+ "location": None,
+ "style": {},
+ "pos_x": 80,
+ "pos_y": 60,
+ **patch,
+ }
+
+
+def api_mount(mount_id="m1", **patch):
+ return {
+ "id": mount_id,
+ "design_id": DESIGN,
+ "rack_id": "r1",
+ "device_id": None,
+ "node_id": None,
+ "label": "Mount",
+ "u_start": 1,
+ "u_height": 1,
+ "col_start": 0,
+ "col_span": 12,
+ "faceplate_id": "server-1u",
+ "color": None,
+ "status": "unknown",
+ "port_visibility": "auto",
+ "ports": [
+ {"id": "p1", "label": "eth1", "type": "rj45", "x": 0.83, "y": 0.5},
+ {"id": "p2", "label": "eth2", "type": "rj45", "x": 0.91, "y": 0.5},
+ ],
+ **patch,
+ }
+
+
+def api_cable(cable_id="c1", **patch):
+ return {
+ "id": cable_id,
+ "design_id": DESIGN,
+ "from_device_id": "m1",
+ "from_port_id": "p1",
+ "to_device_id": "m2",
+ "to_port_id": "p1",
+ "type": "ethernet",
+ "color": "#39d353",
+ "label": None,
+ "label_visible": False,
+ "properties": [],
+ **patch,
+ }
+
+
+def api_item(item_id="i1", **patch):
+ return {
+ "id": item_id,
+ "label": "pve1",
+ "suggested_type": "proxmox",
+ "ip": "192.168.1.10",
+ "status": "approved",
+ "discovery_source": "scan",
+ "racked": False,
+ "node_id": "n1",
+ "rack_faceplate_id": None,
+ "rack_u_height": None,
+ "rack_col_span": None,
+ "rack_color": None,
+ "rack_ports": [],
+ **patch,
+ }
+
+
+class FakeBackend:
+ """Serves the rack state and the tray, and records what is saved."""
+
+ def __init__(self, racks=None, devices=None, cables=None, items=None):
+ self.state = {
+ "racks": racks if racks is not None else [api_rack()],
+ "devices": devices or [],
+ "cables": cables or [],
+ "viewport": dict(VIEWPORT),
+ }
+ self.items = items if items is not None else [api_item()]
+ self.saved = []
+
+ async def get(self, path):
+ if "/racks/inventory" in path:
+ return {"items": copy.deepcopy(self.items)}
+ if path.startswith("/api/v1/racks?"):
+ return copy.deepcopy(self.state)
+ raise AssertionError(f"unexpected GET {path}")
+
+ async def post(self, path, body):
+ assert path == "/api/v1/racks/save"
+ self.saved.append(copy.deepcopy(body))
+ return {"saved": True}
+
+ @property
+ def payload(self):
+ assert self.saved, "nothing was saved"
+ return self.saved[-1]
+
+
+def fake():
+ backend = FakeBackend()
+ with patch("app.racks.backend") as m:
+ m.get = AsyncMock(side_effect=backend.get)
+ m.post = AsyncMock(side_effect=backend.post)
+ yield backend
+
+
+def _use(fake, **kwargs):
+ """Reshape the fixture's state for one test."""
+ for key, value in kwargs.items():
+ if key == "items":
+ fake.items = value
+ else:
+ fake.state[key] = value
+
+
+# --- The state round trip ---------------------------------------------------
+async def test_save_strips_design_id_from_every_row(fake):
+ _use(fake, devices=[api_mount()], cables=[api_cable(to_device_id="m1", to_port_id="p2")])
+ await dispatch_rack("create_rack", {"design_id": DESIGN, "name": "Rack 2"})
+
+ payload = fake.payload
+ assert payload["design_id"] == DESIGN
+ for section in ("racks", "devices", "cables"):
+ assert payload[section], f"{section} was dropped"
+ for row in payload[section]:
+ assert "design_id" not in row, f"{section} row still carries design_id"
+
+
+async def test_save_echoes_the_viewport(fake):
+ """The save overwrites the design's CanvasState — not echoing the viewport
+ back resets the user's pan and zoom."""
+ await dispatch_rack("create_rack", {"design_id": DESIGN, "name": "Rack 2"})
+ assert fake.payload["viewport"] == VIEWPORT
+
+
+# --- Racks ------------------------------------------------------------------
+async def test_create_rack_defaults_and_clamps(fake):
+ result = await dispatch_rack(
+ "create_rack", {"design_id": DESIGN, "name": "Rack 2", "u_height": 999}
+ )
+ created = next(r for r in fake.payload["racks"] if r["name"] == "Rack 2")
+ assert created["u_height"] == 48 # MAX_RACK_U, not the backend's 100
+ assert result["rack_id"] == created["id"]
+ # Laid out to the right of the rack already there.
+ assert created["pos_x"] == 80 + 620
+ assert created["style"]["frame"] == "#1c2129"
+
+
+async def test_create_rack_honours_explicit_geometry(fake):
+ await dispatch_rack("create_rack", {
+ "design_id": DESIGN, "name": "Baie", "u_height": 12,
+ "width_standard": "10", "numbering": "top-down", "location": "Garage",
+ "pos_x": 1000, "pos_y": 200,
+ })
+ created = next(r for r in fake.payload["racks"] if r["name"] == "Baie")
+ assert (created["u_height"], created["width_standard"]) == (12, "10")
+ assert (created["numbering"], created["location"]) == ("top-down", "Garage")
+ assert (created["pos_x"], created["pos_y"]) == (1000, 200)
+
+
+async def test_update_rack_shrink_relocates_the_mounts_it_pushes_out(fake):
+ _use(fake, devices=[api_mount("m1", u_start=1), api_mount("m2", u_start=9)])
+ await dispatch_rack("update_rack", {"design_id": DESIGN, "rack_id": "r1", "u_height": 4})
+
+ moved = next(d for d in fake.payload["devices"] if d["id"] == "m2")
+ assert moved["u_start"] <= 4
+ assert moved["u_start"] != 1 # not on top of the mount that stayed
+
+
+async def test_update_rack_refuses_a_shrink_with_nowhere_to_put_a_mount(fake):
+ _use(fake, devices=[
+ api_mount("m1", u_start=1),
+ api_mount("m2", u_start=2),
+ api_mount("m3", u_start=9),
+ ])
+ with pytest.raises(ValueError, match="Cannot shrink"):
+ await dispatch_rack("update_rack", {"design_id": DESIGN, "rack_id": "r1", "u_height": 2})
+ assert fake.saved == [] # nothing persisted
+
+
+async def test_update_rack_rejects_an_unknown_rack(fake):
+ with pytest.raises(ValueError, match="Unknown rack"):
+ await dispatch_rack("update_rack", {"design_id": DESIGN, "rack_id": "nope", "name": "x"})
+
+
+async def test_delete_rack_takes_its_mounts_and_their_cables(fake):
+ _use(
+ fake,
+ racks=[api_rack("r1"), api_rack("r2", name="Rack 2")],
+ devices=[api_mount("m1", rack_id="r1"), api_mount("m2", rack_id="r2")],
+ cables=[api_cable("c1")],
+ )
+ result = await dispatch_rack("delete_rack", {"design_id": DESIGN, "rack_id": "r1"})
+
+ assert result["unmounted"] == 1 and result["cables_removed"] == 1
+ payload = fake.payload
+ assert [r["id"] for r in payload["racks"]] == ["r2"]
+ assert [d["id"] for d in payload["devices"]] == ["m2"]
+ assert payload["cables"] == []
+
+
+# --- Mounting ---------------------------------------------------------------
+async def test_mount_device_seeds_ports_from_the_suggested_faceplate(fake):
+ result = await dispatch_rack(
+ "mount_device", {"design_id": DESIGN, "rack_id": "r1", "inventory_device_id": "i1"}
+ )
+ mount = fake.payload["devices"][0]
+
+ # proxmox -> server-2u-bays, per the frontend's suggestion map.
+ plate = get_faceplate("server-2u-bays")
+ assert mount["faceplate_id"] == "server-2u-bays"
+ assert mount["u_height"] == plate["u_height"]
+ assert mount["col_span"] == plate["col_span"]
+ assert mount["device_id"] == "i1" and mount["node_id"] == "n1"
+ assert mount["label"] == "pve1" and mount["status"] == "approved"
+
+ assert len(mount["ports"]) == len(plate["ports"])
+ assert [p["label"] for p in mount["ports"]] == [p["label"] for p in plate["ports"]]
+ ids = {p["id"] for p in mount["ports"]}
+ assert len(ids) == len(mount["ports"]) and "" not in ids
+ assert result["mount_id"] == mount["id"]
+
+
+async def test_mount_device_reuses_the_front_panel_the_inventory_owns(fake):
+ """The device wears the same plate in every rack, ports included."""
+ ports = [{"id": "keep-1", "label": "eth1", "type": "rj45", "x": 0.5, "y": 0.5}]
+ _use(fake, items=[api_item(
+ rack_faceplate_id="switch-24", rack_u_height=1, rack_col_span=6,
+ rack_color="#ff6e00", rack_ports=ports,
+ )])
+ await dispatch_rack(
+ "mount_device", {"design_id": DESIGN, "rack_id": "r1", "inventory_device_id": "i1"}
+ )
+ mount = fake.payload["devices"][0]
+ assert mount["faceplate_id"] == "switch-24"
+ assert (mount["u_height"], mount["col_span"]) == (1, 6)
+ assert mount["color"] == "#ff6e00"
+ assert mount["ports"] == ports
+
+
+async def test_mount_device_ignores_a_stored_size_from_another_plate(fake):
+ """The stored size was measured on the plate it was stored with; an explicit
+ faceplate override means the size and ports have to come from that plate."""
+ _use(fake, items=[api_item(
+ rack_faceplate_id="switch-24", rack_u_height=1, rack_col_span=6,
+ rack_ports=[{"id": "old", "label": "eth1", "type": "rj45", "x": 0.5, "y": 0.5}],
+ )])
+ await dispatch_rack("mount_device", {
+ "design_id": DESIGN, "rack_id": "r1", "inventory_device_id": "i1",
+ "faceplate_id": "server-4u-storage",
+ })
+ mount = fake.payload["devices"][0]
+ plate = get_faceplate("server-4u-storage")
+ assert mount["u_height"] == plate["u_height"] == 4
+ assert mount["col_span"] == plate["col_span"]
+ assert [p["id"] for p in mount["ports"]] != ["old"]
+
+
+async def test_mount_device_places_at_the_requested_slot(fake):
+ await dispatch_rack("mount_device", {
+ "design_id": DESIGN, "rack_id": "r1", "inventory_device_id": "i1",
+ "faceplate_id": "sff-half", "u_start": 7, "col_start": 6,
+ })
+ mount = fake.payload["devices"][0]
+ assert (mount["u_start"], mount["col_start"], mount["col_span"]) == (7, 6, 6)
+
+
+async def test_mount_device_refuses_a_device_already_racked(fake):
+ _use(fake, items=[api_item(racked=True)])
+ with pytest.raises(ValueError, match="already mounted"):
+ await dispatch_rack(
+ "mount_device", {"design_id": DESIGN, "rack_id": "r1", "inventory_device_id": "i1"}
+ )
+ assert fake.saved == []
+
+
+async def test_mount_device_refuses_an_unknown_entry(fake):
+ with pytest.raises(ValueError, match="Unknown inventory device"):
+ await dispatch_rack(
+ "mount_device", {"design_id": DESIGN, "rack_id": "r1", "inventory_device_id": "ghost"}
+ )
+
+
+async def test_mount_device_refuses_an_unknown_faceplate(fake):
+ with pytest.raises(ValueError, match="Unknown faceplate"):
+ await dispatch_rack("mount_device", {
+ "design_id": DESIGN, "rack_id": "r1", "inventory_device_id": "i1",
+ "faceplate_id": "server-9u",
+ })
+
+
+async def test_mount_device_reports_a_rack_with_no_room(fake):
+ _use(fake, racks=[api_rack(u_height=2)], devices=[
+ api_mount("m1", u_start=1), api_mount("m2", u_start=2),
+ ])
+ with pytest.raises(ValueError, match="no free slot"):
+ await dispatch_rack(
+ "mount_device", {"design_id": DESIGN, "rack_id": "r1", "inventory_device_id": "i1"}
+ )
+
+
+async def test_mount_accessory_has_no_inventory_row(fake):
+ await dispatch_rack(
+ "mount_accessory", {"design_id": DESIGN, "rack_id": "r1", "faceplate_id": "shelf-1u"}
+ )
+ mount = fake.payload["devices"][0]
+ assert mount["device_id"] is None and mount["node_id"] is None
+ assert mount["label"] == "Shelf 1U" and mount["ports"] == []
+
+
+async def test_unmount_device_drops_its_cables_and_keeps_the_inventory_row(fake):
+ _use(fake, devices=[api_mount("m1"), api_mount("m2", u_start=2)], cables=[api_cable("c1")])
+ result = await dispatch_rack("unmount_device", {"design_id": DESIGN, "mount_id": "m1"})
+
+ assert result["cables_removed"] == 1
+ payload = fake.payload
+ assert [d["id"] for d in payload["devices"]] == ["m2"]
+ assert payload["cables"] == []
+ # Nothing was asked of the inventory: unmounting never deletes a device.
+ assert result["inventory_device_id"] is None
+
+
+async def test_unmount_device_rejects_an_unknown_mount(fake):
+ with pytest.raises(ValueError, match="Unknown mount"):
+ await dispatch_rack("unmount_device", {"design_id": DESIGN, "mount_id": "nope"})
+
+
+# --- Moving -----------------------------------------------------------------
+async def test_move_device_to_a_free_slot(fake):
+ _use(fake, devices=[api_mount("m1", u_start=1)])
+ await dispatch_rack(
+ "move_device", {"design_id": DESIGN, "mount_id": "m1", "u_start": 6}
+ )
+ assert fake.payload["devices"][0]["u_start"] == 6
+
+
+async def test_move_device_refuses_an_occupied_slot(fake):
+ _use(fake, devices=[api_mount("m1", u_start=1), api_mount("m2", u_start=6)])
+ with pytest.raises(ValueError, match="does not fit"):
+ await dispatch_rack("move_device", {"design_id": DESIGN, "mount_id": "m1", "u_start": 6})
+ assert fake.saved == []
+
+
+async def test_move_device_to_another_rack(fake):
+ _use(
+ fake,
+ racks=[api_rack("r1"), api_rack("r2", name="Rack 2")],
+ devices=[api_mount("m1", rack_id="r1", u_start=3)],
+ )
+ await dispatch_rack(
+ "move_device", {"design_id": DESIGN, "mount_id": "m1", "rack_id": "r2", "u_start": 2}
+ )
+ moved = fake.payload["devices"][0]
+ assert (moved["rack_id"], moved["u_start"]) == ("r2", 2)
+
+
+async def test_move_device_keeps_what_was_not_asked_for(fake):
+ _use(fake, devices=[api_mount("m1", u_start=1, col_start=6, col_span=6)])
+ await dispatch_rack("move_device", {"design_id": DESIGN, "mount_id": "m1", "u_start": 5})
+ moved = fake.payload["devices"][0]
+ assert (moved["col_start"], moved["col_span"]) == (6, 6)
+
+
+# --- Faceplates -------------------------------------------------------------
+async def test_set_device_faceplate_reseeds_ports_and_drops_stale_cables(fake):
+ _use(fake, devices=[api_mount("m1"), api_mount("m2", u_start=5)], cables=[api_cable("c1")])
+ result = await dispatch_rack("set_device_faceplate", {
+ "design_id": DESIGN, "mount_id": "m1", "faceplate_id": "switch-8",
+ })
+
+ mount = next(d for d in fake.payload["devices"] if d["id"] == "m1")
+ plate = get_faceplate("switch-8")
+ assert mount["faceplate_id"] == "switch-8"
+ assert [p["label"] for p in mount["ports"]] == [p["label"] for p in plate["ports"]]
+ assert {p["id"] for p in mount["ports"]}.isdisjoint({"p1", "p2"})
+ assert result["cables_removed"] == 1
+ assert fake.payload["cables"] == []
+
+
+async def test_set_device_faceplate_relocates_a_plate_that_no_longer_fits(fake):
+ """A 1U mount with a neighbour right above it cannot grow in place."""
+ _use(fake, devices=[api_mount("m1", u_start=1), api_mount("m2", u_start=2)])
+ await dispatch_rack("set_device_faceplate", {
+ "design_id": DESIGN, "mount_id": "m1", "faceplate_id": "server-4u-storage",
+ })
+ mount = next(d for d in fake.payload["devices"] if d["id"] == "m1")
+ assert mount["u_height"] == 4
+ assert mount["u_start"] >= 3 # clear of the mount on U2
+
+
+# --- Cables -----------------------------------------------------------------
+async def test_patch_cable_resolves_port_labels(fake):
+ _use(fake, devices=[api_mount("m1"), api_mount("m2", u_start=2)])
+ result = await dispatch_rack("patch_cable", {
+ "design_id": DESIGN,
+ "from_mount_id": "m1", "from_port": "eth1",
+ "to_mount_id": "m2", "to_port": "ETH2",
+ })
+ cable = fake.payload["cables"][0]
+ assert (cable["from_device_id"], cable["from_port_id"]) == ("m1", "p1")
+ assert (cable["to_device_id"], cable["to_port_id"]) == ("m2", "p2")
+ # An rj45 patch is copper, and copper is green.
+ assert cable["type"] == "ethernet" and cable["color"] == "#39d353"
+ assert result["from"] == "Mount eth1"
+
+
+async def test_patch_cable_from_a_fibre_port_is_fibre(fake):
+ sfp = [{"id": "s1", "label": "sfp1", "type": "sfp+", "x": 0.9, "y": 0.5}]
+ _use(fake, devices=[api_mount("m1", ports=sfp), api_mount("m2", u_start=2)])
+ await dispatch_rack("patch_cable", {
+ "design_id": DESIGN,
+ "from_mount_id": "m1", "from_port": "sfp1",
+ "to_mount_id": "m2", "to_port": "eth1",
+ })
+ cable = fake.payload["cables"][0]
+ assert cable["type"] == "fiber" and cable["color"] == "#f0a500"
+
+
+async def test_patch_cable_refuses_an_occupied_port(fake):
+ _use(fake, devices=[api_mount("m1"), api_mount("m2", u_start=2)], cables=[api_cable("c1")])
+ with pytest.raises(ValueError, match="already patched"):
+ await dispatch_rack("patch_cable", {
+ "design_id": DESIGN,
+ "from_mount_id": "m1", "from_port": "eth1",
+ "to_mount_id": "m2", "to_port": "eth2",
+ })
+ assert fake.saved == []
+
+
+async def test_patch_cable_refuses_a_port_patched_to_itself(fake):
+ _use(fake, devices=[api_mount("m1")])
+ with pytest.raises(ValueError, match="cannot patch a port to itself"):
+ await dispatch_rack("patch_cable", {
+ "design_id": DESIGN,
+ "from_mount_id": "m1", "from_port": "eth1",
+ "to_mount_id": "m1", "to_port": "eth1",
+ })
+
+
+async def test_patch_cable_names_the_ports_it_knows(fake):
+ _use(fake, devices=[api_mount("m1"), api_mount("m2", u_start=2)])
+ with pytest.raises(ValueError, match="Unknown port 'eth9'.*eth1, eth2"):
+ await dispatch_rack("patch_cable", {
+ "design_id": DESIGN,
+ "from_mount_id": "m1", "from_port": "eth9",
+ "to_mount_id": "m2", "to_port": "eth1",
+ })
+
+
+async def test_patch_cable_carries_a_label(fake):
+ _use(fake, devices=[api_mount("m1"), api_mount("m2", u_start=2)])
+ await dispatch_rack("patch_cable", {
+ "design_id": DESIGN,
+ "from_mount_id": "m1", "from_port": "eth1",
+ "to_mount_id": "m2", "to_port": "eth1",
+ "label": "A12", "label_visible": True, "color": "#00d4ff",
+ })
+ cable = fake.payload["cables"][0]
+ assert (cable["label"], cable["label_visible"], cable["color"]) == ("A12", True, "#00d4ff")
+
+
+async def test_unpatch_cable(fake):
+ _use(fake, devices=[api_mount("m1"), api_mount("m2", u_start=2)], cables=[api_cable("c1")])
+ await dispatch_rack("unpatch_cable", {"design_id": DESIGN, "cable_id": "c1"})
+ assert fake.payload["cables"] == []
+
+
+async def test_unpatch_cable_rejects_an_unknown_id(fake):
+ with pytest.raises(ValueError, match="Unknown cable"):
+ await dispatch_rack("unpatch_cable", {"design_id": DESIGN, "cable_id": "ghost"})
+
+
+# --- Reads ------------------------------------------------------------------
+async def test_list_racks_reports_occupancy(fake):
+ _use(fake, devices=[api_mount("m1", u_start=1, u_height=2)])
+ racks = await dispatch_rack("list_racks", {"design_id": DESIGN})
+ assert racks == [{
+ "id": "r1", "name": "Rack 1", "u_height": 10, "width_standard": "19",
+ "numbering": "bottom-up", "location": None, "mount_count": 1, "free_u": 8,
+ }]
+
+
+async def test_get_rack_returns_mounts_with_their_ports_and_cables(fake):
+ _use(fake, devices=[api_mount("m1"), api_mount("m2", u_start=2)], cables=[api_cable("c1")])
+ result = await dispatch_rack("get_rack", {"design_id": DESIGN, "rack_id": "r1"})
+
+ mounts = result["racks"][0]["devices"]
+ assert [m["id"] for m in mounts] == ["m1", "m2"]
+ assert mounts[0]["ports"] == [
+ {"id": "p1", "label": "eth1", "type": "rj45"},
+ {"id": "p2", "label": "eth2", "type": "rj45"},
+ ]
+ cable = result["cables"][0]
+ assert cable["from"] == {"mount_id": "m1", "device": "Mount", "port_id": "p1", "port": "eth1"}
+
+
+async def test_get_rack_narrows_to_one_rack(fake):
+ _use(
+ fake,
+ racks=[api_rack("r1"), api_rack("r2", name="Rack 2")],
+ devices=[api_mount("m1", rack_id="r1"), api_mount("m2", rack_id="r2")],
+ )
+ result = await dispatch_rack("get_rack", {"design_id": DESIGN, "rack_id": "r2"})
+ assert [r["id"] for r in result["racks"]] == ["r2"]
+ assert [d["id"] for d in result["racks"][0]["devices"]] == ["m2"]
+
+
+async def test_get_rack_rejects_an_unknown_rack(fake):
+ with pytest.raises(ValueError, match="Unknown rack"):
+ await dispatch_rack("get_rack", {"design_id": DESIGN, "rack_id": "ghost"})
+
+
+async def test_list_rack_inventory_flags_what_is_racked_and_modelled(fake):
+ _use(fake, items=[
+ api_item("i1"),
+ api_item("i2", label="sw1", racked=True, rack_faceplate_id="switch-24"),
+ ])
+ items = await dispatch_rack("list_rack_inventory", {"design_id": DESIGN})
+ assert items[0]["racked"] is False and items[0]["modelled"] is False
+ assert items[1]["racked"] is True and items[1]["modelled"] is True
+ assert items[1]["faceplate_id"] == "switch-24"
+
+
+async def test_list_faceplates_covers_the_catalog(fake):
+ plates = await dispatch_rack("list_faceplates", {})
+ ids = [p["id"] for p in plates]
+ assert "server-1u" in ids and "blank-1u" in ids
+ server = next(p for p in plates if p["id"] == "server-2u-bays")
+ assert (server["u_height"], server["col_span"], server["port_count"]) == (2, 12, 6)
+ assert next(p for p in plates if p["id"] == "shelf-1u")["kind"] == "accessory"
+
+
+async def test_rack_tools_are_reachable_from_the_main_dispatch(fake):
+ """tools._dispatch routes rack names here rather than falling through."""
+ from app.tools import _dispatch
+
+ assert await _dispatch("list_racks", {"design_id": DESIGN}) == await dispatch_rack(
+ "list_racks", {"design_id": DESIGN}
+ )